From Gideon.STREET at ergon.com.au Wed Mar 1 00:47:54 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Wed, 1 Mar 2006 09:47:54 +1000 Subject: [Tutor] Telnet to cisco device Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC06E35B@ebnewem01.ergon> Thanks all for the replies. I got tcpwatch up and running and where the program was hanging is actually a page prompt, so now I just need to get the script to pass a space whenever that prompt comes up.... I'm surprised it worked and got to that point (that's a testament to the online tutorials). Fun and games :) -----Original Message----- From: Python [mailto:python at venix.com] Sent: Tuesday, 28 February 2006 11:05 PM To: STREET Gideon (SPARQ) Cc: Tutor Python Subject: Re: [Tutor] Telnet to cisco device On Tue, 2006-02-28 at 16:36 +1000, STREET Gideon (SPARQ) wrote: > tn.read_until('Username: ') #expected prompt after telnetting to the > router tn.write(user + '\r\n') #hopefully write username and pass > character return > Sending both \r and \n may be confusing things. I'd recommend using tcpwatch.py http://hathawaymix.org/Software/TCPWatch to monitor a telnet session that works. That way you will have a collection of exact prompts available to build your script. -- Lloyd Kvam Venix Corp 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 prabhu.chinnee at gmail.com Wed Mar 1 08:05:08 2006 From: prabhu.chinnee at gmail.com (Prabhakar K) Date: Wed, 1 Mar 2006 12:35:08 +0530 Subject: [Tutor] Fwd: Problem wxPython In-Reply-To: <7528bcdd0602170522i395a391dp8af5e56305e409cb@mail.gmail.com> References: <3ae549770602170513o1c4a51e2x67fc09024df1f40@mail.gmail.com> <7528bcdd0602170522i395a391dp8af5e56305e409cb@mail.gmail.com> Message-ID: <3ae549770602282305o533ba085o4eaf9ecc9e590d1f@mail.gmail.com> Hai to all, I installed ActivePython-2.4.1-247-win32-ix86 and wxPython2.6-win32-ansi-2.6.2.1-py2 in my system. When i Run a wxPython example.. geeting an Errors Traceback (most recent call last): File "E:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "F:\python\wx.py", line 1, in ? from wxPython.wx import * File "E:\Python24\lib\site-packages\wx-2.6-msw-ansi\wxPython\__init__.py", line 10, in ? import _wx File "E:\Python24\lib\site-packages\wx-2.6-msw-ansi\wxPython\_wx.py ", line 3, in ? from _core import * File "E:\Python24\lib\site-packages\wx-2.6-msw-ansi\wxPython\_core.py", line 15, in ? import wx._core File "F:\python\wx.py", line 1, in ? from wxPython.wx import * ImportError: No module named wx Program Code: from wxPython.wx import * class MyApp(wxApp): def OnInit(self): frame = wxFrame(NULL, -1, "Hello from wxPython") frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060301/251fc8c3/attachment.html From andreengels at gmail.com Wed Mar 1 11:58:19 2006 From: andreengels at gmail.com (Andre Engels) Date: Wed, 1 Mar 2006 11:58:19 +0100 Subject: [Tutor] password protection in httplib Message-ID: <6faf39c90603010258w53737201n@mail.gmail.com> I am active in pywikipediabot, which is programmed in Python and is used to edit wikis (based on MediaWiki, such as Wikpedia). It uses httplib to connect to the site and get the HTML data. I now want to use it on another site, but this site is password protected (we want to first improve it before releasing it to the public). Is it possible with httplib to connect to password protected sites (given that I know the login and password of course), and if so, how is this done? If not, is there an alternative? -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From kent37 at tds.net Wed Mar 1 13:05:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Mar 2006 07:05:08 -0500 Subject: [Tutor] password protection in httplib In-Reply-To: <6faf39c90603010258w53737201n@mail.gmail.com> References: <6faf39c90603010258w53737201n@mail.gmail.com> Message-ID: <44058DF4.10402@tds.net> Andre Engels wrote: > I am active in pywikipediabot, which is programmed in Python and is > used to edit wikis (based on MediaWiki, such as Wikpedia). It uses > httplib to connect to the site and get the HTML data. > > I now want to use it on another site, but this site is password > protected (we want to first improve it before releasing it to the > public). Is it possible with httplib to connect to password protected > sites (given that I know the login and password of course), and if so, > how is this done? If not, is there an alternative? What kind of authentication is used? Basic and digest authentication will pop up a dialog in the browser asking for your credentials. The browser then remembers the credentials and includes them in subsequent requests. With form-based authentication, a page displays in the browser with a login form; the web site authenticates and usually sends a cookie to the browser which must be included in subsequent requests. urllib2 has good built-in support for basic and digest authentication of web sites. For form-based authentication you have to do a bit more work - install a cookie manager and post to the form yourself. See http://www.voidspace.org.uk/python/articles/authentication.shtml for examples of basic auth. Digest auth works pretty much the same way. Make sure you read to the section "Doing It Properly" - the author likes to show you the hard way first. The article http://www.voidspace.org.uk/python/articles/cookielib.shtml shows how to use cookies, though again the presentation makes it look harder than it really is, at least in Python 2.4 that has CookieLib built in. You have to post to the login form yourself, but that is just another urllib2 request. Kent From joaquin_barcelo_12 at yahoo.es Wed Mar 1 17:13:54 2006 From: joaquin_barcelo_12 at yahoo.es (Joaquin Sanchez Sanchez) Date: Wed, 1 Mar 2006 17:13:54 +0100 (CET) Subject: [Tutor] URGENT doubt!!!! Message-ID: <20060301161354.69849.qmail@web26910.mail.ukl.yahoo.com> I have a doubt I have some modules in python, and in one of them, i have to dictionarys. In them, i have some vars yhat I want to save before clossing my session, ande then, in a new session, i want to load them. I have heard about "pickle" How does it work?I dont understand the help page example How have I to used it? Another suggestion? THANKS A LOT --------------------------------- LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060301/a1ddcbfc/attachment.htm From python at venix.com Wed Mar 1 17:29:48 2006 From: python at venix.com (Python) Date: Wed, 01 Mar 2006 11:29:48 -0500 Subject: [Tutor] URGENT doubt!!!! In-Reply-To: <20060301161354.69849.qmail@web26910.mail.ukl.yahoo.com> References: <20060301161354.69849.qmail@web26910.mail.ukl.yahoo.com> Message-ID: <1141230588.15743.500.camel@www.venix.com> On Wed, 2006-03-01 at 17:13 +0100, Joaquin Sanchez Sanchez wrote: > I have a doubt > > I have some modules in python, and in one of them, i have to > dictionarys. In them, i have some vars yhat I want to save before > clossing my session, ande then, in a new session, i want to load them. > > I have heard about "pickle" > How does it work?I dont understand the help page example > How have I to used it? > Another suggestion? I think the shelve module better fits what you are trying to do. It will store the pickle into a file for later retrieval and possible modification. http://docs.python.org/lib/module-shelve.html Note that you should be using strings for the shelve keys. > > THANKS A LOT > > > ______________________________________________________________________ > > 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 -- Lloyd Kvam Venix Corp From kent37 at tds.net Wed Mar 1 17:37:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Mar 2006 11:37:51 -0500 Subject: [Tutor] URGENT doubt!!!! In-Reply-To: <20060301161354.69849.qmail@web26910.mail.ukl.yahoo.com> References: <20060301161354.69849.qmail@web26910.mail.ukl.yahoo.com> Message-ID: <4405CDDF.7090808@tds.net> Joaquin Sanchez Sanchez wrote: > I have a doubt > > I have some modules in python, and in one of them, i have to > dictionarys. In them, i have some vars yhat I want to save before > clossing my session, ande then, in a new session, i want to load them. > > I have heard about "pickle" > How does it work?I dont understand the help page example Yeah, that is an advanced example, for a simple example look at example 2 on this page: http://www-128.ibm.com/developerworks/library/l-pypers.html Kent From hugonz-lists at h-lab.net Wed Mar 1 18:08:10 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 01 Mar 2006 11:08:10 -0600 Subject: [Tutor] URGENT doubt!!!! In-Reply-To: <20060301161354.69849.qmail@web26910.mail.ukl.yahoo.com> References: <20060301161354.69849.qmail@web26910.mail.ukl.yahoo.com> Message-ID: <4405D4FA.6020309@h-lab.net> Ok, if it's so urgent. import cPickle mydict = {1:"one", 2:"two"} #Saving fileo = open("mysavedfile", "w") cPickle.dump(mydict, fileo) fileo.close() fileo2 = open("mysavedfile", "r") saved_dict = cPickle.load(fileo2) print saved_dict Hope this one is simple enough Hugo From max.mail.lists at googlemail.com Wed Mar 1 12:32:42 2006 From: max.mail.lists at googlemail.com (Max Russell) Date: Wed, 1 Mar 2006 11:32:42 +0000 Subject: [Tutor] Non type object? Message-ID: <101a41db0603010332h3bb1dab7x26ceaa4a36cef983@mail.gmail.com> I'm trying to debug a script that takes a load of Python files and checks them against original text files- it's for checking headers: #script to verify content of a header is what is should be. import difflib, os, re, sys class HeaderChecker(object): def __init__(self, directoryPy, directoryTxt, outputFilePath=None): """script that reverts the headers from a set of Python files and checks them against the original text from a test""" self._directoryToCheck = directoryPy self._directoryForCompare =directoryTxt self._outputFileName = outputFilePath # open file to create/clear it if self._outputFileName != None: outputFile = open(self._outputFileName, "w") outputFile.write("Log file for verifying headers") outputFile.close() # get the contents of the Python directory if not os.path.exists(self._directoryToCheck): raise ScriptException("Directory %s does not exist"%self._directoryToCheck) fileList = os.listdir(self._directoryToCheck) # just look at the python files (make entries with an absolute file path) self._pythonFileList = [] for file in fileList: if file.endswith(".py"): self._pythonFileList.append(self._directoryToCheck + "\\" + file) print self._pythonFileList if len(self._pythonFileList) == 0: raise ScriptException("Directory %s does not contain any python files "%directoryPy) #get the contents of the original text directory for comparison if not os.path.exists(self._directoryForCompare): raise ScriptException("Directory %s does not exist"%self._directoryForCompare) txtList = os.listdir(self._directoryForCompare) self._txtFileList = [] for item in txtList: if item.endswith(".txt"): self._txtFileList.append(self._directoryForCompare + "\\" + item) print self._txtFileList if len(self._txtFileList)==0: raise ScriptException("Directory %s does not contain any python files "%directoryTxt) def getValidPythonFiles(self): """ get valid python files """ self.log(["found %d python files in %s"%(len(self._pythonFileList), self._directoryToCheck)]) return self._pythonFileList def getTextFiles(self): """ get method for list of text files """ self.log(["found %d text files in %s"%(len(self._txtFileList), self._directoryForCompare)]) return self._txtFileList def getFileNameFromPath(self, filePath): """ Extract the file name from the file path @param filePath File path for the python file. @return File name """ path, file = os.path.split(filePath) return file def stripFile(self, filetostrip): """ Strips Python files of "#> " commenting and removes the code, writes out to a stripped file """ print "\n" + "stripFile is executed" + "\n" print ("\n" + filetostrip) fh = open(filetostrip, "r") filelines = fh.readlines() filetostrip = filetostrip.rstrip("py") filetostrip = (filetostrip + "strp") strippedfile = open(filetostrip, "w") for thisline in filelines: if thisline.startswith ("#> "): thisline.lstrip("#> ") strippedfile.write(thisline + "\n") strippedfile.close() fh.close() def compStripToTxt(self, origfile, strippedfile): """ Compares the stripped Python header file to the original text of a test """ print "compStripToTxt is executed" orig = open(origfile, "r") stripped = open(strippedfile, "r") origentry = orig.readlines() strippedentry = stripped.readlines() orig.close() stripped.close() if origentry != strippedentry: d = difflib.Differ() variance = list(d.compare(origentry, strippedentry)) print variance return variance else: return None def log(self, linesToLog): """ Log the script output to a file - echo to the console. @param linesToLog List of strings to write out """ # if we have a output file write to it if self._outputFileName != None: outputFile = open(self._outputFileName, "a") if len(linesToLog) == 0: outputFile.write("\n") for line in linesToLog: outputFile.write(line + "\n") outputFile.close() # output to shell if len(linesToLog) == 0: print for line in linesToLog: print line ###################################### #MAIN SECTION ###################################### if __name__ == "__main__": checker = HeaderChecker(sys.argv[1], sys.argv[2], sys.argv[3]) pythonFileList = checker.getValidPythonFiles() checker.log([]) checker.log(pythonFileList) #For all files in the list of Python files, strip the files of the header #comments markings changes = [] for text in checker._txtFileList: file1 = checker.getFileNameFromPath(text) for pyfile in pythonFileList: file2 = checker.getFileNameFromPath(pyfile) print "comparing %s to %s"%(file1[:-4], file2[:-3]) if file1[:-4] == file2[:-3]: print "matched %s to %s"%(file1[:-4], file2[:-3]) pytostrip = checker._directoryToCheck + "\\" + file2 print pytostrip stripped = checker.stripFile(pytostrip) print stripped #print "\n" + stripped + "\n" diff =checker.compStripToTxt(text, stripped) print diff if diff: # changes.append(diff) print changes break Now, I have a lot of print statements in there for debugging purposes, but I don't understand why when I run it, and it parses through my input directory and comparison directory it returns this None compStripToTxt is executed Traceback (most recent call last): File "HeaderChecker.py", line 182, in ? diff =checker.compStripToTxt(text, stripped) File "HeaderChecker.py", line 114, in compStripToTxt stripped = open(strippedfile, "r") TypeError: coercing to Unicode: need string or buffer, NoneType found Why is it returning the None type? How can I fix this? thanks Max -- Max Russell Senior Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060301/db734e02/attachment.htm From kent37 at tds.net Wed Mar 1 19:25:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Mar 2006 13:25:11 -0500 Subject: [Tutor] Non type object? In-Reply-To: <101a41db0603010332h3bb1dab7x26ceaa4a36cef983@mail.gmail.com> References: <101a41db0603010332h3bb1dab7x26ceaa4a36cef983@mail.gmail.com> Message-ID: <4405E707.10105@tds.net> Max Russell wrote: > None > compStripToTxt is executed > Traceback (most recent call last): > File "HeaderChecker.py", line 182, in ? > diff =checker.compStripToTxt(text, stripped) > File "HeaderChecker.py", line 114, in compStripToTxt > stripped = open(strippedfile, "r") > TypeError: coercing to Unicode: need string or buffer, NoneType found > > > > Why is it returning the None type? > > How can I fix this? It's because stripped is None in your main program, as the print statement shows. stripped is the value returned from stripFile(). Since stripFile() doesn't explicitly return anything, its return value is None. I think you want stripFile() to return the name of the stripped file, which is filetostrip. Kent From Barry.Carroll at psc.com Wed Mar 1 21:13:30 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 1 Mar 2006 12:13:30 -0800 Subject: [Tutor] Unexpected Behavior in unittest Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3607@eugsrv400.psc.pscnet.com> Danny: I went back and double checked all of my test files, and you were right I was actually running an older version of test3.py. In that, the assignment to the character separator was wrong: lg.sc = 2.5 Having forgotten that Python allows dynamic creation of object attributes at run time, I assumed (incorrectly) that the interpreter would catch a misspelled attribute name. lg.sc was being assigned just fine, leaving lg.cs blissfully unchanged. The test case caught the error as it should, leaving me scratching my head and bothering you. A case of C++ memory intruding into Python space. Thank you for pointing out the real problem. 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----- > From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] > Sent: Tuesday, February 28, 2006 2:57 PM > To: Carroll, Barry > Cc: tutor at python.org > Subject: RE: [Tutor] Unexpected Behavior in unittest > > > > > I wish it were that simple. 'test3.py' is the name of the file > > containing the test case class. I left the invocation out of my output > > excerpt. It should look like this: > > Hi Barry, > > > Ok. > > But still go back and make sure you're running the right file. <<snip>> > Python isn't magical, so I have to assume that some program, > different than the one you've shown us, is being executed. > > > Does this make sense? > From Simo10 at mchsi.com Thu Mar 2 01:36:26 2006 From: Simo10 at mchsi.com (Jacob Simonovich) Date: Wed, 1 Mar 2006 18:36:26 -0600 Subject: [Tutor] (no subject) Message-ID: <000601c63d91$579ac1b0$6600a8c0@LivingRoom> I want to learn how to hack but don't know where to start. I have been searching all over the internet to try to find things out but none of the websites have helped me. I would like to know the tools needed and just a step by step process on how to do it using widows xp home edition. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060301/680c01c3/attachment.html From benvinger at googlemail.com Thu Mar 2 11:25:19 2006 From: benvinger at googlemail.com (Ben Vinger) Date: Thu, 2 Mar 2006 10:25:19 +0000 Subject: [Tutor] How can a function know where it was called from Message-ID: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> Hello I want myfunction in the pseudocode below return something different if it was called from indexfunction. def indexfunction(): blah def myfunction(): x = 'whatever' if <myfunction was called from indexfunction>: return x else: return <header> + x + <footer> Thanks Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060302/adc18e1e/attachment.htm From andre.roberge at gmail.com Thu Mar 2 12:23:59 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 2 Mar 2006 07:23:59 -0400 Subject: [Tutor] How can a function know where it was called from In-Reply-To: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> References: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> Message-ID: <7528bcdd0603020323y79ffeccdt7efa1d250c08ae97@mail.gmail.com> On 3/2/06, Ben Vinger <benvinger at googlemail.com> wrote: > > Hello > > I want myfunction in the pseudocode below return something different if it > was called from indexfunction. > How about adding a parameter to myfunction itself: def indexfunction(): blah myfunction(fromindexfunction=True) def myfunction(fromindexfunction=False): x = 'whatever' if fromindexfunction: return x else: return <header> + x + <footer> Andr? From alan.gauld at freenet.co.uk Thu Mar 2 12:25:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 2 Mar 2006 11:25:38 -0000 Subject: [Tutor] How can a function know where it was called from References: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> Message-ID: <008701c63dec$12226ce0$0b01a8c0@xp> Ben, > I want myfunction in the pseudocode below return something > different if it was called from indexfunction. There are several approaches to this. > def indexfunction(): blah > > def myfunction(): > if <myfunction was called from indexfunction>: return x > else: return <header> + x + <footer> The simplest approach simply includes a "sender" parameter in myfunction and callers supply a link or label to indicate who is calling. This is the approach adopted by many GUI toolkits. It works best if you want to identify an object rather than a function however since the caller simply passes self as the value. The other possibility is to use the traceback module and examine the call stack. Thats a moderately advanced technique and you may want to google for some examples of using tracebacks. HTH, Alan G. From noufal at nibrahim.net.in Thu Mar 2 12:39:39 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Thu, 2 Mar 2006 17:09:39 +0530 (IST) Subject: [Tutor] How can a function know where it was called from In-Reply-To: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> References: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> Message-ID: <29521.203.145.176.76.1141299579.squirrel@members.hcoop.net> On Thu, March 2, 2006 3:55 pm, Ben Vinger wrote: > Hello > > I want myfunction in the pseudocode below return something different if it > was called from indexfunction. I'm new to this but maybe it would be good if you passed the appropriate "version" of "myfunction" to indexfunction from where the original decision of which one to use was made rather than doing it at the lower levels. Something like. def myfunwithheaders(x): return header + x + footer def myfunwithoutheaders(x): return x def main(): blah if needheaders: myfunction(myfunwithheaders) else: myfunction(myfunwithoutheaders) def myfunction(ret): x = "whatever" return ret(x) I'd appreciate if some of the more experienced folks on the list comment on the general approach. Thanks much. -- -NI From ewald.ertl at hartter.com Thu Mar 2 12:58:59 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 02 Mar 2006 12:58:59 +0100 Subject: [Tutor] How can a function know where it was called from In-Reply-To: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> References: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> Message-ID: <4406DE03.8000805@hartter.com> Hi Ben! After looking at the modules I detected the traceback-Module in my installation: >>> import traceback >>> def two(): ... one() ... >>> two() >>> def one(): ... print traceback.extract_stack() ... >>> def two(): ... one() ... >>> two() [('<stdin>', 1, '?', None), ('<stdin>', 2, 'two', None), ('<stdin>', 2, 'one', None)] maybe this could be a start for your investigation HTH Ewald Ben Vinger wrote: > Hello > > I want myfunction in the pseudocode below return something different if > it was called from indexfunction. > > def indexfunction(): > blah > > def myfunction(): > x = 'whatever' > if <myfunction was called from indexfunction>: > return x > else: > return <header> + x + <footer> > > > Thanks > Ben > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl at trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl at hartter.com From andreengels at gmail.com Thu Mar 2 13:45:35 2006 From: andreengels at gmail.com (Andre Engels) Date: Thu, 2 Mar 2006 13:45:35 +0100 Subject: [Tutor] password protection in httplib In-Reply-To: <44058DF4.10402@tds.net> References: <6faf39c90603010258w53737201n@mail.gmail.com> <44058DF4.10402@tds.net> Message-ID: <6faf39c90603020445y8d99b52s@mail.gmail.com> Thanks for your help; it brought me quite a bit farther, but not as far as I wanted to come. The authentication is basic authentication, and I have been able to adapt the programs so that I now get my pages correctly. However, the program uses not only 'GET' operations, but also 'PUT' operations. These are done using httplib rather than urllib, and I cannot see at this point how I can mimick those using urllib2. Andre Engels 2006/3/1, Kent Johnson <kent37 at tds.net>: > Andre Engels wrote: > > I am active in pywikipediabot, which is programmed in Python and is > > used to edit wikis (based on MediaWiki, such as Wikpedia). It uses > > httplib to connect to the site and get the HTML data. > > > > I now want to use it on another site, but this site is password > > protected (we want to first improve it before releasing it to the > > public). Is it possible with httplib to connect to password protected > > sites (given that I know the login and password of course), and if so, > > how is this done? If not, is there an alternative? > > What kind of authentication is used? Basic and digest authentication > will pop up a dialog in the browser asking for your credentials. The > browser then remembers the credentials and includes them in subsequent > requests. With form-based authentication, a page displays in the browser > with a login form; the web site authenticates and usually sends a cookie > to the browser which must be included in subsequent requests. > > urllib2 has good built-in support for basic and digest authentication of > web sites. For form-based authentication you have to do a bit more work > - install a cookie manager and post to the form yourself. > > See http://www.voidspace.org.uk/python/articles/authentication.shtml for > examples of basic auth. Digest auth works pretty much the same way. Make > sure you read to the section "Doing It Properly" - the author likes to > show you the hard way first. > > The article http://www.voidspace.org.uk/python/articles/cookielib.shtml > shows how to use cookies, though again the presentation makes it look > harder than it really is, at least in Python 2.4 that has CookieLib > built in. You have to post to the login form yourself, but that is just > another urllib2 request. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From kent37 at tds.net Thu Mar 2 14:20:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Mar 2006 08:20:12 -0500 Subject: [Tutor] How can a function know where it was called from In-Reply-To: <29521.203.145.176.76.1141299579.squirrel@members.hcoop.net> References: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> <29521.203.145.176.76.1141299579.squirrel@members.hcoop.net> Message-ID: <4406F10C.6050006@tds.net> Noufal Ibrahim wrote: > On Thu, March 2, 2006 3:55 pm, Ben Vinger wrote: > >>Hello >> >>I want myfunction in the pseudocode below return something different if it >>was called from indexfunction. > > > I'm new to this but maybe it would be good if you passed the appropriate > "version" of "myfunction" to indexfunction from where the original > decision of which one to use was made rather than doing it at the lower > levels. > > Something like. > > def myfunwithheaders(x): > return header + x + footer > > def myfunwithoutheaders(x): > return x > > def main(): > blah > if needheaders: > myfunction(myfunwithheaders) > else: > myfunction(myfunwithoutheaders) > > def myfunction(ret): > x = "whatever" > return ret(x) > > I'd appreciate if some of the more experienced folks on the list comment > on the general approach. This seems needlessly complicated in this case. I would just give myfunction() a default parameter: def myfunction(includeHeader=False): x = 'whatever' if not includeHeader: return x else: return <header> + x + <footer> Alternately you could have two versions of myfunction, one that includes the header/footer and one that does not. The one that does include the header could call the other one to generate 'x', if that is complex. I would only consider inspecting the stack in an extreme situation, maybe if I was modifying myfunction but had no control over the calling code. But this solution smells badly - it is complex, fragile (will break if the name of the calling function changes) and obscure (there is no clue at the point of call that the behaviour is going to be different). Anyway if you must, take a look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Kent From kent37 at tds.net Thu Mar 2 14:22:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Mar 2006 08:22:40 -0500 Subject: [Tutor] (no subject) In-Reply-To: <000601c63d91$579ac1b0$6600a8c0@LivingRoom> References: <000601c63d91$579ac1b0$6600a8c0@LivingRoom> Message-ID: <4406F1A0.1080200@tds.net> Jacob Simonovich wrote: > I want to learn how to hack but don't know where to start. I have been > searching all over the internet to try to find things out but none of > the websites have helped me. I would like to know the tools needed and > just a step by step process on how to do it using widows xp home edition. If you mean hack in this sense: http://www.catb.org/~esr/faqs/hacker-howto.html then learning Python is a great place to start, check out one of the tutorials here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers If you mean hack as in cracking programs and writing viruses, you've come to the wrong place. Kent From benvinger at googlemail.com Thu Mar 2 14:23:10 2006 From: benvinger at googlemail.com (Ben Vinger) Date: Thu, 2 Mar 2006 13:23:10 +0000 Subject: [Tutor] How can a function know where it was called from In-Reply-To: <4406DE03.8000805@hartter.com> References: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> <4406DE03.8000805@hartter.com> Message-ID: <a4a2301f0603020523q7ea35c93hfa62f6767dd0f96e@mail.gmail.com> Thanks to all who responded. I ended up using a sender parameter as suggested by Andre and Alan, as this was very simple to do. Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060302/c507315d/attachment.htm From kent37 at tds.net Thu Mar 2 14:02:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Mar 2006 08:02:46 -0500 Subject: [Tutor] password protection in httplib In-Reply-To: <6faf39c90603020445y8d99b52s@mail.gmail.com> References: <6faf39c90603010258w53737201n@mail.gmail.com> <44058DF4.10402@tds.net> <6faf39c90603020445y8d99b52s@mail.gmail.com> Message-ID: <4406ECF6.8020609@tds.net> Andre Engels wrote: > Thanks for your help; it brought me quite a bit farther, but not as > far as I wanted to come. The authentication is basic authentication, > and I have been able to adapt the programs so that I now get my pages > correctly. > > However, the program uses not only 'GET' operations, but also 'PUT' > operations. These are done using httplib rather than urllib, and I > cannot see at this point how I can mimick those using urllib2. The docs don't spell it out, but if you pass the 'data' parameter to urllib2.urlopen(), it will make a POST request instead of a GET. The data has to be formatted as application/x-www-form-urlencoded; urllib.urlencode() will do this for you. So for example: import urllib, urllib2 data = dict(param1='foo', param2='bar') data = urllib.urlencode(data) # set up your basic auth as before result = urllib2.urlopen('http://some.server.com', data).read() Kent From hugonz-lists at h-lab.net Thu Mar 2 17:22:52 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 02 Mar 2006 10:22:52 -0600 Subject: [Tutor] More on Pickle Message-ID: <44071BDC.6000703@h-lab.net> Hi Joaquin, Make sure you hit Reply-all in your mail program, so the whole list can get the message. I'm forwarding for visibility anyway. ============ >Thank you for your response, but now i have more >doubts: >the file must exist before that, or it can be created >at the same time I do the call to sabe de dictionary? It is created in the call to the open() function, with parameter "w" (for write) >I have two dictionaries like this: >one to save the type of the variables I save, and it >is indexed by the name of the variable The data is not contained in any variable until you unpickle it and assign it. >what i want to do is sth like that: >save (dictionaries, file) >so in the file I want to save the 2 dictionaries, and >later, load the two dictionaris. Is it possible?Is it >possible to have both dictionaries in the same file? Yes, you use Pickle.dump() for the same file, one var after the other. When you unpickle it, do it from the last var you pickled.. fileo = open("mypickle", "w") cPickle.dump(myvar, fileo) cPickle.dump(myvar2, fileo) then when unpickling myvar2 = cPickle.load(mypickle) myvar = cPickle.load(mypickle) Note the order.... and you don't have to do any seeking in the file or anything. Looks to me that you should try some more in the interactive prompt; that's how one discovers if it works. Hope that helps, give it a shot, remember you can do some tries without incorporating it in your main progran, just to see how it works. Hugo ______________________________________________ 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 Barry.Carroll at psc.com Thu Mar 2 17:58:45 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 2 Mar 2006 08:58:45 -0800 Subject: [Tutor] (no subject) Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C360C@eugsrv400.psc.pscnet.com> Jacob, What, exactly, do you mean by 'hack'? The free dictionary wiktionary http://en.wiktionary.org/wiki gives the following definitions hack Verb to hack (third-person singular simple present hacks, present participle hacking, simple past hacked, past participle hacked) 1. To cough noisily. This cold is awful. I can't stop hacking. 2. To chop or cut down in a rough manner. They hacked the brush down and made their way through the jungle. 3. To withstand or put up with a difficult situation. Can you hack it out here with no electricity or running water? 4. To play hackeysack. 5. to accomplish a difficult programming task. She can hack like no one else and make the program work as expected. 6. To work with on an intimately technical level. I'm currently hacking distributed garbage collection. 7. To make a quick code change to patch a computer program. I hacked in a fix for this bug, but we'll still have to do a real fix later.. 8. To gain unauthorized access to a computer system (e.g. website) by manipulating code. (Widely called "crack") 9. to hack into; to gain illegal access to a computer network; a "crack" in computer parlance. I'm going to guess that you aren't referring to any of the first four definitions, so I'll bypass those. If your interest is in definition 5, 6, or 7, the short answer is, you learn by doing. Find a problem you want to solve, make a stab (hack, if you will) at solving it using Python, and post questions here. There are many skilled people here who will be more than happy to help. If you're talking about definitions 8 or 9, you've come to the wrong place. No one here is interested in helping people break the law or steal someone else's intellectual property. Go to http://catb.org/esr/faqs/hacker-howto.html#MS_hater and read Eric's excellent essay on hacking. If you're still interested, come on back and we'll help you get started. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > ------------------------------ > > Message: 3 > Date: Wed, 1 Mar 2006 18:36:26 -0600 > From: "Jacob Simonovich" <Simo10 at mchsi.com> > Subject: [Tutor] (no subject) > To: <tutor at python.org> > Message-ID: <000601c63d91$579ac1b0$6600a8c0 at LivingRoom> > Content-Type: text/plain; charset="iso-8859-1" > > I want to learn how to hack but don't know where to start. I have been > searching all over the internet to try to find things out but none of the > websites have helped me. I would like to know the tools needed and just a > step by step process on how to do it using widows xp home edition. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20060301/680c01c3/att ac > hment.htm > > ------------------------------ From hugonz-lists at h-lab.net Thu Mar 2 18:52:15 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 02 Mar 2006 11:52:15 -0600 Subject: [Tutor] doubt: 2nd part In-Reply-To: <20060302091126.99308.qmail@web26912.mail.ukl.yahoo.com> References: <20060302091126.99308.qmail@web26912.mail.ukl.yahoo.com> Message-ID: <440730CF.7010502@h-lab.net> Hi Joaquin, Remember to Reply-All for the whole list to receive the message. Joaquin Sanchez Sanchez wrote: > Im proving pickle in python. > As I mentioned before, i do pickle.dump for two times, > because I want to save two dictionaries. > > Then to save the dictionaries, with one pickle.load() > is not enough, because I only load the first > dictionary. You did dump() twice, now you need to do load() twice too.. load() does all of the work with the file, just call it again with the same file object, you will get the first object you pickled. > > So, if I want to save the dictionaries in several > sessions, How can I with one cpickle.load load all the file? If you want to do it in one step, I can think of composing a tuple of the variables you want to pickle, like this: pickle.dump( (mydict1, mydict2) , fileo) Then you could load it like this: mydict1, mydict2 = pickle.load(fileo) =========== See, I just tested it: >>> import pickle >>> fileo = open('lala', 'w') >>> pickle.dump( ('this is some data', 'this is more data'), fileo) >>> fileo.close() >>> >>> fileo2 = open('lala', 'r') >>> pickle.load(fileo2) ('this is some data', 'this is more data') >>> =========== Hugo From carroll at tjc.com Thu Mar 2 21:41:27 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Mar 2006 12:41:27 -0800 (PST) Subject: [Tutor] (no subject) In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C360C@eugsrv400.psc.pscnet.com> Message-ID: <Pine.LNX.4.44.0603021240440.15491-100000@violet.rahul.net> On Thu, 2 Mar 2006, Carroll, Barry wrote: > Go to > > http://catb.org/esr/faqs/hacker-howto.html#MS_hater > > and read Eric's excellent essay on hacking. If you're still interested, > come on back and we'll help you get started. And, as long as you're visiting Eric's site, check out http://www.catb.org/esr/faqs/smart-questions.html#bespecific , too. From bgailer at alum.rpi.edu Thu Mar 2 21:57:02 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 02 Mar 2006 12:57:02 -0800 Subject: [Tutor] How can a function know where it was called from In-Reply-To: <a4a2301f0603020523q7ea35c93hfa62f6767dd0f96e@mail.gmail.com> References: <a4a2301f0603020225q5f6402cbq528d6f1a81ea038a@mail.gmail.com> <4406DE03.8000805@hartter.com> <a4a2301f0603020523q7ea35c93hfa62f6767dd0f96e@mail.gmail.com> Message-ID: <44075C1E.6080305@alum.rpi.edu> Ben Vinger wrote: > Thanks to all who responded. I ended up using a sender parameter as > suggested by Andre and Alan, as this was very simple to do. When confronted with problems like this I tend to create classes, then subclass as needed for special circumstances. You might consider that approach. From carroll at tjc.com Thu Mar 2 22:03:27 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Mar 2006 13:03:27 -0800 (PST) Subject: [Tutor] Sorting a list of objects on different fields Message-ID: <Pine.LNX.4.44.0603021252490.15491-100000@violet.rahul.net> I have a list (or a list-like object, doesn't matter) of objects, each of which has multiple fields. I want to be able to arbitrarily sort the list on any of them, or at least on several of them. To make this a little more concrete, here's a simplified idea. Say the objects each represent a file, and I've got fields in it like this: self.filesz: size of the file self.filename: name of the file self.users : a list of people who need to know if the file gets updated self.filetype : a short description of the file contents etc. I sometimes want to sort the list by filesz; and sometimes by filename; and maybe sometimes by some other field. My sense right now is that the "list" of these objects itself should be an object inheriting from list, and that I should create a small sort method for each field I intend to sort on. (I don't have the book handy, but there's a nice recipe for this in the Python Cookbook, 2d Edition, for such a method.) Is there a better (more clear and easy) way to be able to do this, or am I pretty much on the right track? From kent37 at tds.net Thu Mar 2 22:25:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Mar 2006 16:25:50 -0500 Subject: [Tutor] Sorting a list of objects on different fields In-Reply-To: <Pine.LNX.4.44.0603021252490.15491-100000@violet.rahul.net> References: <Pine.LNX.4.44.0603021252490.15491-100000@violet.rahul.net> Message-ID: <440762DE.5040008@tds.net> Terry Carroll wrote: > I have a list (or a list-like object, doesn't matter) of objects, each of > which has multiple fields. I want to be able to arbitrarily sort the list > on any of them, or at least on several of them. > > To make this a little more concrete, here's a simplified idea. Say the > objects each represent a file, and I've got fields in it > like this: > > self.filesz: size of the file > self.filename: name of the file > self.users : a list of people who need to know if the file gets updated > self.filetype : a short description of the file contents > > etc. > > > I sometimes want to sort the list by filesz; and sometimes by filename; > and maybe sometimes by some other field. > > My sense right now is that the "list" of these objects itself should be an > object inheriting from list, and that I should create a small sort method > for each field I intend to sort on. (I don't have the book handy, but > there's a nice recipe for this in the Python Cookbook, 2d Edition, for > such a method.) As long as your list-like object is list-like enough to be sorted, you can use operator.attrgetter to create functions that serve as a key parameter. In [1]: class foo(object): ...: def __init__(self, a, b, c): ...: self.a = a; self.b = b; self.c = c ...: def __repr__(self): ...: return repr((self.a, self.b, self.c)) ...: ...: In [2]: lst = [foo(1, 'one', 'I'), foo(2, 'two', 'II'), foo(10, 'ten', 'X'), foo(50, 'fifty', 'V')] In [7]: lst Out[7]: [(1, 'one', 'I'), (2, 'two', 'II'), (10, 'ten', 'X'), (50, 'fifty', 'V')] In [8]: from operator import attrgetter In [9]: lst.sort(key=attrgetter('b')); print lst [(50, 'fifty', 'V'), (1, 'one', 'I'), (10, 'ten', 'X'), (2, 'two', 'II')] In [10]: lst.sort(key=attrgetter('c')); print lst [(1, 'one', 'I'), (2, 'two', 'II'), (50, 'fifty', 'V'), (10, 'ten', 'X')] Kent From carroll at tjc.com Thu Mar 2 22:45:25 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Mar 2006 13:45:25 -0800 (PST) Subject: [Tutor] Sorting a list of objects on different fields In-Reply-To: <440762DE.5040008@tds.net> Message-ID: <Pine.LNX.4.44.0603021344070.15491-100000@violet.rahul.net> On Thu, 2 Mar 2006, Kent Johnson wrote: > In [9]: lst.sort(key=attrgetter('b')); print lst Thanks, Kent! I didn't know about "key=". I see it's new in 2.4. I was thinking I'd have to put in a method for each potentially sortable field. From carroll at tjc.com Thu Mar 2 22:52:30 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Mar 2006 13:52:30 -0800 (PST) Subject: [Tutor] Sorting a list of objects on different fields In-Reply-To: <Pine.LNX.4.44.0603021344070.15491-100000@violet.rahul.net> Message-ID: <Pine.LNX.4.44.0603021350450.15491-100000@violet.rahul.net> On Thu, 2 Mar 2006, Terry Carroll wrote: > Thanks, Kent! I didn't know about "key=". I see it's new in 2.4. > I was thinking I'd have to put in a method for each potentially sortable > field. And, in the spirit of RTFM, I should have been looking here first: http://wiki.python.org/moin/HowTo/Sorting Embarrassingly, it's the first Google hit on "python sort". From kermit at polaris.net Thu Mar 2 23:59:33 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 2 Mar 2006 17:59:33 -0500 (Eastern Standard Time) Subject: [Tutor] Environmental variables? Message-ID: <440778D5.000003.03012@YOUR-4105E587B6> In the primary tutor file, in section 2.2.4 The Interactive Startup File . It states: You can do this by setting an environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands How do I set environmental variables in Windows? Kermit < kermit at polaris.net > From ukc802591034 at btconnect.com Fri Mar 3 00:21:26 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Thu, 2 Mar 2006 23:21:26 -0000 Subject: [Tutor] Environmental variables? References: <440778D5.000003.03012@YOUR-4105E587B6> Message-ID: <du7ujr$bj3$1@sea.gmane.org> > You can do this by setting an environment variable named PYTHONSTARTUP to > name of a file containing your start-up commands > > How do I set environmental variables in Windows? If it's Windows 9x/Me use AUTOEXEC.BAT. SET PTYTHONSTARTUP C:\mypath\myfile.py If its Windows NT/2000/XP right click My Computer, select Properties, select Advanced tab click Environment Variables. click New Hopefully self explanatory after that. In either environment searching for envoironment variable in the windows help system gives the answer... The Windows help files are a greatly under used feature of the OS...IMHO Alan G. From rakesh.mishra at gmail.com Fri Mar 3 05:22:10 2006 From: rakesh.mishra at gmail.com (Rakesh Mishra) Date: Fri, 3 Mar 2006 04:22:10 +0000 Subject: [Tutor] Tutorial for creating web server Message-ID: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> hi i wanted to create my own web server, can any body suggest any tutorial, by the way i have gone through book Core Python Programing, in this book one example is given but it is to abstract, that i am unable to understand . Thanks in advance rakesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060303/411c1f27/attachment-0001.htm From john at fouhy.net Fri Mar 3 05:31:41 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 3 Mar 2006 17:31:41 +1300 Subject: [Tutor] Tutorial for creating web server In-Reply-To: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> References: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> Message-ID: <5e58f2e40603022031o726dd035x@mail.gmail.com> On 03/03/06, Rakesh Mishra <rakesh.mishra at gmail.com> wrote: > hi > > i wanted to create my own web server, can any body suggest any tutorial, > by the way i have gone through book Core Python Programing, in this book > one example is given but it is to abstract, that i am unable to understand Do you actually want to create a web server, or do you mean something like CGI programming? If you want to do a web server, you could look at the socket module in the standard library, and track down the RFC that describes the HTTP protocol. Or you could look at BaseHTTPServer or SimpleHTTPServer, again both in the standard library. I've never used them, but it seems like they will drastically simplify the task of making a web server. -- John. From Gideon.STREET at ergon.com.au Fri Mar 3 06:41:42 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Fri, 3 Mar 2006 15:41:42 +1000 Subject: [Tutor] Print list vs telnetlib.telnet.write differences Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC0A256B@ebnewem01.ergon> Hi all, I've got the following snippet in a script I'm playing around with and need some help. Basically the script telnets to a cisco switch, "tn.read_until" a subsection of the config, outputs to a file, then using readlines brings it back into the script as a list where I'm changing some fields and then outputting it again. (the script is long and messy but it's my second attempt at writing something to make my network admin life easier, I'm sure over time I can make it a bit more robust). Anyway, "lines" is the list read from a text file, and a "print lines" looks like: ['banner exec ^\r\n', '##################################################\r\n', ' EMKYSW34 - User Access Switch, 2nd Floor\r\n', " Corner of XXXXXX and XXXX St's XXXXXX XXX\r\n", ' Site Contact: KXXX SXXXXX XX XXXXXXX0\r\n', ' System Contact: XXXXX Helpdesk XXXXXXXXXX\r\n', '############################### ###################\r\n', '^\r\n'] As I'm trying to get the above cleaned up banner sent to the telnet session I use the following command (without the print x # part). tn.read_until('#') for item in lines: x = item print x #tn.write(x) The problem I'm stumbling over is that when I print x, the output is what I want. If I delete the print x and #, leaving only tn.write(x) on the last line everything looks good except it writes the 1st item in "lines" (the banner exec command) twice, once at the beginning where it's supposed to, but then once again at the end. See except below for example. Anyone able to explain why that is happening or is it me just not understanding what I'm doing? Hope my explanation is clear I'm still unfamiliar with the exact phrasology. <SNIP> emkysw34#conf t conf t Enter configuration commands, one per line. End with CNTL/Z. emkysw34(config)#banner exec ^ ################################################## EMKYSW34 - User Access Switch, 2nd Floor Corner of XXXXXX and XXXXXX St's XXXXXX XXX Site Contact: XXXX XXXXXX XX XXXXXXXX System Contact: XXXXX Helpdesk XXXXXXXX ################################################## ^ banner exec ^ <----heres the second instance being printed for no reason I can understand Enter TEXT message. End with the character '^'. ####exit ############## <SNIP> Thanks 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 David.Heiser at intelliden.com Fri Mar 3 07:24:57 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Thu, 2 Mar 2006 23:24:57 -0700 Subject: [Tutor] Print list vs telnetlib.telnet.write differences Message-ID: <3CABD13EA1D5D347A1B75014BD54CFD502B0BB9E@COSIUM03.intelliden.net> I believe you can submit the new config content as a blob where blob = string.join(lines). It looks like your "switch" uses IOS, not CatOS, so make sure you send "config t" first. And I would strip out the \r's. Then maybe: ------------------------ tn.write("\03") # Assures the device is in enable mode x = tn.read_until("#") # The "x =" seems to help flush the read buffer tn.write("conf t\n") x = tn.read_until("#") tn.write(blob) -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of STREET Gideon (SPARQ) Sent: Thursday, March 02, 2006 10:42 PM To: tutor at python.org Subject: [Tutor] Print list vs telnetlib.telnet.write differences Hi all, I've got the following snippet in a script I'm playing around with and need some help. Basically the script telnets to a cisco switch, "tn.read_until" a subsection of the config, outputs to a file, then using readlines brings it back into the script as a list where I'm changing some fields and then outputting it again. (the script is long and messy but it's my second attempt at writing something to make my network admin life easier, I'm sure over time I can make it a bit more robust). Anyway, "lines" is the list read from a text file, and a "print lines" looks like: ['banner exec ^\r\n', '##################################################\r\n', ' EMKYSW34 - User Access Switch, 2nd Floor\r\n', " Corner of XXXXXX and XXXX St's XXXXXX XXX\r\n", ' Site Contact: KXXX SXXXXX XX XXXXXXX0\r\n', ' System Contact: XXXXX Helpdesk XXXXXXXXXX\r\n', '############################### ###################\r\n', '^\r\n'] As I'm trying to get the above cleaned up banner sent to the telnet session I use the following command (without the print x # part). tn.read_until('#') for item in lines: x = item print x #tn.write(x) The problem I'm stumbling over is that when I print x, the output is what I want. If I delete the print x and #, leaving only tn.write(x) on the last line everything looks good except it writes the 1st item in "lines" (the banner exec command) twice, once at the beginning where it's supposed to, but then once again at the end. See except below for example. Anyone able to explain why that is happening or is it me just not understanding what I'm doing? Hope my explanation is clear I'm still unfamiliar with the exact phrasology. <SNIP> emkysw34#conf t conf t Enter configuration commands, one per line. End with CNTL/Z. emkysw34(config)#banner exec ^ ################################################## EMKYSW34 - User Access Switch, 2nd Floor Corner of XXXXXX and XXXXXX St's XXXXXX XXX Site Contact: XXXX XXXXXX XX XXXXXXXX System Contact: XXXXX Helpdesk XXXXXXXX ################################################## ^ banner exec ^ <----heres the second instance being printed for no reason I can understand Enter TEXT message. End with the character '^'. ####exit ############## <SNIP> Thanks 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 _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Mar 3 12:52:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Mar 2006 06:52:15 -0500 Subject: [Tutor] Tutorial for creating web server In-Reply-To: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> References: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> Message-ID: <44082DEF.3050903@tds.net> Rakesh Mishra wrote: > hi > > i wanted to create my own web server, can any body suggest any tutorial, > by the way i have gone through book Core Python Programing, in this book > one example is given but it is to abstract, that i am unable to understand . Can you be more specific? Creating a web server in Python can be done in one line: python -c "import CGIHTTPServer; CGIHTTPServer.test()" will start a web server that serves static files and cgi's. There are *many* options for creating a full web application in Python (too many options, some say). Two currently popular choices are Django and TurboGears but they may be overkill for what you need. Anyway we really need more details of what you want to do and why to be able to help you. Kent From kermit at polaris.net Fri Mar 3 13:07:08 2006 From: kermit at polaris.net (Kermit Rose) Date: Fri, 3 Mar 2006 07:07:08 -0500 (Eastern Standard Time) Subject: [Tutor] windows help system Message-ID: <4408316C.000007.03996@YOUR-4105E587B6> >> You can do this by setting an environment variable named PYTHONSTARTUP to >> name of a file containing your start-up commands > > How do I set environmental variables in Windows? If it's Windows 9x/Me use AUTOEXEC.BAT. SET PTYTHONSTARTUP C:\mypath\myfile.py If its Windows NT/2000/XP right click My Computer, select Properties, select Advanced tab click Environment Variables. click New Hopefully self explanatory after that. In either environment searching for envoironment variable in the windows help system gives the answer... The Windows help files are a greatly under used feature of the OS...IMHO Alan G. Hello Alan! Thanks. I found the windows help and support center. It's not obvious how to use it. Could not find an index search box. I finally did find the windows web newsgroup, and found where someone posted a question about environmental variables, in which he just happened to list the same information you did about environment variable. Environmental variable is not in the windows help glossary. Before today I did not know that a windows help existed. Kermit kermit at polaris.net From kermit at polaris.net Fri Mar 3 13:49:32 2006 From: kermit at polaris.net (Kermit Rose) Date: Fri, 3 Mar 2006 07:49:32 -0500 (Eastern Standard Time) Subject: [Tutor] odbchelper Message-ID: <44083B5C.00000F.03996@YOUR-4105E587B6> When I tried to run a program show at the beginning of "Dive into Python", I got. Traceback (most recent call last): File "<pyshell#2>", line 1, in -toplevel- import odbchelper ImportError: No module named odbchelper >>> From andreengels at gmail.com Fri Mar 3 14:07:23 2006 From: andreengels at gmail.com (Andre Engels) Date: Fri, 3 Mar 2006 14:07:23 +0100 Subject: [Tutor] password protection in httplib In-Reply-To: <4406ECF6.8020609@tds.net> References: <6faf39c90603010258w53737201n@mail.gmail.com> <44058DF4.10402@tds.net> <6faf39c90603020445y8d99b52s@mail.gmail.com> <4406ECF6.8020609@tds.net> Message-ID: <6faf39c90603030507y347eae84t@mail.gmail.com> 2006/3/2, Kent Johnson <kent37 at tds.net>: > Andre Engels wrote: > > Thanks for your help; it brought me quite a bit farther, but not as > > far as I wanted to come. The authentication is basic authentication, > > and I have been able to adapt the programs so that I now get my pages > > correctly. > > > > However, the program uses not only 'GET' operations, but also 'PUT' > > operations. These are done using httplib rather than urllib, and I > > cannot see at this point how I can mimick those using urllib2. > > The docs don't spell it out, but if you pass the 'data' parameter to > urllib2.urlopen(), it will make a POST request instead of a GET. The > data has to be formatted as application/x-www-form-urlencoded; > urllib.urlencode() will do this for you. > > So for example: > > import urllib, urllib2 > data = dict(param1='foo', param2='bar') > data = urllib.urlencode(data) > > # set up your basic auth as before > result = urllib2.urlopen('http://some.server.com', data).read() Thanks, I've gotten some further again, but the following problem is that I am using this connection to get some cookies, which are read from the page headers. As far as I can see, urllib2 puts the page headers into a dictionary, which is not what I need, because there are 4 different set-cookie headers sent out by the site, and I get only one "set-cookie" value. Am I right in this, and is there a way around it? -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From ewald.ertl at hartter.com Fri Mar 3 14:24:11 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Fri, 03 Mar 2006 14:24:11 +0100 Subject: [Tutor] odbchelper In-Reply-To: <44083B5C.00000F.03996@YOUR-4105E587B6> References: <44083B5C.00000F.03996@YOUR-4105E587B6> Message-ID: <4408437B.6050208@hartter.com> Hi! How have you started the script? As far as I could see, in the Chapter 1 of "Dive into Python", the odbchelper.py is just a script-File and not a module to be imported, therefore the Exception with the "ImportError". I do not have a Windows box here to check if the problem is with the PythonIDE. Testing with idle ( the python ide ) under solaris and putting the source-Code from Chapter 1 into the buffer, saving it and just starting with "F5" = "Run Module" just gives the string. Otherwise under unix just start "python odbchelper.py" on the commandline. HTH Ewald Kermit Rose wrote: > When I tried to run a program show at the beginning of "Dive into Python", > > I got. > > > Traceback (most recent call last): > File "<pyshell#2>", line 1, in -toplevel- > import odbchelper > ImportError: No module named odbchelper > > > > >>>> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Fri Mar 3 14:36:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Mar 2006 08:36:33 -0500 Subject: [Tutor] odbchelper In-Reply-To: <44083B5C.00000F.03996@YOUR-4105E587B6> References: <44083B5C.00000F.03996@YOUR-4105E587B6> Message-ID: <44084661.3050503@tds.net> Kermit Rose wrote: > When I tried to run a program show at the beginning of "Dive into Python", > > I got. > > > Traceback (most recent call last): > File "<pyshell#2>", line 1, in -toplevel- > import odbchelper > ImportError: No module named odbchelper odbchelper is the module defined in Example 2.1. You need this file stored somewhere on the python search path; the current working directory is probably a good choice. In the future if you could give a pointer to the program you are trying to run that would be helpful. Kent From kent37 at tds.net Fri Mar 3 14:43:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Mar 2006 08:43:05 -0500 Subject: [Tutor] password protection in httplib In-Reply-To: <6faf39c90603030507y347eae84t@mail.gmail.com> References: <6faf39c90603010258w53737201n@mail.gmail.com> <44058DF4.10402@tds.net> <6faf39c90603020445y8d99b52s@mail.gmail.com> <4406ECF6.8020609@tds.net> <6faf39c90603030507y347eae84t@mail.gmail.com> Message-ID: <440847E9.5090106@tds.net> Andre Engels wrote: > 2006/3/2, Kent Johnson <kent37 at tds.net>: > >>Andre Engels wrote: >> >>>Thanks for your help; it brought me quite a bit farther, but not as >>>far as I wanted to come. The authentication is basic authentication, >>>and I have been able to adapt the programs so that I now get my pages >>>correctly. >>> >>>However, the program uses not only 'GET' operations, but also 'PUT' >>>operations. These are done using httplib rather than urllib, and I >>>cannot see at this point how I can mimick those using urllib2. >> >>The docs don't spell it out, but if you pass the 'data' parameter to >>urllib2.urlopen(), it will make a POST request instead of a GET. The >>data has to be formatted as application/x-www-form-urlencoded; >>urllib.urlencode() will do this for you. >> >>So for example: >> >>import urllib, urllib2 >>data = dict(param1='foo', param2='bar') >>data = urllib.urlencode(data) >> >># set up your basic auth as before >>result = urllib2.urlopen('http://some.server.com', data).read() > > > Thanks, I've gotten some further again, but the following problem is > that I am using this connection to get some cookies, which are read > from the page headers. As far as I can see, urllib2 puts the page > headers into a dictionary, which is not what I need, because there are > 4 different set-cookie headers sent out by the site, and I get only > one "set-cookie" value. Am I right in this, and is there a way around > it? Have you tried using a CookieManager as shown in the first example here: http://docs.python.org/lib/cookielib-examples.html Once you set up your opener with a CookieJar the cookies should be handled automatically - if a server sets a cookie it will be remembered and returned back to the server on subsequent requests. This page has more examples though again IMO they are overly complex: http://www.voidspace.org.uk/python/articles/cookielib.shtml Kent From kent37 at tds.net Fri Mar 3 14:47:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Mar 2006 08:47:38 -0500 Subject: [Tutor] odbchelper In-Reply-To: <4408437B.6050208@hartter.com> References: <44083B5C.00000F.03996@YOUR-4105E587B6> <4408437B.6050208@hartter.com> Message-ID: <440848FA.1060607@tds.net> Ewald Ertl wrote: > Hi! > > How have you started the script? As far as I could see, in the Chapter 1 of > "Dive into Python", the odbchelper.py is just a script-File and not a module > to be imported, therefore the Exception with the "ImportError". It is both, if by "just a script-File" you mean a top-level program intended to be run from the command line. If you import odbchelper it will give you access to the buildConnectionString() function. If you run it from the command line, it will also run the code after if __name__ == "__main__": This is pretty common - to write a module so it can be imported or used as a main program. The parts you want to run only from the command line are set off by this conditional. From andreengels at gmail.com Fri Mar 3 15:26:14 2006 From: andreengels at gmail.com (Andre Engels) Date: Fri, 3 Mar 2006 15:26:14 +0100 Subject: [Tutor] password protection in httplib In-Reply-To: <6faf39c90603030625i1de75265j@mail.gmail.com> References: <6faf39c90603010258w53737201n@mail.gmail.com> <44058DF4.10402@tds.net> <6faf39c90603020445y8d99b52s@mail.gmail.com> <4406ECF6.8020609@tds.net> <6faf39c90603030507y347eae84t@mail.gmail.com> <440847E9.5090106@tds.net> <6faf39c90603030625i1de75265j@mail.gmail.com> Message-ID: <6faf39c90603030626r12af7b6p@mail.gmail.com> 2006/3/3, Kent Johnson <kent37 at tds.net>: > Have you tried using a CookieManager as shown in the first example here: > http://docs.python.org/lib/cookielib-examples.html > > Once you set up your opener with a CookieJar the cookies should be > handled automatically - if a server sets a cookie it will be remembered > and returned back to the server on subsequent requests. > > This page has more examples though again IMO they are overly complex: > http://www.voidspace.org.uk/python/articles/cookielib.shtml I had looked at it yes, but I don't know how to combine the two handlers (the one for authentication and the one for cookies). Apart from that I hoped that because the program already has cookie handling programmed in, reusing that code might be less trouble than splitting the authenticated and the non-authenticated case everywhere. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From kent37 at tds.net Fri Mar 3 15:35:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Mar 2006 09:35:54 -0500 Subject: [Tutor] password protection in httplib In-Reply-To: <6faf39c90603030625i1de75265j@mail.gmail.com> References: <6faf39c90603010258w53737201n@mail.gmail.com> <44058DF4.10402@tds.net> <6faf39c90603020445y8d99b52s@mail.gmail.com> <4406ECF6.8020609@tds.net> <6faf39c90603030507y347eae84t@mail.gmail.com> <440847E9.5090106@tds.net> <6faf39c90603030625i1de75265j@mail.gmail.com> Message-ID: <4408544A.5080807@tds.net> Andre Engels wrote: > 2006/3/3, Kent Johnson <kent37 at tds.net>: > > >>Have you tried using a CookieManager as shown in the first example here: >>http://docs.python.org/lib/cookielib-examples.html >> >>Once you set up your opener with a CookieJar the cookies should be >>handled automatically - if a server sets a cookie it will be remembered >>and returned back to the server on subsequent requests. >> >>This page has more examples though again IMO they are overly complex: >>http://www.voidspace.org.uk/python/articles/cookielib.shtml > > > I had looked at it yes, but I don't know how to combine the two > handlers (the one for authentication and the one for cookies). Apart > from that I hoped that because the program already has cookie handling > programmed in, reusing that code might be less trouble than splitting > the authenticated and the non-authenticated case everywhere. The call to urllib2.build_opener() accepts multiple arguments, just list both handlers. Kent From rakesh.mishra at gmail.com Fri Mar 3 15:40:15 2006 From: rakesh.mishra at gmail.com (Rakesh Mishra) Date: Fri, 3 Mar 2006 20:10:15 +0530 Subject: [Tutor] Tutorial for creating web server In-Reply-To: <44082DEF.3050903@tds.net> References: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> <44082DEF.3050903@tds.net> Message-ID: <39ce20e10603030640j5c5e7600m3c6ca6610966cb6@mail.gmail.com> Hi Johnson I wanted to create web server some think like similar to ZServer of zope. I wanted to use it for publishing my home page (it is in php), or any web application. I am confused with arch. , ???????? bye rakesh On 3/3/06, Kent Johnson <kent37 at tds.net> wrote: > > Rakesh Mishra wrote: > > hi > > > > i wanted to create my own web server, can any body suggest any tutorial, > > by the way i have gone through book Core Python Programing, in this book > > one example is given but it is to abstract, that i am unable to > understand . > > Can you be more specific? Creating a web server in Python can be done in > one line: > > python -c "import CGIHTTPServer; CGIHTTPServer.test()" > > will start a web server that serves static files and cgi's. > > There are *many* options for creating a full web application in Python > (too many options, some say). Two currently popular choices are Django > and TurboGears but they may be overkill for what you need. > > Anyway we really need more details of what you want to do and why to be > able to help you. > > Kent > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060303/dc1a3c6d/attachment.htm From kent37 at tds.net Fri Mar 3 15:51:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Mar 2006 09:51:46 -0500 Subject: [Tutor] Tutorial for creating web server In-Reply-To: <39ce20e10603030640j5c5e7600m3c6ca6610966cb6@mail.gmail.com> References: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> <44082DEF.3050903@tds.net> <39ce20e10603030640j5c5e7600m3c6ca6610966cb6@mail.gmail.com> Message-ID: <44085802.2010401@tds.net> Rakesh Mishra wrote: > Hi Johnson > I wanted to create web server some think like similar to ZServer of zope. > I wanted to use it for publishing my home page (it is in php), or any > web application. > I am confused with arch. I still am not sure what you are asking for. Do you want to create something like Zope? Or do you want to use Zope to create your home page? If you want to learn Zope you should go to the Zope web site. Kent From ewald.ertl at hartter.com Fri Mar 3 16:43:57 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Fri, 03 Mar 2006 16:43:57 +0100 Subject: [Tutor] odbchelper In-Reply-To: <440848FA.1060607@tds.net> References: <44083B5C.00000F.03996@YOUR-4105E587B6> <4408437B.6050208@hartter.com> <440848FA.1060607@tds.net> Message-ID: <4408643D.9090903@hartter.com> Hi Kent! You are absolutely right. Sorry for my bad description. Kent Johnson wrote: > Ewald Ertl wrote: >> Hi! >> >> How have you started the script? As far as I could see, in the Chapter 1 of >> "Dive into Python", the odbchelper.py is just a script-File and not a module >> to be imported, therefore the Exception with the "ImportError". > > It is both, if by "just a script-File" you mean a top-level program > intended to be run from the command line. > Yes I meant a top-level-program. > If you import odbchelper it will give you access to the > buildConnectionString() function. If you run it from the command line, > it will also run the code after > if __name__ == "__main__": > > This is pretty common - to write a module so it can be imported or used > as a main program. The parts you want to run only from the command line > are set off by this conditional. > I looked at the code of odbchelper.py in Example 2.1 in my printed Version of "Dive into Python" and there was no "import", so I assumed some problem with the IDE. But the Traceback came from Example 2.5 in my version. Thanks for your response on my attempt to help Ewald From alan.gauld at freenet.co.uk Fri Mar 3 17:41:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 3 Mar 2006 16:41:26 -0000 Subject: [Tutor] windows help system References: <4408316C.000007.03996@YOUR-4105E587B6> Message-ID: <01ad01c63ee1$507e3550$0b01a8c0@xp> > Environmental variable is not in the windows help glossary. Strange, in both Windows 2000 and XP I type 'environment variable' into the search box and the list of topics returned includes "Setting environment variables" I'm sure Win98 does too because I've used it in the past. > Before today I did not know that a windows help existed. You are not alone, for some reason people never seem to notice it despite it being a standard menu feature. Alan G. From kermit at polaris.net Fri Mar 3 17:47:50 2006 From: kermit at polaris.net (Kermit Rose) Date: Fri, 3 Mar 2006 11:47:50 -0500 (Eastern Standard Time) Subject: [Tutor] windows help system References: <01ad01c63ee1$507e3550$0b01a8c0@xp> Message-ID: <44087336.000001.03040@YOUR-4105E587B6> From: Alan Gauld Date: 03/03/06 11:41:05 To: Kermit Rose; tutor at python.org Subject: Re: [Tutor] windows help system > Environmental variable is not in the windows help glossary. Strange, in both Windows 2000 and XP I type 'environment variable' into the search box and the list of topics returned includes "Setting environment variables" I'm sure Win98 does too because I've used it in the past. I found the windows help glossary, but did not find a search box. How would I find the search box in Microsoft Windows XP Home Edition ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060303/b8dcfbbe/attachment.html From andreengels at gmail.com Fri Mar 3 17:52:01 2006 From: andreengels at gmail.com (Andre Engels) Date: Fri, 3 Mar 2006 17:52:01 +0100 Subject: [Tutor] password protection in httplib In-Reply-To: <4408544A.5080807@tds.net> References: <6faf39c90603010258w53737201n@mail.gmail.com> <44058DF4.10402@tds.net> <6faf39c90603020445y8d99b52s@mail.gmail.com> <4406ECF6.8020609@tds.net> <6faf39c90603030507y347eae84t@mail.gmail.com> <440847E9.5090106@tds.net> <6faf39c90603030625i1de75265j@mail.gmail.com> <4408544A.5080807@tds.net> Message-ID: <6faf39c90603030852y4335d9d6i@mail.gmail.com> Thanks for your answers! It is working now! 2006/3/3, Kent Johnson <kent37 at tds.net>: > Andre Engels wrote: > > 2006/3/3, Kent Johnson <kent37 at tds.net>: > > > > > >>Have you tried using a CookieManager as shown in the first example here: > >>http://docs.python.org/lib/cookielib-examples.html > >> > >>Once you set up your opener with a CookieJar the cookies should be > >>handled automatically - if a server sets a cookie it will be remembered > >>and returned back to the server on subsequent requests. > >> > >>This page has more examples though again IMO they are overly complex: > >>http://www.voidspace.org.uk/python/articles/cookielib.shtml > > > > > > I had looked at it yes, but I don't know how to combine the two > > handlers (the one for authentication and the one for cookies). Apart > > from that I hoped that because the program already has cookie handling > > programmed in, reusing that code might be less trouble than splitting > > the authenticated and the non-authenticated case everywhere. > > The call to urllib2.build_opener() accepts multiple arguments, just list > both handlers. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From alan.gauld at freenet.co.uk Fri Mar 3 18:13:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 3 Mar 2006 17:13:54 -0000 Subject: [Tutor] windows help system References: <01ad01c63ee1$507e3550$0b01a8c0@xp> <44087336.000001.03040@YOUR-4105E587B6> Message-ID: <01b301c63ee5$da582340$0b01a8c0@xp> > I found the windows help glossary, but did not find a search box. > > How would I find the search box in > Microsoft Windows XP Home Edition When you open Help and Support, just above where it says "Pick a Help Topic" there is a text entry box labelled Search and a green arrow. At least there is on mine! Actually I don't see a Glossary link anywhere! Or do you mean the Index? But if so it does include "environment variables"... Strange! I wobnder? Are you using the Classic Windows interface rather than the XP one? It might be different. PS This is getting well off-topic for Python so any further emails should probably be offlist. Alan G. From python at venix.com Fri Mar 3 18:42:24 2006 From: python at venix.com (Python) Date: Fri, 03 Mar 2006 12:42:24 -0500 Subject: [Tutor] Print list vs telnetlib.telnet.write differences In-Reply-To: <5A504BF2C0C9F5438ACBF61D35D49FFC0A256B@ebnewem01.ergon> References: <5A504BF2C0C9F5438ACBF61D35D49FFC0A256B@ebnewem01.ergon> Message-ID: <1141407744.15743.749.camel@www.venix.com> On Fri, 2006-03-03 at 15:41 +1000, STREET Gideon (SPARQ) wrote: > The problem I'm stumbling over is that when I print x, the output is > what I want. If I delete the print x and #, leaving only tn.write(x) > on > the last line everything looks good except it writes the 1st item in > "lines" (the banner exec command) twice, once at the beginning where > it's supposed to, but then once again at the end. See except below for > example. > > Anyone able to explain why that is happening or is it me just not > understanding what I'm doing? Hope my explanation is clear I'm still > unfamiliar with the exact phrasology. > Could that be your data being echoed back to you? Is the router configured correctly after the script runs? I normally feed commands to Cisco devices using tftp. It is relatively easy to edit a file to get the commands correct. Then you could limit your "conversational script" to logging in and running tftp to transfer the command file. It looks like you are pretty close to having this working. -- 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 wpmartin at gmail.com Fri Mar 3 18:50:23 2006 From: wpmartin at gmail.com (Pat Martin) Date: Fri, 3 Mar 2006 09:50:23 -0800 Subject: [Tutor] usernames and uid in linux Message-ID: <44db03850603030950y20a6de48u96dbd4df759e0155@mail.gmail.com> Hello all, I seem to be having a problem finding the right tool in python. Given a username I want to find the uid for it. I can do the reverse very easily with: pwd.getpwuid(2012) This returns a tuple of data from the passwd file. But I want to do something like: command(username) And get something that returns the uid (the number). Thanks -- Pat Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060303/fff49fd6/attachment-0001.html From bill at celestial.net Fri Mar 3 19:22:20 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 3 Mar 2006 10:22:20 -0800 Subject: [Tutor] usernames and uid in linux In-Reply-To: <44db03850603030950y20a6de48u96dbd4df759e0155@mail.gmail.com> References: <44db03850603030950y20a6de48u96dbd4df759e0155@mail.gmail.com> Message-ID: <20060303182220.GA63933@alexis.mi.celestial.com> On Fri, Mar 03, 2006, Pat Martin wrote: > > Hello all, > I seem to be having a problem finding the right tool in python. Given > a username I want to find the uid for it. I can do the reverse very > easily with: > pwd.getpwuid(2012) > This returns a tuple of data from the passwd file. But I want to do > something like: > command(username) > And get something that returns the uid (the number). You're close: import pwd pw = pwd.getpwnam('username') Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Systems, Inc. URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 There is no distinctly native American criminal class save Congress -- Mark Twain From wpmartin at gmail.com Fri Mar 3 19:47:12 2006 From: wpmartin at gmail.com (Pat Martin) Date: Fri, 3 Mar 2006 10:47:12 -0800 Subject: [Tutor] usernames and uid in linux In-Reply-To: <20060303182220.GA63933@alexis.mi.celestial.com> References: <44db03850603030950y20a6de48u96dbd4df759e0155@mail.gmail.com> <20060303182220.GA63933@alexis.mi.celestial.com> Message-ID: <44db03850603031047s1c8e2e7ap8250c6726356be02@mail.gmail.com> > You're close: > > import pwd > > pw = pwd.getpwnam('username') > > Bill > -- > INTERNET: bill at Celestial.COM Bill Campbell; Celestial Systems, Inc. > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) > 236-1676 > > There is no distinctly native American criminal class save Congress > -- Mark Twain > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I completely missed that. Thank you so much. -- Pat Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060303/27af4a91/attachment.html From adam.jtm30 at gmail.com Sat Mar 4 01:38:43 2006 From: adam.jtm30 at gmail.com (Adam) Date: Sat, 4 Mar 2006 00:38:43 +0000 Subject: [Tutor] One shared object. class attribute or global variable? Message-ID: <be4fbf920603031638p24207323w@mail.gmail.com> I've got a module that needs to share a pack of cards pack = ["14s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", "11s", "12s", "13s", "14d", "2d", "3d", "4d", "5d", "6d", "7d", "8d", "9d", "10d", "11d", "12d", "13d", "14c", "2c", "3c", "4c", "5c", "6c", "7c", "8c", "9c", "10c", "11c", "12c", "13c", "14h", "2h", "3h", "4h", "5h", "6h", "7h", "8h", "9h", "10h", "11h", "12h", "13h"] random.shuffle(pack) do you think it is worth making a class with just this attribute or would this be a good place to use a global variable? From adam.jtm30 at gmail.com Sat Mar 4 01:42:42 2006 From: adam.jtm30 at gmail.com (Adam) Date: Sat, 4 Mar 2006 00:42:42 +0000 Subject: [Tutor] One shared object. class attribute or global variable? In-Reply-To: <be4fbf920603031638p24207323w@mail.gmail.com> References: <be4fbf920603031638p24207323w@mail.gmail.com> Message-ID: <be4fbf920603031642g1406316du@mail.gmail.com> On 04/03/06, Adam <adam.jtm30 at gmail.com> wrote: > I've got a module that needs to share a pack of cards > > pack = ["14s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", "11s", > "12s", "13s", "14d", "2d", "3d", "4d", "5d", "6d", "7d", "8d", "9d", "10d", > "11d", "12d", "13d", "14c", "2c", "3c", "4c", "5c", "6c", "7c", "8c", "9c", > "10c", "11c", "12c", "13c", "14h", "2h", "3h", "4h", "5h", "6h", "7h", "8h", > "9h", "10h", "11h", "12h", "13h"] > random.shuffle(pack) > > do you think it is worth making a class with just this attribute or > would this be a good place to use a global variable? > I just realised this probably isn't as clear as it should be, sorry it's late. It needs to share the variable with the functions (or methods) in the module not with anything outside of it. From kent37 at tds.net Sat Mar 4 02:20:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Mar 2006 20:20:40 -0500 Subject: [Tutor] One shared object. class attribute or global variable? In-Reply-To: <be4fbf920603031638p24207323w@mail.gmail.com> References: <be4fbf920603031638p24207323w@mail.gmail.com> Message-ID: <4408EB68.2040700@tds.net> Adam wrote: > I've got a module that needs to share a pack of cards > > pack = ["14s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", "11s", > "12s", "13s", "14d", "2d", "3d", "4d", "5d", "6d", "7d", "8d", "9d", "10d", > "11d", "12d", "13d", "14c", "2c", "3c", "4c", "5c", "6c", "7c", "8c", "9c", > "10c", "11c", "12c", "13c", "14h", "2h", "3h", "4h", "5h", "6h", "7h", "8h", > "9h", "10h", "11h", "12h", "13h"] > random.shuffle(pack) > > do you think it is worth making a class with just this attribute or > would this be a good place to use a global variable? Some choices: 1. Pass the pack as a parameter to the functions that need to use it. 2. Make the pack a class attribute, maybe you can have a Game class. The functions that need it are good candidates for class methods. 3. Make pack a global variable I would start with 1. If you have to pass it to a lot of functions, and the functions seem to cohere into a class, then maybe pick 2. The tipping point between 1 and 2 is a judgement call. I almost never use global variables except for constants and in short throwaway scripts. By the way you may find that a Pack class makes sense, too, with methods like shuffle(), deal(howMany), isEmpty(). Kent From python at venix.com Sat Mar 4 02:26:04 2006 From: python at venix.com (Python) Date: Fri, 03 Mar 2006 20:26:04 -0500 Subject: [Tutor] One shared object. class attribute or global variable? In-Reply-To: <be4fbf920603031642g1406316du@mail.gmail.com> References: <be4fbf920603031638p24207323w@mail.gmail.com> <be4fbf920603031642g1406316du@mail.gmail.com> Message-ID: <1141435564.15743.806.camel@www.venix.com> On Sat, 2006-03-04 at 00:42 +0000, Adam wrote: > On 04/03/06, Adam <adam.jtm30 at gmail.com> wrote: > > I've got a module that needs to share a pack of cards > > > > pack = ["14s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", "11s", > > "12s", "13s", "14d", "2d", "3d", "4d", "5d", "6d", "7d", "8d", "9d", "10d", > > "11d", "12d", "13d", "14c", "2c", "3c", "4c", "5c", "6c", "7c", "8c", "9c", > > "10c", "11c", "12c", "13c", "14h", "2h", "3h", "4h", "5h", "6h", "7h", "8h", > > "9h", "10h", "11h", "12h", "13h"] > > random.shuffle(pack) > > > > do you think it is worth making a class with just this attribute or > > would this be a good place to use a global variable? > > > > I just realised this probably isn't as clear as it should be, sorry > it's late. It needs to share the variable with the functions (or > methods) in the module not with anything outside of it. It looks like this will be shared and modified. In general, I think read-only variables (initialized at start-up when not constants) can work OK as globals. A container that will be changed and shared should almost certainly go in a class. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From sudarshana.ks at gmail.com Sat Mar 4 03:47:13 2006 From: sudarshana.ks at gmail.com (Sudarshana KS) Date: Sat, 4 Mar 2006 08:17:13 +0530 Subject: [Tutor] Urgent - Using Threads for processing each single Packet ? Message-ID: <8036f2bb0603031847l11c7ee11g4127088ec53014c4@mail.gmail.com> Hi All, Currently i am planning for writing a tool which gets a webpage and fills the appropriate fields and posts the page back to the server. The problem is that i am using SCAPY for doing http as i need VLAN TAG to be supported to get the HTTP Page. So before starting this i had couple of questions. 1. As we need to establish a TCP session for http to work , do we need to process each packet as a seperate thread ? I am not sure how the system would respond if we have to get 500 webpages - in the sense the total number of tcp connection is around 500 . Could any body tell me what would be best design ? Using each thread for single packet processing is it worth ? 2. Is there any specific tool or any built in APIs which can parse Http part of the packet ? Please help me . Thanks in advance, Sudarshana K S From rakesh.mishra at gmail.com Sat Mar 4 08:00:59 2006 From: rakesh.mishra at gmail.com (Rakesh Mishra) Date: Sat, 4 Mar 2006 07:00:59 +0000 Subject: [Tutor] Tutorial for creating web server In-Reply-To: <44085802.2010401@tds.net> References: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> <44082DEF.3050903@tds.net> <39ce20e10603030640j5c5e7600m3c6ca6610966cb6@mail.gmail.com> <44085802.2010401@tds.net> Message-ID: <39ce20e10603032300h27fdbb5i6bcced8307637452@mail.gmail.com> hi Johnson late me try to explain what I wants... I am not interested in tool which is used to creating the web pages. but I am interested in tool which is used for webcasting the web pages. in contax of Zope....... Apart from creating web pages it has its own web server called as ZServer. which is used by zope internally to web cast the pages. Even you not clear than simply in one word I wanted to built Apache web server in python. I think now you will understand what I want. please help me out . rakesh On 3/3/06, Kent Johnson <kent37 at tds.net> wrote: > > Rakesh Mishra wrote: > > Hi Johnson > > I wanted to create web server some think like similar to ZServer of > zope. > > I wanted to use it for publishing my home page (it is in php), or any > > web application. > > I am confused with arch. > > I still am not sure what you are asking for. Do you want to create > something like Zope? Or do you want to use Zope to create your home > page? If you want to learn Zope you should go to the Zope web site. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060304/3fe40c91/attachment.htm From ryan_gm at sbcglobal.net Sat Mar 4 09:21:56 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Sat, 4 Mar 2006 00:21:56 -0800 (PST) Subject: [Tutor] Iron Python Message-ID: <20060304082156.64125.qmail@web80832.mail.yahoo.com> Hello, i have a question about Iron Python, what exactly does it do? i know its something about .net but i still dont understand exactly what it does, To use it do you still write your scripts in the Python IDLE, or what 0-o, From mail at ozzmosis.com Sat Mar 4 10:19:44 2006 From: mail at ozzmosis.com (andrew clarke) Date: Sat, 4 Mar 2006 20:19:44 +1100 Subject: [Tutor] Iron Python In-Reply-To: <20060304082156.64125.qmail@web80832.mail.yahoo.com> References: <20060304082156.64125.qmail@web80832.mail.yahoo.com> Message-ID: <20060304091944.GA712@ozzmosis.com> On Sat, Mar 04, 2006 at 12:21:56AM -0800, ryan luna wrote: > Hello, i have a question about Iron Python, what exactly does it do? > i know its something about .net but i still dont understand exactly > what it does, To use it do you still write your scripts in the Python > IDLE, or what 0-o, It's Microsoft's version of Python (written in C#) that runs on top of the .NET Framework, so it can generate .exe files for .NET, among other things. A short demo: D:\devel\IronPython>IronPythonConsole.exe IronPython 1.0.2237 (Beta) on .NET 2.0.50727.42 Copyright (c) Microsoft Corporation. All rights reserved. >>> print "Hello world." Hello world. >>> ^Z D:\devel\IronPython>type hello.py print "Hello world." D:\devel\IronPython>IronPythonConsole.exe hello.py Hello world. D:\devel\IronPython>IronPythonConsole.exe -O -X:SaveAssemblies hello.py Hello world. D:\devel\IronPython>dir hello.exe Directory of D:\devel\IronPython 2006-03-04 20:16 3,072 hello.exe D:\devel\IronPython>hello.exe Hello world. Regards Anderw From ryan_gm at sbcglobal.net Sat Mar 4 10:37:24 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Sat, 4 Mar 2006 01:37:24 -0800 (PST) Subject: [Tutor] Pyexe Message-ID: <20060304093724.70507.qmail@web80827.mail.yahoo.com> Hello, Call me a complete n00b but i dont understand how to get Pyexe to work, Iv read the site and kinda just confuses me, as you can prolly tell im still pretty new to programming, What exactly do i have to do with pyexe to make python scripts exacutables. From narm at go.com.jo Sat Mar 4 10:19:51 2006 From: narm at go.com.jo (Basem Narmok) Date: Sat, 04 Mar 2006 11:19:51 +0200 Subject: [Tutor] Iron Python Message-ID: <44095BB7.4010103@go.com.jo> ryan luna wrote: > Hello, i have a question about Iron Python, what > exactly does it do? i know its something about .net > but i still dont understand exactly what it does, To > use it do you still write your scripts in the Python > IDLE, or what 0-o, > Hi Ryan, http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20051110PythonJH/manifest.xml Have fun Basem Narmok From ml.cyresse at gmail.com Sat Mar 4 12:08:10 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 5 Mar 2006 00:08:10 +1300 Subject: [Tutor] Urgent - Using Threads for processing each single Packet ? In-Reply-To: <8036f2bb0603031847l11c7ee11g4127088ec53014c4@mail.gmail.com> References: <8036f2bb0603031847l11c7ee11g4127088ec53014c4@mail.gmail.com> Message-ID: <b6f3249e0603040308k79ea404evb8cf6e79f0a5b381@mail.gmail.com> Hi Sudarshana, Out of curiosity, what are you building that requires you post 500 pages to a server at once? I apologise if the question is intrusive, but I can think of a few appns that involve that, and none of them are good. Regards, Liam Clarke On 3/4/06, Sudarshana KS <sudarshana.ks at gmail.com> wrote: > Hi All, > > Currently i am planning for writing a tool which gets a webpage and > fills the appropriate fields and posts the page back to the server. > The problem is that i am using SCAPY for doing http as i need VLAN TAG > to be supported to get the HTTP Page. > > So before starting this i had couple of questions. > > 1. As we need to establish a TCP session for http to work , do we need > to process each packet as a seperate thread ? I am not sure how the > system would respond if we have to get 500 webpages - in the sense the > total number of tcp connection is around 500 . Could any body tell me > what would be best design ? Using each thread for single packet > processing is it worth ? > > 2. Is there any specific tool or any built in APIs which can parse > Http part of the packet ? > > Please help me . > Thanks in advance, > > Sudarshana K S > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Sat Mar 4 12:16:01 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 5 Mar 2006 00:16:01 +1300 Subject: [Tutor] Pyexe In-Reply-To: <20060304093724.70507.qmail@web80827.mail.yahoo.com> References: <20060304093724.70507.qmail@web80827.mail.yahoo.com> Message-ID: <b6f3249e0603040316lea3643ev3afc2b2967f9cfb7@mail.gmail.com> Hi Ryan, It took me about a year to cotton onto it as well. So, I wrote a script for my friend, and wanted to send it as an exe. The script I wrote was called disco_spider.py. I assume you've installed py2exe? What I then had to do was create another Python script called setup.py in the same directory as disco_spider.py, this is what setup.py looks like: from distutils.core import setup import py2exe setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "0.5.0", description = "Custom built copier of things.", name = "Disco Spider", # targets to build console = ["disco_spider.py"] ) After that, I open up a DOS prompt, and go to the directory disco_spider.py and setup.py are in and I type: python setup.py py2exe at the command prompt. This runs py2exe, which, if everything goes well, creates a subfolder called dist. Everything in dist is what you need to distribute your script. Good luck, Liam Clarke On 3/4/06, ryan luna <ryan_gm at sbcglobal.net> wrote: > Hello, Call me a complete n00b but i dont understand > how to get Pyexe to work, > Iv read the site and kinda just confuses me, as you > can prolly tell im still pretty new to programming, > What exactly do i have to do with pyexe to make python > scripts exacutables. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ryan_gm at sbcglobal.net Sat Mar 4 12:31:16 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Sat, 4 Mar 2006 03:31:16 -0800 (PST) Subject: [Tutor] Editing Pickled .dat files Message-ID: <20060304113116.78977.qmail@web80824.mail.yahoo.com> Hello, this is like my 3rd question today lol which is making up for not asking any for months =P, anyways I have a pickled .dat file named dictionary, maybe youv guessed this but its a dictionary of the Alphabet, the program is a translator right now all it does is translate the Alpabet (its a stupid made up language helping someone out cuz i needed a project) anyways im pretty sure i have the reading the pickled file, taking input from the user, looking on the word in the .dat file and printing out the translation, Here is where im stuck. I want the program to be able to translate full words to (the only way i know to do that is to put every word in the dictionary, aka .dat file) im not goin to put all the english words and there translation in there myself! so i have a option for the user to put there own definitions, What i need to know is how do i take input from the user, collect the word and its definitions and then pickle it into the .dat but editing the dictionary in the .dat file. heres my code for reading so you get a better idea of what i mean pickle_file = open("dictionary.dat", "r") dictionary = cPickle.load(pickle_file) while sentence != "0": sentence = raw_input("\nInput a english letter/word to be translated: ") if sentence in dictionary: definition = dictionary[sentence] print "\n", definition From kent37 at tds.net Sat Mar 4 13:12:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Mar 2006 07:12:31 -0500 Subject: [Tutor] Tutorial for creating web server In-Reply-To: <39ce20e10603032300h27fdbb5i6bcced8307637452@mail.gmail.com> References: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> <44082DEF.3050903@tds.net> <39ce20e10603030640j5c5e7600m3c6ca6610966cb6@mail.gmail.com> <44085802.2010401@tds.net> <39ce20e10603032300h27fdbb5i6bcced8307637452@mail.gmail.com> Message-ID: <4409842F.6080705@tds.net> Rakesh Mishra wrote: > Even you not clear than simply in one word I wanted to built Apache web > server in python. If you really want to write Apache from scratch in Python you have a lot of learning and a lot of work to do. A good starting point might be the book Foundations of Python Network Programming. http://apress.com/book/bookDisplay.html?bID=363 You will also need to understand HTTP protocol, I'm sure Google can help there. The reference for HTTP is RFC 2068: http://www.freesoft.org/CIE/RFC/2068/index.htm But why do you want to do this? There are several excellent Python webservers available. If your goal is to create a home page, this is the hard way to do it. Kent From ml.cyresse at gmail.com Sat Mar 4 14:19:49 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 5 Mar 2006 02:19:49 +1300 Subject: [Tutor] Editing Pickled .dat files In-Reply-To: <20060304113116.78977.qmail@web80824.mail.yahoo.com> References: <20060304113116.78977.qmail@web80824.mail.yahoo.com> Message-ID: <b6f3249e0603040519i2c1b07f0qf96a607d0a02b4d6@mail.gmail.com> Hi Ryan, Technically, you don't. You haul your dictionary out, as you're doing here - dictionary = cPickle.load(pickle_file) And when you're finished, you pickle it again. Regards, Liam Clarke On 3/5/06, ryan luna <ryan_gm at sbcglobal.net> wrote: > Hello, this is like my 3rd question today lol which is > making up for not asking any for months =P, anyways > I have a pickled .dat file named dictionary, maybe > youv guessed this but its a dictionary of the > Alphabet, the program is a translator right now all it > does is translate the Alpabet (its a stupid made up > language helping someone out cuz i needed a project) > anyways im pretty sure i have the reading the pickled > file, taking input from the user, looking on the word > in the .dat file and printing out the translation, > Here is where im stuck. > I want the program to be able to translate full words > to (the only way i know to do that is to put every > word in the dictionary, aka .dat file) > im not goin to put all the english words and there > translation in there myself! so i have a option for > the user to put there own definitions, > What i need to know is how do i take input from the > user, collect the word and its definitions and then > pickle it into the .dat but editing the dictionary in > the .dat file. > heres my code for reading so you get a better idea of > what i mean > > pickle_file = open("dictionary.dat", "r") > dictionary = cPickle.load(pickle_file) > while sentence != "0": > sentence = raw_input("\nInput a english > letter/word to be translated: ") > if sentence in dictionary: > definition = dictionary[sentence] > print "\n", definition > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Mar 4 14:21:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 4 Mar 2006 13:21:03 -0000 Subject: [Tutor] One shared object. class attribute or global variable? References: <be4fbf920603031638p24207323w@mail.gmail.com> Message-ID: <01ea01c63f8e$7ccf1590$0b01a8c0@xp> > I've got a module that needs to share a pack of cards > > pack = ["14s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", > "11s", > ... > random.shuffle(pack) > > do you think it is worth making a class with just this attribute > or would this be a good place to use a global variable? Classes with single attributes are almost never the right thing. The question is what does the class *do*? What are its responsibilities within the application? You've already suggested that it could shuffle itself. Maybe it could deal a random card too? Maybe it could tell you something about how many cards are left? Or whether a particular card is in the pack? In that case creating a class makers sense. Classes without behaviour are rarely useful. Data without fiunction is rare. Data and function is a class. So if its only a bit of data themn sure make it a module level variable. But ifd you are writing functions that operate on that data consider makng it a class. Particul;arly if there could ever arise the need for more than one pack - a game of Spider or Cribbage for example? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Mar 4 14:28:57 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 4 Mar 2006 13:28:57 -0000 Subject: [Tutor] Pyexe References: <20060304093724.70507.qmail@web80827.mail.yahoo.com> Message-ID: <020401c63f8f$975dadd0$0b01a8c0@xp> > Hello, Call me a complete n00b but i dont understand > how to get Pyexe to work, That's probably because py2exe isn't really aimed at beginners. Its moderately complex to use. That's because most programmers don't need it. > Iv read the site and kinda just confuses me, as you > can prolly tell im still pretty new to programming, > What exactly do i have to do with pyexe to make python > scripts exacutables. To make a script executable you just need to make it readable and then double click on it./ Windows will find the python interpreter and execute the script for you. No need for py2exe. You only need py2exe if you really need to create a standalone exe file that yoiu can distribute without the need for python to be installed. The result will be a largish file incorporating the python interpreter and all your modules in a single file. If you really need that then you will need to tell us what you are doing with py2exe, where it seems to be going wrong and then someone can provide an answer... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ryan_gm at sbcglobal.net Sat Mar 4 14:28:50 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Sat, 4 Mar 2006 05:28:50 -0800 (PST) Subject: [Tutor] Editing Pickled .dat files In-Reply-To: <b6f3249e0603040519i2c1b07f0qf96a607d0a02b4d6@mail.gmail.com> Message-ID: <20060304132850.78803.qmail@web80806.mail.yahoo.com> Hey, thanks for the help but when i try i get a error Bad file descripter, here is the code im using elif choice == "2": pickle_file = open("dictionary.dat", "a") sentence = raw_input("Enter the word youd like to add: ") if sentence not in pickle_file: definition = raw_input("Whats the translated version: ") pickle_file[sentence] = definition print "\n\t'",sentence,"'", "Has been added to the dictionary." else: print "\n\tThat term already exists!" --- Liam Clarke <ml.cyresse at gmail.com> wrote: > Hi Ryan, > > Technically, you don't. > > You haul your dictionary out, as you're doing here - > > dictionary = cPickle.load(pickle_file) > > And when you're finished, you pickle it again. > > Regards, > > Liam Clarke > > On 3/5/06, ryan luna <ryan_gm at sbcglobal.net> wrote: > > Hello, this is like my 3rd question today lol > which is > > making up for not asking any for months =P, > anyways > > I have a pickled .dat file named dictionary, maybe > > youv guessed this but its a dictionary of the > > Alphabet, the program is a translator right now > all it > > does is translate the Alpabet (its a stupid made > up > > language helping someone out cuz i needed a > project) > > anyways im pretty sure i have the reading the > pickled > > file, taking input from the user, looking on the > word > > in the .dat file and printing out the translation, > > Here is where im stuck. > > I want the program to be able to translate full > words > > to (the only way i know to do that is to put every > > word in the dictionary, aka .dat file) > > im not goin to put all the english words and there > > translation in there myself! so i have a option > for > > the user to put there own definitions, > > What i need to know is how do i take input from > the > > user, collect the word and its definitions and > then > > pickle it into the .dat but editing the dictionary > in > > the .dat file. > > heres my code for reading so you get a better idea > of > > what i mean > > > > pickle_file = open("dictionary.dat", "r") > > dictionary = cPickle.load(pickle_file) > > while sentence != "0": > > sentence = raw_input("\nInput a > english > > letter/word to be translated: ") > > if sentence in dictionary: > > definition = dictionary[sentence] > > print "\n", definition > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From ml.cyresse at gmail.com Sat Mar 4 14:39:54 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 5 Mar 2006 02:39:54 +1300 Subject: [Tutor] Editing Pickled .dat files In-Reply-To: <20060304132850.78803.qmail@web80806.mail.yahoo.com> References: <b6f3249e0603040519i2c1b07f0qf96a607d0a02b4d6@mail.gmail.com> <20060304132850.78803.qmail@web80806.mail.yahoo.com> Message-ID: <b6f3249e0603040539t1870c624jca0d7c63ed11038@mail.gmail.com> Hi Ryan, You're trying to use your file, dictionary.dat like a dictionary data structure in Python. They don't work the same way. So. pickle_file = open("dictionary.dat", "r") dictionary = cPickle.load(pickle_file) pickle_file.close() elif choice == "2": pickle_file = open("dictionary.dat", "a") sentence = raw_input("Enter the word youd like to add: ") if sentence not in dictionary: definition = raw_input("Whats the translated version: ") dictionary[sentence] = definition print "\n\t'",sentence,"'", "Has been added to the dictionary." else: print "\n\tThat term already exists!" Once you're done, you just "repickle" the dictionary. pickle_file = open("dictionary.dat", "w") #Opened in write mode cPickle.dump(dictionary, pickle_file) pickle_file.close() Regards, Liam Clarke From ryan_gm at sbcglobal.net Sat Mar 4 14:51:17 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Sat, 4 Mar 2006 05:51:17 -0800 (PST) Subject: [Tutor] Editing Pickled .dat files In-Reply-To: <b6f3249e0603040539t1870c624jca0d7c63ed11038@mail.gmail.com> Message-ID: <20060304135117.94276.qmail@web80823.mail.yahoo.com> Ohhh ok i got it to work! but why isn't the change permanent? it is "writing" to the file isn't it. --- Liam Clarke <ml.cyresse at gmail.com> wrote: > Hi Ryan, > > You're trying to use your file, dictionary.dat like > a dictionary data > structure in Python. > They don't work the same way. > > So. > > pickle_file = open("dictionary.dat", "r") > dictionary = cPickle.load(pickle_file) > pickle_file.close() > > elif choice == "2": > pickle_file = open("dictionary.dat", "a") > sentence = raw_input("Enter the word youd > like to add: ") > if sentence not in dictionary: > definition = raw_input("Whats the > translated version: ") > dictionary[sentence] = definition > print "\n\t'",sentence,"'", "Has been > added to the dictionary." > else: > print "\n\tThat term already exists!" > > > Once you're done, you just "repickle" the > dictionary. > > pickle_file = open("dictionary.dat", "w") #Opened in > write mode > cPickle.dump(dictionary, pickle_file) > pickle_file.close() > > Regards, > > Liam Clarke > From seedseven at home.nl Sat Mar 4 16:22:47 2006 From: seedseven at home.nl (Ingo) Date: Sat, 04 Mar 2006 16:22:47 +0100 Subject: [Tutor] how to get the return value? References: <200603041556580171.014367A0@mail.home.nl> Message-ID: <200603041622470562.015B0BEE@mail.home.nl> To make a time lapse video I've been playing with the sched module. There is one problem I run into, in the code below, how do I get the returned value t from printtime into main? import time from sched import scheduler class time_lapse(scheduler): def time_lapse(self, start_time, stop_time, interval, priority, action, argument): def lapse(): action(*argument) i=self.enter(interval, priority, lapse, ()) if stop_time: if stop_time<self.timefunc(): self.cancel(i) self.enterabs(start_time, priority, lapse, ()) def printtime(strf=None): t=time.time() if strf: print time.strftime("%Y%m%d_%H%M%S") else: print time.localtime() return t def main(): schedule = time_lapse(time.time, time.sleep) start=time.time() stop=list(time.localtime(start)) stop[3]=stop[3]+2 stop=time.mktime(stop) #schedule.time_lapse(None,None,5,1,printtime,()) #start now, run forever schedule.time_lapse(start,stop,7,0,printtime,(1,)) schedule.run() if __name__ == "__main__": main() Ingo From annaraven at gmail.com Sat Mar 4 18:49:31 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Sat, 4 Mar 2006 09:49:31 -0800 Subject: [Tutor] how to get the return value? In-Reply-To: <200603041622470562.015B0BEE@mail.home.nl> References: <200603041556580171.014367A0@mail.home.nl> <200603041622470562.015B0BEE@mail.home.nl> Message-ID: <cb361a610603040949m6a2dff0anf52b3075ee327f4e@mail.gmail.com> On 3/4/06, Ingo <seedseven at home.nl> wrote: > > To make a time lapse video I've been playing with the sched module. > There is one problem I run into, in the code below, how do I get the > returned value t from printtime into main? > > > import time > from sched import scheduler > > class time_lapse(scheduler): > > def time_lapse(self, start_time, stop_time, interval, priority, > action, argument): > def lapse(): > action(*argument) > i=self.enter(interval, priority, lapse, ()) > if stop_time: > if stop_time<self.timefunc(): > self.cancel(i) > self.enterabs(start_time, priority, lapse, ()) > > def printtime(strf=None): > t=time.time() > if strf: > print time.strftime("%Y%m%d_%H%M%S") > else: > print time.localtime() > return t > > def main(): > schedule = time_lapse(time.time, time.sleep) > start=time.time() > stop=list(time.localtime(start)) > stop[3]=stop[3]+2 > stop=time.mktime(stop) > > #schedule.time_lapse(None,None,5,1,printtime,()) #start now, run > forever > schedule.time_lapse(start,stop,7,0,printtime,(1,)) > > schedule.run() > > > if __name__ == "__main__": > main() > > > Ingo > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > main(printtime(strf=None)) should do it. Alternately: tt = printtime(strf=None) main(tt) Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060304/5d4d4a70/attachment.htm From wescpy at gmail.com Sat Mar 4 22:43:03 2006 From: wescpy at gmail.com (w chun) Date: Sat, 4 Mar 2006 13:43:03 -0800 Subject: [Tutor] Tutorial for creating web server In-Reply-To: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> References: <39ce20e10603022022x6668f171r35c81c1757547b76@mail.gmail.com> Message-ID: <78b3a9580603041343r5a703a4cv8c1bef857daec54d@mail.gmail.com> > i wanted to create my own web server, can any body suggest any tutorial, > by the way i have gone through book Core Python Programing, in this book > one example is given but it is to abstract, that i am unable to understand rakesh, 1) based on this thread and responses from various folks, it sounds like you are only interested in publishing your home page (currently in PHP). if you have just static web pages (no CGI, etc.), then you do not need anything nearly as powerful as the Zope webserver nor Apache. Python's generic webservers are good enough for this, and you don't even have to know Python to run them. 2) which example in Core Python confuses you? i'll assume it's Example 19.7. this example is really only necessary if you want to start writing a full-fledged server (similar to the ones already mentioned). if you want to just serve web pages (and even process CGI), here's a webserver for you that you should understand: from CGIHTTPServer import test;test() put this code into a script... say webserver.py and put it into the same directory or folder as your .HTML files. then run "python webserver.py". you should then be able to access your web pages by surfing to http://localhost:8000/myWebPage.html (or whatever it's called). i think that i'll add an example like this to the book too, in case there are others that want to just serve pages and perhaps practice their CGI skills. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ryan_gm at sbcglobal.net Sun Mar 5 02:54:28 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Sat, 4 Mar 2006 17:54:28 -0800 (PST) Subject: [Tutor] Delete in .dat Message-ID: <20060305015428.3971.qmail@web80831.mail.yahoo.com> My question seems like itd be farly simple but i cant seem to get it to work, My .dat file is a dictionary and i need to be able to only delete a single word and its definition, heres what i have so far but it doesn't work. pickle_file = open("dictionary.dat", "r") dictionary = cPickle.load(pickle_file) pickle_file.close() sentence = raw_input("What definition would you like to delete?: ") if sentence in dictionary: del dictionary[sentence] print "\n\t", sentence, "Has been removed" else: print "\n\t", sentence, "That word is not in the dictionary" pickle_file = open("dictionary.dat", "w") cPickle.dump(dictionary, pickle_file) pickle_file.close() From dyoo at hkn.eecs.berkeley.edu Sun Mar 5 05:19:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 4 Mar 2006 20:19:32 -0800 (PST) Subject: [Tutor] Delete in .dat In-Reply-To: <20060305015428.3971.qmail@web80831.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0603042014160.537-100000@hkn.eecs.berkeley.edu> On Sat, 4 Mar 2006, ryan luna wrote: > My question seems like itd be farly simple but i cant seem to get it to > work, My .dat file is a dictionary and i need to be able to only delete > a single word and its definition, heres what i have so far but it > doesn't work. Hi Ryan, By "doesn't work", what happens? Do you get an error message, or ...? The more details here the better, since we really are not sure what the cause of the problem is yet. > pickle_file = open("dictionary.dat", "r") ^^^ This looks somewhat suspicious. pickle files are meant to be stored in binary files, so you may need to open the file in binary mode: pickle_file = open("dictionary.dat", "rb") Otherwise, bad things may happen, especially on Windows platforms. Good luck to you! From seedseven at home.nl Sun Mar 5 19:07:11 2006 From: seedseven at home.nl (Ingo) Date: Sun, 05 Mar 2006 19:07:11 +0100 Subject: [Tutor] how to get the return value? In-Reply-To: <cb361a610603040949m6a2dff0anf52b3075ee327f4e@mail.gmail.com> References: <200603041556580171.014367A0@mail.home.nl> <200603041622470562.015B0BEE@mail.home.nl> <cb361a610603040949m6a2dff0anf52b3075ee327f4e@mail.gmail.com> Message-ID: <200603051907110937.0021F607@mail.home.nl> On 2006/3/04, Anna Ravenscroft wrote: >>[...] > >main(printtime(strf=None)) > >should do it. Alternately: > >tt = printtime(strf=None) >main(tt) > Anna, that results in an syntax error / invalid syntax Ingo From kent37 at tds.net Sun Mar 5 19:17:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Mar 2006 13:17:34 -0500 Subject: [Tutor] how to get the return value? In-Reply-To: <200603051907110937.0021F607@mail.home.nl> References: <200603041556580171.014367A0@mail.home.nl> <200603041622470562.015B0BEE@mail.home.nl> <cb361a610603040949m6a2dff0anf52b3075ee327f4e@mail.gmail.com> <200603051907110937.0021F607@mail.home.nl> Message-ID: <440B2B3E.6070407@tds.net> Ingo wrote: > On 2006/3/04, Anna Ravenscroft wrote: > > >>>[...] >> >>main(printtime(strf=None)) >> >>should do it. Alternately: >> >>tt = printtime(strf=None) >>main(tt) >> > > > Anna, > > that results in an syntax error / invalid syntax It's very helpful to show the actual error and traceback. Kent From ingoogni at CUT.THIS.OUT.home.nl Sun Mar 5 20:02:03 2006 From: ingoogni at CUT.THIS.OUT.home.nl (ingo) Date: Sun, 5 Mar 2006 19:02:03 +0000 (UTC) Subject: [Tutor] how to get the return value? References: <200603051907110937.0021F607@mail.home.nl> <440B2B3E.6070407@tds.net> Message-ID: <Xns977DCBCBBC4CEseed7@sea.gmane.org> in news:440B2B3E.6070407 at tds.net Kent Johnson wrote: >>>>[...] >>> >>>main(printtime(strf=None)) >>> >>>[...] >> >> Anna, >> >> that results in an syntax error / invalid syntax > > It's very helpful to show the actual error and traceback. > Sorry, here it is: File "D:\Ingo\PyScript\VIDEOC~1.9\_ij\_time_lapse.py", line 23 def main(printtime(strf=None)): ^ SyntaxError: invalid syntax Ingo From seedseven at home.nl Sun Mar 5 20:05:07 2006 From: seedseven at home.nl (Ingo) Date: Sun, 05 Mar 2006 20:05:07 +0100 Subject: [Tutor] how to get the return value? In-Reply-To: <440B2B3E.6070407@tds.net> References: <200603041556580171.014367A0@mail.home.nl> <200603041622470562.015B0BEE@mail.home.nl> <cb361a610603040949m6a2dff0anf52b3075ee327f4e@mail.gmail.com> <200603051907110937.0021F607@mail.home.nl> <440B2B3E.6070407@tds.net> Message-ID: <200603052005070984.00570056@mail.home.nl> On 2006/3/05, Kent Johnson wrote: >> >>>>[...] >>> >>>main(printtime(strf=None)) >>> >>>should do it. Alternately: >>> >>>tt = printtime(strf=None) >>>main(tt) >> >> that results in an syntax error / invalid syntax > >It's very helpful to show the actual error and traceback. Sorry, here it is File "D:\Ingo\PyScript\VIDEOC~1.9\_ij\_time_lapse.py", line 23 def main(printtime(strf=None)): ^ SyntaxError: invalid syntax Ingo From dyoo at hkn.eecs.berkeley.edu Sun Mar 5 21:32:24 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 5 Mar 2006 12:32:24 -0800 (PST) Subject: [Tutor] how to get the return value? In-Reply-To: <Xns977DCBCBBC4CEseed7@sea.gmane.org> Message-ID: <Pine.LNX.4.44.0603051201420.16631-100000@hkn.eecs.berkeley.edu> Hi Ingo, I'm coming into this thread a little late, but looking at your original program: http://mail.python.org/pipermail/tutor/2006-March/045505.html you may want to adjust your schedule function a bit to capture return values. As far as I can tell, the code throws them away when it calls action(). ################################################################### class time_lapse(scheduler): def time_lapse(self, start_time, stop_time, interval, priority, action, argument): def lapse(): action(*argument) i=self.enter(interval, priority, lapse, ()) if stop_time: if stop_time<self.timefunc(): self.cancel(i) self.enterabs(start_time, priority, lapse, ()) ################################################################### But since the scheduler runs in a separate loop than the rest of your program, trying to return a value between the two won't work very well. However, there are other approaches: we can use some kind of shared container or communication channel between the main() and the scheduler, so that they can communicate. One possible way they can communicate is with a shared Queue: http://www.python.org/doc/lib/module-Queue.html Here is an example that may help: ###################################################################### from sched import scheduler import time from Queue import Queue from threading import Thread s = scheduler(time.time, time.sleep) q = Queue() PRIORITY = 1 def f(n): """Pushes n into the queue, and then reschedules itself with n+1 to run five seconds later""" q.put(n) s.enter(5, PRIORITY, f, (n+1,)) ## Let's prime things up. We'll set up the scheduler, and then have ## it run on its own daemon thread. s.enter(5, PRIORITY, f, (0,)) t = Thread(target=s.run) t.setDaemon(True) t.start() ## At this point, our main thread of execution is separate from the ## scheduler thread t. while True: print "Waiting for event on queue." print q.get() ###################################################################### Does this make sense? From alan.gauld at freenet.co.uk Sun Mar 5 23:58:35 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 5 Mar 2006 22:58:35 -0000 Subject: [Tutor] how to get the return value? References: <200603041556580171.014367A0@mail.home.nl> <200603041622470562.015B0BEE@mail.home.nl> Message-ID: <001d01c640a8$55b8dde0$0b01a8c0@xp> > To make a time lapse video I've been playing with the sched module. > There is one problem I run into, in the code below, how do I get the > returned value t from printtime into main? This is one place where you really are best to use a global variable IMHO. There are some clever tricks using classes and so on but its really much simpler to just define a global which is visible to both main and printtime() > import time > from sched import scheduler > > class time_lapse(scheduler): > def time_lapse(self, start_time, stop_time, interval, priority, > action, argument): > def lapse(): > action(*argument) One possible alternative is to store the return value gere as an attribute. Then main can query the object. > def printtime(strf=None): > t=time.time() > if strf: > print time.strftime("%Y%m%d_%H%M%S") > else: > print time.localtime() > return t I'd keep t as a local but assign the final value to a global with a clear and unambiguous name. > def main(): > schedule = time_lapse(time.time, time.sleep) > start=time.time() > stop=list(time.localtime(start)) > stop[3]=stop[3]+2 > stop=time.mktime(stop) > > schedule.time_lapse(start,stop,7,0,printtime,(1,)) > > schedule.run() However the real question I have is how you intend to access that result value. Is it a single value at the end you want or the cumulative set of values from each scheduled call? Alan G. From bgailer at alum.rpi.edu Mon Mar 6 00:01:50 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 05 Mar 2006 15:01:50 -0800 Subject: [Tutor] Delete in .dat In-Reply-To: <20060305015428.3971.qmail@web80831.mail.yahoo.com> References: <20060305015428.3971.qmail@web80831.mail.yahoo.com> Message-ID: <440B6DDE.8090508@alum.rpi.edu> ryan luna wrote: > My question seems like itd be farly simple but i cant > seem to get it to work, > My .dat file is a dictionary and i need to be able to > only delete a single word and its definition, > heres what i have so far but it doesn't work. > AARHG! I am always frustrated by "it doesn't work" This gives us insufficient information. Please always present us with the specific diagnostic. "it doesn't work" ... Could mean del raises an exception.. ... Could mean that the key is still in the dictionary after the del. ... Could mean that the key is still in the dictionary after you pickle dump then open load. ... Could mean you see "...Has been removed" ... Could mean you see "...That word is not in the dictionary"" More information, please. > pickle_file = open("dictionary.dat", "r") > > dictionary = cPickle.load(pickle_file) > pickle_file.close() > sentence = raw_input("What definition would > you like to delete?: ") > if sentence in dictionary: > del dictionary[sentence] > print "\n\t", sentence, "Has been removed" > else: > print "\n\t", sentence, "That word is not > in the dictionary" > pickle_file = open("dictionary.dat", "w") > cPickle.dump(dictionary, pickle_file) > pickle_file.close() > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From annaraven at gmail.com Mon Mar 6 02:05:14 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Sun, 5 Mar 2006 17:05:14 -0800 Subject: [Tutor] how to get the return value? In-Reply-To: <Xns977DCBCBBC4CEseed7@sea.gmane.org> References: <200603051907110937.0021F607@mail.home.nl> <440B2B3E.6070407@tds.net> <Xns977DCBCBBC4CEseed7@sea.gmane.org> Message-ID: <cb361a610603051705u631b213l83250f3f75304661@mail.gmail.com> On 3/5/06, ingo <ingoogni at cut.this.out.home.nl> wrote: > > in news:440B2B3E.6070407 at tds.net Kent Johnson wrote: > >>>>[...] > >>> > >>>main(printtime(strf=None)) > >>> > >>>[...] > >> > >> Anna, > >> > >> that results in an syntax error / invalid syntax > > > > It's very helpful to show the actual error and traceback. > > > > Sorry, here it is: > > File "D:\Ingo\PyScript\VIDEOC~1.9\_ij\_time_lapse.py", line 23 > def main(printtime(strf=None)): > ^ > SyntaxError: invalid syntax Yep. I was suggesting calling printtime as part of your *call* to main, not when you define main. Sorry to be unclear. It appeared from your code that you never bound printtime to a variable name when you called it (in fact, I don't remember you ever actually *calling* it but I may be misremembering.) If it's not bound to a variable name, the function does its work and the return value just disappears into the ether. So - to capture the return value, bind the function call to a variable name. Or, alternately, pass the function call directly as the argument for the function, in your case main(), that wants to use the return value, such as: main(printtime(strf=None)) Note that, when you define main in the first place, you'll need to ensure that it takes a parameter like: def main(pt): dosomethingwith pt so that when you later call main(), you can pass it an argument like primetime() or whatever variable name you bound primetime()'s return value to. Hope that makes more sense. Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060305/b2f9e565/attachment.htm From r.arunchand at gmail.com Mon Mar 6 10:16:36 2006 From: r.arunchand at gmail.com (arun) Date: Mon, 6 Mar 2006 14:46:36 +0530 Subject: [Tutor] saving .csv file as an xl worksheet Message-ID: <8e82677d0603060116l419b06b6h4d60e5ef44062931@mail.gmail.com> Hi , Can i save a file with a desired extension?? for ex: I have a .csv file (test.csv) and i want to save this file as test.xls from a python script. Thanx in advance ac -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060306/43aa1999/attachment.html From samrobertsmith at gmail.com Mon Mar 6 11:33:08 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 6 Mar 2006 02:33:08 -0800 Subject: [Tutor] source file or installer Message-ID: <1d987df30603060233t637b0082l3999aef798e361a7@mail.gmail.com> what are the benefits of building python from source file? any difference if using installer? Linda From hameed.u.khan at gmail.com Mon Mar 6 13:15:31 2006 From: hameed.u.khan at gmail.com (Hameed U. Khan) Date: Mon, 6 Mar 2006 17:15:31 +0500 Subject: [Tutor] after signal handler Message-ID: <70576bd20603060415j16b9c7c0l9c325f3bdf02d87@mail.gmail.com> Hi, I want to go back after signal handler to the isntruction where I was stuck. Below is the code I'm trying to play with. #!/usr/bin/env python ### Start of code ### import os, signal def handler(signum, frame): print "Signum: ", signum return signal.signal(signal.SIGALRM,handler) signal.alarm(2) # I want to come back here after signal handler raw_input("Enter input: ") signal.alarm(0) # End of code What I'm trying to do is to implement a prompt with the remaining time they have to enter some input. -- Hameed U. Khan Registered Linux User #: 354374 From seedseven at home.nl Mon Mar 6 13:36:20 2006 From: seedseven at home.nl (seedseven at home.nl) Date: Mon, 6 Mar 2006 13:36:20 +0100 Subject: [Tutor] how to get the return value? Message-ID: <30792784.1141648580515.JavaMail.root@webmail1.groni1> ---- Alan Gauld <alan.gauld at freenet.co.uk> schrijft: > However the real question I have is how you intend to > access that result value. Is it a single value at the end > you want or the cumulative set of values from each > scheduled call? :) Alan, Currently I'm not quite sure what and how I want to do it, so far I've been poking around a bit in the std library to see what options there are to create a sceduling script. Finaly I'd like to be able to have a program do the following, using a "simple" ini_file: for every workingday of a week: from 7.00 until 17.00: every minute: capture a frame and save it at noon: compile a video from the frames gathered this morning do some file manipulations at 17.00: compile a video from the frames gathered this afternoon do some file manipulations on friday 17.00: compile a movie from a selection ( every n_th) of the frames of this week ... The time_lapse function was a first attempt in creating something that starts and stops at a certain time and triggers some actions inbetween. Then I thougth I could use it as the main loop that triggers all the other actions, but then I have to able to change the start and stop times for these from the intial time_lapse loop. Looking at Danny's code, I think a threaded sheduler + shared qeue would be a better approach, but that's something completly new to me. Thanks, Ingo From seedseven at home.nl Mon Mar 6 13:20:40 2006 From: seedseven at home.nl (seedseven at home.nl) Date: Mon, 6 Mar 2006 13:20:40 +0100 Subject: [Tutor] how to get the return value? Message-ID: <49658.1141647640288.JavaMail.root@webmail1.groni1> ---- Anna Ravenscroft <annaraven at gmail.com> schrijft: > On 3/5/06, ingo <ingoogni at cut.this.out.home.nl> wrote: > > > > in news:440B2B3E.6070407 at tds.net Kent Johnson wrote: > > >>>>[...] > > >>> > > >>>main(printtime(strf=None)) > > >>> > > >>>[...] > > >> > > >> Anna, > > >> > > >> that results in an syntax error / invalid syntax > > > > > > It's very helpful to show the actual error and traceback. > > > > > > > Sorry, here it is: > > > > File "D:\Ingo\PyScript\VIDEOC~1.9\_ij\_time_lapse.py", line 23 > > def main(printtime(strf=None)): > > ^ > > SyntaxError: invalid syntax > > > > Yep. I was suggesting calling printtime as part of your *call* to main, not > when you define main. Sorry to be unclear. >[...] > Hope that makes more sense. > Ah, that makes more sense, I'll play a bit with it, Thanks, Ingo From seedseven at home.nl Mon Mar 6 13:24:03 2006 From: seedseven at home.nl (seedseven at home.nl) Date: Mon, 6 Mar 2006 13:24:03 +0100 Subject: [Tutor] how to get the return value? Message-ID: <28653889.1141647843426.JavaMail.root@webmail1.groni1> ---- Danny Yoo <dyoo at hkn.eecs.berkeley.edu> schrijft: > But since the scheduler runs in a separate loop than the rest of your > program, trying to return a value between the two won't work very well. > > > However, there are other approaches: we can use some kind of shared > container or communication channel between the main() and the scheduler, > so that they can communicate. > > > One possible way they can communicate is with a shared Queue: > > http://www.python.org/doc/lib/module-Queue.html > > Here is an example that may help: > > ###################################################################### > from sched import scheduler > import time > from Queue import Queue > from threading import Thread > > > s = scheduler(time.time, time.sleep) > q = Queue() > PRIORITY = 1 > > def f(n): > """Pushes n into the queue, and then reschedules itself with > n+1 to run five seconds later""" > q.put(n) > s.enter(5, PRIORITY, f, (n+1,)) > > ## Let's prime things up. We'll set up the scheduler, and then have > ## it run on its own daemon thread. > s.enter(5, PRIORITY, f, (0,)) > t = Thread(target=s.run) > t.setDaemon(True) > t.start() > > ## At this point, our main thread of execution is separate from the > ## scheduler thread t. > while True: > print "Waiting for event on queue." > print q.get() > ###################################################################### > > > Does this make sense? Not yet completly Danny, I'll have to study it a bit, but from your use of threads I think you have a better understanding of what I want than I have myself. Thanks, Ingo From zeffrin at gmail.com Mon Mar 6 17:02:41 2006 From: zeffrin at gmail.com (ZeffriN) Date: Tue, 7 Mar 2006 02:02:41 +1000 Subject: [Tutor] curses delwin() functionality Message-ID: <4cfc36fd0603060802g7d0266d8y738995c91f2bad6e@mail.gmail.com> Hello all, Im writing about a topic which was discussed previously on this mailing list but didn't seem to be answered.. Bernd Prager asked whether the curses modules in Python had functionality like that of delwin() in the C libraries. He also supplied the below code sample to demonstrate the problem. (Thanks Bernd) Where he has commented # curses.delwin(s) would be where in C one could close the sub window created in sub() and refresh the underlying scrn. Ive also been unable to find how this is done and any assistance would be appreciated. #!/usr/bin/python import sys, curses def sub(scrn): s = curses.newwin(4, 30, 1, 1) s.erase() s.box() s.addstr(1, 1, "sub window") s.refresh() s.getch() # curses.delwin(s) <-- that doesn't exist :-/ scrn.refresh() def main(scrn): scrn = curses.initscr() curses.curs_set(0) # turn cursor off scrn.erase() scrn.addstr(2, 2, "press <F1> to continue, <F12> to quit"); while 1: c = scrn.getch() if c == curses.KEY_F12: sys.exit() elif c == curses.KEY_F1: sub(scrn) # main loop if __name__ == '__main__': curses.wrapper(main) sys.exit() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060307/7fde7059/attachment.html From brainy_muppet at hotmail.com Mon Mar 6 16:36:50 2006 From: brainy_muppet at hotmail.com (sjw28) Date: Mon, 6 Mar 2006 07:36:50 -0800 (PST) Subject: [Tutor] Analysing genetic code (DNA) using python Message-ID: <3263717.post@talk.nabble.com> I have many notepad documents that all contain long chunks of genetic code. They look something like this: atggctaaactgaccaagcgcatgcgtgttatccgcgagaaagttgatgcaaccaaacag tacgacatcaacgaagctatcgcactgctgaaagagctggcgactgctaaattcgtagaa agcgtggacgtagctgttaacctcggcatcgacgctcgtaaatctgaccagaacgtacgt ggtgcaactgtactgccgcacggtactggccgttccgttcgcgtagccgtatttacccaa Basically, I want to design a program using python that can open and read these documents. However, I want them to be read 3 base pairs at a time (to analyse them codon by codon) and find the value that each codon has a value assigned to it. An example of this is below: ** If the three base pairs were UUU the value assigned to it (from the codon value table) would be 0.296 The program has to read all the sequence three pairs at a time, then I want to get all the values for each codon, multiply them together and put them to the power of 1 / the length of the sequence in codons (which is the length of the whole sequence divided by three). However, to make things even more complicated, the notebook sequences are in lowercase and the codon value table is in uppercase, so the sequences need to be converted into uppercase. Also, the Ts in the DNA sequences need to be changed to Us (again to match the codon value table). And finally, before the DNA sequences are read and analysed I need to remove the first 50 codons (i.e. the first 150 letters) and the last 20 codons (the last 60 letters) from the DNA sequence. I've also been having problems ensuring the program reads ALL the sequence 3 letters at a time. I've tried various ways of doing this but keep coming unstuck along the way. Has anyone got any suggestions for how they would tackle this problem? Thanks for any help recieved! -- View this message in context: http://www.nabble.com/Analysing-genetic-code-%28DNA%29-using-python-t1233856.html#a3263717 Sent from the Python - tutor forum at Nabble.com. From robertjlane at gmail.com Mon Mar 6 18:22:47 2006 From: robertjlane at gmail.com (Rob Lane) Date: Mon, 6 Mar 2006 17:22:47 +0000 Subject: [Tutor] Query Message-ID: <19a516050603060922q6026b022m@mail.gmail.com> Hey, I am currently working on a final year project in college building a 3-D virtual model of a building in a python based program called Vizard. I have prepared a set of tutorials on powerpoint which i would like to access by clicking on various objects in the building. e.g. Click on a Window/Air Duct and then open a powerpoint presentation on the topic. I was wondering if there is python code which will let me launch my powerpoint presentations from with my virtual world. Any help would be greatly appreciate kind regards, Robert Lane Civil and Environmental Engineering IV UCC -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060306/24f2c9b6/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Mar 6 19:24:28 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Mar 2006 10:24:28 -0800 (PST) Subject: [Tutor] source file or installer In-Reply-To: <1d987df30603060233t637b0082l3999aef798e361a7@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603061008430.4275-100000@hkn.eecs.berkeley.edu> On Mon, 6 Mar 2006, linda.s wrote: > what are the benefits of building python from source file? any > difference if using installer? Hi Linda, If a binary installer is available for your platform, you'll probably want to stick with it. It provides the most convenient way to get Python. Some weird people insist on compiling all the software on their machines (like me *grin*). But the source is also provided so that other people and organizations can build products around Python. The source code can be treated as more than the "product": it can be treated as raw material: other people can refine it as necessary and build whatever they'd like. It turns out that Python.org produces a packaged product --- the binary installer --- but other people have done so too, including the ActiveState company: http://www.activestate.com/Products/ActivePython/ and other people have embedded Python directly into their own projects. (The video game "Freedom Force", for example, has a Python runtime.) So the accessibility of the Python source code makes it easier for some creators to make shiny products. If you are just trying to get Python so you can learn to program Python, the Python source code itself is probably not so useful for you now. I hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Mar 6 19:33:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Mar 2006 10:33:13 -0800 (PST) Subject: [Tutor] after signal handler In-Reply-To: <70576bd20603060415j16b9c7c0l9c325f3bdf02d87@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603061030370.4275-100000@hkn.eecs.berkeley.edu> On Mon, 6 Mar 2006, Hameed U. Khan wrote: > I want to go back after signal handler to the isntruction where I was > stuck. Below is the code I'm trying to play with. Hi Hameed, Here's a small test program that shows that the signal handling does go back to where we left off: ############################################## import signal import time def handler(signum, frame): print "alarm!" signal.alarm(2) signal.signal(signal.SIGALRM, handler) signal.alarm(2) while True: print "hello" time.sleep(1) ############################################### > What I'm trying to do is to implement a prompt with the remaining time > they have to enter some input. This should be doable. What can we help with? From kent37 at tds.net Mon Mar 6 19:38:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Mar 2006 13:38:48 -0500 Subject: [Tutor] Query In-Reply-To: <19a516050603060922q6026b022m@mail.gmail.com> References: <19a516050603060922q6026b022m@mail.gmail.com> Message-ID: <440C81B8.7010608@tds.net> Rob Lane wrote: > Hey, > > I am currently working on a final year project in college building a 3-D > virtual model of a building in a python based program called Vizard. I > have prepared a set of tutorials on powerpoint which i would like to > access by clicking on various objects in the building. e.g. Click on a > Window/Air Duct and then open a powerpoint presentation on the topic. > > I was wondering if there is python code which will let me launch my > powerpoint presentations from with my virtual world. os.system() will let you execute a command line, for example os.system(r'"C:\Program Files\Microsoft Office\Office\POWERPNT.EXE" F:\Personal\TEACHI~1\TDDINT~1.PPT') Note the use of a raw string to allow \ path separators and the double-quotes around the path to the exe because it has spaces in it. Kent From alan.gauld at freenet.co.uk Mon Mar 6 19:52:46 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Mar 2006 18:52:46 -0000 Subject: [Tutor] how to get the return value? References: <30792784.1141648580515.JavaMail.root@webmail1.groni1> Message-ID: <007d01c6414f$28bdd870$0b01a8c0@xp> > for every workingday of a week: > from 7.00 until 17.00: > every minute: > capture a frame and save it > at noon: > compile a video from the frames gathered this morning > do some file manipulations > at 17.00: > compile a video from the frames gathered this afternoon > do some file manipulations > on friday 17.00: > compile a movie from a selection ( every n_th) of the frames of this > week > ... To be honest I'd do this with a series of separate scripts triggered by the OS - either cron on Unix or at in Windows... Simply save the frames as individually named files, probably using the time... Another script can collect the frames into a video. With suitable choice of argv options you can do all you want with just two scripts. And no need to get caught in the mire of concurrent processing. This follows my motto of keeping things as simple as possible! :-) Alan G From kent37 at tds.net Mon Mar 6 19:52:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Mar 2006 13:52:53 -0500 Subject: [Tutor] Analysing genetic code (DNA) using python In-Reply-To: <3263717.post@talk.nabble.com> References: <3263717.post@talk.nabble.com> Message-ID: <440C8505.4070202@tds.net> sjw28 wrote: > I have many notepad documents that all contain long chunks of genetic > code.... > I've tried various ways of doing this but keep coming unstuck along the > way. Has anyone got any suggestions for how they would tackle this > problem? > Thanks for any help recieved! You really should look at biopython as has been suggested on comp.lang.python. The first example in the quick start guide does most of what you are asking for: http://biopython.org/docs/tutorial/Tutorial003.html#toc5 Alternately you can post what you have tried and what questions you have and we will help you work through them. Kent From gmanbauer at gmail.com Mon Mar 6 19:45:26 2006 From: gmanbauer at gmail.com (gmanbauer at gmail.com) Date: 06 Mar 2006 10:45:26 PST Subject: [Tutor] Are we the same? Message-ID: <20060306184526.D62241FC003@express1.tickle.com> Hi, I just took this test on Tickle.com. To see how I scored, take the test. The Super IQ Test http://web.tickle.com/invite?test=3046&type=t Your score will be shown to me, too. Gavin From annaraven at gmail.com Mon Mar 6 20:14:51 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Mon, 6 Mar 2006 11:14:51 -0800 Subject: [Tutor] Analysing genetic code (DNA) using python In-Reply-To: <3263717.post@talk.nabble.com> References: <3263717.post@talk.nabble.com> Message-ID: <cb361a610603061114s195abc65x7188dc0dbbcd3000@mail.gmail.com> On 3/6/06, sjw28 <brainy_muppet at hotmail.com> wrote: > > > I have many notepad documents that all contain long chunks of genetic > code. They look something like this: > > atggctaaactgaccaagcgcatgcgtgttatccgcgagaaagttgatgcaaccaaacag > tacgacatcaacgaagctatcgcactgctgaaagagctggcgactgctaaattcgtagaa > agcgtggacgtagctgttaacctcggcatcgacgctcgtaaatctgaccagaacgtacgt > ggtgcaactgtactgccgcacggtactggccgttccgttcgcgtagccgtatttacccaa > > > Basically, I want to design a program using python that can open and > read these documents. However, I want them to be read 3 base pairs at a > time (to analyse them codon by codon) and find the value that each > codon has a value assigned to it. An example of this is below: > > > ** If the three base pairs were UUU the value assigned to it (from the > codon value table) would be 0.296 > > > The program has to read all the sequence three pairs at a time, then I > want to get all the values for each codon, multiply them together and > put them to the power of 1 / the length of the sequence in codons > (which is the length of the whole sequence divided by three). > > > However, to make things even more complicated, the notebook sequences > are in lowercase and the codon value table is in uppercase, so the > sequences need to be converted into uppercase. Also, the Ts in the DNA > sequences need to be changed to Us (again to match the codon value > table). And finally, before the DNA sequences are read and analysed I > need to remove the first 50 codons (i.e. the first 150 letters) and the > last 20 codons (the last 60 letters) from the DNA sequence. I've also > been having problems ensuring the program reads ALL the sequence 3 > letters at a time. > > > I've tried various ways of doing this but keep coming unstuck along the > way. Has anyone got any suggestions for how they would tackle this > problem? > Thanks for any help recieved! You've got a lot of pieces to your puzzle. I would use f.read() to read all of the file in, then a list comprehension so you get only the codon characters (leaving out the newlines). A simple slicing of the list can give you each codon. something like might get you started: f = open('codons.txt', 'r') s = f.read() l = [c for c in s if c != '\n'] r = len(l) for x in range(0,r,3): y = x+3 codon = l[x:y] print codon f.close() Use ''.join() to make them back into a string. From there, you could do a lookup of the codon string in a dictionary. use the string method s.upper() to uppercase your codon string. Basically, figure out one problem at a time. Once that works, tackle the next problem. Or, use something someone else already wrote for you, like Kent suggests. cordially, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060306/fd70e5b1/attachment.htm From dyoo at hkn.eecs.berkeley.edu Mon Mar 6 20:25:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Mar 2006 11:25:39 -0800 (PST) Subject: [Tutor] Analysing genetic code (DNA) using python In-Reply-To: <3263717.post@talk.nabble.com> Message-ID: <Pine.LNX.4.44.0603061033210.4275-100000@hkn.eecs.berkeley.edu> > I have many notepad documents that all contain long chunks of genetic > code. They look something like this: > > atggctaaactgaccaagcgcatgcgtgttatccgcgagaaagttgatgcaaccaaacag [data example cut] > Basically, I want to design a program using python that can open and > read these documents. Hello sjw, Ok, let's stop at this point. It sounds like you want to design a function that takes in a string of genetic code, and calculate the "number_I_dont_understand_because_Im_not_a_biologist", or for short, "magical_number". So let's at least start off by writing a template: ###### def calculate_magical_number(codon): """calculate_magical_number: string -> number Calculates some magical number given a single codon. """ ## ... [fill me in] ###### Let's leave it as that for the moment. > However, I want them to be read 3 base pairs at a time (to analyse them > codon by codon) and find the value that each codon has a value assigned > to it. An example of this is below: > > ** If the three base pairs were UUU the value assigned to it (from the > codon value table) would be 0.296 Ok, that sound like we can make a few test examples. Let's imagine for the moment that we did have this program. We'd like to be able to say that: calculate_magic_number("UUU") == 0.296 Let's keep that test case in mind. Can we think of other simple test examples we can think of? Write them out. Would you be able to write calculate_magical_number() at this point? Can you think of a better name than 'calculate_magical_number'? > However, to make things even more complicated, the notebook sequences > are in lowercase and the codon value table is in uppercase, so the > sequences need to be converted into uppercase. So simplify the problem. Close your eyes and ignore the other requirements entirely. *grin* But seriously, don't look at those requirements at all yet. Fix the input to something simple. If you can't get calculate_magic_number() working, there's really no point. Put in a positive light, if you can get calculate_magic_number() right, you're much closer to success. The simple subproblem above completely ignores the fact that you want to do this on whole sequences, not just single codons, but that's ok: you can tackle that problem later. And you can always write helper functions to help sanitize the ugly, messy input and turn it into something that calculate_magic_number can handle. The point is: you must try to write your program iteratively: get a simple, correct subprogram working and tested. Once you have this, you can then start adding more features and helper functions to capture more of the real problem. You end up making progress at all steps, rather than cross your fingers and hope that it all just fits together at the end. But if you try building all at once, without any kind of scaffolding or minimal testing, you'll bound to have the whole structure fall apart, and you won't probably have a good sense of what part is breaking. > I've tried various ways of doing this but keep coming unstuck along the > way. Has anyone got any suggestions for how they would tackle this > problem? The recommendations presented here come from material in: http://www.htdp.org/ If you have time reading through it, I'd highly recommend it. It's not Python, but it does talk about program design. Good luck to you. From dyoo at hkn.eecs.berkeley.edu Mon Mar 6 20:27:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Mar 2006 11:27:48 -0800 (PST) Subject: [Tutor] Are we the same? In-Reply-To: <20060306184526.D62241FC003@express1.tickle.com> Message-ID: <Pine.LNX.4.44.0603061126260.4275-100000@hkn.eecs.berkeley.edu> On 6 Mar 2006 gmanbauer at gmail.com wrote: > I just took this test on Tickle.com. To see how I scored, take the test. [advertisement cut] I don't mean to be dull, but what does this have to do with Python? If it doesn't have anything to do with learning Python or programming, let's keep it off this list. From hugonz-lists at h-lab.net Mon Mar 6 22:07:25 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 06 Mar 2006 15:07:25 -0600 Subject: [Tutor] Are we the same? In-Reply-To: <Pine.LNX.4.44.0603061126260.4275-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0603061126260.4275-100000@hkn.eecs.berkeley.edu> Message-ID: <440CA48D.20005@h-lab.net> I believe it is just spam pretending to be a legit invitation, that made it to the list. Hugo From hugonz-lists at h-lab.net Mon Mar 6 22:11:19 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 06 Mar 2006 15:11:19 -0600 Subject: [Tutor] saving .csv file as an xl worksheet In-Reply-To: <8e82677d0603060116l419b06b6h4d60e5ef44062931@mail.gmail.com> References: <8e82677d0603060116l419b06b6h4d60e5ef44062931@mail.gmail.com> Message-ID: <440CA577.1090908@h-lab.net> Hello, .xls is a proprietary format used by Microsoft office, and unless you have the specs for that format and are willing to implement them (very very hard) it would not make much sense. If you absolutely need that, then maybe a macro in VBA from Excel itself may be a better option. ---- Changing the file extension only (just the filename, not the contents of the file) can be done using the shutil module in Python (high level file manipulation) Hugo arun wrote: > Hi , > Can i save a file with a desired extension?? > for ex: I have a .csv file (test.csv) and i want to save this file as > test.xls from a python script. From dyoo at hkn.eecs.berkeley.edu Mon Mar 6 22:15:32 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Mar 2006 13:15:32 -0800 (PST) Subject: [Tutor] Are we the same? In-Reply-To: <440CA48D.20005@h-lab.net> Message-ID: <Pine.LNX.4.44.0603061313590.22738-100000@hkn.eecs.berkeley.edu> On Mon, 6 Mar 2006, [ISO-8859-1] Hugo González Monteverde wrote: > I believe it is just spam pretending to be a legit invitation, that made > it to the list. Followup: Gavin later sent a reply apologizing to the list --- maybe he got a virus? --- but it didn't make it through since it was addressed to too many people. *grin* Oh well, no real harm done. From seedseven at home.nl Mon Mar 6 22:16:28 2006 From: seedseven at home.nl (Ingo) Date: Mon, 06 Mar 2006 22:16:28 +0100 Subject: [Tutor] how to get the return value? In-Reply-To: <007d01c6414f$28bdd870$0b01a8c0@xp> References: <30792784.1141648580515.JavaMail.root@webmail1.groni1> <007d01c6414f$28bdd870$0b01a8c0@xp> Message-ID: <200603062216280906.001E3E4F@mail.home.nl> On 2006/3/06, Alan Gauld wrote: >> for every workingday of a week: >> [...] >> week >> ... > >To be honest I'd do this with a series of separate scripts triggered by the >OS - either cron on Unix or at in Windows... To be honest, I had my share of troubles with AT, so I try to stay away from it. No unix box here, so ... mmm, there seems to be a pycron maybe that's the tool I'm looking for. >Simply save the frames as individually named files, probably using the >time... Getting the frames and naming them is no big problem, for windows there's the great videocapture module http://videocapture.sourceforge.net/ >This follows my motto of keeping things as simple as possible! :-) I try, I'm trying to try God knows I try Thanks Alan, Ingo From David.Heiser at intelliden.com Mon Mar 6 22:15:30 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Mon, 6 Mar 2006 14:15:30 -0700 Subject: [Tutor] Analysing genetic code (DNA) using python Message-ID: <3CABD13EA1D5D347A1B75014BD54CFD502B0BBAC@COSIUM03.intelliden.net> Here's one approach to the problem (using bogus codon values). -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of sjw28 Sent: Monday, March 06, 2006 8:37 AM To: tutor at python.org Subject: [Tutor] Analysing genetic code (DNA) using python I have many notepad documents that all contain long chunks of genetic code. They look something like this: atggctaaactgaccaagcgcatgcgtgttatccgcgagaaagttgatgcaaccaaacag tacgacatcaacgaagctatcgcactgctgaaagagctggcgactgctaaattcgtagaa agcgtggacgtagctgttaacctcggcatcgacgctcgtaaatctgaccagaacgtacgt ggtgcaactgtactgccgcacggtactggccgttccgttcgcgtagccgtatttacccaa Basically, I want to design a program using python that can open and read these documents. However, I want them to be read 3 base pairs at a time (to analyse them codon by codon) and find the value that each codon has a value assigned to it. An example of this is below: ** If the three base pairs were UUU the value assigned to it (from the codon value table) would be 0.296 The program has to read all the sequence three pairs at a time, then I want to get all the values for each codon, multiply them together and put them to the power of 1 / the length of the sequence in codons (which is the length of the whole sequence divided by three). However, to make things even more complicated, the notebook sequences are in lowercase and the codon value table is in uppercase, so the sequences need to be converted into uppercase. Also, the Ts in the DNA sequences need to be changed to Us (again to match the codon value table). And finally, before the DNA sequences are read and analysed I need to remove the first 50 codons (i.e. the first 150 letters) and the last 20 codons (the last 60 letters) from the DNA sequence. I've also been having problems ensuring the program reads ALL the sequence 3 letters at a time. I've tried various ways of doing this but keep coming unstuck along the way. Has anyone got any suggestions for how they would tackle this problem? Thanks for any help recieved! -- View this message in context: http://www.nabble.com/Analysing-genetic-code-%28DNA%29-using-python-t123 3856.html#a3263717 Sent from the Python - tutor forum at Nabble.com. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: GenCode.py Type: application/octet-stream Size: 1243 bytes Desc: GenCode.py Url : http://mail.python.org/pipermail/tutor/attachments/20060306/5536fbf5/attachment.obj -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: GenCode.txt Url: http://mail.python.org/pipermail/tutor/attachments/20060306/5536fbf5/attachment.txt From hugonz-lists at h-lab.net Mon Mar 6 22:28:39 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 06 Mar 2006 15:28:39 -0600 Subject: [Tutor] Analysing genetic code (DNA) using python In-Reply-To: <3263717.post@talk.nabble.com> References: <3263717.post@talk.nabble.com> Message-ID: <440CA987.106@h-lab.net> Hi Anna, Let's see one thing at a time. wrote: > ** If the three base pairs were UUU the value assigned to it (from the > codon value table) would be 0.296 This can be done in Python, and one appropriate tool may be a dictionary such as: >>> dna_table = { "UUU" : 0.296, "GGG" : 0.3 } >>> print dna_table["UUU"] 0.296 >>> You'd use the table to look the corresponding value. Of course, you'd have to so some programming to get your ASCII translation tables converted to a dictionary. > The program has to read all the sequence three pairs at a time, then I > want to get all the values for each codon, multiply them together and > put them to the power of 1 / the length of the sequence in codons > (which is the length of the whole sequence divided by three). Rational powers are supported by the pow() function in module math, see: >>> import math >>> math.pow(10,0.5) 3.1622776601683791 > > > However, to make things even more complicated, the notebook sequences > are in lowercase and the codon value table is in uppercase, so the > sequences need to be converted into uppercase. Also, the Ts in the DNA > sequences need to be changed to Us (again to match the codon value > table). And finally, before the DNA sequences are read and analysed I > need to remove the first 50 codons (i.e. the first 150 letters) and the > last 20 codons (the last 60 letters) from the DNA sequence. These problems are very straightforward in python with string methods, take a looks at the docs at: http://docs.python.org/lib/string-methods.html I've also > been having problems ensuring the program reads ALL the sequence 3 > letters at a time. > Line endings may be causing you problems if you try to read line by line. Something like this should do: #read 100 characters from your file buff = fileo.read(100) #eliminate line endings buff = buff.replace("\n", "") #read three new characters word = buff[0:4] #consume part of the buffer buff = buff[4:] This is slow and can be polished. One approach could be reading characters into a list and then consuming that list (strings are a bit harder since you cannot change them) Also, the last expressions will throw an exception when the list is too short, and you'll have to read another chunk from the file. Hope this all helps, please let us know how far have you got and when you get stuck so we can help. Hugo From kent37 at tds.net Mon Mar 6 22:34:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Mar 2006 16:34:04 -0500 Subject: [Tutor] saving .csv file as an xl worksheet In-Reply-To: <8e82677d0603060116l419b06b6h4d60e5ef44062931@mail.gmail.com> References: <8e82677d0603060116l419b06b6h4d60e5ef44062931@mail.gmail.com> Message-ID: <440CAACC.8020401@tds.net> arun wrote: > Hi , > Can i save a file with a desired extension?? > for ex: I have a .csv file (test.csv) and i want to save this file as > test.xls from a python script. It's easy to rename a file, or read it and save it with whatever name you like, but that won't convert it to an actual Excel worksheet. To write true xls files you can use win32com to control Excel through its COM interface (google python excel for many examples) or you can use pyExcelerator. http://cheeseshop.python.org/pypi/pyExcelerator/0.6.0a Kent From alan.gauld at freenet.co.uk Tue Mar 7 00:25:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 6 Mar 2006 23:25:10 -0000 Subject: [Tutor] how to get the return value? References: <30792784.1141648580515.JavaMail.root@webmail1.groni1><007d01c6414f$28bdd870$0b01a8c0@xp> <200603062216280906.001E3E4F@mail.home.nl> Message-ID: <00ab01c64175$3695bdc0$0b01a8c0@xp> > To be honest, I had my share of troubles with AT, so I try to stay away > from it. No unix box here, so ... so... download cygwin! including a fully functioning cron. I can't imagine life on Windoze without cygwin :-) Alan G. From john at fouhy.net Tue Mar 7 01:06:57 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 7 Mar 2006 13:06:57 +1300 Subject: [Tutor] [OT] Shells Message-ID: <5e58f2e40603061606w675011e6l@mail.gmail.com> On 07/03/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > I can't imagine life on Windoze without cygwin :-) Agreed --- but the new Microsoft shell looks very interesting. Ars has a good review of it here: http://arstechnica.com/guides/other/msh.ars It borrows from all over the place, including Perl, Python, (ba)sh, and SQL, so the syntax sometimes seems to fight itself. But, overall, I'm very impressed. It looks a lot like the python interpreter, except customised to focus on file manipulation and process management (since that's what shells are for). -- John. From Gideon.STREET at ergon.com.au Tue Mar 7 02:31:06 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Tue, 7 Mar 2006 11:31:06 +1000 Subject: [Tutor] Print list vs telnetlib.telnet.write differences Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC0A256D@ebnewem01.ergon> Lloyd/David and all, I'm still seeing something a bit weird with sending commands back to the router via tn.write(). This is with python 2.4.2 As per David's last email I replaced: tn.read_until('#') for item in lines: x = item tn.write(x) With: blob = string.join(lines) print blob #tn.write("\03") # Assures the device is in enable mode x = tn.read_until("#") # The "x =" seems to help flush the read buffer tn.write("conf t\n") x = tn.read_until("#") tn.write(blob) tn.read_until('#') tn.write('exit' '\n') #disconnect from the session But I am still seeing a command being sent to the device twice :( As per the above I've got a print command outputting what I'm sending back to the router. The output of the print blob looks like (output shown between the lines): ___________________________________________________ banner exec ^ ################################################## switch01 Level XX, XX Some Street, Somewhere Site contact: John Citizen 555 5555 System Contact: Helpdesk 555 5556 ################################################## ^ ___________________________________________________ Yet the output on TCPWatch looks like (output shown between the lines): ____________________________________________________________ Enter configuration commands, one per line. End with CNTL/Z. switch01(config)#banner exec ^ ################################################## switch01 Level XX, XX Some Street, Somewhere Site contact: John Citizen 555 5555 System Contact: Helpdesk 555 5556 ################################################## ^ banner exec ^ <---- this is the second time this command is sent to the device Enter TEXT message. End with the character '^'. ###exit ############ ____________________________________________________________ Any explanation of what I'm doing wrong to get duplication of the sent commands? It looks like the script is looping on the print blob, but I can't see why it should do that? Thanks Gideon (I can send through the entire script but it's a 170+ lines and didn't want to send an epic email to the list) -----Original Message----- From: Python [mailto:python at venix.com] Sent: Saturday, 4 March 2006 3:42 AM To: STREET Gideon (SPARQ) Cc: Tutor Python Subject: Re: [Tutor] Print list vs telnetlib.telnet.write differences On Fri, 2006-03-03 at 15:41 +1000, STREET Gideon (SPARQ) wrote: > The problem I'm stumbling over is that when I print x, the output is > what I want. If I delete the print x and #, leaving only tn.write(x) > on the last line everything looks good except it writes the 1st item > in "lines" (the banner exec command) twice, once at the beginning > where it's supposed to, but then once again at the end. See except > below for example. > > Anyone able to explain why that is happening or is it me just not > understanding what I'm doing? Hope my explanation is clear I'm still > unfamiliar with the exact phrasology. > Could that be your data being echoed back to you? Is the router configured correctly after the script runs? I normally feed commands to Cisco devices using tftp. It is relatively easy to edit a file to get the commands correct. Then you could limit your "conversational script" to logging in and running tftp to transfer the command file. It looks like you are pretty close to having this working. -- 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 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 python at venix.com Tue Mar 7 03:52:25 2006 From: python at venix.com (Python) Date: Mon, 06 Mar 2006 21:52:25 -0500 Subject: [Tutor] Print list vs telnetlib.telnet.write differences In-Reply-To: <5A504BF2C0C9F5438ACBF61D35D49FFC0A256D@ebnewem01.ergon> References: <5A504BF2C0C9F5438ACBF61D35D49FFC0A256D@ebnewem01.ergon> Message-ID: <1141699945.15743.995.camel@www.venix.com> On Tue, 2006-03-07 at 11:31 +1000, STREET Gideon (SPARQ) wrote: > Enter configuration commands, one per line. End with CNTL/Z. > switch01(config)#banner exec ^ > > ################################################## > > switch01 > > Level XX, XX Some Street, Somewhere > Site contact: John Citizen 555 5555 > System Contact: Helpdesk 555 5556 > > ################################################## > > ^ > banner exec ^ <---- this is the second time this command is sent to the device > Enter TEXT message. End with the character '^'. > > ###exit > ############ My tcpwatch.py display shows different colors for each side of the conversation. Do you get two colors? are both in the same color? Isn't the second banner exec simply the echo back from the cisco device? It is giving you your entry instructions. 1. Is the banner exec command working? If it works, then the funny duplication is almost certainly just an artifact of characters getting echoed from the cisco device. -- Lloyd Kvam Venix Corp From python at venix.com Tue Mar 7 05:29:20 2006 From: python at venix.com (Python) Date: Mon, 06 Mar 2006 23:29:20 -0500 Subject: [Tutor] Print list vs telnetlib.telnet.write differences In-Reply-To: <5A504BF2C0C9F5438ACBF61D35D49FFC06E374@ebnewem01.ergon> References: <5A504BF2C0C9F5438ACBF61D35D49FFC06E374@ebnewem01.ergon> Message-ID: <1141705760.15743.1023.camel@www.venix.com> On Tue, 2006-03-07 at 13:39 +1000, STREET Gideon (SPARQ) wrote: > The second banner exec is red, the previous commands I send are in > green. So I take it to mean that it is an echo produced by the router. > MMmm strange as the echo is overwriting what I'm sending initially. Well the device is designed for interactive use by a human who does not spew characters nearly has quickly as your script. In this case you probably need to read the response to the exec banner command before sending the banner. Most commands are done in a single line, but banner is an exception. This kind of scripting is often done with expect and I believe that there is some expect-like module for Python. As I suggested earlier, getting tftp to send command files will make a much better long term solution. This script would only have to manage logging in and starting tftp. Once that works all other commands would be in the file that tftp transfers. Linux/Unix systems already have tftp built in. Cisco provides a tftp implementation for Windows. It is easy to put comments into the command files and also use subversion or some other version control package to track changes. > > The banner appears to work but is then overwritten, maybe I need to come > up with another way of sending the commands so I get around the echo. > > Thanks > > Gideon > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Python > Sent: Tuesday, 7 March 2006 12:52 PM > To: Tutor Python > Subject: Re: [Tutor] Print list vs telnetlib.telnet.write differences > > On Tue, 2006-03-07 at 11:31 +1000, STREET Gideon (SPARQ) wrote: > > Enter configuration commands, one per line. End with CNTL/Z. > > switch01(config)#banner exec ^ > > > > ################################################## > > > > switch01 > > > > Level XX, XX Some Street, Somewhere > > Site contact: John Citizen 555 5555 > > System Contact: Helpdesk 555 5556 > > > > ################################################## > > > > ^ > > banner exec ^ <---- this is the second time this command is sent to > > the device Enter TEXT message. End with the character '^'. > > > > ###exit > > ############ > > My tcpwatch.py display shows different colors for each side of the > conversation. Do you get two colors? are both in the same color? > > Isn't the second banner exec simply the echo back from the cisco device? > It is giving you your entry instructions. > > 1. Is the banner exec command working? > If it works, then the funny duplication is almost certainly just an > artifact of characters getting echoed from the cisco device. > > -- > Lloyd Kvam > Venix Corp > > _______________________________________________ > 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 -- Lloyd Kvam Venix Corp From tak at dfx.co.jp Tue Mar 7 04:57:49 2006 From: tak at dfx.co.jp (tak) Date: Tue, 07 Mar 2006 12:57:49 +0900 Subject: [Tutor] search and replace Message-ID: <440D04BD.4090804@dfx.co.jp> Hello, I have a problem finding specific words. I would like to filter out a word or replace it in a file. I notices that the re module is good for finding patterns. I am trying to filter out a word from strings, but having a little trouble. I was wondering if I can search a string for a specific word and nothing else. For example: hello, Othello. # just the hello and not Othello I know that I could probably put the string in a list and replace it. But I was wondering if it is possible using re module or the other find type attributes to find it. hello will not be necessarily at the beginning or end, so I am opting not to use endswith or startswith. Thank you. Best regards, tak From mail at ozzmosis.com Tue Mar 7 06:38:46 2006 From: mail at ozzmosis.com (andrew clarke) Date: Tue, 7 Mar 2006 16:38:46 +1100 Subject: [Tutor] saving .csv file as an xl worksheet In-Reply-To: <8e82677d0603060116l419b06b6h4d60e5ef44062931@mail.gmail.com> References: <8e82677d0603060116l419b06b6h4d60e5ef44062931@mail.gmail.com> Message-ID: <20060307053846.GA32299@ozzmosis.com> On Mon, Mar 06, 2006 at 02:46:36PM +0530, arun wrote: > Can i save a file with a desired extension?? > for ex: I have a .csv file (test.csv) and i want to save this file as > test.xls from a python script. Just changing the file extension from .csv to .xls won't change the file format. OpenOffice 2.0 supports both .csv and .xls file formats and includes some sort of Python integration. It may be possible to use that. Regards Andrew From cyunem at ofir.dk Mon Mar 6 21:24:26 2006 From: cyunem at ofir.dk (Simon Stoltze) Date: Mon, 06 Mar 2006 21:24:26 +0100 Subject: [Tutor] Functions and random buttons Message-ID: <1141676666_584422@mailout.ofir.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060306/326c6278/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Tue Mar 7 09:13:07 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Mar 2006 00:13:07 -0800 (PST) Subject: [Tutor] search and replace In-Reply-To: <440D04BD.4090804@dfx.co.jp> Message-ID: <Pine.LNX.4.44.0603070007220.14307-100000@hkn.eecs.berkeley.edu> > I have a problem finding specific words. > I would like to filter out a word or replace it in a file. > I notices that the re module is good for finding patterns. Hi Tak, Although regular expressions might be overkill for this problem, it can't hurt to know about the Regex HOWTO: http://www.amk.ca/python/howto/regex/ Note that strings can already do simple replacement: ###### >>> 'this is a test hi world'.replace('hi', 'hello') 'thellos is a test hello world' ###### As this example shows, we need to be a bit careful with it. Regexes allow us to do a slightly smarter, word boundary-specific substitution: ###### >>> import re >>> re.sub(r'\bhi\b', 'hello', 'this is a test hi world') 'this is a test hello world' ###### The Regex HOWTO link above is a tutorial on how to use the module effectively. If you have questions, please feel free to bring them up. Good luck! From alan.gauld at freenet.co.uk Tue Mar 7 10:33:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 7 Mar 2006 09:33:03 -0000 Subject: [Tutor] search and replace References: <440D04BD.4090804@dfx.co.jp> Message-ID: <00ca01c641ca$21f26210$0b01a8c0@xp> Hi tak, > hello, Othello. # just the hello and not Othello One simplistic approach that does not use regex is to search for spaces as part of the string. But that doesn't work for punctuation nor at the start or end of lines. So that leaves us, as you observed, with regular expressions. regex allows us to specify certain conditions in the patterns such as whether the characters are digits etc, and also whether we are kooking for a word which is wat you want. Specifically \W signifies a word boundary so \Whello\W will find hello as a word. Take a look at my tutorial topic on regex for more detail, or go to the excellent regex How-To linked from the Python site. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Mar 7 10:42:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 7 Mar 2006 09:42:00 -0000 Subject: [Tutor] Functions and random buttons References: <1141676666_584422@mailout.ofir.com> Message-ID: <00cd01c641cb$67e168b0$0b01a8c0@xp> Simon, > ...I want to make each button clickable The buttons are clickable so I'm not absolutely sure what you mean? Do you mean you want to add some action to them when they are clicked? Thats done with the command option in Tkinter. define a function and assign it to the button. In this case it will likely be the same function for all buttons so you might want to do a wee bit of trickery like: def func(x,y): #x,y the button coords # do something here for i in range(length): for j in range(length): self.dict['%s%s' % (i, j)] = Button(sel.frame, text = ' ' command = lambda x=i,y=j: func(x,y)) That uses the default values of the lambda function to pass the coords of the button being pressed to your generic function. func can then use those coords to address the button in the dictionary to update the label or appearance etc. One other wee point: self.dict['%s%s' % (i, j)].grid(row = i, column = j) You don't need to use a string for a key in a dictionary, the tuple will be just fine so you can replace the string formatting stuff with: self.dict[(i, j)].grid(row = i, column = j) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Mar 7 11:04:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 7 Mar 2006 10:04:30 -0000 Subject: [Tutor] [OT] Shells References: <5e58f2e40603061606w675011e6l@mail.gmail.com> Message-ID: <00dd01c641ce$887909e0$0b01a8c0@xp> Hi john, > Agreed --- but the new Microsoft shell looks very interesting. > Ars has a good review of it here: > http://arstechnica.com/guides/other/msh.ars Nice heads-up. I hadn't heard of this before, despite reading several of the comics' views on Vista. It looks promising, although without good command line editing and the ability to create active GUIs it will be limited. But then, you can't do GUIs in bash either... But an OO pipeline is interesting, I wonder how long before somebody in Linux comes up with a new shell mechanism for that? Thanks again, Alan G. From tak at dfx.co.jp Tue Mar 7 11:22:09 2006 From: tak at dfx.co.jp (tak) Date: Tue, 07 Mar 2006 19:22:09 +0900 Subject: [Tutor] how to write a string into a specific line in a file Message-ID: <440D5ED1.1010104@dfx.co.jp> Hello, I was wondering if it is possible to write a string to a specific line in a file without reading in the whole file in as the below. ___________________________________________________________________ f = open(filename) lines = f.readlines() f.close() # num for some line number line[num] = "String" f = open(filename) f.writelines(lines) f.close() ____________________________________________________________________ Writing directly to the line number would be ideal. Some thing like: f.write(line number, string) if there is a function like that. Or would the best way to do line replacement be through iteration. __________________________________________________________________ for line in open(filename): # write to current line??? _________________________________________________________________ Thank you. Best regards, Tak From tak at dfx.co.jp Tue Mar 7 11:29:51 2006 From: tak at dfx.co.jp (tak) Date: Tue, 07 Mar 2006 19:29:51 +0900 Subject: [Tutor] how to write a string into a specific line in a file Message-ID: <440D609F.1060207@dfx.co.jp> Sorry, I meant lines in line in the below: f = open(filename) lines = f.readlines() f.close() # num for some line number >>lines[num] = "String" f = open(filename) f.writelines(lines) f.close() ******************************************************************* Hello, I was wondering if it is possible to write a string to a specific line in a file without reading in the whole file in as the below. ___________________________________________________________________ f = open(filename) lines = f.readlines() f.close() # num for some line number line[num] = "String" f = open(filename) f.writelines(lines) f.close() ____________________________________________________________________ Writing directly to the line number would be ideal. Some thing like: f.write(line number, string) if there is a function like that. Or would the best way to do line replacement be through iteration. __________________________________________________________________ for line in open(filename): # write to current line??? _________________________________________________________________ Thank you. Best regards, Tak From alan.gauld at freenet.co.uk Tue Mar 7 12:18:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 7 Mar 2006 11:18:27 -0000 Subject: [Tutor] how to write a string into a specific line in a file References: <440D5ED1.1010104@dfx.co.jp> Message-ID: <00f901c641d8$dbeb7360$0b01a8c0@xp> > I was wondering if it is possible to write a string to a specific line > in a file without reading in the whole file in as the below. Some languages, such as COBOL and some BASICs etc support random access files, unfortunately Python doesn't (Although I'll be amazed if somebody hasn't cooked up (or is cooking up) a module that does it) > f = open(filename) > lines = f.readlines() > f.close() > # num for some line number > line[num] = "String" > f = open(filename) > f.writelines(lines) > f.close() You can shorten that slightly to lines = open(filnemame).readlines() lines[num] = 'foo' open(filename).write('\n'.join(lines)) But essentially that is the standard way to do it. You can avoid reading the entire file by using seek() to go to a specific location in the file. You can also write directly to the file but that is dangerous unless you are writing exactly the same number of bytes as previously existed. (And you can force that by defining a fixed record structure - which is how ISAM files work in BASIC/COBOL etc). > Or would the best way to do line replacement be through iteration. > for line in open(filename): > # write to current line??? This is ok if you open for both reading and writing... Also using enumerate will give you the line number to check. Alan G From hameed.u.khan at gmail.com Tue Mar 7 13:48:44 2006 From: hameed.u.khan at gmail.com (Hameed U. Khan) Date: Tue, 7 Mar 2006 17:48:44 +0500 Subject: [Tutor] after signal handler In-Reply-To: <Pine.LNX.4.44.0603061030370.4275-100000@hkn.eecs.berkeley.edu> References: <70576bd20603060415j16b9c7c0l9c325f3bdf02d87@mail.gmail.com> <Pine.LNX.4.44.0603061030370.4275-100000@hkn.eecs.berkeley.edu> Message-ID: <70576bd20603070448x41977212s718b80275436e4f0@mail.gmail.com> On 3/6/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > > On Mon, 6 Mar 2006, Hameed U. Khan wrote: > > > I want to go back after signal handler to the isntruction where I was > > stuck. Below is the code I'm trying to play with. > > Hi Hameed, > > Here's a small test program that shows that the signal handling does go > back to where we left off: Hi Danny, Thanks your program really solved one misconception I had for singlas. That they dont pass control back. Now I've a little more understanding of signal handlers in python. > > What I'm trying to do is to implement a prompt with the remaining time > > they have to enter some input. > > This should be doable. What can we help with? After your example I realised that I'm following a wrong approach. Then I decided to use select module. I've almost solved the problem, but there is still one issue. which I think can't be resolved. Following is my program which implements prompt with indicator of time left for user to input. I'll be happy to recieve suggestions and improvements :) #!/usr/bin/env python2.4 ####### Start program import sys import time import select def get_input(prompt="Enter input in %d seconds: ",timecount=10): tcount = timecount while True: if tcount == 0: print break print "\r" + prompt % tcount, sys.stdout.flush() time.sleep(1) list = select.select([sys.stdin],[],[],0) if list[0] != []: input = sys.stdin.readline() print return (timecount-tcount,input) tcount = tcount -1 print return None print "Input check: " myin= get_input() if myin == None: print "No input" else: print "You enetered in %d seconds: %s" % myin ######## End program -- Hameed U. Khan Registered Linux User #: 354374 From cyunem at ofir.dk Tue Mar 7 15:27:37 2006 From: cyunem at ofir.dk (Simon Stoltze) Date: Tue, 07 Mar 2006 15:27:37 +0100 Subject: [Tutor] =?iso-8859-1?B?UmU6IFtUdXRvcl0gRnVuY3Rpb25zIGFuZCByYW5kb20gYnV0dG9ucw?= =?iso-8859-1?B?==?= Message-ID: <1141741657_599686@mailout.ofir.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060307/bb5d5cb2/attachment.html From janos.juhasz at VELUX.com Tue Mar 7 17:30:26 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 7 Mar 2006 17:30:26 +0100 Subject: [Tutor] saving .csv file as an xl worksheet In-Reply-To: <mailman.9711.1141712368.27774.tutor@python.org> Message-ID: <OF4A0C482B.4A6FC991-ONC125712A.00296E03-C125712A.005AAD7D@velux.com> Hi, last week I had to make a simple solution to convert prn file to excel. It seems to be very similar. I just wondered how easy to create an xml file that can be opened with excel. It can have functions, autofilters, format descriptions. It is about 100 times faster to create than on the win32com way. It is twice bigger than the binary excel, but it can be compressed into the half size of the compressed binary. People working with excel can't feel the difference :) I don't know how can it be opened with StarOffice, but it works well with excel2003. ################################################################## import os xmlhead = """<?xml version="1.0" encoding="iso-8859-1"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <Worksheet ss:Name="XML XLS test"> <Table> """ xmlsum = """ <Row> <Cell ss:Index="3" ss:Formula="=SUM(R[-%d]C:R[-1]C)"><Data ss:Type="Number"></Data></Cell> </Row> """ xmlfoot = """ </Table> <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> <Unsynced/> <Selected/> </WorksheetOptions> <AutoFilter x:Range="R1C1:R%dC%d" xmlns="urn:schemas-microsoft-com:office:excel"> </AutoFilter> </Worksheet> </Workbook> """ headrow = ('1st;2nd;3rd') lines = ('1;2;3', '2;3;4', '3;4;5', '4;5;6') dest = 'Test.xls' xml = open(dest, 'wt') rownum = 1 ## Header xml.write(xmlhead) ## HeadRow xml.write(' <Row>\n') for data in headrow.split(';'): xml.write(' <Cell><Data ss:Type="String">%s</Data></Cell>\n' % data) xml.write(' </Row>\n') rownum += 1 ## Rows with data for line in lines: colnum = len(line.split(';')) xml.write(' <Row>\n') for data in line.split(';'): xml.write(' <Cell><Data ss:Type="Number">%s</Data></Cell>\n' % data) xml.write(' </Row>\n') rownum += 1 ## Function with reference xml.write(xmlsum % (rownum-2)) ## Foot xml.write(xmlfoot % (rownum, colnum)) xml.close() os.execl(r'c:\Program Files\Microsoft Office\Office10\EXCEL.EXE', dest) ################################################################## Yours sincerely, ______________________________ J?nos Juh?sz Date: Tue, 7 Mar 2006 16:38:46 +1100 From: andrew clarke <mail at ozzmosis.com> Subject: Re: [Tutor] saving .csv file as an xl worksheet To: tutor at python.org Message-ID: <20060307053846.GA32299 at ozzmosis.com> Content-Type: text/plain; charset=us-ascii On Mon, Mar 06, 2006 at 02:46:36PM +0530, arun wrote: > Can i save a file with a desired extension?? > for ex: I have a .csv file (test.csv) and i want to save this file as > test.xls from a python script. Just changing the file extension from .csv to .xls won't change the file format. OpenOffice 2.0 supports both .csv and .xls file formats and includes some sort of Python integration. It may be possible to use that. Regards Andrew From dyoo at hkn.eecs.berkeley.edu Tue Mar 7 19:40:24 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Mar 2006 10:40:24 -0800 (PST) Subject: [Tutor] search and replace In-Reply-To: <00ca01c641ca$21f26210$0b01a8c0@xp> Message-ID: <Pine.LNX.4.44.0603071036210.24774-100000@hkn.eecs.berkeley.edu> > regex allows us to specify certain conditions in the patterns > such as whether the characters are digits etc, and also whether > we are kooking for a word which is wat you want. > Specifically \W signifies a word boundary so > > \Whello\W > > will find hello as a word. Hi Alan, Using the non-word pattern '\W' will work except in cases where we're right at the edge: ###### >>> import re >>> re.sub(r'\Whi\W', 'hello', 'hi there') 'hi there' ###### Slightly more robust is the '\b' boundary assertion pattern: ###### >>> re.sub(r'\bhi\b', 'hello', 'hi there') 'hello there' ###### Best of wishes! From alan.gauld at freenet.co.uk Wed Mar 8 00:15:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 7 Mar 2006 23:15:29 -0000 Subject: [Tutor] search and replace References: <Pine.LNX.4.44.0603071036210.24774-100000@hkn.eecs.berkeley.edu> Message-ID: <010d01c6423d$06ac47f0$0b01a8c0@xp> >> Specifically \W signifies a word boundary so >> > Using the non-word pattern '\W' will work except in cases where we're > right at the edge: Sneaky! I didn't know that... > Slightly more robust is the '\b' boundary assertion pattern: And I never understood why there were two... Which begs the question: under what circumstance would we prefer to use \W instead of \b? I need to dig out my regex book... Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Mar 8 01:20:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Mar 2006 16:20:37 -0800 (PST) Subject: [Tutor] search and replace In-Reply-To: <010d01c6423d$06ac47f0$0b01a8c0@xp> Message-ID: <Pine.LNX.4.44.0603071605230.11175-100000@hkn.eecs.berkeley.edu> > > Slightly more robust is the '\b' boundary assertion pattern: > > And I never understood why there were two... > > Which begs the question: under what circumstance would we prefer > to use \W instead of \b? In terms of code: ###### >>> import re >>> re.search(r'(\W\w+\W)', '||||hello|||').group(1) '|hello|' >>> re.search(r'(\b\w+\b)', '||||hello|||').group(1) 'hello' ###### '\b' is subtly different: it doesn't really capture whatever we're pattern matching against. It's a zero-width "assertion". '\W', on the other hand, has a meaning as any character that's not alphanumeric or underscore ('[^a-zA-Z0-9_]'). Hope this helps! From nequeo at gmail.com Wed Mar 8 03:36:52 2006 From: nequeo at gmail.com (Simon Gerber) Date: Wed, 8 Mar 2006 13:36:52 +1100 Subject: [Tutor] [OT] Shells In-Reply-To: <00dd01c641ce$887909e0$0b01a8c0@xp> References: <5e58f2e40603061606w675011e6l@mail.gmail.com> <00dd01c641ce$887909e0$0b01a8c0@xp> Message-ID: <667ca7b60603071836s13c8be5aq91b016c88508072@mail.gmail.com> > It looks promising, although without good command line editing and the > ability to create active GUIs it will be limited. But then, you can't do GUIs in > bash either... There's always Zenity. Which of course isn't a built in part of the Bash shell. But it does allow you to create simple GUI dialogues to use with shell scripts. And most distro's include it as part of the default installation. -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From jeffpeery at yahoo.com Wed Mar 8 06:55:43 2006 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 7 Mar 2006 21:55:43 -0800 (PST) Subject: [Tutor] PLC communication with python? Message-ID: <20060308055543.1629.qmail@web30504.mail.mud.yahoo.com> Hello, I would like to write a python script that communicates with a PLC (programmable logic controller) as well as instruments like calipers and things. I'm completely in the dark here and not sure where to start reading and learning. could someone point me in the right direction for learning this stuff? thanks! Jeff --------------------------------- Yahoo! Mail Bring photos to life! New PhotoMail makes sharing a breeze. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060307/1d32b004/attachment.html From kent37 at tds.net Wed Mar 8 11:49:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Mar 2006 05:49:00 -0500 Subject: [Tutor] PLC communication with python? In-Reply-To: <20060308055543.1629.qmail@web30504.mail.mud.yahoo.com> References: <20060308055543.1629.qmail@web30504.mail.mud.yahoo.com> Message-ID: <440EB69C.6010606@tds.net> Jeff Peery wrote: > Hello, I would like to write a python script that communicates with a > PLC (programmable logic controller) as well as instruments like calipers > and things. I'm completely in the dark here and not sure where to start > reading and learning. could someone point me in the right direction for > learning this stuff? thanks! How does the equipment connect to the computer? If it connects to the serial port then try pyserial: http://pyserial.sourceforge.net/ If it connects to the parallel port there is http://pyserial.sourceforge.net/pyparallel.html or for Windows there is winioport: http://www.geocities.com/dinceraydin/python/indexeng.html So the first step is to find out what kind(s) of interface you are using, and collect software that allows Python to talk to that interface. Then try some really simple tests - reading a single value or setting a simple setting on the instrument. From there you can build a library of functions that do interesting things and build your programs on that. Kent From mail at ozzmosis.com Wed Mar 8 12:41:21 2006 From: mail at ozzmosis.com (andrew clarke) Date: Wed, 8 Mar 2006 22:41:21 +1100 Subject: [Tutor] how to write a string into a specific line in a file In-Reply-To: <00f901c641d8$dbeb7360$0b01a8c0@xp> References: <440D5ED1.1010104@dfx.co.jp> <00f901c641d8$dbeb7360$0b01a8c0@xp> Message-ID: <20060308114121.GA2677@ozzmosis.com> On Tue, Mar 07, 2006 at 11:18:27AM -0000, Alan Gauld wrote: > > I was wondering if it is possible to write a string to a specific line > > in a file without reading in the whole file in as the below. > > Some languages, such as COBOL and some BASICs etc support > random access files, unfortunately Python doesn't (Although I'll be > amazed if somebody hasn't cooked up (or is cooking up) a module > that does it) You then go on to mention file.seek(). I thought that seek() provided "random access", ie. to seek to anywhere at random in a file. Can you clarify what you mean by "random access files"? Regards Andrew From cspears2002 at yahoo.com Wed Mar 8 18:32:43 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 8 Mar 2006 09:32:43 -0800 (PST) Subject: [Tutor] how does this list comprehension work? Message-ID: <20060308173243.25043.qmail@web51607.mail.yahoo.com> I copied this program from Learning Python and got it to work on Windows XP: import sys, glob print sys.argv[1:] sys.argv = [item for arg in sys.argv for item in glob.glob(arg)] print sys.argv[1:] What the program does is first print the glob and then a list of everything caught by the glob. For example: ['*.py'] ['showglob.py'] The key to the script is the list comprehension, which I am having trouble dissecting. How do I go about trying to figure out how it works? "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 Wed Mar 8 19:32:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Mar 2006 13:32:31 -0500 Subject: [Tutor] how does this list comprehension work? In-Reply-To: <20060308173243.25043.qmail@web51607.mail.yahoo.com> References: <20060308173243.25043.qmail@web51607.mail.yahoo.com> Message-ID: <440F233F.4050102@tds.net> Christopher Spears wrote: > I copied this program from Learning Python and got it > to work on Windows XP: > > import sys, glob > print sys.argv[1:] > sys.argv = [item for arg in sys.argv for item in > glob.glob(arg)] > print sys.argv[1:] > > What the program does is first print the glob and then > a list of everything caught by the glob. For example: > > ['*.py'] > ['showglob.py'] > > The key to the script is the list comprehension, which > I am having trouble dissecting. How do I go about > trying to figure out how it works? A list comprehension is a shortcut for a series of one or more nested for loops and if statements with a list append in the middle of it. The list comp pulls the value to be appended out of the loops but otherwise the order is not affected. Looking at [item for arg in sys.argv for item in glob.glob(arg)] item is the thing that will be appended to the list. The nested for loops are for arg in sys.argv: for item in glob.glob(arg): If you initialize a list outside the loop, and append to it inside the loop, you have the equivalent loops: vals = [] for arg in sys.argv: for item in glob.glob(arg): vals.append(item) Kent From dyoo at hkn.eecs.berkeley.edu Wed Mar 8 19:33:16 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Mar 2006 10:33:16 -0800 (PST) Subject: [Tutor] how does this list comprehension work? In-Reply-To: <20060308173243.25043.qmail@web51607.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0603081013060.27270-100000@hkn.eecs.berkeley.edu> On Wed, 8 Mar 2006, Christopher Spears wrote: > I copied this program from Learning Python and got it to work on Windows > XP: > > import sys, glob > print sys.argv[1:] > sys.argv = [item for arg in sys.argv for item in > glob.glob(arg)] > print sys.argv[1:] > > The key to the script is the list comprehension, which I am having > trouble dissecting. How do I go about trying to figure out how it > works? Hi Chris, Hmmm. Let me stare at it again. > sys.argv = [item for arg in sys.argv for item in > glob.glob(arg)] ... Yikes. to tell the truth, I can't read this either. But it might help if we translated it as this: ###### expandedArguments = [] for arg in sys.argv: for item in glob.glob(arg): expandedArguments.append(item) ###### Does this code make more sense? But I'm not so sure myself that list comprehensions are so good when they get so deeply nested; the nested structure is deceptively obscured in the flatness of that list comprehension. I would have just written the code above instead. Actually, I'd write a function to capture that abstraction of a mapping and appending function. Let's call it "mappend()": ########################################################################## def mappend(f, L): """mappend applies f to each elements in L, and assumes that f returns a list. It collects those results in a single flattened list.""" results = [] for x in L: results.extend(f(x)) return results ########################################################################## (The function name is common to folks who've done Lispy kinds of coding.) And we can see this mappend() function in action: ###### >>> import glob >>> mappend(glob.glob, ['*.txt', '*.doc']) ['sequences.txt', 'foo.txt', 'pub2ara-pipeline_20060216.doc', 'Admission Conditions.doc', 'PhD Offer.doc'] ###### If you have more questions, please feel free to ask. Good luck! From dyoo at hkn.eecs.berkeley.edu Wed Mar 8 19:46:22 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Mar 2006 10:46:22 -0800 (PST) Subject: [Tutor] how to write a string into a specific line in a file In-Reply-To: <20060308114121.GA2677@ozzmosis.com> Message-ID: <Pine.LNX.4.44.0603081033240.27270-100000@hkn.eecs.berkeley.edu> On Wed, 8 Mar 2006, andrew clarke wrote: > On Tue, Mar 07, 2006 at 11:18:27AM -0000, Alan Gauld wrote: > > > > I was wondering if it is possible to write a string to a specific line > > > in a file without reading in the whole file in as the below. > > > > Some languages, such as COBOL and some BASICs etc support > > random access files, unfortunately Python doesn't (Although I'll be > > amazed if somebody hasn't cooked up (or is cooking up) a module > > that does it) > > You then go on to mention file.seek(). I thought that seek() provided > "random access", ie. to seek to anywhere at random in a file. Can you > clarify what you mean by "random access files"? Hi Andrew, I think Alan's referring to be able to go to any arbitrary line in a file or insert arbitrary lines in a file in those other languages. The Python core language gives us random access to a file's byte content by using seek(), but we can't do arbitrary insertion without pushing all the other bytes to the right. If it helps, imagine a list that doesn't allow for insert(), but does allow for appends(). L = ['a', 'c', 'd'] If we wanted to get a 'b' into there in the right place, we could go about it this way: L.append('b') ## ['a', 'c', 'd', 'b'] L[2], L[3] = L[3], L[2] ## ['a', 'c', 'b', 'd'] L[1], L[2] = L[2], L[1] ## ['a', 'b', 'c', 'd'] That is, we bubble the 'b' down. Or looking at it another way, we push and shove everything to the right of our insertion point to make room for the insertion. This impovershed interface is pretty much what we have with files. We're allowed to seek(), read(), and write(), but we're not given insert() as a primitive operation, because that's not an operation that's easy to do with files directly. It's doable, but it's painful and expensive. That's why programs that have to do things like insertion or deletion on a text file will load the file's contents into a list, work on the list, and then spit that list back into the file. It's just easier and faster to use a list as our intermediary. I hope this helps! From alan.gauld at freenet.co.uk Wed Mar 8 22:25:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 8 Mar 2006 21:25:10 -0000 Subject: [Tutor] how to write a string into a specific line in a file References: <440D5ED1.1010104@dfx.co.jp> <00f901c641d8$dbeb7360$0b01a8c0@xp> <20060308114121.GA2677@ozzmosis.com> Message-ID: <012501c642f6$c7dc2800$0b01a8c0@xp> >> Some languages, such as COBOL and some BASICs etc support >> random access files, unfortunately Python doesn't > You then go on to mention file.seek(). I thought that seek() provided > "random access", ie. to seek to anywhere at random in a file. Can you > clarify what you mean by "random access files"? Sure. The languages I'm describing provide the ability to deftine a data record and associate that with a file. The file is declared to be of random access type and this automatically associates an index file with it. The programmer can then go to specific lines directly, read fields out of the line, write new lines directly to the file, delete lines out of the file etc. More or less treating the file as if it were a python list of tuples. The nearest in Python is probably shelve but with the disadvantage that you can only search on the key rather than on any field in the record. To see some examples in MALLARD Basic (one of the ones that I have used in the past - on CP/M!) look here: http://www.fvempel.nl/basic.html (Its got German(or Dutch mebbe given the .nl?) variables and comments but the keywords are in English!) Essentially it is possible to create a Python module to do the same, you just need the index file to hold the byte position for every field of every record. Inserting lines into the middle is actually done by appending and just adding a new index entry. Deletions are done by blanking the file and index entries (maintaining the byte count) Usually a housekeeping routine will tidy things up when the files are closed. Could be an interesting excercise. It could even be based on the bsd database stuff as a starter. The main reason its not popular now is simply that with massive RAM its usually faster and easier to just read the data into memory. If its bigger than that a fuill blown database is a faster option - although several RDBMS are built with ISAM underneath.... PS. For the really curious you can still buy a commercial version of Mallard BASIC from its creators Locomotive Software. I'm not clear whether it is CP/M only or whether they now have a PC version. But there are PC CP/M emulators! More info from Wikipedia: http://en.wikipedia.org/wiki/Mallard_BASIC And for a more coherent explanation of ISAM file access thee is also this: http://en.wikipedia.org/wiki/ISAM Ah! 1984 business computing: BASIC, CP/M, 128K RAM,180K floppies and graphics free text screens... Happy days! :-) HTH, Bet you wish you never asked! :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Mar 8 22:32:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 8 Mar 2006 21:32:47 -0000 Subject: [Tutor] PLC communication with python? References: <20060308055543.1629.qmail@web30504.mail.mud.yahoo.com> Message-ID: <014601c642f7$d8f63fd0$0b01a8c0@xp> > Hello, I would like to write a python script that communicates with > a PLC (programmable logic controller) Assuming your PLC is on a development board on a PC then it might be possible using the serial module interface. Otherwise you probably need to wrap the C API into a Python API using something like SWIG. But thats not a task for the faint harted, especially if you are a novice. If you know a little C then its worth invetigating. > as well as instruments like calipers and things. That will require an interface board and again probably wrapping the API as python using SWIG. You might be able to use serial access or ioctl but it will depend on the interface board and the protocol in use (HPIB for example is probably viable) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Mar 8 22:33:39 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 8 Mar 2006 21:33:39 -0000 Subject: [Tutor] PLC communication with python? References: <20060308055543.1629.qmail@web30504.mail.mud.yahoo.com> <440EB69C.6010606@tds.net> Message-ID: <014a01c642f7$f80f85c0$0b01a8c0@xp> > If it connects to the parallel port there is > http://pyserial.sourceforge.net/pyparallel.html > > or for Windows there is winioport: > http://www.geocities.com/dinceraydin/python/indexeng.html Ooh. I didn't know about these. Thanks for the pointers Kent. Alan G. From aguffabuff at hotmail.com Wed Mar 8 22:56:05 2006 From: aguffabuff at hotmail.com (Ars) Date: Wed, 8 Mar 2006 13:56:05 -0800 Subject: [Tutor] How to monitor streaming data from the internet via modem? Message-ID: <BAY106-DAV1217F59890DC24924C0A8BCAEF0@phx.gbl> Say I want to monitor the data that comes through my modem when I'm running a trading platform (like for stocks) so I can send an alert when a certain condition has been met like the price of a stock. If the trading program is in java or perl, can I just tap into the raw data that trading program is recieving through the modem without interfering with the trading program's own information stream? -Jack -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060308/eacb304a/attachment.html From victorf at google.com Thu Mar 9 00:13:58 2006 From: victorf at google.com (victorf) Date: Wed, 8 Mar 2006 15:13:58 -0800 Subject: [Tutor] Tutor Digest, Vol 25, Issue 18 In-Reply-To: <mailman.65.1141729219.24273.tutor@python.org> Message-ID: <200603082313.k28NDwAa021112@brian.corp.google.com> I need help to connect to db on Linux machine. When I do it manually -all right, try to execute script does not work. My script is simple: ------------------------------------------------------- def Connect3(): #arg=os.system('sql.py --prompt qa2:adsdb inbl27,inbl27,inbl27:root:adsgoogle:qa2ads0,qa2ads1') arg=os.popen('sql.py --prompt qa2:adsdb inbl27,inbl27,inbl27:root:adsgoogle:qa2ads0,qa2ads1') Connect3() ----------------------------------------------------- Thanks in advance, Vic -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of tutor-request at python.org Sent: Tuesday, March 07, 2006 3:00 AM To: tutor at python.org Subject: Tutor Digest, Vol 25, Issue 18 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: search and replace (Danny Yoo) 2. Re: search and replace (Alan Gauld) 3. Re: Functions and random buttons (Alan Gauld) 4. Re: [OT] Shells (Alan Gauld) 5. how to write a string into a specific line in a file (tak) 6. Re: how to write a string into a specific line in a file (tak) ---------------------------------------------------------------------- Message: 1 Date: Tue, 7 Mar 2006 00:13:07 -0800 (PST) From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu> Subject: Re: [Tutor] search and replace To: tak <tak at dfx.co.jp> Cc: tutor at python.org Message-ID: <Pine.LNX.4.44.0603070007220.14307-100000 at hkn.eecs.berkeley.edu> Content-Type: TEXT/PLAIN; charset=US-ASCII > I have a problem finding specific words. > I would like to filter out a word or replace it in a file. > I notices that the re module is good for finding patterns. Hi Tak, Although regular expressions might be overkill for this problem, it can't hurt to know about the Regex HOWTO: http://www.amk.ca/python/howto/regex/ Note that strings can already do simple replacement: ###### >>> 'this is a test hi world'.replace('hi', 'hello') 'thellos is a test hello world' ###### As this example shows, we need to be a bit careful with it. Regexes allow us to do a slightly smarter, word boundary-specific substitution: ###### >>> import re >>> re.sub(r'\bhi\b', 'hello', 'this is a test hi world') 'this is a test hello world' ###### The Regex HOWTO link above is a tutorial on how to use the module effectively. If you have questions, please feel free to bring them up. Good luck! ------------------------------ Message: 2 Date: Tue, 7 Mar 2006 09:33:03 -0000 From: "Alan Gauld" <alan.gauld at freenet.co.uk> Subject: Re: [Tutor] search and replace To: "tak" <tak at dfx.co.jp>, <tutor at python.org> Message-ID: <00ca01c641ca$21f26210$0b01a8c0 at xp> Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original Hi tak, > hello, Othello. # just the hello and not Othello One simplistic approach that does not use regex is to search for spaces as part of the string. But that doesn't work for punctuation nor at the start or end of lines. So that leaves us, as you observed, with regular expressions. regex allows us to specify certain conditions in the patterns such as whether the characters are digits etc, and also whether we are kooking for a word which is wat you want. Specifically \W signifies a word boundary so \Whello\W will find hello as a word. Take a look at my tutorial topic on regex for more detail, or go to the excellent regex How-To linked from the Python site. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ------------------------------ Message: 3 Date: Tue, 7 Mar 2006 09:42:00 -0000 From: "Alan Gauld" <alan.gauld at freenet.co.uk> Subject: Re: [Tutor] Functions and random buttons To: "Simon Stoltze" <cyunem at ofir.dk>, <tutor at python.org> Message-ID: <00cd01c641cb$67e168b0$0b01a8c0 at xp> Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original Simon, > ...I want to make each button clickable The buttons are clickable so I'm not absolutely sure what you mean? Do you mean you want to add some action to them when they are clicked? Thats done with the command option in Tkinter. define a function and assign it to the button. In this case it will likely be the same function for all buttons so you might want to do a wee bit of trickery like: def func(x,y): #x,y the button coords # do something here for i in range(length): for j in range(length): self.dict['%s%s' % (i, j)] = Button(sel.frame, text = ' ' command = lambda x=i,y=j: func(x,y)) That uses the default values of the lambda function to pass the coords of the button being pressed to your generic function. func can then use those coords to address the button in the dictionary to update the label or appearance etc. One other wee point: self.dict['%s%s' % (i, j)].grid(row = i, column = j) You don't need to use a string for a key in a dictionary, the tuple will be just fine so you can replace the string formatting stuff with: self.dict[(i, j)].grid(row = i, column = j) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ------------------------------ Message: 4 Date: Tue, 7 Mar 2006 10:04:30 -0000 From: "Alan Gauld" <alan.gauld at freenet.co.uk> Subject: Re: [Tutor] [OT] Shells To: "John Fouhy" <john at fouhy.net>, "Python Tutor" <tutor at python.org> Message-ID: <00dd01c641ce$887909e0$0b01a8c0 at xp> Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original Hi john, > Agreed --- but the new Microsoft shell looks very interesting. > Ars has a good review of it here: > http://arstechnica.com/guides/other/msh.ars Nice heads-up. I hadn't heard of this before, despite reading several of the comics' views on Vista. It looks promising, although without good command line editing and the ability to create active GUIs it will be limited. But then, you can't do GUIs in bash either... But an OO pipeline is interesting, I wonder how long before somebody in Linux comes up with a new shell mechanism for that? Thanks again, Alan G. ------------------------------ Message: 5 Date: Tue, 07 Mar 2006 19:22:09 +0900 From: tak <tak at dfx.co.jp> Subject: [Tutor] how to write a string into a specific line in a file To: tutor at python.org Message-ID: <440D5ED1.1010104 at dfx.co.jp> Content-Type: text/plain; charset=ISO-2022-JP Hello, I was wondering if it is possible to write a string to a specific line in a file without reading in the whole file in as the below. ___________________________________________________________________ f = open(filename) lines = f.readlines() f.close() # num for some line number line[num] = "String" f = open(filename) f.writelines(lines) f.close() ____________________________________________________________________ Writing directly to the line number would be ideal. Some thing like: f.write(line number, string) if there is a function like that. Or would the best way to do line replacement be through iteration. __________________________________________________________________ for line in open(filename): # write to current line??? _________________________________________________________________ Thank you. Best regards, Tak ------------------------------ Message: 6 Date: Tue, 07 Mar 2006 19:29:51 +0900 From: tak <tak at dfx.co.jp> Subject: Re: [Tutor] how to write a string into a specific line in a file To: tutor at python.org Message-ID: <440D609F.1060207 at dfx.co.jp> Content-Type: text/plain; charset=us-ascii Sorry, I meant lines in line in the below: f = open(filename) lines = f.readlines() f.close() # num for some line number >>lines[num] = "String" f = open(filename) f.writelines(lines) f.close() ******************************************************************* Hello, I was wondering if it is possible to write a string to a specific line in a file without reading in the whole file in as the below. ___________________________________________________________________ f = open(filename) lines = f.readlines() f.close() # num for some line number line[num] = "String" f = open(filename) f.writelines(lines) f.close() ____________________________________________________________________ Writing directly to the line number would be ideal. Some thing like: f.write(line number, string) if there is a function like that. Or would the best way to do line replacement be through iteration. __________________________________________________________________ for line in open(filename): # write to current line??? _________________________________________________________________ Thank you. Best regards, Tak ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 25, Issue 18 ************************************* From kp8 at mac.com Thu Mar 9 00:47:01 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 8 Mar 2006 18:47:01 -0500 Subject: [Tutor] module imports Message-ID: <2f6ca401b9bc1698509cbded22193303@mac.com> i have a module called foo.py foo.py imports random kp.py imports foo.py ... but in kp.py i also need to use stuff from random... so kp.py also imports random.... but i prolly shouldn't do that right? Cause now, haven't i needlessly copied the same names/attributes/methods/functions to 2 namespaces... I get very confused about imports... and accessing names from other spaces and such... and efficiency. i have 2 or more modules all of which need to access a given function or method, what is the best way to do that. i am so cornfused From alan.gauld at freenet.co.uk Thu Mar 9 00:47:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 8 Mar 2006 23:47:51 -0000 Subject: [Tutor] How to monitor streaming data from the internet via modem? References: <BAY106-DAV1217F59890DC24924C0A8BCAEF0@phx.gbl> Message-ID: <018401c6430a$b6b8b4d0$0b01a8c0@xp> > If the trading program is in java or perl, can I just tap into the raw > data that trading program is recieving through the modem without > interfering with the trading program's own information stream? Assuming it turns into IP data at some satage then you can get several programs - some are even free! - that will sniff IP packets and either log them to a file or display them on a screen. This can run in background with only slight impact on performance. So you can use Popen to capture the output and analyze it. Search for 'packet sniffer' on Google. Ethereal is one well known and powerful one, but there are others which may be simpler to use. Here is one web site that lists a few: http://netsecurity.about.com/cs/hackertools/a/aafreepacsniff.htm Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Mar 9 00:55:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 8 Mar 2006 23:55:47 -0000 Subject: [Tutor] Connecting to DB References: <200603082313.k28NDwAa021112@brian.corp.google.com> Message-ID: <018801c6430b$d26678b0$0b01a8c0@xp> Please use meangingful subject lines. I've changed this one. >I need help to connect to db on Linux machine. > When I do it manually -all right, try to execute script does not work. I'm not quite sure what you expect here but... > My script is simple: > ------------------------------------------------------- > def Connect3(): > #arg=os.system('sql.py --prompt qa2:adsdb > inbl27,inbl27,inbl27:root:adsgoogle:qa2ads0,qa2ads1') > arg=os.popen('sql.py --prompt qa2:adsdb > inbl27,inbl27,inbl27:root:adsgoogle:qa2ads0,qa2ads1') > > Connect3() Your script is simple but does nothing useful. It calls popen with a command line(which is the one I assume you used at the command line?) and stores the pipe returned by popen in arg. It then exits the function which deletes arg and therefore the pipe and its connection. At no point do you try to read the output from your commandline, nor do you return anything to the outer part of your script. And of course we have no idea what sql.py does inside, so I'll just assume it works as intended for now What did you think this would do? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From annaraven at gmail.com Thu Mar 9 00:57:27 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Wed, 8 Mar 2006 15:57:27 -0800 Subject: [Tutor] how does this list comprehension work? In-Reply-To: <20060308173243.25043.qmail@web51607.mail.yahoo.com> References: <20060308173243.25043.qmail@web51607.mail.yahoo.com> Message-ID: <cb361a610603081557y39ff6804j66dc322be5b473fa@mail.gmail.com> On 3/8/06, Christopher Spears <cspears2002 at yahoo.com> wrote: > > I copied this program from Learning Python and got it > to work on Windows XP: > > import sys, glob > print sys.argv[1:] > sys.argv = [item for arg in sys.argv for item in > glob.glob(arg)] > print sys.argv[1:] > > What the program does is first print the glob and then > a list of everything caught by the glob. For example: > > ['*.py'] > ['showglob.py'] > > The key to the script is the list comprehension, which > I am having trouble dissecting. How do I go about > trying to figure out how it works? Hi Christopher, Others have ably deciphered this particular list comprehension (LC) for you. I'm curious though, are you having trouble because this is a nested list comprehension or do you not have a good grasp on LCs in general? They can be a little tricky to grok at first. In case you're not completely clear on LCs in general, here's a bit more description. If you are clear, just skip to the next email. ;-) First off - a list comprehension creates a new list. It does so by pulling items from an existing list or other iterable object. So, for example: newlist = [item for item in oldlist] print newlist This example wasn't terribly useful - it just made a new list. You can, however, *do* stuff to the item as you're passing it to the new list. For example, if you want the squares of the items in the old list, you coudl do: oldlist = [1,2,3] sqlist = [item*item for item in oldlist] Another thing you can do is filter the items in the old list in some way. So, if you only want the even numbers you could do: elist = [item for item in oldlist if item%2==0] # using modulo, which returns the remainder You can use LCs with files, with dicts, with strings, with any iterable object. It's really slick, really easy, pretty fast. LCs can be a little tricky, like I mentioned (especially when nested) but are quite handy and fun once you get to know them. Just don't get so tricky that it's hard to read your code. If it's getting hard to read, use a for loop. HTH, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060308/90489047/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Mar 9 01:05:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Mar 2006 16:05:52 -0800 (PST) Subject: [Tutor] Using os.popen() In-Reply-To: <200603082313.k28NDwAa021112@brian.corp.google.com> Message-ID: <Pine.LNX.4.44.0603081556001.31241-100000@hkn.eecs.berkeley.edu> Hi Victor, Meta notes: if you're replying to a message, please make sure that message is relevant to what you're asking. You just replied to the digest and included its whole contents back at the list, which is not useful. In this particular case, it makes more sense to send a new message to the mailing list, not a reply to the archive. Furthermore, please try to make the subject line relevant to your question. I've changed it to 'Connection to a database', since that's what you're asking about. I'm a stickler for these things because doing these things makes the archive at: http://mail.python.org/pipermail/tutor/2006-March/thread.html#start more pleasant. If all the messages in that archive were labeled as "Re: [Tutor] Tutor Digest, Vol 25, Issue 18", that would greatly reduce the usefulness of the archive. Anyway, to your question: > I need help to connect to db on Linux machine. > When I do it manually -all right, try to execute script does not work. > My script is simple: > ------------------------------------------------------- > def Connect3(): > arg=os.popen('sql.py --prompt qa2:adsdb > inbl27,inbl27,inbl27:root:adsgoogle:qa2ads0,qa2ads1') Can you be more specific than "does not work"? Do you see a syntax or runtime error, or nothing, or...? Do you see any output at all? I'm trying to impress the idea that many of us on the list are not psychic. You have to help us with our shortcomings! *grin* I'll assume for the moment that you're using some kind of Unix. What happens if you type: $ sql.py --prompt ... at that directory? I would be surprised if this worked, because your path should not include your current working directory unless you've changed it explicitly. Anyway, good luck to you! From bgailer at alum.rpi.edu Thu Mar 9 01:09:37 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 08 Mar 2006 16:09:37 -0800 Subject: [Tutor] module imports In-Reply-To: <2f6ca401b9bc1698509cbded22193303@mac.com> References: <2f6ca401b9bc1698509cbded22193303@mac.com> Message-ID: <440F7241.9090805@alum.rpi.edu> kevin parks wrote: > i have a module called foo.py > > foo.py imports random > > kp.py imports foo.py ... but in kp.py i also need to use stuff from > random... > > so kp.py also imports random.... > > but i prolly shouldn't do that right? > Wrong. > Cause now, haven't i needlessly copied the same > names/attributes/methods/functions to 2 namespaces... > The first import of a module runs its top level code, and creates a module object. Subsequent imports simply place a reference to that object in the current namespace. > I get very confused about imports... and accessing names from other > spaces and such... > and efficiency. > > i have 2 or more modules all of which need to access a given function > or method, what is the best way to do that. > Put the function in a module and import it as needed. > i am so cornfused > Apparently. Even your spell checker is addled. From kp8 at mac.com Thu Mar 9 01:18:22 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 8 Mar 2006 19:18:22 -0500 Subject: [Tutor] module imports In-Reply-To: <440F7241.9090805@alum.rpi.edu> References: <2f6ca401b9bc1698509cbded22193303@mac.com> <440F7241.9090805@alum.rpi.edu> Message-ID: <91bf02151cd56e0ed5f1d978d0bc51a3@mac.com> On Mar 8, 2006, at 7:09 PM, Bob Gailer wrote: > kevin parks wrote: >> i have a module called foo.py >> >> foo.py imports random >> >> kp.py imports foo.py ... but in kp.py i also need to use stuff from >> random... >> >> so kp.py also imports random.... >> >> but i prolly shouldn't do that right? >> > Wrong. so it is okay to do that? >> Cause now, haven't i needlessly copied the same >> names/attributes/methods/functions to 2 namespaces... >> > The first import of a module runs its top level code, and creates a > module object. Subsequent imports simply place a reference to that > object in the current namespace. >> I get very confused about imports... and accessing names from other >> spaces and such... >> and efficiency. >> >> i have 2 or more modules all of which need to access a given function >> or method, what is the best way to do that. >> > Put the function in a module and import it as needed. but i mean a function from a standard module. >> i am so cornfused >> > Apparently. Even your spell checker is addled. [that was a joke] so let's say i have a script called foo.py. foo.py uses some things from the random module and therefore has import random import kp import sys import time etc. & co. in it but foo.py also imports a module kp which also happens to import random. Should i only be importing random once or are you saying it is just fine to import a module that imports another module that you actually have already imported. -kp-- From adam at lumanation.com Thu Mar 9 01:46:51 2006 From: adam at lumanation.com (=?iso-8859-1?Q?adam?=) Date: Thu, 09 Mar 2006 00:46:51 +0000 Subject: [Tutor] how to read a text file, and find items in it Message-ID: <20060309004651.21510.qmail@hosting335.com> hey guys! I am trying to learn a bit of python, and thought it would be a challenge to make a script that reads a text file and returns all the instances of a word I specify. Basically a find and then a list of all the finds. I am using a text file with some random words in it to test it out on Thanks! Adam My script so far is this: --------------------------------- import fileinput print print "Welcome to LIST YOUR FILEINS script" print print "STEP 01" print "drag'n'drop your script from the Finder here" script = raw_input(">") print print "The location of your script is" print script print file=open(script) text=file.readlines() f = 'file' for f in text: print f ---------------------------------------- The test file: random words file in filein mac From kent37 at tds.net Thu Mar 9 02:55:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Mar 2006 20:55:46 -0500 Subject: [Tutor] module imports In-Reply-To: <91bf02151cd56e0ed5f1d978d0bc51a3@mac.com> References: <2f6ca401b9bc1698509cbded22193303@mac.com> <440F7241.9090805@alum.rpi.edu> <91bf02151cd56e0ed5f1d978d0bc51a3@mac.com> Message-ID: <440F8B22.1010602@tds.net> kevin parks wrote: > so let's say i have a script called foo.py. > foo.py uses some things from the random module and therefore has > > import random > import kp > import sys > import time > > etc. & co. in it > > but foo.py also imports a module kp which also > happens to import random. > > Should i only be importing random once or are you saying it > is just fine to import a module that imports another module that > you actually have already imported. It's fine. Each module that needs to use random (for example) should import it. Only the first import to be executed has any appreciable cost; the subsequent ones just put a reference to the already-loaded and cached module into the current module namespace. Kent From francescoqueirolo at yahoo.com Thu Mar 9 08:46:37 2006 From: francescoqueirolo at yahoo.com (Francesco Queirolo) Date: Wed, 8 Mar 2006 23:46:37 -0800 (PST) Subject: [Tutor] Python interpreter/Xemacs and the py-execute-buffer Message-ID: <20060309074637.30761.qmail@web60713.mail.yahoo.com> Greetings, I have been using Xemacs 21.4 Patch 13 on Windows XP with Python 2.4.2 (final). Whenever I try to run a script inside the xemacs window using: C-c C-c I get the following: Opening output file: Invalid argument, C:\Documents and Settings\jkat\Local Settings\Temp;C:\Devel\emacsk2AS2x and of course my code doesn't pop the output up to the xemacs screen. The last part of the error message "k2AS2x" is different every time. I have already re-installed xemacs and am rather baffled after creating folders called Devel and temp as well. Thanks, Francesco Francesco Queirolo (+1)505.661.2670 francescoqueirolo at yahoo.com --------------------------------- Yahoo! Mail Bring photos to life! New PhotoMail makes sharing a breeze. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060308/0a2afb8c/attachment.html From alan.gauld at freenet.co.uk Thu Mar 9 09:00:32 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Mar 2006 08:00:32 -0000 Subject: [Tutor] how to read a text file, and find items in it References: <20060309004651.21510.qmail@hosting335.com> Message-ID: <01b701c6434f$8aa0a8e0$0b01a8c0@xp> Hi Adam, Its not really clear what you want us to do, so I;ll just make some general comments on the code... In future it would help if you tell us whether there is a problem, and if so what iut is, including any error text. Or whether you would just like a critique of your code. > I am trying to learn a bit of python, and thought it would be a challenge > to make a script that reads a text file and returns all the instances of a > word > I specify. Basically a find and then a list of all the finds. Basically a python version of the standard grep command... :-) > I am using a text file with some random words in it to test it out on > import fileinput > > print > print "Welcome to LIST YOUR FILEINS script" Instead of two prints you can just print a newline character: print "\nWelcome to LIST YOUR FILEINS script" Or use a triple quoted string: print """ Welcome to LIST YOUR FILEINS script""" > print "drag'n'drop your script from the Finder here" > script = raw_input(">") I assume you are on a Mac? Interestingly I didn't know the Terminal supported drag n drop from finder. Pretty neat! > print > print "The location of your script is" > print script > print Again you could replace all of that with: print "\nThe location of your script is", script, "\n\n" Or use string formatting print "\nThe location of your script is %s\n\n" % script > file=open(script) > text=file.readlines() > f = 'file' > for f in text: print f you can iterate over the file directly so you could just use for f in file: print f But I think you didn't really want to use f. The for loop replaces the value of f with each line in your file. What I think you wanted - using more meaningful names! - is: word = 'file' for line in file: if word in line: print line HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From mail at ozzmosis.com Thu Mar 9 13:50:22 2006 From: mail at ozzmosis.com (andrew clarke) Date: Thu, 9 Mar 2006 23:50:22 +1100 Subject: [Tutor] Python interpreter/Xemacs and the py-execute-buffer In-Reply-To: <20060309074637.30761.qmail@web60713.mail.yahoo.com> References: <20060309074637.30761.qmail@web60713.mail.yahoo.com> Message-ID: <20060309125022.GA36554@ozzmosis.com> On Wed, Mar 08, 2006 at 11:46:37PM -0800, Francesco Queirolo wrote: > I have been using Xemacs 21.4 Patch 13 on Windows XP with Python 2.4.2 > (final). Whenever I try to run a script inside the xemacs window using: > C-c C-c I get the following: Opening output file: Invalid argument, > C:\Documents and Settings\jkat\Local Settings\Temp;C:\Devel\emacsk2AS2x > and of course my code doesn't pop the output up to the xemacs screen. > The last part of the error message "k2AS2x" is different every time. I > have already re-installed xemacs and am rather baffled after creating > folders called Devel and temp as well. I wonder if it's because there are spaces in the filename. Just a guess. Regards Andrew From benvinger at googlemail.com Thu Mar 9 13:57:53 2006 From: benvinger at googlemail.com (Ben Vinger) Date: Thu, 9 Mar 2006 12:57:53 +0000 Subject: [Tutor] How to monitor streaming data from the internet via modem? In-Reply-To: <018401c6430a$b6b8b4d0$0b01a8c0@xp> References: <BAY106-DAV1217F59890DC24924C0A8BCAEF0@phx.gbl> <018401c6430a$b6b8b4d0$0b01a8c0@xp> Message-ID: <a4a2301f0603090457n388cc9ebud3fabc8feaa234a0@mail.gmail.com> On 3/8/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > Ethereal is one well known > and powerful one, but there are others which may be simpler to > use. Yes, with Ethereal comes a command-line version called tethereal, which I've used within Python on both Windows and Linux. It worked nicely for trafic analysis, but if you're interested only in the clear text passing through the line, I'd think of using netcat. (Sorry Alan, my previous attempt went straight to you instead of the list) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060309/3294d406/attachment.htm From w.richert at gmx.net Thu Mar 9 14:44:35 2006 From: w.richert at gmx.net (Willi Richert) Date: Thu, 9 Mar 2006 14:44:35 +0100 Subject: [Tutor] Test code organization Message-ID: <200603091444.36066.w.richert@gmx.net> Hi, for some time I try to find the best test code organization. I've come up with the following solution, which I guess is not optimal. Please comment. In the code directory there is a special tests directory, which contains all the unit test files. There is the file alltests.py which collects all python test files and executes them: ===================================== import sys, unittest sys.path.append(".") sys.path.append("..") TEST_DIR = "tests" import glob testCases = [t.split(".")[0] for t in glob.glob1(TEST_DIR, "*Tests.py")] print "Found test case modules "+", ".join(testCases) print for t in testCases: exec("from %s import %s"%(TEST_DIR, t)) def suite(): exec("suites = tuple([x.suite() for x in [%s]])"%str(", ".join(testCases))) suite = unittest.TestSuite(suites) return suite if __name__ == '__main__': suite = suite() result = unittest.TextTestRunner(verbosity=2).run(suite) if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) ====================================== For every class to test I create a ClassTests.py file which contains the following code: Header: ====================================== import sys sys.path.append("..") import unittest from Class... import * ====================================== The footer parses the available test classes: ====================================== def _testclasses(): mod = sys.modules[__name__] return [getattr(mod, name) for name in dir(mod) if name.endswith('TestCase')] def suite(): return unittest.TestSuite([unittest.makeSuite(tc) for tc in _testclasses()]) if __name__ == '__main__': unittest.main() ====================================== What smalls badly is the sys.path.append() stuff every test file must have. Improvements? Thanks for any comment, wr -- Gruss, wr -- Dipl.-Inform. Willi Richert C-LAB - Cooperative Computing & Communication Laboratory der Universit?t Paderborn und Siemens FU.323 F?rstenallee 11 D-33102 Paderborn Tel: +49 5251 60 6120 Fax: +49 5251 60 6165 http://www.c-lab.de From francescoqueirolo at yahoo.com Thu Mar 9 15:03:44 2006 From: francescoqueirolo at yahoo.com (Francesco Queirolo) Date: Thu, 9 Mar 2006 06:03:44 -0800 (PST) Subject: [Tutor] Python interpreter/Xemacs and the py-execute-buffer In-Reply-To: <20060309125022.GA36554@ozzmosis.com> Message-ID: <20060309140344.85157.qmail@web60721.mail.yahoo.com> Cheers Andrew. Well that's certainly possible, but the error message is generated by xemacs and I have no idea how to change paths for something like this. Any ideas? Thanks, Francesco andrew clarke <mail at ozzmosis.com> wrote: On Wed, Mar 08, 2006 at 11:46:37PM -0800, Francesco Queirolo wrote: > I have been using Xemacs 21.4 Patch 13 on Windows XP with Python 2.4.2 > (final). Whenever I try to run a script inside the xemacs window using: > C-c C-c I get the following: Opening output file: Invalid argument, > C:\Documents and Settings\jkat\Local Settings\Temp;C:\Devel\emacsk2AS2x > and of course my code doesn't pop the output up to the xemacs screen. > The last part of the error message "k2AS2x" is different every time. I > have already re-installed xemacs and am rather baffled after creating > folders called Devel and temp as well. I wonder if it's because there are spaces in the filename. Just a guess. Regards Andrew Francesco Queirolo (+1)505.661.2670 francescoqueirolo at yahoo.com --------------------------------- Relax. Yahoo! Mail virus scanning helps detect nasty viruses! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060309/b00e4110/attachment.html From alan.gauld at freenet.co.uk Thu Mar 9 15:15:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 9 Mar 2006 14:15:03 -0000 Subject: [Tutor] Python interpreter/Xemacs and the py-execute-buffer References: <20060309074637.30761.qmail@web60713.mail.yahoo.com> Message-ID: <000f01c64383$dcef39c0$0b01a8c0@xp> This is pure guesswork... > I have been using Xemacs 21.4 Patch 13 on Windows XP with Python 2.4.2 > (final). > using: C-c C-c I get the following: Opening output file: Invalid argument, > C:\Documents and Settings\jkat\Local Settings\Temp;C:\Devel\emacsk2AS2x > > The last part of the error message "k2AS2x" is different every time. I suspect that it is a temporary file with an auto generated filename. In addition to creating the C:\Devel folder did you make it globally writeable? If that aint it then I'm, stuck, sorry, Alan G. From mail at ozzmosis.com Thu Mar 9 15:31:30 2006 From: mail at ozzmosis.com (andrew clarke) Date: Fri, 10 Mar 2006 01:31:30 +1100 Subject: [Tutor] How to monitor streaming data from the internet via modem? In-Reply-To: <a4a2301f0603090457n388cc9ebud3fabc8feaa234a0@mail.gmail.com> References: <BAY106-DAV1217F59890DC24924C0A8BCAEF0@phx.gbl> <018401c6430a$b6b8b4d0$0b01a8c0@xp> <a4a2301f0603090457n388cc9ebud3fabc8feaa234a0@mail.gmail.com> Message-ID: <20060309143130.GA37277@ozzmosis.com> On Thu, Mar 09, 2006 at 12:57:53PM +0000, Ben Vinger wrote: > On 3/8/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > > Ethereal is one well known and powerful one, but there are others > > which may be simpler to use. > > Yes, with Ethereal comes a command-line version called tethereal, which I've > used within Python on both Windows and Linux. It worked nicely for trafic > analysis, but if you're interested only in the clear text passing through > the line, I'd think of using netcat. tcpflow may also be worth a look. http://www.circlemud.org/~jelson/software/tcpflow/ Regards Andrew From kermit at polaris.net Thu Mar 9 19:53:39 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 9 Mar 2006 13:53:39 -0500 (Eastern Standard Time) Subject: [Tutor] Connection time out while attempting to install SOAP Message-ID: <441079B3.000007.03832@YOUR-4105E587B6> I attempted to follow instructions from "Dive into Python" to install the SOAP package. The first step went ok. The second step is not yet accomplished. 12.2.2. Installing fpconst The second library you need is fpconst, a set of constants and functions for working with IEEE754 double-precision special values. This provides support for the special values Not-a-Number (NaN), Positive Infinity (Inf), and Negative Infinity (-Inf), which are part of the SOAP datatype specification. Procedure 12.2. Here is the procedure for installing fpconst: The download of fpconst failed because Download the latest version of fpconst from http://www.analytics.washington.edu/statcomp/projects/rzope/fpconst/ timed out while attempting to reach the web page. Is this the only site that has this second step of programs. Has it moved? Should I keep on trying the same site? *********** 1. There are two downloads available, one in .tar.gz format, the other in .zip format. If you are using Windows, download the .zip file; otherwise, download the .tar.gz file. 2. Decompress the downloaded file. On Windows XP, you can right-click on the file and choose Extract All; on earlier versions of Windows, you will need a third-party program such as WinZip. On Mac OS X, you can double-click the compressed file to decompress it with Stuffit Expander. 3. 4. Open a command prompt and navigate to the directory where you decompressed the fpconst files. 5. Type python setup.py install to run the installation program. To verify that you installed fpconst correctly, run your Python IDE and check the version number. From richert at c-lab.de Thu Mar 9 13:47:13 2006 From: richert at c-lab.de (Willi Richert) Date: Thu, 09 Mar 2006 13:47:13 +0100 Subject: [Tutor] Test code organization Message-ID: <441023D1.9010903@c-lab.de> Hi, for some time I try to find the best test code organization. I've come up with the following solution, which I guess is not optimal. Please comment. In the code directory there is a special tests directory, which contains all the unit test files. There is the file alltests.py which collects all python test files and executes them: ===================================== import sys, unittest sys.path.append(".") sys.path.append("..") TEST_DIR = "tests" import glob testCases = [t.split(".")[0] for t in glob.glob1(TEST_DIR, "*Tests.py")] print "Found test case modules "+", ".join(testCases) print for t in testCases: exec("from %s import %s"%(TEST_DIR, t)) def suite(): exec("suites = tuple([x.suite() for x in [%s]])"%str(", ".join(testCases))) suite = unittest.TestSuite(suites) return suite if __name__ == '__main__': suite = suite() result = unittest.TextTestRunner(verbosity=2).run(suite) if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) ====================================== For every class to test I create a ClassTests.py file which contains the following code: Header: ====================================== import sys sys.path.append("..") import unittest from Class... import * ====================================== The footer parses the available test classes: ====================================== def _testclasses(): mod = sys.modules[__name__] return [getattr(mod, name) for name in dir(mod) if name.endswith('TestCase')] def suite(): return unittest.TestSuite([unittest.makeSuite(tc) for tc in _testclasses()]) if __name__ == '__main__': unittest.main() ====================================== What smalls badly is the sys.path.append() stuff every test file must have. Improvements? Thanks for any comment, wr From dyoo at hkn.eecs.berkeley.edu Thu Mar 9 21:53:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Mar 2006 12:53:51 -0800 (PST) Subject: [Tutor] Python interpreter/Xemacs and the py-execute-buffer In-Reply-To: <20060309074637.30761.qmail@web60713.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0603091242400.1928-100000@hkn.eecs.berkeley.edu> > I have been using Xemacs 21.4 Patch 13 on Windows XP with Python 2.4.2 > (final). Whenever I try to run a script inside the xemacs window using: > C-c C-c I get the following: Opening output file: Invalid argument, > C:\Documents and Settings\jkat\Local Settings\Temp;C:\Devel\emacsk2AS2x Hi Francesco, Hmmm. This looks like it might be a bug in the python bindings that xemacs is using. If you are using python-mode.el, then you may want to send this off to SF as a bug report. http://sourceforge.net/tracker/?atid=581349&group_id=86916&func=browse If you're using the python bindings built into xemacs, I think you need to contact the xemacs folks then. Assuming that you're using python-mode.el, offhand, does running the Python interpreter "C-c !" work for you? If so, then once the *Python* buffer is up, does "C-c C-c" work then? Are you using the latest python-mode.el? http://wiki.python.org/moin/EmacsPythonMode http://sourceforge.net/project/showfiles.php?group_id=86916 Good luck! From tvbare at socket.net Fri Mar 10 00:18:46 2006 From: tvbare at socket.net (->Terry<-) Date: Thu, 9 Mar 2006 17:18:46 -0600 (CST) Subject: [Tutor] htmllib vs re question Message-ID: <Pine.LNX.4.64.0603091626170.1913@elwood.hillbillyhaven.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I want to parse some text from an HTML file that contains blocks of pre-formatted text. All I'm after is what's between the <pre> and </pre> tags. My first thought was to use re for this, but looking through the Library Reference, I see the htmllib module. Is htmllib overkill for this job? The HTML file size varies, but I don't expect the size to exceed 150-200k. Speed is not a bug concern. What is the Pythonic way and why? Any recommendations or comments? Thanks, - -- Terry <tvbareATsocketDOTnet> -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFEELfcQvSnsfFzkV0RAreaAJ9qvD5GoA5a0qD15Wr0hJ4XLLNhiQCeKd1R XIqBMZWoIY66y8r5Rtgevqc= =cUhn -----END PGP SIGNATURE----- From rschroev_nospam_ml at fastmail.fm Fri Mar 10 00:36:39 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 10 Mar 2006 00:36:39 +0100 Subject: [Tutor] how to write a string into a specific line in a file In-Reply-To: <012501c642f6$c7dc2800$0b01a8c0@xp> References: <440D5ED1.1010104@dfx.co.jp> <00f901c641d8$dbeb7360$0b01a8c0@xp> <20060308114121.GA2677@ozzmosis.com> <012501c642f6$c7dc2800$0b01a8c0@xp> Message-ID: <duqe67$3qh$1@sea.gmane.org> Alan Gauld schreef: > To see some examples in MALLARD Basic (one of the ones that > I have used in the past - on CP/M!) look here: > > http://www.fvempel.nl/basic.html > > (Its got German(or Dutch mebbe given the .nl?) variables and comments > but the keywords are in English!) Yep, it's Dutch. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From amonroe at columbus.rr.com Fri Mar 10 00:56:04 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 9 Mar 2006 18:56:04 -0500 Subject: [Tutor] how to read a text file, and find items in it In-Reply-To: <01b701c6434f$8aa0a8e0$0b01a8c0@xp> References: <20060309004651.21510.qmail@hosting335.com> <01b701c6434f$8aa0a8e0$0b01a8c0@xp> Message-ID: <1081637011778.20060309185604@columbus.rr.com> > I assume you are on a Mac? Interestingly I didn't know the Terminal > supported drag n drop from finder. Pretty neat! The tradeoff is that on the Mac, the home and end keys don't move your cursor to the beginning/end of the commandline you're typing (grrrrrrrr!!!!!!). Alan From struggleyb at gmail.com Fri Mar 10 04:04:25 2006 From: struggleyb at gmail.com (Bo Yang) Date: Fri, 10 Mar 2006 11:04:25 +0800 Subject: [Tutor] Any stuff about python interpreter design ? Message-ID: <4410ECB9.9040409@gmail.com> Hello , I have learned and used python half a year , and I like this language very much . I used it in my web server page , in my homework and part-tiem job . Recently , I feel very interested in the python interpreter . So I take a look into the source code .But I get confused about so many files and functions . I want to ask that is there any stuff about the interpreter design and coding ? Thanks in advance ! Regards ! From kent37 at tds.net Fri Mar 10 04:25:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Mar 2006 22:25:47 -0500 Subject: [Tutor] htmllib vs re question In-Reply-To: <Pine.LNX.4.64.0603091626170.1913@elwood.hillbillyhaven.org> References: <Pine.LNX.4.64.0603091626170.1913@elwood.hillbillyhaven.org> Message-ID: <4410F1BB.7050402@tds.net> ->Terry<- wrote: > I want to parse some text from an HTML file that contains > blocks of pre-formatted text. All I'm after is what's between > the <pre> and </pre> tags. > > The HTML file size varies, but I don't expect the size to exceed > 150-200k. Speed is not a bug concern. > > What is the Pythonic way and why? > > Any recommendations or comments? Try Beautiful Soup http://www.crummy.com/software/BeautifulSoup/ Kent From dyoo at hkn.eecs.berkeley.edu Fri Mar 10 06:04:27 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Mar 2006 21:04:27 -0800 (PST) Subject: [Tutor] Any stuff about python interpreter design ? In-Reply-To: <4410ECB9.9040409@gmail.com> Message-ID: <Pine.LNX.4.44.0603092037300.28135-100000@hkn.eecs.berkeley.edu> > So I take a look into the source code .But I get confused about so many > files and functions . I want to ask that is there any stuff about the > interpreter design and coding ? [meta: my reply is really about Scheme, not Python. My apologies to the list, but it's my honest answer.] Hi Bo, There are several books and online material about the writing of interpreters. The ones that I'm most aware aware of that are aimed at beginner programmers, though, target the language 'Scheme'. The core Scheme language has a fairly minimal syntax and semantics, and it's simple enough that it's not too bad for beginner to understand (and write!) a usable Scheme interpreter. So you may find it useful to learn about interpreters by looking at Scheme interpreters. And even though it's not Python, it's still very related and applicable; if you have a model of how a Scheme interpreter works, you'll be better equipped to understand in general how interpreters work. For example, the textbook "How to Design Programs": http://www.htdp.org/ starts covering the evaluation of a programming language by about Chapter 14: http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-19.html#node_sec_14.4 Here are other Scheme resources about interpretation (the first two links contain online books): http://mitpress.mit.edu/sicp/ http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/ http://www.cs.indiana.edu/eopl/ http://www-spi.lip6.fr/~queinnec/WWW/LiSP.html If you have more questions, please feel free to ask! From struggleyb at gmail.com Fri Mar 10 07:05:32 2006 From: struggleyb at gmail.com (Bo Yang) Date: Fri, 10 Mar 2006 14:05:32 +0800 Subject: [Tutor] Any stuff about python interpreter design ? In-Reply-To: <Pine.LNX.4.44.0603092037300.28135-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0603092037300.28135-100000@hkn.eecs.berkeley.edu> Message-ID: <4411172C.1000303@gmail.com> Danny Yoo said: >> So I take a look into the source code .But I get confused about so many >> files and functions . I want to ask that is there any stuff about the >> interpreter design and coding ? >> > > [meta: my reply is really about Scheme, not Python. My apologies to the > list, but it's my honest answer.] > > Hi Bo, > > There are several books and online material about the writing of > interpreters. The ones that I'm most aware aware of that are aimed at > beginner programmers, though, target the language 'Scheme'. The core > Scheme language has a fairly minimal syntax and semantics, and it's simple > enough that it's not too bad for beginner to understand (and write!) a > usable Scheme interpreter. > > So you may find it useful to learn about interpreters by looking at Scheme > interpreters. And even though it's not Python, it's still very related > and applicable; if you have a model of how a Scheme interpreter works, > you'll be better equipped to understand in general how interpreters work. > > > For example, the textbook "How to Design Programs": > > http://www.htdp.org/ > > starts covering the evaluation of a programming language by about Chapter > 14: > > http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-19.html#node_sec_14.4 > > > Here are other Scheme resources about interpretation (the first two links > contain online books): > > http://mitpress.mit.edu/sicp/ > http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/ > http://www.cs.indiana.edu/eopl/ > http://www-spi.lip6.fr/~queinnec/WWW/LiSP.html > > If you have more questions, please feel free to ask! > > > I feeled the people in this mailing list are very really friendly , I will follow your links and ask again if I have any questions ! Regards ! From dave.jaeckel at arcor.de Fri Mar 10 08:55:35 2006 From: dave.jaeckel at arcor.de (Ferry Dave =?iso-8859-1?q?J=E4ckel?=) Date: Fri, 10 Mar 2006 08:55:35 +0100 Subject: [Tutor] Python and unicode Message-ID: <200603100855.42493.dave.jaeckel@arcor.de> Hello list, I try hard to understand python and unicode support, but don't get it really. What I thought about this until yesterday :) If I write my script in unicode encoding and put the magic # -*- coding: utf-8 -*- at its start, I can just use unicode everywhere without problems. Reading strings in different encodings, I have to decode them, specifying there source encoding, and writing them in different encode i have to encode them, giving the target encoding. But I have problems with printing my strings with print >> sys.stderr, mystring. I get "ASCII codec encoding errors". I'm on linux with python2.4 My programming problem where I'm stumbling about this: I have an xml-file from OO.org writer (encoded in utf-8), and I parse this with sax, getting some values from it. This data should go into a mysql db (as utf-8, too). I think this works quite well, but debug printing gives this errors. What is the right way to handle unicode and maybe different encodings in python? What encoding should be put into the header of the file, and when to use the strings encode and decode methods? Are there modules (as maybe sax) which require special treatment because of lack of full unicode support? In general I'd like to keep all strings as unicode in utf-8, and just convert strings from/to other encodings upon input/output. Regards, Dave -- If you're using anything besides US-ASCII, I *stringly* suggest Python 2.0. -- Uche Ogbuji (A fortuitous typo?), 29 Jan 2001 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060310/6da5da7a/attachment.pgp From janos.juhasz at VELUX.com Fri Mar 10 10:15:38 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 10 Mar 2006 10:15:38 +0100 Subject: [Tutor] Automatic software performance meter In-Reply-To: <mailman.9711.1141712368.27774.tutor@python.org> Message-ID: <OF1FE93D30.48212E95-ONC125712D.00316630-C125712D.0032DEAE@velux.com> Hi All, is it any easy way to mesaure a windows software response time from python script ? I think about a small python script that can open a win32 application, insert a new order with sendkey, deliver the goods, do other things and create a small log file with the different split times. I would like to controll the time needed for a business procedure instead of the ping time :) Yours sincerely, ______________________________ J?nos Juh?sz From singletoned at gmail.com Fri Mar 10 10:44:30 2006 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 10 Mar 2006 09:44:30 +0000 Subject: [Tutor] Dynamically naming functions Message-ID: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> How does one go about creating functions, classes, or callable objects when you don't know their name in advance? (For example you want to read their names in from a text file or database). I want to use this in a few different places. For example Faces, the Python Project Management Planner Tool Thingy, uses nested functions to put tasks within a project: def MyProject(): start = "2006-03-06" resource = Me def Task1(): start = "2006-03-13" def Task2(): effort = "1w" I'd like to load these from a database (using SQLObject), but I'm not sure how I can define the name of the function from a filed in a database (or read in from a text file). I'd also like to be able to do this in CherryPy/TurboGears so that I can create a dynamic site structure based on fields in a database. Thanks Ed From ryang at gol.com Fri Mar 10 11:32:19 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Fri, 10 Mar 2006 19:32:19 +0900 Subject: [Tutor] Problem handling utf-8 text Message-ID: <001e01c6442d$e969a5f0$030ba8c0@RYAN> I am just learning python, or trying to, and am having trouble handling utf-8 text. I want to take a utf-8 encoded web page, and feed it to Beautiful Soup (http://crummy.com/software/BeautifulSoup/). BeautifulSoup uses SGMLParser to parse text. But although I am able to read the utf-8 encoded Japanese text from the web page and print it to a file without corruption, the text coming out of Beautiful Soup is mangled. I imagine it's because the parser thinks I'm giving it a string in the system encoding, which is sjis. Here is the code I am using: # -*- coding: utf-8 -*- # ============================== # Test program to read in utf-8 encoded html page # ============================== import urllib2, pprint from BeautifulSoup import BeautifulSoup # utf-8 encoded content html = urllib2.urlopen( 'http://jat.org/jtt/index.html' ).read() # write the raw html to raw.txt # This comes out ok file1 = open("raw.txt", "w") print >> file1, html file1.close() # write the parsed html to parsed.txt # The Japanese text is garbled in this one file2 = open("parsed.txt", "w") soup = BeautifulSoup() soup.feed( html ) print >> file2, soup.html file2.close() # ============================== Any help much appreciated. Regards, Ryan --- Ryan Ginstrom ryang at gol.com / translation at ginstrom.com http://ginstrom.com From klappnase at freenet.de Fri Mar 10 11:54:06 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 10 Mar 2006 11:54:06 +0100 Subject: [Tutor] Python and unicode In-Reply-To: <200603100855.42493.dave.jaeckel@arcor.de> References: <200603100855.42493.dave.jaeckel@arcor.de> Message-ID: <20060310115406.55f0d397.klappnase@freenet.de> On Fri, 10 Mar 2006 08:55:35 +0100 Ferry Dave J?ckel <dave.jaeckel at arcor.de> wrote: > Hello list, > > I try hard to understand python and unicode support, but don't get it > really. > > What I thought about this until yesterday :) > If I write my script in unicode encoding and put the magic # -*- coding: > utf-8 -*- at its start, I can just use unicode everywhere without problems. > Reading strings in different encodings, I have to decode them, specifying > there source encoding, and writing them in different encode i have to > encode them, giving the target encoding. > > But I have problems with printing my strings with print >> sys.stderr, > mystring. I get "ASCII codec encoding errors". I'm on linux with python2.4 > > My programming problem where I'm stumbling about this: > I have an xml-file from OO.org writer (encoded in utf-8), and I parse this > with sax, getting some values from it. This data should go into a mysql db > (as utf-8, too). I think this works quite well, but debug printing gives > this errors. > > What is the right way to handle unicode and maybe different encodings in > python? > What encoding should be put into the header of the file, and when to use the > strings encode and decode methods? Are there modules (as maybe sax) which > require special treatment because of lack of full unicode support? > In general I'd like to keep all strings as unicode in utf-8, and just > convert strings from/to other encodings upon input/output. > Hi Dave, you should be aware that utf-8 is *not* unicode, but just another encoding. Look here for more details: http://www.joelonsoftware.com/articles/Unicode.html I am not sure what happens in your program, but generally when converting a unicode string into a byte string python assumes to use the ascii codec if no other codec is explicitely specified, which seems to be what occurs. In this case calling encode('utf-8') on the unicode string before processing it may help. If you are using strings in different encodings it is probably the best to convert them all into unicode objects after reading with decode() (however you need to know which codec to use) and to use only unicode internally. However you are right, some modules may not be unicode-proof (i don't know about sax though). You will have to encode these strings again when calling these module's functions. If your program is supposed to run on different systems it may help to know the encoding the system uses if you want to read some files there; you can look at the top of the IOBinding module in idlelib to see how to guess the system encoding. I hope this helps Michael From kent37 at tds.net Fri Mar 10 12:13:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Mar 2006 06:13:51 -0500 Subject: [Tutor] Python and unicode In-Reply-To: <200603100855.42493.dave.jaeckel@arcor.de> References: <200603100855.42493.dave.jaeckel@arcor.de> Message-ID: <44115F6F.5060402@tds.net> Ferry Dave J?ckel wrote: > Hello list, > > I try hard to understand python and unicode support, but don't get it > really. > > What I thought about this until yesterday :) > If I write my script in unicode encoding and put the magic # -*- coding: > utf-8 -*- at its start, I can just use unicode everywhere without problems. > Reading strings in different encodings, I have to decode them, specifying > there source encoding, and writing them in different encode i have to > encode them, giving the target encoding. Yes, this is all good practice. The coding declaration at the start of your program may not be necessary - this declares the encoding of your actual program file. You only need it if, for example, you have utf-8 encoded string constants in the file. It doesn't affect the operation of the program. But your strategy of keeping all strings as unicode, decoding and encoding as they enter and leave the program, is sound. > > But I have problems with printing my strings with print >> sys.stderr, > mystring. I get "ASCII codec encoding errors". I'm on linux with python2.4 stderr and stdout have an encoding too. You can check it by printing sys.stderr.encoding and sys.stdout.encoding. The strings that you print should be converted to the correct encoding just as strings you send to mysql are. You can make this automatic by replacing sys.stdout with a codec wrapper, e.g. sys.stdout = codecs.getwriter('latin-1')(sys.stdout) Hmm, on my Windows machine sys.stderr.encoding is None. sys.stdout.encoding is Cp437. That implies that stderr can't accept encoded characters at all, so you probably need a lenient ascii encoder, for example: sys.stdout = codecs.getwriter('ascii')(sys.stdout, 'backslashreplace') > What is the right way to handle unicode and maybe different encodings in > python? > What encoding should be put into the header of the file, and when to use the > strings encode and decode methods? Are there modules (as maybe sax) which > require special treatment because of lack of full unicode support? > In general I'd like to keep all strings as unicode in utf-8, and just > convert strings from/to other encodings upon input/output. I think you are on the right track, though you are keeping all strings as unicode, not utf-8. There are some modules that have weak unicode support but I don't know specifically which ones. I would expect the XML support to be unicode-aware as utf-8 is common in XML. Kent From kent37 at tds.net Fri Mar 10 12:36:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Mar 2006 06:36:10 -0500 Subject: [Tutor] Dynamically naming functions In-Reply-To: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> Message-ID: <441164AA.5040706@tds.net> Ed Singleton wrote: > How does one go about creating functions, classes, or callable objects > when you don't know their name in advance? (For example you want to > read their names in from a text file or database). > > I want to use this in a few different places. For example Faces, the > Python Project Management Planner Tool Thingy, uses nested functions > to put tasks within a project: > > def MyProject(): > start = "2006-03-06" > resource = Me > > def Task1(): > start = "2006-03-13" > > def Task2(): > effort = "1w" > > I'd like to load these from a database (using SQLObject), but I'm not > sure how I can define the name of the function from a filed in a > database (or read in from a text file). This is truly bizarre use of nested functions. Faces must be looking at the compiled function objects to pick this out. I would look into the Project objects themselves and see if there is a way to create them dynamically, rather than trying to build this structure dynamically at run time. > > I'd also like to be able to do this in CherryPy/TurboGears so that I > can create a dynamic site structure based on fields in a database. This seems more practical. I would define a class that is configured by the database can be used as a CP model object. Then you can insert the class into the CP site structure using setattr(). In general you can set an attribute of an object using setattr(): setattr(foo, 'bar', 3) is the same as foo.bar = 3 but the attribute name is specified as a string so it can be determined at runtime. Kent > > Thanks > > Ed > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at freenet.co.uk Fri Mar 10 13:00:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 10 Mar 2006 12:00:28 -0000 Subject: [Tutor] Dynamically naming functions References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> Message-ID: <001c01c6443a$39b716d0$0b01a8c0@xp> > How does one go about creating functions, classes, or callable objects > when you don't know their name in advance? (For example you want to > read their names in from a text file or database). First point, names of functions are no different to names of other things. def f(x): y = blah.... return y is essentialy the same as saying f = lambda x: blah... lambda defines a nameless (aka anonymous) function and then assigns that function to the variable called f. Of course Pythons lambda construct is a bit brain dead so we can achieve the same result with just assigning an existing function to a new name def f(x): y = nblah... return y g = f Now g is a new name that refers to the function called f. And with nested function definitions we can write functions that return functions: def makeMultiplyAndAdd(constants): def f(x): return constant[0] * constant[1] + x return f > I'd like to load these from a database (using SQLObject), > but I'm not sure how I can define the name of the function > from a field in a database (or read in from a text file). Same way as you would for any other kind of variable. This has been discussed many times and there is some trickery you can do using the built in dictionaries that Python uses for its namespaces. But the biggest proiblem with introducing new names at run time is: How does the existing code get to know about those names that didn't exist when the code was written? Ypou need to have the code go exploring for names, work out what kind ioopf value they hold etc... It all gets very messy and complicated and fault prone. So the normal way to do this is to use a dictionary. The dictionary is a collection of names with values asociated with them. Those values can be functions or classes or anything else. Now your code can access the new names by using standard dictionary iterators etc. All you need are some conventions around how many parameters the functions have, their types etc. > I'd also like to be able to do this in CherryPy/TurboGears > so that I can create a dynamic site structure based on fields > in a database. Dynamic site structure shouldn't need dynamic creation of functions although the structure might need to be dynamically loaded into a data structure in the code. It might also be a parameter of the functions. But as always remember that dynamic anything usually means much harder to maintain. All of your backup/archiving tools and error reporting tools etc will need to understand your dynamic structure too. Dynamic sounds like fun but usually means grief and is only justified as a last resort IMHO! But if you must go dynamic Python is as good a language to do it in as you'll get. Alan G. From kent37 at tds.net Fri Mar 10 14:26:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Mar 2006 08:26:53 -0500 Subject: [Tutor] Problem handling utf-8 text In-Reply-To: <001e01c6442d$e969a5f0$030ba8c0@RYAN> References: <001e01c6442d$e969a5f0$030ba8c0@RYAN> Message-ID: <44117E9D.7060807@tds.net> Ryan Ginstrom wrote: > I am just learning python, or trying to, and am having trouble handling utf-8 > text. > > I want to take a utf-8 encoded web page, and feed it to Beautiful Soup > (http://crummy.com/software/BeautifulSoup/). > BeautifulSoup uses SGMLParser to parse text. > > But although I am able to read the utf-8 encoded Japanese text from the web > page and print it to a file without corruption, the text coming out of > Beautiful Soup is mangled. I imagine it's because the parser thinks I'm > giving it a string in the system encoding, which is sjis. You're not the first person to have trouble with BS and non-ascii text, unfortunately. I wrote a program to test round-tripping data through BS. It turns out that BS is being 'helpful' and converting the chars in the range 0x80 to 0x9F to equivalent entity escapes. This might be useful if the source text is in cp1252 but it is disastrous to utf-8 as you have discovered. A solution is to turn off this fixup (and a few others) by passing avoidParserProblems=False to the BeautifulSoup constructor. Here is a short program that successfully round-trips a selection of utf-8 chars: from BeautifulSoup import BeautifulSoup # Test data includes all codepoints from 32-255 as utf-8 data = ''.join(chr(n) for n in range(32,256)) data = unicode(data, 'latin-1').encode('utf-8') html = '<body>' + data + '</body>' soup = BeautifulSoup(html, avoidParserProblems=False) newData = soup.body.string print repr(data) print print repr(newData) assert data == newData Kent From brainy_muppet at hotmail.com Fri Mar 10 15:34:15 2006 From: brainy_muppet at hotmail.com (sjw28) Date: Fri, 10 Mar 2006 06:34:15 -0800 (PST) Subject: [Tutor] problems with numbers in my python code Message-ID: <3339964.post@talk.nabble.com> Basically, I have a code with is almost finished but I've having difficultly with the last stage of the process. I have a program that gets assigns different words with a different value via looking them up in a dictionary: eg if THE is in the writing, it assigns 0.965 and once the whole passage is read it returns all the numbers in the format as follows: ['0.965', '1.000', '0.291', '1.000', '0.503'] However, I can't seem to get the program to treat the numbers as numbers. If I put them in the dictionary as 'THE' = int(0.965) the program returns 1.0 and if I put 'THE' = float(0.965) it returns 0.96555555549 or something similar. Neither of these are right! I basically need to access each item in the string as a number, because for my last function I want to multiply them all together by each other. I have tried two bits of code for this last bit, but neither are working (I'm not sure about the first one but the second one should work I think if I could figure out how to return the values as numbers): 1st code value = codons[x] * codons[x+1] x = (int) x = 0 print value x +=2 if (x<r): new_value = value * codons[x] value = new_value x +=1 else: print new_value This gives the error message Traceback (most recent call last): File "C:\Python24\code2", line 88, in -toplevel- value = codons[x] * codons[x+1] NameError: name 'x' is not defined Code 2 - the most likely code prod = 1 for item in (codons): prod *= item prod print prod Gives this error message: Traceback (most recent call last): File "C:\Python24\code2", line 90, in -toplevel- for item in (codons): prod *= item TypeError: can't multiply sequence by non-int Can anyone help me solve this problem? Thanks. -- View this message in context: http://www.nabble.com/problems-with-numbers-in-my-python-code-t1259271.html#a3339964 Sent from the Python - tutor forum at Nabble.com. From smiles at worksmail.net Fri Mar 10 15:39:34 2006 From: smiles at worksmail.net (Smith) Date: Fri, 10 Mar 2006 08:39:34 -0600 Subject: [Tutor] *args consumption Message-ID: <041701c64450$91078760$f72c4fca@csmith> I see that one way to use *arg in a function is to simply pass them on to another function that perhaps will unpack the arguments: ### def pass_along(func, *args): return func(*args) def adder(x,y): return x+y def suber(x,y): return x-y print pass_along(adder,1,2) print pass_along(suber,1,2) ### But there is another use that I am looking at right now (as encountered in the turtle module) where the arguments are analyzed in the function and not passed along. In such cases it seems like the first two lines of the function below are needed to get the passed arg out of the tuple form that is created and into the form expected in the function. ### def goto(*arg): if len(arg) == 1: arg = arg[0] x, y = arg print x, y goto(1,2) pt = 1,2 goto(pt) ### Without those first two lines, passing 'pt' as in the example results in a runtime error since arg = ((1, 2),) -- a tuple of length 1 -- cannot be unpacked into two items. MY QUESTION: since the pass_along function will work with this unpacking of length = 1 tuples and this is what you have to do anyway if you are going to consume the tuple in a function (as in the goto function above) is there a reason that this isn't automatically done for star arguments? Am I missing some other usage where you wouldn't want to unpack the *arg? If not, would the following "behind the scenes" behavior be possible/preferred? ### def foo(*arg): pass ### automatically does this ### def foo(*arg): if len(arg) == 1: arg = arg[0] pass ### Chris From hugonz-lists at h-lab.net Fri Mar 10 15:43:09 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 10 Mar 2006 08:43:09 -0600 Subject: [Tutor] problems with numbers in my python code In-Reply-To: <3339964.post@talk.nabble.com> References: <3339964.post@talk.nabble.com> Message-ID: <4411907D.2000603@h-lab.net> Hi, > However, I can't seem to get the program to treat the numbers as numbers. If > I put them in the dictionary as 'THE' = int(0.965) the program returns 1.0 > and if I put 'THE' = float(0.965) it returns 0.96555555549 or something > similar. Neither of these are right! I basically need to access each item in > the string as a number, because for my last function I want to multiply them > all together by each other. The latter is right. Floating point numbers have limited precision (limited by the number of bits used in the representation) The exact number .965 does not exist in the representation for your computer, but smart displaying can be done: >>> .965 0.96499999999999997 >>> print .965 0.965 >>> var = .965 >>> var 0.96499999999999997 >>> print var 0.965 >>> str(var) '0.965' >>> repr(var) '0.96499999999999997' >>> Take a look at apprendix B in the tutorial: Floating Point Arithmetic: Issues and Limitations http://docs.python.org/tut/node16.html Also the decimal module may be the solution to your problem: http://docs.python.org/tut/node13.html#SECTION0013800000000000000000 Hope this clarifies things a bit. Hugo > > I have tried two bits of code for this last bit, but neither are working > (I'm not sure about the first one but the second one should work I think if > I could figure out how to return the values as numbers): > > 1st code > value = codons[x] * codons[x+1] > x = (int) > x = 0 > > print value > > x +=2 > > if (x<r): > new_value = value * codons[x] > value = new_value > x +=1 > else: > print new_value > > This gives the error message > Traceback (most recent call last): > File "C:\Python24\code2", line 88, in -toplevel- > value = codons[x] * codons[x+1] > NameError: name 'x' is not defined > > Code 2 - the most likely code > prod = 1 > for item in (codons): prod *= item > prod > print prod > > Gives this error message: > Traceback (most recent call last): > File "C:\Python24\code2", line 90, in -toplevel- > for item in (codons): prod *= item > TypeError: can't multiply sequence by non-int > > > Can anyone help me solve this problem? > Thanks. > > -- > View this message in context: http://www.nabble.com/problems-with-numbers-in-my-python-code-t1259271.html#a3339964 > Sent from the Python - tutor forum at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From annaraven at gmail.com Fri Mar 10 16:06:29 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Fri, 10 Mar 2006 07:06:29 -0800 Subject: [Tutor] problems with numbers in my python code In-Reply-To: <3339964.post@talk.nabble.com> References: <3339964.post@talk.nabble.com> Message-ID: <cb361a610603100706h2ed62f3aqec959f913222625c@mail.gmail.com> On 3/10/06, sjw28 <brainy_muppet at hotmail.com> wrote: > > > Basically, I have a code with is almost finished but I've having > difficultly > with the last stage of the process. I have a program that gets assigns > different words with a different value via looking them up in a > dictionary: > > eg if THE is in the writing, it assigns 0.965 > > and once the whole passage is read it returns all the numbers in the > format > as follows: > > ['0.965', '1.000', '0.291', '1.000', '0.503'] > > However, I can't seem to get the program to treat the numbers as numbers. > If > I put them in the dictionary as 'THE' = int(0.965) the program returns 1.0 > and if I put 'THE' = float(0.965) it returns 0.96555555549 or something > similar. Neither of these are right! I basically need to access each item > in > the string as a number, because for my last function I want to multiply > them > all together by each other. > > I have tried two bits of code for this last bit, but neither are working > (I'm not sure about the first one but the second one should work I think > if > I could figure out how to return the values as numbers): > > 1st code > value = codons[x] * codons[x+1] > x = (int) > x = 0 > > print value > > x +=2 > > if (x<r): > new_value = value * codons[x] > value = new_value > x +=1 > else: > print new_value > > This gives the error message > Traceback (most recent call last): > File "C:\Python24\code2", line 88, in -toplevel- > value = codons[x] * codons[x+1] > NameError: name 'x' is not defined > > Code 2 - the most likely code > prod = 1 > for item in (codons): prod *= item > prod > print prod > > Gives this error message: > Traceback (most recent call last): > File "C:\Python24\code2", line 90, in -toplevel- > for item in (codons): prod *= item > TypeError: can't multiply sequence by non-int > > > Can anyone help me solve this problem? > Thanks. This is exactly what the decimal module was created for. It will take those strings, let you do your computations and give you back the exact decimal values with exactly the precision you want. You get to decide what type of rounding rules you want. If you don't have it already (say you're using 2.3 for example) you can get it from http://www.taniquetil.com.ar/facundo/bdvfiles/get_decimal.html. Otherwise, just import it and run help(decimal) to learn it. I'd show you but I just discovered I'm running 2.3 on this Mac so I need to upgrade. If you have trouble using decimal, let us know. Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060310/e98078ee/attachment-0001.html From edgar.antonio.rv at gmail.com Fri Mar 10 19:31:21 2006 From: edgar.antonio.rv at gmail.com (Edgar Antonio Rodriguez Velazco) Date: Fri, 10 Mar 2006 18:31:21 +0000 Subject: [Tutor] Cannot Understand Message-ID: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> Hi, Could you please explain this code?. f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 Thanks, -- Edgar A. Rodriguez V. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060310/89f0bbd9/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Mar 10 20:17:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Mar 2006 11:17:14 -0800 (PST) Subject: [Tutor] Dynamically naming functions In-Reply-To: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603101111370.8293-100000@hkn.eecs.berkeley.edu> > I want to use this in a few different places. For example Faces, the > Python Project Management Planner Tool Thingy, uses nested functions to > put tasks within a project: > > def MyProject(): > start = "2006-03-06" > resource = Me > > def Task1(): > start = "2006-03-13" > > def Task2(): > effort = "1w" > > I'd like to load these from a database (using SQLObject), but I'm not > sure how I can define the name of the function from a filed in a > database (or read in from a text file). Hi Ed, If we have a bunch of functions in a module, then we can get at a function from its string name by using the getattr() built-in function. http://www.python.org/doc/lib/built-in-funcs.html#l2h-31 For example, let's say that we have a module like the math module. ###### >>> import math ###### We know that we can get the function by naming it. ###### >>> math.sin <built-in function sin> >>> math.sin(3.14) 0.0015926529164868282 ###### But we can also get it if we have a string: ###### >>> def getMathFunction(name): ... return getattr(math, name) ... >>> getMathFunction("sin") <built-in function sin> >>> getMathFunction("sin")(3.14) 0.0015926529164868282 ###### And of course, that string can come from anywhere, including a database. Does this answer your question? If you have questions, please feel free to ask. From dyoo at hkn.eecs.berkeley.edu Fri Mar 10 20:19:42 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Mar 2006 11:19:42 -0800 (PST) Subject: [Tutor] Automatic software performance meter In-Reply-To: <OF1FE93D30.48212E95-ONC125712D.00316630-C125712D.0032DEAE@velux.com> Message-ID: <Pine.LNX.4.44.0603101117220.8293-100000@hkn.eecs.berkeley.edu> On Fri, 10 Mar 2006, [ISO-8859-1] János Juhász wrote: > is it any easy way to mesaure a windows software response time from python > script ? > I think about a small python script that can open a win32 application, > insert a new order with sendkey, deliver the goods, do other things and > create a small log file with the different split times. > > I would like to controll the time needed for a business procedure instead > of the ping time :) Hi Janos, The "profiler" programs that come with Python can give some kind of idea about how long a function takes. One side effect of them, though, is that the profiled Python program will take more time to run because it's doing a lot more measurement, but that may be ok for you. See: http://www.python.org/doc/lib/profile.html and the Instant Users Manual that's in section three of that documentation for examples. Best of wishes to you! From annaraven at gmail.com Fri Mar 10 20:30:52 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Fri, 10 Mar 2006 11:30:52 -0800 Subject: [Tutor] Cannot Understand In-Reply-To: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> Message-ID: <cb361a610603101130q473f2752k98f5e35f9ff390e9@mail.gmail.com> On 3/10/06, Edgar Antonio Rodriguez Velazco <edgar.antonio.rv at gmail.com> wrote: > > Hi, > Could you please explain this code?. > > f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 > This is why lambdas are evil. Officially, they are for creating "anonymous functions"; usually they only succeed in creating obscure unreadable drek. In My Humble Opinion. Okay - start from the middle and work our way through: n is your variable that you're passing as an argument to this unnamed function. say, n were 10. n-1 is 9 add EITHER: absolute value of n-1 AND do a recursive call to f on 9 (and then on 8, and then on 7...), multiplied by n OR add 1. if you type it into your interpreter, here's the result: >>> n = 10 >>> f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 >>> print f(n) 3628800 Yuck. I hate reading lambdas. Personally, I think it's buttugly. Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060310/d5a9135c/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Mar 10 20:37:57 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Mar 2006 11:37:57 -0800 (PST) Subject: [Tutor] *args consumption In-Reply-To: <041701c64450$91078760$f72c4fca@csmith> Message-ID: <Pine.LNX.4.44.0603101121170.8293-100000@hkn.eecs.berkeley.edu> > Am I missing some other usage where you wouldn't want to unpack the > *arg? If not, would the following "behind the scenes" behavior be > possible/preferred? > > ### > def foo(*arg): > pass > ### > > automatically does this > > ### > def foo(*arg): > if len(arg) == 1: > arg = arg[0] > pass > ### Yes: what if we're passing foo() some mixed data? This might not be as weird as it might sound: imagine that a cartegian point [x, y] is represented either as a point: [x, y] or as a single x coordinate number x where the y coordinate is assumed to be zero. x Our list would then contain a mix of data. For example, a list with the points (4, 3) and (5, 0) and (2, 9) could be represented as: [[4, 3], 5, [2, 9]] And even though this looks a little weird, this still works perfectly ok, because we can write functions to reliably get the x,y coordinates of this mixed representation: ########################## def getX(point): if type(point) == int: return point else: return point[0] def getY(point): if type(point) == int: return 0 else: return point[1] ########################## Anyway, ok, so we have points. What's more natural than drawing them and playing connect the dots? *grin* ################################################################# def playConnectTheDots(*points): """Draws all the points given and connects them together with lines.""" # ... fill me in ################################################################# But if we pass playConnectTheDots() with a single point, we want the function not to automatically unpack the argument as if it were something else: it would be a lossy kind of implicit transformation. If the case of len(points) == 1 is treated as a special case, that would make the logic turn into... well, I don't know, it would be ambiguous! >From the example above, if we did feed it: playConnectTheDots([[4, 3]]) ## Draw the point (4, 3) vs: playConnectTheDots([4, 3]) ## Draw between (4, 0) and (3, 0) then imagine what would happen if Python did the kind of automatic unwrapping you're thinking of. How would it tell the difference between these two different cases? So making a special case for the singular list probably won't be as nice as we might expect. It's often better to treat them all consistantly. Lists with one element aren't bad! *grin* From dyoo at hkn.eecs.berkeley.edu Fri Mar 10 20:54:40 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Mar 2006 11:54:40 -0800 (PST) Subject: [Tutor] Cannot Understand In-Reply-To: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603101138340.8293-100000@hkn.eecs.berkeley.edu> On Fri, 10 Mar 2006, Edgar Antonio Rodriguez Velazco wrote: > Could you please explain this code?. > > f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 Hi Edgar, This is terrible code. *grin* I know that this is the factorial function in disguise, but this is just Wrong. I don't think we should study this too seriously, just because the code is deliberately trying to be obscure. But if you really insist... let's break it down into pieces. Let's slowly transform it in phases: ############################################## f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 ############################################## First, let's convert this to a familiar definition without lambdas: ########################################### def f(n): return n-1 + abs(n-1) and f(n-1)*n or 1 ########################################### Next, let's observe that AND and OR behave like this: x AND y --> if x: return y else: return x x OR y --> if x: return x else: return y (This is to a first rough approximation. We're ignoring details, like the fact that Python's if statement isn't an expression, and that we're evaluating this more times than they deserve... *grin*): Ok, let's apply this change to f(n). Let's attack the AND first: ############################## def f(n): if n-1 + abs(n-1): return f(n-1) * n or 1 else: return n-1 + abs(n-1): ############################## The expression n-1 + abs(n-1) is always a true value... except in the case where n is zero. So this is really saying is something much less profound than it looks: ############################## def f(n): if n: return f(n-1) * n or 1 else: return 0 ############################## Ok, let's attack the OR now: ############################## def f(n): if n: if f(n-1) * n: return f(n-1) * n else: return 1 else: return 0 ############################## (... In retrospect, this really is a recursive definition that's a broken factorial function. f(0) evaluates to zero, but it really should be 1.) If you're familiar with the recursive factorial function, the version of f(n) above now will be pretty recognizable now. If not, then I think I have to stop anyway, because then we're going into "what's recursion?", which is a whole another topic. *grin* If you have any questions, please feel free to ask. I hope this helps! From dyoo at hkn.eecs.berkeley.edu Fri Mar 10 21:02:57 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Mar 2006 12:02:57 -0800 (PST) Subject: [Tutor] Cannot Understand In-Reply-To: <Pine.LNX.4.44.0603101138340.8293-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0603101156100.8293-100000@hkn.eecs.berkeley.edu> > The expression n-1 + abs(n-1) is always a true value... except in the > case where n is zero. Sorry, that's wrong of me, but you know what I mean. *grin* It zeros out when n-1 <= 0, that is, when n <= 1. ###### >>> def test(n): ... return n-1 + abs(n-1) ... >>> for x in range(-5, 5): ... print x, test(x) ... -5 0 -4 0 -3 0 -2 0 -1 0 0 0 1 0 2 2 3 4 4 6 ###### So I wasn't paying enough attention. With this, f(n) now looks something like this: ############################## def f(n): if n > 1: return f(n-1) * n or 1 else: return 0 ############################## The rest of the analysis follows from the previous email. So it's not exactly the factorial function, but it's very similar to it. It's off by a small constant. From dyoo at hkn.eecs.berkeley.edu Fri Mar 10 21:13:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Mar 2006 12:13:36 -0800 (PST) Subject: [Tutor] Cannot Understand In-Reply-To: <Pine.LNX.4.44.0603101156100.8293-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0603101209450.8293-100000@hkn.eecs.berkeley.edu> On Fri, 10 Mar 2006, Danny Yoo wrote: > > The expression n-1 + abs(n-1) is always a true value... except in the > > case where n is zero. > > Sorry, that's wrong of me, but you know what I mean. *grin* Ugh, the other thing I screwed up wrong was misreading: X and Y or Z and forgetting my operator precedence. I should be thinking: ((X and Y) or Z) and not (X and (Y or Z)) which was the wrong path my analysis took. But after turning about and retracing the overall steps, we do end up getting the factorial function after all. Sorry about messing up so much; I'm just in a big hurry at the moment. *grin* From Pawel_Kraszewski at wp.pl Fri Mar 10 21:24:21 2006 From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Fri, 10 Mar 2006 21:24:21 +0100 Subject: [Tutor] Cannot Understand In-Reply-To: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> Message-ID: <200603102124.21781.Pawel_Kraszewski@wp.pl> Dnia pi?tek, 10 marca 2006 19:31, Edgar Antonio Rodriguez Velazco napisa?: > f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 Oh God! This smells lispish! Haven't seen a jevel like this before, but I LOVE it! ----------------------------------------- First, let's cut that into pieces: R1 n-1 + abs(n-1) This is a funny way to test if n>1. Indeed, for n>1 it works as 2*n-2 (especially, it is non-zero), for n<=1 it gives a constant 0 R2 f(n-1)*n It is a formula for you-know-what R3 1 Well... This is a ONE, you know. ----------------------------------------- Then, few notes on 'and' and 'or' operators. For correctness of many algorithms, programmers introduced 'partial evaluation'. What does it mean? L1 A and B When A is FALSE, no matter what the B is, the whole result is FALSE. Therefore, we DON'T NEED to evaluate B. When A is TRUE, the result is yet unknown and we must evaluate B L2 A or B When A is TRUE, no matter what the B is, the whole result is TRUE. Therefore, we DON'T NEED to evaluate B. When A is FALSE, the result is yet unknown and we must evaluate B L3 'and' has higher priority than 'or' ----------------------------------------- Putting things together: f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 which may be rewritten due to law L3 as (R1 and R2) or R3 First check is R1 If R1==false (it means n<=1), then whole brace is automaticaly false due to law L1. Moreover, due to the same law, R2 is NOT calculated. We now have the value of brace, which is FALSE. We now have "FALSE or R3", so due to law L2 we now must evaluate R3 to get the final (lambda) result. The total result is value of R3, this means 1. If R1==true (it means n>1), due to law L1 we must evaluate R2 to get the brace result. This is done by recursively calling lambda function with argument "n-1". Let's call the returned value a RES. When RES is non-zero (it actualy always is, due function it implements) we have non-zero result of the whole brace. due to law L2, we don't need to evaluate R3 and calculated result RES is the return value of lambda function. -- Pawel Kraszewski P.S. This might be pythonized and de-recursived this way: ff = lambda n: reduce(lambda x, y: x*y, xrange(1,n+1)) ----------------------------------------- Spoiler below... Scroll down Of course, as a last resort this may be rewritten in "plan english" as: def f(n): if n>1: return n*f(n-1) else: return 1 From mbroe at columbus.rr.com Fri Mar 10 23:00:00 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Fri, 10 Mar 2006 17:00:00 -0500 Subject: [Tutor] Unicode and regexes Message-ID: <5493B587-C201-4D61-A82F-5A9BDF35B253@columbus.rr.com> Does Python support the Unicode-flavored class-specifications in regular expressions, e.g. \p{L} ? It doesn't work in the following code, any ideas? ----- #! /usr/local/bin/python """ usage: ./uni_read.py file """ import codecs import re text = codecs.open(sys.argv[1], mode='r', encoding='utf-8').read() unicode_property_pattern = re.compile(r"\p{L}") dot_pattern = re.compile(".") letters = unicode_property_pattern.findall(text) characters = dot_pattern.findall(text) print 'var letters =', letters print 'var characters = ', characters ----- The input file, encoded in utf-8 is abc <followed by space, alpha, beta gamma> The output is: var letters = [] var characters = [u'a', u'b', u'c', u' ', u'\u03b1', u'\u03b2', u'\u03b3'] From bgailer at alum.rpi.edu Fri Mar 10 23:58:07 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 10 Mar 2006 14:58:07 -0800 Subject: [Tutor] Cannot Understand In-Reply-To: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> Message-ID: <4412047F.2020302@alum.rpi.edu> Edgar Antonio Rodriguez Velazco wrote: > Hi, > Could you please explain this code?. > > f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 You've had 2 replies that dissect the "expression". I fear they might not make lambda itself clear, so I will add my explanation. lambda is a Python operator that creates a function. It's syntax is quite different from other operators: lambda optional-list-of-arguments : expression to be evaluated and returned by the function The statement you posted is equivalent to: def f(n): return n-1 + abs(n-1) and f(n-1)*n or 1 The other replies do a good job of dissecting the expression part, which recursively calculates the (did you know what?) factorial of n. Despite other claims of ugliness lambda has its use, especially in places where you don't need the function bound to a variable. Example would be a dictionary of functions to do arithmetic where the operator is specified by a user. calculator = {'+' : lambda a,b: a+b, '*' : lambda a,b: a*b, etc.} # The user, via some input mechanism provides numbers for n1 and n2, and a symbol for operation. Then result = calculator[operation](n1, n2) From carroll at tjc.com Sat Mar 11 01:43:41 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 10 Mar 2006 16:43:41 -0800 (PST) Subject: [Tutor] execute an OS command, get the output Message-ID: <Pine.LNX.4.44.0603101628550.15729-100000@violet.rahul.net> I need to execute a command and capture the stdout output. I'm overwhelmed by the plethora of means that Python offers to do something like this, and don't know which, if any, is most applicable: 1) the os.system module 2a-d) os.popen, and popen2 popen3 and popen4 3) the popen2 module 4) the subprocess module #1 is synchronous, which is what I want, but it doesn't seem to have any means to capture stdout. #s 2-4 look like they support capturing stdout, but they seem to be asynchronous, which is at the very least overkill for me. I would ideally like something like this: abc = executeit(commandline) or executeit(commandline, abc) where, after execution, abc be a string or list that would contain the output of the command line commandline after its completed. I'm not worried too much about syntax, though; I'd be happy to just find some synchronous command-exeutor that gives me the standard output by any means. More detail, in case it matters: the command line I need to execute is actually three commands, with pipes between them, i.e., string xxxxxxx | grep zzzzzz | head -10 My environment is Python 2.4, Windows/XP (with cygwin installed, hence the availablility of the string, grep and head commands) From alan.gauld at freenet.co.uk Sat Mar 11 01:48:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 11 Mar 2006 00:48:47 -0000 Subject: [Tutor] Cannot Understand References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> <cb361a610603101130q473f2752k98f5e35f9ff390e9@mail.gmail.com> Message-ID: <005401c644a5$8e7717e0$0b01a8c0@xp> >> Could you please explain this code?. >> >> f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 > > This is why lambdas are evil. It's not the lambda thats evil its the need in Python to limit them to a single expression. If we write def f(n): return n-1 + abs(n-1) and f(n-1)*n or 1 its just as obscure. if we write def f(n) if not ((n-1) + abs(n-1)): return f(n-1) * n else return 1 it gets a little clearer. And the only time the if expression is false is when n is zero or 1 so for the last time: def f(n) if n >1: return f(n-1) * n else: return 1 In fact its the factorial function in very strange disguise! If we could write the lambda as f = lambda n: if n>1: return f(n-1) * n else return 1 is it so much more complex? > Officially, they are for creating "anonymous functions"; > usually they only succeed in creating obscure unreadable drek. Unfortunately that's true. But as a concept they are a fundamental part of computing science and its hard to understamnd higher order programming or explore predicate calculus without them They are also of course very useful as shortcuts but thats usually where the cryptic code comes in. Ruby and Smalltalk's block mechanism is probably more readily grokked by those not interested in mathematical purity! > In My Humble Opinion. And in mine, of course :-) > Yuck. I hate reading lambdas. Personally, I think it's buttugly. I think Python's lambdas are seriously underpowered but not totally without merit. They are manby times better than Java's pathetic anonymous inner class mechanism to do the same job! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Mar 11 01:56:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 11 Mar 2006 00:56:58 -0000 Subject: [Tutor] Cannot Understand References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> <cb361a610603101130q473f2752k98f5e35f9ff390e9@mail.gmail.com> Message-ID: <007701c644a6$b363cd40$0b01a8c0@xp> >> Could you please explain this code?. >> >> f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 > > >This is why lambdas are evil. I meant to add to my last post that even using lambdas this is a weird attempt at a factorial fiunction. Here's the equivalent from my web tutor on functional programming: >>> factorial = lambda n: ( (n <= 1) and 1) or ... (factorial(n-1) * n) >>> factorial(5) 120 It uses the same basic constructs but much less esoteric trickery. Hopefully its slightly more readable, but I still wouldn't recommend it as a way to write everyday code! HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From annaraven at gmail.com Sat Mar 11 02:14:07 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Fri, 10 Mar 2006 17:14:07 -0800 Subject: [Tutor] Cannot Understand In-Reply-To: <007701c644a6$b363cd40$0b01a8c0@xp> References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> <cb361a610603101130q473f2752k98f5e35f9ff390e9@mail.gmail.com> <007701c644a6$b363cd40$0b01a8c0@xp> Message-ID: <cb361a610603101714x7e1411c5p8f539669072f0dc5@mail.gmail.com> On 3/10/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > >> Could you please explain this code?. > >> > >> f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 > > > > > >This is why lambdas are evil. > > I meant to add to my last post that even using lambdas this > is a weird attempt at a factorial fiunction. > > Here's the equivalent from my web tutor on functional > programming: > > >>> factorial = lambda n: ( (n <= 1) and 1) or > ... (factorial(n-1) * n) > > >>> factorial(5) > 120 > > It uses the same basic constructs but much less esoteric trickery. > Hopefully its slightly more readable, Much more readable. Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060310/7cf003c4/attachment.html From ml.cyresse at gmail.com Sat Mar 11 02:20:20 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 11 Mar 2006 14:20:20 +1300 Subject: [Tutor] Cannot Understand In-Reply-To: <200603102124.21781.Pawel_Kraszewski@wp.pl> References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> <200603102124.21781.Pawel_Kraszewski@wp.pl> Message-ID: <b6f3249e0603101720w7eae1c80p337be661fcb381de@mail.gmail.com> On 3/11/06, Pawel Kraszewski <Pawel_Kraszewski at wp.pl> wrote: > Dnia pi?tek, 10 marca 2006 19:31, Edgar Antonio Rodriguez Velazco napisa?: > > > f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 > > Oh God! This smells lispish! Haven't seen a jevel like this before, but I LOVE > it! Haha, hey, I've been learning Lisp and at least it'd have brackets in places to make precedence easier to grok. This reminds me, some friends and I were discussing various languages and writing code that generates a string of the first five squares, space delimited. i.e. x = [] for i in range(1, 6): w = str(i) x.append(w) print " ".join(x) Which rapidly turned into an obfuscation contest. I was amazed at how obfuscated you could be in Python, thus proving the adage that you can write Perl in any language. A relatively intelligble one liner is print " ".join([str(i * i) for item in range(1,6)]) A very obfuscated (using lambda and abusing a list comprehension) one is [sys.stdout.write(str((lambda y: y*y)(x))+" ") for x in range(1,6)] (But it also returns [None, None, None, None, None, None] ) And my favourite, because it looks like Lisp/Haskell - print " ".join(map(str, map(lambda x: x*x, range(1,6)))) (My Common Lisp attempt was - (string-trim "()" (write-to-string (loop for i from 1 to 5 collecting (* i i)) :array T)) but I'm such a Lisp newbie it's not funny.) /end OT From annaraven at gmail.com Sat Mar 11 02:27:07 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Fri, 10 Mar 2006 17:27:07 -0800 Subject: [Tutor] Cannot Understand In-Reply-To: <005401c644a5$8e7717e0$0b01a8c0@xp> References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com> <cb361a610603101130q473f2752k98f5e35f9ff390e9@mail.gmail.com> <005401c644a5$8e7717e0$0b01a8c0@xp> Message-ID: <cb361a610603101727y7e2ea98ci84a39652a6e08e25@mail.gmail.com> On 3/10/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > >> Could you please explain this code?. > >> > >> f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1 > > > > This is why lambdas are evil. > > It's not the lambda thats evil its the need in Python to limit > them to a single expression. > > If we write > > def f(n): > return n-1 + abs(n-1) and f(n-1)*n or 1 > > its just as obscure. Someone writing a named function is less likely to feel constrained to do an obscure "one-liner". if we write > > def f(n) > if not ((n-1) + abs(n-1)): > return f(n-1) * n > else return 1 > > it gets a little clearer. And the only time the if expression > is false is when n is zero or 1 so for the last time: > > def f(n) > if n >1: > return f(n-1) * n > else: > return 1 This, is clear, and the kind of thinking that, imho, writing an actual function promotes. The other useful thing with this is: if you give it real name instead of an anonymous, meaningless f, you can actually call the function from other modules, or reuse it in other programs. Meaningful naming also enhances readability. How much did we all have to go through to figure out that this was a factorial function. What if, instead, it had actually been given a real name, like, say "factor"... No need to work through the complex code just to figure out what it was for. In fact its the factorial function in very strange disguise! > > If we could write the lambda as > > f = lambda n: > if n>1: > return f(n-1) * n > else return 1 > > is it so much more complex? > > > Officially, they are for creating "anonymous functions"; > > usually they only succeed in creating obscure unreadable drek. > > Unfortunately that's true. But as a concept they are a fundamental > part of computing science and its hard to understamnd higher order > programming or explore predicate calculus without them > > They are also of course very useful as shortcuts but thats usually > where the cryptic code comes in. Precisely. They are used as shortcuts and usually are far too clever by half. I've seen a few people like you who use them clearly; unfortunately, that's not the norm. > In My Humble Opinion. > > And in mine, of course :-) Well - the nice thing is that we both get to be right! ;-) And I think it's useful to get the pros and cons out occasionally where newbies can see that we don't all agree on everything, but that we can disagree politely and still be helpful. Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060310/7913c1a3/attachment.htm From hugonz-lists at h-lab.net Sat Mar 11 02:50:18 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 10 Mar 2006 19:50:18 -0600 Subject: [Tutor] execute an OS command, get the output In-Reply-To: <Pine.LNX.4.44.0603101628550.15729-100000@violet.rahul.net> References: <Pine.LNX.4.44.0603101628550.15729-100000@violet.rahul.net> Message-ID: <44122CDA.5070402@h-lab.net> Hi Terry, > abc = executeit(commandline) or > executeit(commandline, abc) > Looks like you are looking for the commands module, it provides: getstatusoutput( cmd) getoutput( cmd) getstatus( file) Which do exactly what tou want. Take a look at the docs at: http://python.active-venture.com/lib/module-commands.html Hope that helps, Hugo From beamer30 at gmail.com Sat Mar 11 05:37:57 2006 From: beamer30 at gmail.com (Tom Bachik) Date: Fri, 10 Mar 2006 20:37:57 -0800 Subject: [Tutor] i have a question Message-ID: <4ce40aaa0603102037u53143bs760d5ab5f70f101d@mail.gmail.com> ok say u want python to ask the user to type a username then password for a game account thats easy but how do u get the information they typed back to you? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060310/3b9752b4/attachment.htm From carroll at tjc.com Sat Mar 11 07:18:32 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 10 Mar 2006 22:18:32 -0800 (PST) Subject: [Tutor] execute an OS command, get the output In-Reply-To: <44122CDA.5070402@h-lab.net> Message-ID: <Pine.LNX.4.44.0603102217370.22162-100000@violet.rahul.net> On Fri, 10 Mar 2006, [ISO-8859-1] Hugo González Monteverde wrote: > Looks like you are looking for the commands module, it provides: > > getstatusoutput( cmd) > > getoutput( cmd) > > getstatus( file) > > > Which do exactly what tou want. Take a look at the docs at: > > http://python.active-venture.com/lib/module-commands.html Thanks, Hugo. Unfortunately, it doesn't work for me; for example: >>> print getoutput("dir") '{' is not recognized as an internal or external command, operable program or batch file. The docs say: Availability: Unix. And I'm on Windows/XP, so I'm guessing that although the module's there, it just doesn't work on Windows. From kp8 at mac.com Sat Mar 11 07:38:03 2006 From: kp8 at mac.com (kevin parks) Date: Sat, 11 Mar 2006 01:38:03 -0500 Subject: [Tutor] weighted choices from among many lists In-Reply-To: <mailman.10353.1142040430.27774.tutor@python.org> References: <mailman.10353.1142040430.27774.tutor@python.org> Message-ID: <96cb775b2e2cf81599ba99efc55e9d3f@mac.com> I have several lists... and i would like to some times chose from one list and for a while choose from a different list, etc... so i cooked this up and it almost works so that i can get colors 50% of the time, doggies 25%, beer 10%, and guitars 100% (if i was real smart i would make my index thingy check to make sure my wieghets added up to 100% or scaled them to be..... ) ... meanwhile, as you can see i am 90% of the way there, can anyone figure out what i got wrong or suggest improvements to the code... best, -kevin-- #!/usr/bin/env python import random def windex(lst): '''a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] >>> y=windex(x)''' n = random.uniform(0, 1) for item, weight in lst: if n < weight: break n = n - weight return item def test(): lst_a = [ 'red', 'green', 'blue', 'orange', 'violet', 'yellow', 'black', 'white' ] lst_b = ['Rottweiler', 'Beagle', 'Sheepdog', 'Collie', 'Boxer', 'Terrier', 'Bulldog', 'Chihuahua', 'Retriever', 'Collie', 'Dachshund', 'Doberman', 'Greyhound', 'Pug', 'Spaniel'] lst_c = ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout'] lst_d = ['fender', 'gibson', 'rickenbacker', 'guild', 'danelectro', 'gretsch', 'martin', 'ibanez'] x = [('lst_a', .50), ('lst_b', .25), ('lst_c', .10),('lst_d', .15)] i = 1 while i < 100: lst = windex(x) print i, lst, pick = random.choice(lst) print pick i = i + 1 if __name__ == "__main__": test() From kp8 at mac.com Sat Mar 11 08:44:20 2006 From: kp8 at mac.com (kevin parks) Date: Sat, 11 Mar 2006 02:44:20 -0500 Subject: [Tutor] activestate In-Reply-To: <mailman.10353.1142040430.27774.tutor@python.org> References: <mailman.10353.1142040430.27774.tutor@python.org> Message-ID: <a431e57e529837b2a65accdefd8881ad@mac.com> I noticed a couple days ago that the active state archive seems to have ceased. Is it going away? cheers, kevin From alan.gauld at freenet.co.uk Sat Mar 11 10:06:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 11 Mar 2006 09:06:10 -0000 Subject: [Tutor] execute an OS command, get the output References: <Pine.LNX.4.44.0603101628550.15729-100000@violet.rahul.net> Message-ID: <009901c644eb$0aae3470$0b01a8c0@xp> > 1) the os.system module > 2a-d) os.popen, and popen2 popen3 and popen4 > 3) the popen2 module > 4) the subprocess module Take a look at the OS topic in my tutorial. The process control section covers all of these calls and explains their differences. It also points out that the latter is intended to replace all the others and shows examples. > #1 is synchronous, which is what I want, but it doesn't seem to have any > means to capture stdout. Actually they are all synchronous if the command is not interactive. If the command requires input before it completes then it will wait for Python to supply it if using popen (in the same way that it would from a user if using system). > #s 2-4 look like they support capturing stdout, but they seem to be > asynchronous, which is at the very least overkill for me. output = popen(command).read() isn't too hard is it? > More detail, in case it matters: the command line I need to execute is > actually three commands, with pipes between them, i.e., > > string xxxxxxx | grep zzzzzz | head -10 Just make sure its all within a string and Python doesn't care. But in this case I'd use Pytthon to search for the string and get the last 10 entries rather than grep/head... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Mar 11 10:08:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 11 Mar 2006 09:08:28 -0000 Subject: [Tutor] Cannot Understand References: <9378d12c0603101031k234d71d3xcdd999ec7594a3de@mail.gmail.com><cb361a610603101130q473f2752k98f5e35f9ff390e9@mail.gmail.com><005401c644a5$8e7717e0$0b01a8c0@xp> <cb361a610603101727y7e2ea98ci84a39652a6e08e25@mail.gmail.com> Message-ID: <009f01c644eb$5cf39b30$0b01a8c0@xp> > we don't all agree on everything, but that we can disagree politely and > still be helpful. One of the truly great things about Python is the user community, by far the most civilised that I've encountered in my 20 years or so of internet use. Long may it continue, Alan G. From kent37 at tds.net Sat Mar 11 14:34:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Mar 2006 08:34:49 -0500 Subject: [Tutor] weighted choices from among many lists In-Reply-To: <96cb775b2e2cf81599ba99efc55e9d3f@mac.com> References: <mailman.10353.1142040430.27774.tutor@python.org> <96cb775b2e2cf81599ba99efc55e9d3f@mac.com> Message-ID: <4412D1F9.3040906@tds.net> kevin parks wrote: > I have several lists... and i would like to some times chose from one > list and for a while choose from a different list, etc. You don't say what isn't working but I have a guess. The actual windex() function looks OK to me. > def test(): > > lst_a = [ 'red', 'green', 'blue', 'orange', 'violet', 'yellow', > 'black', 'white' ] > lst_b = ['Rottweiler', 'Beagle', 'Sheepdog', 'Collie', 'Boxer', > 'Terrier', 'Bulldog', 'Chihuahua', 'Retriever', 'Collie', 'Dachshund', > 'Doberman', 'Greyhound', 'Pug', 'Spaniel'] > lst_c = ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout'] > lst_d = ['fender', 'gibson', 'rickenbacker', 'guild', 'danelectro', > 'gretsch', 'martin', 'ibanez'] > x = [('lst_a', .50), ('lst_b', .25), ('lst_c', .10),('lst_d', .15)] x is list containing the *names* of the other lists. You need to keep references to the lists so you can pick from them. x = [(lst_a, .50), (lst_b, .25), (lst_c, .10),(lst_d, .15)] > i = 1 > while i < 100: > lst = windex(x) > print i, lst, with the change above this will print the list, not its name > pick = random.choice(lst) but this will work. If you want to be able to print the name of the list then you could include both the name and the actual list in x: x = [(('lst_a', lst_a), .50), etc...] Kent From kent37 at tds.net Sat Mar 11 14:50:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Mar 2006 08:50:15 -0500 Subject: [Tutor] Unicode and regexes In-Reply-To: <5493B587-C201-4D61-A82F-5A9BDF35B253@columbus.rr.com> References: <5493B587-C201-4D61-A82F-5A9BDF35B253@columbus.rr.com> Message-ID: <4412D597.7010207@tds.net> Michael Broe wrote: > Does Python support the Unicode-flavored class-specifications in > regular expressions, e.g. \p{L} ? It doesn't work in the following > code, any ideas? From http://www.unicode.org/unicode/reports/tr18/ I see that \p{L} is intended to select Unicode letters, and it is part of a large number of selectors based on Unicode character properties. Python doesn't support this syntax. It has limited support for Unicode character properties as an extension of the \d, \D, \s, \S, \w and \W sequences. For example with numbers = re.compile(r'\d', re.UNICODE) numbers will match any Unicode digit. You can combine and difference the built-in categories to get more possibilities. This thread shows how to construct a regex that finds just Unicode letters: http://groups.google.com/group/comp.lang.python/browse_frm/thread/6ef6736581fecaeb/a49326cb48c408ee?q=unicode+character+class&rnum=1#a49326cb48c408ee Python does have built-in support for the Unicode character database in the unicodedata module, so for example you can look up the character class of a character. You can roll your own solution on top of this data. This thread shows how to build your own regex category directly from a property in unicodedata: http://groups.google.com/group/comp.lang.python/browse_frm/thread/fdfdec9a0649c540/471331f518fa680f?q=unicode+character+class&rnum=2#471331f518fa680f Kent From ml.cyresse at gmail.com Sat Mar 11 14:53:45 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 12 Mar 2006 02:53:45 +1300 Subject: [Tutor] Sorting and secondary sorting. Message-ID: <b6f3249e0603110553j464ee0e6hcb9b91503cca15d8@mail.gmail.com> Hi all, I'm trying to think of a way to sort a list of dictionaries. In pseudo-code: l = [ { "host":"foo", "db":"bob"}, { "host":"foo", "db":"dave"}, { "host":"fee", "db":"henry"} ] l.sort( key = lambda item: item["host"], second_key = lambda item: item["db"]) Which, if all went well, would give me - l = [ { "host":"fee", "db":"henry"} { "host":"foo", "db":"bob"}, { "host":"foo", "db":"dave"}, ] So, I'm trying to sort and then do a secondary sort. I'd like to do it Pythonically; currently I'm creating a Pysqlite db in memory and sticking the data in a table, and selecting it back out with an ORDER BY clause, and then reconstituting it into dictionaries in a list. I get that "overlooking something simple" feeling on this one, so any assistance welcomed. I got lost with lists and lists of lists and joining lists back together, so I cheated and went the SQL way. Regards, Liam Clarke From khp at pflaesterer.de Sat Mar 11 15:53:27 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sat, 11 Mar 2006 15:53:27 +0100 Subject: [Tutor] Sorting and secondary sorting. In-Reply-To: <b6f3249e0603110553j464ee0e6hcb9b91503cca15d8@mail.gmail.com> (Liam Clarke's message of "Sun, 12 Mar 2006 02:53:45 +1300") References: <b6f3249e0603110553j464ee0e6hcb9b91503cca15d8@mail.gmail.com> Message-ID: <upsktt4ry.fsf@hamster.pflaesterer.de> On 11 Mrz 2006, ml.cyresse at gmail.com wrote: > I'm trying to think of a way to sort a list of dictionaries. In pseudo-code: > > l = [ { "host":"foo", "db":"bob"}, > { "host":"foo", "db":"dave"}, > { "host":"fee", "db":"henry"} > ] > > l.sort( key = lambda item: item["host"], second_key = lambda item: item["db"]) > > Which, if all went well, would give me - > > l = [ { "host":"fee", "db":"henry"} > { "host":"foo", "db":"bob"}, > { "host":"foo", "db":"dave"}, > ] > > So, I'm trying to sort and then do a secondary sort. I'd like to do it > Pythonically; currently I'm creating a Pysqlite db in memory and > sticking the data in a table, and selecting it back out with an ORDER > BY clause, and then reconstituting it into dictionaries in a list. One easy way could be: .>>> l = [ { "host":"foo", "db":"bob"}, . { "host":"foo", "db":"dave"}, . { "host":"fee", "db":"henry"} . ] .... ... ... >>> l.sort(key=lambda d: (d['host'], d['db'])) .>>> l .[{'host': 'fee', 'db': 'henry'}, {'host': 'foo', 'db': 'bob'}, {'host': 'foo', 'db': 'dave'}] Or you write the above explicitly with DSU; decorate with a tuple of host name and db name, sort and undecorate. Karl -- Please do *not* send copies of replies to me. I read the list From kent37 at tds.net Sat Mar 11 16:13:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Mar 2006 10:13:05 -0500 Subject: [Tutor] Sorting and secondary sorting. In-Reply-To: <b6f3249e0603110553j464ee0e6hcb9b91503cca15d8@mail.gmail.com> References: <b6f3249e0603110553j464ee0e6hcb9b91503cca15d8@mail.gmail.com> Message-ID: <4412E901.4030106@tds.net> Liam Clarke wrote: > Hi all, > > I'm trying to think of a way to sort a list of dictionaries. In pseudo-code: > > l = [ { "host":"foo", "db":"bob"}, > { "host":"foo", "db":"dave"}, > { "host":"fee", "db":"henry"} > ] > > l.sort( key = lambda item: item["host"], second_key = lambda item: item["db"]) > > Which, if all went well, would give me - > > l = [ { "host":"fee", "db":"henry"} > { "host":"foo", "db":"bob"}, > { "host":"foo", "db":"dave"}, > ] > Just make a key that includes both of the values you want to sort on as a tuple: l.sort( key = lambda item: (item["host"], item["db"])) Kent From kermit at polaris.net Sat Mar 11 16:42:31 2006 From: kermit at polaris.net (Kermit Rose) Date: Sat, 11 Mar 2006 10:42:31 -0500 (Eastern Standard Time) Subject: [Tutor] need help tracing a syntax error Message-ID: <4412EFE7.000003.00652@YOUR-4105E587B6> def vmod(a , b ): .r1 = b .r2 = a . m1 = 0 .m2 = 1 .q = Int(r1 / r2) .r3 = r1 - q * r2 .m3 = m1 - q * m2 .while r3 != 0: ...r1 = r2 ...m1 = m2 ...r2 = r3 ...m2 = m3 ...q = Int(r1 / r2) ...r3 = r1 - r2 * q ...m3 = m1 - m2 * q .If r2 == 1: ...If m2 < 0: .....return( m2 + b) ...Else: .....return( m2 ) .Else: ...return( -r2 ) When I attempt to run this function from the shell run menu, I get the message syntax error and it highlights r2 in the line .If r2 == 1: However if I use the eval function in the shell, I get >>> eval("factor30") <module 'factor30' from 'c:\math\factoring\factor30.pyc'> >>> no error message. and when I use help to look at the associated module, this function is not listed. It must be because of the syntax error. >>> help(factor30) Help on module factor30: NAME factor30 FILE c:\math\factoring\factor30.py FUNCTIONS factor(z) factor0(z) gcd(a, b) ifprime(z) ksqrt(j) test(tv) transfac(v) Give me some hint for why this is happening. The periods at the beginning of each line represents beginning spaces. From python at venix.com Sat Mar 11 17:20:58 2006 From: python at venix.com (Python) Date: Sat, 11 Mar 2006 11:20:58 -0500 Subject: [Tutor] need help tracing a syntax error In-Reply-To: <4412EFE7.000003.00652@YOUR-4105E587B6> References: <4412EFE7.000003.00652@YOUR-4105E587B6> Message-ID: <1142094058.10652.167.camel@www.venix.com> On Sat, 2006-03-11 at 10:42 -0500, Kermit Rose wrote: > I get the message > > syntax error > > > and it highlights r2 > > in the line > > .If r2 == 1: if should be lower case (all of the python syntax words are lower case) You will also need to change Else and Elif Int should probably be int unless you are providing an Int class. special python objects get capitalized (None, True, False) -- Lloyd Kvam Venix Corp From carroll at tjc.com Sat Mar 11 17:51:13 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 11 Mar 2006 08:51:13 -0800 (PST) Subject: [Tutor] execute an OS command, get the output In-Reply-To: <009901c644eb$0aae3470$0b01a8c0@xp> Message-ID: <Pine.LNX.4.44.0603110846310.22162-100000@violet.rahul.net> On Sat, 11 Mar 2006, Alan Gauld wrote: > Take a look at the OS topic in my tutorial. The process control section > covers all of these calls and explains their differences. It also points out > that the latter is intended to replace all the others and shows examples. Excellent; I'll check it out. Your tutorials have been vey helpful to me in the past. > output = popen(command).read() > > isn't too hard is it? That's exactly the sort of thing I'm thinking of. > > string xxxxxxx | grep zzzzzz | head -10 > > But in this case I'd use Pytthon to search for the string and get the > last 10 entries rather than grep/head... That was my initial thought, but the files are 1-3 gigabytes. The string command takes 10-15 minutes to get through a file. I've been using the pipe sequence manually, so I know it works, and only takes a second or two to run. The Python program is for my own use, so I don't have to worry about whether and where string/grep/head are installed. From dave.jaeckel at arcor.de Sat Mar 11 18:06:16 2006 From: dave.jaeckel at arcor.de (Ferry Dave =?iso-8859-1?q?J=E4ckel?=) Date: Sat, 11 Mar 2006 18:06:16 +0100 Subject: [Tutor] Python and unicode In-Reply-To: <20060310115406.55f0d397.klappnase@freenet.de> References: <200603100855.42493.dave.jaeckel@arcor.de> <20060310115406.55f0d397.klappnase@freenet.de> Message-ID: <200603111806.22161.dave.jaeckel@arcor.de> Hi Michael and Kent, thanks to your tips I was able to solve my problems! It was quite easy at last. For those interested and struggling with utf-8, ascii and unicode: After knowing the right way of - string.decode() upon input (if in question) - string.encode() upon output (more often then not) where input and output are reading and writing to files, file-like objects, databases... and functions of some not unicode-proof modules I got rid of all calls to encode() and decode() I made by trial and error and which messed it all up. Now I have just a few calls to encode() and voil?! xml.sax seems to read and decode the utf-8 encoded xml-file perfectly right, so do ZipFile.read() and file.write() - no encding oder decoding. To me it was very important to stress out that utf-8 ist *not* unicode, although I have already read about this topic (and you can read this advise often here at this list). On my system sys.stdout and sys.stderr seem to have a utf-8 and a None encoding, respectively (Kubuntu Linux, python2.4, ipython and konsole as terminal). The wrapper suggested by Kent sys.stdout = codecs.getwriter('utf-8')(sys.stdout, 'backslashreplace') sys.stderror = codecs.getwriter('ascii')(sys.stderror, 'backslashreplace') solves all my output problems regarding debugging. Thank you for your help! Dave P.s.: The quotations in my signature are by chance, really. Normally I'm not the kind of guy believing in prevision... ;) -- I never realized it before, but having looked that over I'm certain I'd rather have my eyes burned out by zombies with flaming dung sticks than work on a conscientious Unicode regex engine. -- Tim Peters, 3 Dec 1998 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060311/232256e7/attachment.pgp From dyoo at hkn.eecs.berkeley.edu Sat Mar 11 21:24:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 11 Mar 2006 12:24:29 -0800 (PST) Subject: [Tutor] activestate In-Reply-To: <a431e57e529837b2a65accdefd8881ad@mac.com> Message-ID: <Pine.LNX.4.44.0603111224050.2350-100000@hkn.eecs.berkeley.edu> On Sat, 11 Mar 2006, kevin parks wrote: > I noticed a couple days ago that the active state archive seems to have > ceased. Is it going away? Hi Kevin, Can you check this again? It appears to look ok to me: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor From dyoo at hkn.eecs.berkeley.edu Sat Mar 11 21:30:47 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 11 Mar 2006 12:30:47 -0800 (PST) Subject: [Tutor] need help tracing a syntax error In-Reply-To: <4412EFE7.000003.00652@YOUR-4105E587B6> Message-ID: <Pine.LNX.4.44.0603111225280.2350-100000@hkn.eecs.berkeley.edu> > I get the message > > syntax error > > > and it highlights r2 > > in the line > > .If r2 == 1: Hi Kermit, Next time, rather than describe the error message here in paraphrase, please copy-and-paste it in. Your paraphrase of the situation here hides useful information. We would rather that you give it to us straight and unfiltered. (Gosh, I sound like I'm in a bar or something. *grin*) I can see a problem, but I'm not sure if it's the only one. Keywords are case sensitive. 'If' is different than 'if'. You're using 'If', which is not a keyword, so what Python is seeing is essentially: some_variable_name another_variable_name which is illegal syntax in Python. Python can't tell that 'If' is meant to be the keyword 'if', so the closest it can say is that something weird happened as it was reading up to 'r2', so that's why the syntax error arrow is pointing at r2 rather than the 'If'. From alan.gauld at freenet.co.uk Sat Mar 11 23:41:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 11 Mar 2006 22:41:47 -0000 Subject: [Tutor] need help tracing a syntax error References: <4412EFE7.000003.00652@YOUR-4105E587B6> Message-ID: <00d801c6455c$fb28ca20$0b01a8c0@xp> Hi, It would help us a lot if you send us a cut n paste of the actual code, not retyped versions. Particularly for syntax erros since a single wrong character might be all that's wrong and when you retype it its OK. I'm assuming you are retyping from the fact that you have uppercase keywords etc which aren't valid Python. Also for the error merssage can you cut n paste the full error since they contain a lot of useful info, do not just give us a description of the error. > def vmod(a , b ): > .r1 = b > .r2 = a > . m1 = 0 > .m2 = 1 > .q = Int(r1 / r2) > .r3 = r1 - q * r2 > .m3 = m1 - q * m2 > .while r3 != 0: > ...r1 = r2 > ...m1 = m2 > ...r2 = r3 > ...m2 = m3 > ...q = Int(r1 / r2) > ...r3 = r1 - r2 * q > ...m3 = m1 - m2 * q > .If r2 == 1: > ...If m2 < 0: > .....return( m2 + b) > ...Else: > .....return( m2 ) > .Else: > ...return( -r2 ) > I get the message > syntax error > in the line > > .If r2 == 1: > However if I > use the eval function in the shell, I get >>>> eval("factor30") > <module 'factor30' from 'c:\math\factoring\factor30.pyc'> Sorry, what is the connection between evaluating the string function30 and the code above? function30 doesn't appear anywhere... > and when I use help to look at the associated module, > > this function is not listed. It must be because of the syntax error. Which function? Do you mean that the function you have written is in a file called function30.py? If so then eval("function30") does not do anything with your function, it simply evaluated the name function30 and identifies that it is a module. But this next bit seems to suggest that this is not what you have done. > NAME > factor30 > > FILE > c:\math\factoring\factor30.py > Give me some hint for why this is happening. I feel the same way. Can you send us real code with the full error message and explain where function30 fits into the picture. Preferrably posted as plain text. Otherwise I'm completely confused! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Mar 11 23:56:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 11 Mar 2006 22:56:33 -0000 Subject: [Tutor] execute an OS command, get the output References: <Pine.LNX.4.44.0603110846310.22162-100000@violet.rahul.net> Message-ID: <00e401c6455f$0b1a9920$0b01a8c0@xp> >> But in this case I'd use Pytthon to search for the string and get the >> last 10 entries rather than grep/head... > > That was my initial thought, but the files are 1-3 gigabytes. The string > command takes 10-15 minutes to get through a file. I've been using the > pipe sequence manually, so I know it works, and only takes a second or two > to run. But surely the string command will take just as long to run regardless of whether you use pipes or read the output into Python? Are ytou saying that running strings on its own takes 10 minutes but running it in a pipe takes only a few seconds? What happens if you redirect the strings output to a file instead of a pipe - MS DOS terminal windows are notoriously slow, it could be the display update thats taking the trime... Just a suggestion. But 3GB files will take a while on any system! > The Python program is for my own use, so I don't have to worry about > whether and where string/grep/head are installed. Whatever works for you! :-) Alan G. From alan.gauld at freenet.co.uk Sun Mar 12 01:43:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 12 Mar 2006 00:43:03 -0000 Subject: [Tutor] need help tracing a syntax error References: <00d801c6455c$fb28ca20$0b01a8c0@xp> <441360CC.000007.01324@YOUR-4105E587B6> Message-ID: <00ea01c6456d$ebe011c0$0b01a8c0@xp> [CC'd to the list...] >> Also for the error merssage can you cut n paste the full error since >> they contain a lot of useful info, do not just give us a description of >> the error. >no error message was provided. > It only highlighted the variable in the If statement. But that's exactly what we need to see. Do not describe the error send the actual message including the line that it highlights. There are often subtle hints in those messages that help pinpoint the error, so simply saying it was a syntax error and what was highlighted is not as useful as sending us the actual text of the error. In this case it wouldn't have made much difference since it was the uppercase keywords, but in other scenarios it might make all the difference. I can't emphasise this enough, including the complete actual error message is one of the most useful things you can do to help us help you. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kp8 at mac.com Sun Mar 12 02:06:47 2006 From: kp8 at mac.com (kevin parks) Date: Sat, 11 Mar 2006 20:06:47 -0500 Subject: [Tutor] weighted choices from among many lists In-Reply-To: <mailman.10412.1142108674.27774.tutor@python.org> References: <mailman.10412.1142108674.27774.tutor@python.org> Message-ID: <a0d6b66dcd806626ad19078950706711@mac.com> On Mar 11, 2006, at 3:24 PM, tutor-request at python.org wrote: > > Message: 1 > Date: Sat, 11 Mar 2006 08:34:49 -0500 > From: Kent Johnson <kent37 at tds.net> > Subject: Re: [Tutor] weighted choices from among many lists > Cc: tutor at python.org > Message-ID: <4412D1F9.3040906 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > kevin parks wrote: >> I have several lists... and i would like to some times chose from one >> list and for a while choose from a different list, etc. > > You don't say what isn't working but I have a guess. The actual > windex() > function looks OK to me. yes, that part always worked fine... not the most robust thing, but it works. > >> def test(): >> >> lst_a = [ 'red', 'green', 'blue', 'orange', 'violet', 'yellow', >> 'black', 'white' ] >> lst_b = ['Rottweiler', 'Beagle', 'Sheepdog', 'Collie', 'Boxer', >> 'Terrier', 'Bulldog', 'Chihuahua', 'Retriever', 'Collie', 'Dachshund', >> 'Doberman', 'Greyhound', 'Pug', 'Spaniel'] >> lst_c = ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout'] >> lst_d = ['fender', 'gibson', 'rickenbacker', 'guild', 'danelectro', >> 'gretsch', 'martin', 'ibanez'] >> x = [('lst_a', .50), ('lst_b', .25), ('lst_c', .10),('lst_d', .15)] > > x is list containing the *names* of the other lists. You need to keep > references to the lists so you can pick from them. > x = [(lst_a, .50), (lst_b, .25), (lst_c, .10),(lst_d, .15)] i am an idiot... someone shoot me.. i guess i got so carried away with typing the single quotes for the above lists that when i went to pack those up for windex i didn't realize that i had needlessly typed 'lst_a', etc. Sometimes you just need a fresh pair of eyes to pick up on that type of thing.... >> i = 1 >> while i < 100: >> lst = windex(x) >> print i, lst, > > with the change above this will print the list, not its name >> pick = random.choice(lst) > but this will work. > > If you want to be able to print the name of the list then you could > include both the name and the actual list in x: > > x = [(('lst_a', lst_a), .50), etc...] That produces: ('lst_c', ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout']) ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout'] i am actually trying to get name of list, the choice like so: lst_c Bock From mbroe at columbus.rr.com Sun Mar 12 02:46:54 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Sat, 11 Mar 2006 20:46:54 -0500 Subject: [Tutor] Unicode and regexes Message-ID: <49C96194-41EB-447C-B549-429F36799D6F@columbus.rr.com> Thanks Kent, for breaking the bad news. I'm not angry, just terribly, terribly disappointed. :) "From http://www.unicode.org/unicode/reports/tr18/ I see that \p{L} is intended to select Unicode letters, and it is part of a large number of selectors based on Unicode character properties." Yeah, that's the main cite, and yeah, a large, large number. The only sane way to use regexes with Unicode. Also see Friedl's 'Mastering Regular Expressions' Chapter 3: or actually, if you are a Python only person, don't: it will make you weep. "Python doesn't support this syntax. It has limited support for Unicode character properties [...]". Umm Earth to Python-guys, you *have heard* of Unicode, right? Call me crazy, but in this day and age, I assume a scripting language with regex support will implement standard Unicode conventions, unless there is a compelling reason not to. Very odd. Back to Perl. Right now. Just kidding. Not. Sheesh. This is a big flaw in Python, IMHO. I never saw it coming. From carroll at tjc.com Sun Mar 12 03:07:28 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 11 Mar 2006 18:07:28 -0800 (PST) Subject: [Tutor] execute an OS command, get the output In-Reply-To: <00e401c6455f$0b1a9920$0b01a8c0@xp> Message-ID: <Pine.LNX.4.44.0603111801430.22162-100000@violet.rahul.net> On Sat, 11 Mar 2006, Alan Gauld wrote: > But surely the string command will take just as long to run regardless > of whether you use pipes or read the output into Python? Surely it will! Except that it doesn't. > Are ytou saying that running strings on its own takes 10 minutes but > running it in a pipe takes only a few seconds? Yes, exactly. Not any pipe, though; a pipe that is satisfied and closes down after just the first few hundred lines or so. > What happens if you redirect the strings output to a file instead of a > pipe I haven't tried directing it to an actual file, but when directing it to nul: it's about 10-15 minutes; while directing it to the pipe is just a few seconds. I gotta admit, this took me by surprise, too, but my guess is that once the head command is done, it closes the pipe it's reading from, which is being filled by grep; grep takes the hint and terminates, closing the pipe it's reading from, which is being filled by strings; and strings takes the hint and terminates, even though it hasn't gotten through the entire file. And that all happens in a second or two. From ml.cyresse at gmail.com Sun Mar 12 03:05:25 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 12 Mar 2006 15:05:25 +1300 Subject: [Tutor] Sorting and secondary sorting. In-Reply-To: <4412E901.4030106@tds.net> References: <b6f3249e0603110553j464ee0e6hcb9b91503cca15d8@mail.gmail.com> <4412E901.4030106@tds.net> Message-ID: <b6f3249e0603111805h2a67cdd2w2e460fec7bf60d34@mail.gmail.com> Ahaha, thanks guys, I knew I was overlooking something. Regards, Liam Clarke On 3/12/06, Kent Johnson <kent37 at tds.net> wrote: > Liam Clarke wrote: > > Hi all, > > > > I'm trying to think of a way to sort a list of dictionaries. In pseudo-code: > > > > l = [ { "host":"foo", "db":"bob"}, > > { "host":"foo", "db":"dave"}, > > { "host":"fee", "db":"henry"} > > ] > > > > l.sort( key = lambda item: item["host"], second_key = lambda item: item["db"]) > > > > Which, if all went well, would give me - > > > > l = [ { "host":"fee", "db":"henry"} > > { "host":"foo", "db":"bob"}, > > { "host":"foo", "db":"dave"}, > > ] > > > > Just make a key that includes both of the values you want to sort on as > a tuple: > > l.sort( key = lambda item: (item["host"], item["db"])) > > Kent > > From kent37 at tds.net Sun Mar 12 03:37:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Mar 2006 21:37:52 -0500 Subject: [Tutor] weighted choices from among many lists In-Reply-To: <a0d6b66dcd806626ad19078950706711@mac.com> References: <mailman.10412.1142108674.27774.tutor@python.org> <a0d6b66dcd806626ad19078950706711@mac.com> Message-ID: <44138980.7030608@tds.net> kevin parks wrote: >>From: Kent Johnson <kent37 at tds.net> >>If you want to be able to print the name of the list then you could >>include both the name and the actual list in x: >> >> x = [(('lst_a', lst_a), .50), etc...] > > > > That produces: > ('lst_c', ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout']) > ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout'] > > i am actually trying to get name of list, the choice like so: > > lst_c > Bock Yes, you need to unpack the result of calling windex(). You so ably demonstrated unpacking the list in your for loop I thought you would figure it out :-) Try lst_name, lst = windex(x) then random.choice() and print. Kent From carroll at tjc.com Sun Mar 12 03:44:41 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 11 Mar 2006 18:44:41 -0800 (PST) Subject: [Tutor] execute an OS command, get the output In-Reply-To: <Pine.LNX.4.44.0603111801430.22162-100000@violet.rahul.net> Message-ID: <Pine.LNX.4.44.0603111832240.22162-100000@violet.rahul.net> On Sat, 11 Mar 2006, Terry Carroll wrote: > I gotta admit, this took me by surprise, too, but my guess is that once > the head command is done, it closes the pipe it's reading from, which is > being filled by grep; grep takes the hint and terminates, closing the pipe > it's reading from, which is being filled by strings; and strings takes the > hint and terminates, even though it hasn't gotten through the entire file. Just for the heack of it, I wrote a tiny Python echo program, and interposed it in the pipe between the strings and grep command: while 1: line = raw_input() print line The command line now looks like this: strings 00003193.DAT | python echo.py | grep Newsgroups: | head (the .DAT file is an Agent newsgroup file; the idea here is that by grepping for the first few lines with "Newsgroups:", I can tell what newsgroup the .DAT file is associated with.) I get: > strings 00003193.DAT | python echo.py | grep Newsgroups: | head -10 Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Newsgroups: comp.lang.python.announce Traceback (most recent call last): File "echo.py", line 3, in ? print line IOError: [Errno 22] Invalid argument close failed: [Errno 22] Invalid argument My guess is that the "Invalid argument" here was a write attempting to write to a closed file, the pipe. The string and grep commands (or IO routines called by them) probably detect this and close gracefully; the end result being that a set of piped commands only lasts as long as the shortest-lived consumer, and the upstream producers shut down when they can no longer write to the pipe. From kent37 at tds.net Sun Mar 12 04:13:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Mar 2006 22:13:01 -0500 Subject: [Tutor] Test code organization In-Reply-To: <441023D1.9010903@c-lab.de> References: <441023D1.9010903@c-lab.de> Message-ID: <441391BD.4030206@tds.net> Willi Richert wrote: > Hi, > > for some time I try to find the best test code organization. I've come > up with the following solution, which I guess is not optimal. Please > comment. OK I'll take a stab at it. > > In the code directory there is a special tests directory, which contains > all the unit test files. This is a common organization but I find I prefer to put the tests in the same directory as the modules under test. It makes the directory a bit more crowded but it keeps the modules and their tests close together. > There is the file alltests.py which collects > all python test files and executes them: > > ===================================== > import sys, unittest > sys.path.append(".") > sys.path.append("..") > > TEST_DIR = "tests" > > import glob > testCases = [t.split(".")[0] for t in glob.glob1(TEST_DIR, "*Tests.py")] > print "Found test case modules "+", ".join(testCases) > print > > for t in testCases: > exec("from %s import %s"%(TEST_DIR, t)) You could probably replace this with __import__ (or my_import() from the doc page for __import__()) but maybe it's not worth the trouble. > > def suite(): > exec("suites = tuple([x.suite() for x in [%s]])"%str(", > ".join(testCases))) I don't think you need exec here, you could use suites = [sys.modules.get(x).suite() for x in testCases] > suite = unittest.TestSuite(suites) > return suite > > > if __name__ == '__main__': > suite = suite() > result = unittest.TextTestRunner(verbosity=2).run(suite) > if result.wasSuccessful(): > sys.exit(0) > else: > sys.exit(1) > ====================================== > > > For every class to test I create a ClassTests.py file which contains the > following code: > Header: > ====================================== > import sys > sys.path.append("..") > > import unittest > from Class... import * > ====================================== > > The footer parses the available test classes: > ====================================== > def _testclasses(): > mod = sys.modules[__name__] > return [getattr(mod, name) for name in dir(mod) if > name.endswith('TestCase')] > > def suite(): > return unittest.TestSuite([unittest.makeSuite(tc) for tc in > _testclasses()]) I think all the above footer could be replaced with def suite(): return unittest.defaultTestLoader.loadTestsFromModule(sys.modules.get(__name__)) > > if __name__ == '__main__': > unittest.main() > ====================================== > > > What smalls badly is the sys.path.append() stuff every test file must > have. Improvements? I usually run everything from the base directory of the project. On Windows, the current dir is added to sys.path automatically. (On linux apparently this is not true.) Then the test classes can use normal imports and there is no need to alter sys.path in each test class. You might want to look at some of the other auto-discovery methods such as those included in nose and py.test, either for your own use or to see how they work. http://somethingaboutorange.com/mrl/projects/nose/ http://codespeak.net/py/current/doc/test.html Kent From kp8 at mac.com Sun Mar 12 04:18:36 2006 From: kp8 at mac.com (kevin parks) Date: Sat, 11 Mar 2006 22:18:36 -0500 Subject: [Tutor] weighted choices from among many lists In-Reply-To: <mailman.10439.1142131484.27774.tutor@python.org> References: <mailman.10439.1142131484.27774.tutor@python.org> Message-ID: <33b35c5033073a67cf99f660dd777001@mac.com> > Yes, you need to unpack the result of calling windex(). You so ably > demonstrated unpacking the list in your for loop I thought you would > figure it out :-) > > Try > lst_name, lst = windex(x) > > then random.choice() and print. > Thanks Kent i got it, just another brain-fart on my side... I was already doing something like: lst_name, lst = windex(x) pick = random.choice(lst) But instead of: print i, lst_name, pick I was idiotically still printing: print i, lst, pick now matter how you unpack it all... you are still gonna get lst if that is what is in your print statement... grrr.... of course the another way i would be a use a dictionary and us the list name as a key... the list as a value... Thanks, kevin From smiles at worksmail.net Sat Mar 11 02:43:01 2006 From: smiles at worksmail.net (Smith) Date: Fri, 10 Mar 2006 19:43:01 -0600 Subject: [Tutor] problems with numbers in my python code References: <mailman.10279.1142003192.27774.tutor@python.org> Message-ID: <04cd01c644ad$673b2c40$f72c4fca@csmith> | From: sjw28 | | Basically, I have a code with is almost finished but I've having | difficultly | with the last stage of the process. I have a program that gets assigns | different words with a different value via looking them up in a | dictionary: | | eg if THE is in the writing, it assigns 0.965 | | and once the whole passage is read it returns all the numbers in the | format | as follows: | | ['0.965', '1.000', '0.291', '1.000', '0.503'] | | However, I can't seem to get the program to treat the numbers as | numbers. If | I put them in the dictionary as 'THE' = int(0.965) the program | returns 1.0 | and if I put 'THE' = float(0.965) it returns 0.96555555549 or | something | similar. Neither of these are right! I basically need to access each | item in | the string as a number, because for my last function I want to | multiply them | all together by each other. | | I have tried two bits of code for this last bit, but neither are | working (I'm not sure about the first one but the second one should | work I think if | I could figure out how to return the values as numbers): | | 1st code | value = codons[x] * codons[x+1] | x = (int) | x = 0 | You defined x after you tried to use it and that was the error message: x was not defined yet in the first line of your code. Also, what were you trying to do with x = (int)? [cut] | | Code 2 - the most likely code | prod = 1 | for item in (codons): prod *= item | prod This line is not necessary. In the interactive window typing a variable name will cause the value to be shown to you. But in a script it does nothing. The next line (print prod) is the way to see the product. Also, what is item in Code 2 above: something like 'THE' or something like '0.965'? If you did something like putting the values in a dictionary (named something like 'values') then you should have something like prod *= float(values[item]) instead of what you have above. | print prod | | Gives this error message: | Traceback (most recent call last): | File "C:\Python24\code2", line 90, in -toplevel- | for item in (codons): prod *= item | TypeError: can't multiply sequence by non-int | | | Can anyone help me solve this problem? | Thanks. Others have mentioned why 0.965 doesn't look exactly like that when you view it in repr() form and they have told you where you can read more about this and what other module you might use to avoid this problem. HOWEVER, I don't think you need the decimal module for what you are doing. You have 17 digits of precision in the floating point numbers you are using. The numerical value that python is using for 0.965 is only 0.00000000000000003 units off from the true value. When you get done calculating your product I am guessing that you don't need 17 digits of precision (since your codon values only had 3 digits of precision). If you want a nice representation of your final answer showing maybe 4 of the leading digits, consider using the fpformat option, sci: >>> ll=['0.965', '1.000', '0.291', '1.000', '0.503'] >>> p=1 >>> for li in ll: ... p*=float(li) ... >>> print p 0.141249945 >>> from fpformat import sci >>> sci(0.141249945,3) #rounds to 3rd digit after the first non-zero one '1.412e-001' >>> float(_) #makes it a floating point number (a little ugly) 0.14119999999999999 >>> str(_) #rounds it to 12 digits of precision (or 1 part per trillion) '0.1412' >>> print str(float(sci(0.141249945,3))) #putting it all together 0.1412 Chris What are you going to do with your product when you are done computing it? From carroll at tjc.com Sun Mar 12 04:32:13 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 11 Mar 2006 19:32:13 -0800 (PST) Subject: [Tutor] execute an OS command, get the output In-Reply-To: <Pine.LNX.4.44.0603111832240.22162-100000@violet.rahul.net> Message-ID: <Pine.LNX.4.44.0603111928460.22162-100000@violet.rahul.net> On Sat, 11 Mar 2006, Terry Carroll wrote: > Just for the heack of it, I wrote a tiny Python echo program, and > interposed it in the pipe between the strings and grep command: > > while 1: > line = raw_input() > print line > > The command line now looks like this: > > strings 00003193.DAT | python echo.py | grep Newsgroups: | head Actually, to break it down to its simplest, with the python program: for i in range(1,10000): print "line", i I get: > writeabunch.py | head -5 line 1 line 2 line 3 line 4 line 5 Traceback (most recent call last): File "C:\Agent-files\Giganews\writeabunch.py", line 2, in ? print "line", i IOError: (0, 'Error') close failed: [Errno 22] Invalid argument Same thing, but a far simpler scenario. Interestingly, if I use a low enough range, say range(1,500), it simply runs to completion; I assume that 500 lines in the form of "line n\n" fit within the first written buffer. From wescpy at gmail.com Sun Mar 12 04:37:35 2006 From: wescpy at gmail.com (w chun) Date: Sat, 11 Mar 2006 19:37:35 -0800 Subject: [Tutor] execute an OS command, get the output In-Reply-To: <Pine.LNX.4.44.0603111832240.22162-100000@violet.rahul.net> References: <Pine.LNX.4.44.0603111801430.22162-100000@violet.rahul.net> <Pine.LNX.4.44.0603111832240.22162-100000@violet.rahul.net> Message-ID: <78b3a9580603111937u291b3ec7o95e767b8a2090b89@mail.gmail.com> ok, while we're on the subject, i thought i should ask a question for once(!). it's been awhile since i played with pipes, and i ran into this problem on the same day as this post! if i'm in the shell and playing with a 2-way game with the 'tr' command like so: $ tr '[a-z]' '[A-Z]' us US ca CA de DE $ i can interactively give the cmd some input via stdin and get something out of stdout... giving and taking until i press ^D to terminate the program. however, when i try this using subprocess/popen2, i find that i can't do the same interaction, i.e. writing to tr's stdin, reading from tr's stdout, ad nauseum. it seems that i have to give tr all of my input, then close tr's stdin pipe in order to read anything. (any attempts at reading before closing results in a blocked OS call, whether it's using the FD itself or os.read() on its fileno(). the only way for it to work as i described above is like this: >>> p = subprocess.Popen(('tr', '"[a-z]"', '"[A-Z]"'), stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) >>> po, pi = p.stdin, p.stdout >>> po.write('us\n') >>> po.write('ca\n') >>> po.write('de\n') >>> po.close() >>> pi.readlines() ['US\n', 'CA\n', 'DE\n'] >>> pi.close() i was hoping to do somethign more on the lines of: >>> po.write('us\n') >>> pi.read() # or pi.readline() 'US\n' >>> po.write('ca\n') >>> pi.read() 'CA\n' but to no avail. neither sending po.write(chr(4)) nor po.flush() seem to work. i basically can tell whether a read() will block (or not) using select, as in: >>> from select import select >>> sel = select([pi], [], [pi], 0) >>> sel ([], [], []) <--- MEANS IT WILL BLOCK or ([<open file '<fdopen>', mode 'r' at 0x39ac80>], [], []) -<- WON'T BLOCK is there anyway to do more "asynchronous" I/O where i can more or less interact with the other procses rather than what it's doing now? thanks you guys... i love the tutors! -wesley From alan.gauld at freenet.co.uk Sun Mar 12 09:32:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 12 Mar 2006 08:32:54 -0000 Subject: [Tutor] need help tracing a syntax error References: <00ea01c6456d$ebe011c0$0b01a8c0@xp> <4413709F.00000D.01324@YOUR-4105E587B6> Message-ID: <00f001c645af$8f4b06d0$0b01a8c0@xp> > There was no actual message. The syntax error message to me > occurred in a dialog box which closed immediately. What development tool are you using? I would change it, if it doesn't display a full error trace then it is depriving you of one of the most useful tools in Python! > It's not possible to copy and paste a highlight. > There was no error message except for the fact that r2 was highlighted. And how was the r2 highlighted? Again, what tool are you using? If you must stick with that tool then at least try running your code through the standard Python interpreter which will let you see the full error message, you can then paste that to us. > Anyway, now I understand about uppercase and lower case, > so I won't get a syntax error for this reason again. True, but there are many possible errors that you will get and not being able to clearly see the error text will be a big handicap to you and to us if you post a query. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Mar 12 09:37:19 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 12 Mar 2006 08:37:19 -0000 Subject: [Tutor] execute an OS command, get the output References: <Pine.LNX.4.44.0603111801430.22162-100000@violet.rahul.net> Message-ID: <010a01c645b0$2d4fe850$0b01a8c0@xp> > I gotta admit, this took me by surprise, too, but my guess is that once > the head command is done, it closes the pipe it's reading from, which is > being filled by grep; grep takes the hint and terminates, closing the pipe > it's reading from, which is being filled by strings; and strings takes the > hint and terminates, even though it hasn't gotten through the entire file. yeah, that kind of makes sense. I forgot you were using head not tail - I normally use tail for that kind of thing - in fact I think I've only used head about 2 or 3 times in my life! But head could well stop as soon as it gets the first 10 lines from grep. Interesting, I must try some experiments.... Alan G From alan.gauld at freenet.co.uk Sun Mar 12 09:39:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 12 Mar 2006 08:39:58 -0000 Subject: [Tutor] execute an OS command, get the output References: <Pine.LNX.4.44.0603111832240.22162-100000@violet.rahul.net> Message-ID: <011201c645b0$8bb7d880$0b01a8c0@xp> > Just for the heack of it, I wrote a tiny Python echo program, and > interposed it in the pipe between the strings and grep command: > > while 1: > line = raw_input() > print line > > The command line now looks like this: > >> strings 00003193.DAT | python echo.py | grep Newsgroups: | head -10 > Newsgroups: comp.lang.python.announce > ... > Newsgroups: comp.lang.python.announce > Traceback (most recent call last): > File "echo.py", line 3, in ? > print line > IOError: [Errno 22] Invalid argument > close failed: [Errno 22] Invalid argument Thats exactly what I ghad in mind! :-) You've saved me the effort, thanks agin. Alan G From smiles at worksmail.net Sun Mar 12 09:58:00 2006 From: smiles at worksmail.net (Smith) Date: Sun, 12 Mar 2006 02:58:00 -0600 Subject: [Tutor] *args consumption References: <Pine.LNX.4.44.0603101121170.8293-100000@hkn.eecs.berkeley.edu> Message-ID: <005c01c645b3$3633ba20$2c2c4fca@csmith> Danny Yoo wrote: || Am I missing some other usage where you wouldn't want to unpack the || *arg? If not, would the following "behind the scenes" behavior be || possible/preferred? || || ### || def foo(*arg): || pass || ### || || automatically does this || || ### || def foo(*arg): || if len(arg) == 1: || arg = arg[0] || pass || ### | | | Yes: what if we're passing foo() some mixed data? This might not be | as weird as it might sound: imagine that a cartegian point [x, y] is | represented either as a point: | | [x, y] | | or as a single x coordinate number x where the y coordinate is | assumed to be zero. | | x | | Our list would then contain a mix of data. For example, a list with | the points (4, 3) and (5, 0) and (2, 9) could be represented as: | | [[4, 3], 5, [2, 9]] | [cut] | But if we pass playConnectTheDots() with a single point, we want the | function not to automatically unpack the argument as if it were | something else: it would be a lossy kind of implicit transformation. | OK, I think it's becoming clear. I should think of the *arg in the receiving function as containing a list of things that were sent to it (actually, a tuple). I am likely confusing things a bit because I want to be able to receive an x,y coordinate as foo(x,y) rather than something like foo((x,y)). | If the case of len(points) == 1 is treated as a special case, that | would make the logic turn into... well, I don't know, it would be | ambiguous! | As I understand it now, reducing it to a single point rather than leaving it as a tuple of length 1 destroys ones ability to iterate over the items that were passed in. e.g. if you call foo(42) and foo has a *args as its only argument, them automatcally changine the received value of (42, ) to 42 would destroy the ability to loop over args as ### for arg in args: #do something ### As many times as I would prefer to have len == 1 arguments unpacked, if *args automatically behaved this way then likely the other half of the user-universe would be packing up things that have length 0 so they could iterate over them ;-) ### if len(args) == 0: args = (args, ) ### | From the example above, if we did feed it: | | playConnectTheDots([[4, 3]]) ## Draw the point (4, 3) | | vs: | | playConnectTheDots([4, 3]) ## Draw between (4, 0) and (3, 0) | | then imagine what would happen if Python did the kind of automatic | unwrapping you're thinking of. How would it tell the difference | between these two different cases? | If playConnectTheDots looks like this, ### def playConnectTheDots(*points): if len(points) == 1: points = points[0] for point in points: x,y = getX(point),getY(point) print 'plot %s %s' % (x,y) ### then I imagine it will work exactly as you are describing :-) I think you meant to call the function like this, ### playConnectTheDots(*[[4, 3]]) playConnectTheDots(*[4, 3]) ### if the function is defined as this: ### def playConnectTheDots(*points): for point in points: x,y = getX(point),getY(point) print 'plot %s %s' % (x,y) ### How would you have written the first line(s) of playConnectTheDots? Or did you mean to pass the values like this: ### playConnectTheDots(4, 3) #plot 4,0 and 3,0 playConnectTheDots([4, 3]) #plot 4,3 ### /c From project5 at redrival.net Sun Mar 12 12:11:18 2006 From: project5 at redrival.net (Andrei) Date: Sun, 12 Mar 2006 11:11:18 +0000 (UTC) Subject: [Tutor] i have a question References: <4ce40aaa0603102037u53143bs760d5ab5f70f101d@mail.gmail.com> Message-ID: <loom.20060312T120327-673@post.gmane.org> Tom Bachik <beamer30 <at> gmail.com> writes: > ok say u want python to ask the user to type a username then password for a game account thats easy but how do u get the information they typed back to you? Depends on the environment you're asking it in. If it's command-line, you're probably using the raw_input function in order to get the name. This function simply returns a string that you can use, so you could write something like: username = raw_input("Name: ") password = raw_input("Password: ") if CheckPassword(username, password): print "Hello %s" % username else: print "Incorrect name or password!" Other environments (e.g. wxPython, PyGame or web interfaces) offer different ways of achieving the same results, but I presume you're really new to Python and not yet messing around with those. Yours, Andrei From alan.gauld at freenet.co.uk Sun Mar 12 12:38:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 12 Mar 2006 11:38:09 -0000 Subject: [Tutor] execute an OS command, get the output References: <Pine.LNX.4.44.0603111801430.22162-100000@violet.rahul.net><Pine.LNX.4.44.0603111832240.22162-100000@violet.rahul.net> <78b3a9580603111937u291b3ec7o95e767b8a2090b89@mail.gmail.com> Message-ID: <014101c645c9$7002c2d0$0b01a8c0@xp> Wes, I haven't tried this but I notice you don't specify shell=True in your Popen calls, that might be the cause - ypou aren't acting like the shell does. But aws I say thats just a guess based on a quick scim of your port. Alan G. ----- Original Message ----- From: "w chun" <wescpy at gmail.com> To: <tutor at python.org> Sent: Sunday, March 12, 2006 3:37 AM Subject: Re: [Tutor] execute an OS command, get the output ok, while we're on the subject, i thought i should ask a question for once(!). it's been awhile since i played with pipes, and i ran into this problem on the same day as this post! if i'm in the shell and playing with a 2-way game with the 'tr' command like so: $ tr '[a-z]' '[A-Z]' us US ca CA de DE $ i can interactively give the cmd some input via stdin and get something out of stdout... giving and taking until i press ^D to terminate the program. however, when i try this using subprocess/popen2, i find that i can't do the same interaction, i.e. writing to tr's stdin, reading from tr's stdout, ad nauseum. it seems that i have to give tr all of my input, then close tr's stdin pipe in order to read anything. (any attempts at reading before closing results in a blocked OS call, whether it's using the FD itself or os.read() on its fileno(). the only way for it to work as i described above is like this: >>> p = subprocess.Popen(('tr', '"[a-z]"', '"[A-Z]"'), stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) >>> po, pi = p.stdin, p.stdout >>> po.write('us\n') >>> po.write('ca\n') >>> po.write('de\n') >>> po.close() >>> pi.readlines() ['US\n', 'CA\n', 'DE\n'] >>> pi.close() i was hoping to do somethign more on the lines of: >>> po.write('us\n') >>> pi.read() # or pi.readline() 'US\n' >>> po.write('ca\n') >>> pi.read() 'CA\n' but to no avail. neither sending po.write(chr(4)) nor po.flush() seem to work. i basically can tell whether a read() will block (or not) using select, as in: >>> from select import select >>> sel = select([pi], [], [pi], 0) >>> sel ([], [], []) <--- MEANS IT WILL BLOCK or ([<open file '<fdopen>', mode 'r' at 0x39ac80>], [], []) -<- WON'T BLOCK is there anyway to do more "asynchronous" I/O where i can more or less interact with the other procses rather than what it's doing now? thanks you guys... i love the tutors! -wesley From kent37 at tds.net Sun Mar 12 14:28:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 12 Mar 2006 08:28:17 -0500 Subject: [Tutor] *args consumption In-Reply-To: <041701c64450$91078760$f72c4fca@csmith> References: <041701c64450$91078760$f72c4fca@csmith> Message-ID: <441421F1.50508@tds.net> Smith wrote: > But there is another use that I am looking at right now (as encountered in the turtle module) where the arguments are analyzed in the function and not passed along. In such cases it seems like the first two lines of the function below are needed to get the passed arg out of the tuple form that is created and into the form expected in the function. > > ### > def goto(*arg): > if len(arg) == 1: > arg = arg[0] > x, y = arg > print x, y > goto(1,2) > pt = 1,2 > goto(pt) > ### > > Without those first two lines, passing 'pt' as in the example results > in a runtime error since arg = ((1, 2),) -- a tuple of length 1 -- cannot be unpacked into two items. > > MY QUESTION: since the pass_along function will work with this unpacking of length = 1 tuples and this is what you have to do anyway if you are going to consume the tuple in a function (as in the goto function above) is there a reason that this isn't automatically done for star arguments? Am I missing some other usage where you wouldn't want to unpack the *arg? If not, would the following "behind the scenes" behavior be possible/preferred? Danny has given some reasons why this is not useful standard behaviour. If this is a behaviour you need for many functions, you could create a decorator that provides it so you don't have to include the same boilerplate in each function. Decorators are functions that accept a function as an argument and return a new function as a result. Here is a decorator that will unpack a tuple argument: In [7]: def accept_tuple_or_coordinates(f): ...: def unpacking_f(*args): ...: if len(args) == 1: ...: x, y = args[0] ...: else: ...: x, y = args ...: return f(x, y) ...: return unpacking_f ...: This shows the typical structure of a decorator. It defines a new function that wraps its argument with some new functionality, and returns the new function. Now to define a function of a point that can take either a single point or a pair of coordinates, just write a function of a pair of coordinates and decorate it: In [8]: @accept_tuple_or_coordinates ...: def goto(x, y): ...: print 'Going to', x, y ...: ...: By prefixing the function definition with @accept_tuple_or_coordinates the newly defined function is passed as the argument to the decorator, and the result is rebound to the name of the defined function. It is exactly as if you had written def goto(x, y): ... goto = accept_tuple_or_coordinates(goto) In fact if you want to use decorators in Python 2.3 you have to use this method. A decorator is reusable so you can have lots of functions like this: In [9]: @accept_tuple_or_coordinates ...: def draw(x, y): ...: print 'Drawing', x, y ...: ...: Try it out: In [10]: goto(1, 2) Going to 1 2 In [11]: p = (3, 4) In [12]: goto(p) Going to 3 4 In [13]: draw(p) Drawing 3 4 It works! There are some subtleties to decorators that you can ignore but you may not want to. For example with this simple example the function name is changed by the decorator: In [14]: draw Out[14]: <function unpacking_f at 0x0101B8B0> Docstrings are also lost. The solution is to copy these attributes in the decorator, like this: def accept_tuple_or_coordinates(f): def unpacking_f(*args): if len(args) == 1: x, y = args[0] else: x, y = args return f(x, y) unpacking_f.__name__ = f.__name__ unpacking_f.__dict__ = f.__dict__ unpacking_f.__doc__ = f.__doc__ return unpacking_f Now the function name and docstring is preserved: In [16]: @accept_tuple_or_coordinates ....: def draw(x, y): ....: ''' Draws a single point at the given coordinates ''' ....: print 'Drawing', x, y ....: ....: In [17]: draw Out[17]: <function draw at 0x0101BBF0> In [18]: draw.__doc__ Out[18]: ' Draws a single point at the given coordinates ' Kent From annaraven at gmail.com Sun Mar 12 18:29:58 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Sun, 12 Mar 2006 09:29:58 -0800 Subject: [Tutor] *args consumption In-Reply-To: <441421F1.50508@tds.net> References: <041701c64450$91078760$f72c4fca@csmith> <441421F1.50508@tds.net> Message-ID: <cb361a610603120929w4b8893c1tfb0c0d3af60712f3@mail.gmail.com> On 3/12/06, Kent Johnson <kent37 at tds.net> wrote: > > > > Danny has given some reasons why this is not useful standard behaviour. > If this is a behaviour you need for many functions, you could create a > decorator that provides it so you don't have to include the same > boilerplate in each function. > > Decorators are functions that accept a function as an argument and > return a new function as a result. Here is a decorator that will unpack > a tuple argument: Thanks for a great example of what decorators are good for. Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060312/17ef3fac/attachment.html From wescpy at gmail.com Mon Mar 13 01:09:42 2006 From: wescpy at gmail.com (w chun) Date: Sun, 12 Mar 2006 16:09:42 -0800 Subject: [Tutor] execute an OS command, get the output In-Reply-To: <014101c645c9$7002c2d0$0b01a8c0@xp> References: <Pine.LNX.4.44.0603111801430.22162-100000@violet.rahul.net> <Pine.LNX.4.44.0603111832240.22162-100000@violet.rahul.net> <78b3a9580603111937u291b3ec7o95e767b8a2090b89@mail.gmail.com> <014101c645c9$7002c2d0$0b01a8c0@xp> Message-ID: <78b3a9580603121609r425ecc74x21f630f5f3f6087f@mail.gmail.com> yup, that's right. turns out that it doesn't really matter whether the cmd is run in a shell or not -- that's one of the great things about subprocess -- you get to choose. with os.system(), *everything* is run through the shell. apparently, this problem isn't new... the problem is that the other program doesn't provide unbuffered output. i don't know why it works in pure shell (and not programming pipes) environment, but it does. here is someone else that run into it, and they had access to the C source to the other program to add a flush() call to get the communication the way they want it (similar to my desired output): http://www.dalkescientific.com/writings/diary/archive/2005/04/15/wrapping_command_line_programs_II.html cheers, -wesley ps. on Mac OS X, their 'tr' command has a "-u" (unbuffered output) version, and once i added that option, my code worked exactly the want i desired. so i'm only SOL on the Linux one. :-) On 3/12/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > Wes, > > I haven't tried this but I notice you don't specify shell=True in your Popen > calls, > that might be the cause - ypou aren't acting like the shell does. > > But aws I say thats just a guess based on a quick scim of your port. > > Alan G. > > ----- Original Message ----- > From: "w chun" <wescpy at gmail.com> > To: <tutor at python.org> > Sent: Sunday, March 12, 2006 3:37 AM > Subject: Re: [Tutor] execute an OS command, get the output > > > ok, while we're on the subject, i thought i should ask a question for > once(!). it's been awhile since i played with pipes, and i ran into > this problem on the same day as this post! > > if i'm in the shell and playing with a 2-way game with the 'tr' command like > so: > > $ tr '[a-z]' '[A-Z]' > us > US > ca > CA > de > DE > $ > > i can interactively give the cmd some input via stdin and get > something out of stdout... giving and taking until i press ^D to > terminate the program. > > however, when i try this using subprocess/popen2, i find that i can't > do the same interaction, i.e. writing to tr's stdin, reading from tr's > stdout, ad nauseum. it seems that i have to give tr all of my input, > then close tr's stdin pipe in order to read anything. (any attempts > at reading before closing results in a blocked OS call, whether it's > using the FD itself or os.read() on its fileno(). the only way for it > to work as i described above is like this: > > >>> p = subprocess.Popen(('tr', '"[a-z]"', '"[A-Z]"'), > stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) > >>> po, pi = p.stdin, p.stdout > >>> po.write('us\n') > >>> po.write('ca\n') > >>> po.write('de\n') > >>> po.close() > >>> pi.readlines() > ['US\n', 'CA\n', 'DE\n'] > >>> pi.close() > > i was hoping to do somethign more on the lines of: > > >>> po.write('us\n') > >>> pi.read() # or pi.readline() > 'US\n' > >>> po.write('ca\n') > >>> pi.read() > 'CA\n' > > but to no avail. neither sending po.write(chr(4)) nor po.flush() seem > to work. i basically can tell whether a read() will block (or not) > using select, as in: > > >>> from select import select > >>> sel = select([pi], [], [pi], 0) > >>> sel > ([], [], []) <--- MEANS IT WILL BLOCK > or > ([<open file '<fdopen>', mode 'r' at 0x39ac80>], [], []) -<- WON'T BLOCK > > is there anyway to do more "asynchronous" I/O where i can more or less > interact with the other procses rather than what it's doing now? > > thanks you guys... i love the tutors! > -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From singletoned at gmail.com Mon Mar 13 10:38:36 2006 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 13 Mar 2006 09:38:36 +0000 Subject: [Tutor] Dynamically naming functions In-Reply-To: <441164AA.5040706@tds.net> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <441164AA.5040706@tds.net> Message-ID: <34bb7f5b0603130138l57b7385ax@mail.gmail.com> On 10/03/06, Kent Johnson <kent37 at tds.net> wrote: > Ed Singleton wrote: > > How does one go about creating functions, classes, or callable objects > > when you don't know their name in advance? (For example you want to > > read their names in from a text file or database). > > > > I want to use this in a few different places. For example Faces, the > > Python Project Management Planner Tool Thingy, uses nested functions > > to put tasks within a project: > > > > def MyProject(): > > start = "2006-03-06" > > resource = Me > > > > def Task1(): > > start = "2006-03-13" > > > > def Task2(): > > effort = "1w" > > > > I'd like to load these from a database (using SQLObject), but I'm not > > sure how I can define the name of the function from a filed in a > > database (or read in from a text file). > > This is truly bizarre use of nested functions. Faces must be looking at > the compiled function objects to pick this out. To be honest, this didn't seem that bizarre to me. If I understand properly (which I probably don't) functions are just callable objects like any other callable object (or at least can be treated as such). Isn't this just a handy way of creating a nested object structure that's readable? > I would look into the Project objects themselves and see if there is a > way to create them dynamically, rather than trying to build this > structure dynamically at run time. > > > > I'd also like to be able to do this in CherryPy/TurboGears so that I > > can create a dynamic site structure based on fields in a database. > > This seems more practical. I would define a class that is configured by > the database can be used as a CP model object. Then you can insert the > class into the CP site structure using setattr(). > > In general you can set an attribute of an object using setattr(): > setattr(foo, 'bar', 3) > is the same as > foo.bar = 3 > but the attribute name is specified as a string so it can be determined > at runtime. This makes sense, and I think I can see how I would use it. To create a bunch of objects from some data (just name and start date): for fname, startdate in data: def foo: start = "" setattr(foo, __name__, fname) setattr(foo, start, startdate) Sorting out the nesting should be fairly straightforward (if the above works). Thanks Ed From kent37 at tds.net Mon Mar 13 12:17:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Mar 2006 06:17:43 -0500 Subject: [Tutor] Dynamically naming functions In-Reply-To: <34bb7f5b0603130138l57b7385ax@mail.gmail.com> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <441164AA.5040706@tds.net> <34bb7f5b0603130138l57b7385ax@mail.gmail.com> Message-ID: <441554D7.2090709@tds.net> Ed Singleton wrote: > On 10/03/06, Kent Johnson <kent37 at tds.net> wrote: > >>Ed Singleton wrote: >>>I want to use this in a few different places. For example Faces, the >>>Python Project Management Planner Tool Thingy, uses nested functions >>>to put tasks within a project: >>> >>>def MyProject(): >>> start = "2006-03-06" >>> resource = Me >>> >>> def Task1(): >>> start = "2006-03-13" >>> >>> def Task2(): >>> effort = "1w" >>> >>>I'd like to load these from a database (using SQLObject), but I'm not >>>sure how I can define the name of the function from a filed in a >>>database (or read in from a text file). >> >>This is truly bizarre use of nested functions. Faces must be looking at >>the compiled function objects to pick this out. > > > To be honest, this didn't seem that bizarre to me. If I understand > properly (which I probably don't) functions are just callable objects > like any other callable object (or at least can be treated as such). > Isn't this just a handy way of creating a nested object structure > that's readable? Why not just use nested dicts? MyProject = dict( start = "2006-03-06", resource = Me, Task1 = dict(start = "2006-03-13"), Task2 = dict(effort = "1w"), ) Maybe the appearance isn't quite as nice but the intent is clear, the code to access the data is *much* simpler, and it lends itself to the kind of programmatic creation you are trying to do. Take a look at task.Task._compile() in the faces source to see the gyrations it takes to extract the data in functional form. The Zen of Python says, "Explicit is better than implicit" "Simple is better than complex" >>In general you can set an attribute of an object using setattr(): >> setattr(foo, 'bar', 3) >>is the same as >> foo.bar = 3 >>but the attribute name is specified as a string so it can be determined >>at runtime. > > > This makes sense, and I think I can see how I would use it. > > To create a bunch of objects from some data (just name and start date): > > for fname, startdate in data: > def foo: > start = "" > setattr(foo, __name__, fname) > setattr(foo, start, startdate) > > Sorting out the nesting should be fairly straightforward (if the above works). No, it won't work. A function attribute is not the same as a local variable of the function. What you propose is essentially def foo(): pass foo.bar = 'data' but what you need is def foo(): bar = 'data' which is very different. faces looks at foo.func_code.co_names to find the names you have used, and it actually runs the function with a tracing hook to capture the values. There doesn't seem to be any other way to define a Task in faces, either. You have to actually create functions. I guess this might be a good place to use exec - just create the source code for the function defs in a string and exec it, then retrieve the function from the global namespace and pass it to faces. Then tell me why this API is better than using nested dicts. Kent Kent From singletoned at gmail.com Mon Mar 13 12:24:20 2006 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 13 Mar 2006 11:24:20 +0000 Subject: [Tutor] Dynamically naming functions In-Reply-To: <001c01c6443a$39b716d0$0b01a8c0@xp> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <001c01c6443a$39b716d0$0b01a8c0@xp> Message-ID: <34bb7f5b0603130324u24eb683dv@mail.gmail.com> On 10/03/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > How does one go about creating functions, classes, or callable objects > > when you don't know their name in advance? (For example you want to > > read their names in from a text file or database). > > First point, names of functions are no different to names of other things. > > def f(x): > y = blah.... > return y > > is essentialy the same as saying > > f = lambda x: blah... > > lambda defines a nameless (aka anonymous) function and then assigns that > function to the variable called f. > > Of course Pythons lambda construct is a bit brain dead so we can achieve > the same result with just assigning an existing function to a new name > > def f(x): > y = nblah... > return y > > g = f > > Now g is a new name that refers to the function called f. I have to say I assumed that if you then changed f, g would point to the new f rather than the old f, but I tried it out and it seems otherwise: >>> def f(x): ... print x ... >>> f(1) 1 >>> a = f >>> a(1) 1 >>> def f(x): ... print x * 2 ... >>> f(1) 2 >>> a(1) 1 >>> b = f >>> b(1) 2 Which is really cool, except that the names "a" and "b" need to be decided at run time. > And with nested function definitions we can write functions that > return functions: > > def makeMultiplyAndAdd(constants): > def f(x): > return constant[0] * constant[1] + x > return f > > > > I'd like to load these from a database (using SQLObject), > > but I'm not sure how I can define the name of the function > > from a field in a database (or read in from a text file). > > Same way as you would for any other kind of variable. > This has been discussed many times and there is some trickery you > can do using the built in dictionaries that Python uses for its namespaces. > But the biggest proiblem with introducing new names at run time is: > How does the existing code get to know about those names that > didn't exist when the code was written? Ypou need to have the code > go exploring for names, work out what kind ioopf value they hold etc... > It all gets very messy and complicated and fault prone. > > So the normal way to do this is to use a dictionary. > The dictionary is a collection of names with values asociated with them. > Those values can be functions or classes or anything else. > > Now your code can access the new names by using standard > dictionary iterators etc. All you need are some conventions around > how many parameters the functions have, their types etc. > > > I'd also like to be able to do this in CherryPy/TurboGears > > so that I can create a dynamic site structure based on fields > > in a database. > > Dynamic site structure shouldn't need dynamic creation of functions > although the structure might need to be dynamically loaded into a > data structure in the code. It might also be a parameter of the functions. Doesn't CherryPy/TurboGears require Classes and Functions for it's data structures? (Or parameters passed to them, of course). I had been thinking that I would load my whole site at startup, but I guess it would probably be better to write a function that takes the parameters and looks up the first to see if it exists as a page, then looks to see if the second is a child of the first etc. But this really feels like something CherryPy should be doing for me. > But as always remember that dynamic anything usually means > much harder to maintain. All of your backup/archiving tools and error > reporting tools etc will need to understand your dynamic structure too. > Dynamic sounds like fun but usually means grief and is only justified > as a last resort IMHO! For website, I can't really see how I can not have a dynamic structure. There's no way I'm writing a function for each "folder". I do take your point though, however you often find that it's easy to maintain something dynamic than huge amounts of more static stuff (as in the difference between hundreds of static web pages and using a cms of some kind). > But if you must go dynamic Python is as good a language to do it > in as you'll get. That's certainly been my experience so far.. Thanks Ed From smiles at worksmail.net Mon Mar 13 12:24:00 2006 From: smiles at worksmail.net (Smith) Date: Mon, 13 Mar 2006 05:24:00 -0600 Subject: [Tutor] *args consumption References: <mailman.57.1142247630.30512.tutor@python.org> Message-ID: <004d01c64694$d507cc40$ef2c4fca@csmith> | From: "Anna Ravenscroft" | Subject: Re: [Tutor] *args consumption | To: "Kent Johnson" | | Thanks for a great example of what decorators are good for. DITTO! I've been wondering when those would be useful, and having a need in hand, I'm likely to learn it now. Thanks for explaining the useage in this case. /c From kent37 at tds.net Mon Mar 13 13:49:44 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Mar 2006 07:49:44 -0500 Subject: [Tutor] Dynamically naming functions In-Reply-To: <34bb7f5b0603130324u24eb683dv@mail.gmail.com> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <001c01c6443a$39b716d0$0b01a8c0@xp> <34bb7f5b0603130324u24eb683dv@mail.gmail.com> Message-ID: <44156A68.8080908@tds.net> Ed Singleton wrote: > On 10/03/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: >>Dynamic site structure shouldn't need dynamic creation of functions >>although the structure might need to be dynamically loaded into a >>data structure in the code. It might also be a parameter of the functions. > > > Doesn't CherryPy/TurboGears require Classes and Functions for it's > data structures? (Or parameters passed to them, of course). CherryPy uses classes and functions as the foundation of the site hierarchy but the dynamic part of the site is usually handled by a function that processes parameters and generates a page, not by creating a function or class to handle every conceivable page. > For website, I can't really see how I can not have a dynamic > structure. There's no way I'm writing a function for each "folder". > I do take your point though, however you often find that it's easy to > maintain something dynamic than huge amounts of more static stuff (as > in the difference between hundreds of static web pages and using a cms > of some kind). No, you don't have to do that, you create a handler at a relatively high level that knows how to respond to a request. See for example http://www.cherrypy.org/wiki/PositionalParameters and the section "Partial matches and the default method" in the tutorial: http://www.cherrypy.org/wiki/CherryPyTutorial Kent From kent37 at tds.net Mon Mar 13 13:52:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Mar 2006 07:52:48 -0500 Subject: [Tutor] Dynamically naming functions In-Reply-To: <441554D7.2090709@tds.net> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <441164AA.5040706@tds.net> <34bb7f5b0603130138l57b7385ax@mail.gmail.com> <441554D7.2090709@tds.net> Message-ID: <44156B20.5020804@tds.net> Kent Johnson wrote: > Why not just use nested dicts? > > MyProject = dict( > start = "2006-03-06", > resource = Me, > Task1 = dict(start = "2006-03-13"), > Task2 = dict(effort = "1w"), > ) or nest class instances directly: MyProject = Project( start = "2006-03-06", resource = Me, Task1 = Task(start = "2006-03-13"), Task2 = Task(effort = "1w"), ) That seems pretty clear to me, it would be a snap to create dynamically and the implementation is simple. Kent From singletoned at gmail.com Mon Mar 13 14:49:23 2006 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 13 Mar 2006 13:49:23 +0000 Subject: [Tutor] Dynamically naming functions In-Reply-To: <441554D7.2090709@tds.net> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <441164AA.5040706@tds.net> <34bb7f5b0603130138l57b7385ax@mail.gmail.com> <441554D7.2090709@tds.net> Message-ID: <34bb7f5b0603130549j23ef638ey@mail.gmail.com> On 13/03/06, Kent Johnson <kent37 at tds.net> wrote: > Ed Singleton wrote: > > On 10/03/06, Kent Johnson <kent37 at tds.net> wrote: > > > >>Ed Singleton wrote: > >>>I want to use this in a few different places. For example Faces, the > >>>Python Project Management Planner Tool Thingy, uses nested functions > >>>to put tasks within a project: > >>> > >>>def MyProject(): > >>> start = "2006-03-06" > >>> resource = Me > >>> > >>> def Task1(): > >>> start = "2006-03-13" > >>> > >>> def Task2(): > >>> effort = "1w" > >>> > >>>I'd like to load these from a database (using SQLObject), but I'm not > >>>sure how I can define the name of the function from a filed in a > >>>database (or read in from a text file). > >> > >>This is truly bizarre use of nested functions. Faces must be looking at > >>the compiled function objects to pick this out. > > > > > > To be honest, this didn't seem that bizarre to me. If I understand > > properly (which I probably don't) functions are just callable objects > > like any other callable object (or at least can be treated as such). > > Isn't this just a handy way of creating a nested object structure > > that's readable? > > Why not just use nested dicts? > > MyProject = dict( > start = "2006-03-06", > resource = Me, > Task1 = dict(start = "2006-03-13"), > Task2 = dict(effort = "1w"), > ) > > Maybe the appearance isn't quite as nice but the intent is clear, the > code to access the data is *much* simpler, and it lends itself to the > kind of programmatic creation you are trying to do. Take a look at > task.Task._compile() in the faces source to see the gyrations it takes > to extract the data in functional form. The Zen of Python says, > "Explicit is better than implicit" > "Simple is better than complex" Point taken. Dict's are easier. And the appearance is fine. I've just discovered with a little playing, that you can do: >>> def z(v): ... def f(x): ... print x * v ... return f ... >>> c = z(3) >>> c(1) 3 >>> funcdict = dict(foo = z(4)) >>> funcdict["foo"](1) 4 Which was obvious enough that I thought of trying it, but surprising enough that I was really pleased when it worked. > >>In general you can set an attribute of an object using setattr(): > >> setattr(foo, 'bar', 3) > >>is the same as > >> foo.bar = 3 > >>but the attribute name is specified as a string so it can be determined > >>at runtime. > > > > > > This makes sense, and I think I can see how I would use it. > > > > To create a bunch of objects from some data (just name and start date): > > > > for fname, startdate in data: > > def foo: > > start = "" > > setattr(foo, __name__, fname) > > setattr(foo, start, startdate) > > > > Sorting out the nesting should be fairly straightforward (if the above works). > > No, it won't work. A function attribute is not the same as a local > variable of the function. What you propose is essentially > def foo(): pass > foo.bar = 'data' > > but what you need is > def foo(): > bar = 'data' > > which is very different. > > faces looks at foo.func_code.co_names to find the names you have used, > and it actually runs the function with a tracing hook to capture the values. > > There doesn't seem to be any other way to define a Task in faces, > either. You have to actually create functions. I guess this might be a > good place to use exec - just create the source code for the function > defs in a string and exec it, then retrieve the function from the global > namespace and pass it to faces. Then tell me why this API is better than > using nested dicts. Agreed, though to be fair the author of faces has probably overcomplicated the code for handling it (which is a damn shame as it is really quite a nice project planning tool). I guess you can't blindly iterate over the methods of functions, as there are other methods there that you might not want to use (like setattr and stuff, maybe?). Ed From kent37 at tds.net Mon Mar 13 15:08:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Mar 2006 09:08:06 -0500 Subject: [Tutor] Dynamically naming functions In-Reply-To: <34bb7f5b0603130549j23ef638ey@mail.gmail.com> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <441164AA.5040706@tds.net> <34bb7f5b0603130138l57b7385ax@mail.gmail.com> <441554D7.2090709@tds.net> <34bb7f5b0603130549j23ef638ey@mail.gmail.com> Message-ID: <44157CC6.7070702@tds.net> Ed Singleton wrote: > On 13/03/06, Kent Johnson <kent37 at tds.net> wrote: > I've just discovered with a little playing, that you can do: > > >>>>def z(v): > > ... def f(x): > ... print x * v > ... return f > ... > >>>>c = z(3) >>>>c(1) > > 3 > >>>>funcdict = dict(foo = z(4)) >>>>funcdict["foo"](1) > > 4 > > Which was obvious enough that I thought of trying it, but surprising > enough that I was really pleased when it worked. Yes, functions are first-class objects in Python. Functions can be assigned to variable, passed to and returned from functions, stored in lists and dictionaries...this is *very* useful in many contexts. >>faces looks at foo.func_code.co_names to find the names you have used, >>and it actually runs the function with a tracing hook to capture the values. >> >>There doesn't seem to be any other way to define a Task in faces, >>either. You have to actually create functions. I guess this might be a >>good place to use exec - just create the source code for the function >>defs in a string and exec it, then retrieve the function from the global >>namespace and pass it to faces. Then tell me why this API is better than >>using nested dicts. > > > Agreed, though to be fair the author of faces has probably > overcomplicated the code for handling it (which is a damn shame as it > is really quite a nice project planning tool). I guess you can't > blindly iterate over the methods of functions, as there are other > methods there that you might not want to use (like setattr and stuff, > maybe?). He may have overcomplicated it, but not by much. Offhand I couldn't even think of how he might have done it, I had to look at the code. Python has some ability to look at the details of a function - the attributes of func_code - but to find out what value a local variable gets, you have to call the function. These values aren't exposed outside the function, that is why he uses the settrace() hook. You might want to contact the author of faces and see what he suggests. Maybe he would add an alternate method of creating Tasks and Projects. Otherwise building and exec'ing a string is the only thing I can think of. Yuck. Kent From alan.gauld at freenet.co.uk Mon Mar 13 18:38:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 13 Mar 2006 17:38:09 -0000 Subject: [Tutor] Dynamically naming functions References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <001c01c6443a$39b716d0$0b01a8c0@xp> <34bb7f5b0603130324u24eb683dv@mail.gmail.com> Message-ID: <019001c646c4$e53a5ee0$0b01a8c0@xp> > For website, I can't really see how I can not have a dynamic > structure. There's no way I'm writing a function for each "folder". Hmm, this may be a CherryPie concept thing but the vast majority of websites do not have dynamic structures. It really shouldn't be necessary. Why would you need to write a function per folder, simply write one function that takes the folder as an argument. > I do take your point though, however you often find that it's easy to > maintain something dynamic than huge amounts of more static stuff Very rarely, its easy to do backups of huge amounts of data if you know where to find it, its hard to trawl all over a changing structure looking for the things that need backing up. Particularly if, when you try to restore it, it needs to go in a different place to where you found it! > in the difference between hundreds of static web pages and using > a cms of some kind). Yes but a CMS normally uses a static structure with dynamic content. The templates stored in one place and the content in another. The templates know where to look for the content and the content doesn't care where the templates are. Dynamic content is 'A Good Thing', dynamic structure is usually bad. BTW On the concept of loading your entire site at startup; if you are sharing a server you will make yourself very unpopular since you will be a huge resource hog. That's why ASP, JSP and other frameworks go to a lot of trouble to manage session lengths etc - to free up any unused resources and keep server speed up. Loading the structure of the site in the form of links might be reasonable, but only load content when you absolutely must. This also helps the maintainers update the site without restarting it. Alan G. From cspears2002 at yahoo.com Tue Mar 14 02:08:37 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 13 Mar 2006 17:08:37 -0800 (PST) Subject: [Tutor] How does this work? Message-ID: <20060314010837.70177.qmail@web51610.mail.yahoo.com> Out of Learning Python, I was given this text: This is a paragraph that mentions bell peppers multiple times. For one, here is a red pepper and dried tomato salad recipe. I don't like to use green peppers in my salads as much because they have a harsher flavor. This second paragraph mentions red peppers and green peppers but not the "s" word (s-a-l-a-d), so no bells should show up. This third paragraph mentions red peppercorns and green peppercorns, which aren't vegetables but spices (by the way, bell peppers really aren't peppers, they're chilies, but would you rather have a good cook or a good botanist prepare your salad?). I am supposed to write a program to replace the strings "green pepper" and "red pepper" with "bell pepper" only if they occur together in a paragraph before the word "salad" and not if they are followed (with no space) by the string "corn." I'm supposed to do this without regular expressions. Here is the solution that was given to me: file = open('pepper.txt') text = file.read() paragraphs = text.split('\n\n') def find_indices_for(big, small): indices = [] cum = 0 while 1: index = big.find(small) if index == -1: return indices indices.append(index+cum) big = big[index+len(small):] cum = cum + index + len(small) def fix_paragraphs_with_word(paragraphs, word): lenword = len(word) for par_no in range(len(paragraphs)): p = paragraphs[par_no] wordpositions = find_indices_for(p, word) if wordpositions == []: return for start in wordpositions: # Look for 'pepper' ahead. indexpepper = p.find('pepper') if indexpepper == -1: return -1 if p[start:indexpepper].strip(): # Something other than whitespace in between! continue where = indexpepper+len('pepper') if p[where:where+len('corn')] == 'corn': # It's immediately followed by 'corn'! continue if p.find('salad') < where: # It's not followed by 'salad'. continue # Finally! We get to do a change! p = p[:start] + 'bell' + p[start+lenword:] paragraphs[par_no] = p # Change mutable argument! fix_paragraphs_with_word(paragraphs, 'red') fix_paragraphs_with_word(paragraphs, 'green') for paragraph in paragraphs: print paragraph+'\n' When I first read the question and saw the solution, I was overwhelmed! What was going on?! However, I took the program apart line by line and understand most of it now. I am still fuzzy on a few parts. if p[start:indexpepper].strip(): continue What is that supposed to accomplish? If the program can remove whitespace between red and pepper, it's supposed to move on? p = p[:start] + 'bell' + p[start+lenword:] paragraphs[par_no] = p # Change mutable argument! Not sure how the above lines are supposed to change the text...Give me regular expressions any day! Clarifications are welcome! From kent37 at tds.net Tue Mar 14 03:48:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Mar 2006 21:48:11 -0500 Subject: [Tutor] How does this work? In-Reply-To: <20060314010837.70177.qmail@web51610.mail.yahoo.com> References: <20060314010837.70177.qmail@web51610.mail.yahoo.com> Message-ID: <44162EEB.6030502@tds.net> Christopher Spears wrote: > > if p[start:indexpepper].strip(): > continue > > What is that supposed to accomplish? If the program > can remove whitespace between red and pepper, it's > supposed to move on? Not quite - p[start:indexpepper] is a string. p[start:indexpepper].strip() is the string with whitespace removed from both ends. The test is true if the string is not empty. So essentially this is testing to see if p[start:indexpepper] contains anything other than whitespace; if so, it the 'continue' is executed which skips the rest of that loop iteration and starts the next. > > p = p[:start] + 'bell' + p[start+lenword:] This builds a new string from pieces of the old one p[:start] - all of p up to but not including the index start p[start+lenword:] - all of p from the index start+lenword to the end > paragraphs[par_no] = p # Change mutable argument! and inserts it into the list of paragraphs (replacing what was there) Kent From kp8 at mac.com Tue Mar 14 09:02:47 2006 From: kp8 at mac.com (kevin parks) Date: Tue, 14 Mar 2006 03:02:47 -0500 Subject: [Tutor] scaling values In-Reply-To: <mailman.10578.1142271422.27774.tutor@python.org> References: <mailman.10578.1142271422.27774.tutor@python.org> Message-ID: <031f2907fa24622c0aeaf2aba27778fa@mac.com> i have various functions (that i didn't write) that put out data in lists of various types. But some functions (which i didn't write) that expect the data to be scaled, sometimes 0-1 sometimes 1-2, sometimes 0-127..., sometimes 0 - 32768... gosh you name it. In other words i have a bunch of black boxes that don't speak the same language .... is there a scaling function in python (or numeric or scipy) that can scale a list of values to a high precision? x = [13, 71, 120, 88, 82, 100, 10, 65, 101, 45, 26] foo = scale(x, 0, 1.0) and get that list scaled 0 to 1, or if i had: x = [.12789, .982779, .19798198, .266796, .656527, .257877091] foo = scale(x, 0, 127) cheers, -kp-- From dyoo at hkn.eecs.berkeley.edu Tue Mar 14 09:41:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Mar 2006 00:41:31 -0800 (PST) Subject: [Tutor] scaling values In-Reply-To: <031f2907fa24622c0aeaf2aba27778fa@mac.com> Message-ID: <Pine.LNX.4.44.0603140035050.25971-100000@hkn.eecs.berkeley.edu> On Tue, 14 Mar 2006, kevin parks wrote: > is there a scaling function in python (or numeric or scipy) that can > scale a list of values to a high precision? > > x = [13, 71, 120, 88, 82, 100, 10, 65, 101, 45, 26] > > foo = scale(x, 0, 1.0) Hi Kevin, I'm still confused by the problem. Let's try small examples. Let's say we had this: ########################## x = [13] scaledX = scale(x, 0, 1.0) ########################## What would 'scaledX' have? I'm asking because I have no clue from the problem description! *grin* (There's some hidden knowledge that you have about the problem, so I'm trying to make sure it's out in the open.) We can ask the same question with a slightly larger (but still small) example: x = [13, 71] What should we expect from things like: scale(x, 0.0, 1.0) scale(x, 0.0, 2.0) scale(x, 1.0, 2.0) The results of small examples will help clarify what we'd need to do to make scale() work. Good luck to you! From singletoned at gmail.com Tue Mar 14 10:50:00 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 14 Mar 2006 09:50:00 +0000 Subject: [Tutor] Dynamically naming functions In-Reply-To: <019001c646c4$e53a5ee0$0b01a8c0@xp> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <001c01c6443a$39b716d0$0b01a8c0@xp> <34bb7f5b0603130324u24eb683dv@mail.gmail.com> <019001c646c4$e53a5ee0$0b01a8c0@xp> Message-ID: <34bb7f5b0603140150t32a584fel@mail.gmail.com> On 13/03/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > For website, I can't really see how I can not have a dynamic > > structure. There's no way I'm writing a function for each "folder". > > Hmm, this may be a CherryPie concept thing but the vast majority > of websites do not have dynamic structures. It really shouldn't be > necessary. Why would you need to write a function per folder, > simply write one function that takes the folder as an argument. > > > I do take your point though, however you often find that it's easy to > > maintain something dynamic than huge amounts of more static stuff > > Very rarely, its easy to do backups of huge amounts of data if you > know where to find it, its hard to trawl all over a changing structure > looking for the things that need backing up. Particularly if, when you > try to restore it, it needs to go in a different place to where you found > it! Backing up is generally one of the lesser of my worries. Maintaining content is primary. Unless you are dynamically generating static pages, they are a nightmare to maintain. Particularly as it tends to be quite repetitive. A large amount of the code on any page is the same as on any other page (page structure, boilerplate, etc). I think it's a generally accepted principle that computers are better at handling thousands of files like that better than humans are. The more of the repetitive stuff that can be removed and given to a computer, the better. > > in the difference between hundreds of static web pages and using > > a cms of some kind). > > Yes but a CMS normally uses a static structure with dynamic content. > The templates stored in one place and the content in another. The > templates know where to look for the content and the content doesn't > care where the templates are. I think we might be using different meanings of structure. I'm referring to the site structure, as in which page is a parent of which other page. The site structure is just another aspect of the content. A reference to the parent/child pages is just another attribute like content and title. A (good) CMS would create a dynamic structure for the user to browse, with folders and pages easily creatable and movable, and references to pages would be dynamic so that if yo0u move a page internal links to it still work. > Dynamic content is 'A Good Thing', dynamic structure is usually bad. But structure is just an aspect of content. > BTW On the concept of loading your entire site at startup; if you are > sharing a server you will make yourself very unpopular since you will > be a huge resource hog. That's why ASP, JSP and other frameworks > go to a lot of trouble to manage session lengths etc - to free up any > unused resources and keep server speed up. Loading the structure > of the site in the form of links might be reasonable, but only load content > when you absolutely must. This also helps the maintainers update the > site without restarting it. I have my own dedicated server, but point taken. Though I will still need to reload the structure of the site when the maintainers change it (adding/removing pages etc). Ed From work at infomaniak.ch Tue Mar 14 14:31:19 2006 From: work at infomaniak.ch (Cedric BRINER) Date: Tue, 14 Mar 2006 14:31:19 +0100 Subject: [Tutor] ldap client Message-ID: <20060314133119.GG4333@obs.unige.ch> debian/sarge hello, I'm wanting to interogate an ldap server to fetch informations. so I'm looking for a python2.4 ldap client. And the only I've found is python2.4-ldaptor. Does some of you knows an good ldap client which use SSL ? Ced. -- Cedric BRINER Geneva - Switzerland From singletoned at gmail.com Tue Mar 14 16:14:19 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 14 Mar 2006 15:14:19 +0000 Subject: [Tutor] Using Beautiful Soup to extract tag names Message-ID: <34bb7f5b0603140714s354f6539n@mail.gmail.com> I have (unfortunately) received some data in XML format. I need to use it in Python, preferably as a list of dictionaries. The data is a flat representation of a table, in the style: <tablename> <fieldname1>Some Data</fieldname1> <fieldname2>Some Data</fieldname> ... </tablename> <tablename> <fieldname1>Some Data</fieldname1> <fieldname2>Some Data</fieldname> ... and so on (where tablename is always the same in one file). It looks like Beautiful Soup would be a good option to quickly change it into a usable format, but I need to extract the field name (there's lots and lots of fields) as well as the data, and I can't work out how to do that in Beautiful Soup. If anyone can give me some help I'd be grateful, or if they can point me in the direction of a better solution. Thanks Ed From sanelson at gmail.com Tue Mar 14 16:29:04 2006 From: sanelson at gmail.com (Steve Nelson) Date: Tue, 14 Mar 2006 15:29:04 +0000 Subject: [Tutor] Iterate over letters in a word Message-ID: <b6131fdc0603140729i587f95b2l4f33d0cadae2de36@mail.gmail.com> Hello, I'm trying to work on some programs to help me understand ciphers and ultimately cryptography. I've understood so far, that a simple form of bit-level cryptography is to split the original message into chunks the same length as a 'key' and then do an xor. I'm trying to keep this really simple so I can understand from first principles - so eg: "Hello Tutors!" could be split into: "Hell" "o Tut" "ors!" and xor'd with "beer" I think I understand how xor works (thanks to an earlier post) but I'm not sure how to iterate over each letter in a string. What is the recommended way to do this? Thanks, S. From kent37 at tds.net Tue Mar 14 16:38:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Mar 2006 10:38:46 -0500 Subject: [Tutor] Using Beautiful Soup to extract tag names In-Reply-To: <34bb7f5b0603140714s354f6539n@mail.gmail.com> References: <34bb7f5b0603140714s354f6539n@mail.gmail.com> Message-ID: <4416E386.5080206@tds.net> Ed Singleton wrote: > I have (unfortunately) received some data in XML format. I need to > use it in Python, preferably as a list of dictionaries. The data is a > flat representation of a table, in the style: > > <tablename> > <fieldname1>Some Data</fieldname1> > <fieldname2>Some Data</fieldname> > ... > </tablename> > <tablename> > <fieldname1>Some Data</fieldname1> > <fieldname2>Some Data</fieldname> > ... > > and so on (where tablename is always the same in one file). ElementTree makes short work of this: from elementtree import ElementTree xml = ''' <data><tablename> <fieldname1>Some Data1</fieldname1> <fieldname2>Some Data2</fieldname2> </tablename> <tablename> <fieldname3>Some Data3</fieldname3> <fieldname4>Some Data4</fieldname4> </tablename> </data>''' doc = ElementTree.fromstring(xml) # use ElementTree.parse() to parse a file for table in doc.findall('tablename'): for field in table.getchildren(): print field.tag, field.text prints: fieldname1 Some Data1 fieldname2 Some Data2 fieldname3 Some Data3 fieldname4 Some Data4 If speed is an issue then look at cElementTree which has the same interface and is blazingly fast. http://effbot.org/zone/element.htm Kent From bgailer at alum.rpi.edu Tue Mar 14 16:32:25 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 14 Mar 2006 07:32:25 -0800 Subject: [Tutor] scaling values In-Reply-To: <031f2907fa24622c0aeaf2aba27778fa@mac.com> References: <mailman.10578.1142271422.27774.tutor@python.org> <031f2907fa24622c0aeaf2aba27778fa@mac.com> Message-ID: <4416E209.3050505@alum.rpi.edu> kevin parks wrote: > i have various functions (that i didn't write) that put out data in > lists of various types. But some functions (which i didn't write) that > expect the data to be scaled, sometimes 0-1 sometimes 1-2, sometimes > 0-127..., sometimes 0 - 32768... gosh you name it. In other words i > have a bunch of black boxes that don't speak the same language .... is > there a scaling function in python (or numeric or scipy) that can scale > a list of values to a high precision? > Perhaps someone on this list knows what you want, but I don't. What is "scaling"? What does foo look like? > x = [13, 71, 120, 88, 82, 100, 10, 65, 101, 45, 26] > > foo = scale(x, 0, 1.0) > > and get that list scaled 0 to 1, or if i had: > > x = [.12789, .982779, .19798198, .266796, .656527, .257877091] > > foo = scale(x, 0, 127) > > From David.Heiser at intelliden.com Tue Mar 14 16:56:49 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Tue, 14 Mar 2006 08:56:49 -0700 Subject: [Tutor] scaling values Message-ID: <3CABD13EA1D5D347A1B75014BD54CFD502B0BBD8@COSIUM03.intelliden.net> Is this what you're asking for? # Scaler.py # def scale(OldList, NewMin, NewMax): NewRange = float(NewMax - NewMin) OldMin = min(x) OldMax = max(x) OldRange = float(OldMax - OldMin) ScaleFactor = NewRange / OldRange print '\nEquasion: NewValue = ((OldValue - ' + str(OldMin) + ') x ' + str(ScaleFactor) + ') + ' + str(NewMin) + '\n' NewList = [] for OldValue in OldList: NewValue = ((OldValue - OldMin) * ScaleFactor) + NewMin NewList.append(NewValue) return NewList x = [13, 71, 120, 88, 82, 100, 10, 65, 101, 45, 26] foo = scale(x, 0, 1.0) ##x = [.12789, .982779, .19798198, .266796, .656527, .257877091] ##foo = scale(x, 0, 127) ##x = [0, 50, 100] ##foo = scale(x, 32, 212) ##x = [32, 122, 212] ##foo = scale(x, 0, 100) print 'New List = ' + str(foo) Print >>> Equasion: NewValue = ((OldValue - 10) x 0.00909090909091) + 0 New List = [0.027272727272727271, 0.55454545454545456, 1.0, 0.70909090909090911, 0.65454545454545454, 0.81818181818181812, 0.0, 0.5, 0.82727272727272727, 0.31818181818181818, 0.14545454545454545] >>> -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of kevin parks Sent: Tuesday, March 14, 2006 1:03 AM To: tutor at python.org Subject: [Tutor] scaling values i have various functions (that i didn't write) that put out data in lists of various types. But some functions (which i didn't write) that expect the data to be scaled, sometimes 0-1 sometimes 1-2, sometimes 0-127..., sometimes 0 - 32768... gosh you name it. In other words i have a bunch of black boxes that don't speak the same language .... is there a scaling function in python (or numeric or scipy) that can scale a list of values to a high precision? x = [13, 71, 120, 88, 82, 100, 10, 65, 101, 45, 26] foo = scale(x, 0, 1.0) and get that list scaled 0 to 1, or if i had: x = [.12789, .982779, .19798198, .266796, .656527, .257877091] foo = scale(x, 0, 127) cheers, -kp-- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From singletoned at gmail.com Tue Mar 14 17:05:26 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 14 Mar 2006 16:05:26 +0000 Subject: [Tutor] Using Beautiful Soup to extract tag names In-Reply-To: <4416E386.5080206@tds.net> References: <34bb7f5b0603140714s354f6539n@mail.gmail.com> <4416E386.5080206@tds.net> Message-ID: <34bb7f5b0603140805q4ec9233cu@mail.gmail.com> As always Kent, you're amazing. That will do perfectly. (Though the ElementTree documentation seems a bit difficult to get through. I'm sure I'll get through it eventually). Thanks Ed On 14/03/06, Kent Johnson <kent37 at tds.net> wrote: > Ed Singleton wrote: > > I have (unfortunately) received some data in XML format. I need to > > use it in Python, preferably as a list of dictionaries. The data is a > > flat representation of a table, in the style: > > > > <tablename> > > <fieldname1>Some Data</fieldname1> > > <fieldname2>Some Data</fieldname> > > ... > > </tablename> > > <tablename> > > <fieldname1>Some Data</fieldname1> > > <fieldname2>Some Data</fieldname> > > ... > > > > and so on (where tablename is always the same in one file). > > ElementTree makes short work of this: > > from elementtree import ElementTree > > xml = ''' > <data><tablename> > <fieldname1>Some Data1</fieldname1> > <fieldname2>Some Data2</fieldname2> > </tablename> > <tablename> > <fieldname3>Some Data3</fieldname3> > <fieldname4>Some Data4</fieldname4> > </tablename> > </data>''' > > doc = ElementTree.fromstring(xml) > # use ElementTree.parse() to parse a file > > for table in doc.findall('tablename'): > for field in table.getchildren(): > print field.tag, field.text > > > prints: > fieldname1 Some Data1 > fieldname2 Some Data2 > fieldname3 Some Data3 > fieldname4 Some Data4 > > If speed is an issue then look at cElementTree which has the same > interface and is blazingly fast. > http://effbot.org/zone/element.htm > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Mar 14 17:19:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Mar 2006 11:19:58 -0500 Subject: [Tutor] Using Beautiful Soup to extract tag names In-Reply-To: <34bb7f5b0603140805q4ec9233cu@mail.gmail.com> References: <34bb7f5b0603140714s354f6539n@mail.gmail.com> <4416E386.5080206@tds.net> <34bb7f5b0603140805q4ec9233cu@mail.gmail.com> Message-ID: <4416ED2E.3070607@tds.net> Ed Singleton wrote: > As always Kent, you're amazing. Thank you! > > That will do perfectly. (Though the ElementTree documentation seems a > bit difficult to get through. I'm sure I'll get through it > eventually). Unfortunately I have to agree with you on this one. ET is going to be part of the standard lib in Python 2.5, I hope the docs get a bit of work. Kent From hugonz-lists at h-lab.net Tue Mar 14 18:58:15 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 14 Mar 2006 11:58:15 -0600 Subject: [Tutor] scaling values In-Reply-To: <031f2907fa24622c0aeaf2aba27778fa@mac.com> References: <mailman.10578.1142271422.27774.tutor@python.org> <031f2907fa24622c0aeaf2aba27778fa@mac.com> Message-ID: <44170437.6020503@h-lab.net> Hi Kevin, Do you mean:? 1)take the highest value in the list hval, take the lowest value in the list lval 2) pass top and bottom NEW values for the list: ntop nbot 3) then build another list where hval is replaced by ntop, lval is replaced by nbot, and everything else is geometrically scaled in bewteen? AFAIK, there is no such function in the standard lib (maybe someone knows better) but it is not hard to build such a function. Have you tried? It would be something like: def scaled(x, ntop, nbot) See that you can use min(L) and max(L) to get lval and hval Try it, and if you run into problems or have questions, don't hesitate to ask. Hope that helps, Hugo From dyoo at hkn.eecs.berkeley.edu Tue Mar 14 19:40:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Mar 2006 10:40:14 -0800 (PST) Subject: [Tutor] Iterate over letters in a word In-Reply-To: <b6131fdc0603140729i587f95b2l4f33d0cadae2de36@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603141035001.17060-100000@hkn.eecs.berkeley.edu> > "Hello Tutors!" could be split into: > > "Hell" "o Tut" "ors!" > > and xor'd with "beer" > > I think I understand how xor works (thanks to an earlier post) but I'm > not sure how to iterate over each letter in a string. What is the > recommended way to do this? The xor bitwise operator works with numbers --- not directly with strings --- so one of your tasks will probably be to take a chunk like: "beer" and turn it into some numeric bit pattern. It turns out that this isn't too bad if we abuse the 'struct' module: http://www.python.org/doc/lib/module-struct.html The idea is to unpack four single characters as a single 4-byte integer. For example: ###### >>> struct.unpack('i', 'food') (1685024614,) ###### This kind of transformation is reversable: ###### >>> struct.pack('i', 1685024614) 'food' ###### Does this make sense? From sanelson at gmail.com Tue Mar 14 21:43:57 2006 From: sanelson at gmail.com (Steve Nelson) Date: Tue, 14 Mar 2006 20:43:57 +0000 Subject: [Tutor] Iterate over letters in a word In-Reply-To: <Pine.LNX.4.44.0603141035001.17060-100000@hkn.eecs.berkeley.edu> References: <b6131fdc0603140729i587f95b2l4f33d0cadae2de36@mail.gmail.com> <Pine.LNX.4.44.0603141035001.17060-100000@hkn.eecs.berkeley.edu> Message-ID: <b6131fdc0603141243u7b7413e3m15036024eee117fb@mail.gmail.com> On 3/14/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > The idea is to unpack four single characters as a single 4-byte integer. That's really useful, thanks, as I was planning to iterate over each letter and call ord() > This kind of transformation is reversable: Highly useful. Thanks very much indeed. > Does this make sense? Absolutely. S. From m_webber_sydney at yahoo.com.au Tue Mar 14 21:53:08 2006 From: m_webber_sydney at yahoo.com.au (Matthew Webber) Date: Tue, 14 Mar 2006 20:53:08 -0000 Subject: [Tutor] Iterate over letters in a word In-Reply-To: <b6131fdc0603140729i587f95b2l4f33d0cadae2de36@mail.gmail.com> Message-ID: <001f01c647a9$4c6d1460$0200a8c0@kookaburra> As a side note, remember that that xor-ing a key with a message is trivial to break (it's just a variation on the Vigenere cipher first published in 1568). So don't use if for any real applications. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Steve Nelson Sent: 14 March 2006 15:29 To: tutor at python.org Subject: [Tutor] Iterate over letters in a word Hello, I'm trying to work on some programs to help me understand ciphers and ultimately cryptography. I've understood so far, that a simple form of bit-level cryptography is to split the original message into chunks the same length as a 'key' and then do an xor. I'm trying to keep this really simple so I can understand from first principles - so eg: "Hello Tutors!" could be split into: "Hell" "o Tut" "ors!" and xor'd with "beer" I think I understand how xor works (thanks to an earlier post) but I'm not sure how to iterate over each letter in a string. What is the recommended way to do this? Thanks, S. From sanelson at gmail.com Tue Mar 14 22:07:54 2006 From: sanelson at gmail.com (Steve Nelson) Date: Tue, 14 Mar 2006 21:07:54 +0000 Subject: [Tutor] Iterate over letters in a word In-Reply-To: <001f01c647a9$4c6d1460$0200a8c0@kookaburra> References: <b6131fdc0603140729i587f95b2l4f33d0cadae2de36@mail.gmail.com> <001f01c647a9$4c6d1460$0200a8c0@kookaburra> Message-ID: <b6131fdc0603141307w7db24ea9i491dd5404f9553d6@mail.gmail.com> On 3/14/06, Matthew Webber <m_webber_sydney at yahoo.com.au> wrote: > As a side note, remember that that xor-ing a key with a message is trivial > to break (it's just a variation on the Vigenere cipher first published in > 1568). So don't use if for any real applications. Yes - at the moment this is just a way for me to begin to get my head around how cryptography works from anabsolutely ludicrously basic position. This all started because I couldn't get my head around the difference between an encryption algorithm and the key. I thought that by writing my own, I would work it out! S. From sanelson at gmail.com Tue Mar 14 22:08:04 2006 From: sanelson at gmail.com (Steve Nelson) Date: Tue, 14 Mar 2006 21:08:04 +0000 Subject: [Tutor] Iterate over letters in a word In-Reply-To: <b6131fdc0603141243u7b7413e3m15036024eee117fb@mail.gmail.com> References: <b6131fdc0603140729i587f95b2l4f33d0cadae2de36@mail.gmail.com> <Pine.LNX.4.44.0603141035001.17060-100000@hkn.eecs.berkeley.edu> <b6131fdc0603141243u7b7413e3m15036024eee117fb@mail.gmail.com> Message-ID: <b6131fdc0603141308i74809239p590452e7960f1007@mail.gmail.com> On 3/14/06, Steve Nelson <sanelson at gmail.com> wrote: > On 3/14/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > > The idea is to unpack four single characters as a single 4-byte integer. > > That's really useful, thanks, as I was planning to iterate over each > letter and call ord() Ok, so experimenting a little further, and looking at the documentation, it seems that len(string) and calcsize (i) must be the same. Is there a reason why 'i' is a 4 byte integer? Doesn't this mean that this method wouldn't scale if I then decided I wanted to use, eg, a 6 byte key instead of a four? Or do I misunderstand? I am also struggling to understand why a 4 byte integer is so large? >>> mystring = "Hello I am Steve" >>> import struct >>> struct.unpack('i', mystring[0:4]) (1819043144,) I can see that the largest number I can generate in a 1 byte integer is 255 - which is (2^8)-1. Is the point that with a 4 byte number I can actually get (2^32)-1 , ie 4294967295? This just seems like a huge number! I suppose I've answered my question... but any comments or clarifications would help a lot. S. From dyoo at hkn.eecs.berkeley.edu Tue Mar 14 22:12:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Mar 2006 13:12:39 -0800 (PST) Subject: [Tutor] Iterate over letters in a word In-Reply-To: <001f01c647a9$4c6d1460$0200a8c0@kookaburra> Message-ID: <Pine.LNX.4.44.0603141301400.9789-100000@hkn.eecs.berkeley.edu> > As a side note, remember that that xor-ing a key with a message is > trivial to break (it's just a variation on the Vigenere cipher first > published in 1568). So don't use if for any real applications. Hi Matthew, Counterpoint: think of "one-time pads". http://en.wikipedia.org/wiki/One-time_pad XOR itself is just a technique --- it's just a binary operation between two bit patterns --- but the use of one-time pads provides unbreakable encryption. As long as the xor-ing key is protected, and as long as the encrypting key pattern is as long as the message, it's theoretically unbreakable. If we reuse the same encrypting bit-pattern over and over, or make the XORing key less than random, then all bets are off, of course. *grin* There are different encryption schemes that, at its heart, use XOR. But XOR itself is not inherently insecure: it's our use of it that determines the quality of the result. From dyoo at hkn.eecs.berkeley.edu Tue Mar 14 22:17:12 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 14 Mar 2006 13:17:12 -0800 (PST) Subject: [Tutor] Iterate over letters in a word In-Reply-To: <b6131fdc0603141307w7db24ea9i491dd5404f9553d6@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603141313100.9789-100000@hkn.eecs.berkeley.edu> > Yes - at the moment this is just a way for me to begin to get my head > around how cryptography works from anabsolutely ludicrously basic > position. This all started because I couldn't get my head around the > difference between an encryption algorithm and the key. I thought that > by writing my own, I would work it out! Hi Steve, Yup; it really has to do with numbers. Once we manage that leap, then it's just a matter of writing functions that transform numbers to other numbers. When you want to get more in depth, you may find: http://mitpress.mit.edu/sicp/psets/ps3/readme.html useful; it's a fun homework assignment on the RSA cryptosystem. The support functions are in Scheme, but converting it to Python isn't too bad. Best of wishes! From adam.jtm30 at gmail.com Tue Mar 14 22:49:27 2006 From: adam.jtm30 at gmail.com (Adam) Date: Tue, 14 Mar 2006 21:49:27 +0000 Subject: [Tutor] Iterate over letters in a word In-Reply-To: <Pine.LNX.4.44.0603141313100.9789-100000@hkn.eecs.berkeley.edu> References: <b6131fdc0603141307w7db24ea9i491dd5404f9553d6@mail.gmail.com> <Pine.LNX.4.44.0603141313100.9789-100000@hkn.eecs.berkeley.edu> Message-ID: <be4fbf920603141349yb0e3428r@mail.gmail.com> Here's something you might find useful they've just started a series on cryptography on this site, you can read them or listen to a podcast. From adam.jtm30 at gmail.com Tue Mar 14 22:50:10 2006 From: adam.jtm30 at gmail.com (Adam) Date: Tue, 14 Mar 2006 21:50:10 +0000 Subject: [Tutor] Iterate over letters in a word In-Reply-To: <be4fbf920603141349yb0e3428r@mail.gmail.com> References: <b6131fdc0603141307w7db24ea9i491dd5404f9553d6@mail.gmail.com> <Pine.LNX.4.44.0603141313100.9789-100000@hkn.eecs.berkeley.edu> <be4fbf920603141349yb0e3428r@mail.gmail.com> Message-ID: <be4fbf920603141350t3731fb5do@mail.gmail.com> On 14/03/06, Adam <adam.jtm30 at gmail.com> wrote: > Here's something you might find useful they've just started a series > on cryptography on this site, you can read them or listen to a > podcast. > D'oh! Would help if I actually stuck the link in http://www.grc.com/SecurityNow.htm#30 From kp8 at mac.com Wed Mar 15 00:03:40 2006 From: kp8 at mac.com (kevin parks) Date: Tue, 14 Mar 2006 18:03:40 -0500 Subject: [Tutor] scaling values In-Reply-To: <Pine.LNX.4.44.0603140035050.25971-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0603140035050.25971-100000@hkn.eecs.berkeley.edu> Message-ID: <9e81dbfac306f5bb88c47683b4023333@mac.com> hi, Seems my post added much confusion. Sorry... I was hoping not to have to post my code since it is really wrong and slightly embarrassing.. what i am trying to do is map an input range of values to output range. I was hoping to make it a bit of an all purpose utility that would map pretty much any input range to an output range, also do inverted mapping... and also handle negative numbers and perhaps even a flag for exponential mapping. import random def scaleX(in_seq, low, hi): range1 = max(in_seq) - min(in_seq) #range2 = max(out_seq) - min(outseq) range2 = hi - low ratio = range1/range2 return [(x * ratio) for x in in_seq] def test(): # Create a list of 15 random integers in the range 0 to 127 # see if we can map it to 0 -> 1 inseq = random.sample(xrange(128), 25) print print scaleX(inseq, 0.0, 1.0) print if __name__ == "__main__": test() From sanelson at gmail.com Wed Mar 15 00:11:10 2006 From: sanelson at gmail.com (Steve Nelson) Date: Tue, 14 Mar 2006 23:11:10 +0000 Subject: [Tutor] Splitting a string into n-sized bytes Message-ID: <b6131fdc0603141511l5c43eca7p37de8de165fbe269@mail.gmail.com> Hello all, Further to my previous puzzling, I've been working out the best way to chop a string up into n-sized words: I'm aware that I can use a slice of the string, with, eg, myWord[0:4]. I am also aware that I can do blob = myWord.pop(0) to take (and remove) the first character. I can botch these together, eg myFourLetterWord = myWord.pop(0)+myWord.pop(0)+myWord.pop(0)+myWord.pop(0) but that is really horrid. I then tried doing something suitably silly, as follows: 1) Find the length of string. 2) Create a list using range(0, length, 4) 3) We now have the end points for each 'word', eg 4, 8, 12. 4) Now create a list of tuples that represent the slices we need, ie (0,4), (5,8) etc 5) Iterate over this list, grabbing the slices as depicted in the tuples. 6) Use these tuples to grab slices. The code looked like this: #!/usr/bin/env python myString = "Sir, you are an egotistical rhetorician!!!" length=len(myString) extra=length%4 if extra > 0: myString = myString+("#"*extra)+"#" r = range(0, len(myString), 4) wordRange=[] for i in r: if i>1: wordRange.append((int(i-4),i)) for t in wordRange: print myString[t[0]:t[1]] Surely there's an easier way? S. From adam.jtm30 at gmail.com Wed Mar 15 00:41:39 2006 From: adam.jtm30 at gmail.com (Adam) Date: Tue, 14 Mar 2006 23:41:39 +0000 Subject: [Tutor] Splitting a string into n-sized bytes In-Reply-To: <b6131fdc0603141511l5c43eca7p37de8de165fbe269@mail.gmail.com> References: <b6131fdc0603141511l5c43eca7p37de8de165fbe269@mail.gmail.com> Message-ID: <be4fbf920603141541k4d9cb12ag@mail.gmail.com> On 14/03/06, Steve Nelson <sanelson at gmail.com> wrote: > Hello all, > > Further to my previous puzzling, I've been working out the best way to > chop a string up into n-sized words: > > I'm aware that I can use a slice of the string, with, eg, myWord[0:4]. > > I am also aware that I can do blob = myWord.pop(0) to take (and > remove) the first character. I can botch these together, eg > myFourLetterWord = > myWord.pop(0)+myWord.pop(0)+myWord.pop(0)+myWord.pop(0) but that is > really horrid. > > I then tried doing something suitably silly, as follows: > > 1) Find the length of string. > 2) Create a list using range(0, length, 4) > 3) We now have the end points for each 'word', eg 4, 8, 12. > 4) Now create a list of tuples that represent the slices we need, ie > (0,4), (5,8) etc > 5) Iterate over this list, grabbing the slices as depicted in the tuples. > 6) Use these tuples to grab slices. > > The code looked like this: > #!/usr/bin/env python > myString = "Sir, you are an egotistical rhetorician!!!" > length=len(myString) > extra=length%4 > if extra > 0: > myString = myString+("#"*extra)+"#" > r = range(0, len(myString), 4) > wordRange=[] > for i in r: > if i>1: > wordRange.append((int(i-4),i)) > for t in wordRange: > print myString[t[0]:t[1]] > > Surely there's an easier way? > > S. How's this?: >>> myString = "Sir, you are an egotistical rhetorician!!!" >>> [myString[i:i+4] for i in range(0, len(myString), 4)] ['Sir,', ' you', ' are', ' an ', 'egot', 'isti', 'cal ', 'rhet', 'oric', 'ian!', '!!'] Hopefully that should point you in the right direction to do n-sized words as well. From kent37 at tds.net Wed Mar 15 03:51:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Mar 2006 21:51:51 -0500 Subject: [Tutor] scaling values In-Reply-To: <9e81dbfac306f5bb88c47683b4023333@mac.com> References: <Pine.LNX.4.44.0603140035050.25971-100000@hkn.eecs.berkeley.edu> <9e81dbfac306f5bb88c47683b4023333@mac.com> Message-ID: <44178147.8010703@tds.net> kevin parks wrote: > hi, > > Seems my post added much confusion. Sorry... I was hoping not to have > to post my code since it is really wrong and slightly embarrassing.. I think the confusion was about what input range to use. From your code it looks like you want to use just the actual range of input values. > what i am trying to do is map an input range of values to output range. > I was hoping to make it a bit of an all purpose utility that would map > pretty much any input range to an output range, also do inverted > mapping... and also handle negative numbers and perhaps even a flag for > exponential mapping. > > import random > > def scaleX(in_seq, low, hi): > range1 = max(in_seq) - min(in_seq) > #range2 = max(out_seq) - min(outseq) > range2 = hi - low > ratio = range1/range2 > return [(x * ratio) for x in in_seq] This is actually pretty close. You have ratio backwards and you need to account for the offsets min(in_seq) and low. Try in_low = min(in_seq) ratio = range2/range1 return [ ((x-in_low) * ratio + low) for x in in_seq ] Kent From hk at pop.ms Wed Mar 15 03:20:05 2006 From: hk at pop.ms (hk at pop.ms) Date: Wed, 15 Mar 2006 03:20:05 +0100 Subject: [Tutor] Tix: binding Message-ID: <382176391@web.de> I am looking at Tix and I am stuck with what seems to be a simple problem: I want to bind the cancel buttom of a ExFileSelectBox to a routine in my class, but can not make it work. I guess the problem is the same for any binding of tix sub-widgets, so if someone could send some sample code. >>> import Tix >>> root = Tix.Tk() >>> box = Tix.ExFileSelectBox(root) >>> print box.subwidget(name='cancel') .11827520.bf.cancel #so the sub-widget cancel buttom is there But how to bind it ? >>> box.cancel(command = lambda a,b : a+b ) Traceback (most recent call last): File "<pyshell#12>", line 1, in ? box.cancel(command = lambda a,b : a+b ) AttributeError: _dummyButton instance has no __call__ method Or >>> box.subwidget(name='cancel' , command = lambda a,b : a+b ) Traceback (most recent call last): File "<pyshell#13>", line 1, in ? box.subwidget(name='cancel' , command = lambda a,b : a+b ) TypeError: subwidget() got an unexpected keyword argument 'command' So, it seems I can not bind to command, but what then ? >From the Tix docu I thought the buttoms are normal Tkinter widgets ? -- Harm From john at fouhy.net Wed Mar 15 04:30:29 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 15 Mar 2006 16:30:29 +1300 Subject: [Tutor] [Fwd: Re: Indoor ultimate] In-Reply-To: <cc837f20603141848pa4251f0y57de8883c0e05037@mail.gmail.com> References: <441760D0.4090807@vuw.ac.nz> <9830887c0603141639l9121b31g1c3d21d62e2fd8db@mail.gmail.com> <44176362.3070204@vuw.ac.nz> <9830887c0603141649n199d1f47hf41383104809d3db@mail.gmail.com> <4417657E.50008@vuw.ac.nz> <441767FA.2000807@vuw.ac.nz> <a01350c40603141709p61180f56r3a9cbebc9d32438@mail.gmail.com> <44176B42.8010702@vuw.ac.nz> <5e58f2e40603141729p25b1cbbch@mail.gmail.com> <cc837f20603141848pa4251f0y57de8883c0e05037@mail.gmail.com> Message-ID: <5e58f2e40603141930x2cac9ec7o@mail.gmail.com> On 15/03/06, Sam B <rincewindtvd at gmail.com> wrote: > I'm keen! > > what shoe type do you reccomend? Non-marking cross trainers will do. If you want to spend more money, go into shoe clinic and tell them you want shoes for playing indoor ultimate. I ended up with a pair of Adidas handball shoes. Expect to pay $200 or more, though. -- John. From john at fouhy.net Wed Mar 15 04:31:04 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 15 Mar 2006 16:31:04 +1300 Subject: [Tutor] [Fwd: Re: Indoor ultimate] In-Reply-To: <5e58f2e40603141930x2cac9ec7o@mail.gmail.com> References: <441760D0.4090807@vuw.ac.nz> <44176362.3070204@vuw.ac.nz> <9830887c0603141649n199d1f47hf41383104809d3db@mail.gmail.com> <4417657E.50008@vuw.ac.nz> <441767FA.2000807@vuw.ac.nz> <a01350c40603141709p61180f56r3a9cbebc9d32438@mail.gmail.com> <44176B42.8010702@vuw.ac.nz> <5e58f2e40603141729p25b1cbbch@mail.gmail.com> <cc837f20603141848pa4251f0y57de8883c0e05037@mail.gmail.com> <5e58f2e40603141930x2cac9ec7o@mail.gmail.com> Message-ID: <5e58f2e40603141931u1561fb3bm@mail.gmail.com> Sorry guys, total brain fart there :-) From smiles at worksmail.net Wed Mar 15 04:42:55 2006 From: smiles at worksmail.net (Smith) Date: Tue, 14 Mar 2006 21:42:55 -0600 Subject: [Tutor] Splitting a string into n-sized bytes References: <mailman.10764.1142391121.27774.tutor@python.org> Message-ID: <002c01c647e7$3926a810$742c4fca@csmith> | From: "Steve Nelson" | | Further to my previous puzzling, I've been working out the best way to | chop a string up into n-sized words: | I think the follow use of groupby is from Raymond Hettinger from ASPN recipes. The batch() function will return an iterable to you in user-definable sized sets. #### from itertools import groupby def batch(iterable, size): def ticker(x, s=size, a=[-1]): r = a[0] = a[0] + 1 return r // s for k, g in groupby(iterable, ticker): yield g s='this is my string to parse up.' for i in batch(s,4): print list(i) #### The output is lists of (in this case) 4 characters; the last group is shorter, but you already know how to fix that. #### ['t', 'h', 'i', 's'] [' ', 'i', 's', ' '] ['m', 'y', ' ', 's'] ['t', 'r', 'i', 'n'] ['g', ' ', 't', 'o'] [' ', 'p', 'a', 'r'] ['s', 'e', ' ', 'u'] ['p', '.'] #### /c From yogesh193 at lycos.com Wed Mar 15 05:43:39 2006 From: yogesh193 at lycos.com (yogeshwarran Nadeson) Date: Tue, 14 Mar 2006 23:43:39 -0500 Subject: [Tutor] Help me please Message-ID: <20060315044339.AE55586B14@ws7-1.us4.outblaze.com> Hello, I am a newbie in python programming without previous programming experience.Here i would like to ask a question based on the exercises given by Josh Cogliatti in his tutorial.I'll paste the question.Hope you can help me to solve it.I'd like to end it by saying thanks for all yourr help. :Modify the password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print ``That must have been complicated.'' This is the previous password program: Password.py # Waits until a password has been entered. Use control-C to break out with out # the password #Note that this must not be the password so that the # while loop runs at least once. password = "foobar" #note that != means not equal while password != "unicorn": password = raw_input("Password:") print "Welcome in" Password.py # Waits until a password has been entered. Use control-C to break out with out # the password #Note that this must not be the password so that the # while loop runs at least once. password = "foobar" #note that != means not equal while password != "unicorn": password = raw_input("Password:") print "Welcome in" -- _______________________________________________ Search for businesses by name, location, or phone number. -Lycos Yellow Pages http://r.lycos.com/r/yp_emailfooter/http://yellowpages.lycos.com/default.asp?SRC=lycos10 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060314/1ffb3977/attachment.htm From kp8 at mac.com Wed Mar 15 06:23:51 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 15 Mar 2006 00:23:51 -0500 Subject: [Tutor] scaling values In-Reply-To: <mailman.10764.1142391121.27774.tutor@python.org> References: <mailman.10764.1142391121.27774.tutor@python.org> Message-ID: <9124ddd6ed8ded8a005fde6589cf1ebb@mac.com> Thanks to Kent Johnson, & David Heiser and everyone else. Looks like i was most of the way there...hehe... David Heiser gets special bonus points for actually understanding my initial mysterious query. From cspears2002 at yahoo.com Wed Mar 15 06:21:07 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 14 Mar 2006 21:21:07 -0800 (PST) Subject: [Tutor] OSError Message-ID: <20060315052107.67829.qmail@web51613.mail.yahoo.com> I am trying to write a function that takes a directory name and describes the contents of the directory (file name and size) recursively. Here is what I have written so far: import os, os.path def describeDirectory(directory): if os.listdir(directory) == []: print "Empty directory!" else: for files in os.listdir(directory): if os.path.isdir(files): print files, ' is a directory!' else: print files, 'SIZE: ', os.path.getsize(files) print 'Current Directory: \n' describeDirectory('.') print '\n' print './testFiles: \n' describeDirectory('./testFiles') Here is the result: Current Directory: changePeppers.py SIZE: 915 describeDirectory.py SIZE: 481 describeDirectory.pyc SIZE: 514 error_log SIZE: 0 makezeros.py SIZE: 147 makezeros.pyc SIZE: 481 output SIZE: 387 pepper.txt SIZE: 601 testFiles is a directory! textWrapper.py SIZE: 619 textWrapper.pyc SIZE: 1092 timings.py SIZE: 567 timings.pyc SIZE: 733 ./testFiles: renameFiles.py SIZE: Traceback (most recent call last): File "describeDirectory.py", line 17, in ? describeDirectory('./testFiles') File "describeDirectory.py", line 11, in describeDirectory print files, 'SIZE: ', os.path.getsize(files) File "/usr/lib/python2.4/posixpath.py", line 139, in getsize return os.stat(filename).st_size OSError: [Errno 2] No such file or directory: 'renameFiles.py' I don't understand the OSError. The file 'renameFiles.py' is in './testFiles' directory. Can someone clarify this for me? -Chris "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 sanelson at gmail.com Wed Mar 15 07:38:57 2006 From: sanelson at gmail.com (Steve Nelson) Date: Wed, 15 Mar 2006 06:38:57 +0000 Subject: [Tutor] Splitting a string into n-sized bytes In-Reply-To: <be4fbf920603141541k4d9cb12ag@mail.gmail.com> References: <b6131fdc0603141511l5c43eca7p37de8de165fbe269@mail.gmail.com> <be4fbf920603141541k4d9cb12ag@mail.gmail.com> Message-ID: <b6131fdc0603142238g23be2e32ybd6439c3bf126387@mail.gmail.com> On 3/14/06, Adam <adam.jtm30 at gmail.com> wrote: > Hopefully that should point you in the right direction to do n-sized > words as well. Indeed - as I now have a function: def nsplit(s, n): return [s[i:i+n] for i in range(0, len(s), n)] Incidentally I am currently going with: def nsplit(s, n): while s: yield s[:n] s = s[n:] As my friend just showed me how generators work, and also that the beginning and end of lists are implicit. Very cool. Thanks for all your help! S. From ewald.ertl at hartter.com Wed Mar 15 09:03:26 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed, 15 Mar 2006 09:03:26 +0100 Subject: [Tutor] OSError In-Reply-To: <20060315052107.67829.qmail@web51613.mail.yahoo.com> References: <20060315052107.67829.qmail@web51613.mail.yahoo.com> Message-ID: <4417CA4E.2010007@hartter.com> Hi Chris, I think I've found the problem. os.listdir() gives you all entries of the directory, but your not changing to that directory. The os.path.getsize() just does not find the file in the directory "testFiles" under your current directory. See my short example below. >>> import os >>> os.listdir( "trace" ) ['nbewer', 'installer_acb_2004-10-15.zip', 'epAnalyze.py', 'nbgene', 'ep20051201.txt', 'IPseconLinux.sxw', 'bbaseline', 'inner-classes.patch', 'jde-usages-0.9.1.zip', 'bleuch.ttf', 'privdebug'] >>> os.getcwd() '/users/trinomic/ewer' >>> import os.path >>> os.path.isfile ( "epAnalyze.py" ) False >>> os.path.isfile ( "trace/epAnalyze.py" ) True HTH Ewald Christopher Spears wrote: > I am trying to write a function that takes a directory > name and describes the contents of the directory (file > name and size) recursively. Here is what I have > written so far: > > import os, os.path > > def describeDirectory(directory): > if os.listdir(directory) == []: > print "Empty directory!" > else: > for files in os.listdir(directory): > if os.path.isdir(files): > print files, ' is a directory!' > else: > print files, 'SIZE: ', > os.path.getsize(files) > > print 'Current Directory: \n' > describeDirectory('.') > print '\n' > print './testFiles: \n' > describeDirectory('./testFiles') > > Here is the result: > > Current Directory: > > changePeppers.py SIZE: 915 > describeDirectory.py SIZE: 481 > describeDirectory.pyc SIZE: 514 > error_log SIZE: 0 > makezeros.py SIZE: 147 > makezeros.pyc SIZE: 481 > output SIZE: 387 > pepper.txt SIZE: 601 > testFiles is a directory! > textWrapper.py SIZE: 619 > textWrapper.pyc SIZE: 1092 > timings.py SIZE: 567 > timings.pyc SIZE: 733 > > > ./testFiles: > > renameFiles.py SIZE: > Traceback (most recent call last): > File "describeDirectory.py", line 17, in ? > describeDirectory('./testFiles') > File "describeDirectory.py", line 11, in > describeDirectory > print files, 'SIZE: ', os.path.getsize(files) > File "/usr/lib/python2.4/posixpath.py", line 139, in > getsize > return os.stat(filename).st_size > OSError: [Errno 2] No such file or directory: > 'renameFiles.py' > > I don't understand the OSError. The file > 'renameFiles.py' is in './testFiles' directory. Can > someone clarify this for me? > > -Chris > > "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 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Wed Mar 15 11:52:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Mar 2006 05:52:22 -0500 Subject: [Tutor] Splitting a string into n-sized bytes In-Reply-To: <b6131fdc0603142238g23be2e32ybd6439c3bf126387@mail.gmail.com> References: <b6131fdc0603141511l5c43eca7p37de8de165fbe269@mail.gmail.com> <be4fbf920603141541k4d9cb12ag@mail.gmail.com> <b6131fdc0603142238g23be2e32ybd6439c3bf126387@mail.gmail.com> Message-ID: <4417F1E6.4030801@tds.net> Steve Nelson wrote: > Indeed - as I now have a function: > > def nsplit(s, n): > return [s[i:i+n] for i in range(0, len(s), n)] > > Incidentally I am currently going with: > > def nsplit(s, n): > while s: > yield s[:n] > s = s[n:] You can write the generator function to use the same method as the list comp and avoid creating all the intermediate (partial) lists: def nsplit(s, n): for i in range(0, len(s), n): yield s[i:i+n] One of the cool things about generators is that they make it so easy to maintain state between yields. In Python 2.4, all you have to do is rewrite your original list comp to a generator comprehension: def nsplit(s, n): return (s[i:i+n] for i in range(0, len(s), n)) Kent From kent37 at tds.net Wed Mar 15 11:55:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Mar 2006 05:55:29 -0500 Subject: [Tutor] Help me please In-Reply-To: <20060315044339.AE55586B14@ws7-1.us4.outblaze.com> References: <20060315044339.AE55586B14@ws7-1.us4.outblaze.com> Message-ID: <4417F2A1.1090906@tds.net> yogeshwarran Nadeson wrote: > Hello, > > I am a newbie in python programming without previous programming > experience.Here i would like to ask > a question based on the exercises given by Josh Cogliatti in his > tutorial.I'll paste the question.Hope you can help me to solve it.I'd > like to end it by saying thanks for all yourr help. Have you written a program that uses loops? Could you write a program that uses a loop to print "Hello" three times? Kent > > *:Modify the password guessing program to keep track of how many times > the user has entered the password wrong. If it is more than 3 times, > print ``That must have been complicated.'' * > > This is the previous password program: > > Password.py > > # Waits until a password has been entered. Use control-C to break out with out > # the password > > #Note that this must not be the password so that the > # while loop runs at least once. > password = "foobar" > > #note that != means not equal > while password != "unicorn": > password = raw_input("Password:") > print "Welcome in" From kent37 at tds.net Wed Mar 15 12:00:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Mar 2006 06:00:49 -0500 Subject: [Tutor] OSError In-Reply-To: <20060315052107.67829.qmail@web51613.mail.yahoo.com> References: <20060315052107.67829.qmail@web51613.mail.yahoo.com> Message-ID: <4417F3E1.50404@tds.net> Christopher Spears wrote: > I am trying to write a function that takes a directory > name and describes the contents of the directory (file > name and size) recursively. Here is what I have > written so far: > > import os, os.path > > def describeDirectory(directory): > if os.listdir(directory) == []: > print "Empty directory!" > else: > for files in os.listdir(directory): > if os.path.isdir(files): > print files, ' is a directory!' > else: > print files, 'SIZE: ', > os.path.getsize(files) > > print 'Current Directory: \n' > describeDirectory('.') > print '\n' > print './testFiles: \n' > describeDirectory('./testFiles') Chris, os.path.getsize() needs the full path or relative path to the file, but os.listdir() just returns the bare file name, so there is a slight mismatch here. describeDirectory() works for the current dir because the bare file name is the correct relative path. You should use os.path.join(directory, files) to create the full path to pass to os.path.getsize(). BTW 'files' is not such a great name because it is just one file, not multiple. But don't change it to 'file', that is the name of a built-in function! Maybe 'f' or 'name' or 'filename'. Kent From cvijaybalaji at gmail.com Wed Mar 15 14:00:21 2006 From: cvijaybalaji at gmail.com (K.Vijaya Balaji Chellamani) Date: Wed, 15 Mar 2006 18:30:21 +0530 Subject: [Tutor] "Unexcepted Python Error : Exceptions.IOError: [Errorno 9] Bad File descriptor" Message-ID: <a37988700603150500i37f35eccr@mail.gmail.com> Respected Sir , I am new and introducing myself as Vijaya Balaji Chellmani . When i was using the python for my office application ( uses VC++ ) unfortunately i was awarded with unexcepted python error .The error is "Unexcepted Python Error : Exceptions.IOError: [Errorno 9] Bad File descriptor" Situation for the occurance: i worte a script for querying certain objects .This script was invoked from vc++ through command prompt .Since the execution was slow , we switched over a modification in the script .The modification was all the process of querying were taken under single class .and then we assigned a class id , other infomation for making this class as component.After all modification the script was runned to make a register process in the registry. Then the script was invoked from our application through "OLE" instance.The querying showed a faster response . but the thing is i was stucked sometimes with error message cited above .But after ignoring the message and when i continue again with some query process ( purpose of querying :finding a device name in pickle database ) i stucked up with the error again . Is there is any remedy for this . how can i eliminate this . I will very useful for me if you clarify this doubt . I will be thankful to you. by Vijaya Balaji Chellamani. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060315/de350b6c/attachment.htm From singletoned at gmail.com Wed Mar 15 14:22:00 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 15 Mar 2006 13:22:00 +0000 Subject: [Tutor] Passing Dictionaries to Functions Message-ID: <34bb7f5b0603150522hb2266bbj@mail.gmail.com> If I have a dictionary: mydict{'var1':"a", 'var2':"b"} and I want to pass it to a function as: myfunc(var1="a", var2="b") How would I do it? Thanks Ed From kent37 at tds.net Wed Mar 15 14:53:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Mar 2006 08:53:00 -0500 Subject: [Tutor] "Unexcepted Python Error : Exceptions.IOError: [Errorno 9] Bad File descriptor" In-Reply-To: <a37988700603150500i37f35eccr@mail.gmail.com> References: <a37988700603150500i37f35eccr@mail.gmail.com> Message-ID: <44181C3C.6030800@tds.net> K.Vijaya Balaji Chellamani wrote: > Respected Sir , > I am new and introducing myself as Vijaya Balaji > Chellmani . When i was using the python for my office application ( uses > VC++ ) unfortunately i was awarded with unexcepted python error .The > error is > "Unexcepted Python Error : Exceptions.IOError: [Errorno 9] Bad File > descriptor" You don't give us much to work with. Is there a stack trace associated with the error message? Can you show us the actual code that causes the error? Googling for the error message gives a hint that it may be caused by trying to write to stdout when the process does not have stdout defined. HTH Kent > > Situation for the occurance: > i worte a script for querying certain objects .This script was invoked > from vc++ through command prompt .Since the execution was slow , we > switched over a modification in the script .The modification was all > the process of querying were taken under single class .and then we > assigned a class id , other infomation for making this class as > component.After all modification the script was runned to make a > register process in the registry. Then the script was invoked from our > application through "OLE" instance.The querying showed a faster response > . but the thing is i was stucked sometimes with error message cited > above .But after ignoring the message and when i continue again with > some query process ( purpose of querying :finding a device name in > pickle database ) i stucked up with the error again . > > Is there is any remedy for this . how can i eliminate this . I will very > useful for me if you clarify this doubt . I will be thankful to you. > > > by > Vijaya Balaji Chellamani. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Wed Mar 15 14:56:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Mar 2006 08:56:41 -0500 Subject: [Tutor] Passing Dictionaries to Functions In-Reply-To: <34bb7f5b0603150522hb2266bbj@mail.gmail.com> References: <34bb7f5b0603150522hb2266bbj@mail.gmail.com> Message-ID: <44181D19.6060400@tds.net> Ed Singleton wrote: > If I have a dictionary: > > mydict{'var1':"a", 'var2':"b"} Presumably you mean mydict = {'var1':"a", 'var2':"b"} > > and I want to pass it to a function as: > > myfunc(var1="a", var2="b") > > How would I do it? myfunc(**mydict) Kent From singletoned at gmail.com Wed Mar 15 15:11:59 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 15 Mar 2006 14:11:59 +0000 Subject: [Tutor] Passing Dictionaries to Functions In-Reply-To: <44181D19.6060400@tds.net> References: <34bb7f5b0603150522hb2266bbj@mail.gmail.com> <44181D19.6060400@tds.net> Message-ID: <34bb7f5b0603150611o67826b55k@mail.gmail.com> Thanks again. This does bring up an issue I occaiosionally have with the documentation. Presumambly myfunc(**mydict) is a fairly trivial thing, but it is very hard to find when you don't know what you're looking for. Not sure what the solution is, but the inability to search for things when you don't know what they're called is a bit of a stumbling block sometimes. Maybe a page that very briefly summarises the 'unsearchable' with links to fuller descriptions? Ed On 15/03/06, Kent Johnson <kent37 at tds.net> wrote: > Ed Singleton wrote: > > If I have a dictionary: > > > > mydict{'var1':"a", 'var2':"b"} > > Presumably you mean > mydict = {'var1':"a", 'var2':"b"} > > > > and I want to pass it to a function as: > > > > myfunc(var1="a", var2="b") > > > > How would I do it? > > myfunc(**mydict) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From singletoned at gmail.com Wed Mar 15 15:49:11 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 15 Mar 2006 14:49:11 +0000 Subject: [Tutor] Converting String to Datetime Message-ID: <34bb7f5b0603150649m6117b56fu@mail.gmail.com> I seem to have a lot of questions today. Sorry. How can I convert a string in the format "%Y-%m-%d %H:%M:%S" into a datetime object? I can work out how to convert it to a time object by: import time timestring = "2005-09-01 12:30:09" time_format = "%Y-%m-%d %H:%M:%S" mytime = time.strptime(timestring,time_format) I can't seem to work out how to convert the time object into a datetime object... Any help appreciated. Thanks Ed From singletoned at gmail.com Wed Mar 15 15:55:48 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 15 Mar 2006 14:55:48 +0000 Subject: [Tutor] Converting String to Datetime In-Reply-To: <34bb7f5b0603150649m6117b56fu@mail.gmail.com> References: <34bb7f5b0603150649m6117b56fu@mail.gmail.com> Message-ID: <34bb7f5b0603150655q2d3c02f6v@mail.gmail.com> Nevermind. i seem to have found the answer in that wonderful PLEAC site (I always forget about that. It appears that the following works: import time, datetime timestring = "2005-09-01 12:30:09" time_format = "%Y-%m-%d %H:%M:%S" datetime.datetime.fromtimestamp(time.mktime(time.strptime(mytime, time_format))) Ed On 15/03/06, Ed Singleton <singletoned at gmail.com> wrote: > I seem to have a lot of questions today. Sorry. > > How can I convert a string in the format "%Y-%m-%d %H:%M:%S" into a > datetime object? > > I can work out how to convert it to a time object by: > > import time > timestring = "2005-09-01 12:30:09" > time_format = "%Y-%m-%d %H:%M:%S" > mytime = time.strptime(timestring,time_format) > > I can't seem to work out how to convert the time object into a > datetime object... > > Any help appreciated. > > Thanks > > Ed > From kent37 at tds.net Wed Mar 15 16:05:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Mar 2006 10:05:58 -0500 Subject: [Tutor] Passing Dictionaries to Functions In-Reply-To: <34bb7f5b0603150611o67826b55k@mail.gmail.com> References: <34bb7f5b0603150522hb2266bbj@mail.gmail.com> <44181D19.6060400@tds.net> <34bb7f5b0603150611o67826b55k@mail.gmail.com> Message-ID: <44182D56.2050407@tds.net> Ed Singleton wrote: > Thanks again. > > This does bring up an issue I occaiosionally have with the documentation. > > Presumambly myfunc(**mydict) is a fairly trivial thing, but it is very > hard to find when you don't know what you're looking for. Not sure > what the solution is, but the inability to search for things when you > don't know what they're called is a bit of a stumbling block > sometimes. Yes. This syntax is actually hard to find in the docs when you *do* know what you are looking for. The best coverage I could find is in the Language Reference which isn't exactly light reading: http://docs.python.org/ref/calls.html It's also mentioned in the docs for apply(), which is an older way to do the same thing: http://www.python.org/doc/2.4.2/lib/non-essential-built-in-funcs.html > > Maybe a page that very briefly summarises the 'unsearchable' with > links to fuller descriptions? Hmm. Sounds a little tricky to put together... Kent From kent37 at tds.net Wed Mar 15 16:23:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Mar 2006 10:23:08 -0500 Subject: [Tutor] Converting String to Datetime In-Reply-To: <34bb7f5b0603150649m6117b56fu@mail.gmail.com> References: <34bb7f5b0603150649m6117b56fu@mail.gmail.com> Message-ID: <4418315C.4080906@tds.net> Ed Singleton wrote: > I seem to have a lot of questions today. Sorry. > > How can I convert a string in the format "%Y-%m-%d %H:%M:%S" into a > datetime object? > > I can work out how to convert it to a time object by: > > import time > timestring = "2005-09-01 12:30:09" > time_format = "%Y-%m-%d %H:%M:%S" > mytime = time.strptime(timestring,time_format) > > I can't seem to work out how to convert the time object into a > datetime object... Try datetime.datetime(*mytime[:6]) Gee, two questions in one day where the answer is, "Use extended function call syntax" ;) Kent From francescoqueirolo at yahoo.com Wed Mar 15 18:04:34 2006 From: francescoqueirolo at yahoo.com (Francesco Queirolo) Date: Wed, 15 Mar 2006 09:04:34 -0800 (PST) Subject: [Tutor] xemacs and python mode difficulty Message-ID: <20060315170434.45747.qmail@web60723.mail.yahoo.com> Howdy, Relevant Data ----------------------------------------------------------------- Windows XP SP 2 or greater Python 2.4.2 Final Xemacs 21.4.19 ------------------------------------------------------------------ Problem: I really like xemacs as my editor of everything. However when I downloaded the installer for 21.4.19 to update my xemacs installation, python mode was gone. Searching for how to customize xemacs led me to a great deal of confusion. I would like to know the difference between ~/.emacs and .xemacs\custom.el and also how to install the python module, so that I can get syntax highlighting, the tab trick, C-c C-c, and the rest of the old python mode functionality. Thank you, Francesco Francesco Queirolo (+1)505.661.2670 francescoqueirolo at yahoo.com --------------------------------- Yahoo! Travel Find great deals to the top 10 hottest destinations! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060315/5f010628/attachment-0001.htm From noviceprogrammer at gmail.com Wed Mar 15 18:23:54 2006 From: noviceprogrammer at gmail.com (Brad Hills) Date: Wed, 15 Mar 2006 12:23:54 -0500 Subject: [Tutor] Help with Game over program Message-ID: <962ebbdd0603150923g230f94d6pde1805dcbb55c838@mail.gmail.com> I'm 45 minutes into learning how to program using python. I am reading "Python programming for the absolute begginer" by Michael Dawson, and the first thing I've done was write the "Game Over" program. Which I understand is also called the "Hello World" Program. My main problem at this point is when I try to run the program from the icon on my desktop it asks me which program to associate it with. The book makes it sound like it will automatically execute the program. Am I doing something wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060315/2b99062b/attachment.html From adam.jtm30 at gmail.com Wed Mar 15 18:36:24 2006 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 15 Mar 2006 17:36:24 +0000 Subject: [Tutor] Tix: binding In-Reply-To: <382176391@web.de> References: <382176391@web.de> Message-ID: <be4fbf920603150936t2627a118o@mail.gmail.com> On 15/03/06, hk at pop.ms <hk at pop.ms> wrote: > I am looking at Tix and I am stuck with what seems to be a simple problem: > > I want to bind the cancel buttom of a ExFileSelectBox to a routine in my class, but can not make it work. > I guess the problem is the same for any binding of tix sub-widgets, so if someone could send some sample code. > >>> import Tix > >>> root = Tix.Tk() > >>> box = Tix.ExFileSelectBox(root) > >>> print box.subwidget(name='cancel') > .11827520.bf.cancel #so the sub-widget cancel buttom is there > > But how to bind it ? > > >>> box.cancel(command = lambda a,b : a+b ) > Traceback (most recent call last): > File "<pyshell#12>", line 1, in ? > box.cancel(command = lambda a,b : a+b ) > AttributeError: _dummyButton instance has no __call__ method > > Or > > >>> box.subwidget(name='cancel' , command = lambda a,b : a+b ) > Traceback (most recent call last): > File "<pyshell#13>", line 1, in ? > box.subwidget(name='cancel' , command = lambda a,b : a+b ) > TypeError: subwidget() got an unexpected keyword argument 'command' > > So, it seems I can not bind to command, but what then ? > >From the Tix docu I thought the buttoms are normal Tkinter widgets ? > -- > Harm Here's what I got from a little experimentation and print box.cancel.bind.__doc__. >>> def bar(action): ... print action >>> import Tix >>> root = Tix.Tk() >>> box = Tix.ExFileSelectBox(root) >>> box.pack() >>> box.cancel.bind("<ButtonPress-1>", bar) '-1212073588bar' >>> <Tkinter.Event instance at 0xb779c0ec> <Tkinter.Event instance at 0xb779c0ec> <Tkinter.Event instance at 0xb779c0ec> If you have a look at box.cancel.bind.__doc__ you can find everything you can put into the SEQUENCE string "<ButtonPress-1>" is left mouse click. From annaraven at gmail.com Wed Mar 15 18:39:19 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Wed, 15 Mar 2006 09:39:19 -0800 Subject: [Tutor] Help with Game over program In-Reply-To: <962ebbdd0603150923g230f94d6pde1805dcbb55c838@mail.gmail.com> References: <962ebbdd0603150923g230f94d6pde1805dcbb55c838@mail.gmail.com> Message-ID: <cb361a610603150939g2972c2e1y31c89cafc05eb999@mail.gmail.com> On 3/15/06, Brad Hills <noviceprogrammer at gmail.com> wrote: > > I'm 45 minutes into learning how to program using python. I am reading > "Python programming for the absolute begginer" by Michael Dawson, and the > first thing I've done was write the "Game Over" program. Which I understand > is also called the "Hello World" Program. My main problem at this point is > when I try to run the program from the icon on my desktop it asks me which > program to associate it with. The book makes it sound like it will > automatically execute the program. Am I doing something wrong? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > What operating system are you using? Windowz? Mac? Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060315/fed025dc/attachment.htm From john at fouhy.net Wed Mar 15 23:24:56 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 16 Mar 2006 11:24:56 +1300 Subject: [Tutor] Tix: binding In-Reply-To: <be4fbf920603150936t2627a118o@mail.gmail.com> References: <382176391@web.de> <be4fbf920603150936t2627a118o@mail.gmail.com> Message-ID: <5e58f2e40603151424i75eb698s@mail.gmail.com> On 16/03/06, Adam <adam.jtm30 at gmail.com> wrote: > On 15/03/06, hk at pop.ms <hk at pop.ms> wrote: > > I want to bind the cancel buttom of a ExFileSelectBox to a routine in my class, > Here's what I got from a little experimentation and print > box.cancel.bind.__doc__. > > >>> def bar(action): > ... print action > >>> import Tix > >>> root = Tix.Tk() > >>> box = Tix.ExFileSelectBox(root) > >>> box.pack() > >>> box.cancel.bind("<ButtonPress-1>", bar) > '-1212073588bar' > >>> <Tkinter.Event instance at 0xb779c0ec> > <Tkinter.Event instance at 0xb779c0ec> > <Tkinter.Event instance at 0xb779c0ec> This will bind to leftmouse-down, which is different from clicking a button. If you want to simulate a real button click with event bindings, you will need to set a flag on ButtonPress-1, then in ButtonRelease-1 check for the flag, check to see if the mouse is within the button, and then activate your callback. Something else you could try (which I haven't tested) --- instead of box.cancel.bind, do box.cancel.config(command= ...). -- John. From alan.gauld at freenet.co.uk Thu Mar 16 00:13:25 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 15 Mar 2006 23:13:25 -0000 Subject: [Tutor] Dynamically naming functions References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <001c01c6443a$39b716d0$0b01a8c0@xp> <34bb7f5b0603130324u24eb683dv@mail.gmail.com> <019001c646c4$e53a5ee0$0b01a8c0@xp> <34bb7f5b0603140150t32a584fel@mail.gmail.com> Message-ID: <000901c64886$10373970$0b01a8c0@xp> > > Very rarely, its easy to do backups of huge amounts of data if you > > know where to find it, its hard to trawl all over a changing structure > > looking for the things that need backing up. Particularly if, when you > > try to restore it, it needs to go in a different place to where you > > found > > it! > > Backing up is generally one of the lesser of my worries. Backing up is usually a no brainer, especially in a static structure, but even in a dynamic one you can just do a find on the file types. It's restoring a dynamic structure thats really hard, and usually a manual process... > Maintaining content is primary. Oddly enough I usually expect content maintenance to be a 'business as usual' kind of thing. The content goes in one place per author and the code picks it up as needed. > Unless you are dynamically generating static pages, > they are a nightmare to maintain. If the content is dynamic in any way I always generate them dynamically - and that includes anything with company logo etc on it. About the only pure html pages I use are the Error reports - 404s etc... > be quite repetitive. A large amount of the code on any page is the > same as on any other page (page structure, boilerplate, etc). But most of that is template code just picking up content from a folder someplace (logo images, standard menus etc) and CSS style settings. > I think it's a generally accepted principle that computers are better > at handling thousands of files like that better than humans are. The Absolutely. > > Yes but a CMS normally uses a static structure with dynamic content. > I think we might be using different meanings of structure. I'm > referring to the site structure, as in which page is a parent of which > other page. The site structure is just another aspect of the content. Ah, OK. I'm referring to the physical site structure, the folder heirarchy. > A reference to the parent/child pages is just another attribute like > content and title. Agreed, I'd expect those to be managed in the code and templates. > A (good) CMS would create a dynamic structure for the user to browse, > with folders and pages easily creatable and movable, I'm not sure I agree with that. It should allow movement of pages across folders with auto update iof relative paths etc, but not necessarily dynamic (ie at run time) changes. > and references to pages would be dynamic so that if yo0u move a > page internal links to it still work. I don;t necessarily see that as needing to be a dynamic feature, I'd probably prefer to do those kinds of changes under controlled circumstances and do the updates as a batch update process. >> Dynamic content is 'A Good Thing', dynamic structure is usually bad. > > But structure is just an aspect of content. If you mean navigation structure I agree, but physical structure - where the files live is absolutely not. And to make it so creates a huge headache for the site administrators - who usually cost a good deal more than the developers or content providers! Alan G. From Gideon.STREET at ergon.com.au Thu Mar 16 06:33:14 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Thu, 16 Mar 2006 15:33:14 +1000 Subject: [Tutor] Matching against various login prompts Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC0A2573@ebnewem01.ergon> Hi again, I'm trying to improve on couple of python scripts that I wrote and trying to get a successful/failed login re-usable module sorted out. Is there any way to match a returned string against a predetermined list of strings using the telnetlib module? I'm wanting to use a while loop rather than an 'if ' so that I can get some error checking on the username/password (ie typo in username). uPrompt = ['Username: '] pPrompt = ['Password: '] gPrompt = ['>'] sPrompt = ['login:'] prompt = tn.read_until('', 1) while prompt == gPrompt: do stuff for device here While prompt == uPrompt: do stuff for different device here While prompt == sPrompt: do stuff for different OS here I've tried various combinations of tn.read_until's and tn.expect's but I don't seem to be able to capture the last line returned and match against conditions with it. I've read the telnetlib doco but can't figure out which one of the many options is what I'm after (probably if I define all the above as functions or something I could work it out but haven't got that part straight in my head yet). 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 aguffabuff at hotmail.com Thu Mar 16 06:44:46 2006 From: aguffabuff at hotmail.com (Ars) Date: Wed, 15 Mar 2006 21:44:46 -0800 Subject: [Tutor] Simulate Input from mouse and keyboard? Message-ID: <BAY106-DAV18096BDE98F4EB868A0506CAE70@phx.gbl> Is there a way to control the mouse cursor's position so I can tell it to move to X,Y position on the screen and click or double click automatically? Also, how can you simulate input from the keyboard? I'd like to be able have a program that can call up a webpage, click on a text box and type into it as though a person was actually doing it. I know this is kinda an obtuse way of getting things done, but I think it'd be neat to be able to do it that way. So to recap (this is for windows btw): 1. How do you control the cursor relative to the entire screen, not just locked inside the program's own window. 2. How do you simulate mouse clicks/doubleclicks. 3. How do you emulate keyboard input as though a real person is typing. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060315/344d5942/attachment.htm From aguffabuff at hotmail.com Thu Mar 16 06:55:58 2006 From: aguffabuff at hotmail.com (Ars) Date: Wed, 15 Mar 2006 21:55:58 -0800 Subject: [Tutor] Help with Game over program Message-ID: <BAY106-DAV120411186ABAE83CE69736CAE70@phx.gbl> Python should have made the file associations when it was installed, but you can just manually associate *.py files with C:\Python24\python.exe and then your program should run inside of a little DOS window. -Jack On 3/15/06, Brad Hills <noviceprogrammer at gmail.com> wrote: I'm 45 minutes into learning how to program using python. I am reading "Python programming for the absolute begginer" by Michael Dawson, and the first thing I've done was write the "Game Over" program. Which I understand is also called the "Hello World" Program. My main problem at this point is when I try to run the program from the icon on my desktop it asks me which program to associate it with. The book makes it sound like it will automatically execute the program. Am I doing something wrong? _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor What operating system are you using? Windowz? Mac? Anna -------------------------------------------------------------------------------- _______________________________________________ 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/20060315/5bbb1560/attachment-0001.html From john at fouhy.net Thu Mar 16 07:29:41 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 16 Mar 2006 19:29:41 +1300 Subject: [Tutor] Simulate Input from mouse and keyboard? In-Reply-To: <BAY106-DAV18096BDE98F4EB868A0506CAE70@phx.gbl> References: <BAY106-DAV18096BDE98F4EB868A0506CAE70@phx.gbl> Message-ID: <5e58f2e40603152229t61e10669s@mail.gmail.com> On 16/03/06, Ars <aguffabuff at hotmail.com> wrote: > I'd like to be able have a program that can call up a webpage, click on a > text box and type into it as though a person was actually doing it. I don't know the general solution, but you might be able to solve this particular problem with PAMIE: http://pamie.sourceforge.net/ """ P.A.M.I.E. - stands for Python Automated Module For I.E. Pamie's main use is for testing web sites by which you automate the Internet Explorer client using the Pamie scripting language. PAMIE is not a record playback engine! Pamie allows you to automate I.E. by manipulating I.E.'s Document Object Model via COM. This Free tool is for use by Quality Assurance Engineers and Developers. """ -- John. From alan.gauld at freenet.co.uk Thu Mar 16 09:32:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 16 Mar 2006 08:32:09 -0000 Subject: [Tutor] Simulate Input from mouse and keyboard? References: <BAY106-DAV18096BDE98F4EB868A0506CAE70@phx.gbl> Message-ID: <009201c648d4$1dd73eb0$0b01a8c0@xp> > Is there a way to control the mouse cursor's position so > I can tell it to move to X,Y position on the screen and > click or double click automatically? >Also, how can you simulate input from the keyboard? You can use the Windows API calls to do this, but its not easy and is extremely unreliable since even a small change of your screen layout will mess things up. Check out the documentation for the PostMessage API call on MSDN. > I'd like to be able have a program that can call up a webpage, > click on a text box and type into it as though a person was > actually doing it. But this is usually easier done in other ways by using a robotic browser instead opf trying to control the scren itself. > I know this is kinda an obtuse way of getting things > done, but I think it'd be neat to be able to do it that way. Interesting definition of neat. I presume you went to the same school as Heath-Robinson and others of that ilk?! :-) Personally I call it the path of last resort, if not desparation! > 1. How do you control the cursor relative to the entire screen, > not just locked inside the program's own window. This requires PostMessage events using MouseMove events to position the mouse cursor. But of course if anything moves your real mouse - even by one pixel - it will screw things up. > 2. How do you simulate mouse clicks/doubleclicks. > 3. How do you emulate keyboard input as though a real person is typing. These are both via PostMessage using button click and keypress events. However I'd take a look at the urllib and browser modules plus the COM interface to InternetExplorer. All of these offer better solutions albeit using different tricks to get there. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Mar 16 11:54:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Mar 2006 05:54:00 -0500 Subject: [Tutor] Simulate Input from mouse and keyboard? In-Reply-To: <BAY106-DAV18096BDE98F4EB868A0506CAE70@phx.gbl> References: <BAY106-DAV18096BDE98F4EB868A0506CAE70@phx.gbl> Message-ID: <441943C8.3020908@tds.net> Ars wrote: > Is there a way to control the mouse cursor's position so I can tell it > to move to X,Y position on the screen and click or double click > automatically? > > Also, how can you simulate input from the keyboard? > > I'd like to be able have a program that can call up a webpage, click on > a text box and type into it as though a person was actually doing it. > > I know this is kinda an obtuse way of getting things done, but I think > it'd be neat to be able to do it that way. I agree with John and Alan that there are probably better solutions. The mechanize and ClientForms packages are designed for fetching and filling out web forms from Python. http://wwwsearch.sourceforge.net/mechanize/ Kent From LMartin at navigantconsulting.com Thu Mar 16 17:00:38 2006 From: LMartin at navigantconsulting.com (Louis J Martin) Date: Thu, 16 Mar 2006 10:00:38 -0600 Subject: [Tutor] Louis J Martin is out of the office. Message-ID: <OFC847D5FE.54EA228D-ON86257133.0057F30C-86257133.0057F30C@insidenci.com> I will be out of the office starting 03/16/2006 and will not return until 03/20/2006. I will respond to your message when I return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060316/665eb9a0/attachment.html From alan.gauld at freenet.co.uk Fri Mar 17 00:30:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 16 Mar 2006 23:30:33 -0000 Subject: [Tutor] Web tutor broken again Message-ID: <001a01c64951$9f23f3f0$0b01a8c0@xp> My website is dead once more. I've reported it to my ISP and hopefully service will be restored ASAP. Apologies to regular readers for the loss of service Apologies to non users for consuming bandwidth, but many of my "students" are also list members. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From clajo04 at mac.com Fri Mar 17 05:20:33 2006 From: clajo04 at mac.com (John Clark) Date: Thu, 16 Mar 2006 23:20:33 -0500 Subject: [Tutor] Help with re.sub() Message-ID: <441A3911.5080706@mac.com> Hi, I have a file that is a long list of records (roughly) in the format objid at objdata So, for example: id1 at data1 id1 at data2 id1 at data3 id1 at data4 id2 at data1 .... What I would like to do is run a regular expression against this and wind up with: id1 at data1@data2 at data3@data4 id2 at data1 So I ran the following regex against the string: re.compile(r'([^@]*)@(.*)\n\1@(.*)').sub(r'\1\2\3', string) and I wound up with: id1 at data1@data2 id1 at data3@data4 id2 at data1 So, my questions are: (1) Is there any way to get a single regular expression to handle overlapping matches so that I get what I want in one call? (2) Is there any way (without comparing the before and after strings) to know if a re.sub(...) call did anything? I suppose I could do something like: pattern = re.compile(r'([^@]*)@(.*)\n\1@(.*)') while(pattern.search(string)): string = pattern.sub(r'\1\2\3', string) but I would like to avoid the explicit loop if possible... Actually, should I be able to do something like that? If I execute it in my debugger, my string gets really funky... like the re is losing track of what the groups are... and I end up with a single really long string rather than what I expect.. Any help on this would be appreciated. -jdc From kent37 at tds.net Fri Mar 17 05:54:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Mar 2006 23:54:38 -0500 Subject: [Tutor] Help with re.sub() In-Reply-To: <441A3911.5080706@mac.com> References: <441A3911.5080706@mac.com> Message-ID: <441A410E.9020809@tds.net> John Clark wrote: > Hi, > > I have a file that is a long list of records (roughly) in the format > > objid at objdata > > So, for example: > > id1 at data1 > id1 at data2 > id1 at data3 > id1 at data4 > id2 at data1 > .... > > What I would like to do is run a regular expression against this and > wind up with: > > id1 at data1@data2 at data3@data4 > id2 at data1 Regular expressions aren't so good at dealing with repeating data like this. OTOH itertools.groupby() is perfect for this: # This represents your original data data = '''id1 at data1 id1 at data2 id1 at data3 id1 at data4 id2 at data1 id2 at data5'''.splitlines() # Convert to a list of pairs of (id, data) data = [ line.split('@') for line in data ] from itertools import groupby from operator import itemgetter # groupby() will group them according to whatever key we specify # itemgetter(0) will pull out just the first item # the result of groupby() is a list of (key, sequence of items) for id, items in groupby(data, itemgetter(0)): print '%s@%s' % (id, '@'.join(item[1] for item in items)) I have a longer explanation of groupby() and itemgetter() here: http://www.pycs.net/users/0000323/weblog/2005/12/06.html > So, my questions are: > (1) Is there any way to get a single regular expression to handle > overlapping matches so that I get what I want in one call? I doubt it though I'd be happy to be proven wrong ;) > (2) Is there any way (without comparing the before and after strings) to > know if a re.sub(...) call did anything? Use re.subn() instead, it returns the new string and a count. Kent From dyoo at hkn.eecs.berkeley.edu Fri Mar 17 06:03:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Mar 2006 21:03:41 -0800 (PST) Subject: [Tutor] Help with re.sub() In-Reply-To: <441A3911.5080706@mac.com> Message-ID: <Pine.LNX.4.44.0603162053200.22060-100000@hkn.eecs.berkeley.edu> > I have a file that is a long list of records (roughly) in the format > > objid at objdata > > So, for example: > > id1 at data1 > id1 at data2 > id1 at data3 > id1 at data4 > id2 at data1 > .... > > What I would like to do is run a regular expression against this and > wind up with: I'd recommend scratching out the requirement to use regular expressions. *grin* I'm actually not certain they're appropriate for this problem; it seems more like knowing about data structures like lists and dictionaries will be more crucial here. > Actually, should I be able to do something like that? If I execute it > in my debugger, my string gets really funky... like the re is losing > track of what the groups are... and I end up with a single really long > string rather than what I expect.. I do not see an obvious regular expression that does what you want. I'm not saying that no such regex exists (I'd have to think about it a bit), but that simpler approaches will probably work out better. Would you might if we simplify the problem a bit? Rather than working directly on files, what if you were working on tuples where the id and the data portion was already split up for you? That is, would life be simpler for you if you had a list like: [('id1', 'data1'), ('id1', 'data2'), ('id1', 'data3'), ('id1', 'data4'), ('id2', 'data1'), ...] and given input like this, you were to try to compute something like a dictionary from ids to a list of the data? { 'id1' : ['data1', 'data2', 'data3', 'data4'], 'id2' : ['data1'], ...} Would this be something you'd know how to do? Best of wishes to you! From hugonz-lists at h-lab.net Fri Mar 17 06:18:16 2006 From: hugonz-lists at h-lab.net (=?windows-1252?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 16 Mar 2006 23:18:16 -0600 Subject: [Tutor] Help with re.sub() In-Reply-To: <441A3911.5080706@mac.com> References: <441A3911.5080706@mac.com> Message-ID: <441A4698.8080209@h-lab.net> Hi John, I would just like to suggest a different approach. Like the old saying goes: Some people, when confronted with a problem, think ?I know, I?ll use regular expressions.? Now they have two problems. ? Jamie Zawinski, in comp.lang.emacs If the delimiter is always the same ('@') you can use split() to get the data. Then you can arrange the data in a dictionary of lists, like this. collapsed_data = {} for line in mydata: id_part, data_part = line[:-1].split('@') try: collapsed_data[id_part].append(data_part) except KeyError: #first time insert for that key collapsed_data[id_part] = [data_part] for id, data in collapsed_data.iteritems(): print '@'.join([id] + data) That should be it. Python's data types are very powerful. Of course you could just build a huge list comprehension that does it... Hope that helps, Hugo From dyoo at hkn.eecs.berkeley.edu Fri Mar 17 06:21:43 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Mar 2006 21:21:43 -0800 (PST) Subject: [Tutor] xemacs and python mode difficulty In-Reply-To: <20060315170434.45747.qmail@web60723.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0603162105000.22060-100000@hkn.eecs.berkeley.edu> > I would like to know the difference between ~/.emacs and > .xemacs\custom.el and also how to install the python module, so that I > can get syntax highlighting, the tab trick, C-c C-c, and the rest of the > old python mode functionality. HI Francesco, You may want to ask the xemacs folks about the first part of your question: that part of the question, about the difference between '.emacs' and 'custom.el', is something very emacs/xemacs-specific, and I don't think we at Python-tutor will be able to help you too effectively on that point: you are better off asking people who really know what they're talking about. *grin* You should be able to find some introductory information on the '.emacs' file here: http://www.xemacs.org/Documentation/21.5/html/xemacs_30.html#SEC390 I believe that .custom.el is a file associated with the Custom library that comes bundled with emacs: http://www.dina.kvl.dk/~abraham/custom/ I believe that you probably want to work on .emacs, not .custom.el. but again, I strongly recommend you get a real emacs guru to describe these files. About installing python-mode.el, do the instructions at: http://www.emacswiki.org/cgi-bin/wiki?PythonMode help? From samrobertsmith at gmail.com Fri Mar 17 08:11:42 2006 From: samrobertsmith at gmail.com (linda.s) Date: Thu, 16 Mar 2006 23:11:42 -0800 Subject: [Tutor] Python and R Message-ID: <1d987df30603162311ra856debjfa051c9ae7421c75@mail.gmail.com> Is there any good tutorial about using python to call R modules? Linda From ryang at gol.com Fri Mar 17 08:55:18 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Fri, 17 Mar 2006 16:55:18 +0900 Subject: [Tutor] Japanese and COM Message-ID: <006601c64998$240323c0$030ba8c0@RYAN> I'm (still) having trouble using Japanese in python. I want to use Japanese with the win32com module. But while I can retrieve Japanese text from a COM server without problems, if I try to send Japanese text to a COM server it comes out garbled. Here is an example: #-*- coding: utf-8 -*- import win32com.client o = win32com.client.Dispatch("Excel.Application") o.Visible = 1 o.Workbooks.Add() o.Cells(1,1).Value = "???" #------------ The Japanese text sent to Excel is garbled. Yet I can retrieve Japanese text from Excel or other COM servers, and it's fine. Is there something simple (I hope) that I'm doing wrong? Regards, Ryan --- Ryan Ginstrom ryang at gol.com http://ginstrom.com From fortezza-pyt at fortezzazone.org Fri Mar 17 08:36:35 2006 From: fortezza-pyt at fortezzazone.org (fortezza-pyt) Date: Fri, 17 Mar 2006 00:36:35 -0700 Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <441A3911.5080706@mac.com> References: <441A3911.5080706@mac.com> Message-ID: <441A6703.4080700@fortezzazone.org> If there a semi-standard way to test if a file system has been mounted or not using Python? In the Linux command line, I can type "mount" and see all mounted file system, and then see if the one I am looking for is in the list. While I could replicate this with Python, I am curious if there is an easier way. Thank You, Fortezza From noufal at nibrahim.net.in Fri Mar 17 10:00:10 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Fri, 17 Mar 2006 14:30:10 +0530 (IST) Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <441A6703.4080700@fortezzazone.org> References: <441A3911.5080706@mac.com> <441A6703.4080700@fortezzazone.org> Message-ID: <45160.203.145.176.76.1142586010.squirrel@members.hcoop.net> On Fri, March 17, 2006 1:06 pm, fortezza-pyt wrote: > If there a semi-standard way to test if a file system has been mounted > or not using Python? In the Linux command line, I can type "mount" and > see all mounted file system, and then see if the one I am looking for is > in the list. While I could replicate this with > Python, I am curious if there is an easier way. A quick Google search gives this http://bebop.bigasterisk.com/python/docs/MtPython Non standard perhaps but someone seems to have implemented a module that does something like this. -- -NI From kent37 at tds.net Fri Mar 17 11:42:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Mar 2006 05:42:59 -0500 Subject: [Tutor] Python and R In-Reply-To: <1d987df30603162311ra856debjfa051c9ae7421c75@mail.gmail.com> References: <1d987df30603162311ra856debjfa051c9ae7421c75@mail.gmail.com> Message-ID: <441A92B3.9020001@tds.net> linda.s wrote: > Is there any good tutorial about using python to call R modules? Are you using RPy? It's docs look pretty good. http://rpy.sourceforge.net/ Kent From kent37 at tds.net Fri Mar 17 11:50:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Mar 2006 05:50:51 -0500 Subject: [Tutor] Japanese and COM In-Reply-To: <006601c64998$240323c0$030ba8c0@RYAN> References: <006601c64998$240323c0$030ba8c0@RYAN> Message-ID: <441A948B.2080605@tds.net> Ryan Ginstrom wrote: > I'm (still) having trouble using Japanese in python. > > I want to use Japanese with the win32com module. But while I can retrieve > Japanese text from a COM server without problems, if I try to send Japanese > text to a COM server it comes out garbled. > > Here is an example: > > #-*- coding: utf-8 -*- > import win32com.client > > o = win32com.client.Dispatch("Excel.Application") > o.Visible = 1 > o.Workbooks.Add() > o.Cells(1,1).Value = "???" > > #------------ > > The Japanese text sent to Excel is garbled. Yet I can retrieve Japanese text > from Excel or other COM servers, and it's fine. Is there something simple (I > hope) that I'm doing wrong? When you retrieve Japanese text is it encoded in UTF-8 or is it Unicode or Shift-JIS? What if you try sending a Unicode string? o.Cells(1,1).Value = u"???" --------------------^^^ Kent From klappnase at freenet.de Fri Mar 17 13:12:00 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 17 Mar 2006 13:12:00 +0100 Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <441A6703.4080700@fortezzazone.org> References: <441A3911.5080706@mac.com> <441A6703.4080700@fortezzazone.org> Message-ID: <20060317131200.74b96651.klappnase@freenet.de> On Fri, 17 Mar 2006 00:36:35 -0700 fortezza-pyt <fortezza-pyt at fortezzazone.org> wrote: > If there a semi-standard way to test if a file system has been mounted > or not using Python? In the Linux command line, I can type "mount" and > see all mounted file system, and then see if the one I am looking for is > in the list. While I could replicate this with > Python, I am curious if there is an easier way. > Hi Fortezza, try os.path.ismount() . HTH Michael From kabads at gmail.com Fri Mar 17 15:15:32 2006 From: kabads at gmail.com (Adam Cripps) Date: Fri, 17 Mar 2006 14:15:32 +0000 Subject: [Tutor] Mysql BLOB strangeness? Message-ID: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> I'm trying to build a mini-CMS for my class to manage a single webpage, using CGI and mysql. The children will be storing their main content in a BLOB within a Mysql database. When I query the content column, I get a strange return like this: array('c', 'This is a test ') - when the only text I entered in was 'This is a test'. When I query mysql directly through a prompt, I get 'This is a test'. Does a CGI query get mangled text from a blob? My other VARCHAR columns are fine. Code: def query(statement): results = [] mycursor.execute(statement) myrowcount = int(mycursor.rowcount) for i in range (0, myrowcount): myrow = mycursor.fetchone() results.append(myrow) return results reportquery = "select id, title, content, published from report" reportlist = query(reportquery) print "<p>" + str(reportlist) + "</p>" id = primary key, integer, not null title = varchar(255) content = blob published = char(1), default ='n' I've tried using looking at reportlist[0][2][1], but that just returns 'T' - which is obviously the T in 'This'. TIA Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kent37 at tds.net Fri Mar 17 15:31:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Mar 2006 09:31:35 -0500 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> Message-ID: <441AC847.2040507@tds.net> Adam Cripps wrote: > I'm trying to build a mini-CMS for my class to manage a single > webpage, using CGI and mysql. The children will be storing their main > content in a BLOB within a Mysql database. > > When I query the content column, I get a strange return like this: > > array('c', 'This is a test ') > > - when the only text I entered in was 'This is a test'. MySQL is apparently returning an array.array object, not a string. Just call tostring() on it to get a printable string. Why are you using a BLOB when the content is text? Kent From kabads at gmail.com Fri Mar 17 15:39:27 2006 From: kabads at gmail.com (Adam Cripps) Date: Fri, 17 Mar 2006 14:39:27 +0000 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <441AC847.2040507@tds.net> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441AC847.2040507@tds.net> Message-ID: <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> On 3/17/06, Kent Johnson <kent37 at tds.net> wrote: > Adam Cripps wrote: > > I'm trying to build a mini-CMS for my class to manage a single > > webpage, using CGI and mysql. The children will be storing their main > > content in a BLOB within a Mysql database. > > > > When I query the content column, I get a strange return like this: > > > > array('c', 'This is a test ') > > > > - when the only text I entered in was 'This is a test'. > > MySQL is apparently returning an array.array object, not a string. Just > call tostring() on it to get a printable string. > > Why are you using a BLOB when the content is text? Thanks. I'm using BLOB because I want them to be able to write content that is longer than 255 chars. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kent37 at tds.net Fri Mar 17 15:46:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Mar 2006 09:46:30 -0500 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441AC847.2040507@tds.net> <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> Message-ID: <441ACBC6.1000806@tds.net> Adam Cripps wrote: > On 3/17/06, Kent Johnson <kent37 at tds.net> wrote: >>Why are you using a BLOB when the content is text? > > I'm using BLOB because I want them to be able to write content that is > longer than 255 chars. I'm no MySQL expert but the docs say VARCHAR fields can be up to 65,535 chars. Kent From brian at daviesinc.com Fri Mar 17 17:45:31 2006 From: brian at daviesinc.com (Brian Gustin) Date: Fri, 17 Mar 2006 11:45:31 -0500 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <441ACBC6.1000806@tds.net> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441AC847.2040507@tds.net> <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> <441ACBC6.1000806@tds.net> Message-ID: <441AE7AB.1030401@daviesinc.com> if the data is not binary, you can use TEXT type - accepts all readable characters and data, BLOB type is more for binary data storage, and MYSQL's Varchar type only stores up to 255 characters. (65,536 bits, or 64Kbits) If you are storing Binary data (DES-3 encrypted data, or image data, for example (a silly idea, IMHO, but some people store image data in databases), then you would use BLOB, but I prefer to use TEXT type for plain ol' storage of text or characters (say an html page or template, etc) rather than the binary BLOB type, although BLOB would be a space savings if the data will be quite large, and you will have many rows) HTH Bri! Kent Johnson wrote: > Adam Cripps wrote: > >>On 3/17/06, Kent Johnson <kent37 at tds.net> wrote: >> >>>Why are you using a BLOB when the content is text? >> >>I'm using BLOB because I want them to be able to write content that is >>longer than 255 chars. > > > I'm no MySQL expert but the docs say VARCHAR fields can be up to 65,535 > chars. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:441acc98175353568816312! > > From kabads at gmail.com Fri Mar 17 17:49:04 2006 From: kabads at gmail.com (Adam Cripps) Date: Fri, 17 Mar 2006 16:49:04 +0000 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <441ACBC6.1000806@tds.net> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441AC847.2040507@tds.net> <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> <441ACBC6.1000806@tds.net> Message-ID: <c7ff38550603170849p7b7dd540o4fc03353e6cc2862@mail.gmail.com> On 3/17/06, Kent Johnson <kent37 at tds.net> wrote: > Adam Cripps wrote: > > On 3/17/06, Kent Johnson <kent37 at tds.net> wrote: > >>Why are you using a BLOB when the content is text? > > > > I'm using BLOB because I want them to be able to write content that is > > longer than 255 chars. > > I'm no MySQL expert but the docs say VARCHAR fields can be up to 65,535 > chars. 65,535 for version 5.0.3 upwards - and I'm running version 4 - so it appears that I'm stuck with Blob unless you know something that I don't? Adam -- http://www.monkeez.org PGP key: 0x7111B833 From bill at celestial.net Fri Mar 17 18:30:34 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 17 Mar 2006 09:30:34 -0800 Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <20060317131200.74b96651.klappnase@freenet.de> References: <441A3911.5080706@mac.com> <441A6703.4080700@fortezzazone.org> <20060317131200.74b96651.klappnase@freenet.de> Message-ID: <20060317173033.GA91528@alexis.mi.celestial.com> On Fri, Mar 17, 2006, Michael Lange wrote: >On Fri, 17 Mar 2006 00:36:35 -0700 >fortezza-pyt <fortezza-pyt at fortezzazone.org> wrote: > >> If there a semi-standard way to test if a file system has been mounted >> or not using Python? In the Linux command line, I can type "mount" and >> see all mounted file system, and then see if the one I am looking for is >> in the list. While I could replicate this with >> Python, I am curious if there is an easier way. >> > >Hi Fortezza, > >try os.path.ismount() . That's fine if one knows what the mount points are. The more general problem is to get a list of mounted file systems. The most standard way I've found to get a list of mounted systems is to parse the output of the gdf program from the gnu fileutils compiled with the program prefix `g' so it's called gdf. The gdf program handles a lot of the dirty work, and its output is standard regardless of the underlying system, which you can't say about the system's mount or df commands. The routine below is one I've used for years (actually I used a perl version for a long time before switching primarily to python :-). # This aren't real file systems. pseudofilesys = \ dict(map((lambda x: (x, 1)), ('none', 'shmfs', 'procfs', 'tmpfs'))) gdf_cols = ('filesys', 'blocks', 'used', 'avail', 'use', 'dir') def mounted(): '''Get Mounted File Systems''' df = os.popen('gdf 2>/dev/null', 'r') df.readline() # skip first line mounted = [] for line in df.readlines(): line = line.strip() rec = dict(zip(gdf_cols, line.split(None, 5))) filesys = rec['filesys'] dir = rec.get('dir') if ( dir and not (filesys.find(':') >= 0 or pseudofilesys.get(filesys)) ): mounted.append(dir) df.close() return mounted Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Systems, Inc. URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``I presume you all know who I am. I am humble Abraham Lincoln. I have been solicited by many friends to become a candidate for the legistlature. My politics are short and sweet, like the old woman's dance. I am in favor of a national bank ... in favor of the internal improvements system, and a high protective tariff.'' -- Abraham Lincoln, 1832 From apb_4 at users.sourceforge.net Fri Mar 17 18:41:25 2006 From: apb_4 at users.sourceforge.net (Adam) Date: Fri, 17 Mar 2006 17:41:25 +0000 Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <20060317173033.GA91528@alexis.mi.celestial.com> References: <441A3911.5080706@mac.com> <441A6703.4080700@fortezzazone.org> <20060317131200.74b96651.klappnase@freenet.de> <20060317173033.GA91528@alexis.mi.celestial.com> Message-ID: <be4fbf920603170941je313413s@mail.gmail.com> On 17/03/06, Bill Campbell <bill at celestial.net> wrote: > On Fri, Mar 17, 2006, Michael Lange wrote: > >On Fri, 17 Mar 2006 00:36:35 -0700 > >fortezza-pyt <fortezza-pyt at fortezzazone.org> wrote: > > > >> If there a semi-standard way to test if a file system has been mounted > >> or not using Python? In the Linux command line, I can type "mount" and > >> see all mounted file system, and then see if the one I am looking for is > >> in the list. While I could replicate this with > >> Python, I am curious if there is an easier way. > >> > > > >Hi Fortezza, > > > >try os.path.ismount() . > > That's fine if one knows what the mount points are. > > The more general problem is to get a list of mounted file systems. > How about just reading the mtab? That's usually /etc/mtab it should be readable as a user and it means you don't have to rely on any other programs. From Pawel_Kraszewski at wp.pl Fri Mar 17 18:56:04 2006 From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Fri, 17 Mar 2006 18:56:04 +0100 Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <be4fbf920603170941je313413s@mail.gmail.com> References: <441A3911.5080706@mac.com> <20060317173033.GA91528@alexis.mi.celestial.com> <be4fbf920603170941je313413s@mail.gmail.com> Message-ID: <200603171856.04425.Pawel_Kraszewski@wp.pl> Dnia pi?tek, 17 marca 2006 18:41, Adam napisa?: > > The more general problem is to get a list of mounted file systems. > How about just reading the mtab? That's usually /etc/mtab it should be > readable as a user and it means you don't have to rely on any other > programs. Or always-up-to-date & user readable '/proc/mounts' ? -- Pawel Kraszewski From bill at celestial.net Fri Mar 17 19:06:58 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 17 Mar 2006 10:06:58 -0800 Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <be4fbf920603170941je313413s@mail.gmail.com> References: <441A3911.5080706@mac.com> <441A6703.4080700@fortezzazone.org> <20060317131200.74b96651.klappnase@freenet.de> <20060317173033.GA91528@alexis.mi.celestial.com> <be4fbf920603170941je313413s@mail.gmail.com> Message-ID: <20060317180658.GA97247@alexis.mi.celestial.com> On Fri, Mar 17, 2006, Adam wrote: >On 17/03/06, Bill Campbell <bill at celestial.net> wrote: >> On Fri, Mar 17, 2006, Michael Lange wrote: >> >On Fri, 17 Mar 2006 00:36:35 -0700 >> >fortezza-pyt <fortezza-pyt at fortezzazone.org> wrote: >> > >> >> If there a semi-standard way to test if a file system has been mounted >> >> or not using Python? In the Linux command line, I can type "mount" and >> >> see all mounted file system, and then see if the one I am looking for is >> >> in the list. While I could replicate this with >> >> Python, I am curious if there is an easier way. >> >> >> > >> >Hi Fortezza, >> > >> >try os.path.ismount() . >> >> That's fine if one knows what the mount points are. >> >> The more general problem is to get a list of mounted file systems. >> >How about just reading the mtab? That's usually /etc/mtab it should be >readable as a user and it means you don't have to rely on any other >programs. The words usually, and should are the kickers. In the 24 years I've been making my living on various versions of Unix type systems, I've seen a lot of cases where this type of assumption either fails totally or gets me in trouble because the vendor didn't do it the way they should. This is the reason I started building standard open source tools for all the systems we support (Richard Stallman would probably have said I was creating GNU/Xenix and GNU/OpenServer systems back when we supported many SCO systems :-). My fingers automatically type gfind, gdu, etc., even on Linux systems where I make symbolic links as necessary so I don't have to remember what type of system I'm typing on. One of the basic tenets of the *nix philosophy is ``build on the work of others'', and it's a lot easier to leave figuring out the guts of various systems to the authors of the gnu fileutils than it is to reinvent their work every time I want to do something. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 A fake fortuneteller can be tolerated. But an authentic soothsayer should be shot on sight. Cassandra did not get half the kicking around she deserved. -- R.A. Heinlein From bill at celestial.net Fri Mar 17 19:22:18 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 17 Mar 2006 10:22:18 -0800 Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <200603171856.04425.Pawel_Kraszewski@wp.pl> References: <441A3911.5080706@mac.com> <20060317173033.GA91528@alexis.mi.celestial.com> <be4fbf920603170941je313413s@mail.gmail.com> <200603171856.04425.Pawel_Kraszewski@wp.pl> Message-ID: <20060317182217.GA404@alexis.mi.celestial.com> On Fri, Mar 17, 2006, Pawel Kraszewski wrote: >Dnia pi? tek, 17 marca 2006 18:41, Adam napisa??: > >> > The more general problem is to get a list of mounted file systems. > >> How about just reading the mtab? That's usually /etc/mtab it should be >> readable as a user and it means you don't have to rely on any other >> programs. > >Or always-up-to-date & user readable '/proc/mounts' ? If you're sure it's a Linux system, fine. Like /etc/mtab, this isn't portable. Looking at some of the systems we have here: Linux -- systems from Caldera OpenLinux 2.3 through SuSE 10.0, have /proc/mounts and /etc/mtab. FreeBSD 4.8 Stable -- has /proc file system, but no /proc/mounts, and no /etc/mtab (yeah 4.8 is out of date, but it's been up 632 days and I want to see how long it will stay up :-). OS X 10.4.5 (Tiger) -- no /proc/mounts or /etc/fstab SCO OpenServer 5.0.6a -- no /proc/mounts or /etc/fstab All of these systems have the gnu gdf which returns information in the same format. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Systems, Inc. URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``Fix reason firmly in her seat and call to her tribunal every fact, every opinion. Question with boldness even the existence of a God; because, if there is one, he must more approve of the homage of reason, than that of blindfolded fear.'' --Thomas Jefferson From cspears2002 at yahoo.com Fri Mar 17 19:43:55 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 17 Mar 2006 10:43:55 -0800 (PST) Subject: [Tutor] walking down directories Message-ID: <20060317184355.73286.qmail@web51601.mail.yahoo.com> I am trying to write a function that takes a directory's name, finds any subdirectories, and then prints out the size of the files in all found directories. import os, os.path def describeDirectory(directory): dirList = [directory] for d in os.listdir(directory): if os.path.isdir(d): dirList.append(d) for d in dirList: print d, ':' for f in os.listdir(d): name = os.path.join(d, f) print '\t', name, 'SIZE: ', os.path.getsize(name) describeDirectory('.') Here is the output: >>> . : .\changePeppers.py SIZE: 915 .\describeDirectory.py SIZE: 549 .\describeDirectory.pyc SIZE: 514 .\describeDirectory01.py SIZE: 388 .\error_log SIZE: 778 .\makezeros.py SIZE: 147 .\makezeros.pyc SIZE: 481 .\modPrompt.py SIZE: 342 .\modPrompt.pyc SIZE: 698 .\output SIZE: 387 .\pepper.txt SIZE: 601 .\testFiles SIZE: 0 .\textWrapper.py SIZE: 619 .\textWrapper.pyc SIZE: 1092 .\timings.py SIZE: 567 .\timings.pyc SIZE: 733 testFiles : testFiles\renameFiles.py SIZE: 351 testFiles\some_date SIZE: 29 testFiles\stupid_text.txt SIZE: 12 testFiles\testDir SIZE: 0 As you see, the problem is that there is another directory under testFiles called testDir, but the function doesn't check the directory for files. The function needs to find every directory (including subdirectories within directories). Any hints? I'm starting to wonder if I should abandon trying to do this with one function. For example, I could create one function that finds every directory. This information would then be passed to another function that returns the files' sizes. From slevin at signpuddle.net Fri Mar 17 20:10:46 2006 From: slevin at signpuddle.net (Steve Slevinski) Date: Fri, 17 Mar 2006 14:10:46 -0500 Subject: [Tutor] walking down directories In-Reply-To: <20060317184355.73286.qmail@web51601.mail.yahoo.com> References: <20060317184355.73286.qmail@web51601.mail.yahoo.com> Message-ID: <441B09B6.5010608@signpuddle.net> Recursion. if os.path.isdir(d): describeDirectory(d) Since your printing from the function itself, you may want to add a level or depth arguement with a default value of 0. def describeDirectory(directory, level=0): Then call the function recursively with describeDirectory(d,level+1) Use the level variable in the print statements for proper indentation. Or something like that, -Steve Christopher Spears wrote: > I am trying to write a function that takes a > directory's name, finds any subdirectories, and then > prints out the size of the files in all found > directories. > > import os, os.path > > def describeDirectory(directory): > dirList = [directory] > for d in os.listdir(directory): > if os.path.isdir(d): > dirList.append(d) > for d in dirList: > print d, ':' > for f in os.listdir(d): > name = os.path.join(d, f) > print '\t', name, 'SIZE: ', > os.path.getsize(name) > > describeDirectory('.') > > Here is the output: > > > . : > .\changePeppers.py SIZE: 915 > .\describeDirectory.py SIZE: 549 > .\describeDirectory.pyc SIZE: 514 > .\describeDirectory01.py SIZE: 388 > .\error_log SIZE: 778 > .\makezeros.py SIZE: 147 > .\makezeros.pyc SIZE: 481 > .\modPrompt.py SIZE: 342 > .\modPrompt.pyc SIZE: 698 > .\output SIZE: 387 > .\pepper.txt SIZE: 601 > .\testFiles SIZE: 0 > .\textWrapper.py SIZE: 619 > .\textWrapper.pyc SIZE: 1092 > .\timings.py SIZE: 567 > .\timings.pyc SIZE: 733 > testFiles : > testFiles\renameFiles.py SIZE: 351 > testFiles\some_date SIZE: 29 > testFiles\stupid_text.txt SIZE: 12 > testFiles\testDir SIZE: 0 > > As you see, the problem is that there is another > directory under testFiles called testDir, but the > function doesn't check the directory for files. The > function needs to find every directory (including > subdirectories within directories). Any hints? > > I'm starting to wonder if I should abandon trying to > do this with one function. For example, I could > create one function that finds every directory. This > information would then be passed to another function > that returns the files' sizes. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From khp at pflaesterer.de Fri Mar 17 20:19:14 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Fri, 17 Mar 2006 20:19:14 +0100 Subject: [Tutor] walking down directories In-Reply-To: <20060317184355.73286.qmail@web51601.mail.yahoo.com> (Christopher Spears's message of "Fri, 17 Mar 2006 10:43:55 -0800 (PST)") References: <20060317184355.73286.qmail@web51601.mail.yahoo.com> Message-ID: <uacboevaw.fsf@hamster.pflaesterer.de> On 17 Mrz 2006, cspears2002 at yahoo.com wrote: > As you see, the problem is that there is another > directory under testFiles called testDir, but the > function doesn't check the directory for files. The > function needs to find every directory (including > subdirectories within directories). Any hints? Your function had to call itself (recursively) for each directory found. But if your goal is not to learn how to write such a function take a look at os.walk(). Karl -- Please do *not* send copies of replies to me. I read the list From cspears2002 at yahoo.com Sat Mar 18 00:36:58 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 17 Mar 2006 15:36:58 -0800 (PST) Subject: [Tutor] using cmd Message-ID: <20060317233658.61171.qmail@web51603.mail.yahoo.com> I just completed an assignment out of Learning Python in which I used the Cmd class from the cmd module to create a little shell: import cmd, os, shutil, sys class shell(cmd.Cmd): def do_EOF(self, line): sys.exit() def do_ls(self, line): if line == '': dirs = [os.curdir] else: dirs = line.split() for dirname in dirs: print 'Listing of %s:' % dirname print '\n'.join(os.listdir(dirname)) def do_cd(self, path): os.chdir(path) def do_mv(self, line): src, dest = line.splt() os.rename(src, dest) def do_cp(self, line): words = line.split() sourcefiles, target = words[:-1], words[-1] for sourcefile in sourcefiles: shutil.copyfile(sourcefile, target) def do_rm(self, line): [os.remove(arg) for arg in line.split()] class DirectoryPrompt: def __repr__(self): return os.getcwd() + '> ' cmd.Cmd.prompt = DirectoryPrompt() newShell = shell() newShell.cmdloop() My main question concerns the naming of functions such as: def do_ls(self, line): if line == '': dirs = [os.curdir] else: dirs = line.split() for dirname in dirs: print 'Listing of %s:' % dirname print '\n'.join(os.listdir(dirname)) Originally, I called the function 'ls', but when I did that, the function didn't work when I typed 'ls' at the prompt. When I looked in the back of the book, I saw the name the authors gave their function, which was 'do_ls'. When I changed the function's name to do_ls, the function worked when I typed 'ls' at the prompt. Does anyone know why this happened? From ml.cyresse at gmail.com Sat Mar 18 08:43:03 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 18 Mar 2006 20:43:03 +1300 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <c7ff38550603170849p7b7dd540o4fc03353e6cc2862@mail.gmail.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441AC847.2040507@tds.net> <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> <441ACBC6.1000806@tds.net> <c7ff38550603170849p7b7dd540o4fc03353e6cc2862@mail.gmail.com> Message-ID: <b6f3249e0603172343xbd83db8w10d4a3ff2673bb29@mail.gmail.com> Erk. MySQL 4. I imagine that has TEXT data-types also? On 3/18/06, Adam Cripps <kabads at gmail.com> wrote: > On 3/17/06, Kent Johnson <kent37 at tds.net> wrote: > > Adam Cripps wrote: > > > On 3/17/06, Kent Johnson <kent37 at tds.net> wrote: > > >>Why are you using a BLOB when the content is text? > > > > > > I'm using BLOB because I want them to be able to write content that is > > > longer than 255 chars. > > > > I'm no MySQL expert but the docs say VARCHAR fields can be up to 65,535 > > chars. > > > 65,535 for version 5.0.3 upwards - and I'm running version 4 - so it > appears that I'm stuck with Blob unless you know something that I > don't? > > Adam > -- > http://www.monkeez.org > PGP key: 0x7111B833 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From Pawel_Kraszewski at wp.pl Sat Mar 18 10:38:46 2006 From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Sat, 18 Mar 2006 10:38:46 +0100 Subject: [Tutor] Test If File System is mounted in Linux In-Reply-To: <20060317182217.GA404@alexis.mi.celestial.com> References: <441A3911.5080706@mac.com> <200603171856.04425.Pawel_Kraszewski@wp.pl> <20060317182217.GA404@alexis.mi.celestial.com> Message-ID: <200603181038.46686.Pawel_Kraszewski@wp.pl> Dnia pi?tek, 17 marca 2006 19:22, Bill Campbell napisa?: > If you're sure it's a Linux system, fine. Like /etc/mtab, this isn't > portable. Looking at some of the systems we have here: Fortezza mentioned it the way I assumed he has Linux: >> If there a semi-standard way to test if a file system has been mounted >> or not using Python? In the Linux command line, I can type "mount" and >> see all mounted file system, and then see if the one I am looking for is But, generally - you are right. Each system has its own rules for accessing mount table. Anyway - this would be a great exercise to make a portable pure-python library to get this information. -- Pawel www.kraszewscy.net From kabads at gmail.com Sat Mar 18 11:42:09 2006 From: kabads at gmail.com (Adam Cripps) Date: Sat, 18 Mar 2006 10:42:09 +0000 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <441AE7AB.1030401@daviesinc.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441AC847.2040507@tds.net> <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> <441ACBC6.1000806@tds.net> <441AE7AB.1030401@daviesinc.com> Message-ID: <c7ff38550603180242q8e5cb34s3c53a469e93742b1@mail.gmail.com> On 3/17/06, Brian Gustin <brian at daviesinc.com> wrote: > if the data is not binary, you can use TEXT type - accepts all readable > characters and data, BLOB type is more for binary data storage, and > MYSQL's Varchar type only stores up to 255 characters. (65,536 bits, or > 64Kbits) > > If you are storing Binary data (DES-3 encrypted data, or image data, for > example (a silly idea, IMHO, but some people store image data in > databases), then you would use BLOB, but I prefer to use TEXT type for > plain ol' storage of text or characters (say an html page or template, > etc) rather than the binary BLOB type, although BLOB would be a space > savings if the data will be quite large, and you will have many rows) > > HTH > Bri! Thanks - this makes sense. I will convert the table to text and see how I get on. However, there is still a learning point that might be missed here - how does Python grab BLOB data-types, and how do you manipulate them? If it were a file, would you just be able to grab the file without the array? -- http://www.monkeez.org PGP key: 0x7111B833 From alan.gauld at freenet.co.uk Sat Mar 18 13:53:22 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 18 Mar 2006 12:53:22 -0000 Subject: [Tutor] walking down directories References: <20060317184355.73286.qmail@web51601.mail.yahoo.com> Message-ID: <001b01c64a8a$f09e5b50$0b01a8c0@xp> >I am trying to write a function that takes a > directory's name, finds any subdirectories, and then > prints out the size of the files in all found > directories. > As you see, the problem is that there is another > directory under testFiles called testDir, but the > function doesn't check the directory for files. The > function needs to find every directory (including > subdirectories within directories). Any hints? You mean like the os.walk fiunction does? Take a look at the OS topic in my tutor for an example of using os.walk - its about quarter oif the way down. Alan G. From alan.gauld at freenet.co.uk Sat Mar 18 14:02:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 18 Mar 2006 13:02:53 -0000 Subject: [Tutor] using cmd References: <20060317233658.61171.qmail@web51603.mail.yahoo.com> Message-ID: <002501c64a8c$45411d90$0b01a8c0@xp> >I just completed an assignment out of Learning Python > in which I used the Cmd class from the cmd module to > create a little shell: > Originally, I called the function 'ls', but when I did > that, the function didn't work when I typed 'ls' at > the prompt. When I looked in the back of the book, I > saw the name the authors gave their function, which > was 'do_ls'. When I changed the function's name to > do_ls, the function worked when I typed 'ls' at the > prompt. Does anyone know why this happened? Its just how the module works - many GUI frameworks adopt a similar convention - eg Visual Basic command handlers. My guess os that cmd builds the command string then uses eval() to execute the function, but I could be wrong. But in general frameworks like cmd will either: 1) expect some kind of standard naming scheme (like cmd apparently does) or 2) Have some form of function registration mechanism so that code looks like def someFunc(): # blah, blah registerFunc("someCommand', someFunc) def another(): # and more here registerFunc("another", another) Or sometimes as a table: def foo(): # blah def baz(): # more blah registerFuncs( {"commandFoo": foo, "commandBaz": baz}) wxPython (Or more accurately its underlying framework, wxWidgets) uses this second approach, for example. As does Microsoft in their MFC C++ framework. HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From davholla2002 at yahoo.co.uk Sat Mar 18 14:28:32 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat, 18 Mar 2006 13:28:32 +0000 (GMT) Subject: [Tutor] Fill in a web form Message-ID: <20060318132832.86615.qmail@web25912.mail.ukl.yahoo.com> Is there a way in python to automatically put values in a web page ? For example I used to travel on a train (I live in the UK) that is always late. Is there a way to automatically to do this ? I can't think of how to do it. ------------------------------------------------------------------------------------------------------------------------------------ First they came for the Danes, but I did not speak out because I am not a Dane. --------------------------------- Win a BlackBerry device from O2 with Yahoo!. Enter now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060318/3199d7da/attachment.html From kent37 at tds.net Sat Mar 18 14:59:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Mar 2006 08:59:38 -0500 Subject: [Tutor] using cmd In-Reply-To: <20060317233658.61171.qmail@web51603.mail.yahoo.com> References: <20060317233658.61171.qmail@web51603.mail.yahoo.com> Message-ID: <441C124A.8030109@tds.net> Christopher Spears wrote: > I just completed an assignment out of Learning Python > in which I used the Cmd class from the cmd module to > create a little shell: > My main question concerns the naming of functions such > as: > > def do_ls(self, line): > if line == '': dirs = [os.curdir] > else: dirs = line.split() > for dirname in dirs: > print 'Listing of %s:' % dirname > print '\n'.join(os.listdir(dirname)) > > Originally, I called the function 'ls', but when I did > that, the function didn't work when I typed 'ls' at > the prompt. When I looked in the back of the book, I > saw the name the authors gave their function, which > was 'do_ls'. When I changed the function's name to > do_ls, the function worked when I typed 'ls' at the > prompt. Does anyone know why this happened? Cmd uses introspection (using the built-in function getattr()) to find the handler methods. For a command named 'ls' it looks for a method 'do_ls' to handle the command. You can also provide 'help_ls' to respond to the user command 'help ls'. This naming convention is built-in to Cmd so you have to use it for the module to work correctly. Kent From wescpy at gmail.com Sat Mar 18 17:05:18 2006 From: wescpy at gmail.com (w chun) Date: Sat, 18 Mar 2006 08:05:18 -0800 Subject: [Tutor] ANN: 2006 Python training courses, San Francisco In-Reply-To: <78b3a9580603071020k59e65356rc8f9279181a826d2@mail.gmail.com> References: <78b3a9580603071020k59e65356rc8f9279181a826d2@mail.gmail.com> Message-ID: <78b3a9580603180805u337b9fdfn5e481bfbb28682e6@mail.gmail.com> *** 50% DISCOUNT for STUDENTS / TEACHERS *** For those of you who already know Python or other languages but are learning Python, WE are giving 4 more Python training courses (held near the San Francisco airport) for the remainder of this year. Please forward this message to anyone else you know who may be interested. For the first time, there will be an "advanced" Python course available to the public. In fact, we've added the March intro course date for those prepping to take the advanced class in May. You may register for any of the 4 courses/dates below. (Intensive) Introduction to Python March 29-31, 2006 August 16-18, 2006 Advanced Python Programming May 17-19, 2006 November 8-10, 2006 LOCALS: it'll be at a hotel with BART and CalTrain access (San Bruno stations) as well as having 101/280/380 freeway access VISITORS: free shuttle directly from the San Francisco airport, nice facilities, food, wireless, etc. DISCOUNTS available. for more info and details, go to http://cyberwebconsulting.com and click "Python training." cheers, -wesley ps. a great big public THANKS to Rob Stephenson for putting together the short video clip of one of our training sessions for your viewing pleasure on a video iPod or PC/Mac! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From brian at daviesinc.com Sat Mar 18 17:32:14 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sat, 18 Mar 2006 11:32:14 -0500 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <c7ff38550603180241t5831686cw580713eb548b7d26@mail.gmail.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441AC847.2040507@tds.net> <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> <441ACBC6.1000806@tds.net> <441AE7AB.1030401@daviesinc.com> <c7ff38550603180241t5831686cw580713eb548b7d26@mail.gmail.com> Message-ID: <441C360E.4060209@daviesinc.com> you'd grab a blob the same way you'd grab a text data type- the only difference being the data you insert. for example, make a string of letters only, insert it into both a blob and a text data type- you can get the data out exactly as is either way , however if you attempt to put binary data into a text data type, it gets corrupted (char types will pad data with spaces to fill out the length specifier, varchar will not pad, but *will* truncate trailing spaces, as will text , and in binary data- trailing spaces are critical - they are a binary character, and the alteration of a single byte in a binary file will render it useless) - it's much like taking a compiled C binary and trying to read it in a text editor - you get a long string of incomprehensible characters - putting such data in a text field in mysql would render the code un-executable, however Blob fields dont care about spaces either leading or trailing- it just stores *precisely* what you give it to store. Ideally, if you think your data will exceed 255 characters in any given data type and it will be alphanumeric, non-binary (say, a text file) you would use TEXT field type, if you were gonna do something like store a JPG image , or even a compiled binary (cant imagine why) you would use BLOB field. Most of this information is readily available at the mysql manual, and as far as I know, Python could care less what database type you are using, it can get data from mysql as binary or integer or string or float, whatever you specify it to be.. I know that with php (my primary language, still learning python) data types are automatically converted, and with my limited work to date with python/mysql (using both python-mysqldb and the ADOdb abstraction layer for python) I have had no issues with handling data - when I get an integer from mysql that is of type integer, the value I get in python is also integer.. One thing I have been trying to research/find out is a de-cryption algorithm using our known key, to reverse mysql's own des_encrypt function - we have data stored in a mysql 4.0 table that uses that function, which is not supported in mysql 4.1 and 5 , preventing us from upgrading that one machine, and Ive been trying to find a way to match the DES3 encryption algorithm that mysql uses, (with our known key/seed of course) with little luck so far .. but in all my work, Ive never noticed any problem in handling data types- but then I read the mysql manual pretty throughly, and in my work (extremely high traffic production websites) , MySQL optimization and understanding is critical.. so maybe something seems trivially simple and obvious to me, that may actually need some explanation ? In short, whether I am working with blob or text, I would query teh table and properly type cast the variable or object to the data type I am extracting (if I know data is binary, I get it as a raw string, for example, if I know data is like an image or a compiled binary file, I would handle it as such, rather than making python process it - the object would just contain a reference to the location of the data which was extracted in the mysql query...) but then again, I do very little work with binary, and dont store files or images to a database in the first place.. :) in case I misunderstood your question- (it could also be read as how you extract the data itself from the mysql array result set) - that depends heavily on the type of query and method of fetching data, but as far as I know, you can just fetch a single piece of data from mysql as a single object, and assign it a reference... but that depends heavily on how you structure your query and has more to do with mysql than with python itself :) Bri! Adam Cripps wrote: > On 3/17/06, Brian Gustin <brian at daviesinc.com> wrote: > >>if the data is not binary, you can use TEXT type - accepts all readable >>characters and data, BLOB type is more for binary data storage, and >>MYSQL's Varchar type only stores up to 255 characters. (65,536 bits, or >>64Kbits) >> >>If you are storing Binary data (DES-3 encrypted data, or image data, for >>example (a silly idea, IMHO, but some people store image data in >>databases), then you would use BLOB, but I prefer to use TEXT type for >>plain ol' storage of text or characters (say an html page or template, >>etc) rather than the binary BLOB type, although BLOB would be a space >>savings if the data will be quite large, and you will have many rows) >> >>HTH >>Bri! >> > > > Thanks - this makes sense. I will convert the table to text and see > how I get on. > > However, there is still a learning point that might be missed here - > how does Python grab BLOB data-types, and how do you manipulate them? > If it were a file, would you just be able to grab the file without the > array? > > Adam > > -- > http://www.monkeez.org > PGP key: 0x7111B833 > > !DSPAM:441be3c3320518690210016! > > From mi.janssen at gmail.com Sat Mar 18 18:09:20 2006 From: mi.janssen at gmail.com (Michael Janssen) Date: Sat, 18 Mar 2006 18:09:20 +0100 Subject: [Tutor] Fill in a web form In-Reply-To: <20060318132832.86615.qmail@web25912.mail.ukl.yahoo.com> References: <20060318132832.86615.qmail@web25912.mail.ukl.yahoo.com> Message-ID: <1ff2dfbf0603180909q59a5c4ffs917bad142c3ccf8f@mail.gmail.com> On 3/18/06, David Holland <davholla2002 at yahoo.co.uk> wrote: > Is there a way in python to automatically put values in a web page ? For > example I used to travel on a train (I live in the UK) that is always late. > Is there a way to automatically to do this ? > I can't think of how to do it. You don't "fill" the form fields, but rather you perform the same action the browser would performs with a filled form. You must look into the html-form-tag and its action- and method-attributes. "Action" is the url to the script receiving the filled form. Method tells the browser how to send the data: "get" means to generate an url like "www.google.com?q=python', ie an url with the content of the form. Method "post" means to send the data "inline". urllib2.urlopen handles this (its data parameter for "post" data). Perhaps urllib.urlencode is of interest for you (before generating a get-url, urlencode the data, so that it renders a sane url). This answere is a bit short and might leaves you with a lot of open questions. If so, ask :-) regards Michael From kent37 at tds.net Sat Mar 18 20:26:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Mar 2006 14:26:15 -0500 Subject: [Tutor] Fill in a web form In-Reply-To: <20060318132832.86615.qmail@web25912.mail.ukl.yahoo.com> References: <20060318132832.86615.qmail@web25912.mail.ukl.yahoo.com> Message-ID: <441C5ED7.1020203@tds.net> David Holland wrote: > Is there a way in python to automatically put values in a web page ? > For example I used to travel on a train (I live in the UK) that is > always late. Is there a way to automatically to do this ? Can you be more specific? Do you want to script the browser so it displays a page (try PAMIE for IE or PyXPCOM for Mozilla) or do you want to write a program that fetches the data and displays it (urllib2 or mechanize/ClientForm to fetch the data, BeautifulSoup to parse the response and get what you want). Google any of the above for details or ask again here. Kent From brian at daviesinc.com Sat Mar 18 21:14:23 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sat, 18 Mar 2006 15:14:23 -0500 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> Message-ID: <441C6A1F.5080606@daviesinc.com> Oh. just found the original question.. :) OK perhaps this would be more helpful if you were to manually query mysql on command line and paste the results it outputs here. what I am betting is your method to get the data out of teh query is doing exactly what you tell it to.. :) but this hinges on the answer to "what is the original row of data returned by commandline mysql query" keep in mind Mysql returns a result set as an array (a list or dictionary, when it is associative, if you will) what your code is doing is taking the row (array) and appending it to an additional list.. and where you print the whole, you are basically printing out the multi-dimensional array, and I am betting the *last element* returned non-null in the mysql query is the content field.. :) but again, it depends on what the actual content is.. run these two in mysql command line: mysql> show create table report; mysql> select * from report limit 1; and let me know the results.. :) I doubt that blob vs. text has anything to do with this issue :) Bri! Adam Cripps wrote: > I'm trying to build a mini-CMS for my class to manage a single > webpage, using CGI and mysql. The children will be storing their main > content in a BLOB within a Mysql database. > > When I query the content column, I get a strange return like this: > > array('c', 'This is a test ') > > - when the only text I entered in was 'This is a test'. > > When I query mysql directly through a prompt, I get 'This is a test'. > > Does a CGI query get mangled text from a blob? My other VARCHAR > columns are fine. > > Code: > > def query(statement): > results = [] > mycursor.execute(statement) > myrowcount = int(mycursor.rowcount) > for i in range (0, myrowcount): > myrow = mycursor.fetchone() > results.append(myrow) > return results > > reportquery = "select id, title, content, published from report" > reportlist = query(reportquery) > print "<p>" + str(reportlist) + "</p>" > > > id = primary key, integer, not null > title = varchar(255) > content = blob > published = char(1), default ='n' > > I've tried using looking at > reportlist[0][2][1], but that just returns 'T' - which is obviously > the T in 'This'. > > TIA > Adam > -- > http://www.monkeez.org > PGP key: 0x7111B833 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:441ac610153321413855301! > > From alan.gauld at freenet.co.uk Sun Mar 19 00:13:57 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 18 Mar 2006 23:13:57 -0000 Subject: [Tutor] Fill in a web form References: <20060318132832.86615.qmail@web25912.mail.ukl.yahoo.com> Message-ID: <006001c64ae1$a28d63f0$0b01a8c0@xp> Hi David, You lost me there. What does a late train ghave to do with filling in web forms?! > Is there a way in python to automatically put values in a web page ? > For example I used to travel on a train (I live in the UK) that is > always late. Is there a way to automatically to do this ? Alan G. From kabads at gmail.com Sun Mar 19 09:20:09 2006 From: kabads at gmail.com (Adam Cripps) Date: Sun, 19 Mar 2006 08:20:09 +0000 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <441C6A1F.5080606@daviesinc.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441C6A1F.5080606@daviesinc.com> Message-ID: <c7ff38550603190020i2e42eaa1q8f00473a0a56d0b5@mail.gmail.com> On 3/18/06, Brian Gustin <brian at daviesinc.com> wrote: > Oh. just found the original question.. :) > > OK perhaps this would be more helpful if you were to manually query > mysql on command line and paste the results it outputs here. > > what I am betting is your method to get the data out of teh query is > doing exactly what you tell it to.. :) > > but this hinges on the answer to "what is the original row of data > returned by commandline mysql query" > > keep in mind Mysql returns a result set as an array (a list or > dictionary, when it is associative, if you will) > > what your code is doing is taking the row (array) and appending it to an > additional list.. > > and where you print the whole, you are basically printing out the > multi-dimensional array, and I am betting the *last element* returned > non-null in the mysql query is the content field.. :) > > but again, it depends on what the actual content is.. > > run these two in mysql command line: > > mysql> show create table report; > mysql> select * from report limit 1; > > and let me know the results.. :) > > I doubt that blob vs. text has anything to do with this issue :) > > Bri! Thanks again Bri, for both your responses. As requested - mysql> show create table report: | report | CREATE TABLE `report` ( `id` int(11) NOT NULL auto_increment, `title` varchar(255) default NULL, `content` blob, `author` int(10) default NULL, `published` varchar(10) default 'n', `rejected` char(1) default NULL, PRIMARY KEY (`id`) ) TYPE=MyISAM | mysql> select * from report limit 1; +----+-------+-----------------+--------+-----------+----------+ | id | title | content | author | published | rejected | +----+-------+-----------------+--------+-----------+----------+ | 1 | Test | This is a test | 0 | n | NULL | +----+-------+-----------------+--------+-----------+----------+ 1 row in set (0.02 sec) (shame this doesn't monospace in Gmail) You are right to bet that the last non-null field (part of the array) is the content field (select id, title, content from report) Adam -- http://www.monkeez.org PGP key: 0x7111B833 From brian at daviesinc.com Sun Mar 19 18:39:16 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sun, 19 Mar 2006 12:39:16 -0500 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <c7ff38550603190020i2e42eaa1q8f00473a0a56d0b5@mail.gmail.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441C6A1F.5080606@daviesinc.com> <c7ff38550603190020i2e42eaa1q8f00473a0a56d0b5@mail.gmail.com> Message-ID: <441D9744.4050605@daviesinc.com> OK so I guess you know what you need to do now :) something like this perhaaps : (modified your original code) reportlist = query(reportquery) mystring = '<p>' for row in reportlist: id = row[0] title = row[1] content = row[2] published = row[3] mystring = mystring+id+"\t"+title+"\t"+content+"\t"+published+"</p>" print mystring should get you the data - you may want to force the values to str() type just in case.. anyhow.. when you append an array to an array, you have a multi-dimensional array, so when you iterate, you need to handle two arrays, in essence.. what python is doing is just what it told you to do - convert the multi dimensional list object into a string and print it. :) , therefore, the output would be array("listitem","listitem") basically :) you need to extract your list elements and convert those to strings, then you can work with the whole as a string :) otherwise, do print reportlist (without the str() stuff) and you will print out the entire list of data so you can see what you will be working with :) what I would do is a function that returns the result set, instead, and then iterate over that list object.. Bri! Adam Cripps wrote: > On 3/18/06, Brian Gustin <brian at daviesinc.com> wrote: > >>Oh. just found the original question.. :) >> >>OK perhaps this would be more helpful if you were to manually query >>mysql on command line and paste the results it outputs here. >> >>what I am betting is your method to get the data out of teh query is >>doing exactly what you tell it to.. :) >> >>but this hinges on the answer to "what is the original row of data >>returned by commandline mysql query" >> >>keep in mind Mysql returns a result set as an array (a list or >>dictionary, when it is associative, if you will) >> >>what your code is doing is taking the row (array) and appending it to an >>additional list.. >> >>and where you print the whole, you are basically printing out the >>multi-dimensional array, and I am betting the *last element* returned >>non-null in the mysql query is the content field.. :) >> >>but again, it depends on what the actual content is.. >> >>run these two in mysql command line: >> >>mysql> show create table report; >>mysql> select * from report limit 1; >> >>and let me know the results.. :) >> >>I doubt that blob vs. text has anything to do with this issue :) >> >>Bri! > > > Thanks again Bri, for both your responses. > > As requested - > > mysql> show create table report: > | report | CREATE TABLE `report` ( > `id` int(11) NOT NULL auto_increment, > `title` varchar(255) default NULL, > `content` blob, > `author` int(10) default NULL, > `published` varchar(10) default 'n', > `rejected` char(1) default NULL, > PRIMARY KEY (`id`) > ) TYPE=MyISAM | > > mysql> select * from report limit 1; > +----+-------+-----------------+--------+-----------+----------+ > | id | title | content | author | published | rejected | > +----+-------+-----------------+--------+-----------+----------+ > | 1 | Test | This is a test | 0 | n | NULL | > +----+-------+-----------------+--------+-----------+----------+ > 1 row in set (0.02 sec) > (shame this doesn't monospace in Gmail) > > > You are right to bet that the last non-null field (part of the array) > is the content field (select id, title, content from report) > Adam > -- > http://www.monkeez.org > PGP key: 0x7111B833 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:441d42ee268352025918492! > > From matva88 at gmail.com Sun Mar 19 19:04:11 2006 From: matva88 at gmail.com (John) Date: Sun, 19 Mar 2006 13:04:11 -0500 Subject: [Tutor] what tools will i need to start my project ? Message-ID: <op.s6n9s9kpfxatkd@john> i'm new to programming and decided to go with python as my first language. my goal is to create an excel macros that will grab information from an html file and import it into my worksheet. I figure i should first start apart from excel then work on making it work with it (if it is even possible). is excel macros exclusively vb or is it possible to get excel to work with other languages... or maybe openoffice spreadsheet? either one, doesn't matter to me. the result will be a listing of all my movies complete with information from imdb.com. i already have something that does this in vb but i didn't write it and i'd like to create my own. i read about find() and how it returns the index of the 1st character of what you searched for. from what i can read from the vb code i have, what i have to do is search for a start and end string and grab the string in between. This works because there is certain formatting/code that stays constant in the html files. so for example, if the title of a movie lies somewhere between <strong class= and <small> every time, i would need to grab the text between those start and finish points. Am i making any sense? So basically, i am asking what, in addtion to find(), do i need to read up about. I think the vb equiv is InStr() and something else.. i posted this on the python-forum and recieved only 1 response. I learned how to read from an html using file(). I'm also looking for a searchable directory of python tool usage. for example if i type file() it will give me an explanation of what it does and how to use it. thanks From davholla2002 at yahoo.co.uk Sun Mar 19 19:36:05 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sun, 19 Mar 2006 18:36:05 +0000 (GMT) Subject: [Tutor] Tutor Digest, Vol 25, Issue 47 In-Reply-To: <mailman.11326.1142712867.27774.tutor@python.org> Message-ID: <20060319183605.77465.qmail@web25910.mail.ukl.yahoo.com> Message: 8 Date: Sat, 18 Mar 2006 14:26:15 -0500 From: Kent Johnson Subject: Re: [Tutor] Fill in a web form Cc: tutor python Message-ID: <441C5ED7.1020203 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed David Holland wrote: > Is there a way in python to automatically put values in a web page ? > For example I used to travel on a train (I live in the UK) that is > always late. Is there a way to automatically to do this ? Can you be more specific? Do you want to script the browser so it displays a page (try PAMIE for IE or PyXPCOM for Mozilla) or do you want to write a program that fetches the data and displays it (urllib2 or mechanize/ClientForm to fetch the data, BeautifulSoup to parse the response and get what you want). Google any of the above for details or ask again here. Kent Kent, Michael and Allan, Thank you for the advice. Perhaps I did not explain it very well. What I meant was with python it is possible to create a program that creates a .txt file with various values automically. Is it possible to send values to a web site automatically. (Eg if every day your train is late how would you create a program to complain for you on this page http://www.southwesttrains.co.uk/SWTrains/Customerservice/_Contact+form.htm). I think what Michael suggested is correct. I will have a look when I am better (I am suffering from the flu). Thanks again everyone. ------------------------------------------------------------------------------------------------------------------------------------ First they came for the Danes, but I did not speak out because I am not a Dane. --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with voicemail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060319/1257a125/attachment.htm From sanelson at gmail.com Sun Mar 19 22:05:37 2006 From: sanelson at gmail.com (Steve Nelson) Date: Sun, 19 Mar 2006 21:05:37 +0000 Subject: [Tutor] Alternative to nested loops Message-ID: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com> Hi All, I had a feeling I could do this: >>> foo [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> for c in foo: ... for b in c: ... print b ... 1 2 3 1 2 3 1 2 3 Using a list comprehension, as it seemed to me like I was saying: b for c in foo, but I can't see how to do this. Ultimately I want to sum each number and produce a total. I know how to do this as above, but was wondering if there is an alternative / better way? S. From andre.roberge at gmail.com Sun Mar 19 22:25:21 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Sun, 19 Mar 2006 17:25:21 -0400 Subject: [Tutor] Opening .py files in firefox Message-ID: <7528bcdd0603191325r34fff421ld06ba378d1c0298d@mail.gmail.com> Hi everyone- This is not strictly speaking a Python question but it's probably something that other pythonistas have encountered and, hopefully solved :-) When I click on a link to a ".py" file (either remotely or on my computer) using firefox, it gives me two options: running the script with the default Python app, or saving the file. What I would like is to display the file as text in the browser. Any ideas? This is on Windows XP. Andr? From brian at daviesinc.com Sun Mar 19 22:53:02 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sun, 19 Mar 2006 16:53:02 -0500 Subject: [Tutor] Opening .py files in firefox In-Reply-To: <7528bcdd0603191325r34fff421ld06ba378d1c0298d@mail.gmail.com> References: <7528bcdd0603191325r34fff421ld06ba378d1c0298d@mail.gmail.com> Message-ID: <441DD2BE.2010208@daviesinc.com> server needs to be set up with a handler to tell it what to do with the file , otherwise it will look at local host to determine what to do with it , via the extension, and if no extension is found, then it will simply offer to download the file to your computer . if you want it to display as text, the webserver needs to be set up to do so :) If it is Apache Webserver, you need to use the AddHandler or SetHandler directives (note these directives differ between apache 1.3.x and 2.x) HTH Andre Roberge wrote: > Hi everyone- > > This is not strictly speaking a Python question but it's probably > something that other pythonistas have encountered and, hopefully > solved :-) > > When I click on a link to a ".py" file (either remotely or on my > computer) using firefox, it gives me two options: running the script > with the default Python app, or saving the file. What I would like is > to display the file as text in the browser. Any ideas? This is on > Windows XP. > > Andr? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:441dcd08315282096420017! > > From khp at pflaesterer.de Sun Mar 19 23:11:12 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sun, 19 Mar 2006 23:11:12 +0100 Subject: [Tutor] Alternative to nested loops In-Reply-To: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com> (Steve Nelson's message of "Sun, 19 Mar 2006 21:05:37 +0000") References: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com> Message-ID: <ufyleay4u.fsf@hamster.pflaesterer.de> On 19 Mrz 2006, sanelson at gmail.com wrote: > I had a feeling I could do this: > >>>> foo > [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>>> for c in foo: > ... for b in c: > ... print b > ... > 1 > 2 > 3 > 1 > 2 > 3 > 1 > 2 > 3 > > Using a list comprehension, as it seemed to me like I was saying: b I wouldn't use a list comprehension here since you don't use the list returned. A list comprehension is used if you need a list not to iterate over a list and e.g print the elemenst. > for c in foo, but I can't see how to do this. Ultimately I want to > sum each number and produce a total. I know how to do this as above, > but was wondering if there is an alternative / better way? Use e.g. reduce: .>>> reduce(lambda s, L: s + sum(L), foo, 0) .18 Karl -- Please do *not* send copies of replies to me. I read the list From john at fouhy.net Sun Mar 19 23:41:59 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 20 Mar 2006 10:41:59 +1200 Subject: [Tutor] Alternative to nested loops In-Reply-To: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com> References: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com> Message-ID: <5e58f2e40603191441p7d44661bp@mail.gmail.com> On 20/03/06, Steve Nelson <sanelson at gmail.com> wrote: > Hi All, > > I had a feeling I could do this: > > >>> foo > [[1, 2, 3], [1, 2, 3], [1, 2, 3]] > >>> for c in foo: > ... for b in c: > ... print b What you're doing is called "flattening" a list. You can do it with a list comprehension: >>> foo = [[1,2,3], [4,5,6], [7,8,9]] >>> [x for y in foo for x in y] [1, 2, 3, 4, 5, 6, 7, 8, 9] There are also other ways; ActiveState has several in its cookbook. If you want to sum, you could also use a generator expression (requires Python 2.4): >>> sum(x for y in foo for x in y) 45 This will be slightly faster, depending on how big your list is. But really, there are times when clarity and efficiency both come together and say "Write explicit for loops" :-) -- John. From sanelson at gmail.com Sun Mar 19 23:44:23 2006 From: sanelson at gmail.com (Steve Nelson) Date: Sun, 19 Mar 2006 22:44:23 +0000 Subject: [Tutor] Alternative to nested loops In-Reply-To: <ufyleay4u.fsf@hamster.pflaesterer.de> References: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com> <ufyleay4u.fsf@hamster.pflaesterer.de> Message-ID: <b6131fdc0603191444t69fc2541qf9b1efc021920a05@mail.gmail.com> On 3/19/06, Karl Pfl?sterer <khp at pflaesterer.de> wrote: >>> reduce(lambda s, L: s + sum(L), foo, 0) Ah ok - well that looks pretty cryptic to me, as I've never used either lambda or reduce(). However, this looks to be a 'functional' way of doing what I was doing procedurally, which is, I suppose, what I was asking. Would you mind helping to explain how the above works? Incidentally, I had a look at: http://www-128.ibm.com/developerworks/linux/library/l-prog.html As an introduction to functional programming in Python - it looks interesting. I've never done any functional programming at all, so it all seems a little foreign! Can you recommend another gentle introduction? Or will this fry my brain, as I start trying to mix methodologies? Thanks! S. From sanelson at gmail.com Sun Mar 19 23:58:49 2006 From: sanelson at gmail.com (Steve Nelson) Date: Sun, 19 Mar 2006 22:58:49 +0000 Subject: [Tutor] Alternative to nested loops In-Reply-To: <5e58f2e40603191441p7d44661bp@mail.gmail.com> References: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com> <5e58f2e40603191441p7d44661bp@mail.gmail.com> Message-ID: <b6131fdc0603191458paee98e2k95cbb3ab76c5cd8d@mail.gmail.com> On 3/19/06, John Fouhy <john at fouhy.net> wrote: > What you're doing is called "flattening" a list. You can do it with a > list comprehension: > > >>> foo = [[1,2,3], [4,5,6], [7,8,9]] > >>> [x for y in foo for x in y] > [1, 2, 3, 4, 5, 6, 7, 8, 9] Ah yes, that was the sort of thing I was thinking of. > If you want to sum, you could also use a generator expression > (requires Python 2.4): I am on 2.3.5 so I can do sum([x for y in foo for x in y]) So now looking at both your and Karl's ways, how do I catch exceptions. My current (working) code looks like this: def fleetHealth(self): """Iterate through each square to see if the whole fleet has been sunk.""" s = 0 for c in self.ranks: for b in c: try: s += b.contents.size() except: pass return s I guess this could be significantly refactored! But... readability counts! S. From alan.gauld at freenet.co.uk Mon Mar 20 00:21:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Mar 2006 23:21:10 -0000 Subject: [Tutor] what tools will i need to start my project ? References: <op.s6n9s9kpfxatkd@john> Message-ID: <001901c64bab$cef8cae0$0b01a8c0@xp> Hi John, > i'm new to programming and decided to go with python as my first language. Normally I'd say that was a good choice, but it really depends on what you want to do. > my goal is to create an excel macros that will grab information from an > html file and import it into my worksheet. The easiest way to do that is with a VB macro from within Excel. Therefore you will be better off learning VB for excel. From there you can fairly easily learn Python if you want to write general purpose programs too. But for your purpose you will be better off learning VB IMHO... > I figure i should first start apart from excel then work on making it > work with it If you start from inside excel it all becomes much easier. > possible). is excel macros exclusively vb or is it possible to get excel > to work with other languages... You can use Microsoft COM technology to access Excel from an external program using almost any language, including Python. > one, doesn't matter to me. the result will be a listing of all my movies > complete with information from imdb.com. i already have something that > does this in vb but i didn't write it and i'd like to create my own. OK, If you want to use this as a way to program in the wider sense then Python is indeed a better choice. > i read about find() and how it returns the index of the 1st character of > what you searched for. from what i can read from the vb code i have, what > i have to do is search for a start and end string and grab the string in > between. This works because there is certain formatting/code that stays > constant in the html files. You can use an HTML parser like Beautiful Soup to do all the HTML work, its much easier to do it that way. HTML is surprisingly hard to parse by hand coding, its much better to use a purpose built library like Beautiful Soup. > sense? So basically, i am asking what, in addtion to find(), do i need to > read up about. I think the vb equiv is InStr() and something else.. You probably should start with an introductory tutorial to cover the principles of Python. Any of the beginners tutors should cober the basic string operations. Since you seem to be a little conversant with VB you might find my tutor useful since it compares VBScript(VBs little brother) with python. For this project you only need to cover the "Basics" section. > how to read from an html using file(). I'm also looking for a searchable > directory of python tool usage. for example if i type file() it will give > me an explanation of what it does and how to use it. At the prompt type help: >>> help(file) Use Q to quit the help system. Also Googling for Python file and specifying the python.org website in the advanced settings should help. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Mar 20 00:29:01 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Mar 2006 23:29:01 -0000 Subject: [Tutor] Opening .py files in firefox References: <7528bcdd0603191325r34fff421ld06ba378d1c0298d@mail.gmail.com> Message-ID: <002101c64bac$e7f3f1e0$0b01a8c0@xp> > computer) using firefox, it gives me two options: running the script > with the default Python app, or saving the file. What I would like is > to display the file as text in the browser. Open Tools->Folder Options in Windows explorer Go to File Types tab Scroll down to find .py (and .pyw) Click Advanced button Click New... type Display in Action box (or whatever menu entry you want to use) Use browser to locate the Firefox executable OK back out. Now right click a python file and you should see a Display entry that opens the code in the browser. If the browser tries to execute the script you will need to go to the file types setting in the browser and set .py to plain-text. But I didn't need to do that. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Mar 20 00:31:59 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 19 Mar 2006 23:31:59 -0000 Subject: [Tutor] Alternative to nested loops References: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com><ufyleay4u.fsf@hamster.pflaesterer.de> <b6131fdc0603191444t69fc2541qf9b1efc021920a05@mail.gmail.com> Message-ID: <002901c64bad$51a41110$0b01a8c0@xp> > interesting. I've never done any functional programming at all, so it > all seems a little foreign! > > Can you recommend another gentle introduction? Try the functional programming topic in the Advanced section of my tutor. It covers the concepts and how to do it in Python at the basic level. Covers amonst other things, reduce, lambdas and list comps too. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From sanelson at gmail.com Mon Mar 20 00:46:21 2006 From: sanelson at gmail.com (Steve Nelson) Date: Sun, 19 Mar 2006 23:46:21 +0000 Subject: [Tutor] Alternative to nested loops In-Reply-To: <002901c64bad$51a41110$0b01a8c0@xp> References: <b6131fdc0603191305l797b5758q92fd1c89f0bbadc@mail.gmail.com> <ufyleay4u.fsf@hamster.pflaesterer.de> <b6131fdc0603191444t69fc2541qf9b1efc021920a05@mail.gmail.com> <002901c64bad$51a41110$0b01a8c0@xp> Message-ID: <b6131fdc0603191546r4c88eb59q396dfe831964fb7@mail.gmail.com> On 3/19/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > interesting. I've never done any functional programming at all, so it > > all seems a little foreign! > > > > Can you recommend another gentle introduction? > > Try the functional programming topic in the Advanced section of my tutor. > It covers the concepts and how to do it in Python at the basic level. Thanks - that makes things much clearer. I love the fact that Python can be used in so many ways! S. From andre.roberge at gmail.com Mon Mar 20 00:52:29 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Sun, 19 Mar 2006 19:52:29 -0400 Subject: [Tutor] Opening .py files in firefox In-Reply-To: <002101c64bac$e7f3f1e0$0b01a8c0@xp> References: <7528bcdd0603191325r34fff421ld06ba378d1c0298d@mail.gmail.com> <002101c64bac$e7f3f1e0$0b01a8c0@xp> Message-ID: <7528bcdd0603191552j7fcc1034r1a6b68f591ace4@mail.gmail.com> On 3/19/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > computer) using firefox, it gives me two options: running the script > > with the default Python app, or saving the file. What I would like is > > to display the file as text in the browser. > > Open Tools->Folder Options in Windows explorer > [snipped useful explanation on setting defaults within Windows explorer] > > If the browser tries to execute the script you will need to go to > the file types setting in the browser and set .py to plain-text. This is what I need to do ... but, after looking at all the options (within tools->Options), I still can not find a way to do this; firefox insists on executing the script. This is for a local file. btw, the deleted part of your explantion contained an unfortunate firefox-snafu: when I try to open a file in "my document", firefox splits up the path, interprets the request as a series of files to open, and start to open a number of totally unrelated webpages. > But I didn't need to do that. :-( for me! Thanks for your help, anyway; I'll stick to opening them with an editor for now. Andr? > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > > > > > > > > > From hugonz-lists at h-lab.net Mon Mar 20 05:40:34 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 19 Mar 2006 22:40:34 -0600 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <c7ff38550603180242q8e5cb34s3c53a469e93742b1@mail.gmail.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441AC847.2040507@tds.net> <c7ff38550603170639k91d8d0cp2343baebff75d001@mail.gmail.com> <441ACBC6.1000806@tds.net> <441AE7AB.1030401@daviesinc.com> <c7ff38550603180242q8e5cb34s3c53a469e93742b1@mail.gmail.com> Message-ID: <441E3242.2050802@h-lab.net> > However, there is still a learning point that might be missed here - > how does Python grab BLOB data-types, and how do you manipulate them? > If it were a file, would you just be able to grab the file without the > array? The basic issue is: what form is used for representing arbitrary byte data of arbitrary length. 1) strings: strings in python are arbitrarily large and can store any byte values (compare this with other languages like C where the number 0 signals the end of a string) Strings are OK, and that's what the standard library writes to files. 2) arrays: there is but one problem with strings, and that they are inmutable: you have to create a new string everytime you want to change an old one. Long data chunks are inefficiently worked when using strings, so you may use arrays (array.array) which can be changed in place. Of course there are many more options, like a tuple or a list of 255 or less ints, but these are the main contenders for byte valued sequences. Hope that clears thing a bit, Hugo > > > -- > http://www.monkeez.org > PGP key: 0x7111B833 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Mon Mar 20 21:38:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 20 Mar 2006 20:38:12 -0000 Subject: [Tutor] Opening .py files in firefox References: <7528bcdd0603191325r34fff421ld06ba378d1c0298d@mail.gmail.com><002101c64bac$e7f3f1e0$0b01a8c0@xp> <7528bcdd0603191552j7fcc1034r1a6b68f591ace4@mail.gmail.com> Message-ID: <004f01c64c5e$3577d380$0b01a8c0@xp> > If the browser tries to execute the script you will need to go to > the file types setting in the browser and set .py to plain-text. > > This is what I need to do ... but, after looking at all the options > (within tools->Options), I still can not find a way to do this; Neither can I! How odd. > firefox-snafu: when I try to open a file in "my document", firefox > splits up the path, interprets the request as a series of files to > open, and start to open a number of totally unrelated webpages. You probably need to mess around with quotes. Something like "%1" after the exectuable name might do it %1 is DOS shorthand for the name of the file... Putting it in quotes should stop Firefox splitting the path. > Thanks for your help, anyway; I'll stick to opening them with an editor > for now. You've got me curious how to do this in Firefox now :-) Alan G. From singletoned at gmail.com Tue Mar 21 10:30:22 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 21 Mar 2006 09:30:22 +0000 Subject: [Tutor] Opening .py files in firefox In-Reply-To: <004f01c64c5e$3577d380$0b01a8c0@xp> References: <7528bcdd0603191325r34fff421ld06ba378d1c0298d@mail.gmail.com> <002101c64bac$e7f3f1e0$0b01a8c0@xp> <7528bcdd0603191552j7fcc1034r1a6b68f591ace4@mail.gmail.com> <004f01c64c5e$3577d380$0b01a8c0@xp> Message-ID: <34bb7f5b0603210130u6ced456fo@mail.gmail.com> On 20/03/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > If the browser tries to execute the script you will need to go to > > the file types setting in the browser and set .py to plain-text. > > > > This is what I need to do ... but, after looking at all the options > > (within tools->Options), I still can not find a way to do this; > > Neither can I! How odd. > > > firefox-snafu: when I try to open a file in "my document", firefox > > splits up the path, interprets the request as a series of files to > > open, and start to open a number of totally unrelated webpages. > > You probably need to mess around with quotes. > > Something like "%1" after the exectuable name might do it > %1 is DOS shorthand for the name of the file... Putting it in > quotes should stop Firefox splitting the path. > > > Thanks for your help, anyway; I'll stick to opening them with an editor > > for now. > > You've got me curious how to do this in Firefox now :-) On Windows, Go to Run then type Regedit. Go to HKEY_CLASSES_ROOT and find .py then change it's Content Type to text/plain. As far as I am aware this is the default for python files anyway, but it may have got changed on your computer. Firefox itself doesn't have a list of MimeTypes under normal circumstances. It's mimetypes.rdf is generally empty except for references to online lists of mimetypes. (It's stored in your profile btw, usually [your profile]\Application Data\Mozilla\Firefox\Profiles\) Ed From johanna.freeman at tiscali.it Tue Mar 21 10:50:33 2006 From: johanna.freeman at tiscali.it (Johanna) Date: Tue, 21 Mar 2006 10:50:33 +0100 Subject: [Tutor] Python & MP3 Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAO3frLa9jTtGmo8jK/xV58rCgAAAEAAAAE41ySYcJOpLr58hoyzt3EYBAAAAAA==@tiscali.it> Hallo This is my first post, so hallo to everyone. Im just a newbee with python so I hope my msg will make some sense. :-) Is it possible to work with MP3 in python? I'm looking for a library to modify MP3s (like fade in, fade out, etc..). I know there are actually some libraries for doing this work with .wav but I didn't find one for working with MP3. I'm not sure but should be something like -> http://effbot.org/librarybook/wave.htm . Anyone? Thanks. Jo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060321/6e69c091/attachment.htm From bclum at cs.ucsd.edu Tue Mar 21 10:23:26 2006 From: bclum at cs.ucsd.edu (Brian C. Lum) Date: Tue, 21 Mar 2006 01:23:26 -0800 (PST) Subject: [Tutor] Python Control Flow Graph Message-ID: <Pine.LNX.4.63.0603210121160.14681@csegrad.ucsd.edu> Dear Python Tutors, I have been looking for a good way to convert python code into a control flow graph. I know of Python functions that will convert an expression into an abstract syntax tree (i.e. ast = parser.expr('(x+5)*5') then t = ast.totuple() then t), but I am not sure how to obtain a CFG. I've gone through the compiler and it has code that converts the AST into a CFG (described here: http://www.python.org/doc/peps/pep-0339/#ast-to-cfg-to-bytecode). Basically, PyAST_Compile() in Python/compile.c coverts the AST to a CFG and outputs final bytecode from the CFG by calling two functions: PySymtable_Build() in Python/symtable.c and compiler_mod() in Python/compile.c. PySymtable_Build() will build a symtable and compiler_mod() will create the CFG. I can try to hack with the compiler, but I was wondering if anyone knew of any tools already out there or any easier way. Thanks, Brian From andre.roberge at gmail.com Tue Mar 21 11:32:00 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Tue, 21 Mar 2006 06:32:00 -0400 Subject: [Tutor] Python & MP3 In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAO3frLa9jTtGmo8jK/xV58rCgAAAEAAAAE41ySYcJOpLr58hoyzt3EYBAAAAAA==@tiscali.it> References: <!&!AAAAAAAAAAAYAAAAAAAAAO3frLa9jTtGmo8jK/xV58rCgAAAEAAAAE41ySYcJOpLr58hoyzt3EYBAAAAAA==@tiscali.it> Message-ID: <7528bcdd0603210232o9bb2ac4sa3e32306f3bbd444@mail.gmail.com> On 3/21/06, Johanna <johanna.freeman at tiscali.it> wrote: > Hallo > This is my first post, so hallo to everyone. Im just a newbee with python so > I hope my msg will make some sense. > > Is it possible to work with MP3 in python? > Pygame (http://www.pygame.org/docs/ref/music.html) apparently works with mp3 files. There's also a tutorial on using Pygame to work with sound files at http://takira.freehosting.net/ (check Pygame notes). I haven't used it myself. Andr? > I'm looking for a library to modify MP3s (like fade in, fade out, etc..). I > know there are actually some libraries for doing this work with .wav but I > didn't find one for working with MP3. I'm not sure but should be something > like -> http://effbot.org/librarybook/wave.htm . Anyone? > > > > Thanks. > > > > Jo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From andre.roberge at gmail.com Tue Mar 21 11:59:43 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Tue, 21 Mar 2006 06:59:43 -0400 Subject: [Tutor] Opening .py files in firefox In-Reply-To: <004f01c64c5e$3577d380$0b01a8c0@xp> References: <7528bcdd0603191325r34fff421ld06ba378d1c0298d@mail.gmail.com> <002101c64bac$e7f3f1e0$0b01a8c0@xp> <7528bcdd0603191552j7fcc1034r1a6b68f591ace4@mail.gmail.com> <004f01c64c5e$3577d380$0b01a8c0@xp> Message-ID: <7528bcdd0603210259v77afdb69ua461170805170f8e@mail.gmail.com> ** Copy of a reply sent only to Alan Gauld by mistake. On 3/20/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > If the browser tries to execute the script you will need to go to > > the file types setting in the browser and set .py to plain-text. > > > > This is what I need to do ... but, after looking at all the options > > (within tools->Options), I still can not find a way to do this; > > Neither can I! How odd. > > > firefox-snafu: when I try to open a file in "my document", firefox > > splits up the path, interprets the request as a series of files to > > open, and start to open a number of totally unrelated webpages. > > You probably need to mess around with quotes. > > Something like "%1" after the exectuable name might do it > %1 is DOS shorthand for the name of the file... Putting it in > quotes should stop Firefox splitting the path. > Thanks, that solved both problems! I can now either right-click on a Python file (icon) and chose to display it in the browser, or open the file within Firefox (ctrl-o) itself. Thank you!! :-) Andr? From cdw202 at soton.ac.uk Tue Mar 21 12:57:05 2006 From: cdw202 at soton.ac.uk (Christian Wood) Date: Tue, 21 Mar 2006 11:57:05 -0000 Subject: [Tutor] TKinter question Message-ID: <001c01c64cde$95e8f200$bd1a4e98@soton.ac.uk> To whom this may concern, Attatched is the source code, which demonstrates a problem I am having making a GUI for my python project work. Both files need to be in the same folder. My code writes to a text file 'table.txt', and 'table.txt' is displayed in the GUI. The user can generate new data at the click of a button which re-writes 'table.txt', but I can only add the new table to the GUI window rather than 'update' the existing one. Any assistance would be much appreciated, Regards, Christian Wood. Part III Aerospace Engineering University of Southampton, UK. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: help.py Url: http://mail.python.org/pipermail/tutor/attachments/20060321/299aecf2/attachment.pot -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: table.txt Url: http://mail.python.org/pipermail/tutor/attachments/20060321/299aecf2/attachment.txt From python at venix.com Tue Mar 21 15:14:34 2006 From: python at venix.com (Python) Date: Tue, 21 Mar 2006 09:14:34 -0500 Subject: [Tutor] Python & MP3 In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAO3frLa9jTtGmo8jK/xV58rCgAAAEAAAAE41ySYcJOpLr58hoyzt3EYBAAAAAA==@tiscali.it> References: <!&!AAAAAAAAAAAYAAAAAAAAAO3frLa9jTtGmo8jK/xV58rCgAAAEAAAAE41ySYcJOpLr58hoyzt3EYBAAAAAA==@tiscali.it> Message-ID: <1142950474.6491.188.camel@www.venix.com> On Tue, 2006-03-21 at 10:50 +0100, Johanna wrote: > Hallo > > > > This is my first post, so hallo to everyone. Im just a newbee with > python so I hope my msg will make some sense. J > > > > Is it possible to work with MP3 in python? yumex lists python-eyed3 python-mad as python packages that deal with mp3 files. eyed3 is geared towards tags (id3). mad appears to be closer to what you are looking for. I have no first hand experience with either. > > I?m looking for a library to modify MP3s (like fade in, fade out, > etc..). I know there are actually some libraries for doing this work > with .wav but I didn?t find one for working with MP3. I?m not sure but > should be something like -> http://effbot.org/librarybook/wave.htm . > Anyone? > > > > Thanks. > > > > Jo > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From mizzousundevil at gmail.com Tue Mar 21 17:17:36 2006 From: mizzousundevil at gmail.com (Matt Dempsey) Date: Tue, 21 Mar 2006 09:17:36 -0700 Subject: [Tutor] Struggling with writing results of loop into txt file Message-ID: <35ae985f0603210817i1464164bg91574ccae9679b89@mail.gmail.com> I'm using xmltramp to process some U.S. House of Rep. vote data. I can get it to print what I want but when I try to write it to a text file I had all sorts of problems. Can someone tell me what I'm doing wrong? I've done quite a bit of searching for the solution but as a novice to Python I'm at a loss. Here's the script: #votes data #import xmltramp for reading XML files import xmltramp #load up the house page with the vote I want d= xmltramp.load('http://clerk.house.gov/evs/2006/roll002.xml' ) #loads up the vote data off the site vd= d['vote-data'] #makes a happy nonhyphenated variable out of meta md= d['vote-metadata'] #counts the number of votes per roll votes= len(vd) #Produces the name, party and outcome of every Arizona house member on this vote for each in range(votes): st= str(vd[each].legislator('state')) vt= str(vd[each].vote) nm= (vd[each].legislator('unaccented-name')) pt= str(vd[each].legislator('party')) f= file('housevote.txt', 'w') if st == 'AZ': f.write(nm) else: pass f.close() Before trying to write it to a file, my loop looked like this: for each in range(votes): st= str(vd[each].legislator('state')) if st == 'AZ': print vd[each].legislator('unaccented-name'), vd[each].legislator('party'), vd[each].vote else: pass Any help would be most appreciated. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060321/07b35254/attachment.htm From kent37 at tds.net Tue Mar 21 17:50:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Mar 2006 11:50:15 -0500 Subject: [Tutor] Struggling with writing results of loop into txt file In-Reply-To: <35ae985f0603210817i1464164bg91574ccae9679b89@mail.gmail.com> References: <35ae985f0603210817i1464164bg91574ccae9679b89@mail.gmail.com> Message-ID: <44202EC7.5070500@tds.net> Matt Dempsey wrote: > I'm using xmltramp to process some U.S. House of Rep. vote data. I can > get it to print what I want but when I try to write it to a text file I > had all sorts of problems. Can someone tell me what I'm doing wrong? > > for each in range(votes): > st= str(vd[each].legislator('state')) > vt= str(vd[each].vote) > nm= (vd[each].legislator('unaccented-name')) > pt= str(vd[each].legislator('party')) > f= file('housevote.txt', 'w') > if st == 'AZ': > f.write(nm) > else: > pass > f.close() There are a couple of problems here. First, you are opening the file inside the loop. Each time you open the file it starts over, wiping out what was there before! So move the line f=file(...) to before the for statement. Second, you aren't putting any newlines into the file. f.write() will write just what you ask for - not like print which does some simple formatting for you. So you might try f.write(nm) f.write('\n') Another alternative is to use print-to-file. You can say print >>f, nm This works just like print as far as spaces and newlines, but output will go to f instead of std out. > > Before trying to write it to a file, my loop looked like this: > for each in range(votes): > st= str(vd[each].legislator('state')) > if st == 'AZ': > print vd[each].legislator('unaccented-name'), > vd[each].legislator('party'), vd[each].vote Of course your file-writing code doesn't include all this data. Kent From stvsmth at gmail.com Tue Mar 21 18:42:25 2006 From: stvsmth at gmail.com (stv) Date: Tue, 21 Mar 2006 12:42:25 -0500 Subject: [Tutor] Pythonic? Building a full path from a "visual" file tree Message-ID: <9493d0340603210942y25f3a551u78b2fff2cbdcce36@mail.gmail.com> Hey all, I would like to expand the "visual" representation of a tree hierarchy, given below, where child-ness is defined by indentation, and folder-ness is highlighted with a trailing '/' Input (test.txt): dir1/ file1 file2 1-1/ file3 file4 dir2/ file5 The desired output is a fully qualified path for each input line: dir1/ dir1/file1 dir1/file2 dir1/1-1/ dir1/1-1/file3 dir1/1-1/file4 dir2/ dir2/file5 I considered several brute-force solutions, but I persevered and came to, what I think, is a more Pythonic solution. What do you think? import string def expand_tree(filetree): indent = '\t' stack = [] for f in filetree: indents = f.count(indent) while len(stack) > indents: stack.pop() stack.append(f.strip()) yield string.join(stack,'') if not f.endswith('/'): stack.pop() lines = [line.rstrip() for line in file('test.txt')] for i in expand_tree(lines): print i Those familiar with subversion (particularly, svnlook tree /path/to/repos) may recognize the problem space and the sample input (except that I simplified things a bit here, using a tab to indicate level-of-hierarchy instead of a single space, which could appear in the filename). The real-world solution will use a regex to find run of spaces at the start of element 'f'. It will also get input from stdin instead of a file. Questions: Is the list comprehension the right idiom for getting a file into a list, without the EOL chars? I'm hard-pressed to see how it could be more concise, but this is Python :) and the rtrim() feels a little off. Is string.join() preferred to ''.join? Does importing all of string outweigh the readability of string.join()? Any subversion geeks know of way to eliminate this code with a native svn command? Did other folks choke on generators for as long as I did? I'm not going to admit, publicly, how long that was :) But I found this little test illustrative: def gen(): yield 1 yield 2 yield 3 g = gen() g.next() >>> 1 g.next() >>> 2 g.next() >>> 3 g.next() >>> [stack trace] Beyond simple, but the obviousness of it is hidden in many of the examples I saw. From dyoo at hkn.eecs.berkeley.edu Tue Mar 21 18:51:06 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 09:51:06 -0800 (PST) Subject: [Tutor] Python Control Flow Graph In-Reply-To: <Pine.LNX.4.63.0603210121160.14681@csegrad.ucsd.edu> Message-ID: <Pine.LNX.4.44.0603210947040.19962-100000@hkn.eecs.berkeley.edu> On Tue, 21 Mar 2006, Brian C. Lum wrote: > I have been looking for a good way to convert python code into a control > flow graph. [text cut] Hi Brian, I think you may want to ask your question to the pypy folks, since your question is a bit specialized. Check out pypy, which is an implemenation of Python in Python: http://codespeak.net/pypy/dist/pypy/doc/news.html They've developed tools that I think will be very helpful for you. For example, pypy's object spaces appear applicable here: http://codespeak.net/pypy/dist/pypy/doc/objspace.html#the-flow-model http://codespeak.net/pypy/dist/pypy/doc/objspace.html#introduction Best of wishes! From kent37 at tds.net Tue Mar 21 19:11:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Mar 2006 13:11:35 -0500 Subject: [Tutor] Pythonic? Building a full path from a "visual" file tree In-Reply-To: <9493d0340603210942y25f3a551u78b2fff2cbdcce36@mail.gmail.com> References: <9493d0340603210942y25f3a551u78b2fff2cbdcce36@mail.gmail.com> Message-ID: <442041D7.2060709@tds.net> stv wrote: > I considered several brute-force solutions, but I persevered and came > to, what I think, is a more Pythonic solution. What do you think? Looks pretty sweet to me :-) > > import string > > def expand_tree(filetree): > indent = '\t' > stack = [] > for f in filetree: > indents = f.count(indent) > while len(stack) > indents: stack.pop() > stack.append(f.strip()) > yield string.join(stack,'') > if not f.endswith('/'): stack.pop() > > lines = [line.rstrip() for line in file('test.txt')] > for i in expand_tree(lines): print i > > Questions: > > Is the list comprehension the right idiom for getting a file into a > list, without the EOL chars? I'm hard-pressed to see how it could be > more concise, but this is Python :) and the rtrim() feels a little > off. The list comp is fine but I don't think you need it at all, since you strip() the string before you add it to stack. > > Is string.join() preferred to ''.join? Does importing all of string > outweigh the readability of string.join()? string.join() is deprecated, ''.join() is preferred. Kent From alan.gauld at freenet.co.uk Tue Mar 21 20:06:08 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 21 Mar 2006 19:06:08 -0000 Subject: [Tutor] TKinter question References: <001c01c64cde$95e8f200$bd1a4e98@soton.ac.uk> Message-ID: <00b101c64d1a$83405e40$0b01a8c0@xp> > My code writes to a text file 'table.txt', and 'table.txt' is displayed in > the GUI. The user can generate new data at the click of a button > which re-writes 'table.txt', but I can only add the new table to the GUI > window rather than 'update' the existing one. class MoC: def __init__(self, master): frame = Frame(master, width=600, height=800, bd=1) frame.pack() you are not storing the widgets so they will be lost when you leave __init__. use self.frame, self.text etc so you can access them in other methods. #Text box frame text=Text(iframe5, height=10, width =70) fd = open('table.txt') #table.txt must be in the same folder lines = fd.read() fd.close() text.insert(END, lines) This putes the lines at the end of the text box. You want to use '1.0' as the position instead of END. Check the documentation on the Text widget in the Tkinter reference manual. #Command definitions def quit(self): root.destroy() def DisplayUpdate(self): #The command definition used to update the display. #Could I insert a line here to remove the existing frame/text box first? iframe5 = Frame(root, bd=2, relief=SUNKEN) text = Text(iframe5, height=10, width =70) This creates a new text widget rather than using the one created in init. If you use self.text in init you can reference thatv same widget here. fd = open('table.txt') lines = fd.read() fd.close() Since you do this in two places it might be worth making it a loadFile() method or similar? text.insert(END, lines) If you use '1.0' it should overwrite the old contents. However if the second is shorter you will get remnants so you might want to clear the contents too, look at the delete method and use a start of '1.0' and an end of END... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From stvsmth at gmail.com Tue Mar 21 21:20:07 2006 From: stvsmth at gmail.com (stv) Date: Tue, 21 Mar 2006 15:20:07 -0500 Subject: [Tutor] Pythonic? Building a full path from a "visual" file tree In-Reply-To: <442041D7.2060709@tds.net> References: <9493d0340603210942y25f3a551u78b2fff2cbdcce36@mail.gmail.com> <442041D7.2060709@tds.net> Message-ID: <9493d0340603211220t982aa6br562e3771b0403419@mail.gmail.com> > The list comp is fine but I don't think you need it > at all, since you strip() the string before you > add it to stack. Ahh yes. I used the rstrip() in development, printing intermediary output to stdout, so I could see what my input file-to-list looked like (and it looked ugly with all those EOLs). The strip() to the stack is there primarily to remove the indentation but, of course, it can do double duty. > > string.join() is deprecated, ''.join() is preferred. > Well, I'll live with it ;-) fugly as it looks. I'm really finding that Python nudges me into pleasant code. Doing the above in somthing like VB, I would just brute-force it and it would feel right. Brute forcing it in Python ... well, it just feels wrong ... Thanks for the input. From nospamformeSVP at gmail.com Tue Mar 21 21:13:01 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Tue, 21 Mar 2006 15:13:01 -0500 Subject: [Tutor] function signatures for callbacks Message-ID: <dvpmog$95e$1@sea.gmane.org> I have a piece of code that wants a callback from a client: The code looks like this right now: class pawprints: def __init__(self, callback_fun = None) ... at the client calling site I have something like this: def printme(modulename, codename, lineno, line): ... paws = pawprints(callback_fun = printme) ... My questions: 1) Is this the correct way to do this (the code does seem to work OK). 2) If so, then is there a way to specify the function signature at callback site rather than the client site? It seems backwards to me because because if I get the function definition wrong in the client site then I get a traceback to the callback site - which is meant to be an opaque library that the client should not have to know about. Thanks, Don. From dyoo at hkn.eecs.berkeley.edu Tue Mar 21 22:27:35 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 13:27:35 -0800 (PST) Subject: [Tutor] function signatures for callbacks In-Reply-To: <dvpmog$95e$1@sea.gmane.org> Message-ID: <Pine.LNX.4.44.0603211303010.26507-100000@hkn.eecs.berkeley.edu> > I have a piece of code that wants a callback from a client: > > The code looks like this right now: > > class pawprints: > def __init__(self, callback_fun = None) > ... > > > at the client calling site I have something like this: > > def printme(modulename, codename, lineno, line): > ... > > paws = pawprints(callback_fun = printme) > ... > > > My questions: > > 1) Is this the correct way to do this (the code does seem to work OK). Yes, the passing of printme to the pawprints() looks fine. > 2) If so, then is there a way to specify the function signature at > callback site rather than the client site? By "function signature", do you mean being able to properly check for weird inputs and outputs? If so, then a qualified Yes. One possible idea is to use a concept called "contracts": http://www.python.org/dev/peps/pep-0316/ The problem of providing good error messages for code that uses "higher-order function" callbacks is more difficult. I'm starting to learn about how this problem is handled by the Scheme community, and they do attack this problem head on: http://people.cs.uchicago.edu/~robby/pubs/papers/ho-contracts-icfp2002.pdf So this problem is known. I have not yet read through the PyProtocols documentation at: http://peak.telecommunity.com/PyProtocols.html and perhaps this handles callbacks in a clean way too, but on a quick glance, I don't see this yet. (That means I have to read more carefully! *grin*) So it's possible that the research being done in this area has yet to be fully absorbed into the APIs of more mainstream languages like Python. > It seems backwards to me because because if I get the function > definition wrong in the client site then I get a traceback to the > callback site - which is meant to be an opaque library that the client > should not have to know about. Yes, what you're asking makes sense: we want to "blame" the right party, and if it's the callback provider that messed up, we should only attribute them. (The same kind of problem happens in Tkinter, where bugs in callbacks end up exposing Tkinter internals.) Unfortunately, the stack traceback shows the entire stack trace at the point where bad things happen, so it does a little more than assign proper blame. The stack traceback is an imperfect mechanism for figuring out what went wrong. I don't know yet what the right solution is. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Tue Mar 21 22:44:22 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 13:44:22 -0800 (PST) Subject: [Tutor] function signatures for callbacks In-Reply-To: <Pine.LNX.4.44.0603211303010.26507-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0603211330100.26507-100000@hkn.eecs.berkeley.edu> > > It seems backwards to me because because if I get the function > > definition wrong in the client site then I get a traceback to the > > callback site - which is meant to be an opaque library that the client > > should not have to know about. > > Yes, what you're asking makes sense: we want to "blame" the right party, > and if it's the callback provider that messed up, we should only > attribute them. (The same kind of problem happens in Tkinter, where > bugs in callbacks end up exposing Tkinter internals.) Hi Don, As a quick-and-dirty hack, we can do a kind of wrapped exception handling to hide the internals of the system. Here's an example of this: ##################################################################### """A small example of attaching callbacks and wrapping exceptions.""" class CallbackError(Exception): pass class Announcer(object): def __init__(self): self.listeners = [] def add_listener(self, listener): self.listeners.append(listener) def shout(self, msg): try: self._internal_shout(msg) except Exception, e: raise CallbackError, str(e) def _internal_shout(self, msg): for l in self.listeners: l(msg) ##################################################################### Here's a small demonstration: ###### >>> announcer = Announcer() >>> def f1(x): ... print "f1 sees", x ... >>> def f2(x): ... 1 / 0 ... >>> announcer.add_listener(f1) >>> announcer.add_listener(f2) >>> announcer.shout("foo") f1 sees foo Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/tmp/python-213928MGH.py", line 16, in shout __main__.CallbackError: integer division or modulo by zero ###### The traceback we see here starts off at the entry point --- at shout() --- and because we're returning a new exception object at that point, we don't show that we were at _internal_shout(). If we look at the implementation of shout(): def shout(self, msg): try: self._internal_shout(msg) except Exception, e: raise CallbackError, str(e) then we can probably make this a little more sophisticated by properly extracting more information out of the original exception to make error debugging a little easier. However, if we're going to go through this sophisticated route, we'd better make extra sure not to discard useful debugging information. One thing that beginners will often do is something like: try: ... except: print "Something bad happened" which is just silly. *grin* There's a happy medium between error messages being too detailed and not detailed enough; I'd personally lean toward being too detailed at first, but maybe that's just me. I hope this helps! From mizzousundevil at gmail.com Wed Mar 22 00:05:09 2006 From: mizzousundevil at gmail.com (Matt Dempsey) Date: Tue, 21 Mar 2006 16:05:09 -0700 Subject: [Tutor] unicode issue? Message-ID: <35ae985f0603211505u2e036460g355a428c4ae1453@mail.gmail.com> I'm having a new problem with my House vote script. It's returning the following error: Traceback (most recent call last): File "C:/Python24/evenmorevotes", line 20, in -toplevel- f.write (nm+'*'+pt+'*'+vt+'*'+md['vote-result'][0]+'*'+md['vote-desc'][0]+'*'+'\n') UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 172: ordinal not in range(128) Here's the code: http://pastebin.com/615240 What am I doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060321/7922ccbb/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Mar 22 00:37:34 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 15:37:34 -0800 (PST) Subject: [Tutor] unicode issue? In-Reply-To: <35ae985f0603211505u2e036460g355a428c4ae1453@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603211525240.26991-100000@hkn.eecs.berkeley.edu> On Tue, 21 Mar 2006, Matt Dempsey wrote: > I'm having a new problem with my House vote script. It's returning the > following error: > > Traceback (most recent call last): > File "C:/Python24/evenmorevotes", line 20, in -toplevel- > f.write > (nm+'*'+pt+'*'+vt+'*'+md['vote-result'][0]+'*'+md['vote-desc'][0]+'*'+'\n') > UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in > position 172: ordinal not in range(128) Hi Matt, Just wondering: how familiar are you with Unicode? What's going on is that one of the strings in the string concatenation above contains a Unicode string. It's like an infection: anything that touches Unicode turns Unicode. *grin* ###### >>> 'hello' + u'world' u'helloworld' ###### This has repercussions: when we're writing these strings back to files, because we have a Unicode string, we must now be more explicit about how Unicode is written, since files are really full of bytes, not unicode characters. That is, we need to specify an "encoding". 'utf-8' is a popular encoding that turns Unicode reliably into a bunch of bytes: ###### >>> u'\u201c'.encode('utf8') '\xe2\x80\x9c' ###### and this can be written to a file. Recovering Unicode from bytes can be done by going the other way, by "decoding": ###### >>> '\xe2\x80\x9c'.decode("utf8") u'\u201c' ###### The codecs.open() function in the Standard Library is useful for handling this encode/decode thing so that all we need to do is concentrate on Unicode: http://www.python.org/doc/lib/module-codecs.html#l2h-991 For example: ###### >>> import codecs >>> >>> f = codecs.open("foo.txt", "wb", "utf8") >>> f.write(u'\u201c') >>> f.close() >>> >>> open('foo.txt', 'rb').read() '\xe2\x80\x9c' >>> >>> codecs.open("foo.txt", "rb", "utf-8").read() u'\u201c' ###### We can see that if we read and write to a codec-opened file, it'll transparently do the encoding/decoding step for us as we write() and read() the file. You may also find Joel Spolsky's post on "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode And Character Sets (No Excuses!) useful in clarifying the basic concepts of Unicode: http://www.joelonsoftware.com/articles/Unicode.html I hope this helps! From stvsmth at gmail.com Wed Mar 22 00:44:10 2006 From: stvsmth at gmail.com (stv) Date: Tue, 21 Mar 2006 18:44:10 -0500 Subject: [Tutor] Pythonic? Building a full path from a "visual" file tree In-Reply-To: <9493d0340603210942y25f3a551u78b2fff2cbdcce36@mail.gmail.com> References: <9493d0340603210942y25f3a551u78b2fff2cbdcce36@mail.gmail.com> Message-ID: <9493d0340603211544y4dc52a61q9f70653f199d5dfb@mail.gmail.com> On 3/21/06, stv <stvsmth at gmail.com> wrote: > > import string > > def expand_tree(filetree): > indent = '\t' > stack = [] > for f in filetree: > indents = f.count(indent) > while len(stack) > indents: stack.pop() > stack.append(f.strip()) > yield string.join(stack,'') > if not f.endswith('/'): stack.pop() > The real-world solution will use a regex to find run > of spaces at the start of element 'f'. Hmmm, I'm having to rethink this ... regex will probably not do what I want (count instance of "indent" ... or, even if regex will do, there's probably a cleaner solution without it. Given the subversion problem space (where I can count on 1 space for each level of child-ness), are there cleaner solutions than this: indents = len(f) - len(f.lstrip()) From dyoo at hkn.eecs.berkeley.edu Wed Mar 22 01:41:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 16:41:29 -0800 (PST) Subject: [Tutor] unicode issue? (fwd) Message-ID: <Pine.LNX.4.44.0603211634350.12450-100000@hkn.eecs.berkeley.edu> > A friend of mine showed me where the unicode is showing up but we still > can't get script to work right. We tried encoding the appropriate > variable but it still is spitting back the error. Would I just have: > u'\u201c'.encode('utf8') in my script or should it be > md['vote-desc'][0].encode('utf8') [Keeping tutor in CC. Please do not send replies only to me; you need to give other people on Tutor the opportunity to answer as well. Hi Matt, I should clarify: when I said: > What's going on is that one of the strings in the string concatenation > above contains a Unicode string. I was a bit imprecise. What I should really have said was: What's going on is that at least one --- there could be more! --- strings in the string concatenation contains a Unicode string. I'm positive you have more than one Unicode string in there. *grin* Rather than hunt-and-peck for all the places where Unicode is coming from, it's probably a better approach to just wholesale encode() the whole string after you do the concatenation and before passing it off to write(). Alternative, take a close look at the codecs example I showed before near the bottom of the last message: it handles encoding and decoding for you. Using the codecs module is probably the better approach here, since otherwise you have to look at every file write(), and that can be a bit tiring. From keosophon at khmeros.info Wed Mar 22 02:27:37 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 22 Mar 2006 08:27:37 +0700 Subject: [Tutor] how to get a line text from input file. Message-ID: <200603220827.37194.keosophon@khmeros.info> Hi all, i am new to programming language and python. I wonder how to get a line text from input file. Thanks, sophon From keosophon at khmeros.info Wed Mar 22 02:36:02 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 22 Mar 2006 08:36:02 +0700 Subject: [Tutor] how to set a value to a block of memory Message-ID: <200603220836.02972.keosophon@khmeros.info> Hi all, How can i set a value to a bytes of block of memory. In C, i think they use memset like this. Thanks, Sophon From billburns at pennswoods.net Wed Mar 22 03:35:15 2006 From: billburns at pennswoods.net (Bill Burns) Date: Tue, 21 Mar 2006 21:35:15 -0500 Subject: [Tutor] Python & MP3 In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAO3frLa9jTtGmo8jK/xV58rCgAAAEAAAAE41ySYcJOpLr58hoyzt3EYBAAAAAA==@tiscali.it> References: <!&!AAAAAAAAAAAYAAAAAAAAAO3frLa9jTtGmo8jK/xV58rCgAAAEAAAAE41ySYcJOpLr58hoyzt3EYBAAAAAA==@tiscali.it> Message-ID: <4420B7E3.7060807@pennswoods.net> Johanna wrote: > Hallo > > > > This is my first post, so hallo to everyone. Im just a newbee with > python so I hope my msg will make some sense. J > > > > Is it possible to work with MP3 in python? > > I?m looking for a library to modify MP3s (like fade in, fade out, > etc..). I know there are actually some libraries for doing this work > with .wav but I didn?t find one for working with MP3. I?m not sure but > should be something like -> http://effbot.org/librarybook/wave.htm . Anyone? > > You may want to have a look at PyMedia: http://www.pymedia.org/ HTH, Bill From kent37 at tds.net Wed Mar 22 04:17:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Mar 2006 22:17:34 -0500 Subject: [Tutor] how to set a value to a block of memory In-Reply-To: <200603220836.02972.keosophon@khmeros.info> References: <200603220836.02972.keosophon@khmeros.info> Message-ID: <4420C1CE.7050200@tds.net> Keo Sophon wrote: > Hi all, > > How can i set a value to a bytes of block of memory. In C, i think they use > memset like this. Python does not support direct access to memory, you will need to use another language or maybe a C extension to Python to do this. Kent From kent37 at tds.net Wed Mar 22 04:20:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Mar 2006 22:20:06 -0500 Subject: [Tutor] how to get a line text from input file. In-Reply-To: <200603220827.37194.keosophon@khmeros.info> References: <200603220827.37194.keosophon@khmeros.info> Message-ID: <4420C266.6090106@tds.net> Keo Sophon wrote: > Hi all, > > i am new to programming language and python. I wonder how to get a line text > from input file. The simplest Python idiom to do something with each line of a file is this: for line in open('somefile.txt'): # do something with line You can find out more here: http://docs.python.org/tut/node9.html#SECTION009200000000000000000 Kent From gsf at panix.com Wed Mar 22 06:17:13 2006 From: gsf at panix.com (Gabriel S Farrell) Date: Wed, 22 Mar 2006 00:17:13 -0500 Subject: [Tutor] Python & MP3 In-Reply-To: <4420B7E3.7060807@pennswoods.net> References: <!&!AAAAAAAAAAAYAAAAAAAAAO3frLa9jTtGmo8jK/xV58rCgAAAEAAAAE41ySYcJOpLr58hoyzt3EYBAAAAAA==@tiscali.it> <4420B7E3.7060807@pennswoods.net> Message-ID: <20060322051713.GJ1989@panix.com> On Tue, Mar 21, 2006 at 09:35:15PM -0500, Bill Burns wrote: > Johanna wrote: > > Is it possible to work with MP3 in python? > > > > I?m looking for a library to modify MP3s (like fade in, fade out, > > etc..). > > You may want to have a look at PyMedia: > > http://www.pymedia.org/ I agree with Bill, pymedia looks like the closest thing to what you're after. There's also pyxmms (python-xmms in Debian) if you don't mind going through xmms. pygame might do the trick, also (check out http://www.pygame.org/docs/ref/music.html). gsf From dyoo at hkn.eecs.berkeley.edu Wed Mar 22 06:31:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 21:31:52 -0800 (PST) Subject: [Tutor] how to get a line text from input file. In-Reply-To: <200603220827.37194.keosophon@khmeros.info> Message-ID: <Pine.LNX.4.44.0603212129320.1666-100000@hkn.eecs.berkeley.edu> On Wed, 22 Mar 2006, Keo Sophon wrote: > i am new to programming language and python. I wonder how to get a line > text from input file. Hi Sophon, You may want to look at: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Many of the tutorials there talk about reading from files, including Alan Gauld's "How to Program": http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm How are you learning how to program? Is there a particular tutorial that you're reading from? From dyoo at hkn.eecs.berkeley.edu Wed Mar 22 06:54:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 21:54:31 -0800 (PST) Subject: [Tutor] how to set a value to a block of memory In-Reply-To: <4420C1CE.7050200@tds.net> Message-ID: <Pine.LNX.4.44.0603212132030.1666-100000@hkn.eecs.berkeley.edu> On Tue, 21 Mar 2006, Kent Johnson wrote: > > How can i set a value to a bytes of block of memory. In C, i think > > they use memset like this. Hi Sophon, Secondary question: why are you trying to do this? Are you trying to represent a collection or "array" of things? Some concepts in C aren't well represented in Python because they only make sense from a low-level hardware perspective. For example, asking for an equivalent for C's malloc() or free() functions is "nonsensical" in the sense that, since Python is garbage collected, it provides no such functions to the casual Python user. (Such functions ARE available through third-party modules such as SWIG, but unless you are really trying to integrate with a C library, you don't need this.) As an extended example: C programmers often use malloc() to dynamically build structures, such as linked lists: /**********************************************************/ /*** C Code **/ #include <stdio.h> #include <stdlib.h> struct IntList { int first; struct IntList *rest; }; struct IntList* construct(int head, struct IntList* rest) { struct IntList* newlist; newlist = malloc(sizeof(struct IntList)); newlist->first = head; newlist->rest = rest; return newlist; } void printList(struct IntList* list) { while (list != NULL) { printf("%d\n", list->first); list = list->rest; } } int main() { struct IntList *mylist = NULL; mylist = construct(5, mylist); mylist = construct(1, mylist); mylist = construct(4, mylist); mylist = construct(1, mylist); mylist = construct(3, mylist); printList(mylist); return 0; } /**********************************************************/ But in Python, we can do this structure building without explicitely malloc()ing. The code above has a possible "translation" which looks like: ############################################ ## Python Code ## import sys class LinkedList: def __init__(self, first, rest): self.first, self.rest = first, rest def printList(list): while list != None: print list.first list = list.rest def main(): mylist = None mylist = LinkedList(5, mylist) mylist = LinkedList(1, mylist) mylist = LinkedList(4, mylist) mylist = LinkedList(1, mylist) mylist = LinkedList(3, mylist) printList(mylist) sys.exit(0) if __name__ == '__main__': main() ############################################ where most of the low-level details of allocating memory are all handled by the Python runtime. So rather than ask for direct equivalents to C, it might help to ask about what you're trying to do. We'll do what we can to help translate between C concepts and Python concepts, and for the most part, what you already know will have close analogues. But some concepts will require a bit of tweaking. Good luck! From dyoo at hkn.eecs.berkeley.edu Wed Mar 22 06:58:23 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 21:58:23 -0800 (PST) Subject: [Tutor] how to set a value to a block of memory In-Reply-To: <Pine.LNX.4.44.0603212132030.1666-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0603212156440.1666-100000@hkn.eecs.berkeley.edu> > On Tue, 21 Mar 2006, Kent Johnson wrote: ^^^^^^^^^^^^ > > > How can i set a value to a bytes of block of memory. In C, i think > > > they use memset like this. Whoops, sorry about that Kent! I completely messed up the attribution when cutting-and-pasting. From kaushalshriyan at gmail.com Wed Mar 22 07:41:48 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 22 Mar 2006 12:11:48 +0530 Subject: [Tutor] Hi Message-ID: <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26@mail.gmail.com> Hi I am new to python and I am going through the URL http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment I am going through the Chapter 7 Strings, I am stuck with understanding slice which is a part of a String, I am not able to understand how it functions Awaiting your earnest reply Thanks in Advance Regards Kaushal From dyoo at hkn.eecs.berkeley.edu Wed Mar 22 08:04:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 21 Mar 2006 23:04:36 -0800 (PST) Subject: [Tutor] Hi In-Reply-To: <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603212300200.25864-100000@hkn.eecs.berkeley.edu> > I am new to python and I am going through the URL > http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment I am going > through the Chapter 7 Strings, I am stuck with understanding slice which > is a part of a String, I am not able to understand how it functions Hello, A "slice" takes a string and returns a "substring" of that string. For example, if we have a string like: ###### >>> mystring = "supercalifragilisticexpialidocious" ###### then we can select different portions of the string by indicating the start and end positions. For example, the first ten characters of mystring can be extracted using a slice: ###### >>> mystring[0:10] 'supercalif' ###### Is this what you are confused about? Please give us more details on where you're getting stuck, and we will do what we can to help clarify. Please continue to reply to 'python-help at python.org': do not email me directly. Although I may not personally have the time to answer, I'm sure at least one of the other helpers on the list do, so by continuing the conversation on python-help, we'll be able to guarantee that your questions are not lost. From kaushalshriyan at gmail.com Wed Mar 22 08:14:51 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 22 Mar 2006 12:44:51 +0530 Subject: [Tutor] Hi In-Reply-To: <Pine.LNX.4.44.0603212300200.25864-100000@hkn.eecs.berkeley.edu> References: <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26@mail.gmail.com> <Pine.LNX.4.44.0603212300200.25864-100000@hkn.eecs.berkeley.edu> Message-ID: <6b16fb4c0603212314n73ef102an492b330907e7cfcf@mail.gmail.com> On 3/22/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > > I am new to python and I am going through the URL > > http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment I am going > > through the Chapter 7 Strings, I am stuck with understanding slice which > > is a part of a String, I am not able to understand how it functions > > Hello, > > > A "slice" takes a string and returns a "substring" of that string. For > example, if we have a string like: > > ###### > >>> mystring = "supercalifragilisticexpialidocious" > ###### > > then we can select different portions of the string by indicating the > start and end positions. For example, the first ten characters of > mystring can be extracted using a slice: > > ###### > >>> mystring[0:10] > 'supercalif' > ###### > > > Is this what you are confused about? > > Please give us more details on where you're getting stuck, and we will do > what we can to help clarify. > > > Please continue to reply to 'python-help at python.org': do not email me > directly. Although I may not personally have the time to answer, I'm sure > at least one of the other helpers on the list do, so by continuing the > conversation on python-help, we'll be able to guarantee that your > questions are not lost. > > Thanks Danny Yoo I got this, Lets say if its mystring[n:m] where n may be another number and m may be another number so how will it work in that case, so this becomes general and makes more clear Lets say if its mystring[3:8] so how will i evaluate it Thanks for all the help Regards Kaushal From noufal at nibrahim.net.in Wed Mar 22 08:42:27 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 22 Mar 2006 13:12:27 +0530 (IST) Subject: [Tutor] Hi In-Reply-To: <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26@mail.gmail.com> References: <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26@mail.gmail.com> Message-ID: <24954.203.145.176.76.1143013347.squirrel@members.hcoop.net> On Wed, March 22, 2006 12:11 pm, Kaushal Shriyan wrote: > Hi > > I am new to python and I am going through the URL > http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment > I am going through the Chapter 7 Strings, I am stuck with understanding > slice which is a part of a String, I am not able to understand how it > functions Can you be a bit more specific? String slices are copies of pieces of strings. As for the values of indices, take a look at http://nibrahim.net.in/slice.png It's something I tried to use during a presentation at my workplace. You create something like that by doing foo = "corrupt" Then the indices are as per the diagram. If you say foo[0], you'll get back "c". foo[1] will give you "o" etc. It helps to think of the indices as pointing to in between the letters. Not to the letters themselves. Now, try something like foo[1:3], you'll get back "or" and if you refer the diagram, it's fairly straightforward why (slice starts at position 1 and ends at position 3. Everything in between is displayed). foo [:3] is the same as saying foo[0:3]. foo[3:] is similar. Negative indices start from the position shown. There's a bit of asymmetry here since foo[0] refers to the first element of the string but foo[-1] refers to the last one. You'll get used to it once you get used to the idea of indices pointing to in between the elements though. Another thing you should understand (python experts, please correct me if I'm wrong) is that the slice operator actually creates a new string and doesn't return a piece of the existing string. So, when you say foo[:], you'll get a string that's a copy of the original one. Please let me know if I can help you out with this anymore. -- -NI From SChitti at manh.com Wed Mar 22 08:47:21 2006 From: SChitti at manh.com (Suri Chitti) Date: Wed, 22 Mar 2006 13:17:21 +0530 Subject: [Tutor] Hi Message-ID: <D4A26A6CCC277248B302754076D9053C105996@ma-india11.asia.manh.com> It would be "ercal". The first number n denotes the position where we start. The first position is always zero. So 3 would be the letter at the 4th position which is e. The second number is I guess what confused you. m denotes where we end, counted the same way but by having 1 for the first position. 8 in your case would then be l (8th actual position). Try this mystring[3:4] to understand the working -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kaushal Shriyan Sent: Wednesday, March 22, 2006 12:45 PM To: tutor at python.org Cc: Danny Yoo Subject: Re: [Tutor] Hi On 3/22/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > > I am new to python and I am going through the URL > > http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment I am going > > through the Chapter 7 Strings, I am stuck with understanding slice which > > is a part of a String, I am not able to understand how it functions > > Hello, > > > A "slice" takes a string and returns a "substring" of that string. For > example, if we have a string like: > > ###### > >>> mystring = "supercalifragilisticexpialidocious" > ###### > > then we can select different portions of the string by indicating the > start and end positions. For example, the first ten characters of > mystring can be extracted using a slice: > > ###### > >>> mystring[0:10] > 'supercalif' > ###### > > > Is this what you are confused about? > > Please give us more details on where you're getting stuck, and we will do > what we can to help clarify. > > > Please continue to reply to 'python-help at python.org': do not email me > directly. Although I may not personally have the time to answer, I'm sure > at least one of the other helpers on the list do, so by continuing the > conversation on python-help, we'll be able to guarantee that your > questions are not lost. > > Thanks Danny Yoo I got this, Lets say if its mystring[n:m] where n may be another number and m may be another number so how will it work in that case, so this becomes general and makes more clear Lets say if its mystring[3:8] so how will i evaluate it Thanks for all the help Regards Kaushal _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From keosophon at khmeros.info Wed Mar 22 09:01:05 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 22 Mar 2006 15:01:05 +0700 Subject: [Tutor] Tutor Digest, Vol 25, Issue 54 In-Reply-To: <mailman.11797.1143011693.27774.tutor@python.org> References: <mailman.11797.1143011693.27774.tutor@python.org> Message-ID: <200603221501.05504.keosophon@khmeros.info> On Wednesday 22 March 2006 14:14, tutor-request at python.org wrote: > Hi Sophon, > > You may want to look at: > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Many of the tutorials there talk about reading from files, including Alan > Gauld's "How to Program": > > http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm > > How are you learning how to program? Is there a particular tutorial that > you're reading from? i am reading from a python document in SuSE 10.1. Phon From keosophon at khmeros.info Wed Mar 22 09:16:21 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 22 Mar 2006 15:16:21 +0700 Subject: [Tutor] Tutor Digest, Vol 25, Issue 54 In-Reply-To: <mailman.11797.1143011693.27774.tutor@python.org> References: <mailman.11797.1143011693.27774.tutor@python.org> Message-ID: <200603221516.21752.keosophon@khmeros.info> On Wednesday 22 March 2006 14:14, tutor-request at python.org wrote: > Hi Sophon, > > Secondary question: why are you trying to do this? Are you trying to > represent a collection or "array" of things? i am trying to port a program written in C to python language. The program is reading a plain text file that uses legacy font then converting it to a unicode font file. I don't have any experience with programming besides just knowing C a little bit and just learning python in 3 days ago. Anyway, how can i declare a global variable and assign a value to it in a function? Thanks Sophon From alan.gauld at freenet.co.uk Wed Mar 22 09:30:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 22 Mar 2006 08:30:15 -0000 Subject: [Tutor] how to get a line text from input file. References: <200603220827.37194.keosophon@khmeros.info> Message-ID: <00da01c64d8a$d8536f10$0b01a8c0@xp> > i am new to programming language and python. I wonder how to get a line > text > from input file. f = open('somefile.txt') line = f.readline() For more details on using files see the Handling Files topic in my web tutor. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Mar 22 09:32:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 22 Mar 2006 08:32:58 -0000 Subject: [Tutor] how to set a value to a block of memory References: <200603220836.02972.keosophon@khmeros.info> Message-ID: <00de01c64d8b$398b2110$0b01a8c0@xp> > How can i set a value to a bytes of block of memory. In C, i think they > use > memset like this. Python is a high level programming language and does not support direct memory access in the way that C does. Can you explain why you think you need to do this? Is it essential to access a specific memory location or do you simply want to fill a data table with values? If the latter then Python can help if you need direct memory access you will need to use C I think.. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Mar 22 09:39:14 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 22 Mar 2006 08:39:14 -0000 Subject: [Tutor] Hi References: <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26@mail.gmail.com><Pine.LNX.4.44.0603212300200.25864-100000@hkn.eecs.berkeley.edu> <6b16fb4c0603212314n73ef102an492b330907e7cfcf@mail.gmail.com> Message-ID: <00f401c64d8c$19b48920$0b01a8c0@xp> > I got this, Lets say if its mystring[n:m] where n may be another > number and m may be another number so how will it work in that case, > so this becomes general and makes more clear > n is the index of the first character and m is the index *beyond* the last character > Lets say if its mystring[3:8] so how will i evaluate it It will return the characters at indexes 3,4,5,6, and 7. In other words it operates in the same way as the range function. you could get the same set of characters back using for index in range(n,m): print mystring[index] Does that help? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kaushalshriyan at gmail.com Wed Mar 22 09:55:55 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 22 Mar 2006 14:25:55 +0530 Subject: [Tutor] Hi In-Reply-To: <00f401c64d8c$19b48920$0b01a8c0@xp> References: <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26@mail.gmail.com> <Pine.LNX.4.44.0603212300200.25864-100000@hkn.eecs.berkeley.edu> <6b16fb4c0603212314n73ef102an492b330907e7cfcf@mail.gmail.com> <00f401c64d8c$19b48920$0b01a8c0@xp> Message-ID: <6b16fb4c0603220055p1ec745c5t8d7bf58f94f96301@mail.gmail.com> On 3/22/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote: > > I got this, Lets say if its mystring[n:m] where n may be another > > number and m may be another number so how will it work in that case, > > so this becomes general and makes more clear > > > n is the index of the first character and m is the index *beyond* > the last character > > > Lets say if its mystring[3:8] so how will i evaluate it > > It will return the characters at indexes 3,4,5,6, and 7. > > In other words it operates in the same way as the range > function. > > you could get the same set of characters back using > > for index in range(n,m): > print mystring[index] > > Does that help? > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > Thanks a Lot for all the help, Its excellent and too good Appreciate all of you for making me clear and better in understanding. Regards Kaushal From kent37 at tds.net Wed Mar 22 11:57:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Mar 2006 05:57:33 -0500 Subject: [Tutor] Tutor Digest, Vol 25, Issue 54 In-Reply-To: <200603221516.21752.keosophon@khmeros.info> References: <mailman.11797.1143011693.27774.tutor@python.org> <200603221516.21752.keosophon@khmeros.info> Message-ID: <44212D9D.6040907@tds.net> Keo Sophon wrote: > Anyway, how can i declare a global variable and assign a value to it in a > function? The usual way to do this is to return a value from the function and assign it to the variable. For example: def double(x): return x*2 x=2 doublex = double(x) You really should look at one of the beginners tutorials listed here, they will answer many of your questions: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From alan.gauld at freenet.co.uk Wed Mar 22 16:57:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 22 Mar 2006 15:57:30 -0000 Subject: [Tutor] Hi References: <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26@mail.gmail.com> <24954.203.145.176.76.1143013347.squirrel@members.hcoop.net> Message-ID: <010701c64dc9$539385a0$0b01a8c0@xp> > It helps to think of the indices as pointing to in between the letters. > Not to the letters themselves. Like so, where '|' represents the mark: 'corrupt'[0:] -> '|corrupt' 'corrupt'[1:] -> 'c|orrupt' So an index of 1 moves the mark one place up. > Negative indices start from the position shown. There's a bit of asymmetry > here since foo[0] refers to the first element of the string but foo[-1] > refers to the last one. If you take both of your comments above you'll see that its quite consistent. -1 moves the marker back one place from the end to between the 2nd last and last chars. (it also helps to think of the sequence as circular so that zero is between the first and last characters!) So, 'corrupt'[-1:] -> 'corrup|t' returns from the -1 position to the end of the string - which is 't'. -2 moves the mark back 2 places and so on, so the idea of a mark between the characters is consistent with both forward and negative indexing. > I'm wrong) is that the slice operator actually creates a new string and > doesn't return a piece of the existing string. Correct and is the canonical way to shallow copy a sequence Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Mar 22 17:04:36 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 22 Mar 2006 16:04:36 -0000 Subject: [Tutor] Tutor Digest, Vol 25, Issue 54 References: <mailman.11797.1143011693.27774.tutor@python.org> <200603221516.21752.keosophon@khmeros.info> Message-ID: <010f01c64dca$51690f10$0b01a8c0@xp> > Anyway, how can i declare a global variable and assign a value to it in a > function? Variables in Python are only global in the sense of a file. You cannot declare a global that spans multiple files. However you can import a variable reference from one file to another. This is "A Good Thing(TM)" since it avoids most of the evils of global variables. You can assign to a global variable from within a function by telling the function to use the global name: x = 42 def f(): global x # say use the external variable called x x = 27 f() # actually assigns the value But that's bad practice in most cases and its better to pass the variable in as an argument and return the new value: def g(n): n = 27 return n x = g(x) # same effect as calling f() above You can read more anbout this in my tutorial topic "What's in a Name?" (And more about functions and modules in the "Modules & Functions" topic) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From francois.schnell at gmail.com Wed Mar 22 17:41:14 2006 From: francois.schnell at gmail.com (francois schnell) Date: Wed, 22 Mar 2006 17:41:14 +0100 Subject: [Tutor] Simple way for i18n ? Message-ID: <13a83ca10603220841q4412dff0j@mail.gmail.com> Hello all, I wish to translate a Python script from English to French. I've read the offical documentation (python.org doc) but I must admit that I'm lost now ... I've found some simple explanations here but I can't make it work: http://karrigell.sourceforge.net/en/internationalization.htm Here's where I'm stuck: Let's imagine my app is: myapp.py -- import gettext _ = gettext.gettext print _("hello friends") print _("Bye Bye") --- Here are my folders on a windows box: C:\myappfolder\ -----------------------\Translations\francais\LC_MESSAGES My myapp.py is in myappfolder In this folder I've used pygettext.py to produce a messages.pot file => I add the translation in it => I have a messages.po file. I then used msgfmt.py to produce messages.mo file. I then copied messages.po and messages.mo in LC_MESSAGES folder C:\myappfolder\ -----------------------\Translations\francais\LC_MESSAGES I now come back to myapp.py and add two lines: --- import gettext _ = gettext.gettext t=gettext.translation("messages","c:\myappfolder\Translations","francais") t.install() print _("hello friends") print _("Bye Bye") --- When I do that Python anwers: >>> Traceback (most recent call last): File "C:\myappfolder\myapp.py", line 4, in ? t=gettext.translation ("messages","c:\myappfolder\Translations","francais") File "C:\Python24\lib\gettext.py", line 456, in translation raise IOError(ENOENT, 'No translation file found for domain', domain) IOError: [Errno 2] No translation file found for domain: 'messages' >>> I'm stuck here. I understand it doesn't find the translation file but I can't figure out why. Can you tell me what I'm doing wrong or direct me to an URL (or a Python book) where simple internationalisation for Python is gently explained Thanks francois (...from France) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060322/87f77031/attachment.html From andre.roberge at gmail.com Wed Mar 22 18:02:30 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 22 Mar 2006 13:02:30 -0400 Subject: [Tutor] Simple way for i18n ? In-Reply-To: <13a83ca10603220841q4412dff0j@mail.gmail.com> References: <13a83ca10603220841q4412dff0j@mail.gmail.com> Message-ID: <7528bcdd0603220902g449be7f2sebaf52590a94841d@mail.gmail.com> On 3/22/06, francois schnell <francois.schnell at gmail.com> wrote: > > Hello all, > > I wish to translate a Python script from English to French. I've read the > offical documentation (python.org doc) but I must admit that I'm lost now > ... > I've found some simple explanations here but I can't make it work: > http://karrigell.sourceforge.net/en/internationalization.htm > > Here's where I'm stuck: > > Let's imagine my app is: myapp.py > -- > import gettext > _ = gettext.gettext > > print _("hello friends") > print _("Bye Bye") > --- > > Here are my folders on a windows box: > > C:\myappfolder\ > -----------------------\Translations\francais\LC_MESSAGES > > My myapp.py is in myappfolder > > In this folder I've used pygettext.py to produce a messages.pot file => I > add the translation in it => I have a messages.po file. > I then used msgfmt.py to produce messages.mo file. > > I then copied messages.po and messages.mo in LC_MESSAGES folder > C:\myappfolder\ > -----------------------\Translations\francais\LC_MESSAGES > > I now come back to myapp.py and add two lines: > > --- > import gettext > _ = gettext.gettext > > t=gettext.translation("messages","c:\myappfolder\Translations","francais") > t.install() > > print _("hello friends") > print _("Bye Bye") > --- > > When I do that Python anwers: > > >>> > Traceback (most recent call last): > File "C:\myappfolder\myapp.py", line 4, in ? > > t=gettext.translation("messages","c:\myappfolder\Translations","francais") > File "C:\Python24\lib\gettext.py", line 456, in translation > raise IOError(ENOENT, 'No translation file found for domain', domain) > IOError: [Errno 2] No translation file found for domain: 'messages' > >>> > > I'm stuck here. > I understand it doesn't find the translation file but I can't figure out > why. I've always seen "standard directory structures" (e.g. \locales\fr, etc.) rather than custom ones as above, so I can't comment for sure ... but: try to either write r"c:\myappfolder\Translations" or "c:\\myappfolder\\Translations" to avoid possible backslash problems... Bonne chance! Andr? > > Can you tell me what I'm doing wrong or direct me to an URL (or a Python > book) where simple internationalisation for Python is gently explained > > Thanks > francois (...from France) > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From beamer30 at gmail.com Thu Mar 23 02:45:35 2006 From: beamer30 at gmail.com (Tom Bachik) Date: Wed, 22 Mar 2006 17:45:35 -0800 Subject: [Tutor] i need help please read Message-ID: <4ce40aaa0603221745h38952e47xfc9a7cd73fa8f5f4@mail.gmail.com> ok does anyone know how to righ a script were a box pops up then if it goes over a number on the screen it pops up in the box become the input number so you can alter the number that popped up in the box? if you do can you right it and send it to me and if you cant doit all but know how i can do part will you please help me do it but remeber im new so i dont know to much -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060322/79963f74/attachment.html From patriciap.gu at gmail.com Thu Mar 23 02:54:00 2006 From: patriciap.gu at gmail.com (Patty) Date: Thu, 23 Mar 2006 01:54:00 +0000 (UTC) Subject: [Tutor] =?utf-8?q?html_and_mod=5Fpython?= Message-ID: <loom.20060323T023022-647@post.gmane.org> Hi! I created a form in a python file that takes values selected from 6 different drop down boxes: for target in all_targets: s = s + "<form action='process_info' method='POST'>" s = s + "<input type='hidden' name='tg' value=%s>" % target s = s + "<tr><td></td>" for host in hosts: if target in ants_map[host]: s = s + printbox() else: s = s + printemptybox() s = s + """<td><input type='submit' value='Submit'></td></tr>""" s = s + "</form>" My printbox method contains the following: def printbox(): tag = """ <select name="percent"> <option VALUE="-">-</option> <option VALUE="0">0%</option> <option VALUE="10">10%</option> <option VALUE="20">20%</option> <option VALUE="30">30%</option> <option VALUE="40">40%</option> <option VALUE="50">50%</option> <option VALUE="60">60%</option> <option VALUE="70">70%</option> <option VALUE="80">80%</option> <option VALUE="90">90%</option> <option VALUE="100">100%</option> </select>""" return tag When the values are entered, my program stores them into a database. Everything worked well, but now I have been asked to retain the values selected in the drop down boxes. This means that when I open the web page, the drop down boxes should display the recent values entered. I'm not sure how to do it, and I'm really hoping that someone can point me to the right direction. Thanks, Patty From srini_iyyer_bio at yahoo.com Thu Mar 23 04:09:01 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 22 Mar 2006 19:09:01 -0800 (PST) Subject: [Tutor] efficient method to search between two lists Message-ID: <20060323030901.68201.qmail@web38104.mail.mud.yahoo.com> Dear group, I have a question for solving a problem in more simplistic and efficient way. I have two lists: list_a = ['S83513\tNM_001117', 'X60435\tNM_001117', 'U75370\tNM_005035', 'U05861\tNM_001353', 'S68290\tNM_001353', 'D86864\tNM_145349', 'D86864\tNM_003693', 'D86864\tNM_145351', 'D63483\tNM_145349', 'D63483\tNM_003693', 'D63483\tNM_145351', 'S66427\tNM_002892', 'S57153\tNM_002892'] list_b = ['HC_G110\t1000_at\tS83513', 'HC_G110\t1001_at\tD63483', 'HC_G110\t1002_f_at\tD86864', 'HC_G112\t1003_s_at\tX60435', 'HC_G112\t1004_at\tS57153'] >>> for x in list_b: ... cola = x.split('\t')[2] ... for m in list_a: ... colb = m.split('\t')[0] ... if cola == colb: ... print x+'\t'+m ... HC_G110 1000_at S83513 S83513 NM_001117 HC_G110 1001_at D63483 D63483 NM_145349 HC_G110 1001_at D63483 D63483 NM_003693 HC_G110 1001_at D63483 D63483 NM_145351 HC_G110 1002_f_at D86864 D86864 NM_145349 HC_G110 1002_f_at D86864 D86864 NM_003693 HC_G110 1002_f_at D86864 D86864 NM_145351 HC_G112 1003_s_at X60435 X60435 NM_001117 HC_G112 1004_at S57153 S57153 NM_002892 method b: for m in list_b: cols = m.split('\t')[2] for x in list_a: if x.startswith(cols): print m+'\t'+x HC_G110 1000_at S83513 S83513 NM_001117 HC_G110 1001_at D63483 D63483 NM_145349 HC_G110 1001_at D63483 D63483 NM_003693 HC_G110 1001_at D63483 D63483 NM_145351 HC_G110 1002_f_at D86864 D86864 NM_145349 HC_G110 1002_f_at D86864 D86864 NM_003693 HC_G110 1002_f_at D86864 D86864 NM_145351 HC_G112 1003_s_at X60435 X60435 NM_001117 HC_G112 1004_at S57153 S57153 NM_002892 Problem: # of elements in list_a = 246230 # of elements in list_b = 213612 This is more brute force and hihghly time consuming method. Although dictionary is superfast, due to duplications in both columns of list_a, a dictionary option falls out. I cannot think of any other smart method since these are the only two ways I know possible. Would any one please help me suggesting a neat and efficient way. thanks in advance. Srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kermit at polaris.net Thu Mar 23 05:47:06 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 22 Mar 2006 23:47:06 -0500 (Eastern Standard Time) Subject: [Tutor] urlopen: where are the results? Message-ID: <4422284A.000003.02432@YOUR-4105E587B6> Anybody care to comment on the following? >>> from urllib2 import * >>> urlopen("http://www.kermitrose.com") <addinfourl at 13510096 whose fp = <socket._fileobject object at 0x00CDD768>> >>> From dyoo at hkn.eecs.berkeley.edu Thu Mar 23 06:00:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Mar 2006 21:00:54 -0800 (PST) Subject: [Tutor] efficient method to search between two lists In-Reply-To: <20060323030901.68201.qmail@web38104.mail.mud.yahoo.com> Message-ID: <Pine.LNX.4.44.0603222055430.27754-100000@hkn.eecs.berkeley.edu> > Although dictionary is superfast, due to duplications > in both columns of list_a, a dictionary option falls > out. Hi Srinivas, A dictionary method can work perfectly well. The assumption that I think is being made is that dictionary values are restricted to single values. But dictionaries are more general than this. We can make dictionaries that map from strings to lists of things. For example: ####### sample = { 'a': ['alphabet', 'artichoke', 'antelope'], 'b': ['beta', 'brocolli', 'brontosaurus'], 'g': ['gamma', 'grub', 'gnome'] } ####### is a perfectly good dictionary. From dyoo at hkn.eecs.berkeley.edu Thu Mar 23 06:07:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Mar 2006 21:07:48 -0800 (PST) Subject: [Tutor] urlopen: where are the results? In-Reply-To: <4422284A.000003.02432@YOUR-4105E587B6> Message-ID: <Pine.LNX.4.44.0603222101050.27754-100000@hkn.eecs.berkeley.edu> On Wed, 22 Mar 2006, Kermit Rose wrote: > Anybody care to comment on the following? > > >>> from urllib2 import * Don't do this. *grin* Using 'from [modulename] import *' is not so good in Python because there's no warning if one of the contents in the module is overriding an existing definition. We can use 'import urllib2', or if we really want urlopen(): ###### from urllib2 import urlopen ###### > >>> urlopen("http://www.kermitrose.com") > <addinfourl at 13510096 whose fp = <socket._fileobject object at > 0x00CDD768>> This is fine so far. What we're getting back is a file-like object. But Once we have this, we can use all the file-like methods we know about, like read(), in order to pull out things from the file object. (Aside: the reason that urlopen() doesn't give us the file's contents directly is being there may be other things we may want to do besides read() the whole thing at once. Concretely, we might want to progressively scan through the web site's contents without reading the whole thing in one shot if we're concerned about memory consumption. Or we might just open the file and watch for an error, as a check to see that the file exists on the web site.) But is there something else that's bothering you? Because we can't read minds very well, you'll have to make up for our deficiency by telling us what is surprising to you. *grin* From dyoo at hkn.eecs.berkeley.edu Thu Mar 23 06:22:22 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 Mar 2006 21:22:22 -0800 (PST) Subject: [Tutor] i need help please read In-Reply-To: <4ce40aaa0603221745h38952e47xfc9a7cd73fa8f5f4@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603222110010.27754-100000@hkn.eecs.berkeley.edu> On Wed, 22 Mar 2006, Tom Bachik wrote: > ok does anyone know how to righ a script were a box pops up then if it > goes over a number on the screen it pops up in the box become the input > number so you can alter the number that popped up in the box? if you do > can you right it and send it to me and if you cant doit all but know how > i can do part will you please help me do it but remeber im new so i dont > know to much Hi Tom, Frankly, I'm having a very hard time understanding your question. You are going to have to try harder if you really want a good response from us. I do not mean to be mean: I simply don't understand the terms you are using; I'm having too hard enough time trying to parse your paragraph. My mental model of what you are trying to ask is not strong. If you want help, show us what you've tried so far, and we'll do what we can to point you toward resources that can help you. If this is homework, know that we can not do it for you. If you'd like pointers to tutorial resources, you may find: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers useful; this link contains most of the beginner-level tutorials. If you go through and work through the problems in a tutorial, you should be better equipped to play with Python. You've probably already been pointed to the "How to Ask Questions the Smart Way" page, but just in case, I'll be redundant and point it out: http://www.catb.org/~esr/faqs/smart-questions.html Reading it may help you write your question in a way that will make it easier to approach and answer. From carroll at tjc.com Thu Mar 23 07:00:02 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 22 Mar 2006 22:00:02 -0800 (PST) Subject: [Tutor] efficient method to search between two lists In-Reply-To: <20060323030901.68201.qmail@web38104.mail.mud.yahoo.com> Message-ID: <Pine.LNX.4.44.0603222151460.11771-100000@violet.rahul.net> On Wed, 22 Mar 2006, Srinivas Iyyer wrote: > I cannot think of any other smart method since these > are the only two ways I know possible. > > Would any one please help me suggesting a neat and > efficient way. I'm thinking: 1) use sets to get subsets of both lists down to only those elements that will match at least one element in another list; 2) loop and compare, but only on those elements you know will match somewhere (because of step #1) One try: list_a = ['S83513\tNM_001117', 'X60435\tNM_001117', 'U75370\tNM_005035', 'U05861\tNM_001353', 'S68290\tNM_001353', 'D86864\tNM_145349', 'D86864\tNM_003693', 'D86864\tNM_145351', 'D63483\tNM_145349', 'D63483\tNM_003693', 'D63483\tNM_145351', 'S66427\tNM_002892', 'S57153\tNM_002892'] list_b = ['HC_G110\t1000_at\tS83513', 'HC_G110\t1001_at\tD63483', 'HC_G110\t1002_f_at\tD86864', 'HC_G112\t1003_s_at\tX60435', 'HC_G112\t1004_at\tS57153'] set_a = set([(x.split('\t'))[0] for x in list_a]) set_b = set([(x.split('\t'))[2] for x in list_b]) intersection = list(set_a & set_b) for (whole_b, keypart_b) in \ [(x, x.split('\t')[2]) for x in list_b if x.split('\t')[2] in intersection]: for (whole_a, keypart_a) in \ [(x, x.split('\t')[0]) for x in list_a if x.split('\t')[0] in intersection]: if keypart_b == keypart_a: print whole_b+whole_a Gives as output: HC_G110 1000_at S83513S83513 NM_001117 HC_G110 1001_at D63483D63483 NM_145349 HC_G110 1001_at D63483D63483 NM_003693 HC_G110 1001_at D63483D63483 NM_145351 HC_G110 1002_f_at D86864D86864 NM_145349 HC_G110 1002_f_at D86864D86864 NM_003693 HC_G110 1002_f_at D86864D86864 NM_145351 HC_G112 1003_s_at X60435X60435 NM_001117 HC_G112 1004_at S57153S57153 NM_002892 (Note, my tab settings are different from yours, hence the different output.) From kabads at gmail.com Thu Mar 23 07:29:42 2006 From: kabads at gmail.com (Adam Cripps) Date: Thu, 23 Mar 2006 06:29:42 +0000 Subject: [Tutor] html and mod_python In-Reply-To: <loom.20060323T023022-647@post.gmane.org> References: <loom.20060323T023022-647@post.gmane.org> Message-ID: <c7ff38550603222229k7d7b04f5gb495008605d71f3@mail.gmail.com> On 3/23/06, Patty <patriciap.gu at gmail.com> wrote: > Hi! > > I created a form in a python file that takes values selected from 6 different > drop down boxes: > > for target in all_targets: > s = s + "<form action='process_info' method='POST'>" > s = s + "<input type='hidden' name='tg' value=%s>" % target > s = s + "<tr><td></td>" > for host in hosts: > if target in ants_map[host]: > s = s + printbox() > else: > s = s + printemptybox() > s = s + """<td><input type='submit' value='Submit'></td></tr>""" > s = s + "</form>" > > My printbox method contains the following: > def printbox(): > > tag = """ > <select name="percent"> > <option VALUE="-">-</option> > <option VALUE="0">0%</option> > <option VALUE="10">10%</option> > <option VALUE="20">20%</option> > <option VALUE="30">30%</option> > <option VALUE="40">40%</option> > <option VALUE="50">50%</option> > <option VALUE="60">60%</option> > <option VALUE="70">70%</option> > <option VALUE="80">80%</option> > <option VALUE="90">90%</option> > <option VALUE="100">100%</option> > </select>""" > return tag > > When the values are entered, my program stores them into a database. > Everything worked well, but now I have been asked to retain the values > selected in the drop down boxes. This means that when I open the web page, the > drop down boxes should display the recent values entered. I'm not sure how to > do it, and I'm really hoping that someone can point me to the right direction. > > Thanks, > Patty > I've just done something similar with a radio button. You will need to query your database to find the value. Then with that value, you can have a series of 'if' statements which print the particular option selected if it equals that value. More than likely, there's a much more efficient way to do it than this, but this worked for me. I'd be interested to hear if there were any other ways. HTH Adam -- http://www.monkeez.org PGP key: 0x7111B833 From michel.maho at skynet.be Thu Mar 23 07:44:18 2006 From: michel.maho at skynet.be (michel maho) Date: Thu, 23 Mar 2006 07:44:18 +0100 Subject: [Tutor] basic question Message-ID: <002501c64e45$35ee56c0$660aa8c0@LAPTOP> Hello everybody, I loaded IDLE (python GUI) on my portable installed with Windows XPpro but when I go in Python shell to file, and New wondow ,I do not find run or execute or something like that. I suppose the link with with WSH is not made. Please can and will anybody help a seventy one year young hopefull dummy? Michel -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060323/7e7e16fb/attachment.htm From srini_iyyer_bio at yahoo.com Thu Mar 23 08:11:42 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 22 Mar 2006 23:11:42 -0800 (PST) Subject: [Tutor] efficient method to search between two lists In-Reply-To: <Pine.LNX.4.44.0603222055430.27754-100000@hkn.eecs.berkeley.edu> Message-ID: <20060323071142.62523.qmail@web38110.mail.mud.yahoo.com> Hi Danny, Thanks for reminding me the tip from Kent :-) da = {} for m in list_a: cols = m.split('\t') ter = cols[0] da.setdefault(ter,[]).append(m) >>> da {'S66427': ['S66427\tNM_002892'], 'U05861': ['U05861\tNM_001353'], 'D63483': ['D63483\tNM_145349', 'D63483\tNM_003693', 'D63483\tNM_145351'], 'S68290': ['S68290\tNM_001353'], 'S83513': ['S83513\tNM_001117'], 'S57153': ['S57153\tNM_002892'], 'X60435': ['X60435\tNM_001117'], 'U75370': ['U75370\tNM_005035'], 'D86864': ['D86864\tNM_145349', 'D86864\tNM_003693', 'D86864\tNM_145351']} >>> for i in list_b: ... co = i.split('\t')[2] ... items = da.get(co) ... for x in items: ... print i+'\t'+x ... HC_G110 1000_at S83513 S83513 NM_001117 HC_G110 1001_at D63483 D63483 NM_145349 HC_G110 1001_at D63483 D63483 NM_003693 HC_G110 1001_at D63483 D63483 NM_145351 HC_G110 1002_f_at D86864 D86864 NM_145349 HC_G110 1002_f_at D86864 D86864 NM_003693 HC_G110 1002_f_at D86864 D86864 NM_145351 HC_G112 1003_s_at X60435 X60435 NM_001117 HC_G112 1004_at S57153 S57153 NM_002892 Thanks again danny and Kent. --- Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > Although dictionary is superfast, due to > duplications > > in both columns of list_a, a dictionary option > falls > > out. > > Hi Srinivas, > > A dictionary method can work perfectly well. > > The assumption that I think is being made is that > dictionary values are > restricted to single values. But dictionaries are > more general than this. > We can make dictionaries that map from strings to > lists of things. > > For example: > > ####### > sample = { 'a': ['alphabet', 'artichoke', > 'antelope'], > 'b': ['beta', 'brocolli', > 'brontosaurus'], > 'g': ['gamma', 'grub', 'gnome'] } > ####### > > is a perfectly good dictionary. > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From srini_iyyer_bio at yahoo.com Thu Mar 23 08:15:38 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 22 Mar 2006 23:15:38 -0800 (PST) Subject: [Tutor] efficient method to search between two lists In-Reply-To: <Pine.LNX.4.44.0603222151460.11771-100000@violet.rahul.net> Message-ID: <20060323071538.55442.qmail@web38101.mail.mud.yahoo.com> Thank you Terry, I learned some stuff from your snippet. I used 'Set' but never got to use its power using LC. Thanks again Srini --- Terry Carroll <carroll at tjc.com> wrote: > On Wed, 22 Mar 2006, Srinivas Iyyer wrote: > > > I cannot think of any other smart method since > these > > are the only two ways I know possible. > > > > Would any one please help me suggesting a neat and > > efficient way. > > I'm thinking: > > 1) use sets to get subsets of both lists down to > only those elements that > will match at least one element in another list; > > 2) loop and compare, but only on those elements you > know will match > somewhere (because of step #1) > > One try: > > list_a = ['S83513\tNM_001117', 'X60435\tNM_001117', > 'U75370\tNM_005035', 'U05861\tNM_001353', > 'S68290\tNM_001353', 'D86864\tNM_145349', > 'D86864\tNM_003693', 'D86864\tNM_145351', > 'D63483\tNM_145349', 'D63483\tNM_003693', > 'D63483\tNM_145351', 'S66427\tNM_002892', > 'S57153\tNM_002892'] > > list_b = ['HC_G110\t1000_at\tS83513', > 'HC_G110\t1001_at\tD63483', > 'HC_G110\t1002_f_at\tD86864', > 'HC_G112\t1003_s_at\tX60435', > 'HC_G112\t1004_at\tS57153'] > > set_a = set([(x.split('\t'))[0] for x in list_a]) > set_b = set([(x.split('\t'))[2] for x in list_b]) > intersection = list(set_a & set_b) > > for (whole_b, keypart_b) in \ > [(x, x.split('\t')[2]) for x in list_b > if x.split('\t')[2] in intersection]: > > for (whole_a, keypart_a) in \ > [(x, x.split('\t')[0]) for x in list_a > if x.split('\t')[0] in intersection]: > > if keypart_b == keypart_a: > print whole_b+whole_a > > Gives as output: > > HC_G110 1000_at S83513S83513 NM_001117 > HC_G110 1001_at D63483D63483 NM_145349 > HC_G110 1001_at D63483D63483 NM_003693 > HC_G110 1001_at D63483D63483 NM_145351 > HC_G110 1002_f_at D86864D86864 NM_145349 > HC_G110 1002_f_at D86864D86864 NM_003693 > HC_G110 1002_f_at D86864D86864 NM_145351 > HC_G112 1003_s_at X60435X60435 NM_001117 > HC_G112 1004_at S57153S57153 NM_002892 > > > (Note, my tab settings are different from yours, > hence the different > output.) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From samrobertsmith at gmail.com Thu Mar 23 09:13:26 2006 From: samrobertsmith at gmail.com (linda.s) Date: Thu, 23 Mar 2006 00:13:26 -0800 Subject: [Tutor] 3-D Message-ID: <1d987df30603230013i2626061eg6202f9723dc63121@mail.gmail.com> Is there any sample code to draw 3-D axis in Python. That is, we can see X,Y,Z coordinates? Thanks, Linda From alan.gauld at freenet.co.uk Thu Mar 23 09:29:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 08:29:20 -0000 Subject: [Tutor] urlopen: where are the results? References: <4422284A.000003.02432@YOUR-4105E587B6> Message-ID: <007701c192c3$9830af50$0b01a8c0@xp> > Anybody care to comment on the following? > >>>> from urllib2 import * Its considered bad practice to use from foo import * but at the >>> prompt its not too bad. >>>> urlopen("http://www.kermitrose.com") > <addinfourl at 13510096 whose fp = <socket._fileobject object at > 0x00CDD768>> >>>> Looks good. What did you expect? Alan G From rovingmedic at msn.com Thu Mar 23 09:40:08 2006 From: rovingmedic at msn.com (Shaun Ross) Date: Thu, 23 Mar 2006 12:40:08 +0400 Subject: [Tutor] Getting started - IDLE won't run Message-ID: <BAY5-DAV21D72127D16F97F7C6134BA8DE0@phx.gbl> Hi Group, I'm just getting started with Python. I've downloaded and installed the latest version (2.4.2 for Windows). I'm running Windows XP Prow SP2 on my Toshiba Satellite P4 Centrino 2GHz with 2GB RAM. I'm using Trend-Micro PC-Cillin 2006 anti-virus & firewall. The problem is that Python GUI (IDLE) doesn't run properly. It starts running when I click on the link / icon and then just seems to vanish (the hourglass displays, you can hear the hard drive read/write and then nothing). Python Command Prompt runs as expected. I've tried the recommendations on the Python for windows download page without success. Please advise what I need to do to fix this. Thanks, Shaun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060323/01e7c54e/attachment-0001.html From ajikoe at gmail.com Thu Mar 23 10:04:37 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 23 Mar 2006 10:04:37 +0100 Subject: [Tutor] Getting started - IDLE won't run In-Reply-To: <BAY5-DAV21D72127D16F97F7C6134BA8DE0@phx.gbl> References: <BAY5-DAV21D72127D16F97F7C6134BA8DE0@phx.gbl> Message-ID: <cf5262d20603230104n6da0400bgbee4fdc61ecc7c06@mail.gmail.com> Hello Ross, Can you see pythonw in the task manager process after you run idle ? Please look at this website concerning some firewall that can stop idle: http://www.python.org/download/releases/2.4.2/bugs/ Cheers, pujo On 3/23/06, Shaun Ross <rovingmedic at msn.com> wrote: > > Hi Group, > > I'm just getting started with Python. I've downloaded and installed the > latest version (2.4.2 for Windows). I'm running Windows XP Prow SP2 on my > Toshiba Satellite P4 Centrino 2GHz with 2GB RAM. I'm using Trend-Micro > PC-Cillin 2006 anti-virus & firewall. > > The problem is that Python GUI (IDLE) doesn't run properly. It starts > running when I click on the link / icon and then just seems to vanish (the > hourglass displays, you can hear the hard drive read/write and then > nothing). > > Python Command Prompt runs as expected. > > I've tried the recommendations on the Python for windows download page > without success. > > Please advise what I need to do to fix this. > > Thanks, > Shaun > > _______________________________________________ > 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/20060323/85afb34d/attachment.htm From lists at janeden.org Thu Mar 23 10:27:55 2006 From: lists at janeden.org (Jan Eden) Date: Thu, 23 Mar 2006 10:27:55 +0100 Subject: [Tutor] Webprogramming with the MVC pattern Message-ID: <r02010500-1039-4FC53579BA4F11DAB42D000A959B4026@[10.149.23.172]> Hi, I am about to build my first web application using the MVC pattern. Now I am wondering which might be the best way to initialize both a model and a presenter based on the model and its state. My controller should look like this: ######### model = Models.ModelFactory(cgi_parameters) view = Views.ViewFactory(model) view.Display() ######### The factory method ModelFactory would check the parameters and return an appropriate model: ######## def ModelFactory(params): valid_models = dict(location=Location, prices=Prices, booking=Booking) return valid_models[params['type']](**params) class Location: ... class Prices: ... class Booking: ... ######## But I am stuck with the ViewFactory method. Since the appropriate view depends on both the model's class (type) and state, I am not sure how to implement this. I could do it the ugly way: ######## def ViewFactory(model): if (model.__class__ == 'Booking' and model.state == 'new'): view = new NewBooking() elsif (model.__class__ == 'Booking' and model.state == 'review'): view = new BookingReview() ... return view class LocationView: ... class NewBooking: ... class BookingReview: ... class BookingConfirmation: ... ######## But there must be a better way. Could you give me a hint? Thanks, Jan -- A common mistake that people make when trying to design something completely foolproof is to underestimate the ingenuity of complete fools. From alan.gauld at freenet.co.uk Thu Mar 23 10:42:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 09:42:52 -0000 Subject: [Tutor] basic question References: <002501c64e45$35ee56c0$660aa8c0@LAPTOP> Message-ID: <009501c192cd$df2ddb80$0b01a8c0@xp> Hi Michael, > I loaded IDLE (python GUI) on my portable installed with Windows XPpro > but when I go in Python shell to file, and New wondow , > I do not find run or execute or something like that. First do you actually get a new blank window popping up? If so, you should find a Run menu item on the new Window. If you don't can you send us a list of what menus are visible. Also confirm whgich version of Python and IDLE are running - its displayed in the IDLE startup message. > I suppose the link with with WSH is not made. You lost me. What link with WSH? Python can access WSH objects but you need the Windows extensions installed (They come as standard on the ActiveState version of python or as part of the winall package for the 'official Python') Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Mar 23 10:50:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 09:50:27 -0000 Subject: [Tutor] Getting started - IDLE won't run References: <BAY5-DAV21D72127D16F97F7C6134BA8DE0@phx.gbl> Message-ID: <00a301c192ce$eef00470$0b01a8c0@xp> > The problem is that Python GUI (IDLE) doesn't run properly. I assume you found the stuff about enabling the firewall to allow comms to 127.0.0.1(localhost)? There is a reference to the problem on the Python web site but the fix depends on your firewall. Try disabling the firewall temporarily to prove that IDLE starts ok without it. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From klappnase at freenet.de Thu Mar 23 11:39:26 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 23 Mar 2006 11:39:26 +0100 Subject: [Tutor] Simple way for i18n ? In-Reply-To: <13a83ca10603220841q4412dff0j@mail.gmail.com> References: <13a83ca10603220841q4412dff0j@mail.gmail.com> Message-ID: <20060323113926.6e382c2d.klappnase@freenet.de> On Wed, 22 Mar 2006 17:41:14 +0100 "francois schnell" <francois.schnell at gmail.com> wrote: > Hello all, > > I wish to translate a Python script from English to French. I've read the > offical documentation (python.org doc) but I must admit that I'm lost now > ... > I've found some simple explanations here but I can't make it work: > http://karrigell.sourceforge.net/en/internationalization.htm > > Here's where I'm stuck: > > Let's imagine my app is: myapp.py > -- > import gettext > _ = gettext.gettext > > print _("hello friends") > print _("Bye Bye") > --- > > Here are my folders on a windows box: > > C:\myappfolder\ > -----------------------\Translations\francais\LC_MESSAGES > > My myapp.py is in myappfolder > > In this folder I've used pygettext.py to produce a messages.pot file => I > add the translation in it => I have a messages.po file. > I then used msgfmt.py to produce messages.mo file. > > I then copied messages.po and messages.mo in LC_MESSAGES folder > C:\myappfolder\ > -----------------------\Translations\francais\LC_MESSAGES > > I now come back to myapp.py and add two lines: > > --- > import gettext > _ = gettext.gettext > > t=gettext.translation("messages","c:\myappfolder\Translations","francais") > t.install() > > print _("hello friends") > print _("Bye Bye") > --- > > When I do that Python anwers: > > >>> > Traceback (most recent call last): > File "C:\myappfolder\myapp.py", line 4, in ? > t=gettext.translation > ("messages","c:\myappfolder\Translations","francais") > File "C:\Python24\lib\gettext.py", line 456, in translation > raise IOError(ENOENT, 'No translation file found for domain', domain) > IOError: [Errno 2] No translation file found for domain: 'messages' > >>> > Hi Francois, not sure if it is different on windows, on linux I simply do: import gettext gettext.install(domain, localedir) to install _() into my application's global namespace, where localedir in your case was "c:\myappfolder\Translations". The path that contains the french translation should be "..\fr\LC_MESSAGES" instead of "..\francais\LC_MESSAGES" I think (at least that is true on linux). I hope this helps Michael From kent37 at tds.net Thu Mar 23 11:48:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Mar 2006 05:48:00 -0500 Subject: [Tutor] html and mod_python In-Reply-To: <loom.20060323T023022-647@post.gmane.org> References: <loom.20060323T023022-647@post.gmane.org> Message-ID: <44227CE0.7090503@tds.net> Patty wrote: > Hi! > > I created a form in a python file that takes values selected from 6 different > drop down boxes: > > for target in all_targets: > s = s + "<form action='process_info' method='POST'>" > s = s + "<input type='hidden' name='tg' value=%s>" % target > s = s + "<tr><td></td>" > for host in hosts: > if target in ants_map[host]: > s = s + printbox() > else: > s = s + printemptybox() > s = s + """<td><input type='submit' value='Submit'></td></tr>""" > s = s + "</form>" > > My printbox method contains the following: > def printbox(): > > tag = """ > <select name="percent"> > <option VALUE="-">-</option> > <option VALUE="0">0%</option> > <option VALUE="10">10%</option> > <option VALUE="20">20%</option> > <option VALUE="30">30%</option> > <option VALUE="40">40%</option> > <option VALUE="50">50%</option> > <option VALUE="60">60%</option> > <option VALUE="70">70%</option> > <option VALUE="80">80%</option> > <option VALUE="90">90%</option> > <option VALUE="100">100%</option> > </select>""" > return tag > > When the values are entered, my program stores them into a database. > Everything worked well, but now I have been asked to retain the values > selected in the drop down boxes. This means that when I open the web page, the > drop down boxes should display the recent values entered. I'm not sure how to > do it, and I'm really hoping that someone can point me to the right direction. You have to add the attribute 'SELECTED' to the option tag that you want to be selected. To do this, you should recover the old value from the database and pass it to printbox(). Then change printbox() to create the tag using a loop over the value. For each value, check to see if it is the same as the value passed in and generate the appropriate option tag. HTH Kent From kent37 at tds.net Thu Mar 23 11:58:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Mar 2006 05:58:46 -0500 Subject: [Tutor] efficient method to search between two lists In-Reply-To: <Pine.LNX.4.44.0603222151460.11771-100000@violet.rahul.net> References: <Pine.LNX.4.44.0603222151460.11771-100000@violet.rahul.net> Message-ID: <44227F66.4070700@tds.net> Terry Carroll wrote: > On Wed, 22 Mar 2006, Srinivas Iyyer wrote: > > >>I cannot think of any other smart method since these >>are the only two ways I know possible. >> >>Would any one please help me suggesting a neat and >>efficient way. > > > I'm thinking: > > 1) use sets to get subsets of both lists down to only those elements that > will match at least one element in another list; > > 2) loop and compare, but only on those elements you know will match > somewhere (because of step #1) This is more efficient than the original algorithm because it reduces the size of the loops to the number of matching elements rather than the whole number of elements. But if there are a large number of matches it will still be a lot of loops! If the number of elements in a and b is na and nb and the number of matching elements is nmatch, then the original algorithm executes the inner loop na*nb times. Terry's algorithm reduces this to nmatch*nmatch which still grows quickly as nmatch gets bigger. The virtue of Srinivas' second solution (using a helper dict) is that it has two loops that iterate na and nb times separately, so it eliminates the multiplicative time. This is a huge win when na, nb and nmatch are large. Kent From kent37 at tds.net Thu Mar 23 12:04:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Mar 2006 06:04:20 -0500 Subject: [Tutor] 3-D In-Reply-To: <1d987df30603230013i2626061eg6202f9723dc63121@mail.gmail.com> References: <1d987df30603230013i2626061eg6202f9723dc63121@mail.gmail.com> Message-ID: <442280B4.2090509@tds.net> linda.s wrote: > Is there any sample code to draw 3-D axis in Python. That is, we can > see X,Y,Z coordinates? There is nothing built-in to Python to do this. Google "python 3d graphics" for many possibilities. You might want to look at VPython: http://www.vpython.org/webdoc/visual/VisualIntro.html Kent From rovingmedic at msn.com Thu Mar 23 12:07:08 2006 From: rovingmedic at msn.com (Shaun Ross) Date: Thu, 23 Mar 2006 15:07:08 +0400 Subject: [Tutor] Getting started - IDLE won't run References: <BAY5-DAV21D72127D16F97F7C6134BA8DE0@phx.gbl> <00a301c192ce$eef00470$0b01a8c0@xp> Message-ID: <BAY5-DAV3F276F84EF334613AF045A8DE0@phx.gbl> Hi Alan, I found those references on the Python site. I tried the fixes but nothing seemed to work. I just resorted to re-installing Python to the default directory and everything is working great now. It seems that the space in pathnames (C:\Program Files\) is the big problem. I'm still a novice to all this, but maybe there is a bug in the way IDLE creates the path on installation. Thanks for all your efforts in creating the tutorial. I'm slowly working through that now. Keep up the good work. Kind regards, Shaun ----- Original Message ----- From: "Alan Gauld" <alan.gauld at freenet.co.uk> To: "Shaun Ross" <rovingmedic at msn.com>; <tutor at python.org> Sent: Tuesday, January 01, 2002 6:16 PM Subject: Re: [Tutor] Getting started - IDLE won't run >> The problem is that Python GUI (IDLE) doesn't run properly. > > I assume you found the stuff about enabling the firewall to allow comms to > 127.0.0.1(localhost)? > > There is a reference to the problem on the Python web site but the fix > depends on your firewall. > > Try disabling the firewall temporarily to prove that IDLE starts ok > without it. > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > From rovingmedic at msn.com Thu Mar 23 12:07:57 2006 From: rovingmedic at msn.com (Shaun Ross) Date: Thu, 23 Mar 2006 15:07:57 +0400 Subject: [Tutor] Getting started - IDLE won't run References: <BAY5-DAV21D72127D16F97F7C6134BA8DE0@phx.gbl> <cf5262d20603230104n6da0400bgbee4fdc61ecc7c06@mail.gmail.com> Message-ID: <BAY5-DAV1648286F9135186504841FA8DE0@phx.gbl> Hi Pujo, Thanks for the tip. I re-installed Python in the default directory and everything is working properly now. Just goes to show what happens when you try to be too clever. Cheers, Shaun ----- Original Message ----- From: Pujo Aji To: Shaun Ross Cc: tutor at python.org Sent: Thursday, March 23, 2006 1:04 PM Subject: Re: [Tutor] Getting started - IDLE won't run Hello Ross, Can you see pythonw in the task manager process after you run idle ? Please look at this website concerning some firewall that can stop idle: http://www.python.org/download/releases/2.4.2/bugs/ Cheers, pujo On 3/23/06, Shaun Ross <rovingmedic at msn.com > wrote: Hi Group, I'm just getting started with Python. I've downloaded and installed the latest version (2.4.2 for Windows). I'm running Windows XP Prow SP2 on my Toshiba Satellite P4 Centrino 2GHz with 2GB RAM. I'm using Trend-Micro PC-Cillin 2006 anti-virus & firewall. The problem is that Python GUI (IDLE) doesn't run properly. It starts running when I click on the link / icon and then just seems to vanish (the hourglass displays, you can hear the hard drive read/write and then nothing). Python Command Prompt runs as expected. I've tried the recommendations on the Python for windows download page without success. Please advise what I need to do to fix this. Thanks, Shaun _______________________________________________ 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/20060323/91cba7a6/attachment.html From alan.gauld at freenet.co.uk Thu Mar 23 12:46:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 11:46:51 -0000 Subject: [Tutor] Webprogramming with the MVC pattern References: <r02010500-1039-4FC53579BA4F11DAB42D000A959B4026@[10.149.23.172]> Message-ID: <00ce01c192df$31dd6600$0b01a8c0@xp> Hi Jan, > I am about to build my first web application using the MVC > pattern. MVC can be done in many ways. Are you trying to build this from scratch or are you using some kind of Web framework such as Zope or CherryPy? > Now I am wondering which might be the best way to initialize > both a model and a presenter based on the model and its state. > My controller should look like this: I assume from the code that you want to use a single controller for all of your models not a controller per model? This requires that the controller be model agnostic and cannot know about the classes it controls? ######### model = Models.ModelFactory(cgi_parameters) view = Views.ViewFactory(model) view.Display() ######### One possibility is to use a registration scheme whereby the controller keeps a list of mopdels and correspomnding views. When a new model or view is defined the class is registered with the controller. Then it becomes the controllers responsibility to know what kind of model is required for a given view. > The factory method ModelFactory would check the parameters > and return an appropriate model: This is the alternative approach where the Factory objects must dynamically determine what kind of model or view is required. It usually involves a long if/else chain that must be updated as new classes are added, or else it uses a registration scheme of its own whereby the classes are kept in a dictionary keyed by class name. I favour the latter approach since it doesn't require modification of the factory when a new class is added. I'd therefore make the ModelFactory a class and then I'd remove the valid_models line below and add a class method to register a new model, then call that method after each model definition. (You can in fact create a single Factory class which is then either subclassed for models and views or alternatively instantiated twice) ######## def ModelFactory(params): valid_models = dict(location=Location, prices=Prices, booking=Booking) return valid_models[params['type']](**params) class Location: ... class Prices: ... class Booking: ... ######## > But I am stuck with the ViewFactory method. > Since the appropriate view depends on both the > model's class (type) and state, I'm not sure why the view would depend on model state, it shouldn't in MVC! Normally the user selects the view they want and the controller connects it to an appropriate model. You should be able to support multiple views of the same model at the same time. > I am not sure how to implement this. I could do it the ugly way: ######## def ViewFactory(model): if (model.__class__ == 'Booking' and model.state == 'new'): view = new NewBooking() elsif (model.__class__ == 'Booking' and model.state == 'review'): view = new BookingReview() ... return view class LocationView: ... > But there must be a better way. Could you give me a hint? You can use a registration/dictionary scheme as above. If the controller understands the relationship of view to model then when the view is created the controller joins the two together. In your case you seem to assume that the model is controlling which view is presented which is not an MVC paradigm with which I'm familiar so I'm not sure how that would work.. But you can still avoid the if/else chain by using a tuple of model/state to access the view dictionary. You just need to register the view with all combinations of model/state that could trigger the view... Alan G. From benvinger at yahoo.co.uk Thu Mar 23 14:26:58 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Thu, 23 Mar 2006 13:26:58 +0000 (GMT) Subject: [Tutor] Build your own web server in three lines of code Message-ID: <20060323132658.61665.qmail@web25812.mail.ukl.yahoo.com> The nice-looking, revamped Python web site states that you can do this, but does not go on to say how. Does anyone know? On an OT note, I've recently seen how it can be done in a shell script: http://www.debian-administration.org/articles/371 Ben ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From reed at intersiege.com Thu Mar 23 15:41:15 2006 From: reed at intersiege.com (Reed L. O'Brien) Date: Thu, 23 Mar 2006 09:41:15 -0500 Subject: [Tutor] Build your own web server in three lines of code In-Reply-To: <20060323132658.61665.qmail@web25812.mail.ukl.yahoo.com> References: <20060323132658.61665.qmail@web25812.mail.ukl.yahoo.com> Message-ID: <4422B38B.3010101@intersiege.com> If you have twisted it is in 2 lines like so: $ mktap web -p 9999 --path=C:\Python24 $ twistd -f web.tap Ben Vinger wrote: > The nice-looking, revamped Python web site states that > you can do this, but does not go on to say how. > Does anyone know? > > On an OT note, I've recently seen how it can be done > in a shell script: > http://www.debian-administration.org/articles/371 > > Ben > > > > ___________________________________________________________ > To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- 4.6692916090 'cmVlZEBpbnRlcnNpZWdlLmNvbQ==\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 keyID: 0x0FA09FCE From kent37 at tds.net Thu Mar 23 15:54:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Mar 2006 09:54:41 -0500 Subject: [Tutor] Build your own web server in three lines of code In-Reply-To: <20060323132658.61665.qmail@web25812.mail.ukl.yahoo.com> References: <20060323132658.61665.qmail@web25812.mail.ukl.yahoo.com> Message-ID: <4422B6B1.2030909@tds.net> Ben Vinger wrote: > The nice-looking, revamped Python web site states that > you can do this, but does not go on to say how. > Does anyone know? I don't know how to do it in three lines; how about one line? ;) From a command prompt python -c "import CGIHTTPServer; CGIHTTPServer.test()" will start a web server serving static files from the current directory and subdirectories and serving cgi from ./cgi-bin. Kent From kermit at polaris.net Thu Mar 23 16:36:08 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 23 Mar 2006 10:36:08 -0500 (Eastern Standard Time) Subject: [Tutor] urlopen: where are the results? References: <Pine.LNX.4.44.0603222101050.27754-100000@hkn.eecs.berkeley.edu> Message-ID: <4422C068.000001.00884@YOUR-4105E587B6> From: Danny Yoo Date: 03/23/06 00:08:25 To: Kermit Rose Cc: tutor at python.org Subject: Re: [Tutor] urlopen: where are the results? We can use 'import urllib2', or if we really want urlopen(): ###### from urllib2 import urlopen ###### **** Thanks. **** > >>> urlopen("http://www.kermitrose.com") > <addinfourl at 13510096 whose fp = <socket._fileobject object at > 0x00CDD768>> This is fine so far. What we're getting back is a file-like object. But Once we have this, we can use all the file-like methods we know about, like read(), in order to pull out things from the file object. **** Ah so. should I have assigned a name to the file by website = urlopen(" http://www.kermitrose.com" ) ? Since I did not assign a name, would I be able to use any of the information given in the value of the function to access the file? *** (Aside: the reason that urlopen() doesn't give us the file's contents directly is being there may be other things we may want to do besides read() the whole thing at once. Concretely, we might want to progressively scan through the web site's contents without reading the whole thing in one shot if we're concerned about memory consumption. Or we might just open the file and watch for an error, as a check to see that the file exists on the web site.) ***** Yes. This does make sense. ***** But is there something else that's bothering you? Because we can't read minds very well, you'll have to make up for our deficiency by telling us what is surprising to you. *grin* ***** Thanks. Basically, I had no idea how to interpret the value of urlopen that python returned. And I had not yet found out about the read function, so even if I had understood that urlopen returned a file , I still would not have know how to see the contents of that file. I will search for the read function in the tutorial. What hints can you give me for finding it quickly in the tutorial? Kermit < kermit at polaris.net > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060323/a609dfff/attachment-0001.htm From gv10000 at googlemail.com Thu Mar 23 16:50:45 2006 From: gv10000 at googlemail.com ( gv) Date: Thu, 23 Mar 2006 15:50:45 +0000 Subject: [Tutor] urlopen: where are the results? In-Reply-To: <4422C068.000001.00884@YOUR-4105E587B6> References: <Pine.LNX.4.44.0603222101050.27754-100000@hkn.eecs.berkeley.edu> <4422C068.000001.00884@YOUR-4105E587B6> Message-ID: <a8079de10603230750p1d553adbk95fec56d50682393@mail.gmail.com> On 3/23/06, Kermit Rose <kermit at polaris.net> wrote: > And I had not yet found out about the read function, so even if I had understood > that urlopen returned a file , I still would not have know how to see the contents > of that file. > > I will search for the read function in the tutorial. What hints can you give me for > finding it quickly in the tutorial? You hardly need to read about the read function. Just use it: print urlopen("http://www.kermitrose.com").read() or Webfile = urlopen("http://www.kermitrose.com").read() From patriciap.gu at gmail.com Thu Mar 23 16:54:03 2006 From: patriciap.gu at gmail.com (Patty) Date: Thu, 23 Mar 2006 15:54:03 +0000 (UTC) Subject: [Tutor] =?utf-8?q?html_and_mod=5Fpython?= References: <loom.20060323T023022-647@post.gmane.org> <c7ff38550603222229k7d7b04f5gb495008605d71f3@mail.gmail.com> Message-ID: <loom.20060323T165325-721@post.gmane.org> Hi again! result[0] is the value i got from the database. I tried the following piece of code and got : "TypeError: not enough arguments for format string" if result [0] in range(0, 101, 10): selected_value = result[0] else: selected_value = '-' tag = """ <select name='percent'> <option selected VALUE=%s>%s</option> <option VALUE='-'>-</option> <option VALUE='0'>0%</option> <option VALUE='10'>10%</option> <option VALUE='20'>20%</option> <option VALUE='30'>30%</option> <option VALUE='40'>40%</option> <option VALUE='50'>50%</option> <option VALUE='60'>60%</option> <option VALUE='70'>70%</option> <option VALUE='80'>80%</option> <option VALUE='90'>90%</option> <option VALUE='100'>100%</option> </select>""" % (selected_value,selected_value) return tag What am I doing wrong? Thanks, Patty From patriciap.gu at gmail.com Thu Mar 23 16:45:02 2006 From: patriciap.gu at gmail.com (Patricia G.) Date: Thu, 23 Mar 2006 10:45:02 -0500 Subject: [Tutor] html and mod_python In-Reply-To: <c7ff38550603222229k7d7b04f5gb495008605d71f3@mail.gmail.com> References: <loom.20060323T023022-647@post.gmane.org> <c7ff38550603222229k7d7b04f5gb495008605d71f3@mail.gmail.com> Message-ID: <18f27cbe0603230745m30dc94dcxcbc67539b6f2bea3@mail.gmail.com> Hi again! result[0] is the value i got from the database. I tried the following piece of code and got : "TypeError: not enough arguments for format string" if result [0] in range(0, 101, 10): selected_value = result[0] else: selected_value = '-' tag = """ <select name='percent'> <option selected VALUE=%s>%s</option> <option VALUE='-'>-</option> <option VALUE='0'>0%</option> <option VALUE='10'>10%</option> <option VALUE='20'>20%</option> <option VALUE='30'>30%</option> <option VALUE='40'>40%</option> <option VALUE='50'>50%</option> <option VALUE='60'>60%</option> <option VALUE='70'>70%</option> <option VALUE='80'>80%</option> <option VALUE='90'>90%</option> <option VALUE='100'>100%</option> </select>""" % (selected_value,selected_value) return tag What did i do wrong? Thanks, Patty -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060323/d588961e/attachment.htm From tim.golden at viacom-outdoor.co.uk Thu Mar 23 17:08:49 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Mar 2006 16:08:49 -0000 Subject: [Tutor] html and mod_python Message-ID: <9A28C052FF32734DACB0A288A3533991044D2664@vogbs009.gb.vo.local> [Patty] | I tried the following piece of code and got : | | "TypeError: not enough arguments for format string" | | tag = """ | <select name='percent'> | <option selected VALUE=%s>%s</option> | | <option VALUE='-'>-</option> | <option VALUE='0'>0%</option> | <option VALUE='10'>10%</option> | <option VALUE='20'>20%</option> [... snip similar lines ...] | </select>""" % (selected_value,selected_value) When Python sees % inside a string which is then qualified by a % operator, it expects *every one* of the % signs to introduce a substitution qualifier, like %s or %d. If you actually want a % sign in the string -- and you do here -- you need to put *two* % signs. So this will work: discount_achieved = 15 print "I got %d%% discount" % discount_achieved while this won't: discount_achieved = 15 print "I got %d% discount" % discount_achieved So, replace all the 10%, 20% etc in your string with 10%% and 20%%. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From alan.gauld at freenet.co.uk Thu Mar 23 17:34:04 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 16:34:04 -0000 Subject: [Tutor] urlopen: where are the results? References: <Pine.LNX.4.44.0603222101050.27754-100000@hkn.eecs.berkeley.edu> <4422C068.000001.00884@YOUR-4105E587B6> Message-ID: <00f201c19307$52692080$0b01a8c0@xp> > >>> urlopen("http://www.kermitrose.com") > <addinfourl at 13510096 whose fp = <socket._fileobject object at > 0x00CDD768>> > should I have assigned a name to the file by > website = urlopen(" http://www.kermitrose.com" ) ? Yes thats the idea. Its not really a file, but its what Python calls a "file-like object" That is it behaves like a file in that it has the same metjods and behaviour. It may not support all of the file methods but it will do the basics. > And I had not yet found out about the read function, so even if I had > understood that urlopen returned a file , I still would not have know > how to see the contents of that file. Did you look at the url2lib documentation? If you read it, it tells you that it returns a "file like object" Also at the bottom there is a link to a page full of examples. The first one is: ========================= 11.5.22 Examples This example gets the python.org main page and displays the first 100 bytes of it: >>> import urllib2 >>> f = urllib2.urlopen('http://www.python.org/') >>> print f.read(100) <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <?xml-stylesheet href="./css/ht2html ======================== Which shows how to open and read a web page. And if you went to the index and click 'f' you will find a link to 'file object' which gives you the list of methods you can call on file objects. (Admittedly not all of them work on file-like objects, but most will) I admit learning how to use the Python document set is not intuitive but it's worth persevering and the Module Index is invaluable. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From patriciap.gu at gmail.com Thu Mar 23 17:41:14 2006 From: patriciap.gu at gmail.com (Patty) Date: Thu, 23 Mar 2006 16:41:14 +0000 (UTC) Subject: [Tutor] =?utf-8?q?html_and_mod=5Fpython?= References: <9A28C052FF32734DACB0A288A3533991044D2664@vogbs009.gb.vo.local> Message-ID: <loom.20060323T174027-231@post.gmane.org> > So, replace all the 10%, 20% etc in your string > with 10%% and 20%%. > Thanks!!!!!!!!!!!! That fixed it all. From stvsmth at gmail.com Thu Mar 23 21:17:31 2006 From: stvsmth at gmail.com (stv) Date: Thu, 23 Mar 2006 15:17:31 -0500 Subject: [Tutor] Inner Class access to outer class attributes? Message-ID: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com> # So I figure out inner classes while typing the # first draft of this email, at least mostly # How do I access the "outer" class attributes from # the inner class? class GroupLocation(list): ### Note subclass of list class _Sublocation(object): def __init__(self, sublocation, action): self.sublocation = sublocation self.action = action def do_stuff(self): ### ### How would I get to GroupLocation attributes? ### print GroupLocation.name, self.sublocation def __init__(self, name, group_location): self.name = name self.group_location = group_location def add_sublocation(self, sublocation, action): self.append(GroupLocation._Sublocation(sublocation, action) group = GroupLocation('group1name', 'group1location') group.add_sublocation('sublocation1','foo') group.add_sublocation('sublocation2','bar') group.add_sublocation('sublocation3','zip') group.add_sublocation('sublocation4','foo') [sub.do_stuff() for sub in group if sub.action == 'foo'] # output (if it worked): # Group1location sublocation1 # Group1location sublocation4 # # instead I get this: # AttributeError: type object 'GroupLocation' has no attribute 'name' # Now, I suppose I could start down this road: class GroupLocation(object): def __init__(self,name, group_location): self.name = name self.group_location = group_location self.sublocations = [] def add_sublocation(self,sublocation, action): self.sublocations.append((sublocation, action)) group = GroupLocation('group1', 'group1location') group.add_sublocation('sublocation1','foo') group.add_sublocation('sublocation2','bar') group.add_sublocation('sublocation3','zip') group.add_sublocation('sublocation4','foo') for sub in group.sublocations: if sub[1] == 'foo': print group.group_location, sub[0] # output: # Group1location sublocation1 # Group1location sublocation4 # But that feels wrong in several ways: # 1) Any time I want to do_stuff() I have # to retype # 2) sub[1] & sub [0] are confusing after # not reading the code for a few hours. From stvsmth at gmail.com Thu Mar 23 21:17:31 2006 From: stvsmth at gmail.com (stv) Date: Thu, 23 Mar 2006 15:17:31 -0500 Subject: [Tutor] Inner Class access to outer class attributes? Message-ID: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com> # So I figure out inner classes while typing the # first draft of this email, at least mostly # How do I access the "outer" class attributes from # the inner class? class GroupLocation(list): ### Note subclass of list class _Sublocation(object): def __init__(self, sublocation, action): self.sublocation = sublocation self.action = action def do_stuff(self): ### ### How would I get to GroupLocation attributes? ### print GroupLocation.name, self.sublocation def __init__(self, name, group_location): self.name = name self.group_location = group_location def add_sublocation(self, sublocation, action): self.append(GroupLocation._Sublocation(sublocation, action) group = GroupLocation('group1name', 'group1location') group.add_sublocation('sublocation1','foo') group.add_sublocation('sublocation2','bar') group.add_sublocation('sublocation3','zip') group.add_sublocation('sublocation4','foo') [sub.do_stuff() for sub in group if sub.action == 'foo'] # output (if it worked): # Group1location sublocation1 # Group1location sublocation4 # # instead I get this: # AttributeError: type object 'GroupLocation' has no attribute 'name' # Now, I suppose I could start down this road: class GroupLocation(object): def __init__(self,name, group_location): self.name = name self.group_location = group_location self.sublocations = [] def add_sublocation(self,sublocation, action): self.sublocations.append((sublocation, action)) group = GroupLocation('group1', 'group1location') group.add_sublocation('sublocation1','foo') group.add_sublocation('sublocation2','bar') group.add_sublocation('sublocation3','zip') group.add_sublocation('sublocation4','foo') for sub in group.sublocations: if sub[1] == 'foo': print group.group_location, sub[0] # output: # Group1location sublocation1 # Group1location sublocation4 # But that feels wrong in several ways: # 1) Any time I want to do_stuff() I have # to retype # 2) sub[1] & sub [0] are confusing after # not reading the code for a few hours. From traceyandjoe at tiscali.co.uk Thu Mar 23 21:27:28 2006 From: traceyandjoe at tiscali.co.uk (traceyandjoe at tiscali.co.uk) Date: Thu, 23 Mar 2006 20:27:28 +0000 Subject: [Tutor] Renaming computers In-Reply-To: <mailman.11797.1143011693.27774.tutor@python.org> Message-ID: <43E7212300143752@mk-cpfrontend-3.mail.uk.tiscali.com> Hello there, Could you point me in the right direction, after we have ghosted the machines in college we have to rename them, I would like to try and write a program that does this through matching the MAC address with the computer but I'm quite new to programming and need some advice on where to start many thanks Joe >-- Original Message -- >From: tutor-request at python.org >Subject: Tutor Digest, Vol 25, Issue 54 >To: tutor at python.org >Reply-To: tutor at python.org >Date: Wed, 22 Mar 2006 08:14:53 +0100 > > >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. how to get a line text from input file. (Keo Sophon) > 2. how to set a value to a block of memory (Keo Sophon) > 3. Re: Python & MP3 (Bill Burns) > 4. Re: how to set a value to a block of memory (Kent Johnson) > 5. Re: how to get a line text from input file. (Kent Johnson) > 6. Re: Python & MP3 (Gabriel S Farrell) > 7. Re: how to get a line text from input file. (Danny Yoo) > 8. Re: how to set a value to a block of memory (Danny Yoo) > 9. Re: how to set a value to a block of memory (Danny Yoo) > 10. Hi (Kaushal Shriyan) > 11. Re: Hi (Danny Yoo) > 12. Re: Hi (Kaushal Shriyan) > > >---------------------------------------------------------------------- > >Message: 1 >Date: Wed, 22 Mar 2006 08:27:37 +0700 >From: Keo Sophon <keosophon at khmeros.info> >Subject: [Tutor] how to get a line text from input file. >To: tutor at python.org >Message-ID: <200603220827.37194.keosophon at khmeros.info> >Content-Type: text/plain; charset="us-ascii" > >Hi all, > >i am new to programming language and python. I wonder how to get a line text > >from input file. > >Thanks, >sophon > > >------------------------------ > >Message: 2 >Date: Wed, 22 Mar 2006 08:36:02 +0700 >From: Keo Sophon <keosophon at khmeros.info> >Subject: [Tutor] how to set a value to a block of memory >To: tutor at python.org >Message-ID: <200603220836.02972.keosophon at khmeros.info> >Content-Type: text/plain; charset="us-ascii" > >Hi all, > >How can i set a value to a bytes of block of memory. In C, i think they use > >memset like this. > >Thanks, >Sophon > > >------------------------------ > >Message: 3 >Date: Tue, 21 Mar 2006 21:35:15 -0500 >From: Bill Burns <billburns at pennswoods.net> >Subject: Re: [Tutor] Python & MP3 >To: Johanna <johanna.freeman at tiscali.it> >Cc: Tutor at python.org >Message-ID: <4420B7E3.7060807 at pennswoods.net> >Content-Type: text/plain; charset=windows-1252; format=flowed > >Johanna wrote: >> Hallo >> >> >> >> This is my first post, so hallo to everyone. Im just a newbee with >> python so I hope my msg will make some sense. J >> >> >> >> Is it possible to work with MP3 in python? >> >> I?m looking for a library to modify MP3s (like fade in, fade out, >> etc..). I know there are actually some libraries for doing this work >> with .wav but I didn?t find one for working with MP3. I?m not sure but > >> should be something like -> http://effbot.org/librarybook/wave.htm . Anyone? >> >> > >You may want to have a look at PyMedia: > >http://www.pymedia.org/ > >HTH, > >Bill > > >------------------------------ > >Message: 4 >Date: Tue, 21 Mar 2006 22:17:34 -0500 >From: Kent Johnson <kent37 at tds.net> >Subject: Re: [Tutor] how to set a value to a block of memory >Cc: tutor at python.org >Message-ID: <4420C1CE.7050200 at tds.net> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed > >Keo Sophon wrote: >> Hi all, >> >> How can i set a value to a bytes of block of memory. In C, i think they >use >> memset like this. > >Python does not support direct access to memory, you will need to use >another language or maybe a C extension to Python to do this. > >Kent > > > >------------------------------ > >Message: 5 >Date: Tue, 21 Mar 2006 22:20:06 -0500 >From: Kent Johnson <kent37 at tds.net> >Subject: Re: [Tutor] how to get a line text from input file. >Cc: tutor at python.org >Message-ID: <4420C266.6090106 at tds.net> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed > >Keo Sophon wrote: >> Hi all, >> >> i am new to programming language and python. I wonder how to get a line >text >> from input file. > >The simplest Python idiom to do something with each line of a file is this: > for line in open('somefile.txt'): > # do something with line > >You can find out more here: >http://docs.python.org/tut/node9.html#SECTION009200000000000000000 > >Kent > > > >------------------------------ > >Message: 6 >Date: Wed, 22 Mar 2006 00:17:13 -0500 >From: Gabriel S Farrell <gsf at panix.com> >Subject: Re: [Tutor] Python & MP3 >To: tutor at python.org >Message-ID: <20060322051713.GJ1989 at panix.com> >Content-Type: text/plain; charset=us-ascii > >On Tue, Mar 21, 2006 at 09:35:15PM -0500, Bill Burns wrote: >> Johanna wrote: >> > Is it possible to work with MP3 in python? >> > >> > I?m looking for a library to modify MP3s (like fade in, fade out, >> > etc..). >> >> You may want to have a look at PyMedia: >> >> http://www.pymedia.org/ > >I agree with Bill, pymedia looks like the closest thing to what you're >after. There's also pyxmms (python-xmms in Debian) if you don't mind >going through xmms. pygame might do the trick, also (check out >http://www.pygame.org/docs/ref/music.html). > >gsf > > >------------------------------ > >Message: 7 >Date: Tue, 21 Mar 2006 21:31:52 -0800 (PST) >From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu> >Subject: Re: [Tutor] how to get a line text from input file. >To: Keo Sophon <keosophon at khmeros.info> >Cc: tutor at python.org >Message-ID: > <Pine.LNX.4.44.0603212129320.1666-100000 at hkn.eecs.berkeley.edu> >Content-Type: TEXT/PLAIN; charset=US-ASCII > > > >On Wed, 22 Mar 2006, Keo Sophon wrote: > >> i am new to programming language and python. I wonder how to get a line >> text from input file. > >Hi Sophon, > >You may want to look at: > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > >Many of the tutorials there talk about reading from files, including Alan >Gauld's "How to Program": > > http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm > >How are you learning how to program? Is there a particular tutorial that >you're reading from? > > > >------------------------------ > >Message: 8 >Date: Tue, 21 Mar 2006 21:54:31 -0800 (PST) >From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu> >Subject: Re: [Tutor] how to set a value to a block of memory >To: Keo Sophon <keosophon at khmeros.info> >Cc: Tutor <tutor at python.org> >Message-ID: > <Pine.LNX.4.44.0603212132030.1666-100000 at hkn.eecs.berkeley.edu> >Content-Type: TEXT/PLAIN; charset=US-ASCII > > > >On Tue, 21 Mar 2006, Kent Johnson wrote: > >> > How can i set a value to a bytes of block of memory. In C, i think >> > they use memset like this. > >Hi Sophon, > >Secondary question: why are you trying to do this? Are you trying to >represent a collection or "array" of things? > > >Some concepts in C aren't well represented in Python because they only >make sense from a low-level hardware perspective. For example, asking for >an equivalent for C's malloc() or free() functions is "nonsensical" in the >sense that, since Python is garbage collected, it provides no such >functions to the casual Python user. > >(Such functions ARE available through third-party modules such as SWIG, >but unless you are really trying to integrate with a C library, you don't >need this.) > > >As an extended example: C programmers often use malloc() to dynamically >build structures, such as linked lists: > >/**********************************************************/ >/*** C Code **/ >#include <stdio.h> >#include <stdlib.h> > >struct IntList { > int first; > struct IntList *rest; >}; > >struct IntList* construct(int head, struct IntList* rest) { > struct IntList* newlist; > newlist = malloc(sizeof(struct IntList)); > newlist->first = head; > newlist->rest = rest; > return newlist; >} > >void printList(struct IntList* list) { > while (list != NULL) { > printf("%d\n", list->first); > list = list->rest; > } >} > >int main() { > struct IntList *mylist = NULL; > mylist = construct(5, mylist); > mylist = construct(1, mylist); > mylist = construct(4, mylist); > mylist = construct(1, mylist); > mylist = construct(3, mylist); > printList(mylist); > return 0; >} >/**********************************************************/ > > >But in Python, we can do this structure building without explicitely >malloc()ing. The code above has a possible "translation" which looks >like: > > >############################################ >## Python Code ## >import sys >class LinkedList: > def __init__(self, first, rest): > self.first, self.rest = first, rest > >def printList(list): > while list != None: > print list.first > list = list.rest > >def main(): > mylist = None > mylist = LinkedList(5, mylist) > mylist = LinkedList(1, mylist) > mylist = LinkedList(4, mylist) > mylist = LinkedList(1, mylist) > mylist = LinkedList(3, mylist) > printList(mylist) > sys.exit(0) > >if __name__ == '__main__': > main() >############################################ > >where most of the low-level details of allocating memory are all handled >by the Python runtime. > >So rather than ask for direct equivalents to C, it might help to ask about >what you're trying to do. We'll do what we can to help translate between >C concepts and Python concepts, and for the most part, what you already >know will have close analogues. But some concepts will require a bit of >tweaking. > > >Good luck! > > > > >------------------------------ > >Message: 9 >Date: Tue, 21 Mar 2006 21:58:23 -0800 (PST) >From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu> >Subject: Re: [Tutor] how to set a value to a block of memory >To: Tutor <tutor at python.org> >Message-ID: > <Pine.LNX.4.44.0603212156440.1666-100000 at hkn.eecs.berkeley.edu> >Content-Type: TEXT/PLAIN; charset=US-ASCII > > > >> On Tue, 21 Mar 2006, Kent Johnson wrote: > ^^^^^^^^^^^^ >> > > How can i set a value to a bytes of block of memory. In C, i think >> > > they use memset like this. > > >Whoops, sorry about that Kent! I completely messed up the attribution >when cutting-and-pasting. > > > >------------------------------ > >Message: 10 >Date: Wed, 22 Mar 2006 12:11:48 +0530 >From: "Kaushal Shriyan" <kaushalshriyan at gmail.com> >Subject: [Tutor] Hi >To: tutor at python.org >Message-ID: > <6b16fb4c0603212241g6fb03c9gf61b7baf77217a26 at mail.gmail.com> >Content-Type: text/plain; charset=ISO-8859-1 > >Hi > >I am new to python and I am going through the URL >http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment >I am going through the Chapter 7 Strings, I am stuck with understanding >slice which is a part of a String, I am not able to understand how it functions > >Awaiting your earnest reply > >Thanks in Advance > >Regards > >Kaushal > > >------------------------------ > >Message: 11 >Date: Tue, 21 Mar 2006 23:04:36 -0800 (PST) >From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu> >Subject: Re: [Tutor] Hi >To: Kaushal Shriyan <kaushalshriyan at gmail.com> >Cc: tutor at python.org >Message-ID: > <Pine.LNX.4.44.0603212300200.25864-100000 at hkn.eecs.berkeley.edu> >Content-Type: TEXT/PLAIN; charset=US-ASCII > > >> I am new to python and I am going through the URL >> http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment I am going >> through the Chapter 7 Strings, I am stuck with understanding slice which >> is a part of a String, I am not able to understand how it functions > >Hello, > > >A "slice" takes a string and returns a "substring" of that string. For >example, if we have a string like: > >###### >>>> mystring = "supercalifragilisticexpialidocious" >###### > >then we can select different portions of the string by indicating the >start and end positions. For example, the first ten characters of >mystring can be extracted using a slice: > >###### >>>> mystring[0:10] >'supercalif' >###### > > >Is this what you are confused about? > >Please give us more details on where you're getting stuck, and we will do >what we can to help clarify. > > >Please continue to reply to 'python-help at python.org': do not email me >directly. Although I may not personally have the time to answer, I'm sure >at least one of the other helpers on the list do, so by continuing the >conversation on python-help, we'll be able to guarantee that your >questions are not lost. > > > >------------------------------ > >Message: 12 >Date: Wed, 22 Mar 2006 12:44:51 +0530 >From: "Kaushal Shriyan" <kaushalshriyan at gmail.com> >Subject: Re: [Tutor] Hi >To: tutor at python.org >Cc: Danny Yoo <dyoo at hkn.eecs.berkeley.edu> >Message-ID: > <6b16fb4c0603212314n73ef102an492b330907e7cfcf at mail.gmail.com> >Content-Type: text/plain; charset=ISO-8859-1 > >On 3/22/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: >> >> > I am new to python and I am going through the URL >> > http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment I am going >> > through the Chapter 7 Strings, I am stuck with understanding slice which >> > is a part of a String, I am not able to understand how it functions >> >> Hello, >> >> >> A "slice" takes a string and returns a "substring" of that string. For >> example, if we have a string like: >> >> ###### >> >>> mystring = "supercalifragilisticexpialidocious" >> ###### >> >> then we can select different portions of the string by indicating the >> start and end positions. For example, the first ten characters of >> mystring can be extracted using a slice: >> >> ###### >> >>> mystring[0:10] >> 'supercalif' >> ###### >> >> >> Is this what you are confused about? >> >> Please give us more details on where you're getting stuck, and we will >do >> what we can to help clarify. >> >> >> Please continue to reply to 'python-help at python.org': do not email me >> directly. Although I may not personally have the time to answer, I'm sure >> at least one of the other helpers on the list do, so by continuing the >> conversation on python-help, we'll be able to guarantee that your >> questions are not lost. >> >> > >Thanks Danny Yoo > >I got this, Lets say if its mystring[n:m] where n may be another >number and m may be another number so how will it work in that case, >so this becomes general and makes more clear > >Lets say if its mystring[3:8] so how will i evaluate it > >Thanks for all the help > >Regards > >Kaushal > > >------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > >End of Tutor Digest, Vol 25, Issue 54 >************************************* ___________________________________________________________ Tiscali Broadband from 14.99 with free setup! http://www.tiscali.co.uk/products/broadband/ From kent37 at tds.net Thu Mar 23 21:36:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Mar 2006 15:36:31 -0500 Subject: [Tutor] Inner Class access to outer class attributes? In-Reply-To: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com> References: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com> Message-ID: <442306CF.6050001@tds.net> stv wrote: > # So I figure out inner classes while typing the > # first draft of this email, at least mostly > # How do I access the "outer" class attributes from > # the inner class? Unlike Java (for example), in Python an inner class doesn't have any special access to attributes of an instance of an enclosing class. They are more like Java's static nested classes. If you want access to a GroupLocation instance, just pass it to the sublocation. > > class GroupLocation(list): ### Note subclass of list > > class _Sublocation(object): > def __init__(self, sublocation, action): > self.sublocation = sublocation > self.action = action def __init__(self, grouplocation, sublocation, action): self.grouplocation = grouplocation self.sublocation = sublocation self.action = action > def do_stuff(self): > ### > ### How would I get to GroupLocation attributes? > ### > print GroupLocation.name, self.sublocation print self.grouplocation.name, self.sublocation Kent From stvsmth at gmail.com Thu Mar 23 21:48:21 2006 From: stvsmth at gmail.com (stv) Date: Thu, 23 Mar 2006 15:48:21 -0500 Subject: [Tutor] Inner Class access to outer class attributes? In-Reply-To: <442306CF.6050001@tds.net> References: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com> <442306CF.6050001@tds.net> Message-ID: <9493d0340603231248vea1c237oc30457461c11d337@mail.gmail.com> Hmmm, so every Sublocation object has a copy of the grouplocation data? What happens if I come around & change something: group.grouplocation = differentGroupLocationID Would I need to (forgive me here if I get some terms wrong) use a property (or a setter) & then loop over all the affected sublocations every time grouplocation is re-set? A-la de-normalized relational database Is there a better way to skin this cat? Or am I stuck with a) the non-inner class design & it's ugly indexes for sub in group.sublocations: if sub[1] == 'foo': print group.group_location, sub[0] or b) data duplication & possible un-synching. I'll take a). On 3/23/06, Kent Johnson <kent37 at tds.net> wrote: > > If you want access to a GroupLocation instance, just pass it to the > sublocation. > > > > class GroupLocation(list): > > > > class _Sublocation(object): > > def __init__(self, sublocation, action): > > self.sublocation = sublocation > > self.action = action > > def __init__(self, grouplocation, sublocation, action): > self.grouplocation = grouplocation > self.sublocation = sublocation > self.action = action From dyoo at hkn.eecs.berkeley.edu Thu Mar 23 22:34:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Mar 2006 13:34:19 -0800 (PST) Subject: [Tutor] Renaming computers In-Reply-To: <43E7212300143752@mk-cpfrontend-3.mail.uk.tiscali.com> Message-ID: <Pine.LNX.4.44.0603231320450.8656-100000@hkn.eecs.berkeley.edu> On Thu, 23 Mar 2006 traceyandjoe at tiscali.co.uk wrote: > Could you point me in the right direction, after we have ghosted the > machines in college we have to rename them, I would like to try and > write a program that does this through matching the MAC address with the > computer but I'm quite new to programming and need some advice on where > to start Hi Joe, This project seems doable but will take a bit of work to get right. For introductions on fundamental programming concepts, you may find the tutorials in: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers very helpful in getting up to speed. If you have questions while going through a tutorial there, please feel free to ask the group here, and we will be happy to help. Once you have a foundation for programming, you should be able to better tackle the problem. Your proposed problem sounds very operating-system dependent, and assuming that the machines you're talking about are Windows boxes, you may want to talk with the python-win32 folks to see how to go about this. They have a mailing list here: http://mail.python.org/mailman/listinfo/python-win32 There are examples of programs that people have written to automate some Windows administration tasks. For example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347812 is code to get the MAC address of one's ethernet card, and http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 is a recipe that automates remote system reboots! So I think it's just a matter of knowing what particular win32 calls need to be done to change the Windows name of a machine. Unfortunately, I really don't know Windows very well. I'd recommend poking around with the win32 folks and see if it's possile to get/set the computer name of a Windows machine. But learn a little bit of programming first, at least enough so that you can understand their advice! *grin* Good luck to you. From dyoo at hkn.eecs.berkeley.edu Thu Mar 23 22:58:17 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Mar 2006 13:58:17 -0800 (PST) Subject: [Tutor] Inner Class access to outer class attributes? In-Reply-To: <9493d0340603231248vea1c237oc30457461c11d337@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603231334590.8656-100000@hkn.eecs.berkeley.edu> On Thu, 23 Mar 2006, stv wrote: > Hmmm, so every Sublocation object has a copy of the grouplocation data? Hi stv, Not exactly: each sublocation has a "reference" to the parent grouplocation. There's a distinction between a "reference" and a copy. Think of a reference as an arrow to the other thing. For example: ######################################################### class Person: def __init__(self, name): self.name = name self.friends = [] def befriend(self, other): self.friends.append(other) other.friends.append(self) def greet(self): print "hi, I'm", self.name, "and my friends are:", for friend in self.friends: print friend.name, print ######################################################### If we have three people, say, larry, curly, and moe: ###### >>> larry, curly, moe = Person("Larry"), Person("Curly"), Person("Moe") ###### then befriending between any two people doesn't "copy" anyone: it's just lets them know about each other. ###### >>> larry.befriend(curly) >>> curly.befriend(moe) >>> curly.greet() hi, I'm Curly and my friends are: Larry Moe ###### If we later change the name of someone like moe: ###### >>> moe.name = 'moe the burninator' ###### then if curly starts greeting people again, we see that curly now refers to moe as 'moe the burninator': ###### >>> curly.greet() hi, I'm Curly and my friends are: Larry moe the burninator ###### So Curly has a list of references to friends. A model diagram of the situation looks something like this: larry --------------> { name, friends } | | V | "Larry" [ x, x ] | | | | curly --------------> { name, ...} <-/ | | / V / "Curly" / / moe ----------------> { ... } <------ where I'm just using some ad-hoc notation to show that the names we use are arrows to thingy's that I've put in brackets. And if we look at the friends of Larry, we'll see that each element in friends is actually a reference to the thingy's that represent Curly and Moe. If Curly had "copied" Moe rather than "refered" to Moe, we'd see different results. Does this make sense? From dyoo at hkn.eecs.berkeley.edu Thu Mar 23 23:02:07 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Mar 2006 14:02:07 -0800 (PST) Subject: [Tutor] Inner Class access to outer class attributes? In-Reply-To: <Pine.LNX.4.44.0603231334590.8656-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0603231400290.8656-100000@hkn.eecs.berkeley.edu> > So Curly has a list of references to friends. A model diagram of the > situation looks something like this: > > > larry --------------> { name, friends } > | | > V | > "Larry" [ x, x ] > | | > | | > curly --------------> { name, ...} <-/ | > | / > V / > "Curly" / > / > moe ----------------> { ... } <------ > > > where I'm just using some ad-hoc notation to show that the names we use > are arrows to thingy's that I've put in brackets. ^^^^^^^^ Ooops. I should substitute the word "brackets" with "braces". I always get those two mixed up. From alan.gauld at freenet.co.uk Thu Mar 23 23:10:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 22:10:38 -0000 Subject: [Tutor] Inner Class access to outer class attributes? References: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com> Message-ID: <011601c19336$5a7fb340$0b01a8c0@xp> I'm not sure why you think this needs to be an inner class? Why not just make it a peer class of GroupLocation? Then you can pass in the GroupLocation as a parent to the SubLocation constructor. The sublocation methods then reference the GroupLocation via the parent attribute: class Container(list): def __init__(self) name = 'foo' # do stuff here class Content(object): def __init__(self, parent): self.parent = parent self.action = 'foo' def doThings(self): print parent.name c = Container() for n in range(3): c.append(Content(c)) c[n].doThings() result = [n.doThings() for n in c if n.action == 'foo'] Inner classes are one of those esoteric OO features that sound awfully clever but in practice are hardly ever needed! IMHO at least :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "stv" <stvsmth at gmail.com> To: <Tutor at python.org> Sent: Thursday, March 23, 2006 8:17 PM Subject: [Tutor] Inner Class access to outer class attributes? # So I figure out inner classes while typing the # first draft of this email, at least mostly # How do I access the "outer" class attributes from # the inner class? class GroupLocation(list): ### Note subclass of list class _Sublocation(object): def __init__(self, sublocation, action): self.sublocation = sublocation self.action = action def do_stuff(self): ### ### How would I get to GroupLocation attributes? ### print GroupLocation.name, self.sublocation def __init__(self, name, group_location): self.name = name self.group_location = group_location def add_sublocation(self, sublocation, action): self.append(GroupLocation._Sublocation(sublocation, action) group = GroupLocation('group1name', 'group1location') group.add_sublocation('sublocation1','foo') group.add_sublocation('sublocation2','bar') group.add_sublocation('sublocation3','zip') group.add_sublocation('sublocation4','foo') [sub.do_stuff() for sub in group if sub.action == 'foo'] # output (if it worked): # Group1location sublocation1 # Group1location sublocation4 # # instead I get this: # AttributeError: type object 'GroupLocation' has no attribute 'name' # Now, I suppose I could start down this road: class GroupLocation(object): def __init__(self,name, group_location): self.name = name self.group_location = group_location self.sublocations = [] def add_sublocation(self,sublocation, action): self.sublocations.append((sublocation, action)) group = GroupLocation('group1', 'group1location') group.add_sublocation('sublocation1','foo') group.add_sublocation('sublocation2','bar') group.add_sublocation('sublocation3','zip') group.add_sublocation('sublocation4','foo') for sub in group.sublocations: if sub[1] == 'foo': print group.group_location, sub[0] # output: # Group1location sublocation1 # Group1location sublocation4 # But that feels wrong in several ways: # 1) Any time I want to do_stuff() I have # to retype # 2) sub[1] & sub [0] are confusing after # not reading the code for a few hours. From kent37 at tds.net Thu Mar 23 23:18:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Mar 2006 17:18:15 -0500 Subject: [Tutor] Inner Class access to outer class attributes? In-Reply-To: <9493d0340603231248vea1c237oc30457461c11d337@mail.gmail.com> References: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com> <442306CF.6050001@tds.net> <9493d0340603231248vea1c237oc30457461c11d337@mail.gmail.com> Message-ID: <44231EA7.2090800@tds.net> stv wrote: > Hmmm, so every Sublocation object has a copy of the grouplocation > data? No, as Danny explained it is a reference to the data, not a copy. > > Is there a better way to skin this cat? Or am I stuck with a) the > non-inner class design & it's ugly indexes > > for sub in group.sublocations: > if sub[1] == 'foo': > print group.group_location, sub[0] > > or b) data duplication & possible un-synching. There is an intermediate solution as well. You could use a sublocations class with attributes but no reference to its parent. Then the above would be for sub in group.sublocations: if sub.action == 'foo': print group.group_location, sub.sublocation Kent From Christian.Wyglendowski at greenville.edu Thu Mar 23 23:18:27 2006 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 23 Mar 2006 16:18:27 -0600 Subject: [Tutor] Renaming computers Message-ID: <CE1475C007B563499EDBF8CDA30AB45B064AEE19@empex.greenville.edu> Danny Yoo wrote: > There are examples of programs that people have written to > automate some Windows administration tasks. For example: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347812 > > is code to get the MAC address of one's ethernet card You can also use WMI for this task. The pywin32 package is required. Here is an example using the interactive interpreter: >>> from win32com.client import GetObject >>> machine = GetObject('winmgmts://some_remote_machine/root/cimv2') >>> query = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True" >>> adapters = machine.ExecQuery(query) >>> macs = [a.MACAddress for a in adapters] >>> for m in macs: print m ... 00:0E:0C:82:7A:33 00:14:22:0F:54:3C Christian http://www.dowski.com From john at fouhy.net Thu Mar 23 23:41:46 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 24 Mar 2006 10:41:46 +1200 Subject: [Tutor] Renaming computers In-Reply-To: <Pine.LNX.4.44.0603231320450.8656-100000@hkn.eecs.berkeley.edu> References: <43E7212300143752@mk-cpfrontend-3.mail.uk.tiscali.com> <Pine.LNX.4.44.0603231320450.8656-100000@hkn.eecs.berkeley.edu> Message-ID: <5e58f2e40603231441t6170dc02s@mail.gmail.com> On 24/03/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > Unfortunately, I really don't know Windows very well. I'd recommend > poking around with the win32 folks and see if it's possile to get/set the > computer name of a Windows machine. Microsoft has a repository of sample python scripts for automating WIndows: http://www.microsoft.com/technet/scriptcenter/scripts/python/default.mspx There may be something helpful there.. -- John. From francois.schnell at gmail.com Thu Mar 23 23:58:58 2006 From: francois.schnell at gmail.com (francois schnell) Date: Thu, 23 Mar 2006 23:58:58 +0100 Subject: [Tutor] Simple way for i18n ? In-Reply-To: <20060323113926.6e382c2d.klappnase@freenet.de> References: <13a83ca10603220841q4412dff0j@mail.gmail.com> <20060323113926.6e382c2d.klappnase@freenet.de> Message-ID: <13a83ca10603231458r11ae1308r@mail.gmail.com> Thanks both for your help, I managed to find one book which talk about i18n for Python: "Python in a Nutshell" (few pages for i18n) I've used sys.prefix on my ubuntu box to find the default directory and it works fine this way: http://www.flickr.com/photos/frenchy/116742621/ I've also done like you said: gettext.install(domain, localedir) and now it works fine also with a locale directory :) Then what I've got now is: - I log on the french version of Ubuntu I've got the french app version - I log on the UK version of Ubuntu I've got the original app version in English Now I'd like to be able to change language without loging out, change language, log in. Martelli says in his book that to set the default language for the app I just need to do: >>> os.environ.setdefault('LANG', 'fr_FR') and Python doesn't complain (but doesn't work) but if I then do: >>> print locale.getdefaultlocale() Python says : ('en_GB', 'utf-8') # meaning that really couldn't work ? How can I have my app in French even if I'm still in the GB version of Ubuntu (change the language for the app) ? I've also tried the "translation" way instead of the "install" way: if I do: gettext.install("myapp", localedir) #it translates in French when I'm in the French Ubuntu but if I do instead: gettext.translation("myapp", localedir, languages="fr_FR") #with the same localedir which worked before => Python complains: " gettext.translation("myapp", localedir, languages="fr_FR") File "/usr/lib/python2.4/gettext.py", line 480, in translation raise IOError(ENOENT, 'No translation file found for domain', domain) IOError: [Errno 2] No translation file found for domain: 'myapp' " I find it strange that "install" finds it but not "translation" (for the same localedir) ? Thanks in advance If you can help. francois On 23/03/06, Michael Lange <klappnase at freenet.de> wrote: > > On Wed, 22 Mar 2006 17:41:14 +0100 > "francois schnell" <francois.schnell at gmail.com> wrote: > > > Hello all, > > > > I wish to translate a Python script from English to French. I've read > the > > offical documentation (python.org doc) but I must admit that I'm lost > now > > ... > > I've found some simple explanations here but I can't make it work: > > http://karrigell.sourceforge.net/en/internationalization.htm > > > > Here's where I'm stuck: > > > > Let's imagine my app is: myapp.py > > -- > > import gettext > > _ = gettext.gettext > > > > print _("hello friends") > > print _("Bye Bye") > > --- > > > > Here are my folders on a windows box: > > > > C:\myappfolder\ > > -----------------------\Translations\francais\LC_MESSAGES > > > > My myapp.py is in myappfolder > > > > In this folder I've used pygettext.py to produce a messages.pot file => > I > > add the translation in it => I have a messages.po file. > > I then used msgfmt.py to produce messages.mo file. > > > > I then copied messages.po and messages.mo in LC_MESSAGES folder > > C:\myappfolder\ > > -----------------------\Translations\francais\LC_MESSAGES > > > > I now come back to myapp.py and add two lines: > > > > --- > > import gettext > > _ = gettext.gettext > > > > t=gettext.translation > ("messages","c:\myappfolder\Translations","francais") > > t.install() > > > > print _("hello friends") > > print _("Bye Bye") > > --- > > > > When I do that Python anwers: > > > > >>> > > Traceback (most recent call last): > > File "C:\myappfolder\myapp.py", line 4, in ? > > t=gettext.translation > > ("messages","c:\myappfolder\Translations","francais") > > File "C:\Python24\lib\gettext.py", line 456, in translation > > raise IOError(ENOENT, 'No translation file found for domain', > domain) > > IOError: [Errno 2] No translation file found for domain: 'messages' > > >>> > > > Hi Francois, > > not sure if it is different on windows, on linux I simply do: > > import gettext > gettext.install(domain, localedir) > > to install _() into my application's global namespace, > where localedir in your case was "c:\myappfolder\Translations". > The path that contains the french translation should be > "..\fr\LC_MESSAGES" instead of "..\francais\LC_MESSAGES" > I think (at least that is true on linux). > > I hope this helps > > Michael > > _______________________________________________ > 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/20060323/34d06b6e/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Mar 24 00:35:08 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Mar 2006 15:35:08 -0800 (PST) Subject: [Tutor] i need help please read (fwd) Message-ID: <Pine.LNX.4.44.0603231535001.13530-100000@hkn.eecs.berkeley.edu> [forwarding to tutor] ---------- Forwarded message ---------- Date: Thu, 23 Mar 2006 15:15:11 -0800 From: Tom Bachik <beamer30 at gmail.com> To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu> Subject: Re: [Tutor] i need help please read no it is not homework, i havent started y idea yet but my question for now basicly say how do you get python to make a box pop up? you no like ask you a question or somthin. if you still dont understand i mean how do you make a program were a box pops and does somthing when you run the preogram On 3/22/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > > > On Wed, 22 Mar 2006, Tom Bachik wrote: > > > ok does anyone know how to righ a script were a box pops up then if it > > goes over a number on the screen it pops up in the box become the input > > number so you can alter the number that popped up in the box? if you do > > can you right it and send it to me and if you cant doit all but know how > > i can do part will you please help me do it but remeber im new so i dont > > know to much > > Hi Tom, > > Frankly, I'm having a very hard time understanding your question. You are > going to have to try harder if you really want a good response from us. > I do not mean to be mean: I simply don't understand the terms you are > using; I'm having too hard enough time trying to parse your paragraph. My > mental model of what you are trying to ask is not strong. > > > If you want help, show us what you've tried so far, and we'll do what we > can to point you toward resources that can help you. If this is homework, > know that we can not do it for you. > > > If you'd like pointers to tutorial resources, you may find: > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > useful; this link contains most of the beginner-level tutorials. If you > go through and work through the problems in a tutorial, you should be > better equipped to play with Python. > > > You've probably already been pointed to the "How to Ask Questions the > Smart Way" page, but just in case, I'll be redundant and point it out: > > http://www.catb.org/~esr/faqs/smart-questions.html > > Reading it may help you write your question in a way that will make it > easier to approach and answer. > > From carroll at tjc.com Fri Mar 24 00:36:15 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 23 Mar 2006 15:36:15 -0800 (PST) Subject: [Tutor] efficient method to search between two lists In-Reply-To: <44227F66.4070700@tds.net> Message-ID: <Pine.LNX.4.44.0603231531420.21299-100000@violet.rahul.net> On Thu, 23 Mar 2006, Kent Johnson wrote: > This is more efficient than the original algorithm because it reduces > the size of the loops to the number of matching elements rather than the > whole number of elements. But if there are a large number of matches it > will still be a lot of loops! You're absolutely right. I posted that right before bedtime as I surrendered to this cold I have. I was just drifting off when I realized "well, that's no good: the real problem is still there." I blame my cold medication. That's my story, and I'm sticking to it. Still, it was fun to code. I'm just starting to get comfortable with list comprehensions, and this was a good learning exercise. From alan.gauld at freenet.co.uk Fri Mar 24 01:17:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 24 Mar 2006 00:17:41 -0000 Subject: [Tutor] Inner Class access to outer class attributes? References: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com><442306CF.6050001@tds.net> <9493d0340603231248vea1c237oc30457461c11d337@mail.gmail.com> Message-ID: <013001c19348$1a8e5b30$0b01a8c0@xp> > Hmmm, so every Sublocation object has a copy of the grouplocation > data? What happens if I come around & change something: Recall that in Python variables are simply references to objects. So every sublocation has a reference to the same groupLocation object > Would I need to (forgive me here if I get some terms wrong) use a > property (or a setter) & then loop over all the affected sublocations No, just change the groupLocation and the change will show up in every sublocation. FWIW this is how virtually all GUI frameworks operate, the top level window is passed as a parent to each widget. > Is there a better way to skin this cat? Or am I stuck with a) the > non-inner class design & it's ugly indexes The problem appears to be that you need to read a bit more about Pythons handling of variable names and objects. :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Mar 24 01:24:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 24 Mar 2006 00:24:09 -0000 Subject: [Tutor] Inner Class access to outer class attributes? References: <Pine.LNX.4.44.0603231400290.8656-100000@hkn.eecs.berkeley.edu> Message-ID: <013801c19349$028f83a0$0b01a8c0@xp> > Ooops. I should substitute the word "brackets" with "braces". I always > get those two mixed up. Don't worry Danny, in "real English - ie as spoken in England! - there is no distinction. There are {curly brackets}, (round brackets) and [square brackets]. You also get <angle brackets> and <<chevrons>> But braces are things to hold your trousers (or is that pants?) up... A parenthesis is any kind of grammatical pause, including commas, dashes etc. This was one of the frustrations of writing my book. I was even accused of being an illiterate by one reviewer who thought my 'ignorance' sufficient reason for the publisher to pull the book! :-) Britain and America - two lands divided by a common language. Alan G. From kent37 at tds.net Fri Mar 24 04:13:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Mar 2006 22:13:56 -0500 Subject: [Tutor] i need help please read (fwd) In-Reply-To: <Pine.LNX.4.44.0603231535001.13530-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0603231535001.13530-100000@hkn.eecs.berkeley.edu> Message-ID: <442363F4.5030109@tds.net> > From: Tom Bachik <beamer30 at gmail.com> > To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu> > Subject: Re: [Tutor] i need help please read > > no it is not homework, i havent started y idea yet but my question for now > basicly say how do you get python to make a box pop up? you no like ask you > a question or somthin. if you still dont understand i mean how do you make a > program were a box pops and does somthing when you run the preogram Probably the simplest way to pop up a dialog is with EasyGui: http://www.ferg.org/easygui/ Kent From kent37 at tds.net Fri Mar 24 04:45:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Mar 2006 22:45:22 -0500 Subject: [Tutor] [Fwd: Re: i need help please read (fwd)] Message-ID: <44236B52.20808@tds.net> Forwarding to the list, I don't know how to do this. -------- Original Message -------- Subject: Re: [Tutor] i need help please read (fwd) Date: Thu, 23 Mar 2006 19:43:07 -0800 From: Tom Bachik <beamer30 at gmail.com> To: Kent Johnson <kent37 at tds.net> References: <Pine.LNX.4.44.0603231535001.13530-100000 at hkn.eecs.berkeley.edu> <442363F4.5030109 at tds.net> thanks that was very helpful now i have one more question if you dont know how to do what im say its ok. i wondering if thers a way to get a box pop up were you can see through it lik you can see what inder the box in it do you see what im saying like if the letters google are under it you willsee google in it and be able to alter it if you put the box over a number just somethi for thought. On 3/23/06, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote: > From: Tom Bachik <beamer30 at gmail.com <mailto:beamer30 at gmail.com>> > To: Danny Yoo < dyoo at hkn.eecs.berkeley.edu <mailto:dyoo at hkn.eecs.berkeley.edu>> > Subject: Re: [Tutor] i need help please read > > no it is not homework, i havent started y idea yet but my question for now > basicly say how do you get python to make a box pop up? you no like ask you > a question or somthin. if you still dont understand i mean how do you make a > program were a box pops and does somthing when you run the preogram Probably the simplest way to pop up a dialog is with EasyGui: http://www.ferg.org/easygui/ Kent _______________________________________________ Tutor maillist - Tutor at python.org <mailto:Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor From john at fouhy.net Fri Mar 24 05:52:45 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 24 Mar 2006 16:52:45 +1200 Subject: [Tutor] Practice tomorrow In-Reply-To: <44237572.9050006@vuw.ac.nz> References: <5e58f2e40603231514x2ac29174x@mail.gmail.com> <5e58f2e40603231942w3fd651abh@mail.gmail.com> <9830887c0603231945lb4538b9lb09899cf901ad789@mail.gmail.com> <44237572.9050006@vuw.ac.nz> Message-ID: <5e58f2e40603232052q264b8fcax@mail.gmail.com> On 24/03/06, Naomi Guyer <naomi.guyer at vuw.ac.nz> wrote: > Till just before 1pm would be good. That way I can make the practice at > Martin Luckie at 1pm. As a lifetime member of the Vic flying disc club, I can write you a note excusing you from being late if you like :-) -- John. From smiles at worksmail.net Fri Mar 24 08:00:57 2006 From: smiles at worksmail.net (Smith) Date: Fri, 24 Mar 2006 01:00:57 -0600 Subject: [Tutor] [BULK] Tutor Digest, Vol 25, Issue 57 References: <mailman.11943.1143103942.27774.tutor@python.org> Message-ID: <017201c64f10$d9a6dbe0$2f2c4fca@csmith> | 7. Re: efficient method to search between two lists (Srinivas Iyyer) | |||| for i in list_b: | ... co = i.split('\t')[2] | ... items = da.get(co) ^ -----------------------------| | Are you sure that all co's are in da? One other thing that occurs to me from looking at your dictionary approach is that if you made a dictionary from the items of list_b like you did for list_a and then made a set of the keys from the union of both dictionaries and used that set (rather than co as above) to retrieve matches, this would automatically ensure that the match existed and it would group like items together. Right now (unless your list_b is sorted) you might encounter an item in list_b that has a match in da several times as you pass through list_b. /chris From klappnase at freenet.de Fri Mar 24 10:32:38 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 24 Mar 2006 10:32:38 +0100 Subject: [Tutor] Simple way for i18n ? In-Reply-To: <13a83ca10603231458r11ae1308r@mail.gmail.com> References: <13a83ca10603220841q4412dff0j@mail.gmail.com> <20060323113926.6e382c2d.klappnase@freenet.de> <13a83ca10603231458r11ae1308r@mail.gmail.com> Message-ID: <20060324103238.39474377.klappnase@freenet.de> On Thu, 23 Mar 2006 23:58:58 +0100 "francois schnell" <francois.schnell at gmail.com> wrote: > > Now I'd like to be able to change language without loging out, change > language, log in. > > Martelli says in his book that to set the default language for the app I > just need to do: > > >>> os.environ.setdefault('LANG', 'fr_FR') > > and Python doesn't complain (but doesn't work) but if I then do: > > >>> print locale.getdefaultlocale() > > Python says : ('en_GB', 'utf-8') # meaning that really couldn't work ? > > How can I have my app in French even if I'm still in the GB version of > Ubuntu (change the language for the app) ? > Hi Francois, I tried to do so with one of my apps (on Mandrake) and found that I have to change the LANGUAGE environment variable, changing LANG had no effect on this. >From the python gettext docs I found: If languages is not given, then the following environment variables are searched: LANGUAGE, LC_ALL, LC_MESSAGES, and LANG. So it looks like the easiest may be to do $ LANGUAGE=en_GB in the shell before you start your app. > I've also tried the "translation" way instead of the "install" way: > > if I do: > gettext.install("myapp", localedir) #it translates in French when I'm in the > French Ubuntu > but if I do instead: gettext.translation("myapp", localedir, > languages="fr_FR") #with the same localedir which worked before > => > Python complains: > " gettext.translation("myapp", localedir, languages="fr_FR") > File "/usr/lib/python2.4/gettext.py", line 480, in translation > raise IOError(ENOENT, 'No translation file found for domain', domain) > IOError: [Errno 2] No translation file found for domain: 'myapp' " > > I find it strange that "install" finds it but not "translation" (for the > same localedir) ? > I admit I nevered bothered to find out how to use gettext.translation() since gettext.install() works that fine for me. Maybe you should set "languages" to "fr" instead of "fr_FR" (just a guess though)? I hope this helps Michael From alan.gauld at freenet.co.uk Thu Mar 23 14:29:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 13:29:30 -0000 Subject: [Tutor] i need help please read (fwd) References: <Pine.LNX.4.44.0603231535001.13530-100000@hkn.eecs.berkeley.edu> Message-ID: <015d01c64e7d$d0d31210$0b01a8c0@xp> > no it is not homework, i havent started y idea yet but my question for now > basicly say how do you get python to make a box pop up? You can draw a box in many different ways, but its not clear what kind of box you want to pop-up, nor what you mean by pop-up. For example are you talking about a graphic of a box within a terminal application? Or are you talking about a picture of a box within a graphics application(a game say?) Or are you talking about a dialog box within a GUI? (And if so do you know how to produce the GUI in the first place?) One of the key things to learn about cpmputers and programming is that you have to express your requirements very very precisely. There are many ways to display a box, depending on what kind of box you mean. Here is one of the simplest: print ''' +-----------+ | | | | +-----------+ ''' Is that sufficient? > you no like ask you a question or somthin. Danny was simply asking for more information so that we can answer the question in a useful way. > if you still dont understand i mean how do you make a > program were a box pops and does somthing when you run the preogram The code I show above does almost exactly what you ask. A box pops up Now add this code print '\n' * 50 and it now does something - it disappears again! Do you have anything more specific in mind for what this box should do? And what kind of box you want? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld > On 3/22/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: >> >> >> >> On Wed, 22 Mar 2006, Tom Bachik wrote: >> >> > ok does anyone know how to righ a script were a box pops up then if it >> > goes over a number on the screen it pops up in the box become the input >> > number so you can alter the number that popped up in the box? if you do >> > can you right it and send it to me and if you cant doit all but know >> > how >> > i can do part will you please help me do it but remeber im new so i >> > dont >> > know to much >> >> Hi Tom, >> >> Frankly, I'm having a very hard time understanding your question. You >> are >> going to have to try harder if you really want a good response from us. >> I do not mean to be mean: I simply don't understand the terms you are >> using; I'm having too hard enough time trying to parse your paragraph. My >> mental model of what you are trying to ask is not strong. >> >> >> If you want help, show us what you've tried so far, and we'll do what we >> can to point you toward resources that can help you. If this is >> homework, >> know that we can not do it for you. >> >> >> If you'd like pointers to tutorial resources, you may find: >> >> http://wiki.python.org/moin/BeginnersGuide/NonProgrammers >> >> useful; this link contains most of the beginner-level tutorials. If you >> go through and work through the problems in a tutorial, you should be >> better equipped to play with Python. >> >> >> You've probably already been pointed to the "How to Ask Questions the >> Smart Way" page, but just in case, I'll be redundant and point it out: >> >> http://www.catb.org/~esr/faqs/smart-questions.html >> >> Reading it may help you write your question in a way that will make it >> easier to approach and answer. >> >> > > > From stvsmth at gmail.com Fri Mar 24 15:24:03 2006 From: stvsmth at gmail.com (stv) Date: Fri, 24 Mar 2006 09:24:03 -0500 Subject: [Tutor] Inner Class access to outer class attributes? In-Reply-To: <013001c19348$1a8e5b30$0b01a8c0@xp> References: <9493d0340603231217vf452941t8827426f4c310900@mail.gmail.com> <442306CF.6050001@tds.net> <9493d0340603231248vea1c237oc30457461c11d337@mail.gmail.com> <013001c19348$1a8e5b30$0b01a8c0@xp> Message-ID: <9493d0340603240624i7f5385ffsd051bc26875f4c48@mail.gmail.com> > The problem appears to be that you need to read a bit more > about Pythons handling of variable names and objects. :-) Or learn to spend a bit more time digesting the helpful advice given here ... between this & the searching between two lists thread the quality of advice has been excellent. I should have used my brain a bit more before hitting send. I have a pretty good grasp of refereces vs copies, and a few seconds of time with the interactive interpreter would have clearly shown that I was dealing with references. I'm digesting all the advice ... I think I have what I need & I appreciate everyone's thoughts. I hope, at least, my questions & first drafts have been helpful for others reading along. From benvinger at yahoo.co.uk Fri Mar 24 17:14:25 2006 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Fri, 24 Mar 2006 16:14:25 +0000 (GMT) Subject: [Tutor] TypeError: dict objects are unhashable Message-ID: <20060324161425.58288.qmail@web25809.mail.ukl.yahoo.com> Hello I want to create a dictionary (from SQL usernames) of the format: accounts = { ('psmit', '123456'): 'psmit', ('rmatt', 'mypass'): 'rmatt', } So I have: accounts = {} UserCursor.execute(sqlstr) rows = UserCursor.fetchall() UserConn.commit() for row in rows: U = row['User'] P = row['Password'] InnerDict = {} InnerDict[U] = P accounts[InnerDict] = U But I get: TypeError: dict objects are unhashable Unfortunately, I just can't see what I'm doing wrong Thanks ___________________________________________________________ NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! http://uk.cars.yahoo.com/ From kermit at polaris.net Fri Mar 24 17:27:26 2006 From: kermit at polaris.net (Kermit Rose) Date: Fri, 24 Mar 2006 11:27:26 -0500 (Eastern Standard Time) Subject: [Tutor] urlopen: where are the results? References: <00f201c19307$52692080$0b01a8c0@xp> Message-ID: <44241DEE.000007.03456@YOUR-4105E587B6> From: Alan Gauld Date: 03/23/06 11:34:33 To: Kermit Rose; Danny Yoo Cc: tutor at python.org Subject: Re: [Tutor] urlopen: where are the results? Did you look at the url2lib documentation? **** I thought I had, but I did not see the examples. I did not know enough to make sense of the documentation. So I thought that I would just try running the urlopen and see what happened ***** >>> import urllib2 >>> f = urllib2.urlopen('http://www.python.org/') >>> print f.read(100) <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <?xml-stylesheet href="./css/ht2html ======================== Which shows how to open and read a web page. ****** Thanks. I've experimented with the code you've shown me. I feel comfortable with it now. ****** And if you went to the index and click 'f' you will find a link to 'file object' which gives you the list of methods you can call on file objects. (Admittedly not all of them work on file-like objects, but most will) ********** How do I get to the index?? ***** I admit learning how to use the Python document set is not intuitive but it's worth persevering and the Module Index is invaluable. ***** Eventually I will become expert. Thanks for your help. Kermit < kermit at polaris.net > ***** Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060324/1a29c2fd/attachment.htm From kent37 at tds.net Fri Mar 24 17:31:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Mar 2006 11:31:03 -0500 Subject: [Tutor] TypeError: dict objects are unhashable In-Reply-To: <20060324161425.58288.qmail@web25809.mail.ukl.yahoo.com> References: <20060324161425.58288.qmail@web25809.mail.ukl.yahoo.com> Message-ID: <44241EC7.6030006@tds.net> Ben Vinger wrote: > Hello > > I want to create a dictionary (from SQL usernames) of > the format: > accounts = { > ('psmit', '123456'): 'psmit', > ('rmatt', 'mypass'): 'rmatt', > } > > So I have: > accounts = {} > UserCursor.execute(sqlstr) > rows = UserCursor.fetchall() > UserConn.commit() > for row in rows: > U = row['User'] > P = row['Password'] > InnerDict = {} > InnerDict[U] = P > accounts[InnerDict] = U > > But I get: > TypeError: dict objects are unhashable > Unfortunately, I just can't see what I'm doing wrong You are trying to use a dictionary as the key to your dictionary. This doesn't work - dicts can't be used as dict keys, which is what the error message is trying to tell you. Instead of accounts = { ('psmit', '123456'): 'psmit', ('rmatt', 'mypass'): 'rmatt', } your code tries to make accounts = { {'psmit': '123456'}: 'psmit', {'rmatt': 'mypass'}: 'rmatt', } try this accounts[U, P] = U though I'm not sure why you use a dict instead of a set here, since the value is contained in the key. Kent From tim.golden at viacom-outdoor.co.uk Fri Mar 24 17:35:33 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 24 Mar 2006 16:35:33 -0000 Subject: [Tutor] TypeError: dict objects are unhashable Message-ID: <9A28C052FF32734DACB0A288A3533991044D2670@vogbs009.gb.vo.local> [Ben Vinger] | I want to create a dictionary (from SQL usernames) of | the format: | accounts = { | ('psmit', '123456'): 'psmit', | ('rmatt', 'mypass'): 'rmatt', | } Although possible, this structure looks a little topsy-turvy: you're keying the dictionary on the username & password, and the resultant value is the username? I suspect you want to end up the other way round? | So I have: | accounts = {} | UserCursor.execute(sqlstr) | rows = UserCursor.fetchall() | UserConn.commit() This commit looks unnecessary, unless you have a truly strange SQL engine. You're only selecting.. at least I assume you are since you haven't provided the sqlstr. | for row in rows: | U = row['User'] | P = row['Password'] | InnerDict = {} | InnerDict[U] = P | accounts[InnerDict] = U | | But I get: | TypeError: dict objects are unhashable | Unfortunately, I just can't see what I'm doing wrong First things first: hashing refers to one of many techniques of generating a unique number from some other object. Python uses this number as a sort of sparse index for its dictionary structure. Now for the lookup to be meaningful, an object must always hash to the same value, otherwise you won't find it the next time round. Certain Python objects are known as mutable -- their contents can change -- and these objects obviously won't have a constant hash value. A dictionary is one of these (a list is another) and that's why you can't use them as keys in a dictionary. OK, now we've got all that out of the way, I'm not entirely sure why you're even trying to do that. To achieve the structure you outlined above, you code wants to do something like this: U = row['User'] P = row['Password'] accounts[(U, P)] = U where (U, P) is a *tuple*, not a dictionary which holds U and P together in one structure. As I mentioned above, I rather suspect you want something like: accounts[U] = (U, P) or even accounts[U] = row because it won't cost you anything to hang on to the whole row, and it might be useful. But obviously you know best what your own application needs. Hope that helps TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From hugonz-lists at h-lab.net Fri Mar 24 17:37:13 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 24 Mar 2006 10:37:13 -0600 Subject: [Tutor] TypeError: dict objects are unhashable In-Reply-To: <20060324161425.58288.qmail@web25809.mail.ukl.yahoo.com> References: <20060324161425.58288.qmail@web25809.mail.ukl.yahoo.com> Message-ID: <44242039.1080200@h-lab.net> Ben Vinger wrote: > But I get: > TypeError: dict objects are unhashable > Unfortunately, I just can't see what I'm doing wrong > InnerDict = {} InnerDict[U] = P accounts[InnerDict] = U Your logic is not right somewhere around this. I do not have a lot of context, nor the full error message, but what it says is that you *cannot* use a dictionary as a key for a dictionary. In this line: accounts[InnerDict] = U this is what you're doing. You should be using a dictionary with the tuple, something like this: InnerDict = {} InnerDict[U] = P accounts[(U, P])] = U Again, I do not wuite get why you want to do it like that. If you could explain a bit more to us.... Hugo From dyoo at hkn.eecs.berkeley.edu Fri Mar 24 18:05:53 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Mar 2006 09:05:53 -0800 (PST) Subject: [Tutor] i need help please read (fwd) In-Reply-To: <015d01c64e7d$d0d31210$0b01a8c0@xp> Message-ID: <Pine.LNX.4.44.0603240857090.12639-100000@hkn.eecs.berkeley.edu> > > you no like ask you a question or somthin. > > Danny was simply asking for more information so that we can > answer the question in a useful way. Hi Alan, But you're misinterpreting that part of message. Let's look back at the message: """no it is not homework, i havent started y idea yet but my question for now basicly say how do you get python to make a box pop up? you no like ask you a question or somthin. if you still dont understand i mean how do you make a program were a box pops and does somthing when you run the preogram""" Try to ignore the misspellings for the moment. I'm think he's really trying to say: How do you get Python to make a dialog box pop up? You know, like asking a question or something. How do you connect the buttons up so it does something when you press it? His "you no like ask you a question" was certainly not meant to be interpreted as "You don't like to be asked questions?" These kinds of language misinterpretations is exactly the reason why careful writing matters. From nospamformeSVP at gmail.com Fri Mar 24 18:47:08 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Fri, 24 Mar 2006 12:47:08 -0500 Subject: [Tutor] function signatures for callbacks In-Reply-To: <Pine.LNX.4.44.0603211330100.26507-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0603211303010.26507-100000@hkn.eecs.berkeley.edu> <Pine.LNX.4.44.0603211330100.26507-100000@hkn.eecs.berkeley.edu> Message-ID: <e01bb3$43s$1@sea.gmane.org> Danny: Thanks for this, I think that I can use this idea. When I first read your response I did not see how it helped me, but now I realise that it allows me to add some context to the exception message. I don't suppose that I can change the traceback to point at the definition of f2 instead of shout() but I can give a better hint to the user at why this went wrong. Don. From alan.gauld at freenet.co.uk Thu Mar 23 19:20:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 18:20:09 -0000 Subject: [Tutor] i need help please read (fwd) References: <Pine.LNX.4.44.0603240857090.12639-100000@hkn.eecs.berkeley.edu> Message-ID: <017c01c64ea6$6b546af0$0b01a8c0@xp> > Try to ignore the misspellings for the moment. I'm think he's really > trying to say: > > How do you get Python to make a dialog box pop up? You know, like > asking a question or something. How do you connect the buttons up so > it does something when you press it? Aha! Now I see it. I assumed the English was poor, in fact it was just the spelling! (And this from the world's worst typist! :-) Apologies all round. In that case I guess I'd point him at the simpledialogs module in Tkinter. Alan G. From alan.gauld at freenet.co.uk Thu Mar 23 19:24:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 18:24:34 -0000 Subject: [Tutor] urlopen: where are the results? References: <00f201c19307$52692080$0b01a8c0@xp> <44241DEE.000007.03456@YOUR-4105E587B6> Message-ID: <019301c64ea7$0963d3c0$0b01a8c0@xp> > >And if you went to the index and click 'f' you will find a link > How do I get to the index?? There should be a link at the top of each document page HTH, Alan G. From alan.gauld at freenet.co.uk Thu Mar 23 19:28:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 23 Mar 2006 18:28:48 -0000 Subject: [Tutor] TypeError: dict objects are unhashable References: <20060324161425.58288.qmail@web25809.mail.ukl.yahoo.com> Message-ID: <019d01c64ea7$a0ab6590$0b01a8c0@xp> Ben, Others have addressed the cause of the error, but... > accounts = {} > UserCursor.execute(sqlstr) > rows = UserCursor.fetchall() > UserConn.commit() > for row in rows: > U = row['User'] > P = row['Password'] > InnerDict = {} > InnerDict[U] = P > accounts[InnerDict] = U > > But I get: > TypeError: dict objects are unhashable It really helps if you post the whole error message since it will highlight the actual line causing the problem. Please post the whole stacktrace from the message in future. Alan G. From dyoo at hkn.eecs.berkeley.edu Fri Mar 24 19:59:17 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Mar 2006 10:59:17 -0800 (PST) Subject: [Tutor] function signatures for callbacks In-Reply-To: <e01bb3$43s$1@sea.gmane.org> Message-ID: <Pine.LNX.4.44.0603241054160.12984-100000@hkn.eecs.berkeley.edu> On Fri, 24 Mar 2006, Don Taylor wrote: > When I first read your response I did not see how it helped me, but now > I realise that it allows me to add some context to the exception message. > > I don't suppose that I can change the traceback to point at the > definition of f2 instead of shout() but I can give a better hint to the > user at why this went wrong. Hi Don, Actually, adding something like this would also be possible. ########################################################### ## Pseudocode for sending 'x' to every listener (untested) class CallbackError(Exception): pass for l in self.listeners: try: l(x) except Exception, e: raise CallbackError, ("%s failed" % l.__name__, e) ########################################################### That is, we can wrap an exception handler around calls to the callback function, and if something bad happens, return enough of the context to make the error message reasonable. We can then combine this technique with the way that shout() captured exceptions, in order to hide our module's internals. From nospamformeSVP at gmail.com Fri Mar 24 21:29:56 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Fri, 24 Mar 2006 15:29:56 -0500 Subject: [Tutor] function signatures for callbacks In-Reply-To: <Pine.LNX.4.44.0603241054160.12984-100000@hkn.eecs.berkeley.edu> References: <e01bb3$43s$1@sea.gmane.org> <Pine.LNX.4.44.0603241054160.12984-100000@hkn.eecs.berkeley.edu> Message-ID: <e01ksb$9gt$1@sea.gmane.org> Danny Yoo wrote: > > ########################################################### > ## Pseudocode for sending 'x' to every listener (untested) > class CallbackError(Exception): > pass > > for l in self.listeners: > try: > l(x) > except Exception, e: > raise CallbackError, ("%s failed" % l.__name__, e) > ########################################################### > Danny: Ok I tried this and it is good. I don't think that I need the _internal_shout anymore as this code already wraps the exception handling and I can decide what I want to display in the above except statement. Unless I am missing something? Thanks again, Don. From oasf2004 at yahoo.com Fri Mar 24 22:02:45 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Fri, 24 Mar 2006 13:02:45 -0800 (PST) Subject: [Tutor] What is wrong my code? Message-ID: <20060324210245.72485.qmail@web60018.mail.yahoo.com> Hello: Could anyone, please, let me know what is wrong with my code (shown below)? I am getting a runtime error. Thanks! Hoffmann ps: The code: #!/usr/bin/python import math print '''This program calculates the lenght of the hypotenuse of a right triangle given the lenghts of the two legs as parameters.\n''' leg1 = raw_input('Enter the first leg of the triangle: ') leg2 = raw_input('Enter the second leg of the triangle: ') result = hypotenuse(leg1, leg2) print 'The hypotenuse of the triangle is', result def hypotenuse(x, y): result = math.sqrt(x**2 + y**2) return result __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Fri Mar 24 22:42:34 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Mar 2006 13:42:34 -0800 (PST) Subject: [Tutor] function signatures for callbacks In-Reply-To: <e01ksb$9gt$1@sea.gmane.org> Message-ID: <Pine.LNX.4.44.0603241340280.15631-100000@hkn.eecs.berkeley.edu> > Ok I tried this and it is good. > > I don't think that I need the _internal_shout anymore as this code > already wraps the exception handling and I can decide what I want to > display in the above except statement. > > Unless I am missing something? Yup, nope. *grin* That was just there to show that if we rethrow an exception, we can help hide the internals of our black boxes. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Fri Mar 24 22:45:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Mar 2006 13:45:25 -0800 (PST) Subject: [Tutor] What is wrong my code? In-Reply-To: <20060324210245.72485.qmail@web60018.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0603241342480.15631-100000@hkn.eecs.berkeley.edu> > leg1 = raw_input('Enter the first leg of the triangle: > ') > leg2 = raw_input('Enter the second leg of the > triangle: ') Hi Hoffmann, leg1 and leg2 here are strings, because raw_input() is guaranteed to return strings. You'll want to do something to turn those strings into numbers, since the hypotenuse() function: > result = hypotenuse(leg1, leg2) is going to break on non-numeric input. I think you'll find the float() function useful: it's a function that can take strings and return floating-point numbers. For example: ###### >>> float("3.1415926") 3.1415926000000001 >>> float("7") 7.0 ###### Good luck to you! From mwhite3 at ttsd.k12.or.us Fri Mar 24 22:34:25 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Fri, 24 Mar 2006 13:34:25 -0800 Subject: [Tutor] What is wrong my code? In-Reply-To: <20060324210245.72485.qmail@web60018.mail.yahoo.com> References: <20060324210245.72485.qmail@web60018.mail.yahoo.com> Message-ID: <20060324213425.GE11313@ttsd.k12.or.us> Hi Hoffman, Include the definition for hypotenuse() before it is called in your script. Also, please include the full output from the error next time. It helps with figuring out the exact problem. :) -mtw On Fri, Mar 24, 2006 at 01:02:45PM -0800, Hoffmann (oasf2004 at yahoo.com) wrote: > Hello: > > Could anyone, please, let me know what is wrong with > my code (shown below)? I am getting a runtime error. > Thanks! > Hoffmann > ps: The code: > > #!/usr/bin/python > > import math > > print '''This program calculates the lenght of the > hypotenuse of a right triangle > given the lenghts of the two legs as > parameters.\n''' > > leg1 = raw_input('Enter the first leg of the triangle: > ') > leg2 = raw_input('Enter the second leg of the > triangle: ') > > result = hypotenuse(leg1, leg2) > > print 'The hypotenuse of the triangle is', result > > def hypotenuse(x, y): > result = math.sqrt(x**2 + y**2) > return result > > __________________________________________________ > 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 -- 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 oasf2004 at yahoo.com Fri Mar 24 23:22:45 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Fri, 24 Mar 2006 14:22:45 -0800 (PST) Subject: [Tutor] What is wrong my code? In-Reply-To: <Pine.LNX.4.44.0603241342480.15631-100000@hkn.eecs.berkeley.edu> Message-ID: <20060324222245.10493.qmail@web60013.mail.yahoo.com> --- Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > > leg1 = raw_input('Enter the first leg of the > triangle: > > ') > > leg2 = raw_input('Enter the second leg of the > > triangle: ') > > Hi Hoffmann, > > leg1 and leg2 here are strings, because raw_input() > is guaranteed to > return strings. > > > You'll want to do something to turn those strings > into numbers, since the > hypotenuse() function: > > > result = hypotenuse(leg1, leg2) > > is going to break on non-numeric input. > > > I think you'll find the float() function useful: > it's a function that can > take strings and return floating-point numbers. For > example: > > ###### > >>> float("3.1415926") > 3.1415926000000001 > >>> float("7") > 7.0 > ###### > > > Good luck to you! > > Hello Folks, Thanks for the hints. Please, see below, a new version. What do you think about this new version? Hoffmann ps: The new version: #!/usr/bin/python import math print '''This program calculates the lenght of the hypotenuse of a right triangle given the lenghts of the two legs as parameters.\n''' leg1 = input('Enter the first leg of the triangle: ') leg2= input('Enter the second leg of the triangle: ') def hypotenuse(x, y): result = math.sqrt(x**2 + y**2) return result result = hypotenuse(leg1, leg2) print 'The hypotenuse of the triangle is', result __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Fri Mar 24 23:29:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 24 Mar 2006 22:29:31 -0000 Subject: [Tutor] What is wrong my code? References: <20060324210245.72485.qmail@web60018.mail.yahoo.com> Message-ID: <002501c64f92$6c11e750$0b01a8c0@xp> > Could anyone, please, let me know what is wrong with > my code (shown below)? I am getting a runtime error. For future reference can you post the error as well as the code. It helps a lot in figuring out the problem. Alan G. From dyoo at hkn.eecs.berkeley.edu Fri Mar 24 23:45:25 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Mar 2006 14:45:25 -0800 (PST) Subject: [Tutor] What is wrong my code? In-Reply-To: <20060324222245.10493.qmail@web60013.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0603241429220.26834-100000@hkn.eecs.berkeley.edu> > #!/usr/bin/python > > import math > > print '''This program calculates the lenght of the > hypotenuse of a right triangle > given the lenghts of the two legs as > parameters.\n''' > > leg1 = input('Enter the first leg of the triangle: ') > leg2 = input('Enter the second leg of the triangle: ') Hi Hoffmann, Although this works, the use of input() is a little less safe than using raw_input(), and input gives slightly unhappy error messages on certain kinds of input. For example: ###### >>> input("number? ") number? four Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'four' is not defined ###### That is, certain kinds of input will give us things like NameError. But here's another example where input() can do funny things: ###### >>> def test(): ... x = input("x?: ") ... y = input("y?: ") ... print x, y ... >>> test() x?: 3 y?: x 3 3 ###### Although this is "cute", it shows that it's also terribly hard to figure out what's going on with input() sometimes. *grin* So because of this, I'd recommend using raw_input() instead: even though you have to do a little more work to get numbers out of it, it's ultimately a bit saner and more reliable to use than input(). > def hypotenuse(x, y): > result = math.sqrt(x**2 + y**2) > return result There's no need to do the assignment to 'result' here. We can return the value straightaway: ################################# def hypotenuse(x, y): return math.sqrt(x**2 + y**2) ################################# Although it's "obvious", it might also help to add some kind of documentation string explaining hypotenuse, and what it takes in and returns. Something like: ################################################################### def hypotenuse(x, y): """hypotenuse: number number -> number hypotenuse() returns the length of the hypotenuse of a right triangle with legs of length x and y.""" # ... rest of function body ################################################################### might seem like overkill for such a simple function, but the habit is a good one. In an ideal world, all functions would have some kind of comment like that, to communicate the human intent to the reader. I admit that I often just hack functions up without saying what they mean... but I do feel guilty afterwards. *grin* I hope this helps! From oasf2004 at yahoo.com Sat Mar 25 00:19:50 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Fri, 24 Mar 2006 15:19:50 -0800 (PST) Subject: [Tutor] What is wrong my code? In-Reply-To: <Pine.LNX.4.44.0603241429220.26834-100000@hkn.eecs.berkeley.edu> Message-ID: <20060324231950.45050.qmail@web60020.mail.yahoo.com> --- Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > #!/usr/bin/python > > > > import math > > > > print '''This program calculates the lenght of the > > hypotenuse of a right triangle > > given the lenghts of the two legs as > > parameters.\n''' > > > > leg1 = input('Enter the first leg of the triangle: > ') > > leg2 = input('Enter the second leg of the > triangle: ') > > > Hi Hoffmann, > > Although this works, the use of input() is a little > less safe than using > raw_input(), and input gives slightly unhappy error > messages on certain > kinds of input. For example: > > ###### > >>> input("number? ") > number? four > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "<string>", line 1, in <module> > NameError: name 'four' is not defined > ###### > > That is, certain kinds of input will give us things > like NameError. > > > But here's another example where input() can do > funny things: > > ###### > >>> def test(): > ... x = input("x?: ") > ... y = input("y?: ") > ... print x, y > ... > >>> test() > x?: 3 > y?: x > 3 3 > ###### > > Although this is "cute", it shows that it's also > terribly hard to figure > out what's going on with input() sometimes. *grin* > > So because of this, I'd recommend using raw_input() > instead: even though > you have to do a little more work to get numbers out > of it, it's > ultimately a bit saner and more reliable to use than > input(). > > > > > def hypotenuse(x, y): > > result = math.sqrt(x**2 + y**2) > > return result > > There's no need to do the assignment to 'result' > here. We can return the > value straightaway: > > ################################# > def hypotenuse(x, y): > return math.sqrt(x**2 + y**2) > ################################# > > > > Although it's "obvious", it might also help to add > some kind of > documentation string explaining hypotenuse, and what > it takes in > and returns. Something like: > > ################################################################### > def hypotenuse(x, y): > """hypotenuse: number number -> number > hypotenuse() returns the length of the > hypotenuse of a right > triangle with legs of length x and y.""" > # ... rest of function body > ################################################################### > > might seem like overkill for such a simple function, > but the habit is a > good one. > > > In an ideal world, all functions would have some > kind of comment like > that, to communicate the human intent to the reader. > I admit that I often > just hack functions up without saying what they > mean... but I do feel > guilty afterwards. *grin* > > > I hope this helps! > Hi Danny, I did like your comments about input and raw_input. What about if I use on my program: leg1 = int( raw_input('Enter the first leg of the triangle: ') ) leg2= int( raw_input('Enter the second leg of the triangle: ') ) What do you think? This is better/safer, right? Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Sat Mar 25 01:22:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Mar 2006 16:22:52 -0800 (PST) Subject: [Tutor] What is wrong my code? In-Reply-To: <20060324231950.45050.qmail@web60020.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0603241614280.18797-100000@hkn.eecs.berkeley.edu> > I did like your comments about input and raw_input. > What about if I use on my program: > > leg1 = int( raw_input('Enter the first leg of the > triangle: ') ) > leg2= int( raw_input('Enter the second leg of the > triangle: ') ) > > What do you think? This is better/safer, right? Hi Hoffmann, Yes, this works fine. There's a little bit of copy-and-paste here that we can improve: we can write a helper function to handle the raw_input() andint() conversion stuff: ###### def read_number(prompt): """prompts the user for numeric input, and returns a number.""" # ... ###### By doing this, we isolate the weirdness of calling int(raw_input(...)) to a single place, and throughout the rest of our program, we can use our new helper function read_number(). Concretely: if we had such a function, then we can say: ###### leg1 = read_number('Enter the first leg of the triangle: ') leg2 = read_number('Enter the second leg of the triangle: ') ###### When we program a bit more, we start to accumulate a bunch of helper functions to deal with the little details. Don't be afraid to make such helper functions whenever you're about to copy-and-paste. (Doing this also makes certain improvements more easy to do. For example, one possible thing you might like to try, once you learn a little more Python, is to improve read_number() so it persists on asking for a number until the noncommittal user gives a good number! *grin*) From smiles at worksmail.net Fri Mar 24 16:21:25 2006 From: smiles at worksmail.net (Smith) Date: Fri, 24 Mar 2006 09:21:25 -0600 Subject: [Tutor] efficient method to search between two lists Message-ID: <002401c64f56$c1d150e0$04000100@csmith> Srinivas Iyyer wrote: | |||| for i in list_b: | ... co = i.split('\t')[2] | ... items = da.get(co) ^ -----------------------------| | Are you sure that all co's are in da? One other thing that occurs to me from looking at your dictionary approach is that if you made a dictionary from the items of list_b like you did for list_a and then made a set of the keys from the union of both dictionaries and used that set (rather than co as above) to retrieve matches, this would automatically ensure that the match existed and it would group like items together. Right now (unless your list_b is sorted) you might encounter an item in list_b that has a match in da several times as you pass through list_b. /chris From iqbala-python at qwestip.net Sat Mar 25 04:45:58 2006 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Fri, 24 Mar 2006 22:45:58 -0500 Subject: [Tutor] Authen::ACE Message-ID: <20060325034558.GA21439@qwestip.net> Hi All Does anyone know if there is any python module similar to Authen::ACE available that I can use to authenticate against a RSA SecurID server? Also, what would be a good irc chnl where python folks hang around? Thanks -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu "..there are two kinds of people: those who work and those who take the credit...try to be in the first group;...less competition there." - Indira Gandhi From smiles at worksmail.net Fri Mar 24 16:21:25 2006 From: smiles at worksmail.net (Smith) Date: Fri, 24 Mar 2006 09:21:25 -0600 Subject: [Tutor] efficient method to search between two lists Message-ID: <002401c64f56$c1d150e0$04000100@csmith> Srinivas Iyyer wrote: | |||| for i in list_b: | ... co = i.split('\t')[2] | ... items = da.get(co) ^ -----------------------------| | Are you sure that all co's are in da? One other thing that occurs to me from looking at your dictionary approach is that if you made a dictionary from the items of list_b like you did for list_a and then made a set of the keys from the union of both dictionaries and used that set (rather than co as above) to retrieve matches, this would automatically ensure that the match existed and it would group like items together. Right now (unless your list_b is sorted) you might encounter an item in list_b that has a match in da several times as you pass through list_b. /chris From kabads at gmail.com Sat Mar 25 09:05:16 2006 From: kabads at gmail.com (Adam Cripps) Date: Sat, 25 Mar 2006 08:05:16 +0000 Subject: [Tutor] Mysql BLOB strangeness? In-Reply-To: <441D9744.4050605@daviesinc.com> References: <c7ff38550603170615p292b01d0g6deefc7adbf04184@mail.gmail.com> <441C6A1F.5080606@daviesinc.com> <c7ff38550603190020i2e42eaa1q8f00473a0a56d0b5@mail.gmail.com> <441D9744.4050605@daviesinc.com> Message-ID: <c7ff38550603250005n5fb833fbje7a81b769e57c7fb@mail.gmail.com> On 3/19/06, Brian Gustin <brian at daviesinc.com> wrote: > OK so I guess you know what you need to do now :) something like this > perhaaps : > > (modified your original code) > > reportlist = query(reportquery) > mystring = '<p>' > for row in reportlist: > id = row[0] > title = row[1] > content = row[2] > published = row[3] > mystring = mystring+id+"\t"+title+"\t"+content+"\t"+published+"</p>" > > print mystring > > should get you the data - you may want to force the values to str() type > just in case.. anyhow.. when you append an array to an array, you > have a multi-dimensional array, so when you iterate, you need to handle > two arrays, in essence.. what python is doing is just what it told you > to do - convert the multi dimensional list object into a string and > print it. :) , therefore, the output would be > array("listitem","listitem") basically :) you need to extract your list > elements and convert those to strings, then you can work with the whole > as a string :) otherwise, This is similar to my original code - no? I cannot see anything that dissimilar from my original code. I am attempting to extract the array within the array through the use of content[itr][1]. > do print reportlist (without the str() stuff) and you will print out > the entire list of data so you can see what you will be working with :) Switching to a TEXT field in MySQL worked instantly. I think I understand the idea behind the iteration (almost iteration inside iteration). I did attempt it, but for some reason I couldn't get it to work. Perhaps I'm not at that level yet. Thanks guys. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kabads at gmail.com Sat Mar 25 09:11:06 2006 From: kabads at gmail.com (Adam Cripps) Date: Sat, 25 Mar 2006 08:11:06 +0000 Subject: [Tutor] Cleaning up input before inserting into MySQL. Message-ID: <c7ff38550603250011g73afe893ub0b485cb4c8bcc5c@mail.gmail.com> I have a textarea which collects text and other characters. I'm attempting to put this into a MySQL database. See code at [1]. However, if I use any type of quotes (either single or double) then it prematurely closes the SQL statement, and I get an errror: ProgrammingError: (1064, "You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'test'', '44')' at line 1") How do I insert these quotes without it closing the SQL statement prematurely? TIA Adam [1] def insert(statement): mycursor.execute(statement) statement = """insert into report (title, content, author) values ('""" + str(times.getvalue('title')) + """', '""" + str(times.getvalue('content')) + """', '""" + str(times.getvalue('pupil')) + """')""" insert(statement) -- http://www.monkeez.org PGP key: 0x7111B833 From francois.schnell at gmail.com Sat Mar 25 10:47:51 2006 From: francois.schnell at gmail.com (francois schnell) Date: Sat, 25 Mar 2006 10:47:51 +0100 Subject: [Tutor] Simple way for i18n ? In-Reply-To: <20060324103238.39474377.klappnase@freenet.de> References: <13a83ca10603220841q4412dff0j@mail.gmail.com> <20060323113926.6e382c2d.klappnase@freenet.de> <13a83ca10603231458r11ae1308r@mail.gmail.com> <20060324103238.39474377.klappnase@freenet.de> Message-ID: <13a83ca10603250147t67957d41r@mail.gmail.com> Hello Micheal, I've changed LANGUAGE in the shell , it worked at the beginning and then it stopped working ... Also os.environ.setdefault method still has no effect. I begin to wonder if it's specific to my distro (Ubuntu Breezy). Anyway I managed to use "translation" but if I give None for languages (or nothing) he gives back an IOError. I'm finaly using a mix of "install" and "translation" through an exception handling and I can also change the language on the fly in the app. It works but it's probably not very "academic" :) http://www.flickr.com/photos/frenchy/117229913/ Thanks francois On 24/03/06, Michael Lange <klappnase at freenet.de> wrote: > > On Thu, 23 Mar 2006 23:58:58 +0100 > "francois schnell" <francois.schnell at gmail.com> wrote: > > > > > Now I'd like to be able to change language without loging out, change > > language, log in. > > > > Martelli says in his book that to set the default language for the app I > > just need to do: > > > > >>> os.environ.setdefault('LANG', 'fr_FR') > > > > and Python doesn't complain (but doesn't work) but if I then do: > > > > >>> print locale.getdefaultlocale() > > > > Python says : ('en_GB', 'utf-8') # meaning that really couldn't work ? > > > > How can I have my app in French even if I'm still in the GB version of > > Ubuntu (change the language for the app) ? > > > > Hi Francois, > > I tried to do so with one of my apps (on Mandrake) and found that I have > to change > the LANGUAGE environment variable, changing LANG had no effect on this. > >From the python gettext docs I found: > > If languages is not given, then the following environment variables > are searched: LANGUAGE, LC_ALL, LC_MESSAGES, and LANG. > > So it looks like the easiest may be to do > > $ LANGUAGE=en_GB > > in the shell before you start your app. > > > I've also tried the "translation" way instead of the "install" way: > > > > if I do: > > gettext.install("myapp", localedir) #it translates in French when I'm in > the > > French Ubuntu > > but if I do instead: gettext.translation("myapp", localedir, > > languages="fr_FR") #with the same localedir which worked before > > => > > Python complains: > > " gettext.translation("myapp", localedir, languages="fr_FR") > > File "/usr/lib/python2.4/gettext.py", line 480, in translation > > raise IOError(ENOENT, 'No translation file found for domain', > domain) > > IOError: [Errno 2] No translation file found for domain: 'myapp' " > > > > I find it strange that "install" finds it but not "translation" (for the > > same localedir) ? > > > > I admit I nevered bothered to find out how to use gettext.translation() > since gettext.install() > works that fine for me. Maybe you should set "languages" to "fr" instead > of "fr_FR" (just a guess though)? > > I hope this helps > > Michael > _______________________________________________ > 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/20060325/30e81b0f/attachment.htm From kent37 at tds.net Sat Mar 25 12:46:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Mar 2006 06:46:56 -0500 Subject: [Tutor] Cleaning up input before inserting into MySQL. In-Reply-To: <c7ff38550603250011g73afe893ub0b485cb4c8bcc5c@mail.gmail.com> References: <c7ff38550603250011g73afe893ub0b485cb4c8bcc5c@mail.gmail.com> Message-ID: <44252DB0.5050600@tds.net> Adam Cripps wrote: > I have a textarea which collects text and other characters. I'm > attempting to put this into a MySQL database. See code at [1]. > > However, if I use any type of quotes (either single or double) then it > prematurely closes the SQL statement, and I get an errror: > > ProgrammingError: (1064, "You have an error in your SQL syntax. Check > the manual that corresponds to your MySQL server version for the right > syntax to use near 'test'', '44')' at line 1") You should always pass parameters to cursor.execute() rather than building a SQL statement string yourself. Then the database will correctly escape any special characters in the values. This has a number of benefits: - It works correctly without any effort on your part to escape quotes, etc - It protects against SQL injection attacks, where one of the values is maliciously constructed to damage the database - It may be more efficient because the command can be reused with different values. The syntax varies slightly for different databases. In the case of MySQL you should use mycursor.execute( """insert into report (title, content, author) values %s, %s, %s""", (times.getvalue('title'), times.getvalue('content'), times.getvalue('pupil')) Notice that this is *not* a string formatting command! The %s are placeholders for MySQL and there is no % formatting operator to combine the format with the following tuple. Kent > > How do I insert these quotes without it closing the SQL statement prematurely? > TIA > > Adam > > [1] > def insert(statement): > mycursor.execute(statement) > > statement = """insert into report (title, content, author) values > ('""" + str(times.getvalue('title')) + """', '""" + > str(times.getvalue('content')) + """', '""" + > str(times.getvalue('pupil')) + """')""" > > insert(statement) > > -- > http://www.monkeez.org > PGP key: 0x7111B833 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From beamer30 at gmail.com Sat Mar 25 17:44:32 2006 From: beamer30 at gmail.com (Tom Bachik) Date: Sat, 25 Mar 2006 08:44:32 -0800 Subject: [Tutor] I HAVE A QUESTION Message-ID: <4ce40aaa0603250844u5912933bre5d5909ced4c6ae4@mail.gmail.com> des easygui only demo boxes because thats all i can get it todo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060325/eec224b5/attachment.html From kent37 at tds.net Sat Mar 25 20:31:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Mar 2006 14:31:45 -0500 Subject: [Tutor] I HAVE A QUESTION In-Reply-To: <4ce40aaa0603250844u5912933bre5d5909ced4c6ae4@mail.gmail.com> References: <4ce40aaa0603250844u5912933bre5d5909ced4c6ae4@mail.gmail.com> Message-ID: <44259AA1.6000400@tds.net> Tom Bachik wrote: > des easygui only demo boxes because thats all i can get it todo I don't understand your question. What have you tried? What do you want it to do? The easygui documentation describes the different types of dialog boxes it supports. You will be more likely to get a helpful answer on this list if you write detailed questions with correct grammar and spelling. Kent From kent37 at tds.net Sat Mar 25 22:59:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Mar 2006 16:59:14 -0500 Subject: [Tutor] I HAVE A QUESTION In-Reply-To: <4ce40aaa0603251247s1dbaf6b3ob056b034c74dca62@mail.gmail.com> References: <4ce40aaa0603250844u5912933bre5d5909ced4c6ae4@mail.gmail.com> <44259AA1.6000400@tds.net> <4ce40aaa0603251247s1dbaf6b3ob056b034c74dca62@mail.gmail.com> Message-ID: <4425BD32.9030205@tds.net> Tom Bachik wrote: > all it means is that i have easygui but every time i open it it only > gives me demos is that all it is suppose to do? Or is actually suppose > to teach me how to the boxes it demos because it doesn't You have to write your own program to use easygui. When you run it by itself it runs the demo. You can import easygui into your program and open the dialog boxes you want. There is a simple example in the Introduction section of the readme file. The demo is a more extensive example and the text file explains how to use it. Kent PS Please reply on the list. From samrobertsmith at gmail.com Sun Mar 26 06:16:34 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 25 Mar 2006 20:16:34 -0800 Subject: [Tutor] site-packages Message-ID: <1d987df30603252016j67dd4469l246f63e8e54e88bb@mail.gmail.com> I downloaded some modules and were told to put under *\Python24\Lib\site-packages I use mac machine and run Python 2.4 but why i could not find any folder named Python24. Also, my Mac machine has a default Python 2.3, I do not see any folder named Python2.3 Confused... Linda From dyoo at hkn.eecs.berkeley.edu Sun Mar 26 08:16:35 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 25 Mar 2006 22:16:35 -0800 (PST) Subject: [Tutor] site-packages In-Reply-To: <1d987df30603252016j67dd4469l246f63e8e54e88bb@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603252208010.7666-100000@hkn.eecs.berkeley.edu> On Sat, 25 Mar 2006, linda.s wrote: > I downloaded some modules and were told to put under > *\Python24\Lib\site-packages Hi Linda, Out of curiosity, which module? If we're being asked to copy files manually into site-packages, we should do a double check on this, because that's a slightly odd thing to do these days. A well-packaged module uses the Distutils system: http://docs.python.org/lib/module-distutils.html and will typically include a 'setup.py' program that knows how to relocate that module to the right location, so that you don't have to worry about the details. > I use mac machine and run Python 2.4 but why i could not find any folder > named Python24. Also, my Mac machine has a default Python 2.3, I do not > see any folder named Python2.3 If you really need to do this, run Python 2.4 and then do the following: ###### import distutils.sysconfig print distutils.sysconfig.get_python_lib() ###### This should print out the path that you're looking for. For example, on my Python 2.3 installation (the default on Mac OS X): ###### mumak:~ dyoo$ python Python 2.3.5 (#1, Mar 20 2005, 20:38:20) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import distutils.sysconfig >>> distutils.sysconfig.get_python_lib() '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages' ###### So that's the directory that third-party libraries will live on my system. But again, please tell us what modules you're trying to install, before you go ahead and copy things over. Manually having to copy these files into site-packages/ is bug-prone. You shouldn't have to do this if the module developers have done their due dilligence by including a "setup.py" distutils installer program. From samrobertsmith at gmail.com Sun Mar 26 08:45:11 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 25 Mar 2006 22:45:11 -0800 Subject: [Tutor] site-packages In-Reply-To: <Pine.LNX.4.44.0603252208010.7666-100000@hkn.eecs.berkeley.edu> References: <1d987df30603252016j67dd4469l246f63e8e54e88bb@mail.gmail.com> <Pine.LNX.4.44.0603252208010.7666-100000@hkn.eecs.berkeley.edu> Message-ID: <1d987df30603252245x6c3fd836ne1860eb344e5c20c@mail.gmail.com> On 3/25/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: > > > On Sat, 25 Mar 2006, linda.s wrote: > > > I downloaded some modules and were told to put under > > *\Python24\Lib\site-packages > > Hi Linda, > > Out of curiosity, which module? If we're being asked to copy files > manually into site-packages, we should do a double check on this, because > that's a slightly odd thing to do these days. A well-packaged module uses > the Distutils system: > > http://docs.python.org/lib/module-distutils.html > > and will typically include a 'setup.py' program that knows how to relocate > that module to the right location, so that you don't have to worry about > the details. > > > > I use mac machine and run Python 2.4 but why i could not find any folder > > named Python24. Also, my Mac machine has a default Python 2.3, I do not > > see any folder named Python2.3 > > If you really need to do this, run Python 2.4 and then do the following: > > ###### > import distutils.sysconfig > print distutils.sysconfig.get_python_lib() > ###### > > This should print out the path that you're looking for. For example, on > my Python 2.3 installation (the default on Mac OS X): > > ###### > mumak:~ dyoo$ python > Python 2.3.5 (#1, Mar 20 2005, 20:38:20) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import distutils.sysconfig > >>> distutils.sysconfig.get_python_lib() > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages' > ###### > > So that's the directory that third-party libraries will live on my system. > > > But again, please tell us what modules you're trying to install, before > you go ahead and copy things over. Manually having to copy these files > into site-packages/ is bug-prone. You shouldn't have to do this if the > module developers have done their due dilligence by including a "setup.py" > distutils installer program. It is from http://www.scipy.org/Cookbook/Matplotlib/mplot3D On the webpage, it says " To begin, download the module from http://matplotlib.sourceforge.net/mpl3d.zip Extract the files and place them in a folder named "mpl3d" in *\Python24\Lib\site-packages" From kent37 at tds.net Sun Mar 26 13:43:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 26 Mar 2006 06:43:08 -0500 Subject: [Tutor] Dynamically naming functions In-Reply-To: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> Message-ID: <44267E4C.3080802@tds.net> Ed Singleton wrote: > How does one go about creating functions, classes, or callable objects > when you don't know their name in advance? (For example you want to > read their names in from a text file or database). > > I want to use this in a few different places. For example Faces, the > Python Project Management Planner Tool Thingy, uses nested functions > to put tasks within a project: > > def MyProject(): > start = "2006-03-06" > resource = Me > > def Task1(): > start = "2006-03-13" > > def Task2(): > effort = "1w" > > I'd like to load these from a database (using SQLObject), but I'm not > sure how I can define the name of the function from a filed in a > database (or read in from a text file). Hi Ed, I was just wondering how this came out - did you find a way to generate these functions dynamically? Or change Faces? Or give up? Thanks, Kent From aguffabuff at hotmail.com Mon Mar 27 04:25:49 2006 From: aguffabuff at hotmail.com (Ars) Date: Sun, 26 Mar 2006 18:25:49 -0800 Subject: [Tutor] How do I monitor running processes? Message-ID: <BAY106-DAV11CC5FA11B201508708D3ECAD20@phx.gbl> Is there a command that will monitor all running processes/programs(on Windows ME)? I'd like to make a program that makes a beep when an unrecognized process, such as an adware program, is running. That way I'd know immediately when one of these stealth programs not on my safe list has installed itself. Jack -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060326/0590cd6f/attachment.html From keosophon at khmeros.info Mon Mar 27 04:26:34 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Mon, 27 Mar 2006 09:26:34 +0700 Subject: [Tutor] compilte python to an executable file. Message-ID: <200603270926.34550.keosophon@khmeros.info> hi all, Does anyone know how to compile a python filename.py to an executable file? thanks, phon From john at fouhy.net Mon Mar 27 04:30:45 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Mar 2006 14:30:45 +1200 Subject: [Tutor] compilte python to an executable file. In-Reply-To: <200603270926.34550.keosophon@khmeros.info> References: <200603270926.34550.keosophon@khmeros.info> Message-ID: <5e58f2e40603261830p1ee287ecw@mail.gmail.com> On 27/03/06, Keo Sophon <keosophon at khmeros.info> wrote: > hi all, > > Does anyone know how to compile a python filename.py to an executable file? Google for py2exe. Note, though, it doesn't really "compile" your script. Rather, it bundles up the interpreter and all the flies needed to make it go. It still means you can run your programs on Windows systems without python installed, though. -- John. From aguffabuff at hotmail.com Mon Mar 27 05:38:32 2006 From: aguffabuff at hotmail.com (Ars) Date: Sun, 26 Mar 2006 19:38:32 -0800 Subject: [Tutor] compilte python to an executable file. References: <200603270926.34550.keosophon@khmeros.info> <5e58f2e40603261830p1ee287ecw@mail.gmail.com> Message-ID: <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> > On 27/03/06, Keo Sophon <keosophon at khmeros.info> wrote: > > hi all, > > > > Does anyone know how to compile a python filename.py to an executable file? > > Google for py2exe. > > Note, though, it doesn't really "compile" your script. Rather, it > bundles up the interpreter and all the flies needed to make it go. It > still means you can run your programs on Windows systems without > python installed, though. > > -- > John. ================================== I was kinda wondering about that too. Isn't there any other way to get your program compiled into standalone machine code? Would a py2exe program be practical for a commercial program? I'd think people could read your source code too easily. -Jack From keosophon at khmeros.info Mon Mar 27 06:17:07 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Mon, 27 Mar 2006 11:17:07 +0700 Subject: [Tutor] compilte python to an executable file. In-Reply-To: <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> References: <200603270926.34550.keosophon@khmeros.info> <5e58f2e40603261830p1ee287ecw@mail.gmail.com> <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> Message-ID: <200603271117.07619.keosophon@khmeros.info> On Monday 27 March 2006 10:38, Ars wrote: > > On 27/03/06, Keo Sophon <keosophon at khmeros.info> wrote: > > > hi all, > > > > > > Does anyone know how to compile a python filename.py to an executable > > file? > I don't know how python creates executable file. The purpose is to have the program written in Python can run on Linux and Windows and Mac (if possible). thanks, phon From tim.golden at viacom-outdoor.co.uk Mon Mar 27 09:48:08 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 27 Mar 2006 08:48:08 +0100 Subject: [Tutor] How do I monitor running processes? Message-ID: <9A28C052FF32734DACB0A288A3533991044D2671@vogbs009.gb.vo.local> [Ars] | Is there a command that will monitor all running | processes/programs(on Windows ME)? I'd like to make a | program that makes a beep when an unrecognized process, such | as an adware program, is running. That way I'd know | immediately when one of these stealth programs not on my safe | list has installed itself. I don't know if there's anything absolutely foolproof; I imagine that stealth-type programs know pretty much all the tricks. However, to answer your question in the most general way: you might try looking at WMI. I don't know how much information I need to give you, because you haven't indicated what level of expertise you have, but if you're coming from zero, then start with the Microsoft WMI page (tinyurl link to a Microsoft page): http://tinyurl.com/awq7 and then at the WMI module for Python: http://timgolden.me.uk/python/wmi.html (<cough> yes, that is my name in the URL) and specifically at this example: http://timgolden.me.uk/python/wmi_cookbook.html#watch_notepad whicih gives you a simple example of how you set up a WMI watcher to monitor a particular thing, in this case a process. You can generalise it by watching for, in your case, Creation rather than Deletion, and by removing the ProcessId parameter which is narrowing it down to just the notepad.exe process which the example creates. You could check, for example, the Caption or Name or Description attributes, all of which seem to hold the .exe of the running program. Be warned: I don't know how much of an overhead this will have on the system. Try it cautiously before implementing it for real. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tim.golden at viacom-outdoor.co.uk Mon Mar 27 09:58:03 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 27 Mar 2006 08:58:03 +0100 Subject: [Tutor] Authen::ACE Message-ID: <9A28C052FF32734DACB0A288A3533991044D2673@vogbs009.gb.vo.local> [Asif Iqbal] | Does anyone know if there is any python module similar to Authen::ACE | available that I can use to authenticate against a RSA SecurID server? I don't believe there is, I'm afraid. Certainly, if a Google for python securid doesn't turn anything up, it's not likely. However, it's a specific enough question that you might want to ask on the main Python newsgroup comp.lang.python (or its mirrored mailing list at: http://mail.python.org/mailman/listinfo/python-list or its equivalent Google Group: http://groups.google.com/group/comp.lang.python?hl=en TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From singletoned at gmail.com Mon Mar 27 10:42:14 2006 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 27 Mar 2006 09:42:14 +0100 Subject: [Tutor] Dynamically naming functions In-Reply-To: <44267E4C.3080802@tds.net> References: <34bb7f5b0603100144y6bd32e67m@mail.gmail.com> <44267E4C.3080802@tds.net> Message-ID: <34bb7f5b0603270042g9b1fce4y@mail.gmail.com> On 26/03/06, Kent Johnson <kent37 at tds.net> wrote: > Ed Singleton wrote: > > How does one go about creating functions, classes, or callable objects > > when you don't know their name in advance? (For example you want to > > read their names in from a text file or database). > > > > I want to use this in a few different places. For example Faces, the > > Python Project Management Planner Tool Thingy, uses nested functions > > to put tasks within a project: > > > > def MyProject(): > > start = "2006-03-06" > > resource = Me > > > > def Task1(): > > start = "2006-03-13" > > > > def Task2(): > > effort = "1w" > > > > I'd like to load these from a database (using SQLObject), but I'm not > > sure how I can define the name of the function from a filed in a > > database (or read in from a text file). > > Hi Ed, > > I was just wondering how this came out - did you find a way to generate > these functions dynamically? Or change Faces? Or give up? I just temporarily delayed the problem. I'm going to have a look at trying to change the Faces code to use dictionaries as per your suggestion, but it would a big task for me (my biggest so far probably). (I have a new job that lets me do everything in Python, but sometimes they direct my efforts towards a particular task, which delays my working on interesting things). Ed From kaushalshriyan at gmail.com Mon Mar 27 13:09:01 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Mon, 27 Mar 2006 16:39:01 +0530 Subject: [Tutor] Learning Python Message-ID: <6b16fb4c0603270309i426b38a8qd1d16e3a7ebb1377@mail.gmail.com> Hi I am a novice in Python, Which is the best source of learning python for a beginner Regards Kaushal From kent37 at tds.net Mon Mar 27 13:22:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Mar 2006 06:22:36 -0500 Subject: [Tutor] Learning Python In-Reply-To: <6b16fb4c0603270309i426b38a8qd1d16e3a7ebb1377@mail.gmail.com> References: <6b16fb4c0603270309i426b38a8qd1d16e3a7ebb1377@mail.gmail.com> Message-ID: <4427CAFC.6000600@tds.net> Kaushal Shriyan wrote: > Hi > > I am a novice in Python, Which is the best source of learning python > for a beginner Read one of the tutorials listed here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Write simple programs to try out what you have learned. Ask questions here when you get stuck. Have fun! Kent From noufal at nibrahim.net.in Mon Mar 27 13:26:15 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Mon, 27 Mar 2006 16:56:15 +0530 (IST) Subject: [Tutor] Learning Python In-Reply-To: <6b16fb4c0603270309i426b38a8qd1d16e3a7ebb1377@mail.gmail.com> References: <6b16fb4c0603270309i426b38a8qd1d16e3a7ebb1377@mail.gmail.com> Message-ID: <24709.203.145.176.76.1143458775.squirrel@members.hcoop.net> On Mon, March 27, 2006 4:39 pm, Kaushal Shriyan wrote: > Hi > > I am a novice in Python, Which is the best source of learning python > for a beginner If you're already a "programmer", then the python tutorial at http://docs.python.org/tut/tut.html + a working python installation is enough IMHO. If you want to learn programming itself, perhaps you should take a look at http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Good luck! -- -NI From kaushalshriyan at gmail.com Mon Mar 27 14:10:14 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Mon, 27 Mar 2006 17:40:14 +0530 Subject: [Tutor] Learning Python In-Reply-To: <24709.203.145.176.76.1143458775.squirrel@members.hcoop.net> References: <6b16fb4c0603270309i426b38a8qd1d16e3a7ebb1377@mail.gmail.com> <24709.203.145.176.76.1143458775.squirrel@members.hcoop.net> Message-ID: <6b16fb4c0603270410ubf7678as18d786206d48b216@mail.gmail.com> On 3/27/06, Noufal Ibrahim <noufal at nibrahim.net.in> wrote: > > On Mon, March 27, 2006 4:39 pm, Kaushal Shriyan wrote: > > Hi > > > > I am a novice in Python, Which is the best source of learning python > > for a beginner > > If you're already a "programmer", then the python tutorial at > http://docs.python.org/tut/tut.html + a working python installation is > enough IMHO. > > If you want to learn programming itself, perhaps you should take a look at > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Good luck! > -- > -NI > > Thanks a Ton, I will definetly ping and update all of you :) Regards KaushaL From josipl2000 at yahoo.com Mon Mar 27 14:16:16 2006 From: josipl2000 at yahoo.com (josip) Date: Mon, 27 Mar 2006 04:16:16 -0800 (PST) Subject: [Tutor] newbie exercises Message-ID: <20060327121616.5346.qmail@web60818.mail.yahoo.com> Hi, Python is my first language. I have finished loops, now I'm going to functions. I'm working with Learning Python 2ed book. Can someone give me exercises to do with loops, maybe functions to? Thanks --------------------------------- 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/20060327/d08b7fca/attachment.html From sanelson at gmail.com Mon Mar 27 14:53:26 2006 From: sanelson at gmail.com (Steve Nelson) Date: Mon, 27 Mar 2006 13:53:26 +0100 Subject: [Tutor] newbie exercises In-Reply-To: <20060327121616.5346.qmail@web60818.mail.yahoo.com> References: <20060327121616.5346.qmail@web60818.mail.yahoo.com> Message-ID: <b6131fdc0603270453p28811516q506920a43b1dab8a@mail.gmail.com> On 3/27/06, josip <josipl2000 at yahoo.com> wrote: > Can someone give me exercises to do with loops, maybe functions to? How about a program that produces truth tables for the basic gates? AND, NAND, NOT, OR, XOR? You could write a function for each gate, and one to produce a truth table. S. From jonasmg at softhome.net Mon Mar 27 16:57:01 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Mon, 27 Mar 2006 07:57:01 -0700 Subject: [Tutor] using BeautifulSoup Message-ID: <courier.4427FD3D.00002C8D@softhome.net> Hi! I'm trying to use BeautifulSoup for get data from a table (on right) from: http://en.wikipedia.org/wiki/United_states i.e. i would get data from 'Calling code' that it would be '+1' ---------------------- import urllib2 from BeautifulSoup import BeautifulSoup url="http://en.wikipedia.org/wiki/United_states" html = urllib2.urlopen(url).read() soup = BeautifulSoup() soup.feed(html) mainTable = soup.first('table') rows = mainTable('tr') any help here? Thanks in advance From kent37 at tds.net Mon Mar 27 18:13:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Mar 2006 11:13:56 -0500 Subject: [Tutor] using BeautifulSoup In-Reply-To: <courier.4427FD3D.00002C8D@softhome.net> References: <courier.4427FD3D.00002C8D@softhome.net> Message-ID: <44280F44.9050704@tds.net> jonasmg at softhome.net wrote: > Hi! > > I'm trying to use BeautifulSoup for get data from a table (on right) from: > http://en.wikipedia.org/wiki/United_states > > i.e. i would get data from 'Calling code' that it would be '+1' > > ---------------------- > > import urllib2 > from BeautifulSoup import BeautifulSoup > > url="http://en.wikipedia.org/wiki/United_states" > html = urllib2.urlopen(url).read() > soup = BeautifulSoup() > soup.feed(html) You just have to find some kind of ad hoc search that gets you to where you want to be. I would try something like this: anchor = soup.fetch('a', dict(href="/wiki/List_of_country_calling_codes")) code = anchor.findNext('code') print code.string Presumably you want this to work for other country pages as well; you will have to look at the source, see what they have in common and search on that. Kent From s.varun at gmail.com Mon Mar 27 18:17:55 2006 From: s.varun at gmail.com (Varun Soundararajan) Date: Mon, 27 Mar 2006 21:47:55 +0530 Subject: [Tutor] compilte python to an executable file. In-Reply-To: <200603271117.07619.keosophon@khmeros.info> References: <200603270926.34550.keosophon@khmeros.info> <5e58f2e40603261830p1ee287ecw@mail.gmail.com> <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> <200603271117.07619.keosophon@khmeros.info> Message-ID: <32b5ee760603270817u3136a252hc1453810b93bd30c@mail.gmail.com> Hi jack, You are right. py2exe may not fit well in commercial software products that arent in the open source model. An executable that was py2exe'd could well be converted back to the source.. I feel that its one of the restrictions thats in the way of enterprization of python...(agreed google uses python..but thats internal.. they dont deploy py files in customer's computers).correct me if i am wrong... Cheers Varun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060327/c20ac814/attachment.htm From kent37 at tds.net Mon Mar 27 18:36:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Mar 2006 11:36:31 -0500 Subject: [Tutor] compilte python to an executable file. In-Reply-To: <200603271117.07619.keosophon@khmeros.info> References: <200603270926.34550.keosophon@khmeros.info> <5e58f2e40603261830p1ee287ecw@mail.gmail.com> <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> <200603271117.07619.keosophon@khmeros.info> Message-ID: <4428148F.1040701@tds.net> Keo Sophon wrote: > On Monday 27 March 2006 10:38, Ars wrote: > >>>On 27/03/06, Keo Sophon <keosophon at khmeros.info> wrote: >>> >>>>hi all, >>>> >>>>Does anyone know how to compile a python filename.py to an executable >> >>file? >> > > > I don't know how python creates executable file. The purpose is to have the > program written in Python can run on Linux and Windows and Mac (if possible). A well-written Python program (.py file) is very portable across Linux, Windows and Mac, if the target machine has Python installed. There is no executable format that will run unchanged on these three platforms, you have to build three executable files. Kent From kent37 at tds.net Mon Mar 27 18:37:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Mar 2006 11:37:29 -0500 Subject: [Tutor] compilte python to an executable file. In-Reply-To: <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> References: <200603270926.34550.keosophon@khmeros.info> <5e58f2e40603261830p1ee287ecw@mail.gmail.com> <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> Message-ID: <442814C9.20508@tds.net> Ars wrote: > Would a py2exe program be practical for a commercial program? I'd think > people could read your source code too easily. I think it is possible to create py2exe files that don't contain source code, just compiled pyc files. Kent From jonasmg at softhome.net Mon Mar 27 18:56:37 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Mon, 27 Mar 2006 09:56:37 -0700 Subject: [Tutor] compilte python to an executable file. In-Reply-To: <442814C9.20508@tds.net> References: <200603270926.34550.keosophon@khmeros.info> <5e58f2e40603261830p1ee287ecw@mail.gmail.com> <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> <442814C9.20508@tds.net> Message-ID: <courier.44281945.00002F4A@softhome.net> >jonasmg at softhome.net wrote: >> Hi! >> >> I'm trying to use BeautifulSoup for get data from a table (on right) from: >> http://en.wikipedia.org/wiki/United_states >> >> i.e. i would get data from 'Calling code' that it would be '+1' >> >> ---------------------- >> >> import urllib2 >> from BeautifulSoup import BeautifulSoup >> >> url="http://en.wikipedia.org/wiki/United_states" >> html = urllib2.urlopen(url).read() >> soup = BeautifulSoup() >> soup.feed(html) > You just have to find some kind of ad hoc search that gets you to where > you want to be. I would try something like this: > anchor = soup.fetch('a', dict(href="/wiki/List_of_country_calling_codes")) > code = anchor.findNext('code') > print code.string > Presumably you want this to work for other country pages as well; you > will have to look at the source, see what they have in common and search > on that. > Kent anchor.findNext('code') fails: anchor = soup.fetch('a', {'href': '/wiki/List_of_country_calling_codes'}) print anchor [<a href="/wiki/List_of_country_calling_codes" title="List of country calling codes">Calling code</a>] anchor.findNext('code') [] From jonasmg at softhome.net Mon Mar 27 19:22:37 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Mon, 27 Mar 2006 10:22:37 -0700 Subject: [Tutor] using BeautifulSoup Message-ID: <courier.44281F5D.00004BE9@softhome.net> >jonasmg at softhome.net wrote: >> Hi! >> >> I'm trying to use BeautifulSoup for get data from a table (on right) from: >> http://en.wikipedia.org/wiki/United_states >> >> i.e. i would get data from 'Calling code' that it would be '+1' >> >> ---------------------- >> >> import urllib2 >> from BeautifulSoup import BeautifulSoup >> >> url="http://en.wikipedia.org/wiki/United_states" >> html = urllib2.urlopen(url).read() >> soup = BeautifulSoup() >> soup.feed(html) > You just have to find some kind of ad hoc search that gets you to where > you want to be. I would try something like this: > anchor = soup.fetch('a', dict(href="/wiki/List_of_country_calling_codes")) > code = anchor.findNext('code') > print code.string > Presumably you want this to work for other country pages as well; you > will have to look at the source, see what they have in common and search > on that. > Kent anchor.findNext('code') fails: anchor = soup.fetch('a', {'href': '/wiki/List_of_country_calling_codes'}) print anchor [<a href="/wiki/List_of_country_calling_codes" title="List of country calling codes">Calling code</a>] anchor.findNext('code') [] P.S. : Sorry for my last email, I was wrong with the subject From s.varun at gmail.com Mon Mar 27 19:27:28 2006 From: s.varun at gmail.com (Varun Soundararajan) Date: Mon, 27 Mar 2006 22:57:28 +0530 Subject: [Tutor] compilte python to an executable file. In-Reply-To: <442814C9.20508@tds.net> References: <200603270926.34550.keosophon@khmeros.info> <5e58f2e40603261830p1ee287ecw@mail.gmail.com> <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> <442814C9.20508@tds.net> Message-ID: <32b5ee760603270927j50baed76q5b926e2a42c12102@mail.gmail.com> hi, I face a typical problem that most python programmers face. Most users only want a click and run kind of thing..they are uninterested to install any software on their system , be it python or any other software..so the solution is to pack the code up as a py2exe program for windows and ask them to click it and run... Is there any solution where i dont ask any software to be installed(ie., python) and still be able to assure that if they click something, they get the result that they need?... py2exe partially succeeds in answering this..by packing things up...however any compiled pyc code can easily be decompiled to get the source..its geared towards windows and in linux, we (always) assume that the users are savvy enough and interested to install python if its not already installed...so is the case with mac. Regards -- Varun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060327/a015827c/attachment.html From patriciap.gu at gmail.com Mon Mar 27 19:40:12 2006 From: patriciap.gu at gmail.com (Patty) Date: Mon, 27 Mar 2006 17:40:12 +0000 (UTC) Subject: [Tutor] =?utf-8?q?html_and_mod=5Fpython?= References: <loom.20060323T023022-647@post.gmane.org> <44227CE0.7090503@tds.net> Message-ID: <loom.20060327T193652-840@post.gmane.org> Hi, Can you please give me a quick example of how to do this: > Then change printbox() to create the > tag using a loop over the value. For each value, check to see if it is > the same as the value passed in and generate the appropriate option tag. The way i have it right now is: tag = """ <select name='percent'> <option SELECTED VALUE=%s>%s</option> <option VALUE='-'>-</option> <option VALUE='0'>0%%</option> <option VALUE='10'>10%%</option> <option VALUE='20'>20%%</option> <option VALUE='30'>30%%</option> <option VALUE='40'>40%%</option> <option VALUE='50'>50%%</option> <option VALUE='60'>60%%</option> <option VALUE='70'>70%%</option> <option VALUE='80'>80%%</option> <option VALUE='90'>90%%</option> <option VALUE='100'>100%%</option> </select>""" % (selected_value, selected_value) Although it does what i want, I don't like the way the value is display. Thanks, Patty From Carlo.Capuano at iter.org Mon Mar 27 19:30:00 2006 From: Carlo.Capuano at iter.org (Carlo Capuano) Date: Mon, 27 Mar 2006 19:30:00 +0200 Subject: [Tutor] grab a secodary window content Message-ID: <0F4FBAD10465E047ADB7E8C74B4C189B2FBEA5@de-iws-xch01.iter.org> Hi to all! I'm playing around with VideoCapture and vpython, both open a secondary window with nice images on it, well the one with my face is not so great, anyway I wish to grab the content and put it into a PIL Image, in VideoCapture there are a methods called saveSnapshot and getImage, but somehow they work one every 20000 circa (I made a loop until it doesn't raise errors and it works) with vpython I didn't find nothing at all. Now, I know I could make a snapshot of the entire desktop and than cut what I'm looking for, but shot at butterflies' whit a bazooka is impolite. I fill I'm missing a couple of lines of python, I run on Windows. Any suggest is appreciated! Thanks. Carlo what is ITER? www.iter.org From jonasmg at softhome.net Mon Mar 27 22:55:31 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Mon, 27 Mar 2006 13:55:31 -0700 Subject: [Tutor] using BeautifulSoup In-Reply-To: <courier.44281F5D.00004BE9@softhome.net> References: <courier.44281F5D.00004BE9@softhome.net> Message-ID: <courier.44285143.000032AF@softhome.net> jonasmg at softhome.net writes: >>jonasmg at softhome.net wrote: >>> Hi! >>> >>> I'm trying to use BeautifulSoup for get data from a table (on right) from: >>> http://en.wikipedia.org/wiki/United_states >>> >>> i.e. i would get data from 'Calling code' that it would be '+1' >>> >>> ---------------------- >>> >>> import urllib2 >>> from BeautifulSoup import BeautifulSoup >>> >>> url="http://en.wikipedia.org/wiki/United_states" >>> html = urllib2.urlopen(url).read() >>> soup = BeautifulSoup() >>> soup.feed(html) > >> You just have to find some kind of ad hoc search that gets you to where >> you want to be. I would try something like this: > >> anchor = soup.fetch('a', dict(href="/wiki/List_of_country_calling_codes")) > >> code = anchor.findNext('code') >> print code.string > >> Presumably you want this to work for other country pages as well; you >> will have to look at the source, see what they have in common and search >> on that. > >> Kent > > anchor.findNext('code') fails: > > anchor = soup.fetch('a', {'href': '/wiki/List_of_country_calling_codes'}) > print anchor > > [<a href="/wiki/List_of_country_calling_codes" title="List of country > calling codes">Calling code</a>] > > anchor.findNext('code') > [] > > P.S. : Sorry for my last email, I was wrong with the subject > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Solution _there is that using findChild instead of fetch_: anchor = soup.findChild('a', dict(href="/wiki/List_of_country_calling_codes")) print anchor.findNext('code') From patriciap.gu at gmail.com Mon Mar 27 23:10:53 2006 From: patriciap.gu at gmail.com (Patty) Date: Mon, 27 Mar 2006 21:10:53 +0000 (UTC) Subject: [Tutor] =?utf-8?q?html_and_mod=5Fpython?= References: <loom.20060323T023022-647@post.gmane.org> <44227CE0.7090503@tds.net> <loom.20060327T193652-840@post.gmane.org> Message-ID: <loom.20060327T230935-795@post.gmane.org> > Can you please give me a quick example of how to do this: Nevermind. I figured it out. Thanks anyway :-) Patty From slevin at signpuddle.net Mon Mar 27 23:21:08 2006 From: slevin at signpuddle.net (Steve Slevinski) Date: Mon, 27 Mar 2006 16:21:08 -0500 Subject: [Tutor] Turnkey Python on a USB stick In-Reply-To: <44284243.3030107@signpuddle.net> References: <200603270926.34550.keosophon@khmeros.info> <5e58f2e40603261830p1ee287ecw@mail.gmail.com> <BAY106-DAV13B2BFEFB0E4514E39CACECAD20@phx.gbl> <200603271117.07619.keosophon@khmeros.info> <44284243.3030107@signpuddle.net> Message-ID: <44285744.7000000@signpuddle.net> Hi list, I like the idea of portable apps. Load a USB drive and you're ready to go. I am switching from PHP to Python and I'm curious if anyone has tried using USB sticks for either development or distribution? I was looking at purchasing Movable Python for a USB stick. I was then going to load it up with Twisted, GTK, Leo, py2exe, py2app, protable firefox, portable thunderbird and the Uniform Server. Zip the drive, backup the file and I have an instant recovery. My development environment is safe and stable. My users are not very sophisticated so I wanted to use a USB drive for distribution. They'll plug in the USB stick, which will automatically start the webserver (Uniform Server). Then they'll interact with a wiki style website. Later they can sync their personal server with an online server somewhere for publication and backup. Later I'll include a GTK frontend and twisted server. Does this sound reasonable? Are their any alternatives to Movable Python? (http://www.voidspace.org.uk/python/movpy/) Thanks, -Steve From Barry.Carroll at psc.com Tue Mar 28 00:48:16 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 27 Mar 2006 14:48:16 -0800 Subject: [Tutor] setdefault method Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3632@eugsrv400.psc.pscnet.com> Greetings: What is the purpose of the dictionary method setdefault(k[, x])? For example assume the following dictionary: >>> colors = {'green':(0,255,0), 'red':(255,0,0), 'blue':(0,0,255), 'white':(255,255,255), 'black':(0,0,0)} >>> Now, execute the statement: >>> colors.setdefault('black') (0, 0, 0) >>> I would expect that future references to colors, with no argument or a null argument, would return the value of colors['black'], e.g.: >>> colors[] (0, 0, 0) >>> colors (0, 0, 0) >>> or some similar syntax. This is not the case, however. The actual behavior is: >>> colors {'blue': (0, 0, 255), 'black': (0, 0, 0), 'white': (255, 255, 255), 'green': (0, 255, 0), 'red': (255, 0, 0)} >>> colors[] File "<input>", line 1 colors[] ^ SyntaxError: invalid syntax >>> So, what then is the proper use of setdefault()? And, if d.setdefault does not actually assign a default value for d, is there a way to do this? As always, thanks in advance for your responses. ? Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From ms at cerenity.org Tue Mar 28 02:57:40 2006 From: ms at cerenity.org (Michael Sparks) Date: Tue, 28 Mar 2006 01:57:40 +0100 Subject: [Tutor] Turnkey Python on a USB stick In-Reply-To: <44285744.7000000@signpuddle.net> References: <200603270926.34550.keosophon@khmeros.info> <44284243.3030107@signpuddle.net> <44285744.7000000@signpuddle.net> Message-ID: <200603280157.40865.ms@cerenity.org> On Monday 27 March 2006 22:21, Steve Slevinski wrote: > Does this sound reasonable? ?Are their any alternatives to Movable > Python? (http://www.voidspace.org.uk/python/movpy/) Hi Steve, I've got no experience of setting up such a beast or using movable python, but I just wanted to say it sounds like an EXCELLENT idea, and I'd be interested in hearing how you get on! :) Michael. From Barry.Carroll at psc.com Tue Mar 28 01:51:03 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 27 Mar 2006 15:51:03 -0800 Subject: [Tutor] Data Type with Dictionary and List Behavior Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3633@eugsrv400.psc.pscnet.com> Greetings: I have a function that computes the checksum of an integer, including or excluding digits in the computation based on the content of a mask string. For example, cksum(123456789, '***...***') will do its computation on 123789, masking out the three non-significant digits. My question concerns assigning the value of the mask string. The class that defines the function also pre-defines several masks, say '*********', '***...***', and '......***'. The masks have names: 'all', 'first-last', 'last'. Of these, 'all' is the most commonly used. The user may select one of these masks, or may supply their own, arbitrary value. Further, the user can choose to add their value to the group of pre-defines, and reuse that value later in the session. (The user-defined mask is not saved between sessions; no permanent storage is required.) So far, this structure looks like a dictionary. However, the user also wants to access the group of pre-defined masks as if they were elements of a list: masks[0] returns '*********' masks[1] returns '***...***' and so on. To make matters even more complex, if the user does not specify a mask to use, the function should use the mask employed in the previous invocation, defaulting to masks[0] if this is the first invocation. Finally, the user can set a mask as 'default', which essentially marks a mask as 'last used' without invoking the function. Is there a derived type or data structure in existence that implements these capabilities (in descending order of importance? 1. Access by name (dict) 2. Access by position (list) 3. Addition of new items (dict, list) 4. Set a 'last used' item (??????) 5. Set a 'default' item (dict???) Thanks in advance 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 carroll at tjc.com Tue Mar 28 02:22:30 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 27 Mar 2006 16:22:30 -0800 (PST) Subject: [Tutor] setdefault method In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3632@eugsrv400.psc.pscnet.com> Message-ID: <Pine.LNX.4.44.0603271612550.6659-100000@violet.rahul.net> On Mon, 27 Mar 2006, Carroll, Barry wrote: > So, what then is the proper use of setdefault()? And, if d.setdefault > does not actually assign a default value for d, is there a way to do > this? It's a somewhat misleading name, but setdefault a) looks up an entry in a dictionary and c) returns it... but if it's not found, between steps a & c it b) sets the entry to the default value. Think of it as a way to pre-initialize dictionary entries on the fly the first time they're referenced. Here's an example, which looks at a string of text and creates a dictionary of the constituent characters' frequency: >>> freq = {} >>> sampletext = "norwegian blue" >>> for char in sampletext: ... freq[char] = freq.setdefault(char,0)+1 ... >>> freq {'a': 1, ' ': 1, 'b': 1, 'e': 2, 'g': 1, 'i': 1, 'l': 1, 'o': 1, 'n': 2, 'r': 1, 'u': 1, 'w': 1} >>> From john at fouhy.net Tue Mar 28 02:33:46 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 28 Mar 2006 12:33:46 +1200 Subject: [Tutor] Data Type with Dictionary and List Behavior In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3633@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C3633@eugsrv400.psc.pscnet.com> Message-ID: <5e58f2e40603271633w520296bdndba139c38c3f322d@mail.gmail.com> On 28/03/06, Carroll, Barry <Barry.Carroll at psc.com> wrote: > 1. Access by name (dict) > 2. Access by position (list) > 3. Addition of new items (dict, list) > 4. Set a 'last used' item (??????) > 5. Set a 'default' item (dict???) Probably your best bet is to define your own container class. If you define __getitem__, you can use [] with instances of your class, just like lists or dicts. Something like this, perhaps (untested): class MaskDict(UserDict.DictMixin): def __init__(self): self.keys = [] self.data = {} self.default = None def __getitem__(self, key): if isinstance(key, (int, long)): self.default = self.keys[key] return self.data[self.default] else: self.default = key return self.data[key] def __setitem__(self, key, value): try: self.keys.remove(key) except ValueError: pass self.keys.append(key) self.data[key] = value def __delitem__(self, key, value): del self.data[key] self.keys.remove(key) def keys(self): return self.keys def setDefault(self, key): self.default = key HTH! -- John. From kent37 at tds.net Tue Mar 28 03:23:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Mar 2006 20:23:59 -0500 Subject: [Tutor] setdefault method In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3632@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C3632@eugsrv400.psc.pscnet.com> Message-ID: <4428902F.9010603@tds.net> Carroll, Barry wrote: > Greetings: > > What is the purpose of the dictionary method setdefault(k[, x])? setdefault() is perhaps badly named, but it is very useful. It doesn't do what you think it does! From the docs: setdefault() is like get(), except that if k is missing, x is both returned and inserted into the dictionary as the value of k. x defaults to None. You could define your own like this (with an extra arg for the dict): def setdefault(d, k, x=None): if k in d: return d[k] else: d[k] = x return x If k is in d, the existing value d[k] is returned. If k is not in d, the magic happens - d[k] is set to x, and x is returned to you. I find this most often useful when I want to make a dict that maps a key to a list of values. For example I may have a list of key, value pairs and I want to accumulate the list of all values for each key. This comes up pretty often in my experience. Here is how to code it with setdefault(): d = {} for k, v in some_list: d.setdefault(k, []).append(v) Here setdefault() will return the list that k maps to, if any, or otherwise start a new list. In either case, you can append the new value to the returned list and get the effect you want. > And, if d.setdefault does not actually assign a default value for d, is there a way to do this? See this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389639 Kent From kent37 at tds.net Tue Mar 28 03:25:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Mar 2006 20:25:53 -0500 Subject: [Tutor] setdefault method In-Reply-To: <Pine.LNX.4.44.0603271612550.6659-100000@violet.rahul.net> References: <Pine.LNX.4.44.0603271612550.6659-100000@violet.rahul.net> Message-ID: <442890A1.1050807@tds.net> Terry Carroll wrote: >>>>freq = {} >>>>sampletext = "norwegian blue" >>>>for char in sampletext: > > ... freq[char] = freq.setdefault(char,0)+1 Although I'm a big fan of setdefault() I think this particular example is better written as freq[char] = freq.get(char,0)+1 There is no need to store the initial 0 into freq as it will immediately be overwritten. Kent From kent37 at tds.net Tue Mar 28 03:38:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Mar 2006 20:38:37 -0500 Subject: [Tutor] using BeautifulSoup In-Reply-To: <courier.44281F5D.00004BE9@softhome.net> References: <courier.44281F5D.00004BE9@softhome.net> Message-ID: <4428939D.1070008@tds.net> jonasmg at softhome.net wrote: > anchor.findNext('code') fails: > > anchor = soup.fetch('a', {'href': '/wiki/List_of_country_calling_codes'}) > print anchor > > [<a href="/wiki/List_of_country_calling_codes" title="List of country > calling codes">Calling code</a>] > > anchor.findNext('code') > [] are you sure that's what you got? Looks like an AttributeError to me - anchor is a *list* of anchors. Try anchor[0].findNext('code') Kent From kaushalshriyan at gmail.com Tue Mar 28 09:27:58 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 28 Mar 2006 12:57:58 +0530 Subject: [Tutor] Object Oriented Programmin Message-ID: <6b16fb4c0603272327i451e2b57l28a0b7783deda90a@mail.gmail.com> Hi ALL I have gone through the object oriented programming in Python, I am not able to understand OOP concept in python, is there a methodical way to understand it and simplfy things Thanks in Advance Regards Kaushal From noufal at nibrahim.net.in Tue Mar 28 09:50:55 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Tue, 28 Mar 2006 13:20:55 +0530 (IST) Subject: [Tutor] Python tutor Message-ID: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Greetings all, Are there any programs for python that offer an "interactive" tutorial? Something on the lines of the builtin emacs tutorial (which is basically just a buffer that tells you to try this and try that with itself) or the Inkscape tutorial (which is an SVG document that comes along with inkscape which has instructions on manipulating it so that the reader learns stuff). Another example that comes to mind is the tcltutor program to learn TCL. It contains an instruction window, a code window and an output window. The user is told something, they try it and the output is visible. I personally used it when I was learning TCL. The python tutorial is great and probably all one needs to learn the language but I think a more interactive program to teach it might be useful. I googled a little and found Guido van Robot although I'm not sure if it's exactly like what I'm talking about. Are there any others? Do you all think it'll be a worthwhile project? Bye -- -NI From ajikoe at gmail.com Tue Mar 28 10:16:34 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 28 Mar 2006 10:16:34 +0200 Subject: [Tutor] Object Oriented Programmin In-Reply-To: <6b16fb4c0603272327i451e2b57l28a0b7783deda90a@mail.gmail.com> References: <6b16fb4c0603272327i451e2b57l28a0b7783deda90a@mail.gmail.com> Message-ID: <cf5262d20603280016k571d7c63h887fae36794af309@mail.gmail.com> Object is object, means like ordinary object we know. Let's say good things about objecs paradigm. First you can create object of course. object can contain property and action. You can put your object as part as other object. It makes sense since for example object hand is part of object body in human term. You can derive a new object from your old one (with its property and action). You can, in this new object, add a new function or change the function from the old one. This will make your old object untouchable and your new object easy to build (you don't have to build from the start) Let's start with a simple code. We can create a simple dog class class dog: def __init__(self, name): self.name = name pass def action(self): print 'run' class doberman(dog): def __init__(self, name): dog.__init__(self,name) def bark(self): print 'wuu' class coco(dog): def __init__(self, name): dog.__init__(self,name) def action(self): print 'jump' def bark(self): print 'waa' #-------------------------------------------------- d1 = doberman('deni') d1.action() # 'run' d1.bark() # 'wuu' d2 = coco('mayin') d2.action() # 'jump' d2.bark() # 'waa' ---------------------------------------- Note: Each has name as an ID. a doberman uses the same action like dog class a coco uses different action than the original action from dog which is 'run' In this example we can see we can change one object easily and doesn't change the original class which is dog. This make less prone to error. both doberman and coco can use bark but the result will be different both doberman and coco can access name this also result in different way. It is nice since you can use the same word bark to all of the new dogs you've created. I try to describe as simple as I can. In this example you can put another function like getname in dog class so that all type of dogs has this function automaticaly. Hope this help pujo On 3/28/06, Kaushal Shriyan <kaushalshriyan at gmail.com> wrote: > > Hi ALL > > I have gone through the object oriented programming in Python, I am > not able to understand OOP concept in python, > > is there a methodical way to understand it and simplfy things > > Thanks in Advance > > Regards > > Kaushal > _______________________________________________ > 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/20060328/ecadd4f9/attachment.html From jonasmg at softhome.net Tue Mar 28 11:02:53 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Tue, 28 Mar 2006 02:02:53 -0700 Subject: [Tutor] using BeautifulSoup In-Reply-To: <4428939D.1070008@tds.net> References: <courier.44281F5D.00004BE9@softhome.net> <4428939D.1070008@tds.net> Message-ID: <courier.4428FBBD.00003FC4@softhome.net> Kent Johnson writes: > jonasmg at softhome.net wrote: >> anchor.findNext('code') fails: >> >> anchor = soup.fetch('a', {'href': '/wiki/List_of_country_calling_codes'}) >> print anchor >> >> [<a href="/wiki/List_of_country_calling_codes" title="List of country >> calling codes">Calling code</a>] >> >> anchor.findNext('code') >> [] > > are you sure that's what you got? Looks like an AttributeError to me - > anchor is a *list* of anchors. Try > anchor[0].findNext('code') > > Kent > With 'fetch' you get a list of Tag objects, so there is that using: anchor = soup.fetch('a', {'href': '/wiki/List_of_country_calling_codes'}) anchor[0].findNext('code') But with 'findChild' or 'first' you get only the first Tag that matches, so: anchor = soup.findChild('a', {'href': '/wiki/List_of_country_calling_codes'}) anchor.findNext('code') Thanks for your help, Kent From jonasmg at softhome.net Tue Mar 28 11:15:44 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Tue, 28 Mar 2006 02:15:44 -0700 Subject: [Tutor] BeautifulSoup - deleting tags Message-ID: <courier.4428FEC0.00004CAA@softhome.net> Is possible deleting all tags from a text and how? i.e.: qwe='<td><a href="..." title="...">foo bar</a>;<br /> <a href="..." title="...">foo2</a> <a href="..." title="...">bar2</a></td>' so, I would get only: foo bar, foo2, bar2 Thanks in advance! From kent37 at tds.net Tue Mar 28 12:40:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Mar 2006 05:40:59 -0500 Subject: [Tutor] Object Oriented Programmin In-Reply-To: <6b16fb4c0603272327i451e2b57l28a0b7783deda90a@mail.gmail.com> References: <6b16fb4c0603272327i451e2b57l28a0b7783deda90a@mail.gmail.com> Message-ID: <442912BB.2030304@tds.net> Kaushal Shriyan wrote: > Hi ALL > > I have gone through the object oriented programming in Python, I am > not able to understand OOP concept in python, Both Alan Gauld's tutorial and A Byte of Python have beginner's introductions to OOP: http://www.freenetpages.co.uk/hp/alan.gauld/ http://www.byteofpython.info/read/oops.html I have written an essay that talks about *why* you might want to use OOP, rathre than how... http://www.pycs.net/users/0000323/stories/15.html Kent From kent37 at tds.net Tue Mar 28 12:50:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Mar 2006 05:50:02 -0500 Subject: [Tutor] BeautifulSoup - deleting tags In-Reply-To: <courier.4428FEC0.00004CAA@softhome.net> References: <courier.4428FEC0.00004CAA@softhome.net> Message-ID: <442914DA.4070400@tds.net> jonasmg at softhome.net wrote: > Is possible deleting all tags from a text and how? > > i.e.: > > qwe='<td><a href="..." title="...">foo bar</a>;<br /> > <a href="..." title="...">foo2</a> <a href="..." title="...">bar2</a></td>' > > so, I would get only: foo bar, foo2, bar2 How about this? In [1]: import BeautifulSoup In [2]: s=BeautifulSoup.BeautifulSoup('''<td><a href="..." title="...">foo bar</a>;<br /> ...: <a href="..." title="...">foo2</a> <a href="..." title="...">bar2</a></td>''') In [4]: ' '.join(i.string for i in s.fetch() if i.string) Out[4]: 'foo bar foo2 bar2' Here are a couple of tag strippers that don't use BS: http://www.aminus.org/rbre/python/cleanhtml.py http://www.oluyede.org/blog/2006/02/13/html-stripper/ Kent From kaushalshriyan at gmail.com Tue Mar 28 13:23:10 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 28 Mar 2006 16:53:10 +0530 Subject: [Tutor] Object Oriented Programmin In-Reply-To: <442912BB.2030304@tds.net> References: <6b16fb4c0603272327i451e2b57l28a0b7783deda90a@mail.gmail.com> <442912BB.2030304@tds.net> Message-ID: <6b16fb4c0603280323p4132e5ddrc97e3b3e0e1272a9@mail.gmail.com> On 3/28/06, Kent Johnson <kent37 at tds.net> wrote: > Kaushal Shriyan wrote: > > Hi ALL > > > > I have gone through the object oriented programming in Python, I am > > not able to understand OOP concept in python, > > Both Alan Gauld's tutorial and A Byte of Python have beginner's > introductions to OOP: > http://www.freenetpages.co.uk/hp/alan.gauld/ > http://www.byteofpython.info/read/oops.html > > I have written an essay that talks about *why* you might want to use > OOP, rathre than how... > http://www.pycs.net/users/0000323/stories/15.html > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Thanks a Bunch to All Kaushal From jonasmg at softhome.net Tue Mar 28 13:35:38 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Tue, 28 Mar 2006 04:35:38 -0700 Subject: [Tutor] BeautifulSoup - deleting tags In-Reply-To: <442914DA.4070400@tds.net> References: <courier.4428FEC0.00004CAA@softhome.net> <442914DA.4070400@tds.net> Message-ID: <courier.44291F8A.00006401@softhome.net> Kent Johnson writes: > jonasmg at softhome.net wrote: >> Is possible deleting all tags from a text and how? >> >> i.e.: >> >> s='<td><a href="..." title="...">foo bar</a>;<br /> >> <a href="..." title="...">foo2</a> <a href="..." >> title="...">bar2</a></td>' >> >> so, I would get only: foo bar, foo2, bar2 > > How about this? > > In [1]: import BeautifulSoup > > In [2]: s=BeautifulSoup.BeautifulSoup('''<td><a href="..." title="...">foo > bar</a>;<br /> > ...: <a href="..." title="...">foo2</a> <a href="..." > title="...">bar2</a></td>''') > > In [4]: ' '.join(i.string for i in s.fetch() if i.string) > Out[4]: 'foo bar foo2 bar2' > > > Here are a couple of tag strippers that don't use BS: > http://www.aminus.org/rbre/python/cleanhtml.py > http://www.oluyede.org/blog/2006/02/13/html-stripper/ > > Kent > Another way (valid only for this case): : for i in s.fetch('a'): print i.string From stvsmth at gmail.com Tue Mar 28 17:37:01 2006 From: stvsmth at gmail.com (stv) Date: Tue, 28 Mar 2006 10:37:01 -0500 Subject: [Tutor] Learning Python In-Reply-To: <24709.203.145.176.76.1143458775.squirrel@members.hcoop.net> References: <6b16fb4c0603270309i426b38a8qd1d16e3a7ebb1377@mail.gmail.com> <24709.203.145.176.76.1143458775.squirrel@members.hcoop.net> Message-ID: <9493d0340603280737x4d5c3812y6d636f3713cd0ec4@mail.gmail.com> If you're a bookish type, I found Magnus Lie Hetland's "Beginning Python" excellent. It's really more than a beginners books. I came to Python with a scripting background--mostly lightweight OS stuff (Applescript, DOS) as well as a lot of lightweight application programming (Filemaker, SQL, VBA for Excel, etc) and I got a lot out of the book. It covers the basics for a true beginner, but not in a dumbed-down way. It's also well indexed & somewhat useful as a reference for the most common things. Mark Pilgrim's "Dive Into Python" comes highly recommended, and is available on-line. From oasf2004 at yahoo.com Tue Mar 28 18:56:10 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Tue, 28 Mar 2006 08:56:10 -0800 (PST) Subject: [Tutor] Learning Python In-Reply-To: <9493d0340603280737x4d5c3812y6d636f3713cd0ec4@mail.gmail.com> Message-ID: <20060328165610.78352.qmail@web60013.mail.yahoo.com> I do recommend three books: (1) "How to Think Like a Computer Scientist: Learning with Python", by Allen Downey, Jeffrey Elkner, and Chris Meyers. There exist a free online version, too: http://www.ibiblio.org/obp/thinkCSpy/ (2) "Learning Python", by Mark Lutz and David Ascher. (3) "Beginning Python", by Magnus Lie Hetland. This is all you need for a good start with python. Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From Barry.Carroll at psc.com Tue Mar 28 19:02:36 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 28 Mar 2006 09:02:36 -0800 Subject: [Tutor] setdefault method Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3634@eugsrv400.psc.pscnet.com> Terry and Kent: Thanks for your timely replies. I agree: its creator could have chosen a more intuitive name for setdefault. 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 Barry.Carroll at psc.com Tue Mar 28 19:10:32 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 28 Mar 2006 09:10:32 -0800 Subject: [Tutor] Tutor Digest, Vol 25, Issue 70 Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3635@eugsrv400.psc.pscnet.com> John: Well, I haven't made a custom container class before. This looks like a good time to start. And the sample code you provided looks like a good starting place. 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 > ------------------------------ > > Message: 2 > Date: Tue, 28 Mar 2006 12:33:46 +1200 > From: "John Fouhy" <john at fouhy.net> > Subject: Re: [Tutor] Data Type with Dictionary and List Behavior > To: tutor at python.org > Message-ID: > <5e58f2e40603271633w520296bdndba139c38c3f322d at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > <<snip>> > > Probably your best bet is to define your own container class. If you > define __getitem__, you can use [] with instances of your class, just > like lists or dicts. > <<snip>> > > HTH! > > -- > John. > > From rozdaniel at hotmail.com Tue Mar 28 19:20:18 2006 From: rozdaniel at hotmail.com (Ros Daniel) Date: Tue, 28 Mar 2006 12:20:18 -0500 Subject: [Tutor] Guessing a number with limited no. of tries game gone wrong. Message-ID: <BAY102-F27497D1C171383B6B04409A3D30@phx.gbl> I am a newbie at Python. Just bought Python Programming 2nd ed. by Michael Dawson. While I understand the concepts as the book is going through the code, and I am able get the same results, when it comes to applying what I've learned to the exercises at the end of each chapter, I seem to be stumped. I think my logic is off somehow. I am able to get the program to work if it's just a case of the user guessing the random number, and then being told they guessed correctly in a certain number of tries. It's when the user has a limited number of guesses that I am stumped. Either I get an infinite loop, or the program will say I guessed right in a certain number of tries, but the guess is not correct Can anyone explain to me what I'm missing and doing wrong? Thanks. # Modify the Guess My Number game so that the player has a limited number of guesses. If the player fails to guess in time, the program should display an appropriately chastising message. import random print "Welcome to the new and improved 'Guess My Number' game." print "This time you have a limited number of guesses, so guess wisely.\n" the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 # guessing loop while (guess != the_number): if tries > 5: break elif guess > the_number: print "Lower..." elif guess < the_number: print "Higher..." guess = int(raw_input("Guess again:")) tries += 1 # message of congratulations print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" From johnmlesko at gmail.com Tue Mar 28 22:29:28 2006 From: johnmlesko at gmail.com (John Lesko) Date: Tue, 28 Mar 2006 15:29:28 -0500 Subject: [Tutor] Python tutor In-Reply-To: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: <4ecd786d0603281229l2e35d0a5qa09797a364df1ec4@mail.gmail.com> This actually sounds like very good idea. I have not heard of it before, but I think it would be a very good way to learn. Let me know if you find anything. John On 3/28/06, Noufal Ibrahim <noufal at nibrahim.net.in> wrote: > > Greetings all, > Are there any programs for python that offer an "interactive" tutorial? > Something on the lines of the builtin emacs tutorial (which is > basically just a buffer that tells you to try this and try that with > itself) or the Inkscape tutorial (which is an SVG document that comes > along with inkscape which has instructions on manipulating it so that > the reader learns stuff). Another example that comes to mind is the > tcltutor program to learn TCL. It contains an instruction window, a > code window and an output window. The user is told something, they try > it and the output is visible. I personally used it when I was learning > TCL. > > The python tutorial is great and probably all one needs to learn the > language but I think a more interactive program to teach it might be > useful. I googled a little and found Guido van Robot although I'm not > sure if it's exactly like what I'm talking about. Are there any others? > Do you all think it'll be a worthwhile project? > > Bye > > -- > -NI > > _______________________________________________ > 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/20060328/82fb346a/attachment-0001.html From natmenon at yahoo.com Tue Mar 28 22:39:13 2006 From: natmenon at yahoo.com (Natasha Menon) Date: Tue, 28 Mar 2006 12:39:13 -0800 (PST) Subject: [Tutor] Python help Message-ID: <20060328203913.30126.qmail@web52114.mail.yahoo.com> hi, i need help on a terrible homework assignment. do ul offer hw help? natasha --------------------------------- 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/20060328/fec61b9b/attachment.html From dyoo at hkn.eecs.berkeley.edu Tue Mar 28 23:10:49 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 Mar 2006 13:10:49 -0800 (PST) Subject: [Tutor] Python help In-Reply-To: <20060328203913.30126.qmail@web52114.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0603281303240.8265-100000@hkn.eecs.berkeley.edu> On Tue, 28 Mar 2006, Natasha Menon wrote: > i need help on a terrible homework assignment. do ul offer hw help? Not directly. Your homework is really your own to do. Please try to avoid the temptation of just posting a homework question here and hoping that someone will do the work for you. See: http://www.catb.org/~esr/faqs/smart-questions.html#homework But if you are asking for documentation or tutorial resources, or if you'd like to talk about general concepts or examples to help make things less confusing, we'll be happy to help in that way. Good luck to you. From singingxduck at gmail.com Tue Mar 28 23:24:04 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Tue, 28 Mar 2006 16:24:04 -0500 Subject: [Tutor] Data Type with Dictionary and List Behavior In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3633@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C3633@eugsrv400.psc.pscnet.com> Message-ID: <4429A974.90900@gmail.com> Carroll, Barry wrote: >Greetings: > >I have a function that computes the checksum of an integer, including or excluding digits in the computation based on the content of a mask string. For example, > > cksum(123456789, '***...***') > >will do its computation on 123789, masking out the three non-significant digits. > >My question concerns assigning the value of the mask string. The class that defines the function also pre-defines several masks, say '*********', '***...***', and '......***'. The masks have names: 'all', 'first-last', 'last'. Of these, 'all' is the most commonly used. The user may select one of these masks, or may supply their own, arbitrary value. Further, the user can choose to add their value to the group of pre-defines, and reuse that value later in the session. (The user-defined mask is not saved between sessions; no permanent storage is required.) > >So far, this structure looks like a dictionary. However, the user also wants to access the group of pre-defined masks as if they were elements of a list: > > masks[0] returns '*********' > masks[1] returns '***...***' > >and so on. To make matters even more complex, if the user does not specify a mask to use, the function should use the mask employed in the previous invocation, defaulting to masks[0] if this is the first invocation. Finally, the user can set a mask as 'default', which essentially marks a mask as 'last used' without invoking the function. > >Is there a derived type or data structure in existence that implements these capabilities (in descending order of importance? > > 1. Access by name (dict) > 2. Access by position (list) > 3. Addition of new items (dict, list) > 4. Set a 'last used' item (??????) > 5. Set a 'default' item (dict???) > >Thanks in advance 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 > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Would the following fit the bill? >>> class maskdict(dict): def __init__(self, seq={}): dict.__init__(self,{True:["*********","***...***","......***"],False:{"all":"*********","first-last":"***...***","last":"......***",None:"**********"}}) self.update(seq) def __getitem__(self, index=None): dict.__getitem__(self, isinstance(index,int))[index] self[None] = dict.__getitem__(self,isinstance(index,int))[index] return dict.__getitem__(self, False)[None] def __setitem__(self, index, value): if isinstance(index, int): return dict.__setitem__(self, isinstance(index,int), dict.__getitem__(self,isinstance(index,int))+[value]) return dict.__setitem__(dict.__getitem__(self, False), index, value) def setdef(self, default): self[None] = default >>> md = maskdict() >>> md[0] '*********' >>> md["all"] '*********' >>> md[1] '***...***' >>> md["first-last"] '***...***' >>> md[2] '......***' >>> md["last"] '......***' >>> md.__getitem__() # md[] results in a syntax error instead of passing None on to __getitem__ like you'd expect '......***' >>> md[1] '***...***' >>> md.__getitem__() '***...***' >>> md[0] '*********' >>> md.__getitem__() '*********' >>> md[3] = "****....." >>> md[3] '****.....' >>> md["first-four"] = md[3] >>> md["first-four"] '****.....' >>> md.setdef(md[3]) >>> md.__getitem__() '****.....' You'd still have to figure out how to integrate it in to your checksum function as well as make meaningful error messages, but it should give you a good start. Cheers, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From mhansen at cso.atmel.com Tue Mar 28 23:38:42 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 28 Mar 2006 14:38:42 -0700 Subject: [Tutor] Object Oriented Programmin In-Reply-To: <mailman.12592.1143536579.27774.tutor@python.org> References: <mailman.12592.1143536579.27774.tutor@python.org> Message-ID: <4429ACE2.60603@cso.atmel.com> > Subject: > [Tutor] Object Oriented Programmin > From: > "Kaushal Shriyan" <kaushalshriyan at gmail.com> > Date: > Tue, 28 Mar 2006 12:57:58 +0530 > To: > tutor at python.org > > To: > tutor at python.org > > > Hi ALL > > I have gone through the object oriented programming in Python, I am > not able to understand OOP concept in python, > > is there a methodical way to understand it and simplfy things > > Thanks in Advance > > Regards > > Kaushal > If you are reading Learning Python(2nd Ed), the OOP section was a little thick to me. I read the book, The Object Oriented Thought Process. Then I went back and read the chapters on OOP in Learning Python, and it made a lot more sense. Mike From annaraven at gmail.com Wed Mar 29 01:05:49 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Tue, 28 Mar 2006 15:05:49 -0800 Subject: [Tutor] Python tutor In-Reply-To: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: <cb361a610603281505j6aa562b1ub28266d1b3d591c1@mail.gmail.com> On 3/27/06, Noufal Ibrahim <noufal at nibrahim.net.in> wrote: > > Greetings all, > Are there any programs for python that offer an "interactive" tutorial? > Something on the lines of the builtin emacs tutorial (which is > basically just a buffer that tells you to try this and try that with > itself) or the Inkscape tutorial (which is an SVG document that comes > along with inkscape which has instructions on manipulating it so that > the reader learns stuff). Another example that comes to mind is the > tcltutor program to learn TCL. It contains an instruction window, a > code window and an output window. The user is told something, they try > it and the output is visible. I personally used it when I was learning > TCL. > > The python tutorial is great and probably all one needs to learn the > language but I think a more interactive program to teach it might be > useful. I googled a little and found Guido van Robot although I'm not > sure if it's exactly like what I'm talking about. Are there any others? > Do you all think it'll be a worthwhile project? There are several of us on the edupython list who want something like this but it hasn't (to my knowledge) been created yet. The best things out there so far, are livewires, guido von robot, and rur-ple. If you're interested in working on such a project, you're welcome to join us. http://groups.google.com/group/edupython -- cordially, Anna -- It is fate, but call it Italy if it pleases you, Vicar! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060328/d3229f75/attachment.htm From victor at grupocdm.com Wed Mar 29 02:03:20 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 28 Mar 2006 18:03:20 -0600 Subject: [Tutor] Guessing a number with limited no. of tries game gone wrong. In-Reply-To: <BAY102-F27497D1C171383B6B04409A3D30@phx.gbl> References: <BAY102-F27497D1C171383B6B04409A3D30@phx.gbl> Message-ID: <1143590600.4004.17.camel@elrond> Hi Ros, Look what happens when the user tried for more than 5 times: if tries > 5: break This just takes you out of the loop, but it does not handle the issue that the user did not guess correctly. The next statement will be to print the congratulations message. You should instead tell the user they did not make it and exit the program altogether, probably letting them know what the actual number was. Something like: if tries > 5: print "Too bad. You tried one too many times." print "The number was", the_number sys.exit() You have to 'import sys' first though. Try it out and analyze the flow of the program. Use the debugger to try your code one step at a time to see what is going wrong. I would also change the initial guess to specify the range, like: guess = int(raw_input("Take a guess between 1 and 100: ")) Best of luck. Victor On Tue, 2006-03-28 at 12:20 -0500, Ros Daniel wrote: > I am a newbie at Python. Just bought Python Programming 2nd ed. by Michael > Dawson. While I understand the concepts as the book is going through the > code, and I am able get the same results, when it comes to applying what > I've learned to the exercises at the end of each chapter, I seem to be > stumped. I think my logic is off somehow. I am able to get the program to > work if it's just a case of the user guessing the random number, and then > being told they guessed correctly in a certain number of tries. It's when > the user has a limited number of guesses that I am stumped. Either I get an > infinite loop, or the program will say I guessed right in a certain number > of tries, but the guess is not correct > > Can anyone explain to me what I'm missing and doing wrong? Thanks. > > # Modify the Guess My Number game so that the player has a limited number of > guesses. If the player fails to guess in time, the program should display an > appropriately chastising message. > > > > import random > > print "Welcome to the new and improved 'Guess My Number' game." > print "This time you have a limited number of guesses, so guess wisely.\n" > > > the_number = random.randrange(100) + 1 > > guess = int(raw_input("Take a guess: ")) > tries = 1 > > # guessing loop > while (guess != the_number): > if tries > 5: > break > elif guess > the_number: > print "Lower..." > elif guess < the_number: > print "Higher..." > > guess = int(raw_input("Guess again:")) > tries += 1 > > > # message of congratulations > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From oasf2004 at yahoo.com Wed Mar 29 02:13:56 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Tue, 28 Mar 2006 16:13:56 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward Message-ID: <20060329001356.93209.qmail@web60019.mail.yahoo.com> Hello: I am trying to write a code (this is an exercose from a book). The goal is to write a program that takes a string and outputs the letters backward, ine per line. Ok. I did a test first, by writing a code with numbers: a=0; b=10 while a<=b: print b b -= 1 Here the output is: 10 9 8 7 6 5 4 3 2 1 0 That worked fine. Now, back to my exercise. I tried to write a code that takes the string 'car' as the input: vehicle='car' index = vehicle[-1] #the last letter index_zero = vehicle[0] #the first letter while index >= index_zero: letter=vehicle[index] print letter index -= 1 The problem is that I get no output here. Could I hear from you? Thanks! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john at fouhy.net Wed Mar 29 02:22:36 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 29 Mar 2006 12:22:36 +1200 Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <20060329001356.93209.qmail@web60019.mail.yahoo.com> References: <20060329001356.93209.qmail@web60019.mail.yahoo.com> Message-ID: <5e58f2e40603281622s5d88cfb8nf8b32fb02b4b814@mail.gmail.com> On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > vehicle='car' > index = vehicle[-1] #the last letter > index_zero = vehicle[0] #the first letter > > while index >= index_zero: > letter=vehicle[index] > print letter > index -= 1 > > The problem is that I get no output here. Could I hear > from you? I can print the letters backwards like this: vehicle = 'car' print vehicle[2] print vehicle[1] print vehicle[0] Output: r a c ----- This is not very useful, though, because it will only work for strings that are exactly three letters long. Can you see how to write a loop to produe this output? Hint: the len() function will tell you how long a string is. eg: if vehicle == 'car' then len(vehicle) == 3. -- John. From hugonz-lists at h-lab.net Wed Mar 29 02:27:26 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 28 Mar 2006 18:27:26 -0600 Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <20060329001356.93209.qmail@web60019.mail.yahoo.com> References: <20060329001356.93209.qmail@web60019.mail.yahoo.com> Message-ID: <4429D46E.90905@h-lab.net> Hoffmann wrote: > while index >= index_zero: > letter=vehicle[index] > print letter > index -= 1 > > The problem is that I get no output here. Could I hear > from you? Hi, remember that the condition for the while has to be true. When does index >= index_zero stop being true??? Hope that gets you going, Hugo Ps: there are easier ways of doing this in Python, consider the "for" statement. From mbroe at columbus.rr.com Wed Mar 29 02:41:29 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Tue, 28 Mar 2006 19:41:29 -0500 Subject: [Tutor] Bigrams and nested dictionaries Message-ID: <5D5788FC-DA46-4E25-A5A9-014DFCC8EF9A@columbus.rr.com> I'm playing with the whole idea of creating bigram (digram?) frequencies for text analysis and cryptographic and entropy analysis etc (this is as much an exercise in learning Python and programming as anything else, I realise everything has already been done somewhere somehow :) Though I *am* aiming to run this over unicoded phonetic representations of natural languages, which doesn't seem to be that common. I implemented a single character count using a dictionary, and it worked really well: Character_Count = {} for character in text: Character_Count[character] = Character_Count.get(character, 0) + 1 And so for bigrams I was thinking of creating a data-structure that was a nested dictionary, where the key was the character in position 1, and the value was a sub-dictionary that gave a count of each character in position 2. So the dictionary might begin something like: {'a': {'a':1, 'b':8, 'c':10,...}, 'b' : {'a':23, 'b':0, 'c': 1,...},..., 'z' : {'a':11, 'b':0, 'c':0,...}} The count of the character in position one could be retrieved by summing over the characters in position 2, so the bigram and single- character counts can be done in one pass. I don't want anyone to tell me how to do this :) I'd just like to get a feel for: (i) is this idea of a nested dictionary a good/efficient/tractable data-structure? (ii) is there a straightforward path to the goal of constructing this thing in a single pass over the input string (yes or no will suffice for the moment!), or is there a can of worms lurking in my future. I'd rather have less information than more, but there is something about grabbing characters two-at-a-time, but moving forward one-at-a- time, and sticking the count down a level inside the dictionary that's just a little baffling at the moment. On the other hand it's like moving a two-character window across the text and recording information as you go, which seems like it should be a good thing to do computationally. I like being baffled, I'd just kinda like to know if this is a good problem to work on to gain enlightenment, or a bad one and I should think about a totally different path with a less jazzy data structure. From artificiallystupid at yahoo.com Wed Mar 29 03:11:25 2006 From: artificiallystupid at yahoo.com (Johnston Jiaa) Date: Tue, 28 Mar 2006 17:11:25 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward Message-ID: <20060329011125.25517.qmail@web50411.mail.yahoo.com> Hoffman, I am a newbie at python and programming in general so excuse me if I'm wrong. In your example, you had while index >= index_zero: which I believe to not be what you intended as you are essentially saying: while "last letter of vehicle" >= "first letter of vehicle" "e" is respectively "less than" "v", so that is why your code never executes. You probably mean for the index to actually be the index, not the last letter. "index -= 1" is illegal as the variable points to a string, which can not be subtracted from. Hope I was of help! Johnston Jiaa (artificiallystupid at yahoo.com) --------------------------------- 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/20060328/25d0ce63/attachment.htm From mbroe at columbus.rr.com Wed Mar 29 04:03:30 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Tue, 28 Mar 2006 21:03:30 -0500 Subject: [Tutor] Bigrams and nested dictionaries Message-ID: <C2C575FD-9987-4B16-AEF2-98A8A077702E@columbus.rr.com> Well I ran into an interesting glitch already. For a dictionary D, I can pull out a nested value using this syntax: >>> D['b']['a'] 23 and I can assign to this dictionary using >>> D['d'] = {'a':7, 'b':0'} but I can't assign like this: >>> D['d']['c'] = 1 TypeError: object does not support item assignment. hmmm. From john at fouhy.net Wed Mar 29 04:34:30 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 29 Mar 2006 14:34:30 +1200 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: <C2C575FD-9987-4B16-AEF2-98A8A077702E@columbus.rr.com> References: <C2C575FD-9987-4B16-AEF2-98A8A077702E@columbus.rr.com> Message-ID: <5e58f2e40603281834k3519db40re5d83f1252295858@mail.gmail.com> On 29/03/06, Michael Broe <mbroe at columbus.rr.com> wrote: > Well I ran into an interesting glitch already. For a dictionary D, I > can pull out a nested value using this syntax: > > >>> D['b']['a'] > 23 > > and I can assign to this dictionary using > > >>> D['d'] = {'a':7, 'b':0'} > > but I can't assign like this: > > >>> D['d']['c'] = 1 > TypeError: object does not support item assignment. I can't reproduce this... >>> D = {} >>> D['d'] = {'a':7, 'b':0} >>> D['d']['c'] = 1 >>> D {'d': {'a': 7, 'c': 1, 'b': 0}} Are you sure you haven't mistakenly assigned something other than a dict to D or D['d'] ? -- John. From oasf2004 at yahoo.com Wed Mar 29 04:42:07 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Tue, 28 Mar 2006 18:42:07 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <5e58f2e40603281622s5d88cfb8nf8b32fb02b4b814@mail.gmail.com> Message-ID: <20060329024207.38563.qmail@web60020.mail.yahoo.com> --- John Fouhy <john at fouhy.net> wrote: > On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > > vehicle='car' > > index = vehicle[-1] #the last letter > > index_zero = vehicle[0] #the first letter > > > > while index >= index_zero: > > letter=vehicle[index] > > print letter > > index -= 1 > > > > The problem is that I get no output here. Could I > hear > > from you? > > I can print the letters backwards like this: > > vehicle = 'car' > print vehicle[2] > print vehicle[1] > print vehicle[0] > > Output: > > r > a > c > > ----- > > This is not very useful, though, because it will > only work for strings > that are exactly three letters long. Can you see > how to write a loop > to produe this output? > > Hint: the len() function will tell you how long a > string is. > > eg: if vehicle == 'car' then len(vehicle) == 3. > > -- > John. > _______________________________________________ Hi John and the other colleagues from the Tutor, I still didn't realized how to solve this exercise. Regarding the for loop. I can do that for the "forward" version of the program. See below: name = 'car' for char in name: print char However, I still write a "backward" version (in order to get r a c Could you guys, please, continue talking to me? Thanks! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kp8 at mac.com Wed Mar 29 04:52:54 2006 From: kp8 at mac.com (kevin parks) Date: Tue, 28 Mar 2006 21:52:54 -0500 Subject: [Tutor] Alternating patterns In-Reply-To: <mailman.12206.1143238969.27774.tutor@python.org> References: <mailman.12206.1143238969.27774.tutor@python.org> Message-ID: <c6b99ee26cf49a3d1cc1a3c92c9ac94f@mac.com> I have a set that i iterate over... but each time through it i would like to alternate between the original set and a variation of the set that has one of the members of the set altered (by + or - 1) So if my original set is: [0, 2, 4, 5, 7, 9, 11] I would use that the first pass but on the second pass i might like the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, 9, 11] But then back again to the original on the next pass (+1 back to 4,): [0, 2, 4, 5, 7, 9, 11] and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. in other words i would like to alternate members of the set back and forth. Usually only 1 (or sometimes 2,) member at time. i could also imagine a needing(alter one, alter another, undo that, undo the first back to the original set): [0, 2, 4, 5, 7, 9, 11] --> [0, 2, 3, 5, 7, 9, 11] --> [0, 2, 3, 5, 7, 8, 10] --> [0, 2, 3, 5, 7, 9, 11] --> [0, 2, 4, 5, 7, 9, 11] or: original --> [0, 2, 4, 5, 7, 9, 11] altered --> [0, 2, 3, 5, 7, 9, 11] now back to 4, but change something else (like 11, is now 10): [0, 2, 4, 5, 7, 9, 10] etc... How can one make such alternating patterns? -kp-- From kent37 at tds.net Wed Mar 29 05:24:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Mar 2006 22:24:11 -0500 Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <20060329001356.93209.qmail@web60019.mail.yahoo.com> References: <20060329001356.93209.qmail@web60019.mail.yahoo.com> Message-ID: <4429FDDB.9020208@tds.net> Hoffmann wrote: > Hello: > > I am trying to write a code (this is an exercose from > a book). The goal is to write a program that takes a > string and outputs the letters backward, ine per > line. > Ok. I did a test first, by writing a code with > numbers: > > a=0; b=10 > while a<=b: > print b > b -= 1 > > Here the output is: > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2 > 1 > 0 > That worked fine. > Now, back to my exercise. I tried to write a code that > takes the string 'car' as the input: > > vehicle='car' > index = vehicle[-1] #the last letter > index_zero = vehicle[0] #the first letter > > while index >= index_zero: > letter=vehicle[index] > print letter > index -= 1 You are confusing the index of a letter - the number which represents its position in the word - with the letter itself. In your code, index and index_zero are actually letters, not indices. Try to rewrite the code so they are numbers. > > The problem is that I get no output here. My guess is you got a TypeError on the line letter=vehicle[index] decause index is a letter. It's important to give us accurate descriptions of what happens, and to show error messages and the tracebacks that come with them. This can be very helpful when you have a problem. Kent From oasf2004 at yahoo.com Wed Mar 29 05:29:42 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Tue, 28 Mar 2006 19:29:42 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <4429FDDB.9020208@tds.net> Message-ID: <20060329032942.94360.qmail@web60018.mail.yahoo.com> --- Kent Johnson <kent37 at tds.net> wrote: > Hoffmann wrote: > > Hello: > > > > I am trying to write a code (this is an exercose > from > > a book). The goal is to write a program that takes > a > > string and outputs the letters backward, ine per > > line. > > Ok. I did a test first, by writing a code with > > numbers: > > > > a=0; b=10 > > while a<=b: > > print b > > b -= 1 > > > > Here the output is: > > 10 > > 9 > > 8 > > 7 > > 6 > > 5 > > 4 > > 3 > > 2 > > 1 > > 0 > > That worked fine. > > Now, back to my exercise. I tried to write a code > that > > takes the string 'car' as the input: > > > > vehicle='car' > > index = vehicle[-1] #the last letter > > index_zero = vehicle[0] #the first letter > > > > while index >= index_zero: > > letter=vehicle[index] > > print letter > > index -= 1 > > You are confusing the index of a letter - the number > which represents > its position in the word - with the letter itself. > In your code, index > and index_zero are actually letters, not indices. > Try to rewrite the > code so they are numbers. > > > > The problem is that I get no output here. > > My guess is you got a TypeError on the line > letter=vehicle[index] > > decause index is a letter. It's important to give us > accurate > descriptions of what happens, and to show error > messages and the > tracebacks that come with them. This can be very > helpful when you have a > problem. > > Kent > > _______________________________________________ Hi Kent, Sorry for not showing the traceback the first time. Please, see it below: Traceback (most recent call last): File "<stdin>", line 2, in ? TypeError: string indices must be integers Any hint? Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Wed Mar 29 05:30:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Mar 2006 22:30:53 -0500 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: <5D5788FC-DA46-4E25-A5A9-014DFCC8EF9A@columbus.rr.com> References: <5D5788FC-DA46-4E25-A5A9-014DFCC8EF9A@columbus.rr.com> Message-ID: <4429FF6D.2060504@tds.net> Michael Broe wrote: > I'm playing with the whole idea of creating bigram (digram?) > frequencies for text analysis and cryptographic and entropy analysis > etc (this is as much an exercise in learning Python and programming > as anything else, I realise everything has already been done > somewhere somehow :) Though I *am* aiming to run this over unicoded > phonetic representations of natural languages, which doesn't seem to > be that common. > > I implemented a single character count using a dictionary, and it > worked really well: > > Character_Count = {} > for character in text: > Character_Count[character] = Character_Count.get(character, 0) + 1 > > And so for bigrams I was thinking of creating a data-structure that > was a nested dictionary, where the key was the character in position > 1, and the value was a sub-dictionary that gave a count of each > character in position 2. > > So the dictionary might begin something like: > > {'a': {'a':1, 'b':8, 'c':10,...}, 'b' : {'a':23, 'b':0, 'c': > 1,...},..., 'z' : {'a':11, 'b':0, 'c':0,...}} > > The count of the character in position one could be retrieved by > summing over the characters in position 2, so the bigram and single- > character counts can be done in one pass. > > I don't want anyone to tell me how to do this :) I'd just like to get > a feel for: > > (i) is this idea of a nested dictionary a good/efficient/tractable > data-structure? It can work. An alternative is a dictionary keyed by the two-letter pairs. I don't know which will work better. > > (ii) is there a straightforward path to the goal of constructing this > thing in a single pass over the input string (yes or no will suffice > for the moment!), or is there a can of worms lurking in my future. I think so. > > I'd rather have less information than more, but there is something > about grabbing characters two-at-a-time, but moving forward one-at-a- > time, and sticking the count down a level inside the dictionary > that's just a little baffling at the moment. Encapsulating this in a generator is probably a good plan. If you want help look at the online cookbook. The generator can yield two-character strings or tuples of characters, whichever is more convenient. When you have a generator for the pairs the rest of the program will be pretty straightforward. Kent From kent37 at tds.net Wed Mar 29 05:43:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Mar 2006 22:43:38 -0500 Subject: [Tutor] Alternating patterns In-Reply-To: <c6b99ee26cf49a3d1cc1a3c92c9ac94f@mac.com> References: <mailman.12206.1143238969.27774.tutor@python.org> <c6b99ee26cf49a3d1cc1a3c92c9ac94f@mac.com> Message-ID: <442A026A.9010107@tds.net> kevin parks wrote: > I have a set that i iterate over... but each time through it i would > like to alternate between the original set and a variation of the set > that has one of the members of the set altered (by + or - 1) > > So if my original set is: > > [0, 2, 4, 5, 7, 9, 11] > > I would use that the first pass but on the second pass i might like > the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, > 9, 11] > > But then back again to the original on the next pass (+1 back to 4,): > [0, 2, 4, 5, 7, 9, 11] > > and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. > How can one make such alternating patterns? itertools.cycle() will repeat a sequence indefinitely: In [2]: from itertools import cycle In [3]: i=cycle([1,2]) In [5]: for j in range(6): ...: print i.next() ...: ...: 1 2 1 2 1 2 For non-repeating sequences I would look at writing a generator function for the sequences. Kent From kent37 at tds.net Wed Mar 29 05:46:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Mar 2006 22:46:29 -0500 Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <20060329032942.94360.qmail@web60018.mail.yahoo.com> References: <20060329032942.94360.qmail@web60018.mail.yahoo.com> Message-ID: <442A0315.1070803@tds.net> Hoffmann wrote: > --- Kent Johnson <kent37 at tds.net> wrote: > >>You are confusing the index of a letter - the number >>which represents >>its position in the word - with the letter itself. >>In your code, index >>and index_zero are actually letters, not indices. >>Try to rewrite the >>code so they are numbers. > > Sorry for not showing the traceback the first time. > Please, see it below: > > Traceback (most recent call last): > File "<stdin>", line 2, in ? > TypeError: string indices must be integers > > Any hint? Already gave the hint in the first part of my reply. The error message repeats it. Kent From hugonz-lists at h-lab.net Wed Mar 29 06:51:32 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 28 Mar 2006 22:51:32 -0600 Subject: [Tutor] Python help In-Reply-To: <20060328203913.30126.qmail@web52114.mail.yahoo.com> References: <20060328203913.30126.qmail@web52114.mail.yahoo.com> Message-ID: <442A1254.8010702@h-lab.net> Why not post where you are stuck or what you are trying to understand? and we'll give you help and direction. What we cannot do is solve your homework for you. Hugo Natasha Menon wrote: > hi, > > i need help on a terrible homework assignment. do ul offer hw help? > From mbroe at columbus.rr.com Wed Mar 29 07:15:30 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Wed, 29 Mar 2006 00:15:30 -0500 Subject: [Tutor] Bigrams and nested dictionaries Message-ID: <6FD8FE0A-2A38-4611-A207-5743FF863C5A@columbus.rr.com> Aha! John wrote: "Are you sure you haven't mistakenly assigned something other than a dict to D or D['d'] ?" Thanks for the tip! Yup that was it (and apologies for not reporting the problem more precisely). I hadn't initialized the nested dictionary before trying to assign to it. (I think Perl doesn't require initialization of dictionaries prior to assignment, which in this case, would be a nice thing...) >>> D['a'] = {'a':1, 'b':2} #oops Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'D' is not defined >>> D = {} >>> D['a'] = {'a':1, 'b':2} >>> D {'a': {'a': 1, 'b': 2}} >>> D['c']['a'] = 1 #ooops Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: 'c' >>> D['c'] = {} >>> D['c']['a'] = 1 >>> D {'a': {'a': 1, 'b': 2}, 'c': {'a': 1}} And Kent wrote: "Encapsulating this in a generator is probably a good plan." Yay, I get to play with generators... thanks for the suggestion, I would never have looked in that direction. -------------------------- Python: [x for S in L for x in S] Mathematica: Flatten[L] (but where's the fun in that?) From oasf2004 at yahoo.com Wed Mar 29 07:19:45 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Tue, 28 Mar 2006 21:19:45 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <5e58f2e40603281622s5d88cfb8nf8b32fb02b4b814@mail.gmail.com> Message-ID: <20060329051945.1048.qmail@web60022.mail.yahoo.com> --- John Fouhy <john at fouhy.net> wrote: > On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > > vehicle='car' > > index = vehicle[-1] #the last letter > > index_zero = vehicle[0] #the first letter > > > > while index >= index_zero: > > letter=vehicle[index] > > print letter > > index -= 1 > > > > The problem is that I get no output here. Could I > hear > > from you? > > I can print the letters backwards like this: > > vehicle = 'car' > print vehicle[2] > print vehicle[1] > print vehicle[0] > > Output: > > r > a > c > > ----- > > This is not very useful, though, because it will > only work for strings > that are exactly three letters long. Can you see > how to write a loop > to produe this output? > > Hint: the len() function will tell you how long a > string is. > > eg: if vehicle == 'car' then len(vehicle) == 3. > > -- > John. > _______________________________________________ Hi John, I am still 'blind' here. Please, see below what I did, and what I got: >>> vehicle='car' >>> index = 0 >>> lenght =len(vehicle) >>> last = vehicle[lenght -1] >>> while last >= vehicle[0]: ... letter = vehicle[index] ... print letter ... last -= 1 ... c Traceback (most recent call last): File "<stdin>", line 4, in ? TypeError: unsupported operand type(s) for -=: 'str' and 'int' As you can see, I am still a newbie... Could anyone, please, guide me on this exercise? Thanks! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john at fouhy.net Wed Mar 29 07:32:15 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 29 Mar 2006 17:32:15 +1200 Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <20060329051945.1048.qmail@web60022.mail.yahoo.com> References: <5e58f2e40603281622s5d88cfb8nf8b32fb02b4b814@mail.gmail.com> <20060329051945.1048.qmail@web60022.mail.yahoo.com> Message-ID: <5e58f2e40603282132o5c1094d7n8348b72f49a926ef@mail.gmail.com> On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > >>> vehicle='car' > >>> index = 0 > >>> lenght =len(vehicle) > >>> last = vehicle[lenght -1] > >>> while last >= vehicle[0]: > ... letter = vehicle[index] > ... print letter > ... last -= 1 > ... What is vehicle[index] ? What if I change index, say, index = index + 1 Now what is vehicle[index] ? -- John. From kp8 at mac.com Wed Mar 29 07:33:10 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 29 Mar 2006 00:33:10 -0500 Subject: [Tutor] Alternating patterns In-Reply-To: <mailman.12955.1143603824.27774.tutor@python.org> References: <mailman.12955.1143603824.27774.tutor@python.org> Message-ID: <ec882530c3b77db06c469a306497fbea@mac.com> > > > > ------------------------------ > > Message: 10 > Date: Tue, 28 Mar 2006 22:43:38 -0500 > From: Kent Johnson <kent37 at tds.net> > Subject: Re: [Tutor] Alternating patterns > Cc: tutor at python.org > Message-ID: <442A026A.9010107 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > kevin parks wrote: >> I have a set that i iterate over... but each time through it i would >> like to alternate between the original set and a variation of the set >> that has one of the members of the set altered (by + or - 1) >> >> So if my original set is: >> >> [0, 2, 4, 5, 7, 9, 11] >> >> I would use that the first pass but on the second pass i might like >> the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, >> 9, 11] >> >> But then back again to the original on the next pass (+1 back to 4,): >> [0, 2, 4, 5, 7, 9, 11] >> >> and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. > >> How can one make such alternating patterns? > > itertools.cycle() will repeat a sequence indefinitely: > In [2]: from itertools import cycle > > In [3]: i=cycle([1,2]) > > In [5]: for j in range(6): > ...: print i.next() > ...: > ...: > 1 > 2 > 1 > 2 > 1 > 2 > > For non-repeating sequences I would look at writing a generator > function > for the sequences. > > Kent okay.. i am painfully unaware of generators, iterators, sets, genexes and a lot of the new stuff post 2.3 & 2.4 stuffs... my problem is that i find the online docs kind of terse and few of the Python books yet cover these newer constructs in detail.... itertools looks very cool.... are there any toots on the above and on Sets & itertools? It really seems like it would help to know these for my work... That liddo bit right up there with itertools.cycle already has me a drooling... (so helpful that would be!) -kp-- From oasf2004 at yahoo.com Wed Mar 29 08:03:00 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Tue, 28 Mar 2006 22:03:00 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <5e58f2e40603282132o5c1094d7n8348b72f49a926ef@mail.gmail.com> Message-ID: <20060329060300.15125.qmail@web60021.mail.yahoo.com> --- John Fouhy <john at fouhy.net> wrote: > On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > > >>> vehicle='car' > > >>> index = 0 > > >>> lenght =len(vehicle) > > >>> last = vehicle[lenght -1] > > >>> while last >= vehicle[0]: > > ... letter = vehicle[index] > > ... print letter > > ... last -= 1 > > ... > > What is vehicle[index] ? > > What if I change index, say, > > index = index + 1 > > Now what is vehicle[index] ? > > -- > John. > _______________________________________________ Hi John, (1) vehicle[index] is: 'c' (2) If index = index = 1, so vehicle[index] becomes: 'a' I changed a bit more the code, but I am still in trouble. please, take a look: (1st. try): >>> vehicle='car' >>> index = vehicle[-1] #'r' >>> lenght =len(vehicle) # 3 leters >>> last = vehicle[lenght -1] # >>> while last >= vehicle[0]: ... letter = vehicle[index] ... print letter ... last -= 1 ... Traceback (most recent call last): File "<stdin>", line 2, in ? TypeError: string indices must be integers (2nd, try): >>> vehicle='car' >>> index = vehicle[-1] >>> while vehicle[-1] >= vehicle[0]: ... letter = vehicle[index] ... print letter ... index -= 1 ... Traceback (most recent call last): File "<stdin>", line 2, in ? TypeError: string indices must be integers Such a 'hard' simple problem... Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john at fouhy.net Wed Mar 29 08:10:02 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 29 Mar 2006 18:10:02 +1200 Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <20060329060300.15125.qmail@web60021.mail.yahoo.com> References: <5e58f2e40603282132o5c1094d7n8348b72f49a926ef@mail.gmail.com> <20060329060300.15125.qmail@web60021.mail.yahoo.com> Message-ID: <5e58f2e40603282210v5a79b3eey6e33fa96fba27742@mail.gmail.com> On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > Hi John, > > (1) vehicle[index] is: 'c' > (2) If index = index = 1, so vehicle[index] becomes: > 'a' What I'm getting at here is that, by changing index, we can change which letter we are looking at. And index is a number, which means it's easier to reason about than letters are. Let's have a look at a possible solution: >>> vehicle = 'car' >>> index = 2 >>> print vehicle[index] r >>> index = 1 >>> print vehicle[index] a >>> index = 0 >>> print vehicle[index] c Notice that the three print statements are identical. That suggests we could write the code in a loop, with 'print vehicle[index]' in the body of the loop. Can you have a go at that? -- John. From ajikoe at gmail.com Wed Mar 29 08:25:05 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 29 Mar 2006 08:25:05 +0200 Subject: [Tutor] Alternating patterns In-Reply-To: <ec882530c3b77db06c469a306497fbea@mac.com> References: <mailman.12955.1143603824.27774.tutor@python.org> <ec882530c3b77db06c469a306497fbea@mac.com> Message-ID: <cf5262d20603282225xc979162k3ec6e499845ba6c9@mail.gmail.com> Hi, you can also use simple way of iterating using modus: L = [1,2] for i in range(6): print L[i%len(L)] 1 2 1 2 1 2 Cheers, pujo On 3/29/06, kevin parks <kp8 at mac.com> wrote: > > > > > > > > > ------------------------------ > > > > Message: 10 > > Date: Tue, 28 Mar 2006 22:43:38 -0500 > > From: Kent Johnson <kent37 at tds.net> > > Subject: Re: [Tutor] Alternating patterns > > Cc: tutor at python.org > > Message-ID: <442A026A.9010107 at tds.net> > > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > > > kevin parks wrote: > >> I have a set that i iterate over... but each time through it i would > >> like to alternate between the original set and a variation of the set > >> that has one of the members of the set altered (by + or - 1) > >> > >> So if my original set is: > >> > >> [0, 2, 4, 5, 7, 9, 11] > >> > >> I would use that the first pass but on the second pass i might like > >> the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, > >> 9, 11] > >> > >> But then back again to the original on the next pass (+1 back to 4,): > >> [0, 2, 4, 5, 7, 9, 11] > >> > >> and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. > > > >> How can one make such alternating patterns? > > > > itertools.cycle() will repeat a sequence indefinitely: > > In [2]: from itertools import cycle > > > > In [3]: i=cycle([1,2]) > > > > In [5]: for j in range(6): > > ...: print i.next() > > ...: > > ...: > > 1 > > 2 > > 1 > > 2 > > 1 > > 2 > > > > For non-repeating sequences I would look at writing a generator > > function > > for the sequences. > > > > Kent > > > > okay.. i am painfully unaware of generators, iterators, sets, genexes > and a lot of the new stuff post 2.3 & 2.4 stuffs... my problem is that > i find the online docs kind of terse and few of the Python books yet > cover these newer constructs in detail.... > > itertools looks very cool.... are there any toots on the above and on > Sets & itertools? It really seems like it would help to know these for > my work... That liddo bit right up there with itertools.cycle already > has me a drooling... (so helpful that would be!) > > -kp-- > > > > > > _______________________________________________ > 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/20060329/4ca43188/attachment-0001.htm From keosophon at khmeros.info Wed Mar 29 08:54:25 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 29 Mar 2006 13:54:25 +0700 Subject: [Tutor] get a character of an ascii-value Message-ID: <200603291354.25322.keosophon@khmeros.info> Hi all, I wonder how to get a character of an Ascii-value. For example, i have r = 37. So i wanna print the character of 37. Is there any function? Thanks, Sophon From ajikoe at gmail.com Wed Mar 29 09:16:46 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 29 Mar 2006 09:16:46 +0200 Subject: [Tutor] get a character of an ascii-value In-Reply-To: <200603291354.25322.keosophon@khmeros.info> References: <200603291354.25322.keosophon@khmeros.info> Message-ID: <cf5262d20603282316u168bd81fnc9131aea2adaa692@mail.gmail.com> Hello use this function: print ord('a') print chr(97) Cheers, pujo On 3/29/06, Keo Sophon <keosophon at khmeros.info> wrote: > > Hi all, > > I wonder how to get a character of an Ascii-value. For example, i have r > = > 37. So i wanna print the character of 37. Is there any function? > > Thanks, > Sophon > _______________________________________________ > 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/20060329/449f0e11/attachment.htm From hugonz-lists at h-lab.net Wed Mar 29 09:19:15 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 29 Mar 2006 01:19:15 -0600 Subject: [Tutor] get a character of an ascii-value In-Reply-To: <200603291354.25322.keosophon@khmeros.info> References: <200603291354.25322.keosophon@khmeros.info> Message-ID: <442A34F3.8050702@h-lab.net> Keo Sophon wrote: > Hi all, > > I wonder how to get a character of an Ascii-value. For example, i have r = > 37. So i wanna print the character of 37. Is there any function? > Hi ..yeah, it's called chr(), and its opposite is ord() >>> ord('r') 114 >>> chr(114) 'r' >>> Hugo From kaushalshriyan at gmail.com Wed Mar 29 09:23:52 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 29 Mar 2006 12:53:52 +0530 Subject: [Tutor] ASCII Message-ID: <6b16fb4c0603282323k52abf446v63d3f7bd8ed09ec0@mail.gmail.com> Hi All How do i use this ASCII values in my day to day activities, I am going through learning python, Please illustrate with examples Thanks in Advance Regards Kaushal From ajikoe at gmail.com Wed Mar 29 09:38:14 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 29 Mar 2006 09:38:14 +0200 Subject: [Tutor] ASCII In-Reply-To: <6b16fb4c0603282323k52abf446v63d3f7bd8ed09ec0@mail.gmail.com> References: <6b16fb4c0603282323k52abf446v63d3f7bd8ed09ec0@mail.gmail.com> Message-ID: <cf5262d20603282338y40982457v1596de22077f5169@mail.gmail.com> Hi Kaushal, Please clarify the problem more specific. Or you can tell us that you have a problem and want to use python to solve it? Sincerely Yours, pujo On 3/29/06, Kaushal Shriyan <kaushalshriyan at gmail.com> wrote: > > Hi All > > How do i use this ASCII values in my day to day activities, I am going > through > learning python, > > Please illustrate with examples > > Thanks in Advance > > Regards > > Kaushal > _______________________________________________ > 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/20060329/41e89f5f/attachment.html From keosophon at khmeros.info Wed Mar 29 09:37:59 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 29 Mar 2006 14:37:59 +0700 Subject: [Tutor] get a character of an ascii-value In-Reply-To: <200603291354.25322.keosophon@khmeros.info> References: <200603291354.25322.keosophon@khmeros.info> Message-ID: <200603291438.00038.keosophon@khmeros.info> On Wednesday 29 March 2006 13:54, Keo Sophon wrote: > Hi all, > > I wonder how to get a character of an Ascii-value. For example, i have r = > 37. So i wanna print the character of 37. Is there any function? > > Thanks, > Sophon I just got the answer from Pujo. How about r is bigger than 127. How can i get the character? For example, r = 191. Thanks, Sophon From keosophon at khmeros.info Wed Mar 29 09:42:13 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 29 Mar 2006 14:42:13 +0700 Subject: [Tutor] removing file from zip archive. Message-ID: <200603291442.13643.keosophon@khmeros.info> Hi all, How can we remove one file inside of a zip archive? I'm using this method: import zipfile ziparchive = zipfile.ZipFile('test.odt', 'r') xmldata = ziparchive.read('content.xml') ziparchive.close Thanks in advance, Sophon From kaushalshriyan at gmail.com Wed Mar 29 10:21:30 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 29 Mar 2006 13:51:30 +0530 Subject: [Tutor] ASCII In-Reply-To: <cf5262d20603282338y40982457v1596de22077f5169@mail.gmail.com> References: <6b16fb4c0603282323k52abf446v63d3f7bd8ed09ec0@mail.gmail.com> <cf5262d20603282338y40982457v1596de22077f5169@mail.gmail.com> Message-ID: <6b16fb4c0603290021v2055dd3fn655cda44a95b9cc4@mail.gmail.com> On 3/29/06, Pujo Aji <ajikoe at gmail.com> wrote: > > Hi Kaushal, > > Please clarify the problem more specific. > Or you can tell us that you have a problem and want to use python to solve > it? > > Sincerely Yours, > pujo > > > On 3/29/06, Kaushal Shriyan <kaushalshriyan at gmail.com> wrote: > > > Hi All > > How do i use this ASCII values in my day to day activities, I am going > through > learning python, > > Please illustrate with examples > > Thanks in Advance > > Regards > > Kaushal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi Pujo Its a very general question not related to python at all, I have a minimum knowledge in ASCII just wanted to know how it is used and how it helps out Regards Kaushal From hokkakada at khmeros.info Wed Mar 29 10:22:12 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 29 Mar 2006 15:22:12 +0700 Subject: [Tutor] number of nodes Message-ID: <442A43B4.6040206@khmeros.info> Hello everyone, textp = xmldoc.getElementsByTagName('text:p') from the example above, How can I know how many <text:p> node are there? Thanks, da From ajikoe at gmail.com Wed Mar 29 10:28:33 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 29 Mar 2006 10:28:33 +0200 Subject: [Tutor] ASCII In-Reply-To: <6b16fb4c0603290021v2055dd3fn655cda44a95b9cc4@mail.gmail.com> References: <6b16fb4c0603282323k52abf446v63d3f7bd8ed09ec0@mail.gmail.com> <cf5262d20603282338y40982457v1596de22077f5169@mail.gmail.com> <6b16fb4c0603290021v2055dd3fn655cda44a95b9cc4@mail.gmail.com> Message-ID: <cf5262d20603290028k41700666kaad29d254886ecac@mail.gmail.com> Hello, Basicaly, You use ASCII or Unicode when you have to deal with character conversion for example coding with a different language symbol, chinese letter etc. Sincerely Yours, Pujo On 3/29/06, Kaushal Shriyan <kaushalshriyan at gmail.com> wrote: > > On 3/29/06, Pujo Aji <ajikoe at gmail.com> wrote: > > > > Hi Kaushal, > > > > Please clarify the problem more specific. > > Or you can tell us that you have a problem and want to use python to > solve > > it? > > > > Sincerely Yours, > > pujo > > > > > > On 3/29/06, Kaushal Shriyan <kaushalshriyan at gmail.com> wrote: > > > > > Hi All > > > > How do i use this ASCII values in my day to day activities, I am going > > through > > learning python, > > > > Please illustrate with examples > > > > Thanks in Advance > > > > Regards > > > > Kaushal > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > Hi Pujo > > Its a very general question not related to python at all, I have a > minimum knowledge in ASCII just wanted to know how it is used and how > it helps out > > Regards > > Kaushal > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060329/4068d7e9/attachment.htm From noufal at nibrahim.net.in Wed Mar 29 10:35:28 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 29 Mar 2006 14:05:28 +0530 (IST) Subject: [Tutor] Python tutor In-Reply-To: <cb361a610603281505j6aa562b1ub28266d1b3d591c1@mail.gmail.com> References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> <cb361a610603281505j6aa562b1ub28266d1b3d591c1@mail.gmail.com> Message-ID: <21265.203.145.176.76.1143621328.squirrel@members.hcoop.net> On Wed, March 29, 2006 4:35 am, Anna Ravenscroft wrote: > There are several of us on the edupython list who want something like this > but it hasn't (to my knowledge) been created yet. The best things out > there > so far, are livewires, guido von robot, and rur-ple. If you're > interested > in working on such a project, you're welcome to join us. > http://groups.google.com/group/edupython Thanks. I'll look at GvR, livewires and rur-ple in detail soon. I'm still stuck without a reliable internet connection (should get one in 2 weeks). I've joined the list. Let me come up with a framework and then I'll post again. -- -NI From tim.golden at viacom-outdoor.co.uk Wed Mar 29 10:38:22 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Mar 2006 09:38:22 +0100 Subject: [Tutor] removing file from zip archive. Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E0F3@vogbs009.gb.vo.local> | How can we remove one file inside of a zip archive? | | I'm using this method: | | import zipfile | | ziparchive = zipfile.ZipFile('test.odt', 'r') | xmldata = ziparchive.read('content.xml') | ziparchive.close (Warning: not my area of expertise, but...) Your example *reads* one file from within a zip archive, and is a perfectly good way of doing it (indeed pretty much the only way of doing it). Do I take it you want to end up with the same archive but without that file? If so, I don't believe it's possible as such. What you'd have to do -- and this is almost certainly what any front-end tool will do for you behind-the-scenes -- is to copy the contents of the archive to a temporary file omitting the file(s) in question, and then to rename the temporary file over the original. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From keosophon at khmeros.info Wed Mar 29 10:43:48 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 29 Mar 2006 15:43:48 +0700 Subject: [Tutor] removing file from zip archive. In-Reply-To: <CCAC78D42E32184F8E26DC163DB9830617E0F3@vogbs009.gb.vo.local> References: <CCAC78D42E32184F8E26DC163DB9830617E0F3@vogbs009.gb.vo.local> Message-ID: <200603291543.48230.keosophon@khmeros.info> On Wednesday 29 March 2006 15:38, Tim Golden wrote: > | How can we remove one file inside of a zip archive? > | > | I'm using this method: > | > | import zipfile > | > | ziparchive = zipfile.ZipFile('test.odt', 'r') > | xmldata = ziparchive.read('content.xml') > | ziparchive.close > > (Warning: not my area of expertise, but...) > > Your example *reads* one file from within a zip > archive, and is a perfectly good way of doing it > (indeed pretty much the only way of doing it). > Do I take it you want to end up with the same > archive but without that file? > > If so, I don't believe it's possible as such. > What you'd have to do -- and this is almost > certainly what any front-end tool will do for > you behind-the-scenes -- is to copy the contents > of the archive to a temporary file omitting the > file(s) in question, and then to rename the > temporary file over the original. > > TJG > Thank you. Sophon From kaushalshriyan at gmail.com Wed Mar 29 11:20:34 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 29 Mar 2006 14:50:34 +0530 Subject: [Tutor] Python Code Message-ID: <6b16fb4c0603290120p2d19b09aw4ca21683b113c037@mail.gmail.com> Hi I am unable to execute the below code, I have put this in test.py file and made it executable, when I run this I see no output, Please explain me as what is exactly going on with the below code The below code is from http://www.ibiblio.org/obp/thinkCSpy/chap11.htm def copyFile(oldFile, newFile): f1 = open(oldFile, "r") f2 = open(newFile, "w") while 1: text = f1.read(50) if text == "": break f2.write(text) f1.close() f2.close() return Thanks in Advance Regards Kaushal From noufal at nibrahim.net.in Wed Mar 29 11:45:33 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 29 Mar 2006 15:15:33 +0530 (IST) Subject: [Tutor] Python Code In-Reply-To: <6b16fb4c0603290120p2d19b09aw4ca21683b113c037@mail.gmail.com> References: <6b16fb4c0603290120p2d19b09aw4ca21683b113c037@mail.gmail.com> Message-ID: <55129.203.145.176.76.1143625533.squirrel@members.hcoop.net> On Wed, March 29, 2006 2:50 pm, Kaushal Shriyan wrote: > Hi > > I am unable to execute the below code, I have put this in test.py file > and made it executable, when I run this I see no output, Please > explain me as what is exactly going on with the below code > > The below code is from http://www.ibiblio.org/obp/thinkCSpy/chap11.htm > > def copyFile(oldFile, newFile): > f1 = open(oldFile, "r") > f2 = open(newFile, "w") > while 1: > text = f1.read(50) > if text == "": > break > f2.write(text) > f1.close() > f2.close() > return Did you have only the copyFile definition or did you have an invocation as well? You have to call it to work. :) -- -NI From keosophon at khmeros.info Wed Mar 29 13:59:30 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 29 Mar 2006 18:59:30 +0700 Subject: [Tutor] newbie exercises In-Reply-To: <b6131fdc0603270453p28811516q506920a43b1dab8a@mail.gmail.com> References: <20060327121616.5346.qmail@web60818.mail.yahoo.com> <b6131fdc0603270453p28811516q506920a43b1dab8a@mail.gmail.com> Message-ID: <200603291859.31065.keosophon@khmeros.info> On Monday 27 March 2006 19:53, Steve Nelson wrote: > On 3/27/06, josip <josipl2000 at yahoo.com> wrote: > > Can someone give me exercises to do with loops, maybe functions to? > > How about a program that produces truth tables for the basic gates? > AND, NAND, NOT, OR, XOR? > > You could write a function for each gate, and one to produce a truth > table. > > S. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Is it bitwise operator? Could you give one example? Sophon From sanelson at gmail.com Wed Mar 29 14:11:28 2006 From: sanelson at gmail.com (Steve Nelson) Date: Wed, 29 Mar 2006 13:11:28 +0100 Subject: [Tutor] newbie exercises In-Reply-To: <200603291859.31065.keosophon@khmeros.info> References: <20060327121616.5346.qmail@web60818.mail.yahoo.com> <b6131fdc0603270453p28811516q506920a43b1dab8a@mail.gmail.com> <200603291859.31065.keosophon@khmeros.info> Message-ID: <b6131fdc0603290411y30dd8db8od35203cdb48c5470@mail.gmail.com> On 3/29/06, Keo Sophon <keosophon at khmeros.info> wrote: > Is it bitwise operator? Could you give one example? >>> for a in range(2): ... for b in range(2): ... print a, b, a&b ... 0 0 0 0 1 0 1 0 0 1 1 1 > Sophon S. From kent37 at tds.net Wed Mar 29 15:29:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Mar 2006 08:29:20 -0500 Subject: [Tutor] Alternating patterns In-Reply-To: <ec882530c3b77db06c469a306497fbea@mac.com> References: <mailman.12955.1143603824.27774.tutor@python.org> <ec882530c3b77db06c469a306497fbea@mac.com> Message-ID: <442A8BB0.3080104@tds.net> kevin parks wrote: >>From: Kent Johnson <kent37 at tds.net> >>itertools.cycle() will repeat a sequence indefinitely: >>In [2]: from itertools import cycle >> >>In [3]: i=cycle([1,2]) >> >>In [5]: for j in range(6): >> ...: print i.next() >> ...: >> ...: >>1 >>2 >>1 >>2 >>1 >>2 >> >>For non-repeating sequences I would look at writing a generator >>function >>for the sequences. >> >>Kent > > okay.. i am painfully unaware of generators, iterators, sets, genexes > and a lot of the new stuff post 2.3 & 2.4 stuffs... my problem is that > i find the online docs kind of terse and few of the Python books yet > cover these newer constructs in detail.... > > itertools looks very cool.... are there any toots on the above and on > Sets & itertools? It really seems like it would help to know these for > my work... That liddo bit right up there with itertools.cycle already > has me a drooling... (so helpful that would be!) The best introduction to new features is usually in the What's New document accompanying the release where the feature was added. Of course it helps to know when the feature was added...here are some generator examples: http://www.python.org/doc/2.2.3/whatsnew/node5.html Generators are excellent for encapsulating the generation of a sequence when there is state that must be maintained between elements. For example here is a generator that takes a sequence argument, and yields this sequence of sequences: the original sequence the original sequence with the first element incremented by one the original sequence the original sequence with the second element incremented by one etc until each element has been incremented In [2]: def change_each(seq): ...: seq = list(seq) # Copy and ensure it's a list ...: for i in range(len(seq)): ...: yield seq ...: seq[i] += 1 ...: yield seq ...: seq[i] -= 1 ...: ...: In [3]: s = [1, 3] In [5]: for n in change_each(s): ...: print n ...: ...: [1, 3] [2, 3] [1, 3] [1, 4] If you wanted to repeat this sequence indefinitely you could just wrap it with itertools.cycle(). The module docs for itertools contain quite a few examples: http://docs.python.org/lib/itertools-recipes.html itertools.cycle() is pretty simple, it just loops endlessly over the sequence you give it. The itertools docs shows equivalent Python functions for each of the itertools functions. Most of them are implemented using generator functions so by looking at them you can learn about itertools and generators at the same time. http://docs.python.org/lib/itertools-functions.html Kent From kaushalshriyan at gmail.com Wed Mar 29 16:15:06 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 29 Mar 2006 19:45:06 +0530 Subject: [Tutor] How does it function Message-ID: <6b16fb4c0603290615o724e1aedv9a08210393046a3d@mail.gmail.com> Hi ALL Just wanted to know the detailed explanation about the below statement if __name__ == "__main__": Thanks Regards Kaushal From sanelson at gmail.com Wed Mar 29 16:26:16 2006 From: sanelson at gmail.com (Steve Nelson) Date: Wed, 29 Mar 2006 15:26:16 +0100 Subject: [Tutor] How does it function In-Reply-To: <6b16fb4c0603290615o724e1aedv9a08210393046a3d@mail.gmail.com> References: <6b16fb4c0603290615o724e1aedv9a08210393046a3d@mail.gmail.com> Message-ID: <b6131fdc0603290626m495e97ch3563fa68abffcf59@mail.gmail.com> On 3/29/06, Kaushal Shriyan <kaushalshriyan at gmail.com> wrote: > Hi ALL > > Just wanted to know the detailed explanation about the below statement > > if __name__ == "__main__": Simple answer - any python program you write is effectively a 'module'. Modules have an attribute __name__. If you've imported the module from elsewhere, the __name__ is set to the name of the module, otherwise it is __name__. This means that you can write a test that says:If the code we're trying to run is the main program, go ahead and start running the functions we need. You can read more about it here: http://swaroopch.info/text/Byte_of_Python:Modules and also here: http://diveintopython.org/getting_to_know_python/testing_modules.html More detailed info here: http://www.python.org/doc/current/ref/import.html S. From oasf2004 at yahoo.com Wed Mar 29 17:21:52 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Wed, 29 Mar 2006 07:21:52 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward - almost there! In-Reply-To: <5e58f2e40603282210v5a79b3eey6e33fa96fba27742@mail.gmail.com> Message-ID: <20060329152152.42611.qmail@web60013.mail.yahoo.com> --- John Fouhy <john at fouhy.net> wrote: > On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > > Hi John, > > > > (1) vehicle[index] is: 'c' > > (2) If index = index = 1, so vehicle[index] > becomes: > > 'a' > > What I'm getting at here is that, by changing index, > we can change > which letter we are looking at. And index is a > number, which means > it's easier to reason about than letters are. > > Let's have a look at a possible solution: > > >>> vehicle = 'car' > >>> index = 2 > >>> print vehicle[index] > r > >>> index = 1 > >>> print vehicle[index] > a > >>> index = 0 > >>> print vehicle[index] > c > > Notice that the three print statements are > identical. That suggests > we could write the code in a loop, with 'print > vehicle[index]' in the > body of the loop. Can you have a go at that? > > -- > John. > _______________________________________________ Hi John, We are almost there. I changed the code and, at least, I got the correct output. However, I also got a traceback. I didn't understand the traceback. Could you clarify that? Thanks, Hoffmann ps: The new code: >>> vehicle='car' >>> index = -1 #index of the last letter >>> lenght = len(vehicle) >>> last = vehicle[lenght-1] >>> >>> while last >= vehicle[0]: letter=vehicle[index] print letter index -= 1 r a c Traceback (most recent call last): File "<pyshell#40>", line 2, in -toplevel- letter=vehicle[index] IndexError: string index out of range __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jadams at iastate.edu Wed Mar 29 17:20:06 2006 From: jadams at iastate.edu (Josh Adams) Date: Wed, 29 Mar 2006 09:20:06 -0600 (CST) Subject: [Tutor] newbie question about default arguments Message-ID: <62092921063870@webmail.iastate.edu> Hi all, I was going through the tutorial at http://docs.python.org/tut/node6.html when I came to the bit about default arguments with this code: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) returns: [1] [1, 2] [1, 2, 3] >From the postings here, I think I understand that this occurs because L is only initialized when f is first run. However, this code gives some different results: def f2(a, L=[]): if L == []: L = [] L.append(a) return L print f2(1) print f2(2) print f2(3) returns: [1] [2] [3] I'm not too clear on why this doesn't return the same results as the first. Can someone enlighten me? Thanks, Josh From ajikoe at gmail.com Wed Mar 29 18:33:41 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 29 Mar 2006 18:33:41 +0200 Subject: [Tutor] newbie question about default arguments In-Reply-To: <62092921063870@webmail.iastate.edu> References: <62092921063870@webmail.iastate.edu> Message-ID: <cf5262d20603290833r547a82d6m32710c9aea7249a5@mail.gmail.com> Hello Josh, you wrote a different problem. The tutorial should be like this: *Important warning:* The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) This will print [1] [1, 2] [1, 2, 3] If you don't want the default to be shared between subsequent calls, you can write the function like this instead: def f(a, L=None): if L is None: L = [] L.append(a) return L Look the second example use None instead of [] To explain more detail let's create an example : def f1(a, L=[]): L.append(a) return L def f2(a, L=None): if L is None: L = [] L.append(a) return L def main(): m = f2(3) print m # produce [3] m = f2(4) print m # produce [4] # ---------------- m = f1(3) print m # produce[3] m = f1(4) print m # produce[3,4] pass in f1 : when we don't put the second argument the L=[] is created only once. The second input in f1 will be accumulated. in f2: when we don't put the second argument L is given a None value. Inside this function if L is None then L = [] this will always make L = [] that's way no accumulation happened. Hope this help. pujo On 3/29/06, Josh Adams <jadams at iastate.edu> wrote: > > Hi all, > I was going through the tutorial at http://docs.python.org/tut/node6.htmlwhen I > came to the bit about default arguments with this code: > > def f(a, L=[]): > L.append(a) > return L > > print f(1) > print f(2) > print f(3) > > returns: > [1] > [1, 2] > [1, 2, 3] > > >From the postings here, I think I understand that this occurs because L > is only > initialized when f is first run. However, this code gives some different > results: > > def f2(a, L=[]): > if L == []: > L = [] > L.append(a) > return L > > print f2(1) > print f2(2) > print f2(3) > > returns: > [1] > [2] > [3] > > I'm not too clear on why this doesn't return the same results as the > first. Can > someone enlighten me? > > Thanks, > Josh > > > _______________________________________________ > 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/20060329/f968655d/attachment.htm From jadams at iastate.edu Wed Mar 29 20:21:29 2006 From: jadams at iastate.edu (Josh Adams) Date: Wed, 29 Mar 2006 12:21:29 -0600 (CST) Subject: [Tutor] newbie question about default arguments Message-ID: <2921122921063870@webmail.iastate.edu> Thanks for your help. That makes a lot more sense. Not to ask too many stupid questions, but why does the L2 assignment in the if-block create a new L variable? Shouldn't the scope from the function definition dominate the inner scope of the if-block? Thanks, Josh > Josh, > > If you print the id() of your L inside your f2(), you will notice something.. > In short, the default value stays the same; what you modified was another > copy of []. Hope it helps. > > def f2(a, L=[]): > print "id(L) = ", id(L) > if L==[]: > L=[] > print "id(L2) =", id(L) > L.append(a) > return L > > >>> print f2(1) > id(L)= 11788336 > id(L2)= 12047184 > [1] > > Kenny > > From hugonz-lists at h-lab.net Wed Mar 29 20:25:41 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 29 Mar 2006 12:25:41 -0600 Subject: [Tutor] get a character of an ascii-value In-Reply-To: <200603291438.00038.keosophon@khmeros.info> References: <200603291354.25322.keosophon@khmeros.info> <200603291438.00038.keosophon@khmeros.info> Message-ID: <442AD125.8020409@h-lab.net> Hi, Python strings are binary strings as they can contain any value, including 0 (NULL) Depending on the encoding of the string, this may or may not be printable, and characters over ASCII 127 will mean different letters and symbols. Check the docs for strings and encodings: http://docs.python.org/lib/standard-encodings.html http://python.active-venture.com/api/stringObjects.html Hugo In a > > I just got the answer from Pujo. How about r is bigger than 127. How can i get > the character? For example, r = 191. > > Thanks, > Sophon > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Mar 29 20:49:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Mar 2006 13:49:24 -0500 Subject: [Tutor] newbie question about default arguments In-Reply-To: <2921122921063870@webmail.iastate.edu> References: <2921122921063870@webmail.iastate.edu> Message-ID: <442AD6B4.8060700@tds.net> Josh Adams wrote: > Thanks for your help. That makes a lot more sense. > > Not to ask too many stupid questions, but why does the L2 assignment in the > if-block create a new L variable? Shouldn't the scope from the function > definition dominate the inner scope of the if-block? It doesn't create a new variable, it binds a new value to the name L. if statements don't introduce a new scope so you are right about that. Default values for functions are evaluated just once, when the function is defined. Rebinding L to a new list inside the function makes each execution get a fresh list. This might help you understand Python name-binding semantics: http://effbot.org/zone/python-objects.htm Kent > > Thanks, > Josh > > >>Josh, >> >>If you print the id() of your L inside your f2(), you will notice something.. >>In short, the default value stays the same; what you modified was another >>copy of []. Hope it helps. >> >>def f2(a, L=[]): >> print "id(L) = ", id(L) >> if L==[]: >> L=[] >> print "id(L2) =", id(L) >> L.append(a) >> return L >> >> >>>>>print f2(1) >> >>id(L)= 11788336 >>id(L2)= 12047184 >>[1] >> >>Kenny >> >> > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From mwhite3 at ttsd.k12.or.us Wed Mar 29 20:56:31 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Wed, 29 Mar 2006 10:56:31 -0800 Subject: [Tutor] for loops and exceptions Message-ID: <20060329185631.GR11313@ttsd.k12.or.us> Hello, >From a general style and/or programmatic perspective, which is a "better" way to write this bit of code? try: (dn, attrs) = conn.search_s(search_base, search_scope, search_filter, search_attrs): except Exception, e: warn_the_user(e) do_something_useful() for (name, data) in (dn, attrs): print '%s' % (name) for key, value in data.iteritems(): print '%s => %s' % (key, value) OR try: for dn, attrs in conn.search_s(search_base, search_scope, search_filter, search_attrs): print dn for key, value in attrs.iteritems(): print '\t%s => %s' % (key, value) print except Exception, e: warn_the_user(e) do_something_useful Personally I like the second method more. To my eyes it is compact and efficient. Coming from a perl background I tend to like to get very compact, which can be an impediment to code readability. As I get started with python I want to make sure that I don't repeat the same mistakes and let too many perl-isms creep into my python code. -mtw -- 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 adam.jtm30 at gmail.com Wed Mar 29 23:29:27 2006 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 29 Mar 2006 22:29:27 +0100 Subject: [Tutor] Program for outputing the letter backward - almost there! In-Reply-To: <20060329152152.42611.qmail@web60013.mail.yahoo.com> References: <5e58f2e40603282210v5a79b3eey6e33fa96fba27742@mail.gmail.com> <20060329152152.42611.qmail@web60013.mail.yahoo.com> Message-ID: <be4fbf920603291329u9d8f888rcb6c3063dcd7b892@mail.gmail.com> I just wanted to throw in a couple of ideas for you on this subject. These are the ways I would personally think of going about this problem: >>> ''.join([s[n] for n in range(len(s)-1, -1, -1)]) 'rac' Which looks a bit fugly but is nice and short if you can manage list comps. and now my favourite: >>> l = list("car") >>> l.reverse() >>> ''.join(l) 'rac' hth From srini_iyyer_bio at yahoo.com Wed Mar 29 23:59:38 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 29 Mar 2006 13:59:38 -0800 (PST) Subject: [Tutor] Automating web page parsing In-Reply-To: <2921122921063870@webmail.iastate.edu> Message-ID: <20060329215938.41745.qmail@web38105.mail.mud.yahoo.com> Dear group, ***Disclaimer***Not suitable for BioPython list*** I work with GeneChips to analyze human gene expression patterns. These genechips are various kinds one of the variety is made at Stanford University. In a typical experiment, an experimenter uses roughly over 40 chips. For a third party to analyze data from that chip, we should know the design of that chip and that information is one file. In this case it is GAL file. Since it is difficult and cumbersome to identify each design file type of all chips and get it into your directory. However, on their website SMD (http://genome-www5.stanford.edu/), it is possible to go to each design file and obtain the data. Since this is a time taking procedure, I wrote a socket script that would give me the URL of the file and allowing me to download. The first barrier is, their database does not allow sockets programming. Unfortunately, I have to access each file (there could be 40 - 100 files), get redirected to another page and there I can be able to download. Is there a method to automate this procedure through a browser. Is there any alternative for such clicks. Example: http://smd.stanford.edu/cgi-bin/data/viewDetails.pl?fullID=32898GENEPIX0 In this page at the bottom there is a link to 'Generate GAL file', that URL will allow me to get GAL File. I cannot sit for whole evening and click ~40x30 times and download that. It is painful. Are there any smart ways to hack this process. Thanks Sri. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jjabson at yahoo.com Thu Mar 30 00:38:11 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Wed, 29 Mar 2006 14:38:11 -0800 (PST) Subject: [Tutor] Newbie: Passing variable into re.compile Message-ID: <20060329223811.94439.qmail@web53713.mail.yahoo.com> Hello, I???m having trouble trying to pass a variable into re.compile(), using the ???r??? option. Let???s say I have the following: import re arg1 = ???10??? p = re.compile(r + arg1 + '\.(\d+\.\d+\.\d+)') This works if I do: p = re.compile(r ???10\.(\d+\.\d+\.\d+)') Is there something special I need to do for the ???r??? option? Like escape it when using a variable? Thanks, Jerome __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john at fouhy.net Thu Mar 30 01:09:30 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 30 Mar 2006 11:09:30 +1200 Subject: [Tutor] Newbie: Passing variable into re.compile In-Reply-To: <20060329223811.94439.qmail@web53713.mail.yahoo.com> References: <20060329223811.94439.qmail@web53713.mail.yahoo.com> Message-ID: <5e58f2e40603291509i334446c7qa249566172a9e50c@mail.gmail.com> On 30/03/06, Jerome Jabson <jjabson at yahoo.com> wrote: > import re > > arg1 = '10" > > p = re.compile(r + arg1 + '\.(\d+\.\d+\.\d+)') Have a look at string substitutions :-) --- http://docs.python.org/lib/typesseq-strings.html p = re.compile(r'%s\.(\d+\.\d+\.\d+)' % arg1) -- John. From oasf2004 at yahoo.com Thu Mar 30 01:22:00 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Wed, 29 Mar 2006 15:22:00 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward - almost there! In-Reply-To: <be4fbf920603291329u9d8f888rcb6c3063dcd7b892@mail.gmail.com> Message-ID: <20060329232200.42149.qmail@web60023.mail.yahoo.com> --- Adam <adam.jtm30 at gmail.com> wrote: > I just wanted to throw in a couple of ideas for you > on this subject. > These are the ways I would personally think of going > about this > problem: > > >>> ''.join([s[n] for n in range(len(s)-1, -1, -1)]) > 'rac' > Which looks a bit fugly but is nice and short if you > can manage list comps. > > and now my favourite: > > >>> l = list("car") > >>> l.reverse() > >>> ''.join(l) > 'rac' > > hth > Hi Adam, Defenitely your second alternative is really great! Regarding that my 'bad' alternative, do you have any suggestion about that traceback? I not only would like to have the exercise done. And after your nice suggestion, I ALREADY have it, but also I would like to learn about that traceback I got previously. Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Thu Mar 30 01:24:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Mar 2006 18:24:30 -0500 Subject: [Tutor] Newbie: Passing variable into re.compile In-Reply-To: <20060329223811.94439.qmail@web53713.mail.yahoo.com> References: <20060329223811.94439.qmail@web53713.mail.yahoo.com> Message-ID: <442B172E.90508@tds.net> Jerome Jabson wrote: > Hello, > > > > I?m having trouble trying to pass a variable into > re.compile(), using the ?r? option. Let?s say I > have the following: > > > > import re > > arg1 = ?10? > > p = re.compile(r + arg1 + '\.(\d+\.\d+\.\d+)') > > > > This works if I do: > > > > p = re.compile(r ?10\.(\d+\.\d+\.\d+)') > > > > Is there something special I need to do for the > ?r? option? Like escape it when using a variable? 'r' is not an option to re.compile(), it is a modifier for the string itself that affects how the string is parsed. So you can use p = re.compile(arg1 + r'\.(\d+\.\d+\.\d+)') or use string substitution as John suggests. Kent From kent37 at tds.net Thu Mar 30 01:33:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Mar 2006 18:33:46 -0500 Subject: [Tutor] Automating web page parsing In-Reply-To: <20060329215938.41745.qmail@web38105.mail.mud.yahoo.com> References: <20060329215938.41745.qmail@web38105.mail.mud.yahoo.com> Message-ID: <442B195A.5040809@tds.net> Srinivas Iyyer wrote: > For a third party to analyze data from that chip, we > should know the design of that chip and that > information is one file. In this case it is GAL file. > Since it is difficult and cumbersome to identify each > design file type of all chips and get it into your > directory. However, on their website SMD > (http://genome-www5.stanford.edu/), it is possible to > go to each design file and obtain the data. Since > this is a time taking procedure, I wrote a socket > script that would give me the URL of the file and > allowing me to download. The first barrier is, their > database does not allow sockets programming. What did you try? How did it fail? The website requires a form-based login which probably returns a cookie to your browser. Your socket solution needs to take this into account. There are some articles here with more info: http://www.voidspace.org.uk/python/articles.shtml#http > > Unfortunately, I have to access each file (there could > be 40 - 100 files), get redirected to another page and > there I can be able to download. > > Is there a method to automate this procedure through a > browser. > > Is there any alternative for such clicks. There are several packages intended to help script web sites, take a look at twill http://www.idyll.org/~t/www-tools/twill/ mechanize and ClientForm http://wwwsearch.sf.net/ http://python.org/pypi/mechanoid Kent From adam.jtm30 at gmail.com Thu Mar 30 01:39:57 2006 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 30 Mar 2006 00:39:57 +0100 Subject: [Tutor] Program for outputing the letter backward - almost there! In-Reply-To: <20060329152152.42611.qmail@web60013.mail.yahoo.com> References: <5e58f2e40603282210v5a79b3eey6e33fa96fba27742@mail.gmail.com> <20060329152152.42611.qmail@web60013.mail.yahoo.com> Message-ID: <be4fbf920603291539yfba065v6d512653a169313a@mail.gmail.com> > Hi John, > > We are almost there. I changed the code and, at least, > I got the correct output. However, I also got a > traceback. I didn't understand the traceback. Could > you clarify that? > Thanks, > Hoffmann > ps: The new code: > > >>> vehicle='car' > >>> index = -1 #index of the last letter > >>> lenght = len(vehicle) > >>> last = vehicle[lenght-1] > >>> > >>> while last >= vehicle[0]: > letter=vehicle[index] > print letter > index -= 1 > > > r > a > c > > Traceback (most recent call last): > File "<pyshell#40>", line 2, in -toplevel- > letter=vehicle[index] > IndexError: string index out of range while last >= vehicle[0]: The problem is is that neither vehicle[0] nor last change during the loop so it is always satisified and index eventually becomes a number that doesn't correspond to an index of the string. I would suggest something along these lines instead: for i in range(len(vehicle)-1, -1, -1): print vehicle[i] which is basically what my list comp did but printing out the letters rather than returning a list From kent37 at tds.net Thu Mar 30 02:25:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Mar 2006 19:25:09 -0500 Subject: [Tutor] Program for outputing the letter backward - almost there! In-Reply-To: <20060329152152.42611.qmail@web60013.mail.yahoo.com> References: <20060329152152.42611.qmail@web60013.mail.yahoo.com> Message-ID: <442B2565.2050109@tds.net> Hoffmann wrote: > We are almost there. I changed the code and, at least, > I got the correct output. However, I also got a > traceback. I didn't understand the traceback. Could > you clarify that? > Thanks, > Hoffmann > ps: The new code: > > >>>>vehicle='car' >>>>index = -1 #index of the last letter >>>>lenght = len(vehicle) >>>>last = vehicle[lenght-1] >>>> >>>>while last >= vehicle[0]: > > letter=vehicle[index] > print letter > index -= 1 You are still confusing the index of a letter and the letter itself. In [1]: vehicle = 'car' In [2]: last = vehicle[-1] In [3]: last Out[3]: 'r' last is a letter, not a number. In [5]: vehicle[0] Out[5]: 'c' vehicle[0] is also a letter. So when you write while last >= vehicle[0]: you are comparing two characters, which is not really helpful in the current context. What you really want to do is compare the index of the current character with 0. Here is a working version in the same style: In [6]: index = len(vehicle)-1 In [7]: while index >= 0: ...: print vehicle[index] ...: index -= 1 ...: ...: r a c The best way to reverse a string is with a slice and negative index: In [8]: vehicle[::-1] Out[8]: 'rac' but I'm going to have to leave explanation of that to another day or another poster. Kent From keosophon at khmeros.info Thu Mar 30 02:46:55 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Thu, 30 Mar 2006 07:46:55 +0700 Subject: [Tutor] get a character of an ascii-value In-Reply-To: <442AD125.8020409@h-lab.net> References: <200603291354.25322.keosophon@khmeros.info> <200603291438.00038.keosophon@khmeros.info> <442AD125.8020409@h-lab.net> Message-ID: <200603300746.55331.keosophon@khmeros.info> On Thursday 30 March 2006 01:25, Hugo Gonz?lez Monteverde wrote: > Hi, > > Python strings are binary strings as they can contain any value, > including 0 (NULL) Depending on the encoding of the string, this may or > may not be printable, and characters over ASCII 127 will mean different > letters and symbols. > > Check the docs for strings and encodings: > > http://docs.python.org/lib/standard-encodings.html > http://python.active-venture.com/api/stringObjects.html > > Hugo > Thanks. Phon From carroll at tjc.com Thu Mar 30 03:05:23 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 29 Mar 2006 17:05:23 -0800 (PST) Subject: [Tutor] How does it function In-Reply-To: <b6131fdc0603290626m495e97ch3563fa68abffcf59@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0603291700210.8769-100000@violet.rahul.net> On Wed, 29 Mar 2006, Steve Nelson wrote: > On 3/29/06, Kaushal Shriyan <kaushalshriyan at gmail.com> wrote: > > > > Just wanted to know the detailed explanation about the below statement > > > > if __name__ == "__main__": > > Simple answer - any python program you write is effectively a > 'module'. Modules have an attribute __name__. If you've imported the > module from elsewhere, the __name__ is set to the name of the module, > otherwise it is __name__. I don't mean to nitpick, but I see Steve had a small but crucial slip here. I think he means, " If you've imported the module from elsewhere, the __name__ is set to the name of the module, otherwise it is "__main__". > This means that you can write a test that says:If the code we're > trying to run is the main program, go ahead and start running the > functions we need. Yes; a typical usage is: [bulk of program is here, in the form of one or more callable methods] if __name__ == "__main__": [stuff] Where "[stuff]" is either code to invoke your callable methods as you'd normally have the program run, or, (commonly for modules intended to be imported and used) code to test the module and confirm that a number of predetermined invocations with predetermined expected output actually produce that output. From oasf2004 at yahoo.com Thu Mar 30 03:14:20 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Wed, 29 Mar 2006 17:14:20 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <442B2565.2050109@tds.net> Message-ID: <20060330011420.47563.qmail@web60016.mail.yahoo.com> --- Kent Johnson <kent37 at tds.net> wrote: > Hoffmann wrote: > > We are almost there. I changed the code and, at > least, > > I got the correct output. However, I also got a > > traceback. I didn't understand the traceback. > Could > > you clarify that? > > Thanks, > > Hoffmann > > ps: The new code: > > > > > >>>>vehicle='car' > >>>>index = -1 #index of the last letter > >>>>lenght = len(vehicle) > >>>>last = vehicle[lenght-1] > >>>> > >>>>while last >= vehicle[0]: > > > > letter=vehicle[index] > > print letter > > index -= 1 > > You are still confusing the index of a letter and > the letter itself. > > In [1]: vehicle = 'car' > > In [2]: last = vehicle[-1] > > In [3]: last > Out[3]: 'r' > > last is a letter, not a number. > > In [5]: vehicle[0] > Out[5]: 'c' > > vehicle[0] is also a letter. So when you write > while last >= vehicle[0]: > you are comparing two characters, which is not > really helpful in the > current context. What you really want to do is > compare the index of the > current character with 0. Here is a working version > in the same style: > > In [6]: index = len(vehicle)-1 > > In [7]: while index >= 0: > ...: print vehicle[index] > ...: index -= 1 > ...: > ...: > r > a > c > > The best way to reverse a string is with a slice and > negative index: > > In [8]: vehicle[::-1] > Out[8]: 'rac' > > but I'm going to have to leave explanation of that > to another day or > another poster. > > Kent > > > _______________________________________________ Hello Guys, Thank you very much all of you (in special: Kent, John, and Adam), for the nice explanations about my excercise. I am a newbie that is studying Python programming by myself. I appreciated your attention. See you on my next post :-) Best, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From tamarynsarusi-kiss at optusnet.com.au Thu Mar 30 03:52:11 2006 From: tamarynsarusi-kiss at optusnet.com.au (Tamaryn Sarusi-Kiss) Date: Thu, 30 Mar 2006 11:52:11 +1000 Subject: [Tutor] Beginner can't finish code Message-ID: <442B39CB.000015.02316@ACER-2E68C49B20> Hi, I'm a beginner and can't finish the code I'm working on below. I want the code below to have "hints" when the user asks for them , and I don't know enough to do this.What would be the best way of introducing "hints" and allowing the user to exit when he wants to. Any help would be appreciated. The Word Jumble Game >> import random >> >> # create a sequence of words to choose from >> WORDS = ("python", "easy") >> # pick one word randomly from the sequence >> word = random.choice(WORDS) >> # create a variable to use later to see if the guess is correct >> correct = word >> # create variable to use for hint if needed > hint = "hint" >> # create a jumbled version of the word >> jumble ="" >> while word: >> position = random.randrange(Len(word)) >> jumble += word[position] >> word = word[:position] + word[(position + 1):] >> >> # start the game >> print \ >> """ >> Welcome to Word Jumble! >> >> Unscramble the letters to make a word. >> (Press the enter key at the prompt to quit.) >> """ >> print "The jumble is:", jumble >> print "If you need a hint type 'hint' and Hit enter." >> guess = raw_input("\nYour guess: ") >> guess = guess.lower() >> while (guess != correct) and (guess != "")and (guess != hint): >> print "Sorry, that's not it." >> guess = raw_input("Your guess: ") >> guess = guess.lower() >> if guess == hint: >> print "not hard but" >> guess = raw_input("Your guess: ") >> guess = guess.lower() >> >> while word == python: > hints = {'easy':'not hard but','python':'snake'} > if guess == hint: > print hints[correct] > guess = raw_input("Your guess: ") > guess = guess.lower() >> >> if guess == correct: >> print "That's it! You guessed it!\n" >> >> print "Thanks for playing." >> >> raw_input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060330/107da91b/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 20284 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060330/107da91b/attachment-0001.gif From bgailer at alum.rpi.edu Thu Mar 30 06:34:27 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 29 Mar 2006 20:34:27 -0800 Subject: [Tutor] Automating web page parsing In-Reply-To: <20060329215938.41745.qmail@web38105.mail.mud.yahoo.com> References: <20060329215938.41745.qmail@web38105.mail.mud.yahoo.com> Message-ID: <442B5FD3.6010204@alum.rpi.edu> Srinivas Iyyer wrote: > Dear group, > > ***Disclaimer***Not suitable for BioPython list*** > > I work with GeneChips to analyze human gene expression > patterns. These genechips are various kinds one of the > variety is made at Stanford University. In a typical > experiment, an experimenter uses roughly over 40 > chips. > > For a third party to analyze data from that chip, we > should know the design of that chip and that > information is one file. In this case it is GAL file. > Since it is difficult and cumbersome to identify each > design file type of all chips and get it into your > directory. However, on their website SMD > (http://genome-www5.stanford.edu/), it is possible to > go to each design file and obtain the data. Since > this is a time taking procedure, I wrote a socket > script that would give me the URL of the file and > allowing me to download. The first barrier is, their > database does not allow sockets programming. > > Unfortunately, I have to access each file (there could > be 40 - 100 files), get redirected to another page and > there I can be able to download. > > Is there a method to automate this procedure through a > browser. > > Is there any alternative for such clicks. > > Example: > http://smd.stanford.edu/cgi-bin/data/viewDetails.pl?fullID=32898GENEPIX0 > Unfortunately for me when I go to that link I get a login form, not what you describe. So I can't help until I know how to log in. > In this page at the bottom there is a link to > 'Generate GAL file', that URL will allow me to get GAL > File. > > I cannot sit for whole evening and click ~40x30 times > and download that. It is painful. Are there any smart > ways to hack this process. > > Thanks > Sri. > > __________________________________________________ > 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 sanelson at gmail.com Thu Mar 30 10:45:49 2006 From: sanelson at gmail.com (Steve Nelson) Date: Thu, 30 Mar 2006 09:45:49 +0100 Subject: [Tutor] How does it function In-Reply-To: <Pine.LNX.4.44.0603291700210.8769-100000@violet.rahul.net> References: <b6131fdc0603290626m495e97ch3563fa68abffcf59@mail.gmail.com> <Pine.LNX.4.44.0603291700210.8769-100000@violet.rahul.net> Message-ID: <b6131fdc0603300045r54b78f4ft522082da043b2287@mail.gmail.com> On 3/30/06, Terry Carroll <carroll at tjc.com> wrote: > On Wed, 29 Mar 2006, Steve Nelson wrote: > > > Simple answer - any python program you write is effectively a > > 'module'. Modules have an attribute __name__. If you've imported the > > module from elsewhere, the __name__ is set to the name of the module, > > otherwise it is __name__. > > I don't mean to nitpick, but I see Steve had a small but crucial slip > here. I think he means, " If you've imported the module from elsewhere, > the __name__ is set to the name of the module, otherwise it is "__main__". Yes absolutely - well spotted, and sorry for the typo. S. From singletoned at gmail.com Thu Mar 30 10:48:22 2006 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 30 Mar 2006 09:48:22 +0100 Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <20060329051945.1048.qmail@web60022.mail.yahoo.com> References: <5e58f2e40603281622s5d88cfb8nf8b32fb02b4b814@mail.gmail.com> <20060329051945.1048.qmail@web60022.mail.yahoo.com> Message-ID: <34bb7f5b0603300048m3fbd6cf2jc8b1b1b070e276bb@mail.gmail.com> On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > --- John Fouhy <john at fouhy.net> wrote: > > > On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > > > vehicle='car' > > > index = vehicle[-1] #the last letter > > > index_zero = vehicle[0] #the first letter > > > > > > while index >= index_zero: > > > letter=vehicle[index] > > > print letter > > > index -= 1 > > > > > > The problem is that I get no output here. Could I > > hear > > > from you? > > > > I can print the letters backwards like this: > > > > vehicle = 'car' > > print vehicle[2] > > print vehicle[1] > > print vehicle[0] > > > > Output: > > > > r > > a > > c > > > > ----- > > > > This is not very useful, though, because it will > > only work for strings > > that are exactly three letters long. Can you see > > how to write a loop > > to produe this output? > > > > Hint: the len() function will tell you how long a > > string is. > > > > eg: if vehicle == 'car' then len(vehicle) == 3. > > > > -- > > John. > > _______________________________________________ > > Hi John, > > I am still 'blind' here. > > Please, see below what I did, and what I got: > > >>> vehicle='car' > >>> index = 0 > >>> lenght =len(vehicle) > >>> last = vehicle[lenght -1] > >>> while last >= vehicle[0]: > ... letter = vehicle[index] > ... print letter > ... last -= 1 > ... > c > Traceback (most recent call last): > File "<stdin>", line 4, in ? > TypeError: unsupported operand type(s) for -=: 'str' > and 'int' > > As you can see, I am still a newbie... > Could anyone, please, guide me on this exercise? > Thanks! > Hoffmann A technique I used to find useful when I was very first learning (and struggling) was to calculate the variables for each pass of the loop (basically remove all the variable names, just like doing algebra). So: >>> vehicle='car' >>> index = 0 >>> lenght = len(vehicle) # therefore: >>> lenght = 3 >>> last = vehicle[lenght -1] # therefore: >>> last = vehicle[2] # therefore: >>> last = "r" >>> while "r" >= "c": # first pass ... letter = vehicle[index] # therefore: ... letter = vehicle[0] # therefore: ... letter = "c" ... print letter ... last -= 1 # therefore: ... "r" -= 1 # therefore: ... "r" = "r" - 1 # therefore: ... ERROR You'll find that that can make it much clearer what is actually happening. An alternative is to use lots and lots of print statements: >>> vehicle='car' >>> print vehicle >>> index = 0 >>> print index >>> lenght = len(vehicle) >>> print lenght and so on... It would be really good if there was a way to have a "verbose" interpreter that showed you each of the steps in the process, but I don't know of any. For example: >>> last = vehicle[lenght -1] last = vehicle[2] last = "r" >>> Ed From ml.cyresse at gmail.com Thu Mar 30 13:20:29 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 30 Mar 2006 23:20:29 +1200 Subject: [Tutor] Multi-thread environments Message-ID: <b6f3249e0603300320s24ab90dfn3782c58d48fff486@mail.gmail.com> Hi all, I'm working in my first multi-threaded environments, and I think I might have just been bitten by that. I having issue with one method in a parser of mine. Only the code I think is causing the issue is included below, I can do a full post to RAFB if requested, but there's a bit of it. The parser: class Parser: def __init__(self, Q): self.Q = Q self.players = {} self.teams = {} def parsePack(self, packet): #Do stuff to packet #Few conditionals removed, below is example actions. self.players["A_value"] += self.players["A_value"] self.teams["As_above"] += self.players["As_above"] def sendData(self): if not self.players or not self.teams: return self.Q.put((self.players, self.teams)) self.resetStats() def resetStats(): for key in self.players: self.players[key] = 0 for key in self.teams: self.teams[key] = 0 The thread in question: class ParseThread(threading.Thread): def __init__(self, Q, daoQ, cfg): self.Q = Q self.parser = parserx.WatcherInTheDark(daoQ, cfg["clan_regular_expressions"]) self.shutdown = False self.dump = False threading.Thread.__init__(self) def run(self): print "Parser starting." while True: if self.dump: self.parser.sendDat() self.dump = False try: data = self.Q.get(False) self.parser.check(data) except Empty: if self.shutdown: return continue The variable Q being passed in is a Queue.Queue, which is used to send data into another thread, which holds the DAO. The sendData() method is called by a timer thread setting Parsethread.dump to True. I was looking to avoid any asynchrous problems via these convoluted method. What I'm finding is that if a lot more sets of zeroed data are being sent to the DAO than should occur. If the resetStats() call is commented out, data is sent correctly. I need to reset the variables after each send so as to not try and co-ordinate state with a database, otherwise I'd be away laughing. My speculation is that because the Queue is shared between two threads, one of which is looping on it, that a data write to the Queue may actually occur after the next method call, the resetStats() method, has occurred. So, the call to Queue.put() is made, but the actual data is accessedin memory by the Queue after resetStats has changed it. Am I on a right path here? I may have to do a bit of a rewrite to get around this, as I've made some some assumptions early in the architecture, so before I devote an hour to finding out I'm making another wrong assumption, any hints on multi-threading in general are welcomed and requested, and any confirmation or refutation of my hypothesis also gladly welcomed. I've spent about eight hours so far trying to debug this; I've never been this frustrated in a Python project before to be honest... I've reached my next skill level bump, so to speak. Much thanks, Liam Clarke From kent37 at tds.net Thu Mar 30 14:59:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Mar 2006 07:59:30 -0500 Subject: [Tutor] Multi-thread environments In-Reply-To: <b6f3249e0603300320s24ab90dfn3782c58d48fff486@mail.gmail.com> References: <b6f3249e0603300320s24ab90dfn3782c58d48fff486@mail.gmail.com> Message-ID: <442BD632.6090705@tds.net> Liam Clarke wrote: > Hi all, > > I'm working in my first multi-threaded environments, and I think I > might have just been bitten by that. > > class Parser: > def __init__(self, Q): > self.Q = Q > self.players = {} > self.teams = {} > > def sendData(self): > if not self.players or not self.teams: return > self.Q.put((self.players, self.teams)) > self.resetStats() > > def resetStats(): > for key in self.players: > self.players[key] = 0 > for key in self.teams: > self.teams[key] = 0 > > What I'm finding is that if a lot more sets of zeroed data are being > sent to the DAO than should occur. > > If the resetStats() call is commented out, data is sent correctly. I > need to reset the variables after each send so as to not try and > co-ordinate state with a database, otherwise I'd be away laughing. > > My speculation is that because the Queue is shared between two > threads, one of which is looping on it, that a data write to the Queue > may actually occur after the next method call, the resetStats() > method, has occurred. > > So, the call to Queue.put() is made, but the actual data is accessedin > memory by the Queue after resetStats has changed it. You're close. The call to Queue.put() is synchronous - it will finish before the call to resetStats() is made - but the *data* is still shared. What is in the Queue is references to the dicts that is also referenced by self.players and self.teams. The actual dict is not copied! This is normal Python function call and assignment semantics, but in this case it's not what you want. You have a race condition - if the data in the Queue is processed before the call to resetStats() is made, it will work fine; if resetStats() is called first, it will be a problem. Actually there are many possible failures since resetStats() loops over the dicts, the consumer could be interleaving its reads with the writes in resetStats(). What you need to do is copy the data, either before you put it in the queue or as part of the reset. I suggest rewriting resetStats() to create new dicts because dict.fromkeys() will do just what you want: def resetStats(): self.players = dict.fromkeys(self.players.keys(), 0) self.teams = dict.teams(self.players.keys(), 0) This way you won't change the data seen by the consumer thread. > I've spent about eight hours so far trying to debug this; I've never > been this frustrated in a Python project before to be honest... I've > reached my next skill level bump, so to speak. Yes, threads can be mind-bending until you learn to spot the gotchas like this. By the way you also have a race condition here: > if self.dump: > self.parser.sendDat() > self.dump = False Possibly the thread that sets self.dump will set it again between the time you test it and when you reset it. If the setting thread is on a timer and the time is long enough, it won't be a problem, but it is a potential bug. Kent From kent37 at tds.net Thu Mar 30 15:21:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Mar 2006 08:21:56 -0500 Subject: [Tutor] for loops and exceptions In-Reply-To: <20060329185631.GR11313@ttsd.k12.or.us> References: <20060329185631.GR11313@ttsd.k12.or.us> Message-ID: <442BDB74.1050909@tds.net> Matthew White wrote: > Hello, > >>From a general style and/or programmatic perspective, which is a "better" > way to write this bit of code? Hmm, neither? > > try: > (dn, attrs) = conn.search_s(search_base, search_scope, search_filter, search_attrs): > except Exception, e: > warn_the_user(e) > do_something_useful() > > for (name, data) in (dn, attrs): > print '%s' % (name) > for key, value in data.iteritems(): > print '%s => %s' % (key, value) This will run the for loop even if you get an exception. I think the for loop is buggy, too, it is different from the one below. > > OR > > try: > for dn, attrs in conn.search_s(search_base, search_scope, search_filter, search_attrs): > print dn > for key, value in attrs.iteritems(): > print '\t%s => %s' % (key, value) > print > except Exception, e: > warn_the_user(e) > do_something_useful This might be OK. It will catch exceptions in the for loop, which you may or may not want. If this code is at a low level of your program, it's best to only catch expected exceptions, and let unexpected exceptions propagate to a higher level. At the higher level, you can have a generic except block that reports the error and moves on. This is often in a top-level loop or event handler. Your code has elements of both - code that does real work with a generic except block that reports errors. Anyway here is a construction that is very useful for catching just the exceptions you expect to see from a bit of code, while running the rest of the code outside of the try block. try: (dn, attrs) = conn.search_s(search_base, search_scope, search_filter, search_attrs): except ConnectionError, e: warn_the_user(e) do_something_useful() else: print dn for key, value in attrs.iteritems(): print '\t%s => %s' % (key, value) print The idea is to put as little code as possible in the scope of the try, and to catch as few exceptions as possible. If no exception is raised, the else: block will run. If there is an exception in that code, it will propagate to a higher level. Kent From mhansen at cso.atmel.com Thu Mar 30 17:19:14 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 30 Mar 2006 08:19:14 -0700 Subject: [Tutor] OT: Tutor Digest and Outlook 2003 Message-ID: <011a01c6540d$4e5f3c10$28645f0a@mikehansen> The company I work for is moving to Outlook 2003 and Exchange server. I used to use Thunderbird. Anyway, when digest messages show up in Outlook 2003, all the posts are attachments. Does anyone know how to get them to display in-line? Thanks, Mike From slevin at signpuddle.net Thu Mar 30 18:05:35 2006 From: slevin at signpuddle.net (Steve Slevinski) Date: Thu, 30 Mar 2006 11:05:35 -0500 Subject: [Tutor] Turnkey Python on a USB stick In-Reply-To: <200603280157.40865.ms@cerenity.org> References: <200603270926.34550.keosophon@khmeros.info> <44284243.3030107@signpuddle.net> <44285744.7000000@signpuddle.net> <200603280157.40865.ms@cerenity.org> Message-ID: <442C01CF.10401@signpuddle.net> Hey Michael Sparks, You said you were interested in my Turnkey Python on a USB stick so I thought I'd tell you about it. It's going very well. I'm just putting the polish on it now. I have 2 main USB sticks: 1 for development and 1 for distribution to end users. My development USB can be plugged into any Windows computer and I have my entire development environment ready to go. I can work at home, on location, or even at the library. Movable Python (less than $10 and the only purchase) make this possible. My main editor is Leo (open source python). It takes a while to grok, but there isn't anything else like it. My distribution USB runs the same code as my server. I'm using the Uniform Server project. All my users have to do is plug in the USB, start the server and point the browser to localhost. It should look really nice once I get my logo printed on the USB sticks. Right now my server code is staying PHP, but I'm on the path to Python. The Uniform Server hasn't completed the mod_python plug-in so I have some time. I'm also going to try py2exe once I get the hang of the GTK and Twisted. Again, I have some time. Three additional software packages that help are... PStart - Shortcuts for USB Allway Sync - PC to USB sync. Disc Image XML - take a distribution image and writes a USB stick in under 2 minutes. Regards, -Steve Michael Sparks wrote: > On Monday 27 March 2006 22:21, Steve Slevinski wrote: > >> Does this sound reasonable? Are their any alternatives to Movable >> Python? (http://www.voidspace.org.uk/python/movpy/) >> > > Hi Steve, > > I've got no experience of setting up such a beast or using movable python, but > I just wanted to say it sounds like an EXCELLENT idea, and I'd be interested > in hearing how you get on! > > :) > > Michael. > > > From oasf2004 at yahoo.com Thu Mar 30 18:47:38 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Thu, 30 Mar 2006 08:47:38 -0800 (PST) Subject: [Tutor] Program for outputing the letter backward In-Reply-To: <34bb7f5b0603300048m3fbd6cf2jc8b1b1b070e276bb@mail.gmail.com> Message-ID: <20060330164738.19288.qmail@web60019.mail.yahoo.com> --- Ed Singleton <singletoned at gmail.com> wrote: > On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote: > > --- John Fouhy <john at fouhy.net> wrote: > > > > > On 29/03/06, Hoffmann <oasf2004 at yahoo.com> > wrote: > > > > vehicle='car' > > > > index = vehicle[-1] #the last letter > > > > index_zero = vehicle[0] #the first letter > > > > > > > > while index >= index_zero: > > > > letter=vehicle[index] > > > > print letter > > > > index -= 1 > > > > > > > > The problem is that I get no output here. > Could I > > > hear > > > > from you? > > > > > > I can print the letters backwards like this: > > > > > > vehicle = 'car' > > > print vehicle[2] > > > print vehicle[1] > > > print vehicle[0] > > > > > > Output: > > > > > > r > > > a > > > c > > > > > > ----- > > > > > > This is not very useful, though, because it will > > > only work for strings > > > that are exactly three letters long. Can you > see > > > how to write a loop > > > to produe this output? > > > > > > Hint: the len() function will tell you how long > a > > > string is. > > > > > > eg: if vehicle == 'car' then len(vehicle) == 3. > > > > > > -- > > > John. > > > _______________________________________________ > > > > Hi John, > > > > I am still 'blind' here. > > > > Please, see below what I did, and what I got: > > > > >>> vehicle='car' > > >>> index = 0 > > >>> lenght =len(vehicle) > > >>> last = vehicle[lenght -1] > > >>> while last >= vehicle[0]: > > ... letter = vehicle[index] > > ... print letter > > ... last -= 1 > > ... > > c > > Traceback (most recent call last): > > File "<stdin>", line 4, in ? > > TypeError: unsupported operand type(s) for -=: > 'str' > > and 'int' > > > > As you can see, I am still a newbie... > > Could anyone, please, guide me on this exercise? > > Thanks! > > Hoffmann > > A technique I used to find useful when I was very > first learning (and > struggling) was to calculate the variables for each > pass of the loop > (basically remove all the variable names, just like > doing algebra). > > So: > > >>> vehicle='car' > >>> index = 0 > >>> lenght = len(vehicle) # therefore: > >>> lenght = 3 > >>> last = vehicle[lenght -1] # therefore: > >>> last = vehicle[2] # therefore: > >>> last = "r" > >>> while "r" >= "c": # first pass > ... letter = vehicle[index] # therefore: > ... letter = vehicle[0] # therefore: > ... letter = "c" > ... print letter > ... last -= 1 # therefore: > ... "r" -= 1 # therefore: > ... "r" = "r" - 1 # therefore: > ... ERROR > > You'll find that that can make it much clearer what > is actually > happening. An alternative is to use lots and lots > of print > statements: > > >>> vehicle='car' > >>> print vehicle > >>> index = 0 > >>> print index > >>> lenght = len(vehicle) > >>> print lenght > > and so on... > > It would be really good if there was a way to have a > "verbose" > interpreter that showed you each of the steps in the > process, but I > don't know of any. > > For example: > > >>> last = vehicle[lenght -1] > last = vehicle[2] > last = "r" > >>> > > Ed > Hi Ed, Many thanks for the hints! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Thu Mar 30 22:29:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Mar 2006 15:29:15 -0500 Subject: [Tutor] number of nodes In-Reply-To: <442A43B4.6040206@khmeros.info> References: <442A43B4.6040206@khmeros.info> Message-ID: <442C3F9B.2080800@tds.net> kakada wrote: > Hello everyone, > > textp = xmldoc.getElementsByTagName('text:p') > > from the example above, How can I know how many <text:p> node are there? len(textp), maybe? Kent From jramakrishnan at neuropace.com Fri Mar 31 02:57:05 2006 From: jramakrishnan at neuropace.com (Janesh Ramakrishnan) Date: Thu, 30 Mar 2006 16:57:05 -0800 Subject: [Tutor] Searching across .Py files for a particular string/ character Message-ID: <405EDF2FA0855E43B27EA6DAFA1C78CEE654C7@laguna.neuropace.com> Hi Folks, I was wondering what would be the best way to look up a string across different files in the Python interpreter (PythonWin 2.4). The find function only finds files within currently open files. If I have a folder of .py scripts and need to look up a specific keyword or string among all these files within the project folder, is there any method that you'd recommend? For eg: Visual Studio 6.0 can look for a string across numerous files indexed in a project and returns a list of files containing that specific string. Any help would be greatly appreciated. Thanks. Janesh From David.Heiser at intelliden.com Fri Mar 31 04:17:39 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Thu, 30 Mar 2006 19:17:39 -0700 Subject: [Tutor] Searching across .Py files for a particular string/character Message-ID: <3CABD13EA1D5D347A1B75014BD54CFD502B0BC2D@COSIUM03.intelliden.net> Here's a simple Python script that will do it. It's not very sophisticated, but it's easy to modify for special cases. import os, string def Find(TargetString, DIR, Names): for Name in Names: if Name != "Search.py": try: TargetFile = DIR + "/" + Name Blob = open(TargetFile, "r").read() if Blob.find(TargetString) > -1: print TargetFile except IOError: pass return TargetString = 'telnetlib' print "\nFinding " + TargetString + "\n---------------\n" os.path.walk(".", Find, TargetString) ============================================== -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Janesh Ramakrishnan Sent: Thursday, March 30, 2006 5:57 PM To: tutor at python.org Subject: [Tutor] Searching across .Py files for a particular string/character Hi Folks, I was wondering what would be the best way to look up a string across different files in the Python interpreter (PythonWin 2.4). The find function only finds files within currently open files. If I have a folder of .py scripts and need to look up a specific keyword or string among all these files within the project folder, is there any method that you'd recommend? For eg: Visual Studio 6.0 can look for a string across numerous files indexed in a project and returns a list of files containing that specific string. Any help would be greatly appreciated. Thanks. Janesh _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Mar 31 04:22:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Mar 2006 21:22:39 -0500 Subject: [Tutor] Searching across .Py files for a particular string/ character In-Reply-To: <405EDF2FA0855E43B27EA6DAFA1C78CEE654C7@laguna.neuropace.com> References: <405EDF2FA0855E43B27EA6DAFA1C78CEE654C7@laguna.neuropace.com> Message-ID: <442C926F.3080007@tds.net> Janesh Ramakrishnan wrote: > Hi Folks, > > I was wondering what would be the best way to look up a string across > different files in the Python interpreter (PythonWin 2.4). The find function only finds files within currently open files. If I have a folder of .py scripts and need to look up a specific keyword or string among all these files within the project folder, is there any method that you'd recommend? I would do that in my editor, probably. But Python can get a list of files in a directory with os.listdir(). Loop over the files, use os.path.join() to make a full path, open the file, read the data, look for the string in the data. Kent From keosophon at khmeros.info Fri Mar 31 06:01:18 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Fri, 31 Mar 2006 11:01:18 +0700 Subject: [Tutor] XML node name and property Message-ID: <200603311101.18291.keosophon@khmeros.info> Hi all, How can I get a name of an XML node and and its property name and its property value? Thanks, Sophon From mail at ozzmosis.com Fri Mar 31 06:15:07 2006 From: mail at ozzmosis.com (andrew clarke) Date: Fri, 31 Mar 2006 15:15:07 +1100 Subject: [Tutor] ASCII In-Reply-To: <6b16fb4c0603290021v2055dd3fn655cda44a95b9cc4@mail.gmail.com> References: <6b16fb4c0603282323k52abf446v63d3f7bd8ed09ec0@mail.gmail.com> <cf5262d20603282338y40982457v1596de22077f5169@mail.gmail.com> <6b16fb4c0603290021v2055dd3fn655cda44a95b9cc4@mail.gmail.com> Message-ID: <20060331041506.GA33058@ozzmosis.com> On Wed, Mar 29, 2006 at 01:51:30PM +0530, Kaushal Shriyan wrote: > > How do i use this ASCII values in my day to day activities, I am going > > through learning python, > > Its a very general question not related to python at all, I have a > minimum knowledge in ASCII just wanted to know how it is used and how > it helps out http://en.wikipedia.org/wiki/Ascii may help. From artificiallystupid at yahoo.com Fri Mar 31 06:23:31 2006 From: artificiallystupid at yahoo.com (Johnston Jiaa) Date: Thu, 30 Mar 2006 20:23:31 -0800 (PST) Subject: [Tutor] Apple Remote "Mouse" Message-ID: <20060331042331.75343.qmail@web50405.mail.yahoo.com> I recently bought a Macbook Pro from Apple. As it comes with a remote, I thought it would be great to use it as a mouse when not in Front Row. The fast forward button would move the cursor to the left, the volume increase would move it up the screen, etc and the play button would serve as a "click." Is there any way to manipulate the cursor position on the screen using Python? It is greatly appreciated if someone can point in the direction of where to look or what to search as no immediately useful hits came up from google. I am absolutely clueless about how to implement any of this. It would be awesome if someone could briefly explain, or maybe point me to a tutorial of any sort, how to write a program that could detect the button pressed on the remote and accordingly move the cursor up, down, side-to-side. Knowing how to disable the volume control of the "up and down" function of the anticipated remote would also be great, if anyone has time to elaborate how this can be done. Thank you for reading my message, and I hope you do not regard me as being a waste of your time. Johnston Jiaa (artificiallystupid at yahoo.com) --------------------------------- 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/20060330/2cf00444/attachment.htm From hokkakada at khmeros.info Fri Mar 31 09:21:35 2006 From: hokkakada at khmeros.info (kakada) Date: Fri, 31 Mar 2006 14:21:35 +0700 Subject: [Tutor] remove not-empty directory Message-ID: <442CD87F.9070907@khmeros.info> Hi all, Just a quick question again, how can I remove not-empty directory in python? assumed I have the following directory: ( temp/a/b/ temp/a/c/d.odt temp/e.xml) I want to remove the whole temp/ directory. Thanks :) da From tim.golden at viacom-outdoor.co.uk Fri Mar 31 09:36:09 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 31 Mar 2006 08:36:09 +0100 Subject: [Tutor] remove not-empty directory Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E109@vogbs009.gb.vo.local> [kakada] | Just a quick question again, how can I remove not-empty | directory in python? | | assumed I have the following directory: | | ( temp/a/b/ | temp/a/c/d.odt | temp/e.xml) | | I want to remove the whole temp/ directory. Look at the shutil module, and in particular at the rmtree function TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tim.golden at viacom-outdoor.co.uk Fri Mar 31 10:29:24 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 31 Mar 2006 09:29:24 +0100 Subject: [Tutor] Apple Remote "Mouse" Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E10A@vogbs009.gb.vo.local> [Johnston Jiaa] | I recently bought a Macbook Pro from Apple. As it comes with | a remote, I thought it would be great to use it as a mouse | when not in Front Row. The fast forward button would move | the cursor to the left, the volume increase would move it up | the screen, etc and the play button would serve as a "click." | | Is there any way to manipulate the cursor position on the | screen using Python? It is greatly appreciated if someone | can point in the direction of where to look or what to search | as no immediately useful hits came up from google. Just to warn you: this message will not directly help you to solve your problem, but... ... this seems to me to be the kind of query where you could legitimately post to the main Python newsgroup / mailing list and/or to some Mac-specific one, if there is such a thing. What you're asking is not really about Python as such, but about whatever the technologies are within the Macbook environment for detecting and controlling remote devices. I suggest, if you haven't already, that you post to the main Python list, but first have a Google around to see if someone's done this using *any* programming language which might be a good starting point for someone to explain how to translate that into Python. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kent37 at tds.net Fri Mar 31 12:37:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 05:37:47 -0500 Subject: [Tutor] XML node name and property In-Reply-To: <200603311101.18291.keosophon@khmeros.info> References: <200603311101.18291.keosophon@khmeros.info> Message-ID: <442D067B.3000609@tds.net> Keo Sophon wrote: > Hi all, > > How can I get a name of an XML node and and its property name and its property > value? How are your reading the XML? (xml.dom, ElementTree, BeautifulSoup...) Kent From hokkakada at khmeros.info Fri Mar 31 12:58:34 2006 From: hokkakada at khmeros.info (kakada) Date: Fri, 31 Mar 2006 17:58:34 +0700 Subject: [Tutor] getAttribute Message-ID: <442D0B5A.9010401@khmeros.info> Hello all, Could anyone help me by giving example of getAttribute xmldata = ziparchive.read("content.xml") xmldoc = minidom.parseString(xmldata) officeNode = xmldoc.getElementsByTagName('office:text') I have another function: def go_thru (nodelist): for x in range(nodelist.length): node = nodelist[x] i = 0 print node.getAttribute('text:style-name') go_thru(officeNode) #Calling function I always get error message: AttributeError: Text instance has no attribute 'getAttribute' Could anyone give an explanation? Thanks a lot, da From keosophon at khmeros.info Fri Mar 31 13:17:03 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Fri, 31 Mar 2006 18:17:03 +0700 Subject: [Tutor] XML node name and property In-Reply-To: <442D067B.3000609@tds.net> References: <200603311101.18291.keosophon@khmeros.info> <442D067B.3000609@tds.net> Message-ID: <200603311817.03394.keosophon@khmeros.info> On Friday 31 March 2006 17:37, Kent Johnson wrote: > Keo Sophon wrote: > > Hi all, > > > > How can I get a name of an XML node and and its property name and its > > property value? > > How are your reading the XML? (xml.dom, ElementTree, BeautifulSoup...) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I am using xml.dom. Phon From keosophon at khmeros.info Fri Mar 31 14:06:26 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Fri, 31 Mar 2006 19:06:26 +0700 Subject: [Tutor] how to get the content of an XML elements. Message-ID: <200603311906.26110.keosophon@khmeros.info> Hi all, Is there anyway to get the content of an XML elements. I am using xml.dom. Thanks, Phon From ml.cyresse at gmail.com Fri Mar 31 15:02:33 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 1 Apr 2006 01:02:33 +1200 Subject: [Tutor] Multi-thread environments In-Reply-To: <442BD632.6090705@tds.net> References: <b6f3249e0603300320s24ab90dfn3782c58d48fff486@mail.gmail.com> <442BD632.6090705@tds.net> Message-ID: <b6f3249e0603310502g244f050fo1611826c7655d085@mail.gmail.com> Thanks very much for that Kent, works fine and dandy now. >_< This is one to chalk up to experience. I copied the dicts as you said. Regards, Liam On 3/31/06, Kent Johnson <kent37 at tds.net> wrote: > Liam Clarke wrote: > > Hi all, > > > > I'm working in my first multi-threaded environments, and I think I > > might have just been bitten by that. > > > > class Parser: > > def __init__(self, Q): > > self.Q = Q > > self.players = {} > > self.teams = {} > > > > def sendData(self): > > if not self.players or not self.teams: return > > self.Q.put((self.players, self.teams)) > > self.resetStats() > > > > def resetStats(): > > for key in self.players: > > self.players[key] = 0 > > for key in self.teams: > > self.teams[key] = 0 > > > > > What I'm finding is that if a lot more sets of zeroed data are being > > sent to the DAO than should occur. > > > > If the resetStats() call is commented out, data is sent correctly. I > > need to reset the variables after each send so as to not try and > > co-ordinate state with a database, otherwise I'd be away laughing. > > > > My speculation is that because the Queue is shared between two > > threads, one of which is looping on it, that a data write to the Queue > > may actually occur after the next method call, the resetStats() > > method, has occurred. > > > > So, the call to Queue.put() is made, but the actual data is accessedin > > memory by the Queue after resetStats has changed it. > > You're close. The call to Queue.put() is synchronous - it will finish > before the call to resetStats() is made - but the *data* is still shared. > > What is in the Queue is references to the dicts that is also referenced > by self.players and self.teams. The actual dict is not copied! This is > normal Python function call and assignment semantics, but in this case > it's not what you want. You have a race condition - if the data in the > Queue is processed before the call to resetStats() is made, it will work > fine; if resetStats() is called first, it will be a problem. Actually > there are many possible failures since resetStats() loops over the > dicts, the consumer could be interleaving its reads with the writes in > resetStats(). > > What you need to do is copy the data, either before you put it in the > queue or as part of the reset. I suggest rewriting resetStats() to > create new dicts because dict.fromkeys() will do just what you want: > def resetStats(): > self.players = dict.fromkeys(self.players.keys(), 0) > self.teams = dict.teams(self.players.keys(), 0) > > This way you won't change the data seen by the consumer thread. > > > I've spent about eight hours so far trying to debug this; I've never > > been this frustrated in a Python project before to be honest... I've > > reached my next skill level bump, so to speak. > > Yes, threads can be mind-bending until you learn to spot the gotchas > like this. > > By the way you also have a race condition here: > > if self.dump: > > self.parser.sendDat() > > self.dump = False > > Possibly the thread that sets self.dump will set it again between the > time you test it and when you reset it. If the setting thread is on a > timer and the time is long enough, it won't be a problem, but it is a > potential bug. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Mar 31 15:13:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 08:13:14 -0500 Subject: [Tutor] XML node name and property In-Reply-To: <200603311817.03394.keosophon@khmeros.info> References: <200603311101.18291.keosophon@khmeros.info> <442D067B.3000609@tds.net> <200603311817.03394.keosophon@khmeros.info> Message-ID: <442D2AEA.9010106@tds.net> Keo Sophon wrote: > On Friday 31 March 2006 17:37, Kent Johnson wrote: > >>Keo Sophon wrote: >> >>>How can I get a name of an XML node and and its property name and its >>>property value? >> >>How are your reading the XML? (xml.dom, ElementTree, BeautifulSoup...) >> > > I am using xml.dom. I generally use ElementTree for XML access, it is much simpler than xml.dom. But here is what I figured out: The tag name is node.nodeName If by property you mean attribute, you can get a list of all attributes by node.attributes.keys() and access the value of a particular one by node.attributes['attributeName'].nodeValue Google python xml.dom to find many more examples. Or Google ElementTree to find an easier way to do it... Kent From kent37 at tds.net Fri Mar 31 15:14:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 08:14:53 -0500 Subject: [Tutor] getAttribute In-Reply-To: <442D0B5A.9010401@khmeros.info> References: <442D0B5A.9010401@khmeros.info> Message-ID: <442D2B4D.9000609@tds.net> kakada wrote: > Hello all, > > Could anyone help me by giving example of getAttribute > > xmldata = ziparchive.read("content.xml") > xmldoc = minidom.parseString(xmldata) > officeNode = xmldoc.getElementsByTagName('office:text') > > I have another function: > def go_thru (nodelist): > for x in range(nodelist.length): > node = nodelist[x] > i = 0 > print node.getAttribute('text:style-name') > > go_thru(officeNode) #Calling function > > I always get error message: AttributeError: Text instance has no > attribute 'getAttribute' > Could anyone give an explanation? I think it should be node.attributes['text:style-name'].nodeValue. You might want to look at ElementTree, it is a more Pythonic XML library. Kent From ilias at lazaridis.com Fri Mar 31 14:56:25 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Fri, 31 Mar 2006 15:56:25 +0300 Subject: [Tutor] Looking for Constructs to Remove Redundant Code Message-ID: <e0j8tr$re5$1@sea.gmane.org> I have this python code class Car: """Type of car.""" manufacturer = f.string() model = f.string() modelYear = f.integer() _key(manufacturer, model, modelYear) def __str__(self): return '%s %s %s' % (self.modelYear, self.manufacturer, self.model) - and would like to see it e.g. this way: class Car: """Type of car.""" manufacturer = f.string(true, str=2) model = f.string(true, str=3) modelYear = f.integer(true, str=1) - how would the factory method look like? def string(self, key, str ) # create somehow the __str__ function # create somehow the key . -- http://lazaridis.com From kent37 at tds.net Fri Mar 31 15:34:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 08:34:07 -0500 Subject: [Tutor] Looking for Constructs to Remove Redundant Code In-Reply-To: <e0j8tr$re5$1@sea.gmane.org> References: <e0j8tr$re5$1@sea.gmane.org> Message-ID: <442D2FCF.3000704@tds.net> Ilias Lazaridis wrote: > I have this python code > > class Car: > """Type of car.""" > > manufacturer = f.string() > model = f.string() > modelYear = f.integer() > > _key(manufacturer, model, modelYear) > > def __str__(self): > return '%s %s %s' % (self.modelYear, self.manufacturer, self.model) What is f.string()? What is _key()? Are you using a metaclass here? Did you intentionally omit an __init__() method? If this is working code there is a lot you are not showing. > and would like to see it e.g. this way: > > class Car: > """Type of car.""" > > manufacturer = f.string(true, str=2) > model = f.string(true, str=3) > modelYear = f.integer(true, str=1) > > - > > how would the factory method look like? > > def string(self, key, str ) > # create somehow the __str__ function > # create somehow the key This would go in your metaclass __init__ I think. But hard to say without more details. Kent From jonasmg at softhome.net Fri Mar 31 17:25:21 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Fri, 31 Mar 2006 08:25:21 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters Message-ID: <courier.442D49E1.00001454@softhome.net> From a table, I want to get the cells for then only choose some of them. <table> <tr> <td>WY</td> <td>Wyo.</td> </tr> ... </table> Using: for row in table('tr'): print row.contents ['\n', <td>WY</td>, '\n', <td>Wyo.</td>, '\n'] [...] I get a new line character between each cell. Is possible get them without those '\n'? Thanks in advance! From kent37 at tds.net Fri Mar 31 17:43:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 10:43:52 -0500 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <courier.442D49E1.00001454@softhome.net> References: <courier.442D49E1.00001454@softhome.net> Message-ID: <442D4E38.9050508@tds.net> jonasmg at softhome.net wrote: > From a table, I want to get the cells for then only choose some of them. > > <table> > <tr> > <td>WY</td> > <td>Wyo.</td> > </tr> > ... > </table> > > Using: > > for row in table('tr'): print row.contents > > ['\n', <td>WY</td>, '\n', <td>Wyo.</td>, '\n'] > [...] > > I get a new line character between each cell. > > Is possible get them without those '\n'? Well, the newlines are in your data, so you need to strip them or ignore them somewhere. You don't say what you are actually trying to do, maybe this is close: for row in table('tr'): cellText = [cell.string for cell in row('td')] print ' '.join(cellText) Kent From jonasmg at softhome.net Fri Mar 31 18:01:15 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Fri, 31 Mar 2006 09:01:15 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <442D4E38.9050508@tds.net> References: <courier.442D49E1.00001454@softhome.net> <442D4E38.9050508@tds.net> Message-ID: <courier.442D524B.00003B2D@softhome.net> Kent Johnson writes: > jonasmg at softhome.net wrote: >> From a table, I want to get the cells for then only choose some of them. >> >> <table> >> <tr> >> <td>WY</td> >> <td>Wyo.</td> >> </tr> >> ... >> </table> >> >> Using: >> >> for row in table('tr'): print row.contents >> >> ['\n', <td>WY</td>, '\n', <td>Wyo.</td>, '\n'] >> [...] >> >> I get a new line character between each cell. >> >> Is possible get them without those '\n'? > > Well, the newlines are in your data, so you need to strip them or ignore > them somewhere. > > You don't say what you are actually trying to do, maybe this is close: > for row in table('tr'): > cellText = [cell.string for cell in row('td')] > print ' '.join(cellText) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I want only (for each row) to get some positions (i.e. row.contents[0],row.contents[2]) From kent37 at tds.net Fri Mar 31 18:12:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 11:12:13 -0500 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <courier.442D524B.00003B2D@softhome.net> References: <courier.442D49E1.00001454@softhome.net> <442D4E38.9050508@tds.net> <courier.442D524B.00003B2D@softhome.net> Message-ID: <442D54DD.3070605@tds.net> jonasmg at softhome.net wrote: > Kent Johnson writes: > > >>jonasmg at softhome.net wrote: >> >>> From a table, I want to get the cells for then only choose some of them. >>> >>><table> >>><tr> >>><td>WY</td> >>><td>Wyo.</td> >>></tr> >>>... >>></table> >>> >>>Using: >>> >>>for row in table('tr'): print row.contents >>> >>> ['\n', <td>WY</td>, '\n', <td>Wyo.</td>, '\n'] >>> [...] >>> >>>I get a new line character between each cell. >>> >>>Is possible get them without those '\n'? >> >>Well, the newlines are in your data, so you need to strip them or ignore >>them somewhere. > > I want only (for each row) to get some positions (i.e. > row.contents[0],row.contents[2]) It sounds like you should just work with row('td') instead of row.contents. That will give you a list of just the <td> elements. Kent From jonasmg at softhome.net Fri Mar 31 18:29:33 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Fri, 31 Mar 2006 09:29:33 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <442D54DD.3070605@tds.net> References: <courier.442D49E1.00001454@softhome.net> <442D4E38.9050508@tds.net> <courier.442D524B.00003B2D@softhome.net> <442D54DD.3070605@tds.net> Message-ID: <courier.442D58ED.00005905@softhome.net> Kent Johnson writes: > jonasmg at softhome.net wrote: >> Kent Johnson writes: >> >> >>>jonasmg at softhome.net wrote: >>> >>>> From a table, I want to get the cells for then only choose some of them. >>>> >>>><table> >>>><tr> >>>><td>WY</td> >>>><td>Wyo.</td> >>>></tr> >>>>... >>>></table> >>>> >>>>Using: >>>> >>>>for row in table('tr'): print row.contents >>>> >>>> ['\n', <td>WY</td>, '\n', <td>Wyo.</td>, '\n'] >>>> [...] >>>> >>>>I get a new line character between each cell. >>>> >>>>Is possible get them without those '\n'? >>> >>>Well, the newlines are in your data, so you need to strip them or ignore >>>them somewhere. >> >> I want only (for each row) to get some positions (i.e. >> row.contents[0],row.contents[2]) > > It sounds like you should just work with row('td') instead of > row.contents. That will give you a list of just the <td> elements. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor You have reason but the problem is that some cells have anchors. Sorry, I forgot myself to say it. and using: for row in table('tr'): cellText = [cell.string for cell in row('td')] print cellText I get null values in cell with anchors. From kent37 at tds.net Fri Mar 31 18:38:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 11:38:29 -0500 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <courier.442D58ED.00005905@softhome.net> References: <courier.442D49E1.00001454@softhome.net> <442D4E38.9050508@tds.net> <courier.442D524B.00003B2D@softhome.net> <442D54DD.3070605@tds.net> <courier.442D58ED.00005905@softhome.net> Message-ID: <442D5B05.5020607@tds.net> jonasmg at softhome.net wrote: > You have reason but the problem is that some cells have anchors. > Sorry, I forgot myself to say it. > > and using: > > for row in table('tr'): > cellText = [cell.string for cell in row('td')] > print cellText > > I get null values in cell with anchors. Can you give an example of your actual data and the result you want to generate from it? I can't give you a correct answer if you don't tell me the real question. Kent From jonasmg at softhome.net Fri Mar 31 18:47:05 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Fri, 31 Mar 2006 09:47:05 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <442D5B05.5020607@tds.net> References: <courier.442D49E1.00001454@softhome.net> <442D4E38.9050508@tds.net> <courier.442D524B.00003B2D@softhome.net> <442D54DD.3070605@tds.net> <courier.442D58ED.00005905@softhome.net> <442D5B05.5020607@tds.net> Message-ID: <courier.442D5D09.00006BD9@softhome.net> Kent Johnson writes: > jonasmg at softhome.net wrote: >> You have reason but the problem is that some cells have anchors. >> Sorry, I forgot myself to say it. >> >> and using: >> >> for row in table('tr'): >> cellText = [cell.string for cell in row('td')] >> print cellText >> >> I get null values in cell with anchors. > > Can you give an example of your actual data and the result you want to > generate from it? I can't give you a correct answer if you don't tell me > the real question. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor List of states: http://en.wikipedia.org/wiki/U.S._state : soup = BeautifulSoup(html) : # Get the second table (list of states). : table = soup.first('table').findNext('table') : print table ... <tr> <td>WY</td> <td>Wyo.</td> <td><a href="/wiki/Wyoming" title="Wyoming">Wyoming</a></td> <td><a href="/wiki/Cheyenne%2C_Wyoming" title="Cheyenne, Wyoming">Cheyenne</a></td> <td><a href="/wiki/Cheyenne%2C_Wyoming" title="Cheyenne, Wyoming">Cheyenne</a></td> <td><a href="/wiki/Image:Flag_of_Wyoming.svg" class="image" title=""><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" longdesc="/wiki/Image:Flag_of_Wyoming.svg" /></a></td> </tr> </table> Of each row (tr), I want to get the cells (td): 1,3,4 (postal,state,capital). But cells 3 and 4 have anchors. Thanks Kent. From kent37 at tds.net Fri Mar 31 19:02:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 12:02:06 -0500 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <courier.442D5D09.00006BD9@softhome.net> References: <courier.442D49E1.00001454@softhome.net> <442D4E38.9050508@tds.net> <courier.442D524B.00003B2D@softhome.net> <442D54DD.3070605@tds.net> <courier.442D58ED.00005905@softhome.net> <442D5B05.5020607@tds.net> <courier.442D5D09.00006BD9@softhome.net> Message-ID: <442D608E.9080102@tds.net> jonasmg at softhome.net wrote: > List of states: > http://en.wikipedia.org/wiki/U.S._state > > : soup = BeautifulSoup(html) > : # Get the second table (list of states). > : table = soup.first('table').findNext('table') > : print table > > ... > <tr> > <td>WY</td> > <td>Wyo.</td> > <td><a href="/wiki/Wyoming" title="Wyoming">Wyoming</a></td> > <td><a href="/wiki/Cheyenne%2C_Wyoming" title="Cheyenne, > Wyoming">Cheyenne</a></td> > <td><a href="/wiki/Cheyenne%2C_Wyoming" title="Cheyenne, > Wyoming">Cheyenne</a></td> > <td><a href="/wiki/Image:Flag_of_Wyoming.svg" class="image" title=""><img > src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin > g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" > longdesc="/wiki/Image:Flag_of_Wyoming.svg" /></a></td> > </tr> > </table> > > Of each row (tr), I want to get the cells (td): 1,3,4 > (postal,state,capital). But cells 3 and 4 have anchors. So dig into the cells and get the data from the anchor. cells = row('td') cells[0].string cells[2]('a').string cells[3]('a').string Kent From sanelson at gmail.com Fri Mar 31 21:55:41 2006 From: sanelson at gmail.com (Steve Nelson) Date: Fri, 31 Mar 2006 20:55:41 +0100 Subject: [Tutor] Inverted Index Algorithm Message-ID: <b6131fdc0603311155i35496a91tb7a0b3e994c57eb4@mail.gmail.com> Hello All, I've been reading about "Inverted Indexing" - I'd like to try to write something in Python that illustrates the concpet, as I've got to give a presentation about it. Where would be a good place to start? S. From reddazz at gmail.com Fri Mar 31 22:17:49 2006 From: reddazz at gmail.com (William Mhlanga) Date: Fri, 31 Mar 2006 21:17:49 +0100 Subject: [Tutor] Python app and UNIX commands Message-ID: <f70bccff0603311217o67beebabg5b9809602b6630f9@mail.gmail.com> Hello, I have come up with an idea of an app that I would like to write using python but I need some guidance. I would like to write an app for Linux/Unix that fetches a gzipped or bzipped file from a remote server by http or ftp. The file will be downloaded to a temporary directory, unzipped and its contents copied to specific directory. If the process has gone well, the files in the temporary directory are cleaned up. To do this, I guess I would have to mingle python with some UNIX commands. How do I intermingle python and unix commands? I have read most of Michael Dawsons book but unfortunately it doesn't have this kind of stuff. I have just bought Magnus Lie Hetland's book and just started going through it. Any other recommendations will be appreciated. Thanks. Will -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060331/515e907e/attachment.html From wescpy at gmail.com Fri Mar 31 22:33:12 2006 From: wescpy at gmail.com (w chun) Date: Fri, 31 Mar 2006 12:33:12 -0800 Subject: [Tutor] Python app and UNIX commands In-Reply-To: <f70bccff0603311217o67beebabg5b9809602b6630f9@mail.gmail.com> References: <f70bccff0603311217o67beebabg5b9809602b6630f9@mail.gmail.com> Message-ID: <78b3a9580603311233o149c3af2o383d18913b6f564a@mail.gmail.com> > I would like to write an app for Linux/Unix > that fetches a gzipped or bzipped file from a remote server by http or ftp. > The file will be downloaded to a temporary directory, unzipped and its > contents copied to specific directory. If the process has gone well, the > files in the temporary directory are cleaned up. To do this, I guess I would > have to mingle python with some UNIX commands. How do I intermingle python > and unix commands? hi will, you can do it all in python... no unix at all! check out the Python Library Reference for docs on these modules which you'll be using: - urllib (downloading via HTTP or FTP) - tempfile (creating a temp dir for the work) - gzip and bz2 (for processing gzipped or bzipped files) - os and os.path (for file-related moving, copying, deleting) there may be one or two more, but i think you can do it with just these four as long as you do not have to run other Unix cmds (and/or need to send input or receive output from them). good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Fri Mar 31 22:39:21 2006 From: wescpy at gmail.com (w chun) Date: Fri, 31 Mar 2006 12:39:21 -0800 Subject: [Tutor] Apple Remote "Mouse" In-Reply-To: <CCAC78D42E32184F8E26DC163DB9830617E10A@vogbs009.gb.vo.local> References: <CCAC78D42E32184F8E26DC163DB9830617E10A@vogbs009.gb.vo.local> Message-ID: <78b3a9580603311239j197a205dl1e4ec5bd68fea199@mail.gmail.com> > ... this seems to me to be the kind of query where > you could legitimately post to the main Python > newsgroup / mailing list and/or to some Mac-specific > one, if there is such a thing. ... and there is: http://mail.python.org/mailman/listinfo/pythonmac-sig cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From jonasmg at softhome.net Fri Mar 31 23:08:13 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Fri, 31 Mar 2006 14:08:13 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <442D608E.9080102@tds.net> References: <courier.442D49E1.00001454@softhome.net> <442D4E38.9050508@tds.net> <courier.442D524B.00003B2D@softhome.net> <442D54DD.3070605@tds.net> <courier.442D58ED.00005905@softhome.net> <442D5B05.5020607@tds.net> <courier.442D5D09.00006BD9@softhome.net> <442D608E.9080102@tds.net> Message-ID: <courier.442D9A3E.000006E9@softhome.net> Kent Johnson writes: > jonasmg at softhome.net wrote: > >> List of states: >> http://en.wikipedia.org/wiki/U.S._state >> >> : soup = BeautifulSoup(html) >> : # Get the second table (list of states). >> : table = soup.first('table').findNext('table') >> : print table >> >> ... >> <tr> >> <td>WY</td> >> <td>Wyo.</td> >> <td><a href="/wiki/Wyoming" title="Wyoming">Wyoming</a></td> >> <td><a href="/wiki/Cheyenne%2C_Wyoming" title="Cheyenne, >> Wyoming">Cheyenne</a></td> >> <td><a href="/wiki/Cheyenne%2C_Wyoming" title="Cheyenne, >> Wyoming">Cheyenne</a></td> >> <td><a href="/wiki/Image:Flag_of_Wyoming.svg" class="image" title=""><img >> src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin >> g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" >> longdesc="/wiki/Image:Flag_of_Wyoming.svg" /></a></td> >> </tr> >> </table> >> >> Of each row (tr), I want to get the cells (td): 1,3,4 >> (postal,state,capital). But cells 3 and 4 have anchors. > > So dig into the cells and get the data from the anchor. > > cells = row('td') > cells[0].string > cells[2]('a').string > cells[3]('a').string > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor for row in table('tr'): cells = row('td') print cells[0] IndexError: list index out of range From kent37 at tds.net Fri Mar 31 23:39:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Mar 2006 16:39:10 -0500 Subject: [Tutor] Inverted Index Algorithm In-Reply-To: <b6131fdc0603311155i35496a91tb7a0b3e994c57eb4@mail.gmail.com> References: <b6131fdc0603311155i35496a91tb7a0b3e994c57eb4@mail.gmail.com> Message-ID: <442DA17E.9020800@tds.net> Steve Nelson wrote: > Hello All, > > I've been reading about "Inverted Indexing" - I'd like to try to write > something in Python that illustrates the concpet, as I've got to give > a presentation about it. > > Where would be a good place to start? Do you need help getting started with Python or with inverted indexing in particular? Kent