From idiot1 at netzero.net Mon Mar 1 00:37:35 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Mon Mar 1 00:37:24 2004 Subject: [Tutor] set the mode of a file Message-ID: <4042CC1F.5080203@netzero.net> I want to set the mode of a text file to 666. How do I do it? -- Respectfully, Kirk D Bailey Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From nick at javacat.f2s.com Mon Mar 1 03:27:01 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Mon Mar 1 03:27:12 2004 Subject: [Tutor] problem creating a subclass In-Reply-To: <003c01c3ff2a$13c4a6b0$6401a8c0@xp> References: <20040229212845.60368.qmail@web12403.mail.yahoo.com><404269AE.3040605@venix.com> <20040229225218.7025d0bd@phatbox.local> <003c01c3ff2a$13c4a6b0$6401a8c0@xp> Message-ID: <1078129621.4042f3d5f0733@webmail.freedom2surf.net> DOH! I see now, thankyou for the clarification. Nick. Quoting Alan Gauld <alan.gauld@blueyonder.co.uk>: > > > Maybe I'm missing something obvious here but I don't see how Chris' > > UList class is going to work at all. The class has no UList method, > so > > how is 'a = UList.UList(alist)' going to work ? > > Because this is in another file from ULIst(actually the >>> prompt). > So he imported the ULIst module and is accessing the ULIst class > within the UList module: > > import UList > L = UList.Ulist() # Ulist class within Ulist module > > Compare with: > > import sys > sys.exit() > > HTH > Alan G. > > ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From orbitz at ezabel.com Mon Mar 1 08:59:04 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Mar 1 09:00:44 2004 Subject: [Tutor] set the mode of a file In-Reply-To: <4042CC1F.5080203@netzero.net> References: <4042CC1F.5080203@netzero.net> Message-ID: <20040301085904.6f4948d0.orbitz@ezabel.com> http://www.python.org/doc/current/lib/os-file-dir.html Read the section on chmod On Mon, 01 Mar 2004 00:37:35 -0500 Kirk Bailey <idiot1@netzero.net> wrote: > I want to set the mode of a text file to 666. How do I do it? > > -- > > > Respectfully, > Kirk D Bailey > Pinellas county Florida USA > > think http://www.tinylist.org/ - $FREE$ software for liberty > +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service > | BOX | http://www.listville.net/ - $FREE$ list hosting services > +-------+ http://www.howlermonkey.net/ - $FREE$ email service > kniht http://www.sacredelectron.org/ - My personal SCREED pit > > (C)2004 Kirk D Bailey, all rights reserved- but ask! > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From vicki.stanfield at ROCHE.COM Mon Mar 1 09:35:04 2004 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Mon Mar 1 09:36:05 2004 Subject: [Tutor] accessing db data from pulldown on web page Message-ID: <CA3458C84C976E45B6372A6C14724C9F355EE6@ridmsem02.nala.roche.com> Is it possible to create a web site which contains a dropdown that searches a database based on what is selected from the dropdown? I have tried this in PHP and it doesn't seem possible (according to what "the experts" say). Here is what I want to do: I have a mysql database containing some information. I want to go to a web page (written in Python), select a name from the dropdown, and execute a SQL query based on the name selected. It sounds very simple to me, but I haven't done a lot of web work. --vicki -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040301/6573993a/attachment-0001.html From vicki.stanfield at ROCHE.COM Mon Mar 1 09:40:16 2004 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Mon Mar 1 09:42:34 2004 Subject: [Tutor] why are these two uses different? Message-ID: <CA3458C84C976E45B6372A6C14724C9F9E5B5A@ridmsem02.nala.roche.com> I have a project which includes a big if/elif. I select on the value selected from a pulldown menu of the dictionary values created thusly: self.combo=wxComboBox(self, 30, " ", wxPoint(wxALIGN_LEFT), wxDefaultSize, self.Dict.values(),wxCB_DROPDOWN) I match the selected value with a hexadecimal value like this: if command in ('1D','48','52','50','73','65','67'): <snip> #Get command from dictionary fcommand=self.Dict.keys()[self.Dict.values().index(command)] I have this in the dictionary: self.Dict=('\x78':'78','\x65':'65','\x60':'60',<SNIP>'\x1D':'1D') Each command triggers a whole sequence of serial writes and reads. This works fine. Now I want to create a section which allows me to do them individually. There are no timing issues since I am able to turn that off for the device I am writing to. But when I try to do this: do_it = wxMessageDialog(self,"do you want to continue?", "Send", wxYES_NO | wxICON_QUESTION) if do_it.ShowModal() == wxID_NO: do_it.Destroy() else: singledlg = wxTextEntryDialog (self, "Enter the hex value you'd like to send.", "Send Single", "Enter value here", wxOK | wxCANCEL) if singledlg.ShowModal() == wxID_OK: hexval = singledlg.GetValue() fcommand=self.Dict.keys()[self.Dict.values().index(hexval)] port.write(fcommand) <snip> If I type in the same string that is in the if statement, it sends the each digit of the hex value in hex itself. As in this example: hex 1D gets sent as 31 64. I have tried binascii.hexlify, but this didn't work. I have tried inputting the data with '1D', but that doesn't match the dictionary. Can I get a hint? I keep running into this same problem, so there must be a key piece of the pie that I'm still missing. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040301/c787291c/attachment.html From magnus at thinkware.se Mon Mar 1 10:54:32 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Mar 1 10:54:50 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gd2h5IGFyZSB0aGVzZSB0d28gdXNlcyBkaWZmZXJlbnQ/?= Message-ID: <think001_4043581212b46@webmail.thinkware.se> > Each command triggers a whole sequence of serial writes and reads. This > works fine. Now I want to create a section which allows me to do them > individually. I guess here is where the problem lies. I'm guessing that you have a loop somewhere in your code, where you loop over something like ['1d', 'ff', 'c2'] in the working case. Now, you loop over '1d' instead, and that's just the same as looping over ['1', 'd']. Make sure to feed your loop with a list or tuple instead, and I think it will work. ['1d'] or ('1d',) should work, but notice that ('1d') is *not* a tuple, just a string in parenthesis. E.g. >>> x = '1d' >>> for i in x: print i 1 d >>> for i in (x): print i 1 d >>> for i in (x,): print i 1d >>> for i in [x]: print i 1d -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From hcohen2 at comcast.net Mon Mar 1 09:53:41 2004 From: hcohen2 at comcast.net (hcohen2) Date: Mon Mar 1 10:57:40 2004 Subject: [Tutor] set the mode of a file In-Reply-To: <4042CC1F.5080203@netzero.net> References: <4042CC1F.5080203@netzero.net> Message-ID: <40434E75.9030801@comcast.net> Kirk Bailey wrote: > I want to set the mode of a text file to 666. How do I do it? > Assuming Linux/UNIX $ chmod 666 <file name> /* Means read write for file owner, group, public [i.e. any user] is that what you really want? */ Explanation: 4 - read, 2 - write and 1 - executable, I usually make mine 755 on this one user machine. From vicki.stanfield at ROCHE.COM Mon Mar 1 11:08:10 2004 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Mon Mar 1 11:10:49 2004 Subject: [Tutor] why are these two uses different? Message-ID: <CA3458C84C976E45B6372A6C14724C9F355EE7@ridmsem02.nala.roche.com> I had tried '1D'. Now I have tried to input [1D], ['1D'] but both generate the ValueError: list.index(x): x not in list when I hit the 'fcommand=self.Dict.keys()[self.Dict.values().index(hexval)]' line. It doesn't seem to matter how I enter the data into the wxTextEntryDialog, it doesn't match. Given the following dictionary excerpt: self.Dict=('\x78':'78','\x65':'65','\x60':'60',<SNIP>'\x1D':'1D') What needs to be entered into the wxTextEntryDialog to make it match this dictionary? --vicki -----Original Message----- From: Magnus Lycka [mailto:magnus@thinkware.se] Sent: Monday, March 01, 2004 10:55 AM To: Stanfield, Vicki {D167~Indianapolis}; tutor@python.org Subject: Re: [Tutor] why are these two uses different? > Each command triggers a whole sequence of serial writes and reads. > This works fine. Now I want to create a section which allows me to do > them individually. I guess here is where the problem lies. I'm guessing that you have a loop somewhere in your code, where you loop over something like ['1d', 'ff', 'c2'] in the working case. Now, you loop over '1d' instead, and that's just the same as looping over ['1', 'd']. Make sure to feed your loop with a list or tuple instead, and I think it will work. ['1d'] or ('1d',) should work, but notice that ('1d') is *not* a tuple, just a string in parenthesis. E.g. >>> x = '1d' >>> for i in x: print i 1 d >>> for i in (x): print i 1 d >>> for i in (x,): print i 1d >>> for i in [x]: print i 1d -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From vicki.stanfield at ROCHE.COM Mon Mar 1 15:13:21 2004 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Mon Mar 1 15:45:29 2004 Subject: [Tutor] RE: why are these two uses different? Message-ID: <CA3458C84C976E45B6372A6C14724C9F9E5B64@ridmsem02.nala.roche.com> Well, I fixed it, but I am not sure that I know what I did. When I went to break out the non-functional code to post it here, the subsection of code worked, so I went back to try the main program, and it works too! I don't know how that could be, but I'll take it. Thanks to everyone who tried to help me figure this one out. --vicki -----Original Message----- From: Stewart Midwinter [mailto:stewart@midtoad.homelinux.org] Sent: Monday, March 01, 2004 2:56 PM To: Stanfield, Vicki {D167~Indianapolis} Cc: tutor@python.org Subject: RE: why are these two uses different? Maybe I'm jumping into the middle of this, but why not post a more complete portion of your code, perhaps structured as a complete python modules, to make it easier for someone to run your code and see what the problem is? (or did you do that already, and I missed it?). One other comment, is it possible to split up the following line: fcommand=self.Dict.keys()[self.Dict.values().index(hexval)] into several components to facilitate debugging? -- Stewart Midwinter Calgary, Alberta stewart 'at' midwinter 'dot' ca Quoting "Stanfield, Vicki {D167~Indianapolis}" <vicki.stanfield@ROCHE.COM>: > I had tried '1D'. Now I have tried to input [1D], ['1D'] but both > generate the > > ValueError: list.index(x): x not in list > > when I hit the > 'fcommand=self.Dict.keys()[self.Dict.values().index(hexval)]' line. It > doesn't seem to matter how I enter the data into the > wxTextEntryDialog, it doesn't match. Given the following dictionary > excerpt: > > self.Dict=('\x78':'78','\x65':'65','\x60':'60',<SNIP>'\x1D':'1D') > > What needs to be entered into the wxTextEntryDialog to make it match > this dictionary? > > --vicki From stewart at midtoad.homelinux.org Mon Mar 1 14:56:07 2004 From: stewart at midtoad.homelinux.org (Stewart Midwinter) Date: Mon Mar 1 15:47:59 2004 Subject: [Tutor] RE: why are these two uses different? In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F355EE7@ridmsem02.nala.roche.com> References: <CA3458C84C976E45B6372A6C14724C9F355EE7@ridmsem02.nala.roche.com> Message-ID: <1078170967.4043955784645@midtoad.homelinux.org> Maybe I'm jumping into the middle of this, but why not post a more complete portion of your code, perhaps structured as a complete python modules, to make it easier for someone to run your code and see what the problem is? (or did you do that already, and I missed it?). One other comment, is it possible to split up the following line: fcommand=self.Dict.keys()[self.Dict.values().index(hexval)] into several components to facilitate debugging? -- Stewart Midwinter Calgary, Alberta stewart 'at' midwinter 'dot' ca Quoting "Stanfield, Vicki {D167~Indianapolis}" <vicki.stanfield@ROCHE.COM>: > I had tried '1D'. Now I have tried to input [1D], ['1D'] but both > generate the > > ValueError: list.index(x): x not in list > > when I hit the > 'fcommand=self.Dict.keys()[self.Dict.values().index(hexval)]' line. It > doesn't seem to matter how I enter the data into the wxTextEntryDialog, > it doesn't match. Given the following dictionary excerpt: > > self.Dict=('\x78':'78','\x65':'65','\x60':'60',<SNIP>'\x1D':'1D') > > What needs to be entered into the wxTextEntryDialog to make it match > this dictionary? > > --vicki From stewart at midtoad.homelinux.org Mon Mar 1 14:58:27 2004 From: stewart at midtoad.homelinux.org (Stewart Midwinter) Date: Mon Mar 1 15:48:04 2004 Subject: [Tutor] set the mode of a file In-Reply-To: <40434E75.9030801@comcast.net> References: <4042CC1F.5080203@netzero.net> <40434E75.9030801@comcast.net> Message-ID: <1078171107.404395e390962@midtoad.homelinux.org> If you were wanting to do it from within your Python program, you could use the os.system() command. If you want to check if the mode change was successful, you could monitor the return code from that command, by using os.popen2 or popen4, or even the new popen5 command. cheers -- Stewart Midwinter Calgary, Alberta stewart 'at' midwinter 'dot' ca Quoting hcohen2 <hcohen2@comcast.net>: > Kirk Bailey wrote: > > > I want to set the mode of a text file to 666. How do I do it? > > > Assuming Linux/UNIX > > $ chmod 666 <file name> /* Means read write for file owner, group, > public [i.e. any user] is that what you really want? */ > > Explanation: 4 - read, 2 - write and 1 - executable, I usually make mine > 755 on this one user machine. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From magnus at thinkware.se Mon Mar 1 13:21:12 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Mar 1 15:49:29 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gYWNjZXNzaW5nIGRiIGRhdGEgZnJvbSBwdWxsZG93biBvbiB3ZWIgcGFnZQ==?= Message-ID: <think001_40435d0b6f7b3@webmail.thinkware.se> Vicki wrote: > Is it possible to create a web site which contains a dropdown that > searches a database based on what is selected from the dropdown? I have > tried this in PHP and it doesn't seem possible (according to what "the > experts" say). Here is what I want to do: > > I have a mysql database containing some information. I want to go to a > web page (written in Python), select a name from the dropdown, and > execute a SQL query based on the name selected. It sounds very simple to > me, but I haven't done a lot of web work. This is a completely normal thing to do. I'm not exactly sure what you mean by "a web page (written in Python)", since web pages are typically written in HTML or XHTML. How you create the web page containing the form with the dropdown doesn't matter. It can be created from a Python program, or written in notepad. The relevant thing is the (presumably) Python code that receives the call from the HTML form where the dropdown resides. This can be a simple CGI script, or developed in something more elaborate such as Zope or CherryPy. See http://www.python.org/cgi-bin/moinmoin/WebProgramming for plenty of choices. The typical thing is that the CGI script (or whatever) is called through the action connected to the SUBMIT button on the form, but you can also use JavaScript to make it call your script as soon as you select a row in the dropdown. If you want something PHP-like, with Python embedded in the HMTL, there are several options available, such as PSP. But you still need to handle the database call in a script outside the page. Any code embedded in the web page, be it PHP or PSP is executed on the server side before the web page is sent to the browser. If you want code actually running on the client side accessing your database, I guess need to do it in Java (or Jython). If you are in control of the web server, you could for instance try CherryPy, which I think is fairly neat. If you are not in control of the server, it's more tricky... But here is a pure Python solution based on my hack http://www.thinkware.se/cgi-bin/thinki.cgi/PyNetworkCheck It uses adodbapi, but I'm sure you can swap in the MySql module instead, and you need to change the content of global variable "tables". Run the script, feed it a database connect string, wait for it to display that it's serving HTTP, and surf to http://localhost:8000/ import BaseHTTPServer from StringIO import StringIO import shutil import adodbapi html = """<html><head><title>Hello!</title><h/head> <body><H1>Hello!</H1> <form action="http://localhost:8000/" method="GET"> <SELECT name="table"> %s </SELECT> <INPUT type="submit" value="Send"> </form> <pre> %s </pre> </body></html> """ tables = ['TABLE1','TABLE2'] dsn = raw_input('DSN? ') def get_data(table): cn = adodbapi.connect(dsn) cr = cn.cursor() cr.execute('SELECT * FROM %s' % table) rows = cr.fetchall() return "\n".join(["|".join([" %s " % col for col in row]) for row in rows]).encode('latin-1') class MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): """Serve a GET request.""" f = self.send_head() if f: f = StringIO() options = "\n".join(["<option>%s</option>" % x for x in tables]) table = self.path.split('=')[-1] if table in tables: data = get_data(table) else: data = 'Please select a table' f.write(html % (options, data)) f.seek(0) self.copyfile(f, self.wfile) f.close() return f def do_HEAD(self): """Serve a HEAD request.""" f = self.send_head() if f: f.close() def send_head(self): path = self.path self.send_response(200) self.send_header("Content-type", 'text/plain') self.end_headers() f = StringIO() f.write("A test %s\n" % path) f.seek(0) return f def copyfile(self, source, outputfile): shutil.copyfileobj(source, outputfile) def main(HandlerClass = MyHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass) if __name__ == '__main__': main() -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From pete at freesome.com Mon Mar 1 17:31:33 2004 From: pete at freesome.com (PetesK) Date: Mon Mar 1 18:26:56 2004 Subject: [Tutor] Regular Expresions Message-ID: <4043B9C5.805@freesome.com> 1st post... hi! :-) I am trying to rip the href's from html documents, I've found a regular expression to do this, but it's for .net, and seems to use a slightly different format from python. The RegEx is in two parts the first part was href\s*=\s*\"(?<url>[^\"]*)\" Ive found that Python needs a 'P' before the label, i.e, href\s*=\s*\"(?P<url>[^\"]*)\" However the full regEx is, href\s*=\s*(?:(?:\"(?<url>[^\"]*)\")|(?<url>[^\s*] )) Which uses a 'non-capturing group' to combine the two regEx cases (in this case quotes or no quotes). I would be very grateful if someone could point me in the right direction on how to achieve the same effect in Python, as its complaining about the groups being defined twice rather than merging them into one 'url' group... Thanks From orbitz at ezabel.com Mon Mar 1 18:31:15 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Mar 1 18:31:33 2004 Subject: [Tutor] set the mode of a file In-Reply-To: <1078171107.404395e390962@midtoad.homelinux.org> References: <4042CC1F.5080203@netzero.net> <40434E75.9030801@comcast.net> <1078171107.404395e390962@midtoad.homelinux.org> Message-ID: <20040301183115.5683cedf.orbitz@ezabel.com> Why not just use os.chmod? On Mon, 01 Mar 2004 12:58:27 -0700 Stewart Midwinter <stewart@midtoad.homelinux.org> wrote: > If you were wanting to do it from within your Python program, you could use > the os.system() command. If you want to check if the mode change was > successful, you could monitor the return code from that command, by using > os.popen2 or popen4, or even the new popen5 command. > > cheers > > -- > Stewart Midwinter > Calgary, Alberta > stewart 'at' midwinter 'dot' ca > > > Quoting hcohen2 <hcohen2@comcast.net>: > > > Kirk Bailey wrote: > > > > > I want to set the mode of a text file to 666. How do I do it? > > > > > Assuming Linux/UNIX > > > > $ chmod 666 <file name> /* Means read write for file owner, group, > > public [i.e. any user] is that what you really want? */ > > > > Explanation: 4 - read, 2 - write and 1 - executable, I usually make mine > > 755 on this one user machine. > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From stewart at midtoad.homelinux.org Mon Mar 1 18:50:43 2004 From: stewart at midtoad.homelinux.org (Stewart Midwinter) Date: Mon Mar 1 18:38:58 2004 Subject: [Tutor] set the mode of a file In-Reply-To: <20040301183115.5683cedf.orbitz@ezabel.com> References: <4042CC1F.5080203@netzero.net> <40434E75.9030801@comcast.net> <1078171107.404395e390962@midtoad.homelinux.org> <20040301183115.5683cedf.orbitz@ezabel.com> Message-ID: <1078185043.4043cc530f311@midtoad.homelinux.org> Even better, and more to the point! Quoting orbitz@ezabel.com: > Why not just use os.chmod? From sigurd at 12move.de Mon Mar 1 21:03:54 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Mar 1 21:08:09 2004 Subject: [Tutor] Regular Expresions In-Reply-To: <4043B9C5.805@freesome.com> (PetesK's message of "Mon, 01 Mar 2004 22:31:33 +0000") References: <4043B9C5.805@freesome.com> Message-ID: <m3r7wc115y.fsf@hamster.pflaesterer.de> On 1 Mar 2004, PetesK <- pete@freesome.com wrote: > I am trying to rip the href's from html documents, I've found a > regular expression to do this, but it's for .net, and seems to use a > slightly different format from python. I won't go further here but your regepx won't find all hrefs in a document (e.g. href could be written as HREF (HTML 3.2) or some one used single quotes (unlikely but it may happen)). Consider using HTMlParser to extract elements. If you need help with it post here. But now to your regexp. [...] > Ive found that Python needs a 'P' before the label, i.e, > href\s*=\s*\"(?P<url>[^\"]*)\" Right. > However the full regEx is, > href\s*=\s*(?:(?:\"(?<url>[^\"]*)\")|(?<url>[^\s*] )) > Which uses a 'non-capturing group' to combine the two regEx cases (in IMO there is one group too much. > this case quotes or no quotes). I would be very grateful if someone > could point me in the right direction on how to achieve the same > effect in Python, as its complaining about the groups being defined > twice rather than merging them into one 'url' group... If you wanted it to write like that you *have* to use two different names for the groups (which makes sense since if you wanted to use numbers for the groups you would write \1 and for the first respective \2 for the second group also you know that only one of them can match. The module reference is very clear about that: ,------------------------------------------------------------------------. | ``(?P<NAME>...)'' | | Similar to regular parentheses, but the substring matched by the | | group is accessible via the symbolic group name NAME. Group names | | must be valid Python identifiers, and each group name must be | | defined only once within a regular expression. A symbolic group | | is also a numbered group, just as if the group were not named. So | | the group named 'id' in the example above can also be referenced | | as the numbered group 1. | | | `------------------------------------------------------------------------? So you could write your regexp as: reg = re.compile(r'href\s*=\s*(?P<url>"[^"]*"|\S*(?:\s|$))') Now you need only one named group (and it's written a bit more nicely and a bit more robust than your solution). But: as I said above; that regexp won't find all hrefs; so either think about a more robust solution or use the parser module. Karl -- Please do *not* send copies of replies to me. I read the list From guillermo.fernandez at epfl.ch Tue Mar 2 07:15:36 2004 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Tue Mar 2 07:15:43 2004 Subject: [Tutor] unittest problem Message-ID: <40447AE8.6000304@epfl.ch> hi, I think the mail did not arrive to the mailing list, so I send it again .Sorry if I send it twice... I'm doing a little test of unittest module. I'm having some problems making it run. I guess is more a problem of OO design that unittest problem though... ? have a test.py program with the following code: import os import unittest import begohandler import test_begohandler =>import test_statemachine import test_syslogparse class Base(unittest.TestCase): def setUp(self): if os.path.isfile('test.db'): begohandler.do_opendb('test.db') else: print 'No database to open! Create it first' sys.exit(1) def tearDown(self): begohandler.do_closedb() pass if __name__ == '__main__': runner=unittest.TextTestRunner() runner.run(unittest.makeSuite(test_syslogparse.syslogparseTest,'test')) runner.run(unittest.makeSuite(test_begohandler.begohandlerTest,'test')) => runner.run(unittest.makeSuite(test_statemachine.statemachineTest,'test')) When launching my program with the => lines commented, no problem. When no lines are commented, I obtain the following error: $ python test.py Traceback (most recent call last): File "test.py", line 5, in ? import test_begohandler File "/home/cfernand/bego/code/lib/test_begohandler.py", line 4, in ? import test File "/home/cfernand/bego/code/lib/test.py", line 6, in ? import test_statemachine File "/home/cfernand/bego/code/lib/test_statemachine.py", line 6, in ? class statemachineTest(test.Base): AttributeError: 'module' object has no attribute 'Base' I have veryfied again and again the error, but I'm unable to find what it is. I've also looked possible differences between test_begohandler.py and test_statemachine.py that could lead to an error, but I haven't finded any difference between both. Thanks a lot for any hint that could help me solve this problem. Enclosed are the other test_* files. Guille ________________________________________________________ test_statemachine.py: import unittest import statemachine import test class statemachineTest(test.Base): def testget_macsessions(self): statemachine.get_macsessions(['%']) def testget_apsessions(self): statemachine.get_apsessions(['%']) def testget_roamsessions(self): statemachine.get_roamsessions(['%']) def testget_macroamstats(self): statemachine.get_macroamstats(['%']) def testget_aproamstats(self): statemachine.get_aproamstats(['%']) def testget_maxmacapday(self): statemachine.get_maxmacapday(['%']) def testget_maxmacap(self): statemachine.get_maxmacap(['%']) if __name__ == '__main__': unittest.main() ________________________________________________________ test_begohandler.py: import unittest import begohandler import test class begohandlerTest(test.Base): def testget_apmaclist(self): begohandler.get_apmaclist(['%']) def testget_macaplist(self): begohandler.get_macaplist(['%']) def testget_aphistory(self): begohandler.get_aphistory(['%']) def testget_machistory(self): begohandler.get_machistory(['%']) def testget_macs(self): begohandler.get_macs() def testget_apnames(self): begohandler.get_apnames() def testget_msgstats(self): begohandler.get_msgstats() def testget_macmsgstats(self): begohandler.get_macmsgstats(['%']) def testget_apmsgstats(self): begohandler.get_apmsgstats(['%']) def testget_macsday(self): begohandler.get_macsday() def testget_daysmac(self): begohandler.get_daysmac() def testget_daysmacstat(self): begohandler.get_daysmacstat() def testget_apmacday(self): begohandler.get_apmacday() def testget_apdaymacs(self): begohandler.get_apdaymacs() if __name__ == '__main__': unittest.main() ________________________________________________________ test_syslogparse.py: import os import sys import unittest import syslogparse class syslogparseTest(unittest.TestCase): # first and second added to names in order to force to execute # first the parsefiledb and then the appendfiledb def testfirstdo_parsefiledb(self): try: os.remove('test.db') print 'test.db removed' except: pass if not os.path.isfile('./test.txt') or not os.path.isfile('./testappend.txt'): print 'guille' sys.exit(0) syslogparse.run('test.txt','test.db') def testseconddo_appendfiledb(self): syslogparse.run('testappend.txt','test.db',True) if __name__ == '__main__': unittest.main() ________________________________________________________ From elh at outreachnetworks.com Tue Mar 2 11:30:43 2004 From: elh at outreachnetworks.com (Eric L. Howard) Date: Tue Mar 2 11:30:52 2004 Subject: [Tutor] did I lose the value of record? Message-ID: <20040302163031.GD1754@outreachnetworks.com> I have a file that contains two columns delimited by ":". I can open the file for reading, re.search through the lines for a particular record and string.split the record into two parts which are assigned to two different variables. It's the third assignment that's causing the script to fall over on it's face [the pwd.getpwnam] In the interpreter - this works: >>> >>> record = "elhtest:elh" >>> userhome = pwd.getpwnam(string.split(record, ":")[1])[5] >>> print userhome /home/elh However - this doesn't appear to work: #!/usr/bin/env python import re, string, pwd listingsfile = open("listings","r") for record in listingsfile.readlines(): if re.search("elhtest", record): listing = string.split(record, ":")[0] owner = string.split(record, ":")[1] ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] print "The listing we're found is %s" % listing print "The owner for this listing is %s" % owner print "The owner's home dir is %s" % ownerhome listingsfile.close() I get the following: Traceback (most recent call last): File "./sa_setup.py", line 10, in ? ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] KeyError: 'getpwnam(): name not found' TIA... ~elh -- Eric L. Howard e l h @ o u t r e a c h n e t w o r k s . c o m ------------------------------------------------------------------------ www.OutreachNetworks.com 313.297.9900 ------------------------------------------------------------------------ JabberID: elh@jabber.org Advocate of the Theocratic Rule From sigurd at 12move.de Tue Mar 2 11:41:44 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Mar 2 11:47:18 2004 Subject: [Tutor] Regular Expresions In-Reply-To: <m3r7wc115y.fsf@hamster.pflaesterer.de> (Karl =?iso-8859-1?q?Pfl=E4sterer's?= message of "Tue, 02 Mar 2004 03:03:54 +0100") References: <4043B9C5.805@freesome.com> <m3r7wc115y.fsf@hamster.pflaesterer.de> Message-ID: <m365dnmelw.fsf@hamster.pflaesterer.de> On 2 Mar 2004, Karl Pfl?sterer <- sigurd@12move.de wrote: [...] > So you could write your regexp as: > reg = re.compile(r'href\s*=\s*(?P<url>"[^"]*"|\S*(?:\s|$))') I made a mistake here. reg = re.compile(r'href\s*=\s*"?(?P<url>[^"\s]*)', re.I) should be better. Reading the whole file with file(filename).readlines(), join() the result and test the result with findall() is probably the fastest solution (unless you have realy big files or scarce memory). Like that you might find string as href which weren't written as one; e.g. if someone wrote: <p> An href is written like href="foo" </p> you would find that also. For that a parser is better. The disadvantage of a parser might be that it doesn't play well with invalid documents. As I found that interesting I played a bit and wrote a solution which is a bit safer than a plain regexp albeit it is no real parser; so it might also find hrefs which are no real ones (but very unlikely since that could only happen in <script> or <style> sections (or perhaps in text after the </html> tag; maybe in comments (I'm not sure at the moment)) def href_vals (itr): actions = { 'start' : re.compile(r'.*?<\s*a(?P<href1>)?'), 'href1' : re.compile(r'[^>]*?href\s*(?P<href2>)'), 'href2' : re.compile(r'=\s*"?(?P<href3>)'), 'href3' : re.compile(r'(?P<start>[^\s"]*)') } state = 'start' for line in itr: pos = 0 while 1: m = actions[state].match(line, pos) if not m: break pos = m.end() state = m.groupdict().keys()[0] if state == 'start': yield m.groupdict()[state] This is a little state machine which searches first for an opening `<a' tag, then for the href= in it and then yields the text after the href= as value. If that is new to you (since you wrote you first start with Python); Python has something which is called generators. They are used at places where you iterate over objects like: for foo in bar: ... Perhaps you know it for files. But you can also write your own generator functions; you recognize them by the keyword `yield'. What happens in the above function? It iterates over an object and tries some regexps in turn on the lines of the object (let's think of it as a file). The regexps are values in a dictionray; the keys are the states. It starts with the regexp which is the value of the state 'start'. If no match is found a new line is taken from the file and again that regexp gets tried. It always starts looking at position 0. But what happens if a match succeds? The new state is the name of the group in the regexp. So you can see that after 'start' 'href' will be tried. The new start position will be the end of the previous match. So we don't scan pieces twice. If after state 'href' we had a match, the new state will gain be 'start' but now we will have a href. That is the point were if state == 'start': yield m.groupdict()[state] will be true and the generator yields a value. Then it tries again to find a match untill the file is completely scanned. To use it you could write: f = open('test.html') for url in href_values(f): print url f.close() You have to decide yourself if you really need somethinfg like that or if a simple regexp is enough; anyway it was fun to test it. Karl -- Please do *not* send copies of replies to me. I read the list From Janssen at rz.uni-frankfurt.de Tue Mar 2 11:55:28 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Tue Mar 2 11:55:38 2004 Subject: [Tutor] did I lose the value of record? In-Reply-To: <20040302163031.GD1754@outreachnetworks.com> References: <20040302163031.GD1754@outreachnetworks.com> Message-ID: <Pine.A41.4.56.0403021746540.100412@hermes-22.rz.uni-frankfurt.de> On Tue, 2 Mar 2004, Eric L. Howard wrote: [getpwnam with teststring] > >>> record = "elhtest:elh" > >>> userhome = pwd.getpwnam(string.split(record, ":")[1])[5] > >>> print userhome > /home/elh [now for real] > #!/usr/bin/env python > > import re, string, pwd > > listingsfile = open("listings","r") > for record in listingsfile.readlines(): > if re.search("elhtest", record): > listing = string.split(record, ":")[0] > owner = string.split(record, ":")[1] > ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] > print "The listing we're found is %s" % listing > print "The owner for this listing is %s" % owner > print "The owner's home dir is %s" % ownerhome > listingsfile.close() > > I get the following: > > Traceback (most recent call last): > File "./sa_setup.py", line 10, in ? > ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] > KeyError: 'getpwnam(): name not found' You very likly have found a user not in password database. Do: try: ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] except KeyError: print "ERROR", string.split(record, ":") this way you a) find out the bad name b) catch the error. BTW: you should do string.split(record, ":") only once. Create a temp variable: spl = string.split(record, ":") # spl like split owner = spl[0] or directly: owner, home = string.split(record, ":") Cleaner code, faster Michael From sigurd at 12move.de Tue Mar 2 12:04:44 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Mar 2 12:07:48 2004 Subject: [Tutor] did I lose the value of record? In-Reply-To: <20040302163031.GD1754@outreachnetworks.com> (Eric L. Howard's message of "Tue, 2 Mar 2004 11:30:43 -0500") References: <20040302163031.GD1754@outreachnetworks.com> Message-ID: <m3smgrkwr6.fsf@hamster.pflaesterer.de> On 2 Mar 2004, Eric L. Howard <- elh@outreachnetworks.com wrote: > I have a file that contains two columns delimited by ":". > I can open the file for reading, re.search through the lines for a > particular record and string.split the record into two parts which are > assigned to two different variables. It's the third assignment that's > causing the script to fall over on it's face [the pwd.getpwnam] > In the interpreter - this works: >>>> record = "elhtest:elh" >>>> userhome = pwd.getpwnam(string.split(record, ":")[1])[5] >>>> print userhome > /home/elh > However - this doesn't appear to work: > #!/usr/bin/env python > import re, string, pwd > listingsfile = open("listings","r") > for record in listingsfile.readlines(): > if re.search("elhtest", record): > listing = string.split(record, ":")[0] > owner = string.split(record, ":")[1] What is the value of owner here? [...] > I get the following: > Traceback (most recent call last): > File "./sa_setup.py", line 10, in ? > ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] > KeyError: 'getpwnam(): name not found' That means it can't find the name in your passwd file. Look at the value of owner and look in your passwd file. Karl -- Please do *not* send copies of replies to me. I read the list From elh at outreachnetworks.com Tue Mar 2 12:17:57 2004 From: elh at outreachnetworks.com (Eric L. Howard) Date: Tue Mar 2 12:18:02 2004 Subject: [Tutor] did I lose the value of record? In-Reply-To: <m3smgrkwr6.fsf@hamster.pflaesterer.de> References: <20040302163031.GD1754@outreachnetworks.com> <m3smgrkwr6.fsf@hamster.pflaesterer.de> Message-ID: <20040302171756.GE1754@outreachnetworks.com> At a certain time, now past [Mar.02.2004-06:04:44PM +0100], sigurd@12move.de spake thusly: > On 2 Mar 2004, Eric L. Howard <- elh@outreachnetworks.com wrote: > > > I have a file that contains two columns delimited by ":". > > > I can open the file for reading, re.search through the lines for a > > particular record and string.split the record into two parts which are > > assigned to two different variables. It's the third assignment that's > > causing the script to fall over on it's face [the pwd.getpwnam] > > > In the interpreter - this works: > > > >>>> record = "elhtest:elh" > >>>> userhome = pwd.getpwnam(string.split(record, ":")[1])[5] > >>>> print userhome > > /home/elh > > > However - this doesn't appear to work: > > > #!/usr/bin/env python > > > import re, string, pwd > > > listingsfile = open("listings","r") > > for record in listingsfile.readlines(): > > if re.search("elhtest", record): > > listing = string.split(record, ":")[0] > > owner = string.split(record, ":")[1] > > What is the value of owner here? it's supposed to be elh...did I ever mention that I hate '\n'? > [...] > > > I get the following: > > > Traceback (most recent call last): > > File "./sa_setup.py", line 10, in ? > > ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] > > KeyError: 'getpwnam(): name not found' > > That means it can't find the name in your passwd file. Look at the > value of owner and look in your passwd file. Yah...I looked closer this time. The username 'elh' exists in the passwd file...but the username 'elh\n' doesn't. Prepending string.strip() to string.split cleans up the values and provides the expected output. ~elh -- Eric L. Howard e l h @ o u t r e a c h n e t w o r k s . c o m ------------------------------------------------------------------------ www.OutreachNetworks.com 313.297.9900 ------------------------------------------------------------------------ JabberID: elh@jabber.org Advocate of the Theocratic Rule From elh at outreachnetworks.com Tue Mar 2 12:22:04 2004 From: elh at outreachnetworks.com (Eric L. Howard) Date: Tue Mar 2 12:22:09 2004 Subject: [Tutor] did I lose the value of record? In-Reply-To: <Pine.A41.4.56.0403021746540.100412@hermes-22.rz.uni-frankfurt.de> References: <20040302163031.GD1754@outreachnetworks.com> <Pine.A41.4.56.0403021746540.100412@hermes-22.rz.uni-frankfurt.de> Message-ID: <20040302172203.GF1754@outreachnetworks.com> At a certain time, now past [Mar.02.2004-05:55:28PM +0100], Janssen@rz.uni-frankfurt.de spake thusly: > On Tue, 2 Mar 2004, Eric L. Howard wrote: > > [getpwnam with teststring] > > >>> record = "elhtest:elh" > > >>> userhome = pwd.getpwnam(string.split(record, ":")[1])[5] > > >>> print userhome > > /home/elh > > [now for real] > > #!/usr/bin/env python > > > > import re, string, pwd > > > > listingsfile = open("listings","r") > > for record in listingsfile.readlines(): > > if re.search("elhtest", record): > > listing = string.split(record, ":")[0] > > owner = string.split(record, ":")[1] > > ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] > > print "The listing we're found is %s" % listing > > print "The owner for this listing is %s" % owner > > print "The owner's home dir is %s" % ownerhome > > listingsfile.close() > > > > I get the following: > > > > Traceback (most recent call last): > > File "./sa_setup.py", line 10, in ? > > ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] > > KeyError: 'getpwnam(): name not found' > > You very likly have found a user not in password database. Do: > > try: ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5] > except KeyError: print "ERROR", string.split(record, ":") I didn't even have to get this far...as soon as I saw the try->except...I looked at the data again [I knew for a fact that the username should be in the passwd file] and saw the source of my problem. > this way you a) find out the bad name b) catch the error. > > BTW: you should do string.split(record, ":") only once. Create a temp > variable: > spl = string.split(record, ":") # spl like split > owner = spl[0] > > or directly: > owner, home = string.split(record, ":") > > Cleaner code, faster Cool...thanx. ~elh -- Eric L. Howard e l h @ o u t r e a c h n e t w o r k s . c o m ------------------------------------------------------------------------ www.OutreachNetworks.com 313.297.9900 ------------------------------------------------------------------------ JabberID: elh@jabber.org Advocate of the Theocratic Rule From sigurd at 12move.de Tue Mar 2 15:15:16 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Mar 2 15:21:10 2004 Subject: [PetesK] Re: [Tutor] Regular Expresions Message-ID: <m365dnko52.fsf@hamster.pflaesterer.de> Hi I forward this e-mail from Pete since I think it was intented for the list. -------------- next part -------------- An embedded message was scrubbed... From: PetesK <pete@freesome.com> Subject: Re: [Tutor] Regular Expresions Date: Tue, 02 Mar 2004 18:59:42 +0000 Size: 2254 Url: http://mail.python.org/pipermail/tutor/attachments/20040302/5d5cc4da/attachment.mht -------------- next part -------------- Karl -- Roses are red, Violets are blue, I'm schizophrenic... And I am too. From dyoo at hkn.eecs.berkeley.edu Tue Mar 2 15:49:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 2 15:49:12 2004 Subject: [Tutor] unittest problem In-Reply-To: <40447AE8.6000304@epfl.ch> Message-ID: <Pine.LNX.4.44.0403021240480.10810-100000@hkn.eecs.berkeley.edu> > When launching my program with the => lines commented, no problem. When no > lines are commented, I obtain the following error: > $ python test.py > Traceback (most recent call last): > File "test.py", line 5, in ? > import test_begohandler > File "/home/cfernand/bego/code/lib/test_begohandler.py", line 4, in ? > import test > File "/home/cfernand/bego/code/lib/test.py", line 6, in ? > import test_statemachine > File "/home/cfernand/bego/code/lib/test_statemachine.py", line 6, in ? > class statemachineTest(test.Base): > AttributeError: 'module' object has no attribute 'Base' Python is trying to say that, in the statement that starts off with: class statemachineTest(test.Base): it has no idea what 'test.Base' means. The same error should also apply to begohandlerTest, since it too uses 'test.Base'. ... What is the 'test' module? Ah! There's a "circular dependency" issue here! Your test module contains the following: ### import begohandler import test_begohandler import test_statemachine import test_syslogparse class Base(unittest.TestCase): ... [code cut] ### Conceptually, this is saying that the 'test' module depends on those four modules. But test_begohandler and test_statemachine themselves depend on 'test'. This is called a 'circular dependency', and is not usually a good idea. The easiest way to fix it is to break the circularity. I see that test_begohandler and test_statemachine only care about test.Base, so you can split off test.Base off into a separate module --- call it 'base.py'. Then test_begohandler and test_statemachine only need to import 'base', not 'test', and so we avoid the circularity issue. Does this make sense? Good luck to you! From pete at freesome.com Tue Mar 2 19:31:19 2004 From: pete at freesome.com (PetesK) Date: Tue Mar 2 19:31:17 2004 Subject: [PetesK] Re: [Tutor] Regular Expresions In-Reply-To: <m365dnko52.fsf@hamster.pflaesterer.de> References: <m365dnko52.fsf@hamster.pflaesterer.de> Message-ID: <40452757.8090800@freesome.com> Karl Pfl?sterer wrote: >Hi I forward this e-mail from Pete since I think it was intented for the >list. > > > > > ------------------------------------------------------------------------ > > Subject: > Re: [Tutor] Regular Expresions > From: > PetesK <pete@freesome.com> > Date: > Tue, 02 Mar 2004 18:59:42 +0000 > To: > Karl Pfl?sterer <sigurd@12move.de> > > To: > Karl Pfl?sterer <sigurd@12move.de> > > >Karl Pfl?sterer wrote: > > > >>On 2 Mar 2004, Karl Pfl?sterer <- sigurd@12move.de wrote: >> >> >> >> >> > > > >>You have to decide yourself if you really need somethinfg like that or >>if a simple regexp is enough; anyway it was fun to test it. >> >> >> >> Karl >> >> >> > >Wow, thanks for some great tips there Karl, I had not come accross the >yield ketword yet, but can see its a useful one. I had also missed the >HTMLparser module, so again thanks for bringing that to my attention. >Im not sure yet which method I will use, as this is just for a personal >project to get me up to speed with the language. The HTMLparser mod, >looks interesting, but also rather daunting from my quick skim read of >the docs... I like your second function, and it looks like I can just >drop a vaiant over my exisitng code. I'll let you know... ;-) > >While Im writing, may i recommend to the list a useful little utitlity I >stumbled accross at http://kodos.sourceforge.net/ its a python base >regex debugger. > >Again, thanks for the help. > >Pete > > > > <blush> ignoring your sig-line with style </blush> From guillermo.fernandez at epfl.ch Wed Mar 3 07:28:02 2004 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Wed Mar 3 07:28:09 2004 Subject: [Tutor] unittest problem In-Reply-To: <Pine.LNX.4.44.0403021240480.10810-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0403021240480.10810-100000@hkn.eecs.berkeley.edu> Message-ID: <4045CF52.8040805@epfl.ch> hi, > Conceptually, this is saying that the 'test' module depends on those four > modules. But test_begohandler and test_statemachine themselves depend on > 'test'. This is called a 'circular dependency', and is not usually a good > idea. > The easiest way to fix it is to break the circularity. I see that > test_begohandler and test_statemachine only care about test.Base, so you > can split off test.Base off into a separate module --- call it 'base.py'. > Then test_begohandler and test_statemachine only need to import 'base', > not 'test', and so we avoid the circularity issue. > Does this make sense? Good luck to you! Makes lot's of sens. Thanks! I solved it in a slightly different way though, by moving the imports that where doing the circular reference later (after the definition of Base class) so they would knew what test.Base was. Thanks a lot! Guille From pxlpluker at cfl.rr.com Thu Mar 4 14:15:20 2004 From: pxlpluker at cfl.rr.com (fred) Date: Thu Mar 4 14:20:52 2004 Subject: [Tutor] Sightly off topic - download file name Message-ID: <loom.20040304T201416-564@post.gmane.org> I what to dynamically create a page that has download links to file stored on disk. the part i don't know how to do (or if its possible) is to a different name appear in the browser DL window. i.e. I want the files stored with a random string but when being DL to have real name show in File Save dialog. Fred From hsteiger at comcast.net Thu Mar 4 23:44:38 2004 From: hsteiger at comcast.net (Henry Steigerwaldt) Date: Thu Mar 4 23:44:34 2004 Subject: [Tutor] Question on installing Tcl/Tk Message-ID: <001101c4026c$91d33cc0$0201a8c0@eagle> To All: Quite some time ago, I installed Tcl/Tk 8.0 for windows without a problem. It installed pretty much by itself with little or no interaction on my part. I think I executed a file and it did the rest. Several days ago, I downloaded the following two files to install Tcl/Tk 8.45: tcl845-src.zip tk845-src.zip After I unzipped the files, I did not find anything obvious to select and execute to install either of these programs. So, what are the procedures (or location on the Web for installation instructions) to install these programs? I must have missed something on the Tcl Developer Xchange Web site where if I remember correctly I downloaded the files from. By the way, I see now there is an 8.46 version. Thanks for any response. Henry Steigerwaldt Hermitage, TN From glaine at free.fr Fri Mar 5 08:47:45 2004 From: glaine at free.fr (glaine@free.fr) Date: Fri Mar 5 08:47:49 2004 Subject: [Tutor] Start Message-ID: <1078494465.4048850161b12@imp2-q.free.fr> Hello I'm new in python. I try to make a script which save the win registry each morning after the win98's running. I have a lot of problems to concretize my idea about the moment when my script start. How to do to run automatically my script each morning after the win98's running I will accept any suggestions or ideas. I found some elements with win32events and handle, but I don't understand very well what handle means in python. Is there anybody to explain me ? Thank all for your help. Save Registry.py import _ winreg t=file('c:\\windows\\bureau\\toto.txt','w') p=_winreg.SaveKey(Keys x, Keys y,'t') From rodolfo49 at hotmail.com Fri Mar 5 14:48:25 2004 From: rodolfo49 at hotmail.com (Rodolfo Rosario) Date: Fri Mar 5 15:31:54 2004 Subject: [Tutor] RE: tcl/tk 8.45 installation Message-ID: <BAY1-F167K2v9eHYR5E000021e1@hotmail.com> Henry Steigerwaldt, you downloaded the SOURCES, it means you have to COMPILE those files...the .zip you downloaded don`t bring any executable files(.exe)...just try to get the installation files(.exe or something like it...) that`s what i think...:) rodux >From: tutor-request@python.org >Reply-To: tutor@python.org >To: tutor@python.org >Subject: Tutor Digest, Vol 1, Issue 2643 >Date: Fri, 05 Mar 2004 12:03:36 -0500 >MIME-Version: 1.0 >Received: from mc12-f20.hotmail.com ([65.54.167.156]) by >mc12-s21.hotmail.com with Microsoft SMTPSVC(5.0.2195.6824); Fri, 5 Mar 2004 >09:04:48 -0800 >Received: from mail.python.org ([12.155.117.29]) by mc12-f20.hotmail.com >with Microsoft SMTPSVC(5.0.2195.6824); Fri, 5 Mar 2004 09:03:52 -0800 >Received: from localhost.localdomain ([127.0.0.1] helo=mail.python.org)by >mail.python.org with esmtp (Exim 4.22)id 1AzIjY-0004sY-Ry; Fri, 05 Mar 2004 >12:03:36 -0500 >X-Message-Info: VggZFA0O609FKL16Pw+OVQGTiZHSkFHXBlLduQUQld8= >X-BeenThere: tutor@python.org >X-Mailman-Version: 2.1.5b1 >Precedence: list >List-Id: Discussion for learning programming with Python <tutor.python.org> >List-Unsubscribe: ><http://mail.python.org/mailman/listinfo/tutor>,<mailto:tutor-request@python.org?subject=unsubscribe> >List-Archive: <http://mail.python.org/pipermail/tutor> >List-Post: <mailto:tutor@python.org> >List-Help: <mailto:tutor-request@python.org?subject=help> >List-Subscribe: ><http://mail.python.org/mailman/listinfo/tutor>,<mailto:tutor-request@python.org?subject=subscribe> >Errors-To: tutor-bounces@python.org >Message-Id: <E1AzIjY-0004sY-Ry@mail.python.org> >Return-Path: tutor-bounces@python.org >X-OriginalArrivalTime: 05 Mar 2004 17:03:52.0879 (UTC) >FILETIME=[D63B6BF0:01C402D3] > >Send Tutor mailing list submissions to > tutor@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@python.org > >You can reach the person managing the list at > tutor-owner@python.org > >When replying, please edit your Subject line so it is more specific >than "Re: Contents of Tutor digest..." > > >Today's Topics: > > 1. Sightly off topic - download file name (fred) > 2. Question on installing Tcl/Tk (Henry Steigerwaldt) > 3. Start (glaine@free.fr) > > >---------------------------------------------------------------------- > >Message: 1 >Date: Thu, 4 Mar 2004 19:15:20 +0000 (UTC) >From: fred <pxlpluker@cfl.rr.com> >Subject: [Tutor] Sightly off topic - download file name >To: tutor@python.org >Message-ID: <loom.20040304T201416-564@post.gmane.org> >Content-Type: text/plain; charset=us-ascii > >I what to dynamically create a page that has download links to file >stored on disk. >the part i don't know how to do (or if its possible) is to a different >name appear in the browser DL window. >i.e. I want the files stored with a random string but when being DL to >have real name show in File Save dialog. > > >Fred > > > > >------------------------------ > >Message: 2 >Date: Thu, 4 Mar 2004 22:44:38 -0600 >From: "Henry Steigerwaldt" <hsteiger@comcast.net> >Subject: [Tutor] Question on installing Tcl/Tk >To: <tutor@python.org> >Message-ID: <001101c4026c$91d33cc0$0201a8c0@eagle> >Content-Type: text/plain; charset="iso-8859-1" > >To All: > >Quite some time ago, I installed Tcl/Tk 8.0 for windows without >a problem. It installed pretty much by itself with little or no >interaction on my part. I think I executed a file and it did the >rest. > >Several days ago, I downloaded the following two files to >install Tcl/Tk 8.45: > >tcl845-src.zip >tk845-src.zip > >After I unzipped the files, I did not find anything obvious to >select and execute to install either of these programs. > >So, what are the procedures (or location on the Web >for installation instructions) to install these programs? > >I must have missed something on the Tcl Developer Xchange >Web site where if I remember correctly I downloaded the >files from. By the way, I see now there is an 8.46 version. > >Thanks for any response. > >Henry Steigerwaldt >Hermitage, TN > > > > > >------------------------------ > >Message: 3 >Date: Fri, 5 Mar 2004 14:47:45 +0100 >From: glaine@free.fr >Subject: [Tutor] Start >To: tutor@python.org >Message-ID: <1078494465.4048850161b12@imp2-q.free.fr> >Content-Type: text/plain; charset=ISO-8859-1 > >Hello >I'm new in python. I try to make a script >which save the win registry each morning >after the win98's running. I have a lot of >problems to concretize my idea about the moment >when my script start. How to do to run automatically >my script each morning after the win98's running >I will accept any suggestions or ideas. I found >some elements with win32events and handle, but I don't >understand very well what handle means in python. >Is there anybody to explain >me ? Thank all for your help. >Save Registry.py >import _ winreg >t=file('c:\\windows\\bureau\\toto.txt','w') >p=_winreg.SaveKey(Keys x, Keys y,'t') > > > > >------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > >End of Tutor Digest, Vol 1, Issue 2643 >************************************** _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From cspears2002 at yahoo.com Fri Mar 5 17:47:59 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri Mar 5 17:48:08 2004 Subject: [Tutor] removing duplicates Message-ID: <20040305224759.33606.qmail@web12404.mail.yahoo.com> I have made more progress on my probelm. Here is the code so far: import UserList class UList(UserList.UserList): def __init__(self, initlist=None): UserList.UserList.__init__(self, initlist) def __add__(self, other): for s in range(len(self)): if self[s] not in other: if isinstance(other, UList): return self.__class__(self.data + other.data) elif isinstance(other, type(self.data)): return self.__class__(self.data + other) else: return self.__class__(self.data + list(other)) else: print "Found duplicate %s" %self[s] del self[s] When I first tested the script out, everything seemed to work fine: >>> import UList >>> list= [1,2,3] >>> a = UList.UList(list) >>> a [1, 2, 3] >>> list1 = [1,4,5] >>> b = UList.UList(list1) >>> b [1, 4, 5] >>> a + b Found duplicate 1 [2, 3, 1, 4, 5] However, I have been discovering situations where the script breaks. For example, in cases where there are more than one duplicate: >>> list2 = [1,2,4] >>> c = UList.UList(list2) >>> c [1, 2, 4] >>> b [1, 4, 5] >>> c + b Found duplicate 1 Found duplicate 4 Traceback (most recent call last): File "<pyshell#12>", line 1, in -toplevel- c + b File "C:\Documents and Settings\Christstopher Spears\My Documents\python\UList.py", line 9, in __add__ if self[s] not in other: File "C:\Python23\lib\UserList.py", line 28, in __getitem__ def __getitem__(self, i): return self.data[i] IndexError: list index out of range >>> d [8, 9] >>> f = [8,8,10] >>> d + f Found duplicate 8 Traceback (most recent call last): File "<pyshell#23>", line 1, in -toplevel- d + f File "C:\Documents and Settings\Christstopher Spears\My Documents\python\UList.py", line 9, in __add__ if self[s] not in other: File "C:\Python23\lib\UserList.py", line 28, in __getitem__ def __getitem__(self, i): return self.data[i] IndexError: list index out of range I am feeling a little silly because one would think that an IndexError would be easy to solve. However, I have no idea what is going on! Any hints or suggestions?! -Chris From darnold02 at sprynet.com Fri Mar 5 20:18:20 2004 From: darnold02 at sprynet.com (don arnold) Date: Fri Mar 5 20:25:44 2004 Subject: [Tutor] removing duplicates References: <20040305224759.33606.qmail@web12404.mail.yahoo.com> Message-ID: <13be01c40319$e6cce570$b611ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "Christopher Spears" <cspears2002@yahoo.com> To: <tutor@python.org> Sent: Friday, March 05, 2004 4:47 PM Subject: [Tutor] removing duplicates > I have made more progress on my probelm. Here is the > code so far: > > import UserList > > class UList(UserList.UserList): > def __init__(self, initlist=None): > UserList.UserList.__init__(self, initlist) > > def __add__(self, other): > for s in range(len(self)): > if self[s] not in other: > if isinstance(other, UList): > return self.__class__(self.data + > other.data) > elif isinstance(other, > type(self.data)): > return self.__class__(self.data + > other) > else: > return self.__class__(self.data + > list(other)) > else: > print "Found duplicate %s" %self[s] > del self[s] > > When I first tested the script out, everything seemed > to work fine: > >>> import UList > >>> list= [1,2,3] > >>> a = UList.UList(list) > >>> a > [1, 2, 3] > >>> list1 = [1,4,5] > >>> b = UList.UList(list1) > >>> b > [1, 4, 5] > >>> a + b > Found duplicate 1 > [2, 3, 1, 4, 5] > > However, I have been discovering situations where the > script breaks. For example, in cases where there are > more than one duplicate: > >>> list2 = [1,2,4] > >>> c = UList.UList(list2) > >>> c > [1, 2, 4] > >>> b > [1, 4, 5] > >>> c + b > Found duplicate 1 > Found duplicate 4 > Traceback (most recent call last): > File "<pyshell#12>", line 1, in -toplevel- > c + b > File "C:\Documents and Settings\Christstopher > Spears\My Documents\python\UList.py", line 9, in > __add__ > if self[s] not in other: > File "C:\Python23\lib\UserList.py", line 28, in > __getitem__ > def __getitem__(self, i): return self.data[i] > IndexError: list index out of range > > <snip> This is because you're deleting items from the list as you iterate over it. When you delete the 1 at index 0, everything shifts to the left and your length is now 2 (with items at indices 0 and 1). Unfortunately, s was based on your original length, so it's eventually going to try to access self.data[2], which no longer exists. The _usual_ way to deal with this is to iterate over a copy of your list, deleting corresponding items from the original. However, you have other problems here: your loop actually returns as soon as the first non-duplicate character is encountered. This means you won't find a dup unless it's the first item in your original list: >>> a = UList.UList([1,2,3]) >>> b = UList.UList([6,7,3,2]) >>> a+b [1, 2, 3, 6, 7, 3, 2] I don't think this is what you're after. Since you've asked for hints, I won't rewrite the code for you, but I suggest that you restructure the function so that it only returns after all characters have been processed. HTH, Don From jakieabraham at yahoo.com Sat Mar 6 01:50:16 2004 From: jakieabraham at yahoo.com (Jacob Abraham) Date: Sat Mar 6 01:50:25 2004 Subject: [Tutor] import statement Message-ID: <20040306065016.66539.qmail@web11208.mail.yahoo.com> Dear Tutors, Is it possible use the import statement between two files. eg #filea.py from fileb import * #fileb.py from filea import * #NameError: global name 'MyClass' is not defined Thanks, Jacob Abraham __________________________________ Do you Yahoo!? Yahoo! Search - Find what you’re looking for faster http://search.yahoo.com From marilyn at deliberate.com Sat Mar 6 14:12:38 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Mar 6 14:12:43 2004 Subject: [Tutor] Tkinter Message-ID: <Pine.LNX.4.44.0403061108360.11161-100000@Kuna> Hi again, I'm a bit confused about the top-level processing in Tkinter. 2 of my books start with tk=Tk() and build inside tk. 1 book starts with o = MyClass() where MyClass(Frame) and builds inside itself. But when I self.destoy() a frame gets left behind. Then I read that there's a toplevel widget. What's Tk()? I know there's some understanding that I'm missing. Can anyone help me? Marilyn Davis From pythontutor at venix.com Sat Mar 6 18:23:55 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Mar 6 18:23:58 2004 Subject: [Tutor] import statement In-Reply-To: <20040306065016.66539.qmail@web11208.mail.yahoo.com> References: <20040306065016.66539.qmail@web11208.mail.yahoo.com> Message-ID: <404A5D8B.1010705@venix.com> I do not think you can get that working using the from <module> import * syntax. It is a bad idea in any case. It is not worth the grief you go through to make it work and keep it working. Use a common file that has the pieces that filea and fileb depend on - or simply combine filea and fileb into one module. Jacob Abraham wrote: > Dear Tutors, > Is it possible use the import statement between two > files. > > eg > #filea.py > from fileb import * > > #fileb.py > from filea import * > > #NameError: global name 'MyClass' is not defined > > Thanks, > Jacob Abraham > > > __________________________________ > Do you Yahoo!? > Yahoo! Search - Find what you?re looking for faster > http://search.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From klappnase at freenet.de Sat Mar 6 19:54:51 2004 From: klappnase at freenet.de (Michael Lange) Date: Sat Mar 6 20:04:21 2004 Subject: [Tutor] Tkinter In-Reply-To: <Pine.LNX.4.44.0403061108360.11161-100000@Kuna> References: <Pine.LNX.4.44.0403061108360.11161-100000@Kuna> Message-ID: <20040307015451.0941c9fb.klappnase@freenet.de> On Sat, 6 Mar 2004 11:12:38 -0800 (PST) Marilyn Davis <marilyn@deliberate.com> wrote: > Hi again, > > I'm a bit confused about the top-level processing in Tkinter. > > 2 of my books start with tk=Tk() and build inside tk. > > 1 book starts with o = MyClass() where MyClass(Frame) and > builds inside itself. But when I self.destoy() a frame gets > left behind. > > Then I read that there's a toplevel widget. What's Tk()? > > I know there's some understanding that I'm missing. > > Can anyone help me? > > Marilyn Davis > Hi, Marilyn, Tk() is the application's main (or root) window; any Tkinter app needs a Tk() window as parent for all the other widgets. That's why you have to call the mainloop() for your Tk() window to keep the whole thing alive. The toplevel widget (called with the Toplevel() command) is a window that looks just like the Tk() window, but is in fact a child of the mainwindow. You don't need to call a mainloop() on Toplevel() windows. When you close your mainwindow the children Toplevel windows are closed as well, but not vice versa. Toplevel windows are used for things like dialog boxes or in complex guis where you need more than one window. About the example with MyClass(Frame) I can just guess; maybe the code looked like this: root = Tk() o = MyClass(root)#Frame that contains some other widgets o.pack() Now when you destroy the MyClass instance an empty window should be left (the Tk() was not destroyed) which might look like a window with a frame inside (an empty gray rectangle). I hope this helps Michael From idiot1 at netzero.net Sat Mar 6 20:16:43 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Mar 6 20:16:03 2004 Subject: [Tutor] world's shortest wiki Message-ID: <404A77FB.1040506@netzero.net> just 11 lines, python obsfercation par excellance... Courtesy of Mr. Sean B Palmer, at http://infomesh.net/2003/wypy Here is the code, ALL the code: #!/usr/bin/python import re,os,cgi;d,h=os.listdir('.'),'<a href=wy?';p,e,g,s=tuple(map(cgi.parse( ).get,'pegs'));f=lambda s:reduce(lambda s,(r,q):re.sub('(?m)'+r,q,s),(('\r','') ,('([A-Z][a-z]+){2,}',lambda m:('%s'+h+'e=%s>?</a>',h+'g=%s>%s</a>')[m.group(0) in d]%((m.group(0),)*2)),('^{{$','<ul>'),('^# ','<li>'),('^}}$','</ul>'),('(ht\ tp:[^<>"\s]+)',h[:-3]+r'\1>\1</a>'),('\n\n','<p>')),s);o,g=lambda y:(y in d and cgi.escape(open(y).read()))or'',(g or p and[open(p[0].strip('./'),'w').write(s[ 0])or p[0]]or[0])[0];print'Content-Type:text/html\n\n'+(s and', '.join([f(n)for n in d if s[0]in o(n)])or'')+(e and'<form action=wy?p=%s method=POST><textarea\ name=s rows=8 cols=50>%s</textarea><input type=submit></form>'%(e[0],o(e[0])) or'')+(g and'<h1>%ss=%s>%s</a>,%se=%s>edit</a></h1>'%(h,g,g,h,g)+f(o(g))or'') I never said it was well annotated, merely 11 lines long... -- Respectfully, Kirk D Bailey Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From marilyn at deliberate.com Sat Mar 6 20:25:37 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Mar 6 20:25:43 2004 Subject: [Tutor] Tkinter In-Reply-To: <20040307015451.0941c9fb.klappnase@freenet.de> Message-ID: <Pine.LNX.4.44.0403061709180.11161-100000@Kuna> On Sun, 7 Mar 2004, Michael Lange wrote: > On Sat, 6 Mar 2004 11:12:38 -0800 (PST) > Marilyn Davis <marilyn@deliberate.com> wrote: > > > Hi again, > > > > I'm a bit confused about the top-level processing in Tkinter. > > > > 2 of my books start with tk=Tk() and build inside tk. > > > > 1 book starts with o = MyClass() where MyClass(Frame) and > > builds inside itself. But when I self.destoy() a frame gets > > left behind. > > > > Then I read that there's a toplevel widget. What's Tk()? > > > > I know there's some understanding that I'm missing. > > > > Can anyone help me? > > > > Marilyn Davis > > > Hi, Marilyn, > > Tk() is the application's main (or root) window; any Tkinter app > needs a Tk() window as parent for all the other widgets. > > That's why you have to call the mainloop() for your Tk() window to > keep the whole thing alive. > > The toplevel widget (called with the Toplevel() command) is a window > that looks just like the Tk() window, but is in fact a child of the > mainwindow. You don't need to call a mainloop() on Toplevel() windows. And you don't call mainloop on any "slaves"? Is 'slaves' the right word? I see 'master' and I see 'children'. Maybe 'slaves' is politically incorrect -- but technically correct? I don't like 'children' because it can be confused with inheritance hierarchies. > > When you close your mainwindow the children Toplevel windows are > closed as well, but not vice versa. But it's slaves are. Right. (I've been studying all day) > > Toplevel windows are used for things like dialog boxes or in complex > guis where you need more than one window. So Toplevel windows are good for having several windows up and active simultaneously. The user moves the mouse to get from one toplevel window to the other. > > About the example with MyClass(Frame) I can just guess; maybe the > code looked like this: > > root = Tk() > o = MyClass(root)#Frame that contains some other widgets > o.pack() Nope, surprisingly, the examples from the Deitel book look like: # Fig. 11.5: fig11_05.py # Canvas paint program. from Tkinter import * class PaintBox( Frame ): """Demonstrate drawing on a Canvas""" def __init__( self, title='A simple paint program'): """Create Canvas and bind paint method to mouse dragging""" Frame.__init__( self ) self.pack( expand = YES, fill = BOTH ) self.master.title( title) self.master.geometry( "300x150" ) self.message = Label( self, text = "Drag the mouse to draw" ) self.message.pack( side = BOTTOM ) # create Canvas component self.myCanvas = Canvas( self ) self.myCanvas.pack( expand = YES, fill = BOTH ) # bind mouse dragging event to Canvas self.myCanvas.bind( "<B1-Motion>", self.paint ) def paint( self, event ): """Create an oval of radius 4 around the mouse position""" x1, y1 = ( event.x - 4 ), ( event.y - 4 ) x2, y2 = ( event.x + 4 ), ( event.y + 4 ) self.myCanvas.create_oval( x1, y1, x2, y2, fill = "black" ) def main(): PaintBox().mainloop() if __name__ == "__main__": main() -------- > Now when you destroy the MyClass instance an empty window should be > left (the Tk() was not destroyed) which might look like a window > with a frame inside (an empty gray rectangle). Yes. This happened. But when I called myclass.master.destroy(), it all went away. So I'm thinking that if you instantiate Frame without a master, it automatically makes a Tk object for you to be your master? Or a Toplevel object for you? Probably Tk? (It's cool, the slave generates the master. Maybe that's politically correct.) I don't think I ever got it to call my __del__ method though. I wonder what is the relationship between destroy() and __del__(). Maybe I have to look at the source code some time. > > I hope this helps Yes yes. Thank you so much. Anything more you can tell me? Marilyn > > Michael > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From idiot1 at netzero.net Sat Mar 6 21:41:23 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Mar 6 21:41:20 2004 Subject: [Tutor] Wikinehesa Message-ID: <404A8BD3.2000902@netzero.net> Wikinehesa now does ordered and unordered lists, and has a minor bug with the editor fixed. The wiki is at: http://www.tinylist.org/ and the archive is now available there as: http://www.tinylist.org/wikinehesa.1.4.0.tar.gz And a hearty hiho, and off to watch Enterprise! -- Respectfully, Kirk D Bailey Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From klappnase at freenet.de Sat Mar 6 21:47:58 2004 From: klappnase at freenet.de (Michael Lange) Date: Sat Mar 6 21:57:28 2004 Subject: [Tutor] Tkinter In-Reply-To: <Pine.LNX.4.44.0403061709180.11161-100000@Kuna> References: <20040307015451.0941c9fb.klappnase@freenet.de> <Pine.LNX.4.44.0403061709180.11161-100000@Kuna> Message-ID: <20040307034758.36efa58b.klappnase@freenet.de> On Sat, 6 Mar 2004 17:25:37 -0800 (PST) Marilyn Davis <marilyn@deliberate.com> wrote: > > > Tk() is the application's main (or root) window; any Tkinter app > > needs a Tk() window as parent for all the other widgets. > > > > That's why you have to call the mainloop() for your Tk() window to > > keep the whole thing alive. > > > > The toplevel widget (called with the Toplevel() command) is a window > > that looks just like the Tk() window, but is in fact a child of the > > mainwindow. You don't need to call a mainloop() on Toplevel() windows. > > And you don't call mainloop on any "slaves"? Right - never. > > Is 'slaves' the right word? I see 'master' and I see 'children'. > Maybe 'slaves' is politically incorrect -- but technically correct? I > don't like 'children' because it can be confused with inheritance > hierarchies. Most people say "parent" and "children" I think; for political correctness reasons maybe we should use "president" and "citizens" ;-) > > About the example with MyClass(Frame) I can just guess; maybe the > > code looked like this: > > > > root = Tk() > > o = MyClass(root)#Frame that contains some other widgets > > o.pack() > > Nope, surprisingly, the examples from the Deitel book look like: > > # Fig. 11.5: fig11_05.py > # Canvas paint program. > > from Tkinter import * > > class PaintBox( Frame ): > """Demonstrate drawing on a Canvas""" > > def __init__( self, title='A simple paint program'): > """Create Canvas and bind paint method to mouse dragging""" > > Frame.__init__( self ) > self.pack( expand = YES, fill = BOTH ) > self.master.title( title) > self.master.geometry( "300x150" ) > > self.message = Label( self, text = "Drag the mouse to draw" ) > self.message.pack( side = BOTTOM ) > > # create Canvas component > self.myCanvas = Canvas( self ) > self.myCanvas.pack( expand = YES, fill = BOTH ) > > # bind mouse dragging event to Canvas > self.myCanvas.bind( "<B1-Motion>", self.paint ) > > def paint( self, event ): > """Create an oval of radius 4 around the mouse position""" > > x1, y1 = ( event.x - 4 ), ( event.y - 4 ) > x2, y2 = ( event.x + 4 ), ( event.y + 4 ) > self.myCanvas.create_oval( x1, y1, x2, y2, fill = "black" ) > > def main(): > PaintBox().mainloop() > > if __name__ == "__main__": > main() > > -------- > > > Now when you destroy the MyClass instance an empty window should be > > left (the Tk() was not destroyed) which might look like a window > > with a frame inside (an empty gray rectangle). > > Yes. This happened. But when I called myclass.master.destroy(), it > all went away. So I'm thinking that if you instantiate Frame without > a master, it automatically makes a Tk object for you to be your > master? Or a Toplevel object for you? Probably Tk? > Seems like we find the magic for this in Tkinter.py, line 1717 ff.(Python2.2.1): class BaseWidget(Misc): """Internal class.""" def _setup(self, master, cnf): """Internal function. Sets up information about children.""" if _support_default_root: global _default_root if not master: if not _default_root: _default_root = Tk() master = _default_root > (It's cool, the slave generates the master. Maybe that's politically > correct.) I guess somehow they always do so. However, viewed from this aspect I think I should better drop the "president" / "citizen" suggestion. How about "employer" and "employees" ? > > I don't think I ever got it to call my __del__ method though. I wonder > what is the relationship between destroy() and __del__(). Maybe I have > to look at the source code some time. > I did so, Tkinter.py line 1760 ff. shows BaseWidget.destroy(): def destroy(self): """Destroy this and all descendants widgets.""" for c in self.children.values(): c.destroy() if self.master.children.has_key(self._name): del self.master.children[self._name] self.tk.call('destroy', self._w) Misc.destroy(self) Complicated! Base.Widget.destroy() calls Misc.destroy() (Tkinter.py line 282 ff.): def destroy(self): """Internal function. Delete all Tcl commands created for this widget in the Tcl interpreter.""" if self._tclCommands is not None: for name in self._tclCommands: #print '- Tkinter: deleted command', name self.tk.deletecommand(name) self._tclCommands = None However, most people seem to prefer the quit() method to close Tkinter apps anyway, destroy() only to get rid of some "employees" (mostly Toplevels I guess) Now that I have already Tkinter.py opened, I see this is a method of the Misc class, too: def quit(self): """Quit the Tcl interpreter. All widgets will be destroyed.""" self.tk.quit() I am not that kind of expert, but I think I read something about the reasons for quit() to be the preferred method, unfortunately I must admit I forgot about the details. I hope this helped a little more Michael From cspears2002 at yahoo.com Sun Mar 7 01:04:30 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sun Mar 7 01:04:33 2004 Subject: [Tutor] string problems Message-ID: <20040307060430.85266.qmail@web12403.mail.yahoo.com> I'm trying to create a new class that will keep duplicate values from being used in extend. Here is the code: import UserList class UList(UserList.UserList): def __init__(self, initlist=None): UserList.UserList.__init__(self, initlist) self.copy = self self.duplicates = [] #Here is code that modifies __add__. def __add__(self, other): blahblahblah... #Here is code that modifies extend. def extend(self, other): for s in range(len(self.copy)): if self.copy[s] in other: print "Found duplicate" self.duplicates.append(self[s]) print self.duplicates for d in range(len(self.duplicates)): self.remove(self.duplicates[d]) if isinstance(other, UList): self.data.extend(other.data) else: self.data.extend(other) self.duplicates = [] On first glance, the code seems to work: >>> a.extend([2,3,4]) Found duplicate [2] Found duplicate [2, 3] >>> a [1, 2, 3, 4] However, things fall apart when I try to use a string that is not in a list: >>> a.extend("string") Traceback (most recent call last): File "<pyshell#84>", line 1, in -toplevel- a.extend("string") File "C:\Documents and Settings\Christstopher Spears\My Documents\python\UList.py", line 24, in extend if self.copy[s] in other: TypeError: 'in <string>' requires string as left operand I tried to catch the exception, and this is the curious result: >>> import UList >>> a = UList.UList([1,2,3]) >>> a [1, 2, 3] >>> a.extend("string") Put string in a list >>> a [1, 2, 3, 's', 't', 'r', 'i', 'n', 'g'] Anyway, it's late, and I'm burnt out. Any suggestions would be appreciated! -Chris From sigurd at 12move.de Sun Mar 7 11:47:11 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Sun Mar 7 11:52:21 2004 Subject: [Tutor] string problems In-Reply-To: <20040307060430.85266.qmail@web12403.mail.yahoo.com> (Christopher Spears's message of "Sat, 6 Mar 2004 22:04:30 -0800 (PST)") References: <20040307060430.85266.qmail@web12403.mail.yahoo.com> Message-ID: <m3fzckd40r.fsf@hamster.pflaesterer.de> On 7 Mar 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > class UList(UserList.UserList): > def __init__(self, initlist=None): > UserList.UserList.__init__(self, initlist) > self.copy = self > self.duplicates = [] > #Here is code that modifies __add__. > def __add__(self, other): > blahblahblah... > #Here is code that modifies extend. > def extend(self, other): > for s in range(len(self.copy)): > if self.copy[s] in other: > print "Found duplicate" > self.duplicates.append(self[s]) > print self.duplicates > for d in range(len(self.duplicates)): > self.remove(self.duplicates[d]) > if isinstance(other, UList): > self.data.extend(other.data) > else: > self.data.extend(other) > self.duplicates = [] > On first glance, the code seems to work: [...] > However, things fall apart when I try to use a string > that is not in a list: >>>> a.extend("string") > Traceback (most recent call last): > File "<pyshell#84>", line 1, in -toplevel- > a.extend("string") > File "C:\Documents and Settings\Christstopher > Spears\My Documents\python\UList.py", line 24, in > extend > if self.copy[s] in other: > TypeError: 'in <string>' requires string as left > operand Did you read what the method extend does? ,---- | Help on built-in function extend: | | extend(...) | L.extend(iterable) -- extend list by appending elements from the iterable `---- So it takes its argument as an iterable and appends the returned elements to the list. If you have: >>> L = [1,2,3] >>> L.extend('string') >>> L [1, 2, 3, 's', 't', 'r', 'i', 'n', 'g'] >>> So what happens: you iterate over the length of an copy of the list; then look what happens, when the index is 0. The element is 1 (a number) and you try to compute `1 in 'string'. Let's see what Python says: >>> 1 in 'string' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'in <string>' requires string as left operand Now you see where your error came from. I don't see a reason, why your extend code should be so complicated or why it should create such a lot of copies. Since we know that the argument to extend is an iterable it's safe to iterate over that argument and not over the list. Then you can look for a duplicate and remove it in the same loop. The need for a separate list to hold the duplicate values vanishes also. def extend(self, other): for s in other: if s in self: print 'Found duplicate' self.remove(s) print s if isinstance(other, UList): self.data.extend(other.data) else: self.data.extend(other) Karl -- Please do *not* send copies of replies to me. I read the list From bgailer at alum.rpi.edu Sun Mar 7 13:20:03 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Mar 7 13:18:37 2004 Subject: [Tutor] Start In-Reply-To: <1078494465.4048850161b12@imp2-q.free.fr> References: <1078494465.4048850161b12@imp2-q.free.fr> Message-ID: <6.0.0.22.0.20040307111656.0407f308@mail.mric.net> At 06:47 AM 3/5/2004, glaine@free.fr wrote: >Hello >I'm new in python. I try to make a script >which save the win registry each morning >after the win98's running. I have a lot of >problems to concretize my idea about the moment >when my script start. How to do to run automatically >my script each morning after the win98's running Right-click on the Start Button and pick Explore. This should put you in the Start Menu Folder. Under this you should see the Programs Folder. Expand this and you should see the Startup Folder. Put your Python program (or a shortcut to it) in the Startup Folder. >I will accept any suggestions or ideas. I found >some elements with win32events and handle, but I don't >understand very well what handle means in python. >Is there anybody to explain >me ? Thank all for your help. >Save Registry.py >import _ winreg >t=file('c:\\windows\\bureau\\toto.txt','w') >p=_winreg.SaveKey(Keys x, Keys y,'t') > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From alan.gauld at blueyonder.co.uk Sun Mar 7 14:04:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 7 14:04:17 2004 Subject: [Tutor] Tkinter References: <Pine.LNX.4.44.0403061108360.11161-100000@Kuna> Message-ID: <004c01c40477$07e39070$6401a8c0@xp> > I'm a bit confused about the top-level processing in Tkinter. > > 2 of my books start with tk=Tk() and build inside tk. THis is normal wisdom when working with TRk - you create a top level widget which forms the paremt of all others and traditionally call it tk (or sometimes top). > 1 book starts with o = MyClass() where MyClass(Frame) and > builds inside itself. This is because Tk (the underlying toolkit) takes an object based approach to widgets whereas Tkinter is a wholly object oriented version. But Tkinter allows you to use either form of GUI building style - either procedural using objects or OOP. The MyClass(Frame) style is using takes the pure OOP approach. > But when I self.destoy() a frame gets left behind. I suspect that's because you aren't passing the parent onto MyClass constructor? tk = Tk() app = MyClass(tk) So when you destroy the MyClass instance the Tk() window remains? But thats a guess... > Then I read that there's a toplevel widget. What's Tk()? Its the top level widget! :-) HTH, Alan G. From alan.gauld at blueyonder.co.uk Sun Mar 7 14:09:44 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 7 14:09:26 2004 Subject: [Tutor] Tkinter References: <Pine.LNX.4.44.0403061108360.11161-100000@Kuna> <20040307015451.0941c9fb.klappnase@freenet.de> Message-ID: <005101c40477$c0041990$6401a8c0@xp> > The toplevel widget (called with the Toplevel() command) is > a window that looks just like the Tk() window, Oops I misread this bit in the original posters mail. I thought it was *the Top Level* widget she was asking about(note the spacing) not the Toplevel widget which is used to create modeless dialogs etc... Apologies for any confusion. Alan G. From alan.gauld at blueyonder.co.uk Sun Mar 7 14:20:25 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 7 14:20:09 2004 Subject: [Tutor] Tkinter References: <Pine.LNX.4.44.0403061709180.11161-100000@Kuna> Message-ID: <005601c40479$3e770d40$6401a8c0@xp> > And you don't call mainloop on any "slaves"? No, you only call mainloop() once in any Tkinter application. > Is 'slaves' the right word? I see 'master' and I see 'children'. > Maybe 'slaves' is politically incorrect -- but technically correct? Its normally referred to as parent/child. Its a containment relationship and its explicit in that you can do a dir() on any widget instance and you'll see the parent and child variables in there. You can even examine them. Whan a widget draws itself it sends draw() to each of its children... Similarly when a window kills itself it sends kill to each child (which sends kill to each of its children etc...) > don't like 'children' because it can be confused with inheritance > hierarchies. I tend to use "subclasses" for that... > > Toplevel windows are used for things like dialog boxes or in complex > > guis where you need more than one window. > > So Toplevel windows are good for having several windows up and active > simultaneously. The user moves the mouse to get from one toplevel > window to the other. Specifically where the new window is non modal. If you just want to pop up a temporary modal window you don;t need top level. A good example is a Find dialog in a text editor - they tend to be long lived so you can do repeat finds etc. So they tend to come from Toplevel. > Nope, surprisingly, the examples from the Deitel book look like: > > class PaintBox( Frame ): > """Demonstrate drawing on a Canvas""" > > def __init__( self, title='A simple paint program'): > """Create Canvas and bind paint method to mouse dragging""" This is a bit naughty. Good Tk style says the first argument(after self) should be a Parent. The Parent should be passed on to the Frame. > > Frame.__init__( self, parent ) As I've done here. > def paint( self, event ): > """Create an oval of radius 4 around the mouse position""" > > > def main(): tk = Tk() > PaintBox(tk).mainloop() Would sort it out. > (It's cool, the slave generates the master. Maybe that's politically > correct.) No its a bad idea. Especially if you try to reuse your widgets in another program. Start with a top level widget and pass it in to the children. Then Tkinter will look after things for you. > what is the relationship between destroy() and __del__(). Maybe I have > to look at the source code some time. ISTR destroy() kills the window on screen whereas __del__() is the destructor called when the object gets garbage collected. Alan G. From cybersamurai at terra.com.br Sun Mar 7 18:47:40 2004 From: cybersamurai at terra.com.br (Luiz Siqueira) Date: Sun Mar 7 18:41:34 2004 Subject: [Tutor] Difference between object and instances Message-ID: <404BB49C.4090001@terra.com.br> What is the real difference between objects and instances? From apqle75 at hotmail.com Thu Mar 4 20:40:36 2004 From: apqle75 at hotmail.com (APQ LE) Date: Sun Mar 7 18:47:24 2004 Subject: [Tutor] Help Message-ID: <LAW11-F118KP7Ie8tlM00042c1b@hotmail.com> Hi, I've installed python 2.3.2 on my Win 2K. I try to run a simple script, but I keep getting this message 'Python' is not recognized as an internal or external command, operable program or batch file'. what do I need to do? _________________________________________________________________ Fast. Reliable. Get MSN 9 Dial-up - 3 months for the price of 1! (Limited-time Offer) http://click.atdmt.com/AVE/go/onm00200361ave/direct/01/ From cspears2002 at yahoo.com Thu Mar 4 19:01:25 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sun Mar 7 18:48:09 2004 Subject: [Tutor] problem update Message-ID: <20040305000125.95166.qmail@web12406.mail.yahoo.com> I've been hacking away at my problem, and I have made some progress. Here is the original problem: Using the UserList module, create a class called Ulist, and override the __add__, append, and extend methods so that duplicate values will not be added to the list by any of these operations. Here is the script so far: import UserList class UList(UserList.UserList): def __init__(self, initlist=None): UserList.UserList.__init__(self, initlist) def __add__(self, other): for s in range(len(self)): if self[s] not in other: if isinstance(other, UList): return self.__class__(self.data + other.data) elif isinstance(other, type(self.data)): return self.__class__(self.data + other) else: return self.__class__(self.data + list(other)) else: print "Found duplicate %s" %self[s] When I run the code, I get the following results: >>> import UList >>> list = [1,2,3] >>> list1 = [1,4,5] >>> a = UList.UList(list) >>> b = UList.UList(list1) >>> a [1, 2, 3] >>> b [1, 4, 5] >>> a + b Found duplicate 1 [1, 2, 3, 1, 4, 5] My code is only working halfway. The script detects a duplicate but adds the duplicates in the lists anyway, so the next step is to modify the script so that duplicates will be eliminated. Any hints? My guess is that 1 is not added in beginning of the loop because the script detects it. Therefore, 1 must be added when 2 is being compared against b. -Chris From helena_b2001 at yahoo.com Fri Mar 5 20:13:32 2004 From: helena_b2001 at yahoo.com (helena bhaska) Date: Sun Mar 7 18:48:36 2004 Subject: [Tutor] cgi script -closing a browser In-Reply-To: <Pine.LNX.4.44.0402231046370.32753-100000@hkn.eecs.berkeley.edu> Message-ID: <20040306011332.2822.qmail@web20421.mail.yahoo.com> Hi, I've written a bunch of cgi scripts which do a lot of things, one of which is open a connection to a database. I would like this connection to be open until the user closes the browser. My questions is this - how do I know when a user closed a browser? Is there some library with api that deals with broswers? Thanks a lot of any pointers! __________________________________ Do you Yahoo!? Yahoo! Search - Find what you’re looking for faster http://search.yahoo.com From libsvm at tom.com Sun Mar 7 11:03:41 2004 From: libsvm at tom.com (Denny Li) Date: Sun Mar 7 18:49:26 2004 Subject: [Tutor] help with ScientificPython Message-ID: <404B47DD.9000004@tom.com> I download ScientificPython-2.4.5 cource code and install it according to its document. but when i run its examples in the directory "Examples" ,it raise error: [root@qlli Examples]# python compile.py make: Makefile.pre.in: No such file or Directory make: *** No rule to make target `Makefile.pre.in'. Stop. make: *** No targets specified and no makefile found. Stop. and i think the Doc in ScientificPython are TOO simple, is there an detailed document about ScientificPython? thanks From orbitz at ezabel.com Fri Mar 5 13:33:27 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Sun Mar 7 18:52:41 2004 Subject: [Tutor] ftplib stalling Message-ID: <20040305133327.41486fa4.orbitz@ezabel.com> Hello, I'm using ftplib to download a lot of files from an FTP site. The problem is sometimes when I do retrbinary(...) it just stalls indefiniatly. I never get a timeout exception or anything. Right now I am runingit myself and whenever it appears to stall i just hit ^C and catch the KeyboardInterrupt and have it restart the connection. I would like to automate this some how. Does anyone have any suggestions for doing any of the follow (or a better solution): 1) Sending an exception to my program every few seconds that I catch to make it restart the conn. 2) Some how set a timeout for the socket so I get a timeout exception. 3) A nother FTP module that handles these better. I'm considering twisted but for right now I'd like to stay away from it for this application but will deffinatly use it if it is the best solution. Thanks From pxlpluker at cfl.rr.com Sat Mar 6 09:31:49 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Sun Mar 7 18:53:14 2004 Subject: [Tutor] Pushing file name to browser In-Reply-To: <4041DE9C.9070201@pusspaws.net> References: <4041DE9C.9070201@pusspaws.net> Message-ID: <4049E0D5.2000504@cfl.rr.com> I what to dynamically create a page that has download links to file stored on disk. the part i don't know how to do (or if its possible) is to a different name appear in the browser DL window. i.e. I want the files stored with a random string but when being DL to have real name show in File Save dialog. in essence i want to push the file name to the browser Fred From red_necks25 at yahoo.com Fri Mar 5 20:19:16 2004 From: red_necks25 at yahoo.com (moore william) Date: Sun Mar 7 18:53:23 2004 Subject: [Tutor] Newby Still Lost with GUI!!! Message-ID: <20040306011916.64657.qmail@web13607.mail.yahoo.com> I am trying inhance my program to create a GUI interface instead of my current one. However I am coming up with "amount" and "self" are not defined. I thought I did this earlier. How would I go about creating the GUI and where did I miss my defentition? Thanks in advance for any guidence! import shelve s = shelve.open('d:/College/numberdata') if s.has_key('numbers'): numbers = s['numbers'] else: numbers = {} class AccountTransaction(object): def __init__(self, amount, time): self.amount = amount self.time = time def __repr__(self): description = time.ctime(self.time) + ' ' if self.amount < 0: description += '-' description += '$' + str(abs(self.amount)) return description def __self__(self, initial): self.balance = amount while 1: print print print 'Welcome to the Bank" print '1. Deposite' print '2. Withdraw' print '3. Getbalance' print '9. Quit' print choice = int(raw_input('Enter your choice: ')) # I added the exception line so that negartive numbers woudl not be added. if choice == 1: amount = raw_input ('Amount: ') elif amount < 0: raise ValueError, 'Deposites must be positive' elif self.balance - amount < 0: raise ValueError, 'The account only holds $' + str(self.balance) self._perform_transaction(-amount) date = raw_input ('Date: ') numbers[amount] = date # I added the exception line so that only positive numbers woudl eb entered for withdraws. line so that elif choice == 2: amount = raw_input ('Amount: ') if amount < 0: raise ValueError, 'Withdrawals must be negative' elif self.balance - amount < 0: raise ValueError, 'The account only holds $' + str(self.balance) self._perform_transaction(-amount) date = raw_input ('Date: ') numbers[amount] = date elif choice == 3: print for amount, date in numbers.items(): print '%-20s : %-14s' % (amount, date) elif choice == 9: break else: print_menu() print "Goodbye" ##save numbers when done s['numbers'] = numbers s.close() __________________________________ Do you Yahoo!? Yahoo! Search - Find what you’re looking for faster http://search.yahoo.com From RobinHood42 at clickta.com Sat Mar 6 23:30:25 2004 From: RobinHood42 at clickta.com (alice) Date: Sun Mar 7 18:53:48 2004 Subject: [Tutor] recursion and power sets Message-ID: <200403071130.25672.RobinHood42@clickta.com> Ouch! I think I've injured my brain on this one. I'm beginning to think recursion is not so cool after all..... I was trying to write a function that would take a set - represented as a list with non repeating elements - and return the power set, so given: [1,2,3] it should return: [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]] After much general confusion, this is what I eventually came up with: def foo(pool,head,result,n): """ pool, head and result should be lists, n a positive integer """ if (n == 0): while (pool != []): head.append(pool.pop()) result.append(head[:]) head.pop() else: while (pool != []): head.append(pool.pop()) foo(pool[:],head,result,n-1) head.pop() def power(set): head = [] result = [[]] for i in range(len(set)): foo(set[:],head,result,i) return result This gives the subsets in a simmilar order to the one in which I would find them if I was doing it by hand, but its kind of difficult to think about, so I thought about it a bit more and came up with: def power(set): result = [] bits = len(set) for string in range(2**bits): subset = [] position = 0 while (string > 0): if (string % 2 != 0): subset.append(set[position]) string /= 2 position += 1 result.append(subset) return result Even though this algorithm gives the subsets in a completely different order to the way I'd normally find them by hand, I'm guessing its closer to the "canonical" algorithm for finding power sets than my recursive attempt, am I right? or is there a third, completely different way of doing this? From rodolfo49 at hotmail.com Fri Mar 5 11:26:39 2004 From: rodolfo49 at hotmail.com (Rodolfo Rosario) Date: Sun Mar 7 18:54:01 2004 Subject: [Tutor] help Message-ID: <BAY1-F80gYRUVvn3CWx000015f6@hotmail.com> hello all, i`m a TOTAL newbie in programming in general and in python...i`m learning python because it`s the easier programming language around(at least they told me) and that it`s easy to enter the world of programming with it...i am reading "INSTANT HACKING" and i`m stuck with one of the exercises, i don`t know how to do it, please help me with it... EXERCISE 1 Write a program that continually reads in numbers from the user and adds them together until the sum reaches 100. I really don`t know how to sum what the user types...:( rodux _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From zahar at upsi.edu.my Wed Mar 3 20:56:23 2004 From: zahar at upsi.edu.my (Md. Zahar Othman) Date: Sun Mar 7 18:54:23 2004 Subject: [Tutor] Tree that doesn't grow Message-ID: <3309.10.10.11.241.1078365383.squirrel@mail.upsi.edu.my> I'm a newbie trying to convert my old Pascal tree program - pointer implementation to python OOP The program seem to run but unable to disp the required result. The method _insert is based on pascal procedure. Why the method does not work ? ============================= class binary_tree: def __init__(self): self.tree=None def insert (self,key): if self.tree: self._insert(self.tree,key) else: self.tree = node(key) def _insert (self,tree,key): if tree==None: tree = node(key) elif key < tree.key: self._insert(tree.left,key) elif key > tree.key: self._insert(tree.right,key) class node: def __init__(self,key): self.key=key self.left=None self.right=None t1=binary_tree() t1.insert(14) t1.insert(6) t1.insert(3) t1.tree.left.key # error t1.tree.left.left.key #error -- Think digital Act Analogue From alan.gauld at blueyonder.co.uk Sun Mar 7 19:43:40 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 7 19:43:20 2004 Subject: [Tutor] Difference between object and instances References: <404BB49C.4090001@terra.com.br> Message-ID: <001d01c404a6$66bcada0$6401a8c0@xp> > What is the real difference between objects and instances? Terminology. The generally accepted terms are Class and Object where Object is an instanciation of a class. but in some languages, including Python things can be objects which are not instances of classes - for example functions, and even classes themselves! So to differentiate between any object and objects created from classes it is sometimes necessary to be specific and say that we are talking about an instance rather than any object. (I suspect that as Python's type system becomes ever more unified even this distinction will dissappear eventually!) But 99% of the time objects and intstances are interchangeable. Alan G. From alan.gauld at blueyonder.co.uk Sun Mar 7 19:46:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 7 19:46:33 2004 Subject: [Tutor] Help References: <LAW11-F118KP7Ie8tlM00042c1b@hotmail.com> Message-ID: <002201c404a6$da696900$6401a8c0@xp> > I've installed python 2.3.2 on my Win 2K. I try to run a simple script, but > I keep getting this message 'Python' is not recognized as an internal or > external command, operable program or batch file'. How are you running the script? 1) via the Start->Run dialog 2) via a CMD (or DOS) box 3) via explorer - double clicking 4) From within IDLE Some other way? Also how does the message manifest itself? As a pop up dialog or as a message in the terminal window? My initial guess is that your PATH environment variable does not include Python, but I can't be sure based solely on what you've told us. Alan G. From alan.gauld at blueyonder.co.uk Sun Mar 7 19:52:40 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 7 19:52:22 2004 Subject: [Tutor] Newby Still Lost with GUI!!! References: <20040306011916.64657.qmail@web13607.mail.yahoo.com> Message-ID: <002b01c404a7$a89b3510$6401a8c0@xp> > I am trying inhance my program to create a GUI > interface instead of my current one. However I am > coming up with "amount" and "self" are not defined. I > thought I did this earlier. You did it inside the class definition, but you are trying to use them outside the class - check the indentation... > class AccountTransaction(object): > def __init__(self, amount, time): > self.amount = amount > self.time = time > > def __repr__(self): > def __self__(self, initial): End of class definition because while is not indented to right level incidentally what does __self__ do, thats a new one on me... > while 1: > print ''' Welcome to the Bank 1. Deposite 2. Withdraw 3. Getbalance 9. Quit ''' Triple quoted strings save a lot of typing of print statements... choice = int(raw_input('Enter your choice: ')) > if choice == 1: > amount = raw_input ('Amount: ') > elif amount < 0: > raise ValueError, 'Deposites must be positive' > elif self.balance - amount < 0: This is not part of the class so self doesn't exist... HTH, Alan G. From tim.one at comcast.net Sun Mar 7 20:53:23 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun Mar 7 20:53:27 2004 Subject: [Tutor] recursion and power sets In-Reply-To: <200403071130.25672.RobinHood42@clickta.com> Message-ID: <LNBBLJKPBEHFEDALKOLCAENNJFAB.tim.one@comcast.net> [alice] > Ouch! I think I've injured my brain on this one. > I'm beginning to think recursion is not so cool after all..... > > I was trying to write a function that would take a set - > represented as a list with non repeating elements - and return > the power set, so given: > > [1,2,3] > > it should return: > > [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]] > > After much general confusion, this is what I eventually came up with: ... [code to generate in order of size] ... > This gives the subsets in a simmilar order to the one in which I > would find them if I was doing it by hand, but its kind of difficult > to think about, so I thought about it a bit more and came up with: ... [code that looks at the integers in range(2**len(set)), and picks apart the bits to select subsets] ... > Even though this algorithm gives the subsets in a completely > different order to the way I'd normally find them by hand, I'm > guessing its closer to the "canonical" algorithm for finding power > sets than my recursive attempt, am I right? There isn't really a canonical way -- "whatever works" is fine. > or is there a third, completely different way of doing this? Oh, many <wink>. There are 2**N pieces in the result, and the factorial of that many ways to order them. Here's a particularly concsise way of generating the powerset: def powset(seq): if seq: head, tail = seq[:1], seq[1:] for smaller in powset(tail): yield smaller yield head + smaller else: yield [] Given that, then for s in powset([1, 2, 3]): print s prints [] [1] [2] [1, 2] [3] [1, 3] [2, 3] [1, 2, 3] That's close to "canonical" in the sense that it closely follows a natural way of *thinking* about the problem. Suppose we already had the powerset of a set S, and wanted the powerset of the set T consisting of S and a new element x. Well, each element of the powerset of T either does or doesn't contain x. If it doesn't contain x, it must be an element of the powerset of S too. Conversely, each element of the powerset of S is also an element of the powerset of T. On the other hand, if it does contain x, then if we took x out of it we'd also be left with an element of the powerset of S; and adding x to an element of the powerset of S must conversely give an element of the powerset of T. Put it all together, and the powerset of T is the powerset of S, plus the powerset of S fiddled by adding x to each element. That's how the code above works: if S isn't empty: pick the first element and call it "head" call the rest of S "tail" for each element e of the powerset of tail: one element of the powerset of S is e another is e plus head Now that's a naturally recursive way of thinking about the problem (we think about how the powerset of a set is related to the powerset of a smaller set), so it leads to simple recursive code. Your > I'm beginning to think recursion is not so cool after all..... comes from trying to force a recursive solution out of a non-recursive way of thinking about the problem. That is indeed painful <wink>. From op73418 at mail.telepac.pt Sun Mar 7 21:17:12 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Mar 7 21:14:44 2004 Subject: [Tutor] Difference between object and instances In-Reply-To: <001d01c404a6$66bcada0$6401a8c0@xp> References: <404BB49C.4090001@terra.com.br> <001d01c404a6$66bcada0$6401a8c0@xp> Message-ID: <tcln409287g9msvkt0l9o9fdlrspt9ca2t@4ax.com> Em Mon, 8 Mar 2004 00:43:40 -0000, "Alan Gauld" <alan.gauld@blueyonder.co.uk> atirou este peixe aos pinguins: > >> What is the real difference between objects and instances? > >Terminology. > >The generally accepted terms are > >Class and Object where Object is an instanciation of a class. > >but in some languages, including Python things can be objects >which are not instances of classes - for example functions, >and even classes themselves! > Actually, in Python (*) -- I'm using 2.3 but this is true in 2.2 already -- functions and classes themselves are instances of a some class. >>> def f(arg): ... pass ... >>> f <function f at 0x010D6B30> >>> f.__class__ <type 'function'> >>> id(f) 17656624 >>> import types >>> isinstance(f, types.FunctionType) True As you can see it an instance of a class. You can't subclass FunctionType although in c.l.py a request for it has appeared recently. The same for classes >>> F <class '__main__.F'> >>> id(F) 13570592 >>> F.__class__ <type 'type'> >>> isinstance(F, type) True You *can* subclass the class type. And then we are in metaclass programming lala-land. In fact, ATM I can't recall any object in Python that's not an instance of some class -- does anybody have a counterexample? With my best regards, G. Rodrigues (*) This is not true in Java for example. From glaine at free.fr Mon Mar 8 03:57:22 2004 From: glaine at free.fr (glaine@free.fr) Date: Mon Mar 8 03:57:30 2004 Subject: [Tutor] Start Again In-Reply-To: <6.0.0.22.0.20040307111656.0407f308@mail.mric.net> References: <1078494465.4048850161b12@imp2-q.free.fr> <6.0.0.22.0.20040307111656.0407f308@mail.mric.net> Message-ID: <1078736242.404c3572a5dce@imp2-q.free.fr> Selon Bob Gailer <bgailer@alum.rpi.edu>: > At 06:47 AM 3/5/2004, glaine@free.fr wrote: > >Hello > >I'm new in python. I try to make a script > >which save the win registry each morning > >after the win98's running. I have a lot of > >problems to concretize my idea about the moment > >when my script start. How to do to run automatically > >my script each morning after the win98's running > > Right-click on the Start Button and pick Explore. > This should put you in the Start Menu Folder. > Under this you should see the Programs Folder. > Expand this and you should see the Startup Folder. > Put your Python program (or a shortcut to it) in the Startup Folder. > > >I will accept any suggestions or ideas. I found > >some elements with win32events and handle, but I don't > >understand very well what handle means in python. > >Is there anybody to explain > >me ? Thank all for your help. > >Save Registry.py > >import _ winreg > >t=file('c:\\windows\\bureau\\toto.txt','w') > >p=_winreg.SaveKey(Keys x, Keys y,'t') > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > Thank you for your idea but it's not that I try to do. My script must be running automatically each morning after the Win's starting. I must click on my script with your idea what I don't want to do. My script looks like a sub routine of Win98 in my head. I thank you again very much, because it's great to share his time and ideas with the others. It's a good way too to be clearer. Guillaume From Janssen at rz.uni-frankfurt.de Mon Mar 8 07:00:31 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon Mar 8 07:00:42 2004 Subject: [Tutor] help In-Reply-To: <BAY1-F80gYRUVvn3CWx000015f6@hotmail.com> References: <BAY1-F80gYRUVvn3CWx000015f6@hotmail.com> Message-ID: <Pine.A41.4.56.0403081234400.286838@hermes-22.rz.uni-frankfurt.de> On Fri, 5 Mar 2004, Rodolfo Rosario wrote: > i`m a TOTAL newbie in programming in general and in python...i`m learning > python because it`s the easier programming language around(at least they > told me) and that it`s easy to enter the world of programming with it...i am > reading "INSTANT HACKING" and i`m stuck with one of the exercises, i don`t > know how to do it, please help me with it... > > EXERCISE 1 > Write a program that continually reads in numbers from the user and adds > them together until the sum reaches 100. > > I really don`t know how to sum what the user types...:( Hello Rodolfo, given by the Instant Hacking website you know already how to get input from the user. number = input("Type in a number: ") BTW: it's a pity that the author of this site chooses to use input instead of raw_input. The function input takes the user input *and evals it immidiatly" - that means: use it as a command. That's not good in respect of security and not good in respect of usability. input is more a function for "writing a quick script for expert use" to state from the Library Reference Docs. It's better to use raw_input and get strings from the user back: number_as_string = raw_input("Type in a number: ") number = int(number_as_string) # turn string into integer >From here on, all you have to do is to ask the user for that many numbers, until their sum reaches 100. You will have to use some kind of a loop (I leave decission on "for" or "while" to you - that's a main part of this exercise and I wouldn't help you if I solve it for you :-), track the current sum in a variable and break the loop when your sum is 100 or above ('above' would be the wrong result but the only way to know "until 100" is reached. You will need to print out the sum as it was before growing larger than 100. The easy case is when your user hits exactly the 100). Michael From darnold02 at sprynet.com Mon Mar 8 07:13:37 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Mar 8 07:13:57 2004 Subject: [Tutor] problem update References: <20040305000125.95166.qmail@web12406.mail.yahoo.com> Message-ID: <03c301c40506$c9ec0f50$bd10ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "Christopher Spears" <cspears2002@yahoo.com> To: <tutor@python.org> Sent: Thursday, March 04, 2004 6:01 PM Subject: [Tutor] problem update > I've been hacking away at my problem, and I have made > some progress. Here is the original problem: > > Using the UserList module, create a class called > Ulist, and override the __add__, append, and extend > methods so that duplicate values will not be added to > the list by any of these operations. > > Here is the script so far: > > import UserList > > class UList(UserList.UserList): > def __init__(self, initlist=None): > UserList.UserList.__init__(self, initlist) > > def __add__(self, other): > for s in range(len(self)): > if self[s] not in other: > if isinstance(other, UList): > return self.__class__(self.data + > other.data) > elif isinstance(other, > type(self.data)): > return self.__class__(self.data + > other) > else: > return self.__class__(self.data + > list(other)) > else: > print "Found duplicate %s" %self[s] > > When I run the code, I get the following results: > > >>> import UList > >>> list = [1,2,3] > >>> list1 = [1,4,5] > >>> a = UList.UList(list) > >>> b = UList.UList(list1) > >>> a > [1, 2, 3] > >>> b > [1, 4, 5] > >>> a + b > Found duplicate 1 > [1, 2, 3, 1, 4, 5] > > My code is only working halfway. The script detects a > duplicate but adds the duplicates in the lists anyway, > so the next step is to modify the script so that > duplicates will be eliminated. Any hints? My guess > is that 1 is not added in beginning of the loop > because the script detects it. Therefore, 1 must be > added when 2 is being compared against b. > > -Chris You have return statements within your loop, which can lead to unexpected behavior. In this case, your function returns as soon as it hits the first non-duplicate character. Furthermore, it always returns the same thing: a list with all of self's data and all of other's. I suggest you restructure this so that there is a single return that happens after all of you looping is done. Here's some pseudocode that might help you: set result equal to self.data for each item in other: if the item isn't already in result: add item to result return a UList built from result HTH, Don From cspears2002 at yahoo.com Mon Mar 8 13:02:57 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon Mar 8 13:04:06 2004 Subject: [Tutor] iterables Message-ID: <20040308180257.76485.qmail@web12405.mail.yahoo.com> Thanks to Karl for showing me the error of my ways! I did not look up the definition of the extend function so much as just played with it to see what it does. Anyway, I do have another basic question. What is an iterable? Again, this is a definition that I instinctively understand but have a hard time putting into words. The precise definition of the word iterate (according to my old Webster's dictionary) is to do or say again or again and again. Therefore, an iterable must be an object that you can perform a repetitive action upon, right? -Chris From cspears2002 at yahoo.com Mon Mar 8 13:15:43 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon Mar 8 13:15:50 2004 Subject: [Tutor] arrays in Python? Message-ID: <20040308181543.14234.qmail@web12401.mail.yahoo.com> What is an array? Does Python actually have them? Why or why not? -Chris From cspears2002 at yahoo.com Mon Mar 8 13:23:12 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon Mar 8 13:23:24 2004 Subject: [Tutor] I solved it! Message-ID: <20040308182312.20725.qmail@web12404.mail.yahoo.com> Thanks for everyone's help! Here is my solution! import UserList class UList(UserList.UserList): def __init__(self, initlist=None): UserList.UserList.__init__(self, initlist) self.copy = self self.duplicates = [] def __add__(self, other): for s in range(len(self.copy)): if self.copy[s] in other: self.duplicates.append(self[s]) for d in range(len(self.duplicates)): self.remove(self.duplicates[d]) if isinstance(other, UList): return self.__class__(self.data + other.data) elif isinstance(other, type(self.data)): return self.__class__(self.data + other) else: return self.__class__(self.data + list(other)) def extend(self, other): for s in other: if s in self: self.remove(s) if isinstance(other, UList): self.data.extend(other.data) else: self.data.extend(other) self.duplicates = [] def append(self, item): if item in self: self.remove(item) self.data.append(item) From dyoo at hkn.eecs.berkeley.edu Mon Mar 8 13:52:31 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 8 13:52:37 2004 Subject: [Tutor] help with ScientificPython In-Reply-To: <404B47DD.9000004@tom.com> Message-ID: <Pine.LNX.4.44.0403081041230.4105-100000@hkn.eecs.berkeley.edu> On Mon, 8 Mar 2004, Denny Li wrote: > I download ScientificPython-2.4.5 cource code and install it according > to its document. > but when i run its examples in the directory "Examples" ,it raise error: > [root@qlli Examples]# python compile.py > make: Makefile.pre.in: No such file or Directory > make: *** No rule to make target `Makefile.pre.in'. Stop. > make: *** No targets specified and no makefile found. Stop. > and i think the Doc in ScientificPython are TOO simple, is there an > detailed document about ScientificPython? > thanks Hi Denny, Hmmm... I'll assume that you mean: http://starship.python.net/~hinsen/ScientificPython/ It appears that the system requires a file called 'Makefile.pre.in' that's included with the source distribution of Python. Makefile.pre.in has traditionally been used to build third-party Python extensions. However, I don't believe that file is included in recent versions of Python, as the old build system has been deprecated in favor of the Distutils system. You may want to email the author of the module to see if the author would be willing to modify the Examples to use Distutils. Good luck to you! From marilyn at deliberate.com Mon Mar 8 13:53:12 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Mar 8 13:53:20 2004 Subject: [Tutor] Re: Tkinter Message-ID: <Pine.LNX.4.44.0403081042490.11161-100000@Kuna> Thank you Michael and Alan. I'm getting clearer. "Container and containee"! Of course. And yes, the destroy method does call __del__. That's a relief. I'm liking this form: ---------------- #!/usr/bin/env python '''Hello World in a GUI using Tkinter''' from Tkinter import * class Hello(Tk): def __init__(self): Tk.__init__(self) self.title('Hello World') if __name__ == '__main__': Hello().mainloop() ------------------ Is this acceptible? I'm confused about pack() and grid(). I understand that you shouldn't pack and grid into the same container. But can I not grid into a container that is packed into its container? I'm surprised that the following doesn't work. The Label in the Frame at the bottom doesn't show up. Are constrained to use the same geometry manager throughout an application? Or am I making some other mistake? -------- #!/usr/bin/python from Tkinter import * class Hello(Tk): def __init__(self): Tk.__init__(self) self.title("Hello World") self.geometry("150x100") #width x height Label(self, text="Hello World").pack(side=LEFT) b = Button(self, text="Bye", command=self.destroy) b.pack(side=RIGHT) f = Frame(self) f.pack() Label(f, text='Frame').grid() if __name__ == '__main__': Hello().mainloop() -------- Thank you again for the valuable help. Marilyn Davis From dyoo at hkn.eecs.berkeley.edu Mon Mar 8 14:09:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 8 14:12:26 2004 Subject: [Tutor] Tree that doesn't grow In-Reply-To: <3309.10.10.11.241.1078365383.squirrel@mail.upsi.edu.my> Message-ID: <Pine.LNX.4.44.0403081055140.4105-100000@hkn.eecs.berkeley.edu> On Thu, 4 Mar 2004, Md. Zahar Othman wrote: > class binary_tree: > > def __init__(self): > self.tree=None > > def insert (self,key): > if self.tree: > self._insert(self.tree,key) > else: > self.tree = node(key) > > def _insert (self,tree,key): > if tree == None: > tree = node(key) > elif key < tree.key: > self._insert(tree.left,key) > elif key > tree.key: > self._insert(tree.right,key) > Why the method does not work ? Hi Zahar, Let's take a detour for a moment. Take a look at the following code: ### def makeListEmpty(L): """Tries to empty out L. Buggy.""" L = [] L = [1, 2, 3, 4, 5] makeListEmpty(L) print L ### What do you expect to see here? Does it do what you expect? If you understand why this 'makeListEmpty()' function doesn't work, then that should help make it easier to see why binary_tree._insert() isn't having the effect you want. Please feel free to ask questions. Good luck to you! From elh at outreachnetworks.com Mon Mar 8 14:27:51 2004 From: elh at outreachnetworks.com (Eric L. Howard) Date: Mon Mar 8 14:28:08 2004 Subject: [Tutor] arrays in Python? In-Reply-To: <20040308181543.14234.qmail@web12401.mail.yahoo.com> References: <20040308181543.14234.qmail@web12401.mail.yahoo.com> Message-ID: <20040308192741.GA1480@outreachnetworks.com> At a certain time, now past [Mar.08.2004-10:15:43AM -0800], cspears2002@yahoo.com spake thusly: > What is an array? Does Python actually have them? An array is an indexed list of items. The same essential feature set is provided via the _list_ data type in Python core. ~elh -- Eric L. Howard e l h @ o u t r e a c h n e t w o r k s . c o m ------------------------------------------------------------------------ www.OutreachNetworks.com 313.297.9900 ------------------------------------------------------------------------ JabberID: elh@jabber.org Advocate of the Theocratic Rule From dyoo at hkn.eecs.berkeley.edu Mon Mar 8 14:27:53 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 8 14:28:10 2004 Subject: [Tutor] arrays in Python? In-Reply-To: <20040308181543.14234.qmail@web12401.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0403081110440.4105-100000@hkn.eecs.berkeley.edu> On Mon, 8 Mar 2004, Christopher Spears wrote: > What is an array? Hi Chris, As with many things, it depends on the definition. There's a terse definition here: http://www.nist.gov/dads/HTML/array.html and there's a more full-fledged entry from the Wikipedia: http://en.wikipedia.org/wiki/Array """An array, also known as a vector or list, is one of the simplest data structures in computer programming. Arrays hold a fixed number of equally-sized data elements, generally of the same data type. Individual elements are accessed by index using a consecutive range of integers, as opposed to an associative array.""" And that definition should sound similar to something you've already seen: the Python List fits that description pretty well. Not exactly, but pretty closely. Many folks who say "array" will usually restrict the meant to be a collection of the same data type. That is, some folks will feel slightly disturbed to see something like: ### >>> l = ['one', 2, list('three')] >>> l ['one', 2, ['t', 'h', 'r', 'e', 'e']] ### because there are three distinct "types" of things in here (strings, ints, and lists) , and in most languages, it's usually very difficult to write functions that handle different types. In Python, those three things can be handled "generically" --- that is, it's possible to define functions that work on all three types: ### >>> def double(x): return x + x ... >>> for x in l: ... print x, double(x) ... one oneone 2 4 ['t', 'h', 'r', 'e', 'e'] ['t', 'h', 'r', 'e', 'e', 't', 'h', 'r', 'e', 'e'] ### However, it's often difficult to write such generic operations for everything that we want to do. And for the most part, it's often a good idea to keep lists of a single type. Please feel free to ask more questions about this. Good luck! From sigurd at 12move.de Mon Mar 8 15:09:04 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Mar 8 15:11:36 2004 Subject: [Tutor] Tree that doesn't grow In-Reply-To: <3309.10.10.11.241.1078365383.squirrel@mail.upsi.edu.my> (Md. Zahar Othman's message of "Thu, 4 Mar 2004 09:56:23 +0800 (MYT)") References: <3309.10.10.11.241.1078365383.squirrel@mail.upsi.edu.my> Message-ID: <m3ad2ryurd.fsf@hamster.pflaesterer.de> On 4 Mar 2004, Md. Zahar Othman <- zahar@upsi.edu.my wrote: > I'm a newbie trying to convert my old Pascal tree program - pointer > implementation to python OOP And here is the problem: python has call by value semantics whereas Pascal has IIRC call by reference or call by value (you can choose). > Why the method does not work ? Because of the different semantic. > ============================= > class binary_tree: > def __init__(self): > self.tree=None > def insert (self,key): > if self.tree: > self._insert(self.tree,key) > else: > self.tree = node(key) > def _insert (self,tree,key): > if tree==None: > tree = node(key) In Pascal this could be a pointer or a reference to an address but in Python this won't work that way. You could change your code a bit: class binary_tree: def __init__(self): self.tree=None def insert (self,key): if self.tree: self._insert(self.tree,key) else: self.tree = node(key) def _insert (self,tree,key): if key < tree.key: if tree.left: self._insert(tree.left,key) else: tree.left = node(key) elif key > tree.key: if tree.right: self._insert(tree.right,key) else: tree.right = node(key) >>> p = binary_tree() >>> p.insert(10) >>> p.insert(11) >>> p.insert(9) >>> p.insert(12) >>> p.tree.key 10 >>> p.tree.left.key 9 >>> p.tree.right.key 11 >>> p.tree.right.right.key 12 >>> Karl -- Please do *not* send copies of replies to me. I read the list From RobinHood42 at clickta.com Mon Mar 8 04:48:26 2004 From: RobinHood42 at clickta.com (alice) Date: Mon Mar 8 17:34:07 2004 Subject: [Tutor] recursion and power sets In-Reply-To: <LNBBLJKPBEHFEDALKOLCAENNJFAB.tim.one@comcast.net> References: <LNBBLJKPBEHFEDALKOLCAENNJFAB.tim.one@comcast.net> Message-ID: <200403081648.26761.RobinHood42@clickta.com> <email> <tim> Suppose we already had the powerset of a set S, and wanted the powerset of the set T consisting of S and a new element x. The powerset of T is the powerset of S, plus the powerset of S fiddled by adding x to each element. </ tim> <image> light bulb turning on above alice's head </image> <python> def powset(seq): if seq: head, tail = seq[:1], seq[1:] for smaller in powset(tail): yield smaller yield head + smaller else: yield [] for s in powset([1, 2, 3]): print s </python> <alice> This is one of them iterator-thingy-ma-bobs, isn't it? hmmmm..... </alice> <sound> pieces of puzzle slowly falling into place </sound> <tim> There isn't really a canonical way -- "whatever works" is fine..... Here's a particularly concsise way..... </tim> <alice> I kind of thought that, with respect to algorithms, "canonical" and "most concise" were the same thing? Surely python programmers, of all people, are not of the attitude that: "whatever works is fine"! </alice> <tim> That's close to "canonical" in the sense that it closely follows a natural way of *thinking* about the problem. (we think about how the powerset of a set is related to the powerset of a smaller set) </tim> <alice> In retrospect it does seem like a very natural way of thinking about the problem. I wonder why I didn't see it myself? Perhaps because I knew that I _could_ find the subsets in order of smallest to largest, I felt that somehow I _should_. hmmmm... Anyway, thanks for guiding me from the first apparent solution to the beautiful one! Now I have to go and think about them iterator-thingy-ma-bobs..... </alice> </email> From pxlpluker at cfl.rr.com Mon Mar 8 17:24:19 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Mon Mar 8 17:34:11 2004 Subject: [Tutor] Re: Pushing file name to browser In-Reply-To: <4048925C.1030505@cfl.rr.com> References: <4041DE9C.9070201@pusspaws.net> <4048925C.1030505@cfl.rr.com> Message-ID: <404CF293.4090804@cfl.rr.com> after being pointed in the right direction by the other posts this is the answer that i have. print 'Content-type: application/force-download; ' print 'Content-disposition: attachment; filename="fname.ext"' will work on mozilla and the xp version of IE. i havent checked lower versions yet. to test simply do this: #!/usr/bin/env python print 'Content-type: application/force-download; ' print 'Content-disposition: attachment; filename="fname.ext"' print '\nThis is a test.' -------------------------------------------------------------------------------------------------------- pxlpluker wrote: > I what to dynamically create a page that has download links to file > stored on disk. > > the part i don't know how to do (or if its possible) is to a different > name appear in the browser DL window. > > i.e. I want the files stored with a random string but when being DL to > have real name show in File Save dialog. > > in essence i want to push the file name to the browser > > Fred > > > > > > From tim.one at comcast.net Mon Mar 8 23:34:16 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon Mar 8 23:34:25 2004 Subject: [Tutor] recursion and power sets In-Reply-To: <200403081648.26761.RobinHood42@clickta.com> Message-ID: <LNBBLJKPBEHFEDALKOLCCEFOJGAB.tim.one@comcast.net> [alice] > .. > <image> > light bulb turning on above alice's head > </image> > > <python> > def powset(seq): > if seq: > head, tail = seq[:1], seq[1:] > for smaller in powset(tail): > yield smaller > yield head + smaller > else: > yield [] > > for s in powset([1, 2, 3]): > print s > </python> > > This is one of them iterator-thingy-ma-bobs, isn't it? hmmmm..... It's called a generator. It's always easy to turn a generator into a function that materializes the entire result list in one gulp; for example, we could write the function above like so: def powset2(seq): result = [] if seq: head, tail = seq[:1], seq[1:] for smaller in powset(tail): result.append(smaller) result.append(head + smaller) else: result.append([]) return result IOW, everywhere we "yield"ed a result in the generator version, in the giant-result-list version we just append it to a result list instead. The joy of a generator is that it produces intermediate results one at a time. If, for example, len(seq)==60, there's not enough computer memory on Earth to hold the entire powerset at once, but the generator version doesn't need to. There's a lot more info about generators in PEP 255: http://www.python.org/peps/pep-0255.html Once you're used to them, they're almost always exactly what you want for, umm, *generating* a sequence of combinatorial objects (powersets, combinations, permutations, etc). [Tim] >> There isn't really a canonical way -- "whatever works" is fine..... [alice] > I kind of thought that, with respect to algorithms, "canonical" and > "most concise" were the same thing? Surely python programmers, of all > people, are not of the attitude that: "whatever works is fine"! Happy Python programmers generally prefer clarity to conciseness, and the two aren't always the same. If you're generating powersets just for the intellectual challenge, then the definition of "works" is pretty loose. But, for example, if you're generating powersets for "a real reason", perhaps you *need* to generate them in increasing size. Then the definition of "works" gets harder to meet. > In retrospect it does seem like a very natural way of thinking about > the problem. I wonder why I didn't see it myself? > Perhaps because I knew that I _could_ find the subsets in order of > smallest to largest, I felt that somehow I _should_. The *output* is prettier that way. You could try to think about that recursively too: suppose you had the powerset of S, and wanted the powerset of S *plus* a new element x, and wanted to generate the elements in increasing order of size. Well, we could first sort the powerset of S by size. The powerset of T is again the powerset of S, plus the powerset of S fiddled to add x to each element. Adding x to an element increases its size by 1. So we first want to yield the size-0 elements of the powerset of S, then the size-1 elements of the powerset of S, then the size-0 elements of the powerset of S fiddled to add x to each, then the size-2 elements of the powerset of S, then the size-1 elements of the powerset of S fiddled to add x to each, and so on. Here's a program to do that: def powset_bysize(seq): if seq: head, tail = seq[:-1], seq[-1:] segregated_by_size = [[] for dummy in range(len(seq))] for x in powset_bysize(head): segregated_by_size[len(x)].append(x) last_one = [] for sized_list in segregated_by_size: for x in sized_list: yield x for x in last_one: yield x + tail last_one = sized_list for x in last_one: yield x + tail else: yield [] Then powset_bysize([1, 2, 3]) generates in this order: [] [1] [2] [3] [1, 2] [1, 3] [2, 3] [1, 2, 3] It's not nearly as *clear* a program, though, IMO. Maybe you can find a way to make it prettier. It also loses much of the memory advantage of generators, because the topmost invocation ends up materializing the entire powerset of seq[:-1] (which is half the size of the powerset of seq) at once. A more natural approach could follow from the one you started with: take "generate all the subsets of size i" as a problem in its own right (that's called "a combination", btw). Then, assuming you have a generator gen_subsets_of_size(set, size) the powerset generator is just def gen_powset_by_size(set): for size in range(len(set) + 1): for x in gen_subsets_of_size(set, size): yield x That has a different kind of beauty, because gen_subsets_of_size() is likely to be a useful generator on its own, and it's always lovely to reuse code! In the concise department, here's a shorter way to write a giant-result-list version: def powset3(seq): if seq: p = powset3(seq[1:]) return p + [x + seq[:1] for x in p] else: return [[]] If you want to get *really* concise <wink>, here's a tiny non-recursive generator version, using the bit-fiddling trick you discovered earlier: def powset4(seq): pairs = [(2**i, x) for i, x in enumerate(seq)] for i in xrange(2**len(pairs)): yield [x for (mask, x) in pairs if i & mask] Are these getting clearer as they get shorter? I don't think so. > hmmmm... > Anyway, thanks for guiding me from the first apparent solution to the > beautiful one! It's just decades of practice <wink>. From idiot1 at netzero.net Tue Mar 9 00:26:04 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Mar 9 00:26:56 2004 Subject: [Tutor] aquire user id - uid Message-ID: <404D556C.6050407@netzero.net> I want to set the ownership of a file. The command os.setuid(usernumber) demands a NUMBER to set. ok, how do I determine the uid # of a user name? -- Respectfully, Kirk D Bailey Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From sandip at linux-delhi.org Tue Mar 9 01:45:58 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Tue Mar 9 01:50:39 2004 Subject: [Tutor] aquire user id - uid In-Reply-To: <404D556C.6050407@netzero.net> References: <404D556C.6050407@netzero.net> Message-ID: <404D6826.6070207@linux-delhi.org> Kirk Bailey wrote: > I want to set the ownership of a file. The command os.setuid(usernumber) > demands a NUMBER to set. ok, how do I determine the uid # of a user name? > For your own uid, use os.getuid() For somebody else's, use pwd.getpwnam() - Sandip -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From klappnase at freenet.de Tue Mar 9 06:16:46 2004 From: klappnase at freenet.de (Michael Lange) Date: Tue Mar 9 06:15:00 2004 Subject: [Tutor] Re: Tkinter In-Reply-To: <Pine.LNX.4.44.0403081042490.11161-100000@Kuna> References: <Pine.LNX.4.44.0403081042490.11161-100000@Kuna> Message-ID: <20040309121646.6c1fc968.klappnase@freenet.de> On Mon, 8 Mar 2004 10:53:12 -0800 (PST) Marilyn Davis <marilyn@deliberate.com> wrote: Hi, Marilyn, > I'm liking this form: > ---------------- > #!/usr/bin/env python > '''Hello World in a GUI using Tkinter''' > > from Tkinter import * > > class Hello(Tk): > def __init__(self): > Tk.__init__(self) > self.title('Hello World') > > if __name__ == '__main__': > Hello().mainloop() > ------------------ > Is this acceptible? > > I'm confused about pack() and grid(). I understand that you > shouldn't pack and grid into the same container. But can I > not grid into a container that is packed into its container? > > > I'm surprised that the following doesn't work. The Label in > the Frame at the bottom doesn't show up. > > Are constrained to use the same geometry manager throughout an > application? Or am I making some other mistake? > You've understood it right, you can use pack() and grid() within different Frames inside the same window, but NEVER inside the same Frame. > -------- > > #!/usr/bin/python > from Tkinter import * > > class Hello(Tk): > def __init__(self): > Tk.__init__(self) > self.title("Hello World") > self.geometry("150x100") #width x height > > Label(self, text="Hello World").pack(side=LEFT) > > b = Button(self, text="Bye", command=self.destroy) > b.pack(side=RIGHT) > > f = Frame(self) > f.pack() > Label(f, text='Frame').grid() > > if __name__ == '__main__': > Hello().mainloop() > > -------- > > Thank you again for the valuable help. > > Marilyn Davis > I tried your example and the Label *did* show up, but not at the bottom of the window but at the top and not completely (just "Fram" instead of "Frame"). If I enlarged the window it was completely there. The problem here is obviously an inappropriate use of pack(). Generally, for the kind of window layout I think you intended, I'd recommend the use of grid() instead of pack(), because grid makes it very easy to arrange widgets in any number of rows and columns, with pack() you will find that it is often necessary to create extra Frames to arrange your widgets like you wanted. I changed your code a little: ----------- #!/usr/bin/python from Tkinter import * class Hello(Tk): def __init__(self): Tk.__init__(self) self.title("Hello World") self.geometry("150x100") #width x height Label(self, text="Hello World").grid(row=0, column=0) b = Button(self, text="Bye", command=self.destroy) b.grid(row=0, column=1) f = Frame(self) f.grid(row=1, column=0, columnspan=2)# the extra Frame here is in fact not really necessary Label(f, text='Frame').pack() if __name__ == '__main__': Hello().mainloop() ----------- I think this is probably what you intended. The strength of pack() is that it is easier to use if you just want to have one or two widgets inside a Frame and want to control which widget expands and collapses when the window is resized. A resizable Text widget instead of Label(f, text='Frame') at the bottom with pack(): Text(self).pack(fill='both', expand=1) With grid() you would have to call grid_rowconfigure() and grid_columnconfigure() first: self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) Text(self).grid(row=1, column=0, columnspan=2, sticky='news') Pack() is also very handy if you want to put a number of widgets in the same Frame, always in the same direction (I added the following to the example): f2 = Frame(self) f2.grid(row=2, column=0, columnspan=2) for i in range(10): Label(f, text=str(i)).pack(side='left') However pack() gets hard to use if you want more than one direction for your widgets - it is hard to mix 'left', 'right', 'top' and 'bottom' (as in your example). In general, grid() is more powerful on complex layouts than pack(), but pack() is often easier to use for simple guis. If in doubt which to use I prefer grid(), because it can handle anything pack() can, but not vice versa. I hope this helps Michael From glingl at aon.at Tue Mar 9 08:57:47 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Mar 9 08:56:54 2004 Subject: [Tutor] 1 or 2 Tkinter Canvas questions Message-ID: <404DCD5B.6010408@aon.at> Hi! The very interesting reply to the last posting of Marilyn lets me hope, that there are people reading and writing here, who can answer the following questions: Recently I wrote a simple Tkinter program example which should draw a maximal rectangle on a (resizable) Canvas. It goes essentially like this: from Tkinter import * class RedRect(Tk): def __init__(self): Tk.__init__(self) self.title("RedRect") CvRedRect(self).pack(expand=1, fill="both") class CvRedRect(Canvas): def __init__(self, root): Canvas.__init__(self, root, bg="white") self.bind("<Configure>", self.paint) self.r = self.create_rectangle(0,0,0,0, outline="red") self.txt1 = self.create_text(30,30,text="") self.txt2 = self.create_text(30,60,text="") def paint(self, event): w,h=event.width, event.height self.itemconfig(self.txt1, text=str(w)) self.itemconfig(self.txt2, text=str(h)) self.coords(self.r,2,2,w-3,h-3) if __name__ == "__main__": RedRect().mainloop() # Marilyn's idea, nice! Now my questions: (1) Why do I have to use in self.coords(self.r,2,2,w-3,h-3) the constant(s) 2 and 3? One would expect, that something like self.coords(self.r,0,0,w-1,h-1) or self.coords(self.r,0,0,w,h) would work. But no, these rectangles are outside the visible prtion of the canvas. Moreover: is there some property ("option") of canvas which represents this sort of "inset"? Shortly: why doesn't appear the whole Canvas on the screen? (2) Why does apparently self.geometry("400x300+50+50") determine the size of the canvas packed into the Tk() - window and not the sizue of the Tk-window it*self*, which is 408*327 pixels? Minor questions, maybe. But I find it annoying that I need *experiment* with canvas and rectangle in order to get it as wanted. I'd prefer to compute it over trial an error. Thanks in advance Gregor From billintucson at yahoo.com Tue Mar 9 10:28:06 2004 From: billintucson at yahoo.com (Bill Gillespie) Date: Tue Mar 9 10:28:22 2004 Subject: [Tutor] Trying to post sensor readings to the web. Message-ID: <20040309152806.31739.qmail@web11807.mail.yahoo.com> Hi Folks! I have a great, fun and interesting project - but I have no idea what I am doing! :) I'm trying to learn how to post some sensor data, to a web page, by running a python cgi program. The objective is that each time I request the web page, and run the cgi program, the page would display the current readings for the sensors I am trying to monitor via the web. I have the sensors data in the form of a log file, but I'm not sure how to pass those logged sensor variables, to the web page through the cgi program. The log file is called "sensor.txt" and the data in it looks like this: -------------------------------------------------------------------- chan0=125, chan1=32, chan2=255, chan3=003, chan4=103, ... chan0=125, chan1=33, chan2=255, chan3=002, chan4=114, ... chan0=123, chan1=33, chan2=254, chan3=004, chan4=124, ... chan0=125, chan1=30, chan2=255, chan3=000, chan4=136, ... for 24 channels total -------------------------------------------------------------------- Here is what I have so far for the cgi program: All it can do at this point is generate a time stamp for the web page, and generate a simple 3 x 8 table. I'm working with python 2.3, running on a Mandrake 9.2, Linux machine. ------------------------------------------------------------------- monitor_telemetry.py - a cgi program for posting data to a web page ------------------------------------------------------------------- #! /usr/bin/python import time timenow = time.ctime(time.time()) print """Content-type: text/html <title>Current Sensor Readings</title> <BR> <BR> <BR> <CENTER> <H3>Sensor Readings - Data Page</H3> <HR> <HR> <p>Current date and time</p> <table border=3> """ for i in range(3): print "<tr>" for j in range(8): print "<td>%d.%d</td>" % (i,j) print "</tr>" ## print the date and time print timenow print "<br><br><br>" print """ </table> <HR> """ --------------------------------------------- Thanks much for any help. Bill __________________________________ Do you Yahoo!? Yahoo! Search - Find what you’re looking for faster http://search.yahoo.com From bgailer at alum.rpi.edu Tue Mar 9 12:49:57 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Mar 9 12:49:05 2004 Subject: {Spam?} [Tutor] Trying to post sensor readings to the web. In-Reply-To: <20040309152806.31739.qmail@web11807.mail.yahoo.com> References: <20040309152806.31739.qmail@web11807.mail.yahoo.com> Message-ID: <6.0.0.22.0.20040309104902.040bf3b0@mail.mric.net> At 08:28 AM 3/9/2004, Bill Gillespie wrote: >Hi Folks! > >I have a great, fun and interesting project - but I have no idea what I >am doing! > >:) > >I'm trying to learn how to post some sensor data, to a web page, by >running a python cgi program. The objective is that each time I request >the web page, and run the cgi program, the page would display the >current readings for the sensors I am trying to monitor via the web. > >I have the sensors data in the form of a log file, but I'm not sure how >to pass those logged sensor variables, to the web page through the cgi >program. > >The log file is called "sensor.txt" and the data in it looks like this: >-------------------------------------------------------------------- >chan0=125, chan1=32, chan2=255, chan3=003, chan4=103, ... >chan0=125, chan1=33, chan2=255, chan3=002, chan4=114, ... >chan0=123, chan1=33, chan2=254, chan3=004, chan4=124, ... >chan0=125, chan1=30, chan2=255, chan3=000, chan4=136, ... > > for 24 channels total > >-------------------------------------------------------------------- > >Here is what I have so far for the cgi program: > >All it can do at this point is generate a time stamp for the web page, >and generate a simple 3 x 8 table. I'm working with python 2.3, running >on a Mandrake 9.2, Linux machine. Is your question "How do I open and parse a file?"? >------------------------------------------------------------------- >monitor_telemetry.py - a cgi program for posting data to a web page >------------------------------------------------------------------- > >#! /usr/bin/python > >import time > >timenow = time.ctime(time.time()) > >print """Content-type: text/html > ><title>Current Sensor Readings</title> ><BR> ><BR> ><BR> ><CENTER> ><H3>Sensor Readings - Data Page</H3> ><HR> > > ><HR> > ><p>Current date and time</p> ><table border=3> >""" > >for i in range(3): > print "<tr>" > for j in range(8): > print "<td>%d.%d</td>" % (i,j) > print "</tr>" > >## print the date and time >print timenow >print "<br><br><br>" > > >print """ ></table> > > ><HR> >""" > >--------------------------------------------- > >Thanks much for any help. > >Bill > > > > > > >__________________________________ >Do you Yahoo!? >Yahoo! Search - Find what you're looking for faster >http://search.yahoo.com > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From dyoo at hkn.eecs.berkeley.edu Tue Mar 9 12:58:55 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 9 12:59:05 2004 Subject: [Tutor] Trying to post sensor readings to the web. In-Reply-To: <20040309152806.31739.qmail@web11807.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0403090943550.21198-100000@hkn.eecs.berkeley.edu> On Tue, 9 Mar 2004, Bill Gillespie wrote: > I'm trying to learn how to post some sensor data, to a web page, by > running a python cgi program. The objective is that each time I request > the web page, and run the cgi program, the page would display the > current readings for the sensors I am trying to monitor via the web. > > I have the sensors data in the form of a log file, but I'm not sure how > to pass those logged sensor variables, to the web page through the cgi > program. > > The log file is called "sensor.txt" and the data in it looks like this: > -------------------------------------------------------------------- > chan0=125, chan1=32, chan2=255, chan3=003, chan4=103, ... > chan0=125, chan1=33, chan2=255, chan3=002, chan4=114, ... > chan0=123, chan1=33, chan2=254, chan3=004, chan4=124, ... > chan0=125, chan1=30, chan2=255, chan3=000, chan4=136, ... Hi Bill, An approach that might help is to create a function that takes your 'sensor.txt' file, and extracts an MxN matrix of its data. Every line of your program appears to relate to a "row", and you can use some string manipulation to pull out the channel values out of a line. One possibility is to use the split() method of a string: ### >>> '3,4,5,6,7,8,9,10'.split() ['3,4,5,6,7,8,9,10'] >>> >>> >>> def extractElements(line): ... return line.split(', ') ... >>> extractElements('chan0=125, chan1=30, chan2=255, chan3=000') ['chan0=125', 'chan1=30', 'chan2=255', 'chan3=000'] ### And it should be simple to modify extractElements() to strip off the 'chan' prefix off of every channel value. Another powerful tool that you can look at is the 're' regular expression library. http://www.python.org/doc/lib/module-re.html http://www.amk.ca/python/howto/regex/ Regular expressions give us tools to do sophisticated pattern matching on strings. If you have questions on this, please feel free to ask on Tutor. Good luck to you! From alan.gauld at blueyonder.co.uk Tue Mar 9 18:59:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 9 18:58:50 2004 Subject: [Tutor] Re: Tkinter References: <Pine.LNX.4.44.0403081042490.11161-100000@Kuna> <20040309121646.6c1fc968.klappnase@freenet.de> Message-ID: <00b801c40632$98014cd0$6401a8c0@xp> > > I'm confused about pack() and grid(). I understand that you > > shouldn't pack and grid into the same container. But can I > > not grid into a container that is packed into its container? MIchael explained that bit for you. (One advantage of getting the digest is most of the hard work is already done :-) > Generally, for the kind of window layout I think you intended, I'd recommend > the use of grid() instead of pack(), because grid makes it very easy to arrange > widgets in any number of rows and columns, with pack() you will find that it is often > necessary to create extra Frames to arrange your widgets like you wanted. Again I agree with Michael here. > The strength of pack() is that it is easier to use if you just want to > have one or two widgets inside a Frame and want to control which widget > expands and collapses when the window is resized. Its also most useful with non symetrical layouts. If your GUI fits a grid pattern grid is great but if the widgts are, for whatver reason, sprayed all over the window then Pack is mucgh easier. Plus as Michael says its easier to control just what resizes and how with pack than with grid. But in most well designed UIs grid is proably the most appropriate choice. > ....I prefer grid(), because it can handle anything pack() can, > but not vice versa. I'm not sure thats true, but I'll need to go play to see if I can come up with a valid example... :-) > > I hope this helps > > Michael > > > > From alan.gauld at blueyonder.co.uk Tue Mar 9 19:05:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 9 19:04:44 2004 Subject: [Tutor] 1 or 2 Tkinter Canvas questions References: <404DCD5B.6010408@aon.at> Message-ID: <00bd01c40633$6be82050$6401a8c0@xp> > (2) Why does apparently > self.geometry("400x300+50+50") > determine the size of the canvas packed into the > Tk() - window and not the sizue of the Tk-window > it*self*, which is 408*327 pixels? Guessing, but that looks like the size of the border. ie 27 for the title bar and bottom frame and 8 (= 2x4) for the frame sides? Whereas the canvas is the drawable bit inside. Mebbe? Alan G. From klappnase at freenet.de Tue Mar 9 19:54:13 2004 From: klappnase at freenet.de (Michael Lange) Date: Tue Mar 9 20:03:47 2004 Subject: [Tutor] 1 or 2 Tkinter Canvas questions In-Reply-To: <404DCD5B.6010408@aon.at> References: <404DCD5B.6010408@aon.at> Message-ID: <20040310015413.3e841f59.klappnase@freenet.de> Hi, Gregor, On Tue, 09 Mar 2004 14:57:47 +0100 Gregor Lingl <glingl@aon.at> wrote: > Recently I wrote a simple Tkinter program > example which should draw a maximal rectangle > on a (resizable) Canvas. It goes essentially > like this: > > from Tkinter import * > > class RedRect(Tk): > def __init__(self): > Tk.__init__(self) > self.title("RedRect") > CvRedRect(self).pack(expand=1, fill="both") > > class CvRedRect(Canvas): > def __init__(self, root): > Canvas.__init__(self, root, bg="white") > self.bind("<Configure>", self.paint) > self.r = self.create_rectangle(0,0,0,0, outline="red") > self.txt1 = self.create_text(30,30,text="") > self.txt2 = self.create_text(30,60,text="") > def paint(self, event): > w,h=event.width, event.height > self.itemconfig(self.txt1, text=str(w)) > self.itemconfig(self.txt2, text=str(h)) > self.coords(self.r,2,2,w-3,h-3) > > if __name__ == "__main__": > RedRect().mainloop() # Marilyn's idea, nice! > > Now my questions: > > (1) Why do I have to use in > self.coords(self.r,2,2,w-3,h-3) > the constant(s) 2 and 3? One would expect, that > something like > self.coords(self.r,0,0,w-1,h-1) > or > self.coords(self.r,0,0,w,h) > would work. But no, these rectangles are outside > the visible prtion of the canvas. Moreover: is > there some property ("option") of canvas which > represents this sort of "inset"? > I changed the 2 and 3 in your code to 1 and 2 and still got the rectangle visible; obviously that's the width of the rectangle' lines(for x0/y0 1 pixel, for x1/y1 2 pixels, because you must add the width of the left and right / top and bottom lines). Obviously x0/x1/y0/y1 determine the coordinates of the rectangle *inside* the red rectangle we see. (with x1/y1 as width and height of the rectangle) That's why the option is called "OUTline" - it's outside the rectangle. I added a test to your paint method: def paint(self, event): w,h=event.width, event.height print w, h, self['width'], self['height'] self.itemconfig(self.txt1, text=str(w)) self.itemconfig(self.txt2, text=str(h)) self.coords(self.r,1,1,w-2,h-2) The result when I start the program: [pingu@localhost pingu]$ /usr/local/share/test3.py 297 209 295 207 Obviously the Canvas gets larger when the rectangle is created; the difference is even the same if you change the rectangle's width to 0 ! I guess we'll just have to get used to that. > Shortly: why doesn't appear the whole Canvas on the > screen? > > (2) Why does apparently > self.geometry("400x300+50+50") > determine the size of the canvas packed into the > Tk() - window and not the sizue of the Tk-window > it*self*, which is 408*327 pixels? > I think the answer is obvious: you determine the geometry of the part of the window you can use - the container and not the geometry of your window manager's border decoration. > Minor questions, maybe. But I find it annoying that I need > *experiment* with canvas and rectangle in order to get it as > wanted. I'd prefer to compute it over trial an error. > I haven't done much on Tkinter Canvasses yet, but I am not sure if the Canvas/rectangle behavior which might look like a *bug* here could be a *feature* in some cases. I hope this helped Michael From klappnase at freenet.de Wed Mar 10 07:01:17 2004 From: klappnase at freenet.de (Michael Lange) Date: Wed Mar 10 07:10:50 2004 Subject: [Tutor] Re: Tkinter In-Reply-To: <00b801c40632$98014cd0$6401a8c0@xp> References: <Pine.LNX.4.44.0403081042490.11161-100000@Kuna> <20040309121646.6c1fc968.klappnase@freenet.de> <00b801c40632$98014cd0$6401a8c0@xp> Message-ID: <20040310130117.2a94d2e0.klappnase@freenet.de> On Tue, 9 Mar 2004 23:59:43 -0000 "Alan Gauld" <alan.gauld@blueyonder.co.uk> wrote: > > > ....I prefer grid(), because it can handle anything pack() can, > > but not vice versa. > > I'm not sure thats true, but I'll need to go play to see if I can come > up with a valid example... :-) > > Oops, maybe I should correct myself here; is it ok to say grid() can handle most things pack() can? Anyway, I am interested if you find an example where grid() fails on something pack() can manage, I think this might be very instructive. Best regards Michael From Michael.Baker at IGT.com Wed Mar 10 14:11:40 2004 From: Michael.Baker at IGT.com (Baker.Michael.B) Date: Wed Mar 10 14:10:38 2004 Subject: [Tutor] smtplib broken in python 2.3? Message-ID: <CD9581266E2DD611A2190002A5377ACB0579E6FF@RNOEXCH05> i'm running winXP Pro and this code: from smtplib import * import sys def prompt(prompt): sys.stdout.write(prompt + ": ") return sys.stdin.readline().strip() fromaddr = prompt("From") toaddrs = prompt("To").split(',') print "Enter message, end with ^D:" msg = '' while 1: line = sys.stdin.readline() if not line: break msg = msg + line print "Message length is " + `len(msg)` server = SMTP('RNOEXCH05', 25) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() ok in 2.2, but fail in 2.3: Traceback (most recent call last): File "C:/Python23/email.py", line 1, in -toplevel- from smtplib import * File "C:\Python23\lib\smtplib.py", line 49, in -toplevel- from email.base64MIME import encode as encode_base64 File "C:/Python23\email.py", line 19, in -toplevel- server = SMTP('RNOEXCH05', 25) NameError: name 'SMTP' is not defined also strange: 2.2: >>> dir(smtplib) ['CRLF', 'OLDSTYLE_AUTH', 'SMTP', 'SMTPAuthenticationError', 'SMTPConnectError', 'SMTPDataError', 'SMTPException', 'SMTPHeloError', 'SMTPRecipientsRefused', 'SMTPResponseException', 'SMTPSenderRefused', 'SMTPServerDisconnected', 'SMTP_PORT', 'SSLFakeFile', 'SSLFakeSocket', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'base64', 'encode_base64', 'hmac', 'quoteaddr', 'quotedata', 're', 'rfc822', 'socket', 'types'] 2.3: >>> dir(smtplib) ['__builtins__', '__doc__', '__file__', '__name__', 'base64', 'hmac', 're', 'rfc822', 'socket'] what am i missing??? thanks in advance :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040310/d41e7d5f/attachment.html From sigurd at 12move.de Wed Mar 10 15:25:32 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Wed Mar 10 15:28:13 2004 Subject: [Tutor] smtplib broken in python 2.3? In-Reply-To: <CD9581266E2DD611A2190002A5377ACB0579E6FF@RNOEXCH05> (Baker Michael B.'s message of "Wed, 10 Mar 2004 11:11:40 -0800") References: <CD9581266E2DD611A2190002A5377ACB0579E6FF@RNOEXCH05> Message-ID: <m33c8gpi8z.fsf@hamster.pflaesterer.de> On 10 Mar 2004, Baker.Michael.B <- Michael.Baker@IGT.com wrote: > ok in 2.2, but fail in 2.3: > Traceback (most recent call last): > File "C:/Python23/email.py", line 1, in -toplevel- > from smtplib import * > File "C:\Python23\lib\smtplib.py", line 49, in -toplevel- > from email.base64MIME import encode as encode_base64 ^^^^^ > File "C:/Python23\email.py", line 19, in -toplevel- ^^^^^ You gave your file the same name as a module which should be imported (actually it's the name of the directory the files for the email package live in). That will cause problems (maybe in 2.4 it would run again if the new Pep from Aahz according import gets included). > what am i missing??? thanks in advance :) Give your file another name and try it again. Karl -- Please do *not* send copies of replies to me. I read the list From magnus at thinkware.se Wed Mar 10 18:47:07 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Mar 10 18:47:25 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVHJlZSB0aGF0IGRvZXNuJ3QgZ3Jvdw==?= Message-ID: <think001_404fa47f6c5ff@webmail.thinkware.se> > I'm a newbie trying to convert my old Pascal tree program - pointer > implementation to python OOP I'm not sure why you make two classes, tree and node. Isn't the left and right branches in the root trees themselves? I'd just use one class, not two. I think you are making a common mistake in OO programming, which is caused by a background in procedural programming. You make one data class (node) and one logic class (binary_tree). As Yoda said to Luke Skywalker: "You have to unlearn what you have learnt." The fundamental idea with classes is to encapulate a type of data together with the operations that operate on that data in a single class. Good luck with your programming! Is Python taught at UPSI, or is learning it a private initiative? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Wed Mar 10 20:03:39 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 10 20:03:52 2004 Subject: [Tutor] Tree that doesn't grow [implementing linked lists] In-Reply-To: <3346.10.10.11.241.1078890787.squirrel@mail.upsi.edu.my> Message-ID: <Pine.LNX.4.44.0403101010130.30719-100000@hkn.eecs.berkeley.edu> > > Let's take a detour for a moment. Take a look at the following code: > > > > ### > > def makeListEmpty(L): > > """Tries to empty out L. Buggy.""" > > L = [] > > > > L = [1, 2, 3, 4, 5] > > makeListEmpty(L) > > print L > > ### > > > > What do you expect to see here? Does it do what you expect? > > What you are saying is this. In python, function is pass by value except > if you using list. Hi Zahar, Actually, everything is "pass by value" in Python. Lists are no different, and that's why the code above doesn't do anything: ### >>> def makeListEmpty(L): ... L = [] ... >>> L = range(10) >>> makeListEmpty(L) >>> L [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ### At the moment, you're trying to implement binary trees. If you're still stuck, try something simpler. Have you tried implementing a simpler structure, like a linked list? Here's is a buggy implementation of a linked list that simulates essentially the same bug: ### class Node: def __init__(self, value, next): """Constructs a new node with attributes 'value' and 'next'.""" self.value, self.next = value, next def make_llist(): """Constructs a new Linked List. Implementation node: the list is initially a sentinel node. """ return Node("sentinel front", None) def display(llist): """Displays a linked list.""" node = llist.next ## skip the sentinel node print "[", while node != None: print node.value, node = node.next print "]" def insert(llist, value): """Inserts a new value into a linked list.""" insert_helper(llist, value) def insert_helper(node, value): """Tries to add a new value to the end of a list. Broken.""" if node == None: node = Node(value, None) else: insert_helper(node.next, value) ### I've removed most of the class stuff to make things a little simpler, plus I've modified the representation slightly so that every list has a "sentinel" head. Let's see how this code might work: ### >>> l = make_llist() >>> l.next = Node("foobar", None) ## let's manually insert 'foobar' >>> display(l) [ foobar ] >>> >>> >>> insert(l, "hello") ## let's try it through our function >>> display(l) [ foobar ] ## nope, no effect. >>> >>> >>> l.next.next = Node("manually_inserted", None) >>> display(l) [ foobar manually_inserted ] ### Everything here except the insert_helper() is functioning, and, again insert_helper() appears to have no effect. So let's take another look at the insert_helper(): ### def insert_helper(node, value): """Tries to add a new value to the end of a list. Broken.""" if node == None: node = Node(value, None) else: insert_helper(node.next, value) ### insert_helper() is recursive, so we can break this down into cases. What's the base case? The code, as it stands now, thinks that the base case is when if node == None: node = Node(value, None) As we saw above, though, because of call-by-value, this really has no effect: we're just rebinding 'node' to a new Node, and there's no linking going on between our list and the new node. If we have a list like: "sentinel" and we want to add "node2", it's not enough to just draw a new node: "sentinel" "node2" because "node2" is floating around in space, and is not attached to anything. That's what something like: if node == None: node = Node(value, None) is doing. But instead, we need to do more: we need to draw a link from one node to another: "sentinel" ----> "node2" where we tie the 'next' arrow of some node and loop it at the Node that we've just constructed. The base case on insertion should not be when we've fallen off our list and hit None, because, by that time, it's too late to try attaching anything to the list. We need to be anchored right at the edge, teetering at the very end, so that we can tie an arrow with 'next' to our new node. And that's a different base case than 'node == None'. Anyway, hope this helps. Good luck! From cspears2002 at yahoo.com Wed Mar 10 20:03:59 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed Mar 10 20:04:38 2004 Subject: [Tutor] regular expressions Message-ID: <20040311010359.51064.qmail@web12405.mail.yahoo.com> I am hacking away on my final project: A file with a name like picture.jpg is said to have an extension of "jpg"; i.e. the extension of a file is the part of the file after the final period in its name. Write a program that takes as an argument the name of a directory (folder) and then finds the extension of each file. Then, for each extension found, it prints the number of files with that extension and the minimum, average, and maximum size for files with that extension in the selected directory. Here is my code so far: def whatsindirectory(path): extensions = [] final_ext = [] filewext = [] import os,re files = os.listdir(path) pattern = re.compile(r"\.[a-z]*",re.I) for f in range(len(files)): ext = re.findall(pattern,files[f]) extensions.append(ext[0]) for e in range(len(extensions)): if extensions[e] not in final_ext: final_ext.append(extensions[e]) print "Extensions in directory:", final_ext for x in range(len(final_ext)): pattern01 = re.compile(final_ext[x],re.I) print "Files with extension %s" %final_ext[x] for f in range(len(files)): matches = re.findall(pattern01,files[f]) filewext = filewext + matches print filewext filewext = [] I have managed to extract the extensions from the files. But how do I use the extensions to get a name? I tried the following: pattern01 = re.compile(r".*"final_ext[x],re.I) That got my a syntax error. Any hints? -Chris From sandip at linux-delhi.org Thu Mar 11 03:09:53 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Thu Mar 11 03:14:47 2004 Subject: [Tutor] regular expressions In-Reply-To: <20040311010359.51064.qmail@web12405.mail.yahoo.com> References: <20040311010359.51064.qmail@web12405.mail.yahoo.com> Message-ID: <40501ED1.2050908@linux-delhi.org> Christopher Spears wrote: > I am hacking away on my final project: > > A file with a name like picture.jpg is said to have an > extension of "jpg"; i.e. the extension of a file is > the part of the file after the final period in its > name. Write a program that takes as an argument the > name of a directory (folder) and then finds the > extension of each file. Then, for each extension > found, it prints the number of files with that > extension and the minimum, average, and maximum size > for files with that extension in the selected > directory. > > Here is my code so far: > Thanks for giving me a pet problem to get me up to speed with python. :) Are you sure you want to use regular expressions for this? The os.path module gives you all you need. Here is my code for doing it without regexp. No intention to spoil your work. Just took it as my excercise. ;) ==================== #!/usr/bin/python import os.path,os from stat import ST_SIZE dirpath = raw_input("Enter path:") filelist = os.listdir(dirpath) extlist={} for fname in filelist: if not os.path.isfile(fname): pass undef,file = os.path.split(fname) b,e= os.path.splitext(file) size = os.stat(dirpath+"/"+fname)[ST_SIZE] if not extlist.has_key(e): extlist[e] = (1,size,size,size) else: n,smin,savg,smax=extlist[e] if smin > size: smin = size if smax < size: smax = size savg = (savg*n + size)/(n+1) n+=1 extlist[e] = (n,smin,savg,smax) for ext in extlist.keys(): n,smin,savg,smax=extlist[ext] print "%20s %3d %8d %8d %8d" % (ext[1:], n,smin,savg,smax) ============= -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From stig_matt at hotpop.com Thu Mar 11 05:36:52 2004 From: stig_matt at hotpop.com (stig mattsson) Date: Thu Mar 11 05:51:49 2004 Subject: [Tutor] sorting of unicode text Message-ID: <237825102.20040311133652@hotpop.com> Hello tutors, I am completely new to Python and I need to make the alphabetical sorting of a text utf8 file. Is it possible to make such a sorting with Python? Could you please give me an example? Thank you. stig From pythontut at pusspaws.net Thu Mar 11 08:47:16 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu Mar 11 09:15:00 2004 Subject: [Tutor] OK real basic problem ... Message-ID: <40506DE4.8070307@pusspaws.net> I've created a file called pycode ... #!/usr/bin/env python print "hi my module is loaded !!!\n" def addit(a,b): print a+b good so far, chmod a+x pycode In python I have ... >>> import pycode >>> reload(pycode) hi my module is loaded !!! <module 'pycode' from '/home/dave/pycode/pycode.py'> >>> addit(1,2) Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'addit' is not defined >>> From my message "hi my module has loaded ... I thought addit() would work .. OK I know this is simple ... but ... err .. any ideas Dave From sandip at linux-delhi.org Thu Mar 11 09:49:14 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Thu Mar 11 09:53:55 2004 Subject: [Tutor] OK real basic problem ... In-Reply-To: <40506DE4.8070307@pusspaws.net> References: <40506DE4.8070307@pusspaws.net> Message-ID: <40507C6A.7000207@linux-delhi.org> Dave S wrote: > >>>> addit(1,2) > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > NameError: name 'addit' is not defined > How about pycode.addit(1,2) ? ;) - Sandip -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From alan.gauld at blueyonder.co.uk Thu Mar 11 10:23:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Mar 11 10:23:17 2004 Subject: [Tutor] OK real basic problem ... References: <40506DE4.8070307@pusspaws.net> Message-ID: <014d01c4077c$d4252600$6401a8c0@xp> > I've created a file called pycode ... > > #!/usr/bin/env python > print "hi my module is loaded !!!\n" > > def addit(a,b): > print a+b > > good so far, chmod a+x pycode Actually to import the file you don;t need to make it executable, merely readable... However if you ever want to run it standalone you will need +x. Just a wee point. > >>> import pycode > >>> reload(pycode) YOu shouldn't need the reload! > hi my module is loaded !!! And this should have printed on the initial import too. > >>> addit(1,2) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > NameError: name 'addit' is not defined An import(or reload) imports the names that you give it - in this case "pycode". It does NOT import the names inside pycode. (You can do that with "from pycode import *" but as you will see thats usually a bad idea.) So you have imported the name pycode which refers to your file(or module). To access the contents of your module prefix the function with the module name: pycode.addit(1,2) > From my message "hi my module has loaded ... I thought addit() would > work .. When you import a module it executes all the code in that module. Your print statement is simply being executed by the import. Your function definition is likewise being exactuted and a function object created. But you can't directly see that object because its inside pycode. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Thu Mar 11 10:12:04 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu Mar 11 10:39:48 2004 Subject: [Tutor] OK real basic problem ... In-Reply-To: <40506DE4.8070307@pusspaws.net> References: <40506DE4.8070307@pusspaws.net> Message-ID: <405081C4.7030108@pusspaws.net> Dave S wrote: > I've created a file called pycode ... > > #!/usr/bin/env python > print "hi my module is loaded !!!\n" > > def addit(a,b): > print a+b > > good so far, chmod a+x pycode > > In python I have ... > >>>> import pycode >>>> reload(pycode) >>> > hi my module is loaded !!! > > <module 'pycode' from '/home/dave/pycode/pycode.py'> > >>>> addit(1,2) >>> > Traceback (most recent call last): > File "<stdin>", line 1, in ? > NameError: name 'addit' is not defined > >>>> > > From my message "hi my module has loaded ... I thought addit() would > work .. > > OK I know this is simple ... but ... err .. any ideas > > Dave > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Thanks everyone ... I got the idea now pycode.addit(1,2) Does the job + I now understand a bit more about modules :-) Cheers once again Dave From dyoo at hkn.eecs.berkeley.edu Thu Mar 11 12:23:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 11 12:23:33 2004 Subject: [Tutor] sorting of unicode text In-Reply-To: <237825102.20040311133652@hotpop.com> Message-ID: <Pine.LNX.4.44.0403110921530.4048-100000@hkn.eecs.berkeley.edu> On Thu, 11 Mar 2004, stig mattsson wrote: > I am completely new to Python and I need to make the alphabetical > sorting of a text utf8 file. Is it possible to make such a sorting with > Python? Could you please give me an example? Thank you. Hi Stig, Sure; have you had a chance to look at: http://www.amk.ca/python/howto/sorting/sorting.html That Sorting HOWTO has a few examples of using sort() to order a list, and should help you get started. If you have questions, please feel free to ask! From sigurd at 12move.de Thu Mar 11 12:31:35 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Mar 11 12:36:26 2004 Subject: [Tutor] regular expressions In-Reply-To: <20040311010359.51064.qmail@web12405.mail.yahoo.com> (Christopher Spears's message of "Wed, 10 Mar 2004 17:03:59 -0800 (PST)") References: <20040311010359.51064.qmail@web12405.mail.yahoo.com> Message-ID: <m3vflb8io7.fsf@hamster.pflaesterer.de> On 11 Mar 2004, Christopher Spears <- cspears2002@yahoo.com wrote: > I am hacking away on my final project: As it seems to be homework I won't show you all solutions. > A file with a name like picture.jpg is said to have an > extension of "jpg"; i.e. the extension of a file is > the part of the file after the final period in its > name. Write a program that takes as an argument the Here a extension is defined as the part of the file after the *final* period. > name of a directory (folder) and then finds the > extension of each file. Then, for each extension > found, it prints the number of files with that > extension and the minimum, average, and maximum size > for files with that extension in the selected > directory. > Here is my code so far: [...] > pattern = re.compile(r"\.[a-z]*",re.I) That regexp won't find the part that's defined above as extension. E.g.: >>> pattern = re.compile(r"\.[a-z]*",re.I) >>> pattern.search('a_tar_and_gz_file.tar.gz').group() '.tar' That's wrong. > for f in range(len(files)): You can iterate directly over a sequence with: for f in seq: ... [...] > I have managed to extract the extensions from the > files. But how do I use the extensions to get a name? > I tried the following: > pattern01 = re.compile(r".*"final_ext[x],re.I) > That got my a syntax error. Any hints? First to the syntax error. If you want to concatenate two strings (I assume `final_ext[x]' is a string) just write a `+' between them. Now to your problem. I think you tried to many things at once and therefore you wrote a much too complicated solution. Try to split the problem in logical parts, solve each one and glue the together again. Let's look at your problem. (a) Find the names of all files in a directory. For that you used a function from the os module: os.listdir(). Fine problem one solved. -> os.listdir() (b) Find the names of all extensions of these files. As Sandip pointed out there is also a function in the os module which helps us with that: -> os.path.splitext() (c) Find the number of files for each extension ... So you have a list of all files in a directory and you want to know how may files of each sort extension exist. There are several solutions possible, the easiest one is to use a dictionary where the file extension is the key and the absolute frequency of that extension is the value. Each time you enter a new key you either set its value to 1 (if the key didn't exist before) or you increment its value by one. dictionaries have the get() method which can be used easily for that task. >>> d = {} >>> d['tar'] = d.get('tar', 0) + 1 >>> d {'tar': 1} >>> d['tar'] = d.get('tar', 0) + 1 >>> d {'tar': 2} So let's combine the above. exts = {} for file in os.listdir(d): base, ext = os.path.splitext(file) ext = ext[1:] exts[ext] = exts.get(ext, 0) + 1 I wrote here ext[1:] since the split method returns also the period with the extension. (d) ... and their minimum, average and maximum sizes. To find the size of a file you can use os.path.getsize(). The above dictionary has to be changed a bit to allow us to store that information as well. We'll use now a list as value. The first entry of that list will be the frequency and the second will be a list with all the sizes. So the above becomes: exts = {} for file in os.listdir(d): base, ext = os.path.splitext(file) if ext: ext = ext[1:] size = os.path.getsize(os.path.join(d, file)) exts[ext] = exts.get(ext, [0, []]) exts[ext][0] += 1 exts[ext][1].append(size) Now you have all you need. You have a dictionary where the keys are the file extensions, the values are lists with the frequencies of the extensions and a list of corresponding file sizes as values. To find the minimum or maximum value of a list of numbers you can use min() or max() >>> L = range(10) >>> min(L) 0 >>> max(L) 9 And the average? Sum the items and divide them through their count. To sum items you can use sum() and the count is the length of the list. HTH Karl -- Please do *not* send copies of replies to me. I read the list From Michael.Baker at IGT.com Thu Mar 11 13:09:23 2004 From: Michael.Baker at IGT.com (Baker.Michael.B) Date: Thu Mar 11 13:08:27 2004 Subject: [Tutor] smtplib broken in python 2.3? Message-ID: <CD9581266E2DD611A2190002A5377ACB0579EC80@RNOEXCH05> that did the trick. what an obvious solution - i had forgotten that i named my py file email.py. thanks Michael Baker >Date: Wed, 10 Mar 2004 21:25:32 +0100 >From: sigurd@12move.de ( Karl Pfl?sterer ) >Subject: Re: [Tutor] smtplib broken in python 2.3? >To: tutor@python.org >Message-ID: <m33c8gpi8z.fsf@hamster.pflaesterer.de> >Content-Type: text/plain; charset=us-ascii >On 10 Mar 2004, Baker.Michael.B <- Michael.Baker@IGT.com wrote: >> ok in 2.2, but fail in 2.3: >> Traceback (most recent call last): >> File "C:/Python23/email.py", line 1, in -toplevel- >> from smtplib import * >> File "C:\Python23\lib\smtplib.py", line 49, in -toplevel- >> from email.base64MIME import encode as encode_base64 ^^^^^ >> File "C:/Python23\email.py", line 19, in -toplevel- ^^^^^ >You gave your file the same name as a module which should be imported (actually it's the name of the directory the files for the email package >live in). That will cause problems (maybe in 2.4 it would run again if the new Pep from Aahz according import gets included). >> what am i missing??? thanks in advance :) >Give your file another name and try it again. > Karl >-- >Please do *not* send copies of replies to me. >I read the list From simple_twist at adelphia.net Thu Mar 11 16:09:54 2004 From: simple_twist at adelphia.net (Nick Noda) Date: Thu Mar 11 16:17:21 2004 Subject: [Tutor] a simple password program Message-ID: <000801c407ad$33ce20e0$17c54544@vnnyca.adelphia.net> hey guys, i've only been using python for a few days now and i was following a non-programers tutorial. one of the excercises was to make a password program that after 3 incorrect guesses at the password tells the user that the pass was incorrect. this is what i got: password = "foobar" count = 0 while password != "nabbers": if count < 3: password = raw_input("Password:") count = count + 1 else: print "Too complicated, huh?" print "Welcome inside." i can get it to say "Welcome inside." if the pass is correct, but if the pass is guessed wrong three times it just keeps looping "Too complicated, huh?" i was wondering if it is supposed to do that or if there is a way that i can get it to say it once then quit. any help i would jump up and down for. newbie to python, Nick Noda --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.614 / Virus Database: 393 - Release Date: 3/5/04 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040311/afc813a9/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Mar 11 16:52:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 11 16:53:02 2004 Subject: [Tutor] a simple password program In-Reply-To: <000801c407ad$33ce20e0$17c54544@vnnyca.adelphia.net> Message-ID: <Pine.LNX.4.44.0403111349040.2660-100000@hkn.eecs.berkeley.edu> On Thu, 11 Mar 2004, Nick Noda wrote: > i've only been using python for a few days now and i was following a > non-programers tutorial. one of the excercises was to make a password > program that after 3 incorrect guesses at the password tells the user > that the pass was incorrect. this is what i got: > > password = "foobar" > count = 0 > while password != "nabbers": > if count < 3: > password = raw_input("Password:") > count = count + 1 > else: > print "Too complicated, huh?" > print "Welcome inside." > > i can get it to say "Welcome inside." if the pass is correct, but if > the pass is guessed wrong three times it just keeps looping "Too > complicated, huh?" i was wondering if it is supposed to do that or if > there is a way that i can get it to say it once then quit. Hi Nick, Yes, you probably want to "break" out of the loop. Here's an example: ### >>> def yesOrNo(): ... while True: ... print "y/n?", ... choice = raw_input() ... if choice in ('y', 'n'): ... break ... return choice ... >>> yesOrNo() y/n?blah y/n?yes y/n?y 'y' ### Hope this helps! From sigurd at 12move.de Thu Mar 11 16:48:43 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Mar 11 16:54:42 2004 Subject: [Tutor] a simple password program In-Reply-To: <000801c407ad$33ce20e0$17c54544@vnnyca.adelphia.net> (Nick Noda's message of "Thu, 11 Mar 2004 13:09:54 -0800") References: <000801c407ad$33ce20e0$17c54544@vnnyca.adelphia.net> Message-ID: <m3ekrz83s8.fsf@hamster.pflaesterer.de> On 11 Mar 2004, Nick Noda <- simple_twist@adelphia.net wrote: > while password != "nabbers": > if count < 3: > password = raw_input("Password:") > count = count + 1 > else: > print "Too complicated, huh?" > print "Welcome inside." > i can get it to say "Welcome inside." if the pass is correct, but if the > pass is guessed wrong three times it just keeps looping "Too complicated, > huh?" i was wondering if it is supposed to do that or if there is a way > that i can get it to say it once then quit. any help i would jump up and > down for. Think what happens if after the third pass the password is still wrong: The loop looks in the condition: password != "nabbers!" which is true, so the loop starts a new cycle; count is bigger than three so it jumps directly to the else part, prints its message and starts a new cycle ... So you have to find a way to break the loop unconditionally: if you only wanted to stop the loop `break' would be right, but you also want to stop the programm; for that you could use a method from the sys module: sys.exit(). You could write: import sys count = 0 password = "" while password != "nabbers": if count < 3: password = raw_input("Password: ") count += 1 else: print "Too complicated, huh?" sys.exit() print "Welcome inside." Karl -- Please do *not* send copies of replies to me. I read the list From magnus at thinkware.se Thu Mar 11 17:07:12 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Mar 11 17:07:22 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gYSBzaW1wbGUgcGFzc3dvcmQgcHJvZ3JhbQ==?= Message-ID: <think001_4050e2fb96c30@webmail.thinkware.se> Nick Noda wrote: > hey guys, Hello Nick, and welcome. [code snipped] > i can get it to say "Welcome inside." if the pass is correct, but if the pass is guessed wrong three times it just keeps looping "Too complicated, huh?" i was wondering if it is supposed to do that or if there is a way that i can get it to say it once then quit. any help i would jump up and down for. You are obviously supposed to be able to make the program do whatever you want. There are at least two solutions that come to mind. You might want to look up what the "break" statement does. You might also consider turning the loop and if conditions around... Just as well as you can loop while not right password and do something particular after three guesses, you might instead loop three times, and do something special when the guess is right. (Such as leave the loop, read about break.) There are many ways to skin a cat. If you want the program to exit after three wrong guesses you can just write import sys; sys.exit() after 'print "Too complicated, huh?"' For a password program that actually lets you stop worrying about administering passwords :), check out http://www.thinkware.se/cgi-bin/thinki.cgi/PopAuthPy -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From greg at thewhittiers.com Thu Mar 11 19:44:20 2004 From: greg at thewhittiers.com (Greg Whittier) Date: Thu Mar 11 19:43:33 2004 Subject: [Tutor] dataset module Message-ID: <1079052260.15921.22.camel@localhost.localdomain> I'm doing what Python Programming on Win32 calls "data laundering." Basically, I'm taking data from a database via odbc and manipulating it in python (interpolating, transforming, plotting, etc.). I've implemented a simple DataSet class like that in the book that just holds data in a list of lists. The book has a paired down class and I've been implementing extra methods as I need them (sorting by columns, etc.). It's been a good exercise (got to use decorate-sort-unsort a lot!), but I feel like I'm reinventing the wheel. Looking at the web, however, I found a presentation http://starship.python.net/crew/pirx/spam7/COMtut.PPT that describes a DataSet class with a pretty good set of methods. Is this code available anywhere? Is there another standard module people generally use? Or, do people generally craft their own data access widget? Thanks, Greg From alan.gauld at blueyonder.co.uk Fri Mar 12 12:26:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Mar 12 12:26:26 2004 Subject: [Tutor] a simple password program References: <000801c407ad$33ce20e0$17c54544@vnnyca.adelphia.net> Message-ID: <001d01c40857$2db04440$6401a8c0@xp> > i've only been using python for a few days now and i was > following a non-programers tutorial. one of the excercises > was to make a password program that after 3 incorrect > guesses at the password tells the user that the pass was incorrect. Hmm, I think Josh needs to do some work on his tutor since this always seems to be the exercise that stumps newbies! :-) > count = 0 > while password != "nabbers": > if count < 3: > password = raw_input("Password:") > count = count + 1 One thing that beginners often seem to miss is that boolean expressions (ie tests) can be combined using logical operators(and, or, not, etc). Thus you can check while (password != 'nabbers') and (count < 3): This can greatly simplify the logic inside the loop. Its exactly like you combine arithmetic operations together using parentheses. Take a look at my tutorial pages on Raw Materials, under Boolean Values and also in the Branching topic where it discusses combining tests. Remeber that computers need to be told *exactly* what to do, they can't infer things from what you've already told them... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From oyvind.sporck at eniro.no Thu Mar 11 12:31:59 2004 From: oyvind.sporck at eniro.no (=?iso-8859-1?Q?=D8yvind_Dale_Sp=F8rck?=) Date: Fri Mar 12 13:36:02 2004 Subject: [Tutor] For statement Message-ID: <47017DDDD14F20499CE7F361FABC1E10517824@maia.a.sol.no> I have a list: a= ['golden,','poodle,','flat,','retriever,'] I would like to remove the , after the word, with a for statement. However, the result doesn't end up as I like. I end up removing one of the items at the time or getting a "TypeError: list indices must be integers" error. I have tried tons of different versions such as: >>> for x in a: ... a[:] = a[:][:-1] ... print a But it doesn't work. How would I do it? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040311/79d2e864/attachment.html From pete at freesome.com Mon Mar 8 18:08:13 2004 From: pete at freesome.com (PetesK) Date: Fri Mar 12 13:36:21 2004 Subject: [Tutor] Twisted? Message-ID: <404CFCDD.6050404@freesome.com> Hi, I need to wite a simple socket server that can talk to many flash clients over TCP, I have been playing around wiht the SocketServer, but had started to wonder about simple things like how to safely pass in data from other threads to this server. I googled, and found a reply form this list about using Twisted. Looks like a massive framework (as the docs clearly say)... Does aniy one have experiace with Twisted, do you think it will save me a lot of hair pulling, r is it overkill for a simple system...? Thanks... PetesK From philippe.strauss at practeo.ch Thu Mar 11 04:46:46 2004 From: philippe.strauss at practeo.ch (Philippe Strauss) Date: Fri Mar 12 13:36:38 2004 Subject: [Tutor] hexadecimal to decimal Message-ID: <200403111046.46207.philippe.strauss@practeo.ch> Dear Python Tutor :^) I need to convert some number represented by hexadecimal STRINGS to decimal integers (then strings again, btw). Python 2.2.1 (#1, Apr 21 2002, 08:38:44) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print int(0xe7) 231 ok. >>> print int(0x00) 0 ok. >>> print int('1') 1 ok. >>> print int('0xe7') Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): 0xe7 >>> ko. what's the trick? thanks in advance. From qed at enterprise.net Thu Mar 11 06:35:55 2004 From: qed at enterprise.net (John Bibby) Date: Fri Mar 12 13:37:00 2004 Subject: [Tutor] jpg to doc conversion Message-ID: <NFBBIDGCMKOGANEBALDAEEFBILAA.qed@enterprise.net> Hi ! What was the outcome of this discussion please? - can I extract text out of a JPG file into DOC or TXT format? Thanks JOHN BIBBY (York, England) ============== [Tutor] jpg to doc conversion Shobhan Challa shobhan.challa at cybernetsoft.com Wed Nov 5 23:57:17 EST 2003 Previous message: [Tutor] newbie question on sys.path.append() Next message: [Tutor] RE: Tutor Digest, Vol 4, Issue 6 Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] ---------------------------------------------------------------------------- ---- Hi Alan, Yes, what i mean is typically the jpg files are images of text, and i want to convert them to Microsoft Word .doc format. Any ideas about any Open Source apps...?? Thanks and regards Schalla > Im new to python, I have an idea about converting jpg/jpeg image files > into doc files. The jpg files contain text and the text should be > converted into doc format. You mean the jpg files are images of text - eg from a scanner? And you want to perform a kind of OCR function on them to convert it to text, but in a Doc format (I assume you mean Microsoft Word .doc and not any other proprietary format called .doc - there are several!) Before we all start jumping in with ideas can you confirm that's what you mean please? Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031106/47bd0c36/attachm ent.html ---------------------------------------------------------------------------- ---- Previous message: [Tutor] newbie question on sys.path.append() Next message: [Tutor] RE: Tutor Digest, Vol 4, Issue 6 Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] ---------------------------------------------------------------------------- ---- More information about the Tutor mailing list From shitizb at yahoo.com Fri Mar 12 09:55:47 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Mar 12 13:37:15 2004 Subject: [Tutor] 2D list assignment Message-ID: <20040312145547.27437.qmail@web41504.mail.yahoo.com> Hi, This is a sample python code: a=((2,4),(4,2)) a[1][1]=4 Traceback (most recent call last): File "<pyshell#2>", line 1, in -toplevel- a[1][1]=4 TypeError: object doesn't support item assignment Is it a bug or am i missing the point? Shitiz --------------------------------- Do you Yahoo!? Yahoo! Search - Find what you’re looking for faster. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040312/3a72e5f3/attachment.html From vicki at stanfield.net Wed Mar 10 22:00:18 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Fri Mar 12 13:37:44 2004 Subject: [Tutor] loop based on a binary number? Message-ID: <1335.192.168.11.4.1078974018.squirrel@www.thepenguin.org> I am reading in binary data from an instrument using Python. The second field in my data is supposed to represent the length (number of bytes of binary data). Can I loop based on a binary? Or do I have to convert it? --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From William.Denson at Heidelberg.com Mon Mar 8 19:08:24 2004 From: William.Denson at Heidelberg.com (Denson, William HDi) Date: Fri Mar 12 13:38:00 2004 Subject: [Tutor] Changing fonts in Pmw ScrolledText object Message-ID: <940D296CF2177D4484C0C39632D8BAFE035EA9@rocms02003.nam.corp.heidelberg.com> How can I change font size in a Pmw ScrolledText aobject? Bill Denson Process Engineer Heidelberg Digital, LLC william.denson@heidelberg.com 585-512-8230 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040308/c9223f55/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Mar 12 13:59:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 12 14:00:26 2004 Subject: [Tutor] jpg to doc conversion In-Reply-To: <NFBBIDGCMKOGANEBALDAEEFBILAA.qed@enterprise.net> Message-ID: <Pine.LNX.4.44.0403121054230.16799-100000@hkn.eecs.berkeley.edu> On Thu, 11 Mar 2004, John Bibby wrote: > What was the outcome of this discussion please? - can I extract text out > of a JPG file into DOC or TXT format? I'm not sure if this may be useful, but there is an open source Optical Character Recognition system called GOCR: http://jocr.sourceforge.net/ Good luck to you! From project5 at redrival.net Fri Mar 12 14:11:18 2004 From: project5 at redrival.net (Andrei) Date: Fri Mar 12 14:15:00 2004 Subject: [Tutor] Re: For statement References: <47017DDDD14F20499CE7F361FABC1E10517824@maia.a.sol.no> Message-ID: <x7yu9phmxrj6$.7wd9jauxxozm.dlg@40tude.net> ?yvind Dale Sp?rck wrote on Thu, 11 Mar 2004 18:31:59 +0100: > I have a list: > > a= ['golden,','poodle,','flat,','retriever,'] > > I would like to remove the , after the word, with a for statement. However, the result doesn't end up as I like. I end up removing one of the items at the time or getting a "TypeError: list indices must be integers" error. > > I have tried tons of different versions such as: > >>>> for x in a: In this case x will be an item inside the list, so in the first run of the loop x='golden,', in the second run x='poodle,', etc. This is nice if you just need the items, but it's not nice if you want to manipulate the list because you have no idea where in the list you are. So in this case you need to loop by index. Items in a list are indexed starting with 0 and ending with len(MyList)-1. So in your list we have: len(a) == 4 a[0] == 'golden,' a[3] == 'retriever,' The range() function happens to work terribly well with lists, like this: for i in range(len(a)): print i, a[i] Try that in the Python interpreter. It's now obvious that using this loop, you could replace the print statement with the code which manipulates a[i]: the item at position i in list a. This is the stuff you're looking for, but I'll comment on the code you posted as well. > ... a[:] = a[:][:-1] a[:] simply returns a copy of a. So we can pretty much reduce this statement to: a = a[:-1] Which means all of a except the last item (last item has index -1 as well as index len(a)-1 ). Since you're looping over the list, you'll try to strip off one item of the list in every loop, so you'll end up with two items instead of 4. This also demonstrates that you should *never* manipulate a list used as loop control variable inside that sime loop. You were probably expecting to have four loops, but you only get two. What happens is this: At the start of the first loop: a = [0,1,2,3] ^ (^ indicates what the loop is reading from a; looping will continue until ^ reaches the end of the list) First loop: last item is stripped off: a = [0,1,2] ^ Loop is ended, position moves one forward: a = [0,1,2] ^ Second loop is started and executed, last item is stripped again: a = [0,1] ^ Second loop is done. But now a is only two items large which means that the ^ has reached the end after only two loops instead of 4 as we expected. Another tip: if you got those items from a single string like: a = 'golden, poodle, flat, retriever'.split() you could have used: a = 'golden, poodle, flat, retriever'.split(', ') to get the same results in one go. Last but not least: list comprehensions are terribly useful for this kind of list manipulations. You should have a look at them, they're quite nifty and very easy to use once you understand how they work. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From glingl at aon.at Fri Mar 12 14:23:28 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Mar 12 14:22:35 2004 Subject: [Tutor] 2D list assignment In-Reply-To: <20040312145547.27437.qmail@web41504.mail.yahoo.com> References: <20040312145547.27437.qmail@web41504.mail.yahoo.com> Message-ID: <40520E30.2050703@aon.at> Shitiz Bansal schrieb: > Hi, > This is a sample python code: > a=((2,4),(4,2)) > > > a[1][1]=4 > Traceback (most recent call last): > File "<pyshell#2>", line 1, in -toplevel- > a[1][1]=4 > TypeError: object doesn't support item assignment > Is it a bug or am i missing the point? It's not a bug! You create a data structure and then try to change it (i.e. it'S content). In Python there are several types of "sequences", among them: tuples, which are immutable and lists which are mutable. You used a tuple (of tuples), designated by parentheses () Instead you should have used lists, designated by brackets [], because only they are mutable: >>> a=[[2,4],[4,2]] >>> a[1][1]=4 >>> a [[2, 4], [4, 4]] See Docs: Python Library reference, 2.3.6 Sequence Types and especially 2.3.6.4 Mutable Sequence Types Regards, Gregor > Shitiz > ------------------------------------------------------------------------ > Do you Yahoo!? > Yahoo! Search - Find what you?re looking for faster. > <http://search.yahoo.com/?fr=ad-mailsig-home> > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From sigurd at 12move.de Fri Mar 12 14:53:09 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Mar 12 14:56:03 2004 Subject: [Tutor] hexadecimal to decimal In-Reply-To: <200403111046.46207.philippe.strauss@practeo.ch> (Philippe Strauss's message of "Thu, 11 Mar 2004 10:46:46 +0100") References: <200403111046.46207.philippe.strauss@practeo.ch> Message-ID: <m3ish97sl3.fsf@hamster.pflaesterer.de> On 11 Mar 2004, Philippe Strauss <- philippe.strauss@practeo.ch wrote: > Python 2.2.1 (#1, Apr 21 2002, 08:38:44) Did you read about the buffer overflow in Python 2.2? I'm not sure if it was fixed in 2.2.1. >>>> print int('0xe7') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ValueError: invalid literal for int(): 0xe7 > what's the trick? >>> print int('0xe7', 16) 231 I.e. tell int() what base to use (10 is the default base). >>> int('10') 10 >>> int('10', 16) 16 Karl -- Please do *not* send copies of replies to me. I read the list From abli at freemail.hu Fri Mar 12 17:14:07 2004 From: abli at freemail.hu (Abel Daniel) Date: Fri Mar 12 17:14:11 2004 Subject: [Tutor] Re: Changing fonts in Pmw ScrolledText object In-Reply-To: <940D296CF2177D4484C0C39632D8BAFE035EA9@rocms02003.nam.corp.heidelberg.com> (William HDi Denson's message of "Mon, 8 Mar 2004 19:08:24 -0500") References: <940D296CF2177D4484C0C39632D8BAFE035EA9@rocms02003.nam.corp.heidelberg.com> Message-ID: <E1B1uuu-0000K0-00@hooloovoo> "Denson, William HDi" writes: > How can I change font size in a Pmw ScrolledText aobject? (you might get a better answer from the pmw-general maillist at http://lists.sourceforge.net/lists/listinfo/pmw-general ) (not tested) ScrolledText is basically a wrapper around Tkinter.Text, so you can change the font size/color/etc. the same way as with a Tkinter.Text. I think you will need to 'create' a font with the needed size with import tkFont font = tkFont.Font(...) Then, you can add tags to the text with Tkinter.Text.tag_add(...) and you can set what a tag means with Tkinter.Text.tag_config(...). Pass your font object you created above to tag_config. There is a very good Tkinter reference 'Tkinter reference: a GUI for Python' in ps and pdf formats from http://www.nmt.edu/tcc/help/pubs/lang.html. Using fonts is at page 7, using tags in Tkinter.Text at 51, Tkinter.Text.tag_... methods are from page 56. -- Abel Daniel From alan.gauld at blueyonder.co.uk Fri Mar 12 20:20:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Mar 12 20:19:44 2004 Subject: [Tutor] hexadecimal to decimal References: <200403111046.46207.philippe.strauss@practeo.ch> Message-ID: <006801c40899$51ac6e90$6401a8c0@xp> > >>> print int('0xe7') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ValueError: invalid literal for int(): 0xe7 > >>> > > ko. > what's the trick? Add the base at the end: print int('0xe7',16) # 16 is base HTH, Alan G. From alan.gauld at blueyonder.co.uk Fri Mar 12 20:22:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Mar 12 20:21:41 2004 Subject: [Tutor] 2D list assignment References: <20040312145547.27437.qmail@web41504.mail.yahoo.com> Message-ID: <007001c40899$97507ef0$6401a8c0@xp> > a=((2,4),(4,2)) THese are tuples. You aren't allowed to change tuples, they are whats called immutable. You can create lists from them and change those, or just start with lists in the first place: a = [[2,4],[4,2]] a[1][1] = 4 Should now work. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Fri Mar 12 20:27:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Mar 12 20:27:01 2004 Subject: [Tutor] loop based on a binary number? References: <1335.192.168.11.4.1078974018.squirrel@www.thepenguin.org> Message-ID: <007501c4089a$55aacfe0$6401a8c0@xp> > I am reading in binary data from an instrument using Python. The second > field in my data is supposed to represent the length (number of bytes of > binary data). Can I loop based on a binary? Or do I have to convert it? Assuming the number you read in is an integer not a string you can use it directly. After all, all numbers in a computer are in binary. You ae reading a bit stream and somehow chunking those bits into pieces depending on your protocol. Presumably your protocol says the first N bits do one thing and the next M bits represent the size. The question is how many bits and in what representation. If it's 8 or 16 or 32 or even 64 is important in determining the number. Even the order of the bytes, is is big or little endian? But assuming you have read the bits into the right format to represent it as a number then you can use that number like any other: def getInput(bits): you define this bit... number = getInput(bitstream) for n in range(number): yada, yada.... Alan G. From mwagman at charter.net Fri Mar 12 20:37:46 2004 From: mwagman at charter.net (Mike Wagman) Date: Fri Mar 12 20:32:06 2004 Subject: [Tutor] Linux Home directory Message-ID: <1079141866.3758.5.camel@c66.190.54.168.jvl.wi.charter.com> How can I tell using python what the user that is running the softwares home directory is. I need it so I can finish a linux app and save config files (etc) in that directory. Thanks Mike From shitizb at yahoo.com Fri Mar 12 20:54:12 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Mar 12 20:54:17 2004 Subject: [Tutor] Linux Home directory In-Reply-To: <1079141866.3758.5.camel@c66.190.54.168.jvl.wi.charter.com> Message-ID: <20040313015412.95104.qmail@web41508.mail.yahoo.com> Hi, The required code is: import commands x= commands.getstatusoutput('echo $HOME') x[1] gives the value of required directory as string. Shitiz Mike Wagman <mwagman@charter.net> wrote: How can I tell using python what the user that is running the softwares home directory is. I need it so I can finish a linux app and save config files (etc) in that directory. Thanks Mike _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? Yahoo! Search - Find what you’re looking for faster. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040312/c7d1bedf/attachment.html From sandip at linux-delhi.org Fri Mar 12 21:37:59 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Fri Mar 12 21:42:44 2004 Subject: [Tutor] Linux Home directory In-Reply-To: <20040313015412.95104.qmail@web41508.mail.yahoo.com> References: <20040313015412.95104.qmail@web41508.mail.yahoo.com> Message-ID: <40527407.2000102@linux-delhi.org> Shitiz Bansal wrote: > Hi, > The required code is: > > import commands > x= commands.getstatusoutput('echo $HOME') > > x[1] gives the value of required directory as string. I think this is more portable. Should even work correctly on Windows. >>> import os.path >>> print os.path.expanduser("~") /home/sandip - Sandip -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From fredm at smartypantsco.com Fri Mar 12 21:53:59 2004 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Fri Mar 12 21:56:14 2004 Subject: [Tutor] For statement In-Reply-To: <47017DDDD14F20499CE7F361FABC1E10517824@maia.a.sol.no> Message-ID: <5.1.0.14.0.20040313133304.034cf130@192.168.1.1> At 06:31 PM 11/03/04 +0100, you wrote: >I have a list: > >a= [ 'golden,' , 'poodle,' , 'flat,' , 'retriever,' ] > >I would like to remove the , after the word, with a for statement. >However, the result doesn't end up as I like. I end up removing one of the >items at the time or getting a TypeError: list indices must be integers error. You say that "I would like to remove the , after the word, with a for statement." Maybe you have a special reason for using a for loop. Andrei has explained the logic error in your for loop construct. Andrei also mentioned list comprehension. You may not be aware of list comprehensions that allow you to create new lists from an existing list simply and quickly. A simple general syntax for list comprehension is [modified-x for x in y if condition], where: x is the name you give each element in your list y is your original list modified-x is either x (each element as it was in the original list) or some modified form of x (any valid Python operation) the condition is optional The output is a new list. For example, if you are sure that every word in your list a has a comma after it, you can write: newwordlist = [word[:-1] for word in a] You can also specify conditions in your list comprehension expression. For example, if you had words with and without commas and only wanted to find the words that had a comma at the end, you could write: commawords = [word[:-1] for word in a if word.endswith(',')] There are many more things you can do with list comprehension, and I have simplified the syntax a bit here for ease of explanation, but this should give you enough to get started with list comprehension. Hope this helps, Fred From schalla at vasoftware.com Sat Mar 13 01:06:31 2004 From: schalla at vasoftware.com (Shobhan) Date: Sat Mar 13 00:59:12 2004 Subject: [Tutor] jpg to doc conversion In-Reply-To: <Pine.LNX.4.44.0403121054230.16799-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0403121054230.16799-100000@hkn.eecs.berkeley.edu> Message-ID: <1079157991.1136.13.camel@shobs.cybernetsoft.com> And also, http://www.claraocr.org/ Best On Sat, 2004-03-13 at 00:29, Danny Yoo wrote: > On Thu, 11 Mar 2004, John Bibby wrote: > > > What was the outcome of this discussion please? - can I extract text out > > of a JPG file into DOC or TXT format? > > > I'm not sure if this may be useful, but there is an open source Optical > Character Recognition system called GOCR: > > http://jocr.sourceforge.net/ > > > Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From oyvind.sporck at eniro.no Sat Mar 13 05:20:36 2004 From: oyvind.sporck at eniro.no (=?iso-8859-1?Q?=D8yvind_Dale_Sp=F8rck?=) Date: Sat Mar 13 05:21:21 2004 Subject: [Tutor] cx_freeze problem Message-ID: <47017DDDD14F20499CE7F361FABC1E107C3009@maia.a.sol.no> I am trying to use cx_freeze on a program I have written. It opens Excel and starts with the following: import urllib, urllister from urllib import urlopen import re from string import lower from sets import Set from win32com.client import Dispatch I have both tried Py2exe and cx_freeze. Both gives me errors: Cx_freeze: Traceback (most recent call last): File "spy.py", line 6, in ? File "C:\Python23\Lib\site-packages\win32com\__init__ SetupEnvironment() File "C:\Python23\Lib\site-packages\win32com\__init__ vironment __path__.append( win32api.RegQueryValue(key, "Exten AttributeError: 'str' object has no attribute 'append' When I run it normally in Python, it works perfect. Is there some additional commands I have to give cx_freeze? C:\Python23\cx_freeze>FreezePython.exe --base-binary ./ConsoleBase.exe -install -dir spy -t spy.py Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040313/e39eaff5/attachment-0001.html From alan.gauld at blueyonder.co.uk Sat Mar 13 10:53:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Mar 13 10:53:17 2004 Subject: [Tutor] Linux Home directory References: <20040313015412.95104.qmail@web41508.mail.yahoo.com> Message-ID: <00a301c40913$49721b60$6401a8c0@xp> > import commands > x= commands.getstatusoutput('echo $HOME') > > x[1] gives the value of required directory as string. Or just use d = os.getenv('HOME') Alan G. From bgailer at alum.rpi.edu Sat Mar 13 20:14:43 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Mar 13 20:16:29 2004 Subject: [Tutor] 2D list assignment In-Reply-To: <20040312145547.27437.qmail@web41504.mail.yahoo.com> References: <20040312145547.27437.qmail@web41504.mail.yahoo.com> Message-ID: <6.0.0.22.0.20040313180608.02676048@mail.mric.net> At 07:55 AM 3/12/2004, Shitiz Bansal wrote: >Hi, >This is a sample python code: > > a[1][1]=4 >Traceback (most recent call last): > File "<pyshell#2>", line 1, in -toplevel- > a[1][1]=4 >TypeError: object doesn't support item assignment Examining... >>> a=((2,4),(4,2)) >>> type(a[1]) <type 'tuple'> Look up 3.2 The standard type hierarchy in the Language Reference. Here you find that tuples are immutable sequences, and: "Immutable sequences An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.) " Now try: >>> a=([2,4],[4,2]) >>> type(a[1]) <type 'list'> >>> a[1][1]=4 >>> a ([2, 4], [4, 4]) > >Is it a bug or am i missing the point? > >Shitiz > > >Do you Yahoo!? >Yahoo! Search - <http://search.yahoo.com/?fr=ad-mailsig-home>Find what >you're looking for faster. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040313/0c7490c3/attachment.html From marilyn at deliberate.com Sat Mar 13 20:44:15 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Mar 13 20:44:19 2004 Subject: [Tutor] Clueless Message-ID: <Pine.LNX.4.44.0403131722060.11161-100000@Kuna> I can't even give this one a good subject line, I'm so clueless. I'm trying to make something meaningful using __getattribute__. What a bear to stop all the infinite loops! But, finally, I have all that under control. So, my classes are: Logger object /|\ /|\ /|\ | | | Watched -------------------- | /|\ list | /|\ | | WatchedList --------------------- All is cool as long as I don't implement Logger.__del__ But if I do, crash-city when an object goes away: Exception exceptions.AttributeError: "'NoneType' object has no attribute 'close'" in <bound method WatchedList.__del__ of []> ignored If anyone has time and inclination, could you help? Thank you so much. Marilyn Davis #!/usr/bin/env python2.2 '''New style classes have __getattribute__ which intercept all references to attributes, ones that exist and don't exist. We'll make a Watched class that logs all accesses and assignments.''' import time class Logger: def __init__(self, name): self.file = open(name, 'w') def logit(self, entry): self.file.write(time.ctime(time.time())) self.file.write('\n' + entry + '\n') self.file.flush() # def __del__(self): # self.file.close() class Watched(object, Logger): def __init__(self, log_name): self.log = Logger(log_name + '.log') def __getattribute__(self, attrname): # print 'getattribute called on', attrname ret = object.__getattribute__(self, attrname) if attrname != 'log' and attrname[:2] != '__': self.log.logit(attrname + ' accessed, value = ' + str(ret)) return ret def __getattr__(self, attrname): '''Called when attrname is not in __dict__ already.''' if attrname != 'log' and attrname[:2] != '__': self.log.logit('Attempt to access ' + attrname + ' which does not exist.') self.__dict__[attrname] = None return None def __setattr__(self, attrname, value): if attrname != 'log' and attrname[:2] != '__': try: self.log.logit(attrname + ' changed from ' + self.__dict__[attrname] + ' to ' + str(value)) except KeyError: self.log.logit(attrname + ' created = ' + str(value)) self.__dict__[attrname] = value class WatchedList(Watched, list): def __init__(self, log_name, init_list = None): Watched.__init__(self, log_name) if init_list: list.__init__(self, init_list) assets = WatchedList('assets') dir(assets) ############################################################ # OUTPUT: # Everything works as expected if there's no Watched.__del__: # # bash-2.05a$ python2.2 -i att5.py # >>> assets # [] # >>> assets += [2,4,6] # >>> assets[0] # 2 # >>> assets.max = max(assets) # >>> assets.max # 6 # >>> del assets # >>> # The assets.log: # Sat Mar 13 17:34:20 2004 # max created = 6 # Sat Mar 13 17:34:22 2004 # max accessed, value = 6 ################################### # # But with Watched.__del__ there: # bash-2.05a$ ./att5.py # Exception exceptions.AttributeError: "'NoneType' object has no attribute 'close'" in <bound method WatchedList.__del__ of []> ignored # # And the assets.log: # Sat Mar 13 17:36:57 2004 # max created = 6 # Sat Mar 13 17:37:00 2004 # max accessed, value = 6 # Sat Mar 13 17:37:03 2004 # Attempt to access file which does not exist. From cspears2002 at yahoo.com Sat Mar 13 22:25:15 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sat Mar 13 22:25:23 2004 Subject: [Tutor] Unix shell through Python Message-ID: <20040314032515.1617.qmail@web12406.mail.yahoo.com> I'm using a Windows 2000 machine with Python installed on it. I want to brush up on my shell scripting. Has anyone created an Unix shell that runs through Python? -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 "The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter From rmkrauter at yahoo.com Sat Mar 13 23:02:54 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat Mar 13 23:08:41 2004 Subject: [Tutor] Clueless In-Reply-To: <Pine.LNX.4.44.0403131722060.11161-100000@Kuna> References: <Pine.LNX.4.44.0403131722060.11161-100000@Kuna> Message-ID: <1079236974.4980.19.camel@vaio> On Sat, 2004-03-13 at 20:44, Marilyn Davis wrote: > I can't even give this one a good subject line, I'm so clueless. > > I'm trying to make something meaningful using __getattribute__. > What a bear to stop all the infinite loops! > > But, finally, I have all that under control. > > So, my classes are: > > Logger object > /|\ /|\ /|\ > | | | > Watched -------------------- | > /|\ list > | /|\ > | | > WatchedList --------------------- > > All is cool as long as I don't implement Logger.__del__ > > But if I do, crash-city when an object goes away: > > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'close'" in <bound method WatchedList.__del__ of []> ignored > > If anyone has time and inclination, could you help? > > Thank you so much. > > Marilyn Davis > > #!/usr/bin/env python2.2 > '''New style classes have __getattribute__ which intercept > all references to attributes, ones that exist and don't > exist. We'll make a Watched class that logs all accesses and > assignments.''' > > import time > > class Logger: > def __init__(self, name): > self.file = open(name, 'w') > def logit(self, entry): > self.file.write(time.ctime(time.time())) > self.file.write('\n' + entry + '\n') > self.file.flush() > # def __del__(self): > # self.file.close() > Hi Marilyn, I added this to the Watched class, and it seemed to help: def __del__(self): Logger.__del__(self.log) Also, I wouldn't use 'file' as an attribute name. It's in synonym for 'open'. Hope that helps. Rich From darnold02 at sprynet.com Sat Mar 13 23:12:05 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sat Mar 13 23:10:47 2004 Subject: [Tutor] Unix shell through Python In-Reply-To: <20040314032515.1617.qmail@web12406.mail.yahoo.com> References: <20040314032515.1617.qmail@web12406.mail.yahoo.com> Message-ID: <C0CA7FCE-756D-11D8-88B4-000A95C4F940@sprynet.com> On Mar 13, 2004, at 9:25 PM, Christopher Spears wrote: > I'm using a Windows 2000 machine with Python installed > on it. I want to brush up on my shell scripting. Has > anyone created an Unix shell that runs through Python? > > -Chris > You might want to take a look at cygwin at www.cygwin.com. It's about as close as you can come to working under Linux on Windows. HTH, Don From marilyn at deliberate.com Sun Mar 14 03:27:03 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Mar 14 03:27:11 2004 Subject: [Tutor] Clueless In-Reply-To: <1079236974.4980.19.camel@vaio> Message-ID: <Pine.LNX.4.44.0403140021120.11161-100000@Kuna> On Sat, 13 Mar 2004, Rich Krauter wrote: > On Sat, 2004-03-13 at 20:44, Marilyn Davis wrote: > > I can't even give this one a good subject line, I'm so clueless. > > > > I'm trying to make something meaningful using __getattribute__. > > What a bear to stop all the infinite loops! > > > > But, finally, I have all that under control. > > > > So, my classes are: > > > > Logger object > > /|\ /|\ /|\ > > | | | > > Watched -------------------- | > > /|\ list > > | /|\ > > | | > > WatchedList --------------------- > > > > All is cool as long as I don't implement Logger.__del__ > > > > But if I do, crash-city when an object goes away: > > > > Exception exceptions.AttributeError: "'NoneType' object has no > > attribute 'close'" in <bound method WatchedList.__del__ of []> ignored > > > > If anyone has time and inclination, could you help? > > > > Thank you so much. > > > > Marilyn Davis > > > > #!/usr/bin/env python2.2 > > '''New style classes have __getattribute__ which intercept > > all references to attributes, ones that exist and don't > > exist. We'll make a Watched class that logs all accesses and > > assignments.''' > > > > import time > > > > class Logger: > > def __init__(self, name): > > self.file = open(name, 'w') > > def logit(self, entry): > > self.file.write(time.ctime(time.time())) > > self.file.write('\n' + entry + '\n') > > self.file.flush() > > # def __del__(self): > > # self.file.close() > > > > Hi Marilyn, > > I added this to the Watched class, and it seemed to help: > > def __del__(self): > Logger.__del__(self.log) Did you do anything else? I still get the same crash. You don't? What version of python? > > Also, I wouldn't use 'file' as an attribute name. It's in synonym for > 'open'. I didn't know that. Thank you. I changed that too. But I'm still stumped. Thank you for beating your head against this too. Marilyn > > Hope that helps. > > Rich > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From shitizb at yahoo.com Sun Mar 14 06:21:00 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sun Mar 14 06:21:05 2004 Subject: [Tutor] Internship Message-ID: <20040314112100.34387.qmail@web41509.mail.yahoo.com> Hello, I am a 3rd year Civil Engineering student at Indian Institute of Technology, Delhi. I am looking for an internship in the industry in the coming summer vacations. I have a strong inclination towards programming.So instead of the regular internships available for Civil Engineering student I was looking forward to something related to software development for construction industry.Unfortunately i have not been very successful in my search so far. If anybody of you have any idea about any such industry please do let me know. My skills in brief: C++/Java, perl , php learning Python Fmod graphics library. If anybody of you is interested please mail me for my detailed resume. Yours sincerely, Shitiz Bansal Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040314/1a461789/attachment.html From thorsten at thorstenkampe.de Sun Mar 14 10:58:07 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun Mar 14 11:01:16 2004 Subject: [Tutor] Re: Unix shell through Python References: <20040314032515.1617.qmail@web12406.mail.yahoo.com> Message-ID: <qjcvrgr49702$.dlg@thorstenkampe.de> * Christopher Spears (2004-03-14 04:25 +0100) > I'm using a Windows 2000 machine with Python installed > on it. I want to brush up on my shell scripting. Has > anyone created an Unix shell that runs through Python? IPython From GREENDAY31087 at aol.com Sun Mar 14 14:00:15 2004 From: GREENDAY31087 at aol.com (GREENDAY31087@aol.com) Date: Sun Mar 14 14:04:19 2004 Subject: [Tutor] what do I use for this? Message-ID: <1e9.1b57012d.2d8605bf@aol.com> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 2553 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040314/2a075969/attachment-0001.jpe From rmkrauter at yahoo.com Sun Mar 14 09:38:21 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sun Mar 14 14:16:28 2004 Subject: [Tutor] Clueless In-Reply-To: <Pine.LNX.4.44.0403140021120.11161-100000@Kuna> References: <Pine.LNX.4.44.0403140021120.11161-100000@Kuna> Message-ID: <1079275101.5613.32.camel@vaio> On Sun, 2004-03-14 at 03:27, Marilyn Davis wrote: > On Sat, 13 Mar 2004, Rich Krauter wrote: > > On Sat, 2004-03-13 at 20:44, Marilyn Davis wrote: > > > Did you do anything else? I still get the same crash. You don't? > > > What version of python? Marilyn, My python version is 2.2.2. I just double-checked and it seems to be working ok. I've posted the code below; and below that I posted a diff on the two versions. I only changed all 'file' to 'f', and added the __del__ method to the Watched class. Hopefully if you paste the code below into a file and run it, it'll work. Rich #!/usr/bin/env python2.2 '''New style classes have __getattribute__ which intercept all references to attributes, ones that exist and don't exist. We'll make a Watched class that logs all accesses and assignments.''' import time class Logger: def __init__(self, name): self.f = open(name, 'w') def logit(self, entry): self.f.write(time.ctime(time.time())) self.f.write('\n' + entry + '\n') self.f.flush() def __del__(self): self.f.close() class Watched(object, Logger): def __init__(self, log_name): self.log = Logger(log_name + '.log') def __getattribute__(self, attrname): # print 'getattribute called on', attrname ret = object.__getattribute__(self, attrname) if attrname != 'log' and attrname[:2] != '__': self.log.logit(attrname + ' accessed, value = ' + str(ret)) return ret def __getattr__(self, attrname): '''Called when attrname is not in __dict__ already.''' if attrname != 'log' and attrname[:2] != '__': self.log.logit('Attempt to access ' + attrname + ' which does not exist.') self.__dict__[attrname] = None return None def __setattr__(self, attrname, value): if attrname != 'log' and attrname[:2] != '__': try: self.log.logit(attrname + ' changed from ' + self.__dict__[attrname] + ' to ' + str(value)) except KeyError: self.log.logit(attrname + ' created = ' + str(value)) self.__dict__[attrname] = value def __del__(self): Logger.__del__(self.log) class WatchedList(Watched, list): def __init__(self, log_name, init_list = None): Watched.__init__(self, log_name) if init_list: list.__init__(self, init_list) assets = WatchedList('assets') dir(assets) Diff on the two versions: 11c11 < self.f = open(name, 'w') --- > self.file = open(name, 'w') 13,17c13,17 < self.f.write(time.ctime(time.time())) < self.f.write('\n' + entry + '\n') < self.f.flush() < def __del__(self): < self.f.close() --- > self.file.write(time.ctime(time.time())) > self.file.write('\n' + entry + '\n') > self.file.flush() > # def __del__(self): > # self.file.close() 45,47d44 < def __del__(self): < Logger.__del__(self.log) < From darnold02 at sprynet.com Sun Mar 14 14:29:33 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sun Mar 14 14:28:13 2004 Subject: [Tutor] what do I use for this? In-Reply-To: <1e9.1b57012d.2d8605bf@aol.com> References: <1e9.1b57012d.2d8605bf@aol.com> Message-ID: <EC30C190-75ED-11D8-88B4-000A95C4F940@sprynet.com> On Mar 14, 2004, at 1:00 PM, GREENDAY31087@aol.com wrote: > I want to make a script that asks for a port number and returns its > meaning. Since there are a few thousand ports, I just want to start > with common ones. What would I use in this program? An array(s)?<Jimmy > Page .jpg>_______________________________________________ > Although you could use a list (Python's version of an array), you're better off using a dictionary here: >>> ports = {80:'HTTP', 70: 'Gopher', 79: 'finger'} >>> print ports[80] HTTP That way, you won't be wasting memory with a list thousands of items long were only a relative few are actually populated. HTH, Don -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 728 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040314/bd7569e9/attachment.bin From sigurd at 12move.de Sun Mar 14 14:32:34 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Sun Mar 14 14:38:20 2004 Subject: [Tutor] what do I use for this? In-Reply-To: <1e9.1b57012d.2d8605bf@aol.com> (GREENDAY's message of "Sun, 14 Mar 2004 14:00:15 EST") References: <1e9.1b57012d.2d8605bf@aol.com> Message-ID: <m3vfl7z0n3.fsf@hamster.pflaesterer.de> An unnamed person wrote: > I want to make a script that asks for a port number and returns its meaning. > Since there are a few thousand ports, I just want to start with common ones. > What would I use in this program? An array(s)? A dictionary. (BTW please don't post HTML and jpg attachments) Karl -- Please do *not* send copies of replies to me. I read the list From op73418 at mail.telepac.pt Sun Mar 14 15:37:54 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Mar 14 15:35:28 2004 Subject: [Tutor] Clueless In-Reply-To: <Pine.LNX.4.44.0403131722060.11161-100000@Kuna> References: <Pine.LNX.4.44.0403131722060.11161-100000@Kuna> Message-ID: <ugg95054o4gkh94ekvrjcg92ndcjgnec4c@4ax.com> Em Sat, 13 Mar 2004 17:44:15 -0800 (PST), Marilyn Davis <marilyn@deliberate.com> fed this fish to the penguins: > >I can't even give this one a good subject line, I'm so clueless. > >I'm trying to make something meaningful using __getattribute__. >What a bear to stop all the infinite loops! > >But, finally, I have all that under control. > >So, my classes are: > > Logger object > /|\ /|\ /|\ > | | | > Watched -------------------- | > /|\ list > | /|\ > | | > WatchedList --------------------- > >All is cool as long as I don't implement Logger.__del__ > >But if I do, crash-city when an object goes away: > >Exception exceptions.AttributeError: "'NoneType' object has no >attribute 'close'" in <bound method WatchedList.__del__ of []> ignored > >If anyone has time and inclination, could you help? I do not know what is the problem, so I suggest you post to comp.lang.py if no one elese can help. Still there are a few glitches with your code -- see below. > >Thank you so much. > >Marilyn Davis > >#!/usr/bin/env python2.2 >'''New style classes have __getattribute__ which intercept >all references to attributes, ones that exist and don't >exist. We'll make a Watched class that logs all accesses and >assignments.''' > >import time > >class Logger: > def __init__(self, name): > self.file = open(name, 'w') > def logit(self, entry): > self.file.write(time.ctime(time.time())) > self.file.write('\n' + entry + '\n') > self.file.flush() ># def __del__(self): ># self.file.close() > Python calls __del__ the object is about to be destroyed (it's refcount is 0). There are problems when the object participates in a cycle - in that case Python's garbage collector refuses to dispose of the cycle because of the existence of __del__. All told, this means in practice that __del__ is almost always a bad choice for managing external resources. Just free them explicitely -- that is, call close when you're done with the resource. >class Watched(object, Logger): > def __init__(self, log_name): > self.log = Logger(log_name + '.log') > > def __getattribute__(self, attrname): ># print 'getattribute called on', attrname > ret = object.__getattribute__(self, attrname) > if attrname != 'log' and attrname[:2] != '__': > self.log.logit(attrname + ' accessed, value = ' + str(ret)) > return ret > > def __getattr__(self, attrname): > '''Called when attrname is not in __dict__ already.''' > if attrname != 'log' and attrname[:2] != '__': > self.log.logit('Attempt to access ' + attrname + ' which does not exist.') > self.__dict__[attrname] = None > return None > __getattr__ will *never* be called so this is not needed. Recall: __getattribute__ gets called on *every* attribute lookup, so it *always* overrides __getattr__. This means that, even for self.__dict__ __getattribute__ is called! It is a very tricky method, easy to get into infinite loops. I don't have anything else to point right now, I'm out of time but I'll still try to have a look at the code later and see if anything is wrong. If I find out anything I'll post here on the list. With my best regards, G. Rodrigues From tolis at softhome.net Sun Mar 14 16:12:32 2004 From: tolis at softhome.net (=?iso-8859-7?B?0/Tl8ePf7/UgwfDv8/T86+fy?=) Date: Sun Mar 14 16:39:46 2004 Subject: [Tutor] cannot import win32com.client Message-ID: <000001c40a09$22b5cde0$5108f9d5@nemesis> Take a look: >>> import win32com.client Traceback (most recent call last): File "<interactive input>", line 1, in ? File "C:\Python23\lib\site-packages\win32com\__init__.py", line 6, in ? import pythoncom File "C:\Python23\lib\site-packages\pythoncom.py", line 3, in ? pywintypes.__import_pywin32_system_module__("pythoncom", globals()) AttributeError: 'module' object has no attribute '__import_pywin32_system_module__' >>> I use: WinXP PRO Greek version 5.01.2600 Service Pack 1 And: PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammon (mhammond@skippinet. com.au) - see 'Help/About PythonWin' for further copyright information. When I installed "win32all-163.exe" I got 3 errors: 1) Registration of the AXScript Engine COM server failed. Installation will continue, but this server will require manual registration before it will function exceptions.AttributeError: 'module' object has no attribute '__import_pywin32_system_module__' 2) Registration of the Python Interpreter COM server failed. Installation will continue, but this server will require manual registration before it will function exceptions.AttributeError: 'module' object has no attribute 'com_error' 3) Registration of the Python Dictionary COM server failed. Installation will continue, but this server will require manual registration before it will function exceptions.ImportError: cannot import name DISPATCH_METHOD Any time I try to reinstall I get the same 3 errors... Any solution? From alan.gauld at blueyonder.co.uk Sun Mar 14 17:48:17 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 14 21:34:20 2004 Subject: [Tutor] Clueless References: <Pine.LNX.4.44.0403131722060.11161-100000@Kuna> Message-ID: <001801c40a16$716fd810$6401a8c0@xp> > I can't even give this one a good subject line, I'm so clueless. I'm not totally sure on this one but a scan of the code shows up one strangeness at least: > > Logger object > /|\ /|\ /|\ > | | | > Watched -------------------- | > /|\ list > | /|\ > | | > WatchedList --------------------- > > All is cool as long as I don't implement Logger.__del__ > WAtched is a subnclass of Logger so inherits Loggers del method. But... > class Watched(object, Logger): > def __init__(self, log_name): > self.log = Logger(log_name + '.log') INstead of initisalising the inherited file you choose to also have a Logger object have a reference to a logger. Thats OK of course but it does mean we eff4ectively have two Logger instances in the program each with a __del__ defined, but only one of them with file defined... > class WatchedList(Watched, list): > def __init__(self, log_name, init_list = None): > Watched.__init__(self, log_name) > if init_list: > list.__init__(self, init_list) And Watched List also drives indirectly from Logger, so instsances of this will also have a __del__ method, and they use the Watched initialiser so that they too have a loger attached, so again two instances of Leggoer exist... > assets = WatchedList('assets') So assets is a logger and references a logger... > # >>> assets > # [] > # >>> assets += [2,4,6] > # >>> assets[0] > # 2 > # >>> assets.max = max(assets) > # >>> assets.max > # 6 > # >>> del assets So we now remove the reference to assets which gets GC'd, including it's associated logger object. The associated object has a file so its del works OK but assets never did have a valid file attribute so closing it will cause a problem.... Maybe your del should look like def __del__(self): if self.file: self.file.close() At least, I think thats the problem.... Although maybe its more to do with the design. Is Watched really a logger? Or does it just use one? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sun Mar 14 17:50:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 14 21:34:42 2004 Subject: [Tutor] Unix shell through Python References: <20040314032515.1617.qmail@web12406.mail.yahoo.com> Message-ID: <001d01c40a16$c98a2a50$6401a8c0@xp> > I'm using a Windows 2000 machine with Python installed > on it. I want to brush up on my shell scripting. Has > anyone created an Unix shell that runs through Python? There was a project at one time to implement all the Unix commands in Python but I think it died off. But then why not just download Cygwin? Then you get a real Bash shell and all the other Unix commands native on Windows (including X if you really want!). No Unix hacker should ever be without Cygwin when on a windows box... Alan G. From alan.gauld at blueyonder.co.uk Sun Mar 14 17:53:14 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 14 21:34:50 2004 Subject: [Tutor] what do I use for this? References: <1e9.1b57012d.2d8605bf@aol.com> Message-ID: <002d01c40a17$223bda90$6401a8c0@xp> > I want to make a script that asks for a port number and returns its meaning. > Since there are a few thousand ports, I just want to start with common ones. > What would I use in this program? An array(s)? > What do you mean by its meaning? Ports can be used for anything. Even the common assignments (port 25 for SMTP etc) can be changed - although they shouldn't be!. How would you define the meaning of a port? Alan G. From kp8 at mac.com Sun Mar 14 23:02:15 2004 From: kp8 at mac.com (kevin parks) Date: Sun Mar 14 23:03:43 2004 Subject: [Tutor] Help with Data representations Message-ID: <8BB569F9-7635-11D8-8EE5-003065555ABC@mac.com> hi all! I have some data that i want to get a handle on. My data is (so far) is formatted thusly: m219a = [5,0,10,7] m219b = [5,0,10,7,2] m221a = [5,6] m221b = [5,6,7] m222a = [0,10] m222b = [0,10,2] m223a = [2,8] The m291a is the variable name (but i am thinking that it also needs to be added to the list or the input list turned in to a dictionary?).... I am not sure what the best way is, but let me first explain what that data is.. the m291a refers to a point on my time line and the list contains the values for that item. Sometimes there are more actually a few items that go on that point on the timeline so that is why there is a 219a and 219b. The m is just to make it a legal variable name. So it turns out that i have several hundreds of these items, but only about 60 or so unique items. I am able to map, sort, and normalize my data and all the other massaging that i want to do and spit it all out. Now it turns out that what i really would find helpful is to find out where each item is in a sort of histogram so that i get a list of all my 60 or so unique items and each m000x number for where it appears and finally a tally for how often it appears in a kind of score board. So that i get something like: 1. [0,10,2] : m222b, m381, m129c : 3 2. [5,6,7] : m221b, m19a, m411b, m367b, m377a : 6 with apologies to the list i will post a much abbreviated version of my script so that the tutors will better be able to understand my query.. cheers, kevin -- snip --- #!/usr/bin/env python from normtest import * from interval import * from unique2 import unique def printout(seq): print '-' * 62 print seq,"\t",step1(seq),"\t", (min(ordering(rotations(step1(seq))))[3]),"\t", optional(min(ordering(rotations(step1(seq))))[3]) def test(): m1 = [8, 3, 5, 4] m7 = [4, 3, 2, 2] m14 = [8, 3, 7, 5] m18 = [10, 2, 8, 7] m20 = [10, 0, 5, 7] m22 = [10, 2, 8, 7] m24 = [7, 9, 3, 8] m28 = [10, 0, 5, 7] m29 = [10, 11] m30 = [8, 3, 5, 4] m32 = [5, 0, 11, 7] m34 = [8, 3, 7, 9] m36a = [5, 4, 3, 1] m36b = [5, 4, 3, 1, 7] m37a = [0, 8, 2, 4, 9, 10, 1] m37b = [0, 8, 2, 4, 9, 10, 1, 6] m39a = [8, 10, 1, 9] m39b = [8, 10, 1, 9, 7] m41a = [2, 0, 3, 1] m41b = [2, 0, 3, 1, 6] page2 = [m1, m7, m14, m18, m20, m22, m24, m28, m29, m30, m32, m34, m36a, m36b, m37a, m37b, m39a, m39b, m41a, m41b] # ~~~~~~~~~~~~~~~~~~~~ page 3 ~~~~~~~~~~~~~~~~~~~~ m43 = [3, 2, 4] m44a = [0, 8, 2, 4, 9, 10, 1] m44b = [0, 8, 2, 4, 9, 10, 1, 6] m45a = [5, 4, 3, 1] m45b = [5, 4, 3, 1, 7] m47a = [5,0,3,1] m47b = [5,4,3,1] m47c = [5,4,3,1,7] m49a = [8,10,1,9] m49b = [8,10,1,9,5] m51 = [5,0,3,1] m51b = [5,0,3,1,7] m53 = [8,3,7,9] m54a = [5,10,7,0] m54b = [5,10,7,0, 2] m55 = [0,8,2,4,9,10,1] m55b = [0,8,2,4,9,10,1,6] m57a = [5,0,3,1] m57b = [5,4,3,1] m59a = [5,4,3,1] m59b = [5,4,3,1,7] m61 = [2,4,3] m62a = [10,2,8,7] m62b = [10,2,8,7,0] m63 = [10,11] m64 = [8,5,7,10,2] m64b = [8,5,7,10,2, 9] m66 = [0,1,6] m68a = [5,0,3,1] m86b = [5,0,3,1,7] m70a = [8,9,10,1] m70b = [8,9,10,1,7] m71 = [2,4,11,10] m72 = [0,1,6,5] m74 = [8,2,5,4] m78 = [8,7,10,2] m80 = [11,8,6,1] m82a = [7,2,6,8] m82b = [10,9,0,11] m82c = [10,9,0,11,4] m84a = [10,8,2,7] m84b = [10,8,2,7,0,5] m85 = [0,1,6,5] page3 = [m43, m44a, m44b, m45a, m45b, m47a, m47b, m47c, m49a, m49b, m51, m51b, m53, m54a, m54b, m55, m55b, m57a, m57b, m59a, m59b, m61, m62a, m62b, m63, m64, m64b, m66, m68a, m86b, m70a, m70b, m71, m72, m74, m78, m80, m82a, m82b, m82c, m84a, m84b, m85] # -+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+- all = page2+page3 # tr = [] outlist = [] # first normalize and map everything and pack it in a list for j in all: if len(j) > 1: tr = optional(min(ordering(rotations(step1(j))))[3]) outlist.append(tr) # now let's find all the unique items foo = unique(outlist) unique_item_count = 1 # and then print them out (while counting how many there are) for item in foo: print unique_item_count, "\t",item unique_item_count = unique_item_count + 1 pages = [page2, page3] pp = 0 for page in pages: print '=' * 62 print " --- Page ", pp+2, ": " print '=' * 62 print "set\tmap & sort:\tnormalized:\tto zero:" pp = pp + 1 # print page for item in page: printout(item) if __name__ == "__main__": test() # -- From marilyn at deliberate.com Sun Mar 14 23:12:25 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Mar 14 23:12:32 2004 Subject: [Tutor] Clueless In-Reply-To: <001801c40a16$716fd810$6401a8c0@xp> Message-ID: <Pine.LNX.4.44.0403141932380.11161-100000@Kuna> On Sun, 14 Mar 2004, Alan Gauld wrote: > > I can't even give this one a good subject line, I'm so clueless. > > I'm not totally sure on this one but a scan of the code shows > up one strangeness at least: > > > > > Logger object > > /|\ /|\ /|\ > > | | | > > Watched -------------------- | > > /|\ list > > | /|\ > > | | > > WatchedList --------------------- > > > > All is cool as long as I don't implement Logger.__del__ > > > > WAtched is a subnclass of Logger so inherits Loggers del method. > But... > > > class Watched(object, Logger): > > def __init__(self, log_name): > > self.log = Logger(log_name + '.log') Oh! Duh! Good eye! > > INstead of initisalising the inherited file you choose to also > have a Logger object have a reference to a logger. Thats OK of > course but it does mean we eff4ectively have two Logger instances > in the program each with a __del__ defined, but only one of them > with file defined... Not wonder it was so confused. And that's all it was! Alan, you are great! And thank you Gon?alo Rodrigues. > Python calls __del__ the object is about to be destroyed (it's > refcount is 0). There are problems when the object participates in a > cycle - in that case Python's garbage collector refuses to dispose of > the cycle because of the existence of __del__. > > All told, this means in practice that __del__ is almost always a bad > choice for managing external resources. Just free them explicitely -- > that is, call close when you're done with the resource. Happily, python wasn't confused without reason. I can keep my call to close in Logger.__del__ and all is well. > > __getattr__ will *never* be called so this is not needed. Recall: > __getattribute__ gets called on *every* attribute lookup, so it > *always* overrides __getattr__. No. __getattribute__ calls __getattr__ when the attribute doesn't exist. I was surprised by this too. Here I make both methods verbose: bash-2.05a$ python2.2 -i att5.py getattribute called on __dict__ >>> assets [] >>> x = assets.x getattribute called on x getattr called on x getattribute called on logit getattribute called on log_file getattribute called on log_file getattribute called on log_file getattribute called on __dict__ >>> del assets >>> > This means that, even for self.__dict__ > __getattribute__ is called! It is a very tricky method, easy to get > into infinite loops. Yes. It was a difficult. This code prevented loops on self.logit and __dict__ by not allowing the call to self.logit or self.__dict__ when the attribute was self.logit or self.__dict__. Note that this code is duplicated 3 times. I couldn't find any way to put it in a method that didn't loop. And I don't know why. def __getattribute__(self, attrname): print 'getattribute called on', attrname ret = object.__getattribute__(self, attrname) if attrname[:3] != 'log' and attrname[:2] != '__': self.logit(attrname + ' accessed, value = ' + str(ret)) return ret Anyhow, here's the whole (working) code, in case anyone has any more thoughts about it. It's sort of silly because it doesn't log accesses to the list. All criticisms and suggestions gratefully accepted. #!/usr/bin/env python2.2 '''New style classes have __getattribute__ which intercept all references to attributes, ones that exist and don't exist. We'll make a Watched class that logs all accesses and assignments.''' import time class Logger(object): def __init__(self, name): self.log_file = open(name, 'w') def logit(self, entry): self.log_file.write(time.ctime(time.time())) self.log_file.write('\n' + entry + '\n') self.log_file.flush() def __del__(self): self.log_file.close() class Watched(object, Logger): def __init__(self, log_name): Logger.__init__(self, log_name + '.log') def __getattribute__(self, attrname): print 'getattribute called on', attrname ret = object.__getattribute__(self, attrname) if attrname[:3] != 'log' and attrname[:2] != '__': self.logit(attrname + ' accessed, value = ' + str(ret)) return ret def __getattr__(self, attrname): '''Called when attrname is not in __dict__ already.''' print 'getattr called on', attrname if attrname[:3] != 'log' and attrname[:2] != '__': self.logit('Attempt to access ' + attrname + ' which does not exist.') self.__dict__[attrname] = None return None def __setattr__(self, attrname, value): if attrname[:3] != 'log' and attrname[:2] != '__': try: self.logit(attrname + ' changed from ' + self.__dict__[attrname] + ' to ' + str(value)) except KeyError: self.logit(attrname + ' created = ' + str(value)) self.__dict__[attrname] = value class WatchedList(Watched, list): def __init__(self, log_name, init_list = None): Watched.__init__(self, log_name) if init_list: list.__init__(self, init_list) assets = WatchedList('assets') ############################################################ # OUTPUT: # bash-2.05a$ python2.2 -i att5.py # >>> assets # [] # >>> assets += [1,2,3] # >>> assets.x = 3 # >>> assets.sort() # >>> assets # [1, 2, 3] # >>> del assets # >>> # bash-2.05a$ From brian at dungeoncrawl.org Sun Mar 14 23:15:16 2004 From: brian at dungeoncrawl.org (Brian Christopher Robinson) Date: Sun Mar 14 23:15:24 2004 Subject: [Tutor] Cookies In-Reply-To: <E1B2jM2-0003o4-Vw@mail.python.org> Message-ID: <5.2.0.9.0.20040314231139.020033d8@localhost> I have a simple Python program that is used to back up entries on a weblogging site called Livejournal. Livejournal allows you to make posts that aren't visible to the public, so you need to be logged into your account to see them. I need to make my tool able to log in to the site, but I'm not sure how to do that. I think it will involve cookies but I don't know how to go about putting cookies into a Python program. I did find a cookie class in the documentation on python.org, but I couldn't figure out what to do with it. Any help or pointers on where to learn more about this stuff would be appreciated. From greg at thewhittiers.com Mon Mar 15 03:19:12 2004 From: greg at thewhittiers.com (Greg Whittier) Date: Mon Mar 15 03:18:20 2004 Subject: [Tutor] Help with Data representations In-Reply-To: <8BB569F9-7635-11D8-8EE5-003065555ABC@mac.com> References: <8BB569F9-7635-11D8-8EE5-003065555ABC@mac.com> Message-ID: <1079338751.1983.22.camel@localhost.localdomain> I'm kind of new to this, but I'll take a stab. My inclination would be to use a dictionary with a tuple as the key. In other words, m219a = [5,0,10,7] becomes m[(219,0)] = [5,0,10,7] m219b = [5,0,10,7,2] becomes m[(219,1)] = [5,0,10,7,2] Because it's keyed with a tuple you can sort on this. If I understand the latter part of the question about the histogram, the following should work mvaldict = {} for key, val in m.items(): mvaldict[tuple(val)] = \ mvaldict.setdefault(tuple(val),[]).append(key) # print results for key in mvaldict.keys() print key, mvaldict[key], len(mvaldict[key]) Hope this helps, Greg On Sun, 2004-03-14 at 23:02, kevin parks wrote: > hi all! > > I have some data that i want to get a handle on. My data is (so far) is > formatted thusly: > > m219a = [5,0,10,7] > m219b = [5,0,10,7,2] > m221a = [5,6] > m221b = [5,6,7] > m222a = [0,10] > m222b = [0,10,2] > m223a = [2,8] > > The m291a is the variable name (but i am thinking that it also needs to > be added to the list or the input list turned in to a dictionary?).... > I am not sure what the best way is, but let me first explain what that > data is.. the m291a refers to a point on my time line and the list > contains the values for that item. Sometimes there are more actually a > few items that go on that point on the timeline so that is why there is > a 219a and 219b. The m is just to make it a legal variable name. > > So it turns out that i have several hundreds of these items, but only > about 60 or so unique items. I am able to map, sort, and normalize my > data and all the other massaging that i want to do and spit it all out. > Now it turns out that what i really would find helpful is to find out > where each item is in a sort of histogram so that i get a list of all > my 60 or so unique items and each m000x number for where it appears and > finally a tally for how often it appears in a kind of score board. So > that i get something like: > > 1. [0,10,2] : m222b, m381, m129c : 3 > 2. [5,6,7] : m221b, m19a, m411b, m367b, m377a : 6 > > with apologies to the list i will post a much abbreviated version of my > script so that the tutors will better be able to understand my query.. > > cheers, > kevin > > > -- snip --- > > #!/usr/bin/env python > > from normtest import * > from interval import * > from unique2 import unique > > def printout(seq): > print '-' * 62 > print seq,"\t",step1(seq),"\t", > (min(ordering(rotations(step1(seq))))[3]),"\t", > optional(min(ordering(rotations(step1(seq))))[3]) > > > def test(): > m1 = [8, 3, 5, 4] > m7 = [4, 3, 2, 2] > m14 = [8, 3, 7, 5] > m18 = [10, 2, 8, 7] > m20 = [10, 0, 5, 7] > m22 = [10, 2, 8, 7] > m24 = [7, 9, 3, 8] > m28 = [10, 0, 5, 7] > m29 = [10, 11] > m30 = [8, 3, 5, 4] > m32 = [5, 0, 11, 7] > m34 = [8, 3, 7, 9] > m36a = [5, 4, 3, 1] > m36b = [5, 4, 3, 1, 7] > m37a = [0, 8, 2, 4, 9, 10, 1] > m37b = [0, 8, 2, 4, 9, 10, 1, 6] > m39a = [8, 10, 1, 9] > m39b = [8, 10, 1, 9, 7] > m41a = [2, 0, 3, 1] > m41b = [2, 0, 3, 1, 6] > page2 = [m1, m7, m14, m18, m20, m22, m24, m28, m29, m30, m32, m34, > m36a, m36b, m37a, m37b, m39a, m39b, m41a, m41b] > # ~~~~~~~~~~~~~~~~~~~~ page 3 ~~~~~~~~~~~~~~~~~~~~ > m43 = [3, 2, 4] > m44a = [0, 8, 2, 4, 9, 10, 1] > m44b = [0, 8, 2, 4, 9, 10, 1, 6] > m45a = [5, 4, 3, 1] > m45b = [5, 4, 3, 1, 7] > m47a = [5,0,3,1] > m47b = [5,4,3,1] > m47c = [5,4,3,1,7] > m49a = [8,10,1,9] > m49b = [8,10,1,9,5] > m51 = [5,0,3,1] > m51b = [5,0,3,1,7] > m53 = [8,3,7,9] > m54a = [5,10,7,0] > m54b = [5,10,7,0, 2] > m55 = [0,8,2,4,9,10,1] > m55b = [0,8,2,4,9,10,1,6] > m57a = [5,0,3,1] > m57b = [5,4,3,1] > m59a = [5,4,3,1] > m59b = [5,4,3,1,7] > m61 = [2,4,3] > m62a = [10,2,8,7] > m62b = [10,2,8,7,0] > m63 = [10,11] > m64 = [8,5,7,10,2] > m64b = [8,5,7,10,2, 9] > m66 = [0,1,6] > m68a = [5,0,3,1] > m86b = [5,0,3,1,7] > m70a = [8,9,10,1] > m70b = [8,9,10,1,7] > m71 = [2,4,11,10] > m72 = [0,1,6,5] > m74 = [8,2,5,4] > m78 = [8,7,10,2] > m80 = [11,8,6,1] > m82a = [7,2,6,8] > m82b = [10,9,0,11] > m82c = [10,9,0,11,4] > m84a = [10,8,2,7] > m84b = [10,8,2,7,0,5] > m85 = [0,1,6,5] > page3 = [m43, m44a, m44b, m45a, m45b, m47a, m47b, m47c, m49a, m49b, > m51, m51b, m53, m54a, m54b, m55, m55b, m57a, m57b, m59a, m59b, m61, > m62a, m62b, m63, m64, m64b, m66, m68a, m86b, m70a, m70b, m71, m72, m74, > m78, m80, m82a, m82b, m82c, m84a, m84b, m85] > # -+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+- > all = page2+page3 > # tr = [] > outlist = [] > # first normalize and map everything and pack it in a list > for j in all: > if len(j) > 1: > tr = optional(min(ordering(rotations(step1(j))))[3]) > outlist.append(tr) > # now let's find all the unique items > foo = unique(outlist) > unique_item_count = 1 > # and then print them out (while counting how many there are) > for item in foo: > print unique_item_count, "\t",item > unique_item_count = unique_item_count + 1 > pages = [page2, page3] > pp = 0 > for page in pages: > print '=' * 62 > print " --- Page ", pp+2, ": " > print '=' * 62 > print "set\tmap & sort:\tnormalized:\tto zero:" > pp = pp + 1 > # print page > for item in page: > printout(item) > > if __name__ == "__main__": > test() > > # -- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Greg Whittier <greg@thewhittiers.com> From ellen.reitmayr at relevantive.de Mon Mar 15 12:19:50 2004 From: ellen.reitmayr at relevantive.de (Ellen Reitmayr) Date: Mon Mar 15 12:14:52 2004 Subject: [Tutor] Popup menu for items in a tkinter listbox Message-ID: <1079371190.2802.38.camel@ariane.localhost> hi, I'm trying to set up an 'add contact from addressbook' dialog with tkinter. There are three listboxes on the right side, showing the selected contacts (to, cc, bcc). Now I want to add a popup menu to the single entries of each list in order to remove the selected item. But I'm faces several problems: - I bound <button-3> with each of the three listboxes to invoke the popup, and <button-1> with the menu to invoke the remove-method: How do I know which listbox is the target list? 'event.widget' does not work, as the menu is the widget. Do I have to compare the x/y-coordinates? Or is there a simpler way to identify the widgets at the current mouse position (I did not use a canvas, so find_overlapping(x1,y1,x2,y2) does not work). - But actually I'm not just interested in the whole list, but in the list entries. Is there a way to bind the popups to the list entries, not to the whole list? And if that is not possible - How can I make a list item be selected when I right-click it (if I do not know the index)? Maybe someone can help me, or tell me were to find a code example for this problem? Thanks and have a nice day, ellen ----------------------------------------------- def popup(event): removeMenu.post(event.x_root, event.y_root) def removeContact(event): # ???? how can I refer to the correct list/list item?? # #[....] # removeMenu = Menu(root, tearoff=0) removeMenu.add_command(label="Entfernen",) removeMenu.bind("<Button-1>",removeContact) toList.bind("<Button-3>",popup) ccList.bind("<Button-3>",popup) bccList.bind("<Button-3>",popup) -- -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20040315/8d753050/attachment.bin From dyoo at hkn.eecs.berkeley.edu Mon Mar 15 12:47:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 15 12:47:07 2004 Subject: [Tutor] Internship In-Reply-To: <20040314112100.34387.qmail@web41509.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0403150942120.20359-100000@hkn.eecs.berkeley.edu> On Sun, 14 Mar 2004, Shitiz Bansal wrote: > If anybody of you have any idea about any such industry please do let me > know. Hello, Python-tutor is probably not the best forum for asking for internships. Have you tried the Python Jobs page? http://python.org/Jobs.html Good luck to you. From pythontut at pusspaws.net Mon Mar 15 12:23:14 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon Mar 15 12:51:37 2004 Subject: [Tutor] A couple of queries ... Message-ID: <4055E682.2020301@pusspaws.net> Is there a python equiverlant of BASH "sleep xm". Ie halt, go to sleep for x mins (Without resorting to a for loop with a v.large count, inaccurate + eats CPU cycles!) ? Second query. Is it possible for a python program to start up as a background process? The app I am writting needs a demon... (see query above :-) ) Rather than writting a seperate BASH script to call the python script with "proggy.pg &" in it. This would work but seems a bit awkward. Many thanks in advance for all your help Cheers Dave From roypython at hotmail.com Mon Mar 15 14:46:15 2004 From: roypython at hotmail.com (roy ollis) Date: Mon Mar 15 15:31:05 2004 Subject: [Tutor] cannot import win32com.client Message-ID: <BAY2-F537hVfuXS1i7y00042993@hotmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040315/18854a09/attachment.html From Christian.Wyglendowski at greenville.edu Mon Mar 15 17:42:17 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Mon Mar 15 17:42:34 2004 Subject: [Tutor] Testing Membership in a Sequence Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A38E4@empex.greenville.edu> Ok, here is a question that I thought I knew the answer to and even vaguely remember discussing somewhere, but now I don't have the foggiest (and I was unable to bend google to do my bidding). What is the most pythonic way to test for membership of multiple items in a sequence? For example: x = ['a', 'b', 'c'] <pseudo code> is ('v' or 'b') in x </pseudo code> I know I can do it via a loop but I was hoping to learn some nice, clear, succinct way of doing this. Am I hoping for too much? Christian http://www.dowski.com From darnold02 at sprynet.com Mon Mar 15 19:01:18 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Mon Mar 15 19:00:04 2004 Subject: [Tutor] Testing Membership in a Sequence In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B0A38E4@empex.greenville.edu> References: <CE1475C007B563499EDBF8CDA30AB45B0A38E4@empex.greenville.edu> Message-ID: <0D17EDB2-76DD-11D8-88B4-000A95C4F940@sprynet.com> On Mar 15, 2004, at 4:42 PM, Christian Wyglendowski wrote: > Ok, here is a question that I thought I knew the answer to and even > vaguely remember discussing somewhere, but now I don't have the > foggiest > (and I was unable to bend google to do my bidding). > > What is the most pythonic way to test for membership of multiple items > in a sequence? For example: > > x = ['a', 'b', 'c'] > > <pseudo code> > is ('v' or 'b') in x > </pseudo code> > > I know I can do it via a loop but I was hoping to learn some nice, > clear, succinct way of doing this. Am I hoping for too much? > Christian > http://www.dowski.com > I don't know if it's the most Pythonic way, but I'd use a list comprehension: a = (1,2,3,4,5,6,7) b = [1,3,5,8] c = [item for item in b if item in a] if c: print 'common items:', c else: print 'no common items found' common items: [1, 3, 5] HTH, Don From cspears2002 at yahoo.com Mon Mar 15 19:04:00 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon Mar 15 19:08:35 2004 Subject: [Tutor] when do I use this? Message-ID: <20040316000400.95840.qmail@web12405.mail.yahoo.com> Several times I have iterated over a sequence with some code that looks like this: for f in range(len(files)): and fellow hackers have told me I can just use: for f in seq: From greg at thewhittiers.com Mon Mar 15 19:16:03 2004 From: greg at thewhittiers.com (Greg Whittier) Date: Mon Mar 15 19:15:25 2004 Subject: [Tutor] Testing Membership in a Sequence In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B0A38E4@empex.greenville.edu> References: <CE1475C007B563499EDBF8CDA30AB45B0A38E4@empex.greenville.edu> Message-ID: <1079396163.6720.6.camel@localhost.localdomain> My first reaction was ('v' in x) or ('b' in x). I assume you want this where there can be more than two items you want to test for. I cheated and used list comprehensions, but it looks pretty nifty albeit inefficient. x = ['a','b','c'] y = ['v','b'] yisinx = 1 in [j in x for j in y] On Mon, 2004-03-15 at 17:42, Christian Wyglendowski wrote: > Ok, here is a question that I thought I knew the answer to and even > vaguely remember discussing somewhere, but now I don't have the foggiest > (and I was unable to bend google to do my bidding). > > What is the most pythonic way to test for membership of multiple items > in a sequence? For example: > > x = ['a', 'b', 'c'] > > <pseudo code> > is ('v' or 'b') in x > </pseudo code> > > I know I can do it via a loop but I was hoping to learn some nice, > clear, succinct way of doing this. Am I hoping for too much? > > Christian > http://www.dowski.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Greg Whittier <greg@thewhittiers.com> From missive at hotmail.com Mon Mar 15 19:26:49 2004 From: missive at hotmail.com (Lee Harr) Date: Mon Mar 15 19:26:54 2004 Subject: [Tutor] Re: what do I use for this? Message-ID: <BAY2-F156hur860EWmR0000120a@hotmail.com> >I want to make a script that asks for a port number and returns its >meaning. >Since there are a few thousand ports, I just want to start with common >ones. >What would I use in this program? An array(s)? I usually just use grep ... $ egrep "\b80/" /etc/services http 80/tcp www www-http #World Wide Web HTTP http 80/udp www www-http #World Wide Web HTTP $ egrep "\b135/" /etc/services loc-srv 135/tcp epmap #Location Service loc-srv 135/udp epmap #Location Service the \b means "word boundary" so that it does not match 180. the / matches the slash before the tcp or udp so that it does not match 800, 805, etc. _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From tim at johnsons-web.com Mon Mar 15 19:39:33 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Mar 15 19:31:44 2004 Subject: [Tutor] when do I use this? In-Reply-To: <20040316000400.95840.qmail@web12405.mail.yahoo.com> References: <20040316000400.95840.qmail@web12405.mail.yahoo.com> Message-ID: <20040316003933.GL5967@johnsons-web.com> * Christopher Spears <cspears2002@yahoo.com> [040315 15:22]: > Several times I have iterated over a sequence with > some code that looks like this: I'm going to put in my two cents worth because I've thus far taken a very simplistic approach to iteration myself: > for f in range(len(files)): Suppose one had several sequences that were of the same length. Then with the approach above, one could use <f> to access each of them. However, I believe that there are more 'elegant' and 'pythonesque' ways of iterating over multiple sequences, so I'm looking forward to more comments. > and fellow hackers have told me I can just use: > > for f in seq: I love this approach .... like to see this in other languages! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From missive at hotmail.com Mon Mar 15 19:33:32 2004 From: missive at hotmail.com (Lee Harr) Date: Mon Mar 15 19:33:36 2004 Subject: [Tutor] Re: A couple of queries ... Message-ID: <BAY2-F128Dw9sux5yPU0003c4ce@hotmail.com> >Is there a python equiverlant of BASH "sleep xm". Ie halt, go to sleep >for x mins (Without resorting to a for loop with a v.large count, >inaccurate + eats CPU cycles!) ? > import time time.sleep(seconds) >Second query. Is it possible for a python program to start up as a >background process? The app I am writting needs a demon... (see query >above :-) ) Rather than writting a seperate BASH script to call the >python script with "proggy.pg &" in it. This would work but seems a bit >awkward. I think I would use twisted. http://www.twistedmatrix.com/ http://www.onlamp.com/pub/a/python/2004/01/15/twisted_intro.html _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From cspears2002 at yahoo.com Mon Mar 15 19:34:39 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon Mar 15 19:34:45 2004 Subject: [Tutor] get() method for dictionaries Message-ID: <20040316003439.99489.qmail@web12407.mail.yahoo.com> Why do we need the get() method for dictionaries? On the surface, there doesn't seem to be a whole of difference between: d = {} d[1] = "stuff" d[1] 'stuff' and d.get(1) 'stuff' From missive at hotmail.com Mon Mar 15 19:40:26 2004 From: missive at hotmail.com (Lee Harr) Date: Mon Mar 15 19:40:39 2004 Subject: [Tutor] Re: when do I use this? Message-ID: <BAY2-F116IqKgHifG9k0004351c@hotmail.com> >Several times I have iterated over a sequence with >some code that looks like this: > >for f in range(len(files)): > >and fellow hackers have told me I can just use: > >for f in seq: > Almost always. If you do not need to know the index numbers of the items in the sequence, then just iterate over the sequence. So, to extend your code ... for n in range(len(files)): print 'processing file number', n+1 file = files[n] file.process() for file in files: file.process() _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From greg at thewhittiers.com Mon Mar 15 19:47:01 2004 From: greg at thewhittiers.com (Greg Whittier) Date: Mon Mar 15 19:46:10 2004 Subject: [Tutor] get() method for dictionaries In-Reply-To: <20040316003439.99489.qmail@web12407.mail.yahoo.com> References: <20040316003439.99489.qmail@web12407.mail.yahoo.com> Message-ID: <1079398021.6720.16.camel@localhost.localdomain> I tend to use it only for the optional default argument d={} d[1] = 'stuff' d.get(1,"no stuff") 'stuff' d.get(267,"no stuff") 'no stuff' This is useful if you don't want to check for the key first or deal with an exception. Greg On Mon, 2004-03-15 at 19:34, Christopher Spears wrote: > Why do we need the get() method for dictionaries? On > the surface, there doesn't seem to be a whole of > difference between: > > d = {} > d[1] = "stuff" > d[1] > 'stuff' > > and > > d.get(1) > 'stuff' > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Greg Whittier <greg@thewhittiers.com> From tim at johnsons-web.com Mon Mar 15 20:05:12 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Mar 15 19:57:23 2004 Subject: [Tutor] [tutor-bounces@python.org: Auto-response for your message to the "Tutor" mailing list] Message-ID: <20040316010512.GM5967@johnsons-web.com> Danny: I'm forwarding this as an assumption that you are the python list maintainer now. My apology if I've forwarded this to the wrong person... I get a message like this from time to time. FYI, to the best of my memory, I've been continuously on this list for about 3 years now..... I.E: I'm not new to the list, I just don't post a lot. Guess that makes me a "lurker". Thought the list maintainer might like to know, as this is kind of an error. Thanks tim ----- Forwarded message from tutor-bounces@python.org ----- Date: Mon, 15 Mar 2004 19:31:42 -0500 From: tutor-bounces@python.org Subject: Auto-response for your message to the "Tutor" mailing list To: tim@johnsons-web.com Errors-to: tutor-bounces@python.org X-Mailer: The Mailman Replybot Precedence: bulk X-Ack: No X-BeenThere: tutor@python.org X-Mailman-Version: 2.1.5b1 X-List-Administrivia: yes List-Id: Discussion for learning programming with Python <tutor.python.org> Your message for tutor@python.org, the Python programming tutor list, has been received and is being delivered. This automated response is sent to those of you new to the Tutor list, to point out a few resources that can help with answering your own questions, or improve the chances of getting a useful answer from the other subscribers. If your question is something akin to: "I've just heard about Python, and it sounds great! Where can I find out more on how to program with Python?" or: "What's Python?" please read section 1 below. On the other hand, if your question is: "I've heard that Python is good for hacking -- I want to know more!" or "Can you teach me how to break into a computer with Python?" please read section 2 at the bottom of this email. Section 1: ---------- The most comprehensive overview of python.org help resources is at http://www.python.org/Help.html The Python FAQ is available at http://www.python.org/doc/FAQ.html and it has answers to many questions that people ask, possibly including your question. Another wealth of information and experience can be found via the python.org searches, at http://www.python.org/search/ There you'll find comprehensive, easy-to-use searches over the python.org web site and the Python newsgroup, comp.lang.python. Python has an online tutorial, available freely from http://www.python.org/doc/current/tut/tut.html Finally, when you do send email to the Tutor list, be as clear as you can about the problem, including, when relevant, details like: - Precise error messages, including complete tracebacks - The hardware platform (available in the Python sys module as sys.platform) - The python version (sys.version) - The python search path (sys.path) In general, be specific about what was going on connected with the problem or what specific concept you're having difficulties with. The better the info you provide, the more likely the helpers will be able to glean the answer... There's a HOWTO that shows how to ask "smart" questions to technical folks: http://catb.org/~esr/faqs/smart-questions.html Although it is provocative, it does have some good points, and is an interesting read. Note that no one is paid to read the tutor list or provide answers, and most readers often have other work that demands their attention. Well-posed requests for help are usually answered fairly promptly, but occasionally a request slips by, so if you do not get a response with one or two working days (it's usually quicker than that), please feel free to send a followup, asking whether anyone is working on your question. Anyway, your message is being delivered to the Tutor list as this one is being sent. However, if your question was about as detailed as "Teach me how to program in Python", do not count on an answer -- this email contains all the information you need to start. Come back with a more precise question, and we'll be glad to help. Thanks! Section 2: ---------- We periodically get requests which ask about hacking or cracking or breaking into computers. If you haven't yet, go read Eric Raymond's article "How To Become a Hacker" at http://catb.org/esr/faqs/hacker-howto.html If, after you've read that, you want help learning how to hack the way Eric defines the word, then come back to us (and read Section 1 above). If you want help learning how to crack, go look elsewhere -- we're not interested in helping you do that. ----- End forwarded message ----- -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From dyoo at hkn.eecs.berkeley.edu Mon Mar 15 20:17:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 15 20:17:52 2004 Subject: [Tutor] Testing Membership in a Sequence In-Reply-To: <1079396163.6720.6.camel@localhost.localdomain> Message-ID: <Pine.LNX.4.44.0403151713290.15851-100000@hkn.eecs.berkeley.edu> On 15 Mar 2004, Greg Whittier wrote: > My first reaction was ('v' in x) or ('b' in x). I assume you want this > where there can be more than two items you want to test for. I cheated > and used list comprehensions, but it looks pretty nifty albeit > inefficient. > > x = ['a','b','c'] > y = ['v','b'] > > yisinx = 1 in [j in x for j in y] Hi everyone, The Set class in the 'sets' Standard Library module can make short work of this problem: ### >>> from sets import Set >>> Set(['v', 'b']) & Set(['a', 'b', 'c']) >>> Set(['x', 'y']) & Set(['a', 'b', 'c']) Set([]) ### We're using the idea of "set intersection" by asking: what elements are shared between the first and second sets? We can read more about the Set class here: http://www.python.org/doc/lib/module-sets.html Good luck! From dyoo at hkn.eecs.berkeley.edu Mon Mar 15 20:28:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 15 20:28:27 2004 Subject: [Tutor] get() method for dictionaries In-Reply-To: <1079398021.6720.16.camel@localhost.localdomain> Message-ID: <Pine.LNX.4.44.0403151720270.15851-100000@hkn.eecs.berkeley.edu> On 15 Mar 2004, Greg Whittier wrote: > I tend to use it only for the optional default argument > > d={} > d[1] = 'stuff' > d.get(1,"no stuff") > 'stuff' > d.get(267,"no stuff") > 'no stuff' > > This is useful if you don't want to check for the key first or deal with > an exception. Hi Chris, By the way, the built-in data types in Python are described in the Library Documentation at: http://www.python.org/doc/lib/builtin.html The Library Documentation is slightly more formal than tutorial material, since it's meant to be used as reference material. As a consequence, it names things in ways that we might not recognize at first. Dictionaries, for example, fall under the "Mapping Types" docs: http://www.python.org/doc/lib/typesmapping.html I hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Mar 15 20:40:03 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 15 20:40:15 2004 Subject: [Tutor] Testing Membership in a Sequence In-Reply-To: <Pine.LNX.4.44.0403151713290.15851-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0403151738310.15851-100000@hkn.eecs.berkeley.edu> On Mon, 15 Mar 2004, Danny Yoo wrote: > The Set class in the 'sets' Standard Library module can make short work > of this problem: > > > ### > >>> from sets import Set > >>> Set(['v', 'b']) & Set(['a', 'b', 'c']) > >>> Set(['x', 'y']) & Set(['a', 'b', 'c']) > Set([]) > ### Argh! I copied and pasted that wrong. Let me try that again: ### >>> from sets import Set >>> Set(['v', 'b']) & Set(['a', 'b', 'c']) Set(['b']) >>> Set(['x', 'y']) & Set(['a', 'b', 'c']) Set([]) ### Ok, better. *grin* My apologies! From dyoo at hkn.eecs.berkeley.edu Mon Mar 15 21:08:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 15 21:08:46 2004 Subject: [Tutor] when do I use this? [iterators!] In-Reply-To: <20040316003933.GL5967@johnsons-web.com> Message-ID: <Pine.LNX.4.44.0403151728390.15851-100000@hkn.eecs.berkeley.edu> On Mon, 15 Mar 2004, Tim Johnson wrote: > I'm going to put in my two cents worth because > I've thus far taken a very simplistic approach > to iteration myself: > > > for f in range(len(files)): [some text cut] > > and fellow hackers have told me I can just use: > > > > for f in seq: > > I love this approach .... like to see this in > other languages! Hi Tim, Other languages, thankfully, do allow for this style of direct iteration. Most people have had experience with them from the Unix shell scripting langages (/bin/sh, /bin/csh) It might be interesting to just quickly touch on what element iteration looks like in some other languages: Perl has a 'foreach' syntax that works on lists. foreach my $s (@seqs) { ... } ## pseudo-Perl Java 1.5, too, supports a similar syntax on java.util.Iterator objects: for(Sequence s : seqs) { ... } // pseudo-Java 1.5 OCaml supports iteration by having an 'iter()' function in many of its standard modules: List.iter (fun s -> ...) seqs (* pseudo-OCaml *) So it is very nice to see that the computer languages today are converging on making the "iterator" concept universal. Since this is Python-tutor, we have to say something about Python. *grin* Python makes iteration work in many different ways. We already know that it's possible to iterate across a list: ### >>> for name in ['rocky', 'bullwinkle', 'pinky', 'brain']: ... print name.capitalize() ... Rocky Bullwinkle Pinky Brain ### But it's also possible to iterate across a file: ### >>> for line in open('/usr/share/dict/words'): ... if line.startswith('py'): ... print line, ... pygmies pygmy pyramid pyramids pyre python ### as well as a string: ### >>> for character in "hello world": ... print character.upper(), ... H E L L O W O R L D ### So iterators are pretty deeply ingrained in Python. What's surprising is that this hasn't always been so --- iterators were added to the Python language in 2001: http://python.org/peps/pep-0234.html and it always amazes me to think of what life was like before them. *grin* Hope this helps! From bvande at po-box.mcgill.ca Mon Mar 15 22:48:22 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Mar 15 22:47:59 2004 Subject: [Tutor] basic question about help() Message-ID: <40567906.3080301@po-box.mcgill.ca> Hi all, this one has stumped me early on in my attempt to learn Python and I'm afraid it will have one of those "make's you feel silly for asking" answers, but here goes: launch IDLE type "help()" type "topics" Sure enough, a long list of topics comes up. But for almost all entries in that list, if FOO is in the list, typing 'foo' at the prompt yields: no Python documentation found for 'foo' whereas typing 'FOO' yields: Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. However, the HTML Python docs can be accessed via IDLE's help menu, so I know they are there. And, from within the documentation browser, a search and check of the index for information about the PYTHONDOCS environment variable comes up empty. So, how do I make help work? Where do I set this environment variable PYTHONDOCS? If it matters, I am using Windows and all Python files live on my D: partition. Thanks, Brian vdB From alan.gauld at blueyonder.co.uk Tue Mar 16 03:45:14 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 03:44:43 2004 Subject: [Tutor] A couple of queries ... References: <4055E682.2020301@pusspaws.net> Message-ID: <00e101c40b33$004bc5e0$6401a8c0@xp> > Is there a python equiverlant of BASH "sleep xm". Ie halt, go to sleep > for x mins (Without resorting to a for loop with a v.large count, > inaccurate + eats CPU cycles!) ? Yes, its: time.sleep(x*60) # sleep takes seconds as an argument > Second query. Is it possible for a python program to start up as a > background process? The app I am writting needs a demon... (see query > above :-) ) Rather than writting a seperate BASH script to call the > python script with "proggy.pg &" in it. This would work but seems a bit > awkward. Have you tried just doing proggy.py & In other words why use a bash script? If you need the formal daemon treatment complete with funny ownerships and flags etc then there is a how-to page on the web somewhere... Alan G. From alan.gauld at blueyonder.co.uk Tue Mar 16 03:50:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 03:50:23 2004 Subject: [Tutor] Testing Membership in a Sequence References: <CE1475C007B563499EDBF8CDA30AB45B0A38E4@empex.greenville.edu> Message-ID: <00e701c40b33$ca7f6240$6401a8c0@xp> > What is the most pythonic way to test for membership of multiple items > in a sequence? For example: > > x = ['a', 'b', 'c'] > > <pseudo code> > is ('v' or 'b') in x > </pseudo code> I'd probably just do: if ('v' in x) or ('b' in x): ... For longer lists you could use some of the functional programming constructs, but they can get quite convoluted. A simple comprehension might be: if [c for c in ['b', 'v'] if c in x]: .... But that's just a loop in very thin disguise... Alan G From alan.gauld at blueyonder.co.uk Tue Mar 16 03:55:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 03:54:33 2004 Subject: [Tutor] when do I use this? References: <20040316000400.95840.qmail@web12405.mail.yahoo.com> Message-ID: <00ee01c40b34$5f546d70$6401a8c0@xp> > Several times I have iterated over a sequence with > some code that looks like this: > > for f in range(len(files)): > > and fellow hackers have told me I can just use: > > for f in seq: That's right. If you have a collection of items there is no point in you calculating the length of the collection then manually extracting each item within your for loop when python will hand you the item directly. So if you want to process all the items in a collection use for item in collection: doit(item) instead of for index in range(len(collection)): item = collection[index] doit(item) It's less error prone and a lot shorter to type! Alan G. From alan.gauld at blueyonder.co.uk Tue Mar 16 04:01:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 04:01:24 2004 Subject: [Tutor] get() method for dictionaries References: <20040316003439.99489.qmail@web12407.mail.yahoo.com> Message-ID: <00fb01c40b35$54f32690$6401a8c0@xp> > Why do we need the get() method for dictionaries? On > the surface, there doesn't seem to be a whole of > difference between: > Try this extended example >>> d = {} >>> d[1] = 'one' >>> d[1] 'one' >>> d.get(2) >>> d[2] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: 2 >>> d.get(3,'three') 'three' >>> d[3] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: 3 >>> So using get() means we don't get errors if we try to access a non existent member and we can optionally pass a value that get returns if the dict doesn't have one (but note it does't set that value in the dict...) So it means a bit less error handling in some cases. Alan G. From op73418 at mail.telepac.pt Tue Mar 16 07:59:36 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Mar 16 07:57:10 2004 Subject: [Tutor] when do I use this? In-Reply-To: <20040316003933.GL5967@johnsons-web.com> References: <20040316000400.95840.qmail@web12405.mail.yahoo.com> <20040316003933.GL5967@johnsons-web.com> Message-ID: <e9ud501640q761f28dt8nfqjrpc55olikl@4ax.com> Em Mon, 15 Mar 2004 15:39:33 -0900, Tim Johnson <tim@johnsons-web.com> atirou este peixe aos pinguins: >* Christopher Spears <cspears2002@yahoo.com> [040315 15:22]: >> Several times I have iterated over a sequence with >> some code that looks like this: > > I'm going to put in my two cents worth because > I've thus far taken a very simplistic approach > to iteration myself: > >> for f in range(len(files)): > > Suppose one had several sequences that were of the > same length. Then with the approach above, one > could use <f> to access each of them. > > However, I believe that there are more 'elegant' > and 'pythonesque' ways of iterating over multiple > sequences, so I'm looking forward to more comments. > Use zip. >>> help(zip) Help on built-in function zip: zip(...) zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence. >>> For example, the following should give you a clue (it also uses tuple unpacking): >>> lst = ["some", "list", "of", "words"] >>> print zip(range(len(lst)), lst) [(0, 'some'), (1, 'list'), (2, 'of'), (3, 'words')] >>> for index, word in zip(range(len(lst)), lst): ... print "lst[%d]=%s" % (index, word) ... lst[0]=some lst[1]=list lst[2]=of lst[3]=words With my best regards, G. Rodrigues From Christian.Wyglendowski at greenville.edu Tue Mar 16 09:18:32 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue Mar 16 09:18:39 2004 Subject: [Tutor] Testing Membership in a Sequence Message-ID: <CE1475C007B563499EDBF8CDA30AB45B028B3E85@empex.greenville.edu> > -----Original Message----- > On Monday 15 Mar 2004 22:42 pm, Christian Wyglendowski wrote: > > > x = ['a', 'b', 'c'] > > > > <pseudo code> > > is ('v' or 'b') in x > > </pseudo code> > > The simplest way is this: > > if 'v' in x or 'b' in x: > do_something() This looks like the closest to what I envisioned as the solution. Thanks for kickstarting my brain. What I am actually trying to do is look for command line options in sys.argv. if '-o' in sys.argv or '--option' in sys.argv: apply_option() Thanks to everyone for the advice. Christian http://www.dowski.com From magnus at thinkware.se Tue Mar 16 09:21:05 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Mar 16 09:21:18 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gd2hlbiBkbyBJIHVzZSB0aGlzPw==?= Message-ID: <think001_40570a948f869@webmail.thinkware.se> Christopher Spears wrote: > Several times I have iterated over a sequence with > some code that looks like this: > > for f in range(len(files)): > > and fellow hackers have told me I can just use: > > for f in seq: Assuming files is a list of file objects, you would perhaps rather do: for i in range(len(files)): f = files[i] print f.read() (Using f for an index number confuses me at least.) But if you don't need the index number for any particular purpose, you are much better off skipping the detour via index numbers (which you only do because other languages lack the ability to go straight.) Then you get: for f in files: print f.read() In recent versions of Python, you don't even need the range(len()) hack even if you need the index. Use the builtin function "enumerate" instead. for i, f in enumerate(files): print "Content of file number", i print f.read() -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From kalle at lysator.liu.se Tue Mar 16 10:15:23 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Tue Mar 16 10:12:45 2004 Subject: [Tutor] Testing Membership in a Sequence In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B028B3E85@empex.greenville.edu> References: <CE1475C007B563499EDBF8CDA30AB45B028B3E85@empex.greenville.edu> Message-ID: <20040316151523.GB32478@i92.ryd.student.liu.se> [Christian Wyglendowski] > What I am actually trying to do is look for command line options in > sys.argv. > > if '-o' in sys.argv or '--option' in sys.argv: > apply_option() In that case you might want to take a look at the optparse module. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From sigurd at 12move.de Tue Mar 16 10:41:43 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Mar 16 10:46:46 2004 Subject: [Tutor] Testing Membership in a Sequence In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B028B3E85@empex.greenville.edu> (Christian Wyglendowski's message of "Tue, 16 Mar 2004 08:18:32 -0600") References: <CE1475C007B563499EDBF8CDA30AB45B028B3E85@empex.greenville.edu> Message-ID: <m3oeqw6cd2.fsf@hamster.pflaesterer.de> Christian Wyglendowski <- Christian.Wyglendowski@greenville.edu wrote: > What I am actually trying to do is look for command line options in > sys.argv. > if '-o' in sys.argv or '--option' in sys.argv: > apply_option() You could either use the optparse module or subclass the list class and define a custom __contains__ method. class MList (list): def __contains__(self, seq): try: for e in seq: if list.__contains__(self, e): return True return False except TypeError: return list.__contains__(self, seq) For two options it may be a bit overkill but for a larger list it can be convenient. Here's an example: In [42]: lst = MList(range(10)) In [43]: lst Out[43]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [44]: 3 in lst Out[44]: True In [45]: (3, 11, 9) in lst Out[45]: True In [46]: (11, 20, -1) in lst Out[46]: False So you could write: if ('-o', '--option) in MList(sys.argv): ... Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Tue Mar 16 10:55:41 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Mar 16 10:57:23 2004 Subject: [Tutor] when do I use this? [iterators!] In-Reply-To: <Pine.LNX.4.44.0403151728390.15851-100000@hkn.eecs.berkeley.edu> (Danny Yoo's message of "Mon, 15 Mar 2004 18:08:38 -0800 (PST)") References: <Pine.LNX.4.44.0403151728390.15851-100000@hkn.eecs.berkeley.edu> Message-ID: <m3k71k6ba4.fsf@hamster.pflaesterer.de> On 16 Mar 2004, Danny Yoo <- dyoo@hkn.eecs.berkeley.edu wrote: > But it's also possible to iterate across a file: > ### >>>> for line in open('/usr/share/dict/words'): > ... if line.startswith('py'): > ... print line, > ... This idiom has one (IMO) great disadvantage: you can't explicitly close the file. Maybe someday the for loop will be extended so that files opened in that way are automagically closed when the loop ends (or breaks). Then you could safely open files for reading or writing. [...] > So iterators are pretty deeply ingrained in Python. What's surprising is > that this hasn't always been so --- iterators were added to the Python > language in 2001: And with generators and the itertools module you can write very nice code (I'm waiting for the generator functions). Karl -- Please do *not* send copies of replies to me. I read the list From wiseone6 at hotmail.com Tue Mar 16 12:26:23 2004 From: wiseone6 at hotmail.com (Maxim Ryan) Date: Tue Mar 16 12:26:29 2004 Subject: [Tutor] help please? Message-ID: <Sea2-F27vSuyTwCSb6i00023e16@hotmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040316/d4637d43/attachment.html From tim at johnsons-web.com Tue Mar 16 12:43:35 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Mar 16 12:35:46 2004 Subject: [Tutor] when do I use this? [iterators!] In-Reply-To: <Pine.LNX.4.44.0403151728390.15851-100000@hkn.eecs.berkeley.edu> References: <20040316003933.GL5967@johnsons-web.com> <Pine.LNX.4.44.0403151728390.15851-100000@hkn.eecs.berkeley.edu> Message-ID: <20040316174335.GP5967@johnsons-web.com> * Danny Yoo <dyoo@hkn.eecs.berkeley.edu> [040315 17:19]: > > > On Mon, 15 Mar 2004, Tim Johnson wrote: > > > I'm going to put in my two cents worth because > > I've thus far taken a very simplistic approach > > to iteration myself: > > > > > for f in range(len(files)): > > [some text cut] > > > > > and fellow hackers have told me I can just use: > > > > > > for f in seq: > > > > I love this approach .... like to see this in > > other languages! > > ### > >>> for character in "hello world": > ... print character.upper(), > ... > H E L L O W O R L D Hi Danny: <...> I'm well apprised of this method and use it all the time. Since my first degree was in philosophy of Language, <for item in sequence> makes all kinds of sense, and is aesthetically pleasing. I also like the iteritem method, that is great! I *have* noted that python is adding features all the time. *And* appears to be adopting (with great care) what seems to work well in other languages. My other main scripting language is rebol, which is awesomely flexible (but with flexibility come issues). Although rebol doesn't allow <for item in sequence>, it has a very nice native iterator: given seq: [1 2 3 4 5 6] foreach [odd even] seq yields 1 2, 3 4, 5 6 iterators can also be hand-rolled as in a 'for-every' iterator that I've implemented. given seq1 [1 2 3 4 5 6] and seq2 ["one" "two" "three" "four" "five" "six"] for-every allows code to iterate over both (or any number of sequences for that matter) "at once" (and 1 or more items at a time for each sequence) as in forevery [[odd1 even1] seq1 [odd2 eve2] seq2][ ;.. body of code] or forevery [item1 seq1 item2 seq2][ ;.. body of code] <g>Didn't I tell you earler that I would pose this topic? Actually I bet python could do this with list comprehension, you think? Good talking to you. tim -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From jsh47 at cam.ac.uk Tue Mar 16 12:37:04 2004 From: jsh47 at cam.ac.uk (Jonathan Hayward) Date: Tue Mar 16 12:37:13 2004 Subject: [Tutor] help please? In-Reply-To: <Sea2-F27vSuyTwCSb6i00023e16@hotmail.com> References: <Sea2-F27vSuyTwCSb6i00023e16@hotmail.com> Message-ID: <40573B40.1040709@cam.ac.uk> Maxim Ryan wrote: > > i am trying to write a hangman game in python and i need your help. so > can you help me with the code please. > What specifically do you need help with? Do you need help approaching the problem? Do you need help with some specific detail? People on the list are more likely to help you with something specific--or several whole things--than write a whole hangman program. Have you read How to Think like a Computer Scientist ( http://www.ibiblio.org/obp/thinkCSpy/ )? That's a little long, but in the end it's a big shortcut. > > thank you. > > > ------------------------------------------------------------------------ > Tired of spam? Get advanced junk mail protection > <http://g.msn.com/8HMAEN/2734??PS=> with MSN 8. > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From apqle75 at hotmail.com Mon Mar 15 19:39:09 2004 From: apqle75 at hotmail.com (APQ LE) Date: Tue Mar 16 12:48:16 2004 Subject: [Tutor] Question Message-ID: <BAY16-F52mofno6Su940000cf8a@hotmail.com> what does 'retries' mean in this example? def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint _________________________________________________________________ Find things fast with the new MSN Toolbar – includes FREE pop-up blocking! http://clk.atdmt.com/AVE/go/onm00200414ave/direct/01/ From gustabares at verizon.net Fri Mar 12 14:15:37 2004 From: gustabares at verizon.net (Gus Tabares) Date: Tue Mar 16 12:49:06 2004 Subject: [Tutor] exception classes Message-ID: <40520C59.70203@verizon.net> Hello all, I was wondering if it was possible for custom exception classes to have 'property' attributes? From what I understand, classes that use property attributes must subclass 'object', i.e. class MyClass(object) and exception classes must subclass 'Exception', i.e. class MyClass(Exception) I'm not really sure if it's possible or how it would be done. Any ideas are appreciated... Thanks, Gus From jeffpeery at yahoo.com Sun Mar 14 19:28:54 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue Mar 16 12:49:24 2004 Subject: [Tutor] how to clear variables in IDLE Message-ID: <20040315002854.80463.qmail@web60104.mail.yahoo.com> hi, I'm working on writing a couple scripts and when I run them I first import them then execute a functino from within the module. however when I change the function and then run it again it seems to not show the change. how can I clear the imported modules. similarly if I do something like: variable = 1 how can I clear the variable list in the IDLE so "variable" no longer exists. thanks! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040314/ccf1c844/attachment.html From Michele_Lugton at newhorizons.co.nz Mon Mar 15 18:55:39 2004 From: Michele_Lugton at newhorizons.co.nz (Michele Lugton) Date: Tue Mar 16 12:49:50 2004 Subject: [Tutor] New Zealand Python Contractor Message-ID: <FD971E82AD9ED541A47EA59CD683AF5A024C3D41@alexmail.etgnz.eagle.co.nz> We are a training Centre in Auckland New Zealand. We have a client who is interested in regular Python training for our yet to be announced training schedule. We are looking for potential trainers to be available to fill these training dates as and when needed. If you are interested, please contact me at operations@newhorizons.co.nz <mailto:operations@newhorizons.co.nz> Michele Lugton National Training and Operations Manager New Horizons Computer Learning Centres New Zealand - AUCKLAND Gate D, Alexandra Park, Greenlane West, Epsom Private Bag 93211, Parnell 1033, Auckland e: michele_lugton@newhorizons.co.nz <mailto:michele_lugton@newhorizons.co.nz> w: www.newhorizons.co.nz <http://www.newhorizons.co.nz/> "The world's largest computer training company" IDC 2002 New Horizons New Zealand is a wholly owned subsidiary of Eagle Technology Group Ltd www.eagle.co.nz This email is confidential and may be legally privileged. If received in error please destroy and immediately notify us. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040316/75aeaf2a/attachment.html From shaleh at speakeasy.net Sat Mar 13 04:31:09 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Tue Mar 16 12:51:48 2004 Subject: [Tutor] For statement In-Reply-To: <5.1.0.14.0.20040313133304.034cf130@192.168.1.1> References: <5.1.0.14.0.20040313133304.034cf130@192.168.1.1> Message-ID: <200403130131.09191.shaleh@speakeasy.net> On Friday 12 March 2004 18:53, Alfred Milgrom wrote: > You can also specify conditions in your list comprehension expression. For > example, if you had words with and without commas and only wanted to find > the words that had a comma at the end, you could write: > > commawords = [word[:-1] for word in a if word.endswith(',')] > > There are many more things you can do with list comprehension, and I have > simplified the syntax a bit here for ease of explanation, but this should > give you enough to get started with list comprehension. > as a former C(++) coder one of the things I had to get used to in Python was ignoring the details. The fact that the above is "wasteful" and generates another list should just be forgotten. In languages like python the easiest and often fastest approaches are like this. Don't let yourself get caught up with "oh my, I am using twice the memory I should be". You can always go back and optimize the sections that need it. From vicki.stanfield at ROCHE.COM Mon Mar 15 15:29:57 2004 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Mar 16 12:52:06 2004 Subject: [Tutor] Another parsing question Message-ID: <CA3458C84C976E45B6372A6C14724C9F355EF2@ridmsem02.nala.roche.com> I have inherited a project which writes some data to a file in hexadecimal format as 0x11, 0x4, etc. The hex values are pipe-delimited as so: 0x11|0x4|0x14 I need to parse the file to transmit the values over a serial port as hex, but when I send the data that I have parsed out, I get it sending the 0, the x, the 1, and another 1 instead of the hex value for 0x11. How would one grab the whole thing as hex? Here is what I am doing now: for line in data_file.readlines(): if len(line)>1: tokens=line.split("|") i=0 for piece in tokens: port.write(piece) time.sleep(S_INTERVAL) i = i + 1 It seems to me that I have done this before, but I have searched my code base and not found an example. TIA, --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040315/22c36e06/attachment-0001.html From sigurd at 12move.de Tue Mar 16 12:54:21 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Mar 16 12:56:33 2004 Subject: [Tutor] help please? In-Reply-To: <Sea2-F27vSuyTwCSb6i00023e16@hotmail.com> (Maxim Ryan's message of "Tue, 16 Mar 2004 17:26:23 +0000") References: <Sea2-F27vSuyTwCSb6i00023e16@hotmail.com> Message-ID: <m3brmw65q9.fsf@hamster.pflaesterer.de> On 16 Mar 2004, Maxim Ryan <- wiseone6@hotmail.com wrote: > <html><div style='background-color:'><DIV class=RTE> > <P><BR>i am trying to write a hangman game in python and i need your help. so > <P>can you help me with the code please. </P> To be able to help you, you must show us what you've done so far. (BTW please stop sending HTML E-Mails [especially which such b0rked HTML -:) ]). Karl -- Please do *not* send copies of replies to me. I read the list From vicki at stanfield.net Fri Mar 12 13:50:33 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Tue Mar 16 13:06:26 2004 Subject: [Tutor] loop based on a binary number? In-Reply-To: <1335.192.168.11.4.1078974018.squirrel@www.thepenguin.org> References: <1335.192.168.11.4.1078974018.squirrel@www.thepenguin.org> Message-ID: <63424.206.53.226.235.1079117433.squirrel@www.thepenguin.org> Nevermind. I posted this yesterday and have resolved it already. > > I am reading in binary data from an instrument using Python. The second > field in my data is supposed to represent the length (number of bytes of > binary data). Can I loop based on a binary? Or do I have to convert it? > > --vicki > > "A pessimist sees the difficulty in every opportunity; an optimist sees > the opportunity in every difficulty." > -- Winston Churchill > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From alan.gauld at blueyonder.co.uk Tue Mar 16 13:09:19 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 13:08:46 2004 Subject: [Tutor] Testing Membership in a Sequence References: <CE1475C007B563499EDBF8CDA30AB45B028B3E85@empex.greenville.edu> Message-ID: <014a01c40b81$d03b4b10$6401a8c0@xp> > What I am actually trying to do is look for command line > options in sys.argv. > > if '-o' in sys.argv or '--option' in sys.argv: > apply_option() Have you looked at the getopt module? It might be easier... Alan G. From alan.gauld at blueyonder.co.uk Tue Mar 16 13:12:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 13:12:28 2004 Subject: [Tutor] help please? References: <Sea2-F27vSuyTwCSb6i00023e16@hotmail.com> Message-ID: <016301c40b82$4e95a320$6401a8c0@xp> > i am trying to write a hangman game in python and i need your help. > so can you help me with the code please. If you find my book its got hangman as a case study :-) Alternatively you can get the commented code on the Useless Python web site. hmgui.zip is, I think the filename. Alan G. From connally at fas.harvard.edu Tue Mar 16 13:17:02 2004 From: connally at fas.harvard.edu (Emily Lea Connally) Date: Tue Mar 16 13:17:06 2004 Subject: [Tutor] remove me? Message-ID: <Pine.LNX.4.58.0403161316350.22119@ls01.fas.harvard.edu> hey, i thought i had been removed from this list.. how do i re-remove myself? M From alan.gauld at blueyonder.co.uk Tue Mar 16 13:27:25 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 13:26:47 2004 Subject: [Tutor] Another parsing question References: <CA3458C84C976E45B6372A6C14724C9F355EF2@ridmsem02.nala.roche.com> Message-ID: <017501c40b84$54c37220$6401a8c0@xp> Vicki, > I have inherited a project which writes some data to a file > in hexadecimal format as 0x11, 0x4, etc. The hex values are > pipe-delimited as so: 0x11|0x4|0x14 Don't take this the wrong way, but it seems you really need to go back to basics on how information is stored and represented in computer systems. Most of your questions seem to be based on confusion between strings and binary formats. > hex, but when I send the data that I have parsed out, I get > it sending the 0, the x, the 1, and another 1 instead of the > hex value for 0x11. That's because you have parsed a string - ie a series of characters. You want to send a series of bytes. You need to convert the 4 byte character strings into single byte numbers. Try using the int() operaion: >>> int('12') 12 >>> int('0x12',16) 18 >>> print "As hex: %0X" % int('0x12',16) As hex: 12 Notice the hex is purely a representation thing. There is no real difference between hex 0x12 and decimal 18 (or even octal 22!) They are just different string representations of the same underlying binary number. Now you can send that binary number down the pipe: for line in data_file.readlines(): if len(line)>1: tokens=line.split("|") i=0 # I have no idea what you need the i for??? for piece in tokens: port.write(int(piece,16)) # convert to number time.sleep(S_INTERVAL) i = i + 1 # nor why you increment it here HTH, Alan G. From asekwababe at yahoo.com Tue Mar 16 13:34:19 2004 From: asekwababe at yahoo.com (olebile sekwababe) Date: Tue Mar 16 13:34:27 2004 Subject: [Tutor] Re: Tutor Digest, Vol 1, Issue 2662 In-Reply-To: <E1B3Ijc-0004lU-7v@mail.python.org> Message-ID: <20040316183419.23458.qmail@web60202.mail.yahoo.com> ******************************************************** Hello guys! i have a problem with some here: how do i write a program to evaluate an expression of string like this [[(2+4)*(2+6)]+[(5/2)-(2+3)]],the parentheses must be balanced and the program should return a single number which is the value of the evaluated expression.these program should use stacks and Queues be programmed in Java. please help! bye! ****************************************************** __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From pythontut at pusspaws.net Tue Mar 16 13:14:49 2004 From: pythontut at pusspaws.net (Dave S) Date: Tue Mar 16 13:42:40 2004 Subject: [Tutor] A couple of queries ... In-Reply-To: <00e101c40b33$004bc5e0$6401a8c0@xp> References: <4055E682.2020301@pusspaws.net> <00e101c40b33$004bc5e0$6401a8c0@xp> Message-ID: <40574419.1000106@pusspaws.net> Alan Gauld wrote: >>Is there a python equiverlant of BASH "sleep xm". Ie halt, go to >> >> >sleep > > >>for x mins (Without resorting to a for loop with a v.large count, >>inaccurate + eats CPU cycles!) ? >> >> > >Yes, its: > >time.sleep(x*60) # sleep takes seconds as an argument > > > >>Second query. Is it possible for a python program to start up as a >>background process? The app I am writting needs a demon... (see >> >> >query > > >>above :-) ) Rather than writting a seperate BASH script to call the >>python script with "proggy.pg &" in it. This would work but seems a >> >> >bit > > >>awkward. >> >> > >Have you tried just doing > >proggy.py & > >In other words why use a bash script? > >If you need the formal daemon treatment complete with funny ownerships >and flags etc then there is a how-to page on the web somewhere... > >Alan G. > > > Thanks for your help, it is much appreciated Dave From sigurd at 12move.de Tue Mar 16 14:45:24 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Mar 16 14:48:39 2004 Subject: [Tutor] Question In-Reply-To: <BAY16-F52mofno6Su940000cf8a@hotmail.com> (APQ LE's message of "Mon, 15 Mar 2004 18:39:09 -0600") References: <BAY16-F52mofno6Su940000cf8a@hotmail.com> Message-ID: <m3y8q04mes.fsf@hamster.pflaesterer.de> On 16 Mar 2004, APQ LE <- apqle75@hotmail.com wrote: > what does 'retries' mean in this example? > def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): > while True: > ok = raw_input(prompt) > if ok in ('y', 'ye', 'yes'): return True > if ok in ('n', 'no', 'nop', 'nope'): return False > retries = retries - 1 > if retries < 0: raise IOError, 'refusenik user' > print complaint The same it means in English. Did you try to eval the code in your head? What happens if you enter e.g. `foo' at the prompt? Instead of hiding the condition for the while loop in the body it would IMO be clearer to write something like: while retries < 4: . . . raise ... Karl -- Please do *not* send copies of replies to me. I read the list From magnus at thinkware.se Tue Mar 16 14:58:52 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Mar 16 14:58:59 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gYmFzaWMgcXVlc3Rpb24gYWJvdXQgaGVscCgp?= Message-ID: <think001_40571e126a8f6@webmail.thinkware.se> Brian van den Broek wrote: > this one has stumped me early on in my attempt to learn Python and > I'm afraid it will have one of those "make's you feel silly for > asking" answers, but here goes: Don't think so. It seems this won't work out of the box on Windows. Probably because Windows users typically prefer the normal windows help engine anyway. I never heard of anyone asking about this before, and I never even noticed that "topics" feature. Does anyone on this mailing list use it? You should also note that the help function will typically (not for this special "topics" feature I guess) just extract the builtin documentation strings from the source code, and that is not the main source of documentation for the standard modules or builtin functions. It's probably more helpful as a reminder for skilled programmers than as a way of learning Python. Have you worked through the Python tutorial? I think that's a much better start. Then I'd use the Library reference. That's a very good source of information, particularly chapter 2. There are also plenty of other online tutorials and many good books. I don't think I'd bother with this help function, but anyway... > launch IDLE > type "help()" > type "topics" > > Sure enough, a long list of topics comes up. But for almost all > entries in that list, if FOO is in the list, typing 'foo' at the > prompt yields: Note that Python is case sensitive. Don't expect 'foo' to be in any way equivalent to 'FOO'. I assume this topic feature uses capitalized names just because they won't collide with actual Python objects, such as standard modules or builtin functions. You don't by any chance have your roots in the VMS world? In that case you have to get used to case sensitivity and don't expect help() to be anything like the help system in VMS. > However, the HTML Python docs can be accessed via IDLE's help > menu, so I know they are there. Are you sure? At least on my system, D:\Python23\Doc just contains a windows help file (Python23.chm). It's been created *from* HTML files, but they aren't included. For this to work, you might have to download the Python source code package, and extract the HTML files from there. (I'm not sure it's worth the effort though.) > And, from within the documentation > browser, a search and check of the index for information about the > PYTHONDOCS environment variable comes up empty. > > So, how do I make help work? Where do I set this environment > variable PYTHONDOCS? Environment variables are a standard feature of most operating systems, and you set them differently in Windows, Unix etc. Python uses them, but they are not a Python feature. I guess the error message could be more clear in hinting about that, but you can't expect it to give a lot of operating system specific details. That would cause an tough maintenance burden on the Python developers. (Really! Python supports a large number of operating systems, and the different flavours of Windows are enough to cause problems.) Clicking on Start->Help and looking for "environment" in the index will probably show you how to do it. (Otherwise you can probably find the place if you go to the Control Panel, and then to "System", but the details vary between Windows versions.) Note that you will have to restart Idle after you change environment settings. You can find the current environment settings from within Python with: >>> import os >>> envnames = os.environ.keys() >>> envnames.sort() >>> for name in envnames: print name, '=', os.environ[name] -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From shavais at hotmail.com Tue Mar 16 16:02:30 2004 From: shavais at hotmail.com (Sha vais) Date: Tue Mar 16 16:02:37 2004 Subject: [Tutor] here's a printf() function Message-ID: <BAY7-F30eO6NJCAj6Qp0006c1d5@hotmail.com> I'm a C / C++ programmer (in a weak kind of a way, I think) and I'm learning Python (and loving it). I was slightly irritated by the automagical spaces between elements and ending carriage return that Python's built in "print" function does, so I made a printf() function that I thought I'd share. (This list probably gets one of these every other week or so? Lol..) Here's the module file, sf_utils.py --- """ Some basic formatted string output functions to make things easier for someone who is used to C. """ from sys import stdout def printf(format, *args): "Write the arguments to standard out in the specified format." s = format % args stdout.write(s) # (no added spaces or ending carriage return, woohoo!) def fprintf(file, format, *args): "Write the arguments to the given open file in the specified format." s = format % args file.write(s) def sprintf(format, *args): "Return a string with the arguments concatenated in the specified format." s = format % args return s ---- That's it, hehe. Ez as Py. Now I can do stuff like... ---- >>>from sf_utils import printf >>>printf("%s! There's a %s fly in my %4.5fth bowl of %s!\n", >>>"Argh","flipping", 3.14159236, "goo") Argh! There's a flipping fly in my 3.14159th bowl of goo! ---- Kinda silly and pointless, I guess, but then, kinda maybe not. ~Shavais p.s. I was in search of the py_compile.compile(filename,...) function (which I gratefully found, whew) and I came across an old post by someone who thought "is" was not behaving properly and thought it was a bug in the interpreter. Remember that "is" is not a value comparison. If it were, how would you see if the variable x is referring to the same memory space (the same object) as the variable y? (While processing complex data structures, for example.) That's what "is" does. If you use "is" interchangeably with "==" you will make nasty bugs. Your program might behave one way in .py form, and another in .pyc form, for example. (Or one way on Monday, and another on Tuesday, for that matter, lol.) What they really mean by "object identity" (to a C programmer like me) is "pointer equality." Every Python variable is a pointer. '==' tests to see if the values at the memory addresses that the pointers are pointing to are the same. 'is' tests to see if the pointers are pointing to the same memory address. Two completely different tests. Two different python variables, who's values are the same, may refer to the same memory location, or they may not. If you use "is" when you mean "==", don't blame the interpretter for producing strange results, hehe. _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee® Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From cspears2002 at yahoo.com Tue Mar 16 16:54:53 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue Mar 16 16:55:00 2004 Subject: [Tutor] solution Message-ID: <20040316215453.83232.qmail@web12403.mail.yahoo.com> After Karl showed me the logic, everything fell into place! Here is the code: def whatsindirectory(path): extensions = {} import os,re files = os.listdir(path) for f in files: base,ext = os.path.splitext(f) if ext: ext = ext[1:] size = os.path.getsize(path + "\\" + f) extensions[ext] = extensions.get(ext, [0, []]) extensions[ext][0] += 1 extensions[ext][1].append(size) print "extensions: ",extensions.keys() frequency = [] for e in extensions.keys(): frequency.append(extensions[e][0]) print "frequency: ",frequency minimum = [] maximum = [] for e in extensions: minimum.append(min(extensions[e][1])) maximum.append(max(extensions[e][1])) print "minimum sizes:", minimum print "maximum sizes:", maximum averages = [] for e in extensions: averages.append((sum(extensions[e][1]))/(len(extensions[e][1]))) print "average sizes:", averages From gustabares at verizon.net Tue Mar 16 17:22:58 2004 From: gustabares at verizon.net (Gus Tabares) Date: Tue Mar 16 17:23:31 2004 Subject: [Tutor] cannot import win32com.client Message-ID: <200403161723.12800.gustabares@verizon.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > I use: WinXP PRO Greek version 5.01.2600 Service Pack 1 > And: PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 > 32 bit (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammon > (mhammond at skippinet. com.au) - see 'Help/About PythonWin' for > further copyright information. > > When I installed "win32all-163.exe" I got 3 errors: > 1) Registration of the AXScript Engine COM server failed. > Installation will continue, but this server will require manual > registration before it will function > > exceptions.AttributeError: 'module' object has no attribute > '__import_pywin32_system_module__' > > 2) Registration of the Python Interpreter COM server failed. > Installation will continue, but this server will require manual > registration before it will function > > exceptions.AttributeError: 'module' object has no attribute > 'com_error' > > 3) Registration of the Python Dictionary COM server failed. > Installation will continue, but this server will require manual > registration before it will function > > exceptions.ImportError: cannot import name DISPATCH_METHOD > > Any time I try to reinstall I get the same 3 errors... > > Any solution? Hi there, I've run into this exact same problem. In fact I've already reported a bug to Mark Hammond informing him of the problem. I'm not really sure what the workaround for this is; unless there is something terribly important in version 163 that you need, you may want to revert back to the previous version as I have done. For some reason I think this problem has more to do with a Microsoft update than an actual problem with the Python Windows extensions. You can check out the bug I've already filed here: https://sourceforge.net/tracker/index.php?func=detail&aid=868473&group_id=78018&atid=551954 Good luck, Gus Tabares -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAV35KlBrctWk2LusRAsEPAKChxIM5rRo4Fukn+b1TpoCyP+6ZiACfTY46 9cPbyzBZC8pJ07+2jhAro04= =R6L0 -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Tue Mar 16 17:38:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 16 17:38:57 2004 Subject: [Tutor] remove me? In-Reply-To: <Pine.LNX.4.58.0403161316350.22119@ls01.fas.harvard.edu> Message-ID: <Pine.LNX.4.44.0403161436340.11687-100000@hkn.eecs.berkeley.edu> On Tue, 16 Mar 2004, Emily Lea Connally wrote: > hey, i thought i had been removed from this list.. how do i re-remove > myself? Hi Emily, Strange. Well, the mailing list software that we use to maintain Python-tutor had been upgraded recently; it's possible that we may still be seeing some wackiness from that upgrade. Try visiting: http://mail.python.org/mailman/listinfo/tutor There should be an 'unsubscribe' form near the bottom of that page; try unsubscribing again. If you run into problems with this, please send a holler to the administrative address "tutor-admin@python.org", and we'll unsubscribe you manually. From alan.gauld at blueyonder.co.uk Tue Mar 16 18:10:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 18:10:28 2004 Subject: [Tutor] basic question about help() References: <think001_40571e126a8f6@webmail.thinkware.se> Message-ID: <01a901c40bab$ee842f90$6401a8c0@xp> > > launch IDLE > > type "help()" > > type "topics" > > > > Sure enough, a long list of topics comes up. But for almost all > > entries in that list, if FOO is in the list, typing 'foo' at the > > prompt yields: > > Note that Python is case sensitive. Don't expect 'foo' to be > in any way equivalent to 'FOO'. Magnus is correct you need to use uppercase. > At least on my system, D:\Python23\Doc just contains a windows > help file (Python23.chm). It's been created *from* HTML files, > but they aren't included. Really? My python install does have the help as html. (You don't use the ActiveState installer by any chance Magnus?) > So, how do I make help work? Where do I set this environment > variable PYTHONDOCS? Depends on OS. But assuming you are on NT/W2K/XP you go into MyComputer->Properties->Advanced->Environment Variables (On Win 9X/Me its by editing the C:\AUTOEXEC.BAT file.) Either for yourself(probably best) or for the full system hit New Enter the name PYTHONDOCS and the Value E:\PYTHON\DOc on my system. Hit OK three times and restart Python. Alan G. From alan.gauld at blueyonder.co.uk Tue Mar 16 18:24:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Mar 16 18:23:44 2004 Subject: [Tutor] here's a printf() function References: <BAY7-F30eO6NJCAj6Qp0006c1d5@hotmail.com> Message-ID: <01ae01c40bad$d14c9000$6401a8c0@xp> > function does, so I made a printf() function that I thought I'd share. > (This list probably gets one of these every other week or so? Lol..) Nope, more like once a year. Most folks just learn to cope with the built in foibles... :-) > for example.) That's what "is" does. If you use "is" interchangeably with > "==" you will make nasty bugs. Your program might behave one way in .py > form, and another in .pyc form, for example. Nope it should be equally wrong in both forms! :-) You are right about is and == being different but the unpredicatability shouldn't happen because in Python we are not comparing memory addresses like we do in C/C++ > another on Tuesday, for that matter, lol.) What they really mean by "object > identity" (to a C programmer like me) is "pointer equality." Every Python > variable is a pointer. Nope again. It's a dangerous mistake to try to equate Python and C++ variables too closely. They work completely differently. Python variable names are keys in a dictionary with their associated variable as the value. You can change the value for any key - as in any dictionary. Also you can't do pointer arithmetic - after all what would adding 3 to a dictionary key do? There is no concept of an address anywhere in the naming scheme. > '==' tests to see if the values at the memory addresses that the > pointers are pointing to are the same. It tests the values certainly but it has no copncept of memory addresses, it really is simply a dictionary lookup. > 'is' tests to see if the pointers are pointing to the same > memory address. Only by an accident of implementation. In some operating systems variables are stored in arrays at a given index(aka handle). In these cases Python would be comparing handle values not memory addresses. Python is much farther away from memory than C/C++. (Although of course it is implemented in C at the basement level. But it can be a dangerous habit to try to equate Python and C too closely.) However your general point is correct. is checks for dentical objects, equality checks for identical values. So: If (A is B) is true then (A == B) is true also If (A == B) is true then (A is B) is still unknown Alan G. From p.hartley at spitech.com Tue Mar 16 21:51:30 2004 From: p.hartley at spitech.com (Hartley, Paul) Date: Tue Mar 16 21:45:46 2004 Subject: [Tutor] Contract work Message-ID: <00d701c40bca$c0bb3490$01eb18ac@paul> I realize this is probably not the right forum for this request. But I would be interested in having someone develop software for my company and writing the software in Python. Any suggestions how I might go about finding people to do the programming? My company is in the Philippines so we would have to do this all online. Kind regards Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040317/6219eb92/attachment.html From shitizb at yahoo.com Wed Mar 17 00:51:19 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 17 00:51:31 2004 Subject: [Tutor] remove me? In-Reply-To: <Pine.LNX.4.44.0403161436340.11687-100000@hkn.eecs.berkeley.edu> Message-ID: <20040317055119.6604.qmail@web41502.mail.yahoo.com> Hi, I too believe there is some problem with your removing prgram. I have been removed twice though i never unsubscribed. Shitiz Bansal Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: On Tue, 16 Mar 2004, Emily Lea Connally wrote: > hey, i thought i had been removed from this list.. how do i re-remove > myself? Hi Emily, Strange. Well, the mailing list software that we use to maintain Python-tutor had been upgraded recently; it's possible that we may still be seeing some wackiness from that upgrade. Try visiting: http://mail.python.org/mailman/listinfo/tutor There should be an 'unsubscribe' form near the bottom of that page; try unsubscribing again. If you run into problems with this, please send a holler to the administrative address "tutor-admin@python.org", and we'll unsubscribe you manually. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor t Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040316/2c5da5e4/attachment.html From stevege at i-way.net.uk Wed Mar 17 06:40:18 2004 From: stevege at i-way.net.uk (Steve George) Date: Wed Mar 17 06:40:41 2004 Subject: [Tutor] Accessing class instances Message-ID: <DD9AA1EA-7807-11D8-8363-000A9575AA4A@i-way.net.uk> Hi, I'm having a bit of a problem understanding how to use modules and class instances. The basic idea in my program is to have a number of classes as follows: MainProgram() "" Does all my start-up stuff and controls it """ Options() """ parses options and stores them as attributes""" DataLoader() """ Loads a data file and allows operations on it """ I put MainProgram() and Options() classes into one single text file and my DataLoader() class into another. When I instantiate my DataLoader object I want it to look at the instance of my Options() class and pull some information from it. At the moment I get: in get_price print Opts.line_size NameError: global name 'Opts' is not defined I think I have two problems going on: a. I don't think I understand how a class can query an instance of a class So here my DataLoader class when it's instantiated needs to query an instance of my Options() class named Opts. At the moment I understand how one module can access another and instantiate an object e.g. DataLoader.dataloader() but I'm less clear how a module can access the instance of that class at runtime. b. Have I mis-used modules? I used the different files/modules thinking that it logically separated how I was thinking about the problem. Howerver, there is some information I need to pass back and forward between them, the use of 'options' is a good example. How do Python programmers normally get around this? Hope I've been clear in my explanation! Thanks, Steve From cybersamurai at terra.com.br Wed Mar 17 07:24:50 2004 From: cybersamurai at terra.com.br (Luiz Siqueira Neto) Date: Wed Mar 17 07:25:32 2004 Subject: [Tutor] setattr and classes Message-ID: <40584392.4030607@terra.com.br> Only a class of object "x" can have the __setattr__ of "x"? From sigurd at 12move.de Wed Mar 17 11:03:39 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Wed Mar 17 11:05:44 2004 Subject: [Tutor] Contract work In-Reply-To: <00d701c40bca$c0bb3490$01eb18ac@paul> (Paul Hartley's message of "Wed, 17 Mar 2004 10:51:30 +0800") References: <00d701c40bca$c0bb3490$01eb18ac@paul> Message-ID: <m3d67bh3fd.fsf@hamster.pflaesterer.de> On 17 Mar 2004, Hartley, Paul <- p.hartley@spitech.com wrote: > I realize this is probably not the right forum for this request. But I would > be interested in having someone develop software for my company and writing > the software in Python. Any suggestions how I might go about finding people to > do the programming? There is a newsgroup (bidirectional gate of a mailing list) comp.lang.python where IMO could be the right place to post your request. There read and write a lot of professionals. Also the website http://www.python.org/ has a job board; you can send your request to the site admins and they will place it there. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Wed Mar 17 11:09:23 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Wed Mar 17 11:10:55 2004 Subject: [Tutor] Accessing class instances In-Reply-To: <DD9AA1EA-7807-11D8-8363-000A9575AA4A@i-way.net.uk> (Steve George's message of "Wed, 17 Mar 2004 11:40:18 +0000") References: <DD9AA1EA-7807-11D8-8363-000A9575AA4A@i-way.net.uk> Message-ID: <m38yhzh31r.fsf@hamster.pflaesterer.de> On 17 Mar 2004, Steve George <- stevege@i-way.net.uk wrote: > I'm having a bit of a problem understanding how to use modules and > class instances. To be able to help you it helps a lot if you write a small example where your problems can be seen. > The basic idea in my program is to have a number of classes as follows: > MainProgram() > "" Does all my start-up stuff and controls it """ > Options() > """ parses options and stores them as attributes""" > DataLoader() > """ Loads a data file and allows operations on it """ I'm not sure if it's a good idea to have her three sparate classes. But before we know what each class does it's hard to tell. > I put MainProgram() and Options() classes into one single text file > and my DataLoader() class into another. > When I instantiate my DataLoader object I want it to look at the > instance of my Options() class and pull some information from it. At > the moment I get: > in get_price > print Opts.line_size > NameError: global name 'Opts' is not defined > I think I have two problems going on: In which file is that code? How did you import the other file? (with example code it would be clear). Karl -- Please do *not* send copies of replies to me. I read the list From bvande at po-box.mcgill.ca Wed Mar 17 14:06:59 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Mar 17 14:37:05 2004 Subject: [Tutor] basic question about help() In-Reply-To: <01a901c40bab$ee842f90$6401a8c0@xp> References: <think001_40571e126a8f6@webmail.thinkware.se> <01a901c40bab$ee842f90$6401a8c0@xp> Message-ID: <4058A1D3.7020701@po-box.mcgill.ca> Alan Gauld said unto the world upon 16/03/2004 18:10: <SNIP> > >>So, how do I make help work? Where do I set this environment >>variable PYTHONDOCS? > > > Depends on OS. But assuming you are on NT/W2K/XP you go into > MyComputer->Properties->Advanced->Environment Variables > (On Win 9X/Me its by editing the C:\AUTOEXEC.BAT file.) > > Either for yourself(probably best) or for the full system > hit New > > Enter the name PYTHONDOCS > and the Value > > E:\PYTHON\DOc > > on my system. > > Hit OK three times and restart Python. > > Alan G. > Hi all, Thanks for the help Alan and Magnus. Alan, I run the dreaded WinMe and haven't yet followed up on your suggestion, but you've given me enough that I think I will be able to work it out; thanks. Magnus Lycka said unto the world upon 16/03/2004 14:58: > Have you worked through the Python tutorial? I think that's a > much better start. Then I'd use the Library reference. That's > a very good source of information, particularly chapter 2. There > are also plenty of other online tutorials and many good books. Magnus, I think you are certainly right that learning Python just with the help() feature would be the hard way! I've worked through (though not necessarily internalized) Lutz and Ascher's Learning Python and was using help() to explore the various modules. Happened to hit upon the "topics" oddness by accident, but once I found it, it began to bother me. I've got O'Reilly's Programming Python and Python in a Nutshell on order, so fairly soon I should have all the materials I need for quite a while. :-) (While I've seen that there are a lot of good looking resources available online, I need a physical book for serious learning.) Anyway, thanks again to both. Also, I have a quick question about the list practices. Is it the general practice of this list to cc all those in a thread? I've not noticed that in any other list before, but I'm happy to play by the local norms (and respect the sig files I've noticed which specifically request not to be cc'ed). Thanks, Best to all, Brian vdB From alan.gauld at blueyonder.co.uk Wed Mar 17 14:49:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Mar 17 14:48:33 2004 Subject: [Tutor] Accessing class instances References: <DD9AA1EA-7807-11D8-8363-000A9575AA4A@i-way.net.uk> Message-ID: <01f001c40c58$f46b3ae0$6401a8c0@xp> > I put MainProgram() and Options() classes into one single text file and > my DataLoader() class into another. > > When I instantiate my DataLoader object I want it to look at the > instance of my Options() class and pull some information from it. The usual way to do this is to pass the OPtions instance into your DataLoaderclass as an argument to the constructor: class Dataloader: def __init__(self,anOptionsInstance): self.options = anOptionsInstance self.options.readOption('FOO') # or whatever... > in get_price > print Opts.line_size > NameError: global name 'Opts' is not defined Its nearly always a bad idea to rely on global variable names in your classes - it severely restricts reusability, and if the name is defined in another module its even worse. Much better to pass the object in as an argument. > instantiate an object e.g. DataLoader.dataloader() but I'm less clear > how a module can access the instance of that class at runtime. import dataLoader opts = Options() myDL = dataLoader.DataLoader(opts) data = myDL.getData() and so on... > b. Have I mis-used modules? Nope sounds like you got the right idea, just needs a wee tweak to make it work as you want. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Wed Mar 17 15:04:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Mar 17 15:03:42 2004 Subject: [Tutor] basic question about help() References: <think001_40571e126a8f6@webmail.thinkware.se> <01a901c40bab$ee842f90$6401a8c0@xp> <4058A1D3.7020701@po-box.mcgill.ca> Message-ID: <020201c40c5b$12fe4ef0$6401a8c0@xp> > Also, I have a quick question about the list practices. Is it the > general practice of this list to cc all those in a thread? I've > not noticed that in any other list before, but I'm happy to play > by the local norms (and respect the sig files I've noticed which > specifically request not to be cc'ed). Thanks, Hmm, I know a few folks ask for no CC but I admit I usually prefer it because I get the digest. If there is no CC I don't see replies till the next digest arrives, whereas with a CC I get replies immediately. Thus I can respond faster to those threads with which I'm involved and read the others at leisure. So I tend to hit Reply All (sorry Karl) as a habit unless I specifically remember that someone has asked me not to. Alan G From isrgish at fusemail.com Wed Mar 17 15:53:32 2004 From: isrgish at fusemail.com (Isr Gish) Date: Wed Mar 17 15:52:44 2004 Subject: [Tutor] remove me? Message-ID: <E1B3i1f-0007aw-QN@fuse1.fusemail.net> I was allso removed a fewstimes without ever unsubscribing. Isr Gish -----Original Message----- >From: "Shitiz Bansal"<shitizb@yahoo.com> >Sent: 3/17/04 12:51:19 AM >To: "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu>, "tutor@python.org"<tutor@python.org> >Subject: Re: [Tutor] remove me? > > >Hi, >I too believe there is some problem with your removing prgram. >I have been removed twice though i never unsubscribed. > >Shitiz Bansal >Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > >On Tue, 16 Mar 2004, Emily Lea Connally wrote: > >> hey, i thought i had been removed from this list.. how do i re-remove >> myself? > > >Hi Emily, > >Strange. Well, the mailing list software that we use to maintain >Python-tutor had been upgraded recently; it's possible that we may still >be seeing some wackiness from that upgrade. > > >Try visiting: > >http://mail.python.org/mailman/listinfo/tutor > >There should be an 'unsubscribe' form near the bottom of that page; try >unsubscribing again. > > >If you run into problems with this, please send a holler to the >administrative address "tutor-admin@python.org", and we'll unsubscribe you >manually. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor t >Do you Yahoo!? >Yahoo! Mail - More reliable, more storage, less spam From sigurd at 12move.de Wed Mar 17 15:55:49 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Wed Mar 17 16:00:36 2004 Subject: [Tutor] basic question about help() In-Reply-To: <020201c40c5b$12fe4ef0$6401a8c0@xp> (Alan Gauld's message of "Wed, 17 Mar 2004 20:04:37 -0000") References: <think001_40571e126a8f6@webmail.thinkware.se> <01a901c40bab$ee842f90$6401a8c0@xp> <4058A1D3.7020701@po-box.mcgill.ca> <020201c40c5b$12fe4ef0$6401a8c0@xp> Message-ID: <m3hdwnfbnh.fsf@hamster.pflaesterer.de> On 17 Mar 2004, Alan Gauld <- alan.gauld@blueyonder.co.uk wrote: >> Also, I have a quick question about the list practices. Is it the >> general practice of this list to cc all those in a thread? I've >> not noticed that in any other list before, but I'm happy to play >> by the local norms (and respect the sig files I've noticed which >> specifically request not to be cc'ed). Thanks, > Hmm, I know a few folks ask for no CC but I admit I usually prefer Who might that be? > it because I get the digest. If there is no CC I don't see replies As a special for you (for your great tutorial) I add you as recipient. [...] > So I tend to hit Reply All (sorry Karl) as a habit unless I No problem; I can live with it :-) The readers and writers of the most lists (closed lists like this one) I read insist on not getting CCs since every writer is subscribed to the list. Now we most only find a way to get back on topic so we don't have too many OT postings. I don't know anything; I can only write about my joy about the new os.walk. I used it recently to write some code which helped me cleaning some directories (Cygwin install directories). I needed only some minutes and the code is clear and only several lines long. I like generators every day a bit more. Karl -- Please do *not* send copies of replies to me. I read the list From gustabares at verizon.net Wed Mar 17 17:48:51 2004 From: gustabares at verizon.net (Gus Tabares) Date: Wed Mar 17 17:48:52 2004 Subject: [Tutor] remove me? In-Reply-To: <E1B3i1f-0007aw-QN@fuse1.fusemail.net> References: <E1B3i1f-0007aw-QN@fuse1.fusemail.net> Message-ID: <200403171748.51390.gustabares@verizon.net> On Wednesday 17 March 2004 15:53, Isr Gish wrote: I guess I'll add that I was also removed not too long ago without unsubscribing. Gus Tabares > I was allso removed a fewstimes without ever unsubscribing. > > Isr Gish > > -----Original Message----- > > >From: "Shitiz Bansal"<shitizb@yahoo.com> > >Sent: 3/17/04 12:51:19 AM > >To: "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu>, > > "tutor@python.org"<tutor@python.org> Subject: Re: [Tutor] remove me? > > > > > >Hi, > >I too believe there is some problem with your removing prgram. > >I have been removed twice though i never unsubscribed. > > > >Shitiz Bansal > >Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > >On Tue, 16 Mar 2004, Emily Lea Connally wrote: > >> hey, i thought i had been removed from this list.. how do i re-remove > >> myself? > > > >Hi Emily, > > > >Strange. Well, the mailing list software that we use to maintain > >Python-tutor had been upgraded recently; it's possible that we may > > still be seeing some wackiness from that upgrade. > > > > > >Try visiting: > > > >http://mail.python.org/mailman/listinfo/tutor > > > >There should be an 'unsubscribe' form near the bottom of that page; try > >unsubscribing again. > > > > > >If you run into problems with this, please send a holler to the > >administrative address "tutor-admin@python.org", and we'll unsubscribe > > you manually. > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor t > >Do you Yahoo!? > >Yahoo! Mail - More reliable, more storage, less spam > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From burton_boy03 at hotmail.com Wed Mar 17 19:42:25 2004 From: burton_boy03 at hotmail.com (Charles Richard) Date: Wed Mar 17 19:42:30 2004 Subject: [Tutor] (no subject) Message-ID: <BAY16-F19cP1jxTxXPh00015b6c@hotmail.com> i want to be able to read and write python and also to write programms plz help me learn. HateCell _________________________________________________________________ http://join.msn.com/?pgmarket=en-ca&page=byoa/prem&xAPID=1994&DI=1034&SU=http://hotmail.com/enca&HL=Market_MSNIS_Taglines From amonroe at columbus.rr.com Wed Mar 17 20:29:08 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Mar 17 20:23:21 2004 Subject: [Tutor] (no subject) In-Reply-To: <BAY16-F19cP1jxTxXPh00015b6c@hotmail.com> References: <BAY16-F19cP1jxTxXPh00015b6c@hotmail.com> Message-ID: <139865481226.20040317202908@columbus.rr.com> > i want to be able to read and write python and also to write programms plz > help me learn. Step 1: Have you installed it on your box yet? Are you on Windows or Linux? Alan From tim at johnsons-web.com Wed Mar 17 20:33:17 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Mar 17 20:25:19 2004 Subject: [Tutor] remove me? In-Reply-To: <200403171748.51390.gustabares@verizon.net> References: <E1B3i1f-0007aw-QN@fuse1.fusemail.net> <200403171748.51390.gustabares@verizon.net> Message-ID: <20040318013317.GY5967@johnsons-web.com> * Gus Tabares <gustabares@verizon.net> [040317 14:03]: > On Wednesday 17 March 2004 15:53, Isr Gish wrote: > > I guess I'll add that I was also removed not too long ago without > unsubscribing. My situation is a little different. Even though I've been on list for about 3 years, if I haven't posted something for a month, and do so, I get an automated email meant for a new list user. <G>I guess that makes me an eternal newbie! tj > Gus Tabares > > > > I was allso removed a fewstimes without ever unsubscribing. > > > > Isr Gish > > > > -----Original Message----- > > > > >From: "Shitiz Bansal"<shitizb@yahoo.com> > > >Sent: 3/17/04 12:51:19 AM > > >To: "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu>, > > > "tutor@python.org"<tutor@python.org> Subject: Re: [Tutor] remove me? > > > > > > > > >Hi, > > >I too believe there is some problem with your removing prgram. > > >I have been removed twice though i never unsubscribed. > > > > > >Shitiz Bansal > > >Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > > > >On Tue, 16 Mar 2004, Emily Lea Connally wrote: > > >> hey, i thought i had been removed from this list.. how do i re-remove > > >> myself? > > > > > >Hi Emily, > > > > > >Strange. Well, the mailing list software that we use to maintain > > >Python-tutor had been upgraded recently; it's possible that we may > > > still be seeing some wackiness from that upgrade. > > > > > > > > >Try visiting: > > > > > >http://mail.python.org/mailman/listinfo/tutor > > > > > >There should be an 'unsubscribe' form near the bottom of that page; try > > >unsubscribing again. > > > > > > > > >If you run into problems with this, please send a holler to the > > >administrative address "tutor-admin@python.org", and we'll unsubscribe > > > you manually. > > > > > > > > >_______________________________________________ > > >Tutor maillist - Tutor@python.org > > >http://mail.python.org/mailman/listinfo/tutor t > > >Do you Yahoo!? > > >Yahoo! Mail - More reliable, more storage, less spam > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From dyoo at hkn.eecs.berkeley.edu Wed Mar 17 23:45:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 17 23:45:33 2004 Subject: [Tutor] (no subject) In-Reply-To: <BAY16-F19cP1jxTxXPh00015b6c@hotmail.com> Message-ID: <Pine.LNX.4.44.0403172038150.29630-100000@hkn.eecs.berkeley.edu> On Wed, 17 Mar 2004, Charles Richard wrote: > i want to be able to read and write python and also to write programms > plz help me learn. Hi Charles, Welcome aboard! Have you had a chance to play around with Python yet? The "Python for Non-Programmers" page has links to all sorts of tutorials: http://www.python.org/topics/learn/non-prog.html (We actually have a few of those tutorial authors here on Python-Tutor!) Please feel free to ask questions about them on the mailing list; we'll be happy to help you get started. All of the tutorials there are pretty good, although I think the official Python tutorial: http://www.python.org/doc/current/tut/ is actually slightly hard for newcomers because it covers a deluge of Python's features. But if you have programmed in another language in the past, then that kind of presentation is probably the fastest way to get knee-deep. Many of the other tutorials on the "Python for Non-Programmers" page are gentler, so if you find yourself getting stuck on one, try another and see if it's more to your liking. Have you had any programming experience before? Talk to you later! From dyoo at hkn.eecs.berkeley.edu Wed Mar 17 23:49:18 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 17 23:49:23 2004 Subject: [Tutor] remove me? In-Reply-To: <20040318013317.GY5967@johnsons-web.com> Message-ID: <Pine.LNX.4.44.0403172045460.29630-100000@hkn.eecs.berkeley.edu> On Wed, 17 Mar 2004, Tim Johnson wrote: > > I guess I'll add that I was also removed not too long ago without > > unsubscribing. > > My situation is a little different. Even though I've been on > list for about 3 years, if I haven't posted something for a > month, and do so, I get an automated email meant for a new > list user. > > <G>I guess that makes me an eternal newbie! Hi Tim, This happens to me too. *grin* Well, I've mentioned it to the folks on the other Python mailing lists; it may have just been a fluke during the software update. I'll keep watching and see if wacky things continue to happen. My apologies for this; it's slightly out of my control. From dyoo at hkn.eecs.berkeley.edu Thu Mar 18 00:07:47 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 18 00:07:57 2004 Subject: [Tutor] setattr and classes In-Reply-To: <40584392.4030607@terra.com.br> Message-ID: <Pine.LNX.4.44.0403172050590.29630-100000@hkn.eecs.berkeley.edu> On Wed, 17 Mar 2004, Luiz Siqueira Neto wrote: > Only a class of object "x" can have the __setattr__ of "x"? Hi Luiz, Let me make sure I understand the question: are you asking if it's possible to define the __setattr__ of individual instances? If not, I have to admit that I'm confused. Can you rephrase your question? A concrete example may help make things more clear for me. But if so, then yes, it's possible to customize the methods of individual instances in Python. Here's an example: ### >>> class Foo: ... def mymethod(self): ... print "I am a method" ... >>> f = Foo() >>> f.mymethod() I am a method ### Ok, so here's a toy class. It's possible to redefine 'mymethod()' here specifically just for one instance: ### >>> def some_function(): ... print "huh?" ... >>> another_f.mymethod = some_function >>> another_f.mymethod() huh? >>> f.mymethod() I am a method ### This doesn't quite work, since some_function isn't taking in a 'self'. But it's close, and it shows that we can jerry-rig a function to an instance. But it's also possible to attach arbitrary methods that are also 'self' aware. A working way to do this is with a function called new.instancemethod(): ### >>> f = Foo() >>> def talk(self): ... print "I, a", self, "am self aware" ... >>> import new >>> f.talk = new.instancemethod(talk, f, Foo) >>> f.talk() I, a <__main__.Foo instance at 0x41ee0> am self aware ### So this 'f' instance is a little bit more individual than the rest of its kin: it's the only Foo with a talk() method. That being said, it may not be a good idea to do this kind of dynamic redefinition. It becomes more messy to figure out what method an instance has: classes are supposed to guarantee that certain methods are attached to a class. But it's interesting to know we can do this, even if we never do it in practice. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Mar 18 00:36:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 18 00:36:57 2004 Subject: [Tutor] Accessing class instances [Party people] In-Reply-To: <DD9AA1EA-7807-11D8-8363-000A9575AA4A@i-way.net.uk> Message-ID: <Pine.LNX.4.44.0403172108150.29630-100000@hkn.eecs.berkeley.edu> On Wed, 17 Mar 2004, Steve George wrote: > The basic idea in my program is to have a number of classes as follows: > > MainProgram() > "" Does all my start-up stuff and controls it """ > > Options() > """ parses options and stores them as attributes""" > > DataLoader() > """ Loads a data file and allows operations on it """ > > I put MainProgram() and Options() classes into one single text file and > my DataLoader() class into another. > > When I instantiate my DataLoader object I want it to look at the > instance of my Options() class and pull some information from it. At > the moment I get: > > in get_price > print Opts.line_size > NameError: global name 'Opts' is not defined Hi Steve, I think we'll need to see more code; the problem here might be as simple as a capitalizing problem, or something more subtle. > a. I don't think I understand how a class can query an instance of a > class So here my DataLoader class when it's instantiated needs to query > an instance of my Options() class named Opts. The DataLoader appears to need to talk to Opts. Did you send Opts out to the DataLoader instance? Where is Opts defined, in the Operations module? > At the moment I understand how one module can access another and > instantiate an object e.g. DataLoader.dataloader() but I'm less clear > how a module can access the instance of that class at runtime. It's possible to access it by name, but you probably will need to put the module name in there too. So say that we're in DataLoader, and we want to get at a variable called "Opts" that lives in the 'options' module. While we're standing in DataLoader, we need to say: options.Opts > b. Have I mis-used modules? > I used the different files/modules thinking that it logically separated > how I was thinking about the problem. Howerver, there is some > information I need to pass back and forward between them, the use of > 'options' is a good example. How do Python programmers normally get > around this? When classes need to communicate with each other, it's often possible to "matchmake" them. Here's an example: ### >>> class Person: ... def __init__(self, name): ... self.name = name ... self.friends = [] ... def meet(self, other): ... self.friends.append(other) ... def greet(self): ... for friend in self.friends: ... print "I", self.name, "greet you,", friend.name ... >>> a = Person("Alice") >>> b = Person("Bob") >>> a.meet(b) >>> a.greet() I Alice greet you, Bob >>> >>> >>> c = Person("Cathy") >>> a.meet(c) >>> a.greet() I Alice greet you, Bob I Alice greet you, Cathy ### Here, we're letting each Person talk to one other by letting them "meet" each other first. What's neat is that this approach allows us to tie these folks together in interesting and wacky ways: ### >>> def party(people): ... for p in people: p.greet() ... >>> c.meet(b) >>> b.meet(a) >>> party([a, b, c]) I Alice greet you, Bob I Alice greet you, Cathy I Bob greet you, Alice I Cathy greet you, Bob ### The key to this is to let each instance keep a little bit of memory of who they've met. In the Person class definition, we say that every Person remembers by keeping track of their aquaintences in a 'people' list. But if a person just needs to remember one person, we can just say: ### >>> class SolitaryPerson: ... def __init__(self, name): ... self.name = name ... self.friend = None ... def meet(self, other): ... self.friend = other ... def greet(self): ... if self.friend: ... print "I", self.name, "greet you,", self.friend.name ... else: ... print "but I don't have any friends. Waaa." ... >>> d = SolitaryPerson("Dan") >>> d.greet() But I Dan don't have any friends. Waaa. >>> d.meet(a) >>> d.meet(b) >>> d.meet(c) >>> d.meet(d) >>> d.greet() I Dan greet you, Dan ### in which case, we get a SolitaryPerson who is really close-knit. Anyway, so no lists are really necessary. But the idea of these instances talking to each other, keeping tabs on each other by maintaining some state in 'self', should be a little clearer. This approach of getting instances aware of each other is usually preferred over hardcoding references to other modules --- it's a little easier to redefine the ties that bind each other with the matchmaking approach. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Mar 18 00:41:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 18 00:41:35 2004 Subject: [Tutor] Accessing class instances [Party people] In-Reply-To: <Pine.LNX.4.44.0403172108150.29630-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0403172137540.29630-100000@hkn.eecs.berkeley.edu> > But if a person just needs to remember one person, we can just say: > > ### > >>> class SolitaryPerson: > ... def __init__(self, name): > ... self.name = name > ... self.friend = None > ... def meet(self, other): > ... self.friend = other > ... def greet(self): > ... if self.friend: > ... print "I", self.name, "greet you,", self.friend.name > ... else: > ... print "but I don't have any friends. Waaa." > ... > >>> d = SolitaryPerson("Dan") > >>> d.greet() > But I Dan don't have any friends. Waaa. ^^^^ Argh. The last example was a bad case of cut-and-paste; the method as written above won't produce that output. Let me try that again. ### >>> class SolitaryPerson: ... def __init__(self, name): ... self.name = name ... self.friend = None ... def meet(self, other): ... self.friend = other ... def greet(self): ... if self.friend: ... print "I", self.name, "greet you,", self.friend.name ... else: ... print "but I", self.name, "don't have any friends. Waaa." ... >>> d = SolitaryPerson("Dan") >>> d.greet() but I Dan don't have any friends. Waaa. >>> d.meet(a) >>> d.meet(b); d.meet(c) ; d.meet(d) >>> d.greet() I Dan greet you, Dan ### Better, yet sad in a kind of pathetic way. *grin* My apologies! From kp8 at mac.com Thu Mar 18 14:49:11 2004 From: kp8 at mac.com (kevin parks) Date: Thu Mar 18 14:51:13 2004 Subject: [Tutor] randomly gen values from .000001 to 10 In-Reply-To: <E1B40uf-0003FH-AE@mail.python.org> Message-ID: <53C5080E-7915-11D8-9ECE-003065555ABC@mac.com> Hi. I need to generate random values from 0.000001 to 10.00 i know that i can scale values with something like random.random()*.01 to get smaller values or random.random()*10 to get larger, but i am not sure how to get good random values over the whole range. I'd also love to be able to able to generate 0.000001 to 10.00 that were not an even distribution but tended towards certain values, but that maybe a problem for a different day... for now i would be happy with just getting 0.000001 to 10.00 cheers, kevin U-Va From dyoo at hkn.eecs.berkeley.edu Thu Mar 18 16:13:18 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 18 16:13:24 2004 Subject: [Tutor] randomly gen values from .000001 to 10 In-Reply-To: <53C5080E-7915-11D8-9ECE-003065555ABC@mac.com> Message-ID: <Pine.LNX.4.44.0403181304210.29269-100000@hkn.eecs.berkeley.edu> On Thu, 18 Mar 2004, kevin parks wrote: > i know that i can scale values with something like random.random()*.01 > > to get smaller values or random.random()*10 to get larger, but i am not > sure how to get good random values over the whole range. Hi Kevin, Let's look at that that second example that you've tried: ### >>> import random >>> random.random()*10 9.5044186602992262 >>> random.random()*10 9.1268490268847771 >>> random.random()*10 4.4645183806858117 >>> random.random()*10 9.3013894173392124 >>> random.random()*10 9.2990688724785358 >>> random.random()*10 9.4395125993629172 >>> random.random()*10 1.0715089388394972 >>> random.random()*10 8.7858219429482141 >>> random.random()*10 8.9274058823317084 ### But isn't this what we're looking for? This is giving numbers between 0 and 10. > I'd also love to be able to able to generate 0.000001 to 10.00 that were > not an even distribution but tended towards certain values, but that > maybe a problem for a different day. The other random "distributions" that the Library Documentation talks about in: http://python.org/doc/lib/module-random.html might be applicable. random.random() uses a uniform distribution, so every choice is equally likely. But if we wanted to get a few random numbers that were mostly centered near 5, we can use the normalvariate() function: ### >>> random.normalvariate(5, 1) 6.3978911394573048 >>> random.normalvariate(5, 1) 4.084965225312204 >>> random.normalvariate(5, 1) 5.7286811794960588 >>> random.normalvariate(5, 1) 3.296976254913472 >>> random.normalvariate(5, 1) 3.336182140531454 >>> random.normalvariate(5, 1) 5.5250707868445943 ### Talk to you later! From dyoo at hkn.eecs.berkeley.edu Thu Mar 18 18:21:18 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 18 18:21:28 2004 Subject: [Tutor] (no subject) In-Reply-To: <BAY16-F76CfpnLtqq6A0001955b@hotmail.com> Message-ID: <Pine.LNX.4.44.0403181516100.10103-100000@hkn.eecs.berkeley.edu> On Thu, 18 Mar 2004, Charles Richard wrote: > but are they [the tutorials] free? Hi Charles, (By the way, please keep tutor@python.org in CC, so that everyone there can help answer your questions.) Yes, all the tutorials in: http://www.python.org/topics/learn/non-prog.html are free to either browser or download. The tools you'll need to actually do some programming are also free to download. You can download Python from: http://python.org/2.3.3/ And of course, we won't charge you money if you ask questions on Python-tutor. *grin* Talk to you later! From kp8 at mac.com Thu Mar 18 19:16:56 2004 From: kp8 at mac.com (kevin parks) Date: Thu Mar 18 19:18:24 2004 Subject: [Tutor] randomly gen values from .000001 to 10 In-Reply-To: <Pine.LNX.4.44.0403181304210.29269-100000@hkn.eecs.berkeley.edu> Message-ID: <BB24ADC6-793A-11D8-BE29-003065555ABC@mac.com> Ah -HA!! actually all i need it to take that and add 0.000001 to it to make sure i don't get anything lower (perhaps that is not even possible? Is it statistically possible that random.random() also put out an actual 0? but since i am not needing to be so precise i can actually just do: import random foo = (random.random() * 10) + 0.000001 and get numbers from 0.000001 --> 10. 0.000001 which is actually good enough for gov't work. I don't care that i go over, but i do care if i get less than 0.000001 which would make my filter blow up. >> I'd also love to be able to able to generate 0.000001 to 10.00 that >> were >> not an even distribution but tended towards certain values, but that >> maybe a problem for a different day. > > The other random "distributions" that the Library Documentation talks > about in: > > http://python.org/doc/lib/module-random.html > > might be applicable. Yes, i saw these and am actually in the library now figuring out which one does what i need. looks like the one you mention: random.normalvariate(5, 1) is the ticket (just change the parameters). But i still need to find a book that tells me (or better shows me a picture as well) what some of these other distributions do. I use to have a distribution cheet sheet that would show what some of these look like, but other than beta and gaussian i am foggy on what these others do. Thanks Danny! you are the man! cheers, kevin > random.random() uses a uniform distribution, so every choice is equally > likely. But if we wanted to get a few random numbers that were mostly > centered near 5, we can use the normalvariate() function: > > ### >>>> random.normalvariate(5, 1) > 6.3978911394573048 >>>> random.normalvariate(5, 1) > 4.084965225312204 >>>> random.normalvariate(5, 1) > 5.7286811794960588 >>>> random.normalvariate(5, 1) > 3.296976254913472 >>>> random.normalvariate(5, 1) > 3.336182140531454 >>>> random.normalvariate(5, 1) > 5.5250707868445943 > ### From dbroadwell at mindspring.com Thu Mar 18 21:36:23 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Thu Mar 18 21:32:55 2004 Subject: [Tutor] randomly gen values from .000001 to 10 In-Reply-To: <BB24ADC6-793A-11D8-BE29-003065555ABC@mac.com> Message-ID: <MBBBKPICGBKFODJNCCLJMENBDCAA.dbroadwell@mindspring.com> > import random > foo = (random.random() * 10) + 0.000001 > > and get numbers from 0.000001 --> 10. 0.000001 > > which is actually good enough for gov't work. I don't care that I go > over, but I do care if I get less than 0.000001 which would make my > filter blow up. ? if foo is not between 0.000001 and 10.: get_a_new_random_number() -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From alex at alexnewby.com Fri Mar 19 01:08:32 2004 From: alex at alexnewby.com (Alex Newby) Date: Fri Mar 19 01:09:14 2004 Subject: [Tutor] Accessing class instances [Party people] Message-ID: <1079676512.25973.182952733@webmail.messagingengine.com> This example is really great! I just thought you should know:) Sincerely, Alex Newby Date: Wed, 17 Mar 2004 21:36:48 -0800 (PST) From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Here, we're letting each Person talk to one other by letting them "meet" each other first. What's neat is that this approach allows us to tie these folks together in interesting and wacky ways: ### >>> def party(people): ... for p in people: p.greet() ... >>> c.meet(b) >>> b.meet(a) >>> party([a, b, c]) I Alice greet you, Bob I Alice greet you, Cathy I Bob greet you, Alice I Cathy greet you, Bob ### The key to this is to let each instance keep a little bit of memory of who they've met. In the Person class definition, we say that every Person remembers by keeping track of their aquaintences in a 'people' list. But if a person just needs to remember one person, we can just say: ### >>> class SolitaryPerson: ... def __init__(self, name): ... self.name = name ... self.friend = None ... def meet(self, other): ... self.friend = other ... def greet(self): ... if self.friend: ... print "I", self.name, "greet you,", self.friend.name ... else: ... print "but I don't have any friends. Waaa." ... >>> d = SolitaryPerson("Dan") >>> d.greet() But I Dan don't have any friends. Waaa. >>> d.meet(a) >>> d.meet(b) >>> d.meet(c) >>> d.meet(d) >>> d.greet() I Dan greet you, Dan ### in which case, we get a SolitaryPerson who is really close-knit. Anyway, so no lists are really necessary. But the idea of these instances talking to each other, keeping tabs on each other by maintaining some state in 'self', should be a little clearer. This approach of getting instances aware of each other is usually preferred over hardcoding references to other modules --- it's a little easier to redefine the ties that bind each other with the matchmaking approach. Hope this helps! From vicki at stanfield.net Fri Mar 19 11:08:21 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Fri Mar 19 11:08:31 2004 Subject: [Tutor] Iterating through tokens from a split command Message-ID: <64557.206.53.226.235.1079712501.squirrel@www.thepenguin.org> I am getting an Index Error as I loop through some data from an input file. I don't get the error until several iterations into the data. Here is the code followed by an example of the input. The index error comes on the first if statement inside the while loop. TIA, --vicki ------------------------------------ import fileinput, time, binascii class ConvertFile: #Open logfile with name selected inputfile = open('F:/TimeResolve.dat','r') outputfile = open('F:/ConvertedTR.dat','w+') new = "" EndOfData = 0 try: line = inputfile.readline() if line =="": EndOfData=1 tokens=line.split("|") i=0 while not EndOfData: outputfile.write("counter is "+str(i)+".\n") if tokens[i] == '0x11': new = '0x02|' outputfile.write(new) elif tokens[i] == '0x03': outputfile.write(tokens[i]+"|") elif len(tokens[i])==4: new=binascii.hexlify(tokens[i][3])+"|" outputfile.write('0x'+new) elif len(tokens[i])==3: new = '0x30|' new2=binascii.hexlify(tokens[i][2])+"|" outputfile.write(new+"0x"+new2) else: print "Just blah.\n" new = "blah" outputfile.write(new) i=i+1 except IOError: print "Got IO Error.\n" outputfile.flush() inputfile.close() outputfile.close() if __name__ == "__main__": ConvertFile() ----------------------------- And the data: 0x11|0x4|0x14|0x21|0x0|0x21|0x7a|0x3|0x11|0x4|0x14|0x20|0x0|0x20|0x7a|0x3|0x11|0x4|0x0|0x0|0x0|0x45|0x2b|0x3|0x11|0x4|0x14|0x10|0x0|0x10|0x7a|0x3|0x11|0x8|0x16|0x91|0x0|0x0|0x0|0x0|0x0|0x0|0xe9|0x3|0x11|0x8|0x16|0x90|0x41|0xa9|0xe9|0xed|0x80|0x12|0x96|0x3|0x11|0x8|0x16|0x93|0x41|0x29|0xfd|0x4|0xf8|0x2f|0xad|0x3|0x11|0x8|0x16|0x92|0x0|0x0|0x0|0x0|0x0|0x0|0xea|0x3|0x11|0x8|0x16|0x95|0x0|0x0|0x0|0x0|0x0|0x0|0xed|0x3|0x11|0x8|0x16|0x94|0x0|0x0|0x0|0x0|0x0|0x0|0xec|0x3|0x11|0x2e|0x16|0x10|0x44|0xfa|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0xd6|0x3|0x11|0x2e|0x16|0x20|0x44|0xfa|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0x0|0xe6|0x3|0x11|0x2e|0x16|0x30|0x44|0xfa|0x0|0x0|0x3d|0x92|0x1f|0x6d|0xc2|0xbf|0xce|0x2|0x39|0x92|0x3b|0x6f|0x3f|0x1|! 0x42|0xfd|0x45|0xd8|0x46|0xdf|0x47|0x2d|0x46|0xb1|0x46|0x2|0x44|0x22|0x40|0x7e|0x3c|0x7d|0x39|0xa2|0x38|0x5b|0x38|0x55|0x38|0xdc|0x51|0x3| "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From John.Ertl at fnmoc.navy.mil Fri Mar 19 12:47:28 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Fri Mar 19 12:43:53 2004 Subject: [Tutor] MIME from string? Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C078@lanexc107p.fnmoc.navy.mil> I am just starting to investigate MIME and how to use it in a web service to send images using ZSI SOAP. I have been trying to take a multipart mime message and read it in and parse it. The message is from a ZSI test (that uses mimetools...now depricated). I have done the following: def parsseMessage(mime): msgstring = mime msg = email.message_from_string(msgstring) print msg.is_multipart() print msg.get_content_maintype() for part in msg.walk(): print part.get_content_type() The output is: False text text/plain How do I read in a MIME message from a string and have it recognize that it is a multipart message. mime = """ Return-Path: <rsalz@zolera.com> Received: from zolera.com (os390.zolera.com [10.0.1.9]) by zolera.com (8.11.0/8.11.0) with ESMTP id f57I2sf00832 for <rsalz@zolera.com>; Thu, 7 Jun 2001 14:02:54 -0400 Sender: rsalz@zolera.com Message-ID: <3B1FC1D1.FF6B21B4@zolera.com> Date: Thu, 07 Jun 2001 14:02:57 -0400 From: Rich Salz <rsalz@zolera.com> X-Mailer: Mozilla 4.72 [en] (X11; U; Linux 2.2.14-5.0 i686) X-Accept-Language: en MIME-Version: 1.0 To: rsalz@zolera.com Subject: mime with attachments Content-Type: multipart/mixed; boundary="------------68E4BAC5B266315E42428C64" Status: R This is a multi-part message in MIME format. --------------68E4BAC5B266315E42428C64 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit <SOAP-ENV:Envelope xmlns="http://www.example.com/schemas/TEST" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"> <SOAP-ENV:Body> <hreftest> <stringtest href="cid:part1@zolera.com"/> <b64 href="cid:partii@zolera.com"/> <xmltest href="cid:12@zolera.com"/> </hreftest> </SOAP-ENV:Body> </SOAP-ENV:Envelope> --------------68E4BAC5B266315E42428C64 Content-Type: text/plain; charset=us-ascii; name="abs.txt" Content-Transfer-Encoding: 7bit Content-ID: <part1@zolera.com> Content-Disposition: inline; filename="abs.txt" Digitial Signatures in a Web Services World An influential Forrestor report created the term inverted security: it's not about who you keep out, it's about who you let in. Customer portals, without a costly PKI deployment or application integration issues. --------------68E4BAC5B266315E42428C64 Content-Type: application/pdf; name="gmpharma.pdf" Content-Transfer-Encoding: base64 Content-ID: <partii@zolera.com> Content-Disposition: inline; filename="gmpharma.pdf" JVBERi0xLjINJeLjz9MNCjQzIDAgb2JqDTw8IA0vTGluZWFyaXplZCAxIA0vTyA0NSANL0gg WyAxMTQ0IDM5NiBdIA0vTCA2NjkwMiANL0UgMTAyODIgDS9OIDkgDS9UIDY1OTI0IA0+PiAN RB3nwVOQH9JpmFv6Ri2Zq7mlddSS2B5WcZwvAP+gy9QtuYlfqj1rsi9WqJOszzHXmXZ8fXxK XBBztIpgbkRrd+SGtY4QXo0fX0VN86uKXwtrkd7h1qiq2FUtXl6uNfnCoyX1Dve1O3RPRyhG sKn6fLMb+uSSIHPQkClRBwu5gechz/1PBUBSB34jXbPdMTIb+/wRP+pauSAhLBzFELDOgk5b PaIPAnIudFovQTc7Df2Ws9Atz4Bua+oINphIOojogG5LP3Tb3oNu8bsmuK+wFXEdbfgFIx+G gKULYx5A2WnaDXB5JeoRQg90S0HcX2dCPmRCqDXB/aX34KujsPwJ/UpRdxXPeAftDkQS6hag bh/yTOiUyqBz9CzxnyMYQGDO0jrUZ47kkWfmYvVg --------------68E4BAC5B266315E42428C64 Content-ID: <12@zolera.com> <foo xmlns="example.com" xmlns:Z="zolera"> this is a foo <b xmlns:Z="zolera">redundnant ns decl</b> <b Z:x="this was first" Z:a="2nd-orig">b test</b> </foo> --------------68E4BAC5B266315E42428C64-- """ John C. Ertl Fleet Numerical Meteorology & Oceanography Center 7 Grace Hopper Ave Monterey, CA 93943 phone: (831) 656-5704 fax: (831) 656-4363 From sigurd at 12move.de Fri Mar 19 13:44:21 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri Mar 19 13:45:37 2004 Subject: [Tutor] Iterating through tokens from a split command In-Reply-To: <64557.206.53.226.235.1079712501.squirrel@www.thepenguin.org> (Vicki Stanfield's message of "Fri, 19 Mar 2004 11:08:21 -0500 (EST)") References: <64557.206.53.226.235.1079712501.squirrel@www.thepenguin.org> Message-ID: <m3brmsr8bh.fsf@hamster.pflaesterer.de> On 19 Mar 2004, Vicki Stanfield <- vicki@stanfield.net wrote: > I am getting an Index Error as I loop through some data from an input > file. I don't get the error until several iterations into the data. Here > is the > code followed by an example of the input. The index error comes on the > first if statement inside the while loop. Can you explain what you want to achieve? And why you use a class for something which is just a function? [...] > EndOfData = 0 > try: > line = inputfile.readline() > if line =="": > EndOfData=1 > tokens=line.split("|") > i=0 > while not EndOfData: If you have a line EndOfData is here false and will never change. So you loop forever. [...] > i=i+1 You increment every loop cycle `i' which gets used as index variable. Sooner or later you'll get an index error. [...] > if __name__ == "__main__": > ConvertFile() Why a class? Karl -- Please do *not* send copies of replies to me. I read the list From dyoo at hkn.eecs.berkeley.edu Fri Mar 19 13:50:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 19 13:50:07 2004 Subject: [Tutor] randomly gen values from .000001 to 10 In-Reply-To: <BB24ADC6-793A-11D8-BE29-003065555ABC@mac.com> Message-ID: <Pine.LNX.4.44.0403191025300.28474-100000@hkn.eecs.berkeley.edu> On Thu, 18 Mar 2004, kevin parks wrote: > Ah -HA!! actually all i need it to take that and add 0.000001 to it to > make sure i don't get anything lower (perhaps that is not even possible? > Is it statistically possible that random.random() also put out an actual > 0? Hi Kevin, Yes, it's possible for random.random() to emit zero. In the 'random' docs, there's a small note that: """ random() Return the next random floating point number in the range [0.0, 1.0). """ The documentation is actually using a math notation called "half-open" intervals. When it says [0.0, 1.0). It translates to "anything between zero and 1, including zero, but not including 1.0. The notation [a, b) tries to suggest that we're including the left endpoint, but not the right endpoint. Not sure if that makes sense visually --- are curvy surfaces less adhesive than flat surfaces? --- but I hope that idea is a little clearer. But we've already seen something similar to half-open intervals: Python's range() operator can take two endpoints, and returns all integers in that range: ### >>> range(7, 17) [7, 8, 9, 10, 11, 12, 13, 14, 15, 16] ### Here, we see that range() returns all the integers in the "half-open" interval [7, 17). Half-intervals have nice properties. In particular, they "glue" together nicely: [a, b) + [b, c) ====> [a, c) Hope this helps! From max_ig at yahoo.com Fri Mar 19 13:58:07 2004 From: max_ig at yahoo.com (MI) Date: Fri Mar 19 13:58:17 2004 Subject: [Tutor] Unsuscribe Message-ID: <20040319185807.44826.qmail@web11305.mail.yahoo.com> I used to be suscribed to this list and unsuscribed about 6 month ago. Some how I began receiving emails again. How can unsuscribe from here again? Max __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From alan.gauld at blueyonder.co.uk Fri Mar 19 16:23:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Mar 19 16:23:28 2004 Subject: [Tutor] randomly gen values from .000001 to 10 References: <53C5080E-7915-11D8-9ECE-003065555ABC@mac.com> Message-ID: <02a401c40df8$7d018a80$6401a8c0@xp> > I'd also love to be able to able to generate 0.000001 to 10.00 that > were not an even distribution but tended towards certain values, but > that maybe a problem for a different day... for now i would be happy > with just getting 0.000001 to 10.00 Not that hard provided you don't need a precisely controlled distribution. Try this to bias the numbers to the high end: >>> for i in range(20): ... n = random.random() ... print n < 0.5 and n*2 or n ... HTH, Alan G. From alan.gauld at blueyonder.co.uk Fri Mar 19 16:35:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Mar 19 16:35:24 2004 Subject: [Tutor] Iterating through tokens from a split command References: <64557.206.53.226.235.1079712501.squirrel@www.thepenguin.org> Message-ID: <02b101c40dfa$26e5dc80$6401a8c0@xp> Hi Vicki, A couple of things here. First you only ever read a single line from the file. You then iterate over the tokens in that line but never stop - hence the index error! You probably want to restructure it soomething like: for line in inputfile.readlines(): #readlines, plural! tokens = line.split['|'] for token in tokens: # iterates over the tokens if token == '0x11': new = '0x02|' outputfile.write(new) elif token == '0x03': outputfile.write(token + "|") etc... This saves all the indexing, means you don't need to check for index errors or end of file limits. It lets Python take the strain and makes your job easier. HTH, Alan G. From python_simpleton at yahoo.com Fri Mar 19 22:31:39 2004 From: python_simpleton at yahoo.com (python_simpleton) Date: Fri Mar 19 22:34:35 2004 Subject: [Tutor] "hello, python world!" Message-ID: <20040320033139.34449.qmail@web61206.mail.yahoo.com> i downloaded the python 2.3 installer and did a quick install. Icons are all over my desktop but I can get to all programs I need. I took a quick look at IDLE 1.0 (guess they have not updated this program) I also opened python command? It was black and white which brings me to my first question. Q. On my first night trying to learn Python 2.3, I noticed when I click on the program it opens a window that lookes like DOS, is this because Python for Windows is based on python for DOS?(Read that in the instalation) Q. Can python change the input or raw_input window to the size of a message box with color? (pixels, percent ect.) Q. I had a hard time figuring out how to do the password.py in the tutorial Josh Cogliati made. it took me hours trying to use the command line and IDLE and reading error after error to notice the text files that came with 2.3 then i typed the program in Notepad and opened it with IDLE (now i find you can just open new window!) Is Notepad suitable for programming on Windows XP? I use the internest on a Windows ME. Q. Can I attach files, example code, print out of errors incountered? Q. Since indentation is very important where can i go to find the rules in a way a non-programmer can understand(high school level) Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040319/8d79d6da/attachment.html From Janssen at rz.uni-frankfurt.de Sat Mar 20 09:12:18 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sat Mar 20 09:12:34 2004 Subject: [Tutor] "hello, python world!" In-Reply-To: <20040320033139.34449.qmail@web61206.mail.yahoo.com> References: <20040320033139.34449.qmail@web61206.mail.yahoo.com> Message-ID: <Pine.A41.4.56.0403201443020.332894@hermes-22.rz.uni-frankfurt.de> On Fri, 19 Mar 2004, python_simpleton wrote: > Q. On my first night trying to learn Python 2.3, I noticed when I > click on the program it opens a window that lookes like DOS, is > this because Python for Windows is based on python for DOS?(Read > that in the instalation) it's not DOS, it's a shell-window. You can type commands in a shell window or run programms that havn't a graphical interface. I would suggest to learn how to start a raw shell window (without prestarted python) and how to start python from there on or launch your script-files (this suggestions is made by a linux user how can't live without shells ;-). Or use IDLE to give you a python session and run scripts. > Q. Can python change the input or raw_input window to the size of > a message box with color? (pixels, percent ect.) You intermixes textmode programms (like the python interactive mode) and GUI (graphical user interface) programms. The latter can spawn all kinds of boxes and windows and - of course - can be programmed in python. Doing GUI programming might be a huge steps for a beginner (but some kind of steps you've allways to take). The other possibility is to stay in textmode and think about problems not grafical representation. Then you're stuck to whatever your shell window provides. > Q. I had a hard time figuring out how to do the password.py in the > tutorial Josh Cogliati made. it took me hours trying to use the > command line and IDLE and reading error after error to notice the > text files that came with 2.3 then i typed the program in Notepad > and opened it with IDLE (now i find you can just open new window!) > Is Notepad suitable for programming on Windows XP? I use the > internest on a Windows ME. It's fine ;-) You probably want two more things: colored code and help with indentation (last is more important, not because indentation is that hard, but it's much to type with no help by the text-editor). You need to get a real text-editor with those features (perhaps other can suggest what to use under MS-Windows). > Q. Can I attach files, example code, print out of errors > incountered? To ask us about it? Yes, definitly. Keep it to the relevant parts (tracebacks are allways relevant in full) and paste it directly into your mail text. When showing some code it's best when the code is actually runable which means don't cut it to tight to the relevant parts ;-). > Q. Since indentation is very important where can i go to find the > rules in a way a non-programmer can understand(high school level) What's difficult to understand (I even don't know that rules exist ;-) OTOH there must be rules ;-)? Make shure your text-editor does a good job helping you here (mine is 80% correct about its guesses where I want to have my indentation). Search python.org : http://www.python.org/topics/learn/ http://www.python.org/editors http://www.python.org/doc/faq/gui.html Michael From alan.gauld at blueyonder.co.uk Sat Mar 20 13:33:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Mar 20 13:33:53 2004 Subject: [Tutor] Iterating through tokens from a split command References: <64557.206.53.226.235.1079712501.squirrel@www.thepenguin.org> <m3brmsr8bh.fsf@hamster.pflaesterer.de> Message-ID: <02cf01c40ea9$e558cb00$6401a8c0@xp> > > if __name__ == "__main__": > > ConvertFile() > > Why a class? This is considered good OOP style by many teachers. The application is a class and so, to run the application, instantiate it. Thus "everything is an object". It does have the benefit of making the application as a whole potentially reusable and extendable. But that has nothing to do with Vicki's problem. Alan G. From alan.gauld at blueyonder.co.uk Sat Mar 20 13:54:02 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Mar 20 13:54:27 2004 Subject: [Tutor] "hello, python world!" References: <20040320033139.34449.qmail@web61206.mail.yahoo.com> Message-ID: <02e101c40eac$c5453f30$6401a8c0@xp> Hello and welcome. > i downloaded the python 2.3 installer and did a quick install. Well done, that's the first step. > I took a quick look at IDLE 1.0 (guess they have not updated this > program) Actually IDLE has been progressing for quite a while, it only reached 1.0 with Python 2.2 I think... In the early Python releases IDLE didn't even exist! > Q. On my first night trying to learn Python 2.3, I noticed > when I click on the program it opens a window that lookes > like DOS, It is DOS. Or more accurately its a Windows Command prompt. > is this because Python for Windows is based on python > for DOS? Nope. There is only one Python (actually not strictly true but for the purposes of this discussin it is!). The same basic Python program works on DOS, Windows, Linux and Macintosh. They all bring up a command line prompt if you type (or click) python without passing a file to it. > Q. Can python change the input or raw_input window to the > size of a message box with color? (pixels, percent ect.) No, but it can be used to program GUIs which have those features. However the simplest commands (print, raw_input) use the command prompt (aka DOS box). Thats one reason for IDLE, to provide a more Windows like environment. > Q. I had a hard time figuring out how to do the password.py > in the tutorial Josh Cogliati made. So does everyone it seems! :-) But at least you made it, so thats excellent! > then i typed the program in Notepad and opened it with IDLE > (now i find you can just open new window!) Is Notepad > suitable for programming on Windows XP? As you've seen it can be done but IDLE is much better. Regular programmers all have their favourite text editor and can argue for hours over which is best, but if you are not allready addicted to one particular brand - and it sounds like you might be a complete beginner to programming not just Python? - you might like to try downloading Scite. Its an excellent alternative to IDLE, at least then you have a choice. But before doing that go to Danny Yoo's IDLE tutorial and run through that. You might well decide to stick with IDLE. > Q. Can I attach files, example code, print out of errors incountered? Attach files if they aren't too long(not thousands of lines!). Example code is usually best. Error printouts definitely, with a few lines of code to provide the context if possible too. > Q. Since indentation is very important where can i go to > find the rules in a way a non-programmer can understand The rules are really simple. Just be consistent in how much and never mix tabs and spaces. (In fact I strongly recommend to just use spaces!) In practice most folks find you need at least 2 spaces to be effective and more than 4 or 5 becomes very spread out. The whole concept of indenting code is so that you get a visual clue as to the structure of the program. All the related lines are grouped together by the indentation. If you keep those ideas in mind indentatuon will quickly become intuitive. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From sigurd at 12move.de Sat Mar 20 15:27:14 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Sat Mar 20 15:31:14 2004 Subject: [Tutor] Iterating through tokens from a split command In-Reply-To: <02cf01c40ea9$e558cb00$6401a8c0@xp> (Alan Gauld's message of "Sat, 20 Mar 2004 18:33:53 -0000") References: <64557.206.53.226.235.1079712501.squirrel@www.thepenguin.org> <m3brmsr8bh.fsf@hamster.pflaesterer.de> <02cf01c40ea9$e558cb00$6401a8c0@xp> Message-ID: <m3ekrnjnq8.fsf@hamster.pflaesterer.de> On 20 Mar 2004, Alan Gauld <- alan.gauld@blueyonder.co.uk wrote: >> > if __name__ == "__main__": >> > ConvertFile() >> Why a class? > This is considered good OOP style by many teachers. Forgive me but this is just brain dead (regarding the teachers). > The application is a class and so, to run the application, > instantiate it. Thus "everything is an object". It does A long time ago I took a quick look at Java, saw that to get a simple Hello World programm I had to create a class and decided that Java and I were not compatible :-) Something which is clearly a function, used only once in a programm and performs only some side effects (IO) needn't be a class. If it's a function call it a function. > have the benefit of making the application as a whole > potentially reusable and extendable. Without being a prophet or having a crystal ball: that will here never happen; there are millions of small programms which are written for one special task (like the one in our example). If you make the failure of many programmers to write programms too generally (implement a lot of options which are never used; solve all cases where you only have to write a programm for a special case) you get bloated software which is furthermore unnecessarily complicated. Some days ago I read http://www.strauss.za.com/sla/code_std.html (`How to write unmaintainable code'). It's funny to read but describes also real existing problems. Everyone who tries to create for every action a class should read it. Also Richard Gabriel (a Lisp hacker) has some good writings software in general (and also especially Lisp); look at http://www.dreamsongs.com/ if you're interested. Those with a bit time can read "Objects Have Failed"; these are articles with pro and con OOP; the authors are Richard Gabriel, Brian Foote on the one side and Guy Steele and James Noble on the other side. Karl -- Please do *not* send copies of replies to me. I read the list From pythontut at pusspaws.net Sun Mar 21 05:11:00 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Mar 21 05:38:54 2004 Subject: [Tutor] How do I get exact function call timing in Python. Message-ID: <405D6A34.10905@pusspaws.net> I am trying to write a Python equiverlant of the BASH prog ... while true; do myfunctioninbackground & sleep "30m" done So that "myfunctioninbackground" is executed every 30mins on the dot, no matter how long the function takes to execute. So far I have ... import time while True: myfunction() time.sleep(30*60) This executed "myfunction" 30 minuets after the last "myfunction" ended. Not quite the same. Is there an elegant way round this? Many thanks in advance Dave From Janssen at rz.uni-frankfurt.de Sun Mar 21 07:24:38 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sun Mar 21 07:24:53 2004 Subject: [Tutor] How do I get exact function call timing in Python. In-Reply-To: <405D6A34.10905@pusspaws.net> References: <405D6A34.10905@pusspaws.net> Message-ID: <Pine.A41.4.56.0403211255350.332852@hermes-22.rz.uni-frankfurt.de> On Sun, 21 Mar 2004, Dave S wrote: > I am trying to write a Python equiverlant of the BASH prog ... > > while true; do > myfunctioninbackground & > sleep "30m" > done > > So that "myfunctioninbackground" is executed every 30mins on the dot, no > matter how long the function takes to execute. > So far I have ... > > import time > while True: > myfunction() > time.sleep(30*60) > > This executed "myfunction" 30 minuets after the last "myfunction" ended. > Not quite the same. > > Is there an elegant way round this? of course you can compute the time the function actually has used: import time while 1: start = time.time() raw_input("stops running on ENTER: ") used = time.time() - start time.sleep( 30*60 - used ) # can get negative ... Here's another solution: import time sleep_target = time.time() while 1: raw_input("stops running on ENTER: ") sleep_target += 30*60 sleep_time = sleep_target - time.time() # can get negative... time.sleep(sleep_time) this reduces the need of a time.time call to one and with precalculated sleep_targets you can set them to a nice value (running a job every half hour each 00 and 30 min) which is good in some applications. Both ways will throw an Exception when the function runs longer than the intervall and sleep is instructed to run for a negative time. This must be catched, when your python-bash should be as good as the real bash ;-) Did I understand you right, that you want to "write a Python equivalent of the bash prog"? Awefull. Or just an equivalent of this bash snipplet? Michael From pythontut at pusspaws.net Sun Mar 21 08:39:50 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Mar 21 09:07:44 2004 Subject: [Tutor] How do I get exact function call timing in Python. In-Reply-To: <Pine.A41.4.56.0403211255350.332852@hermes-22.rz.uni-frankfurt.de> References: <405D6A34.10905@pusspaws.net> <Pine.A41.4.56.0403211255350.332852@hermes-22.rz.uni-frankfurt.de> Message-ID: <405D9B26.8080607@pusspaws.net> Michael Janssen wrote: >On Sun, 21 Mar 2004, Dave S wrote: > > > >>I am trying to write a Python equiverlant of the BASH prog ... >> >>while true; do >>myfunctioninbackground & >>sleep "30m" >>done >> >>So that "myfunctioninbackground" is executed every 30mins on the dot, no >>matter how long the function takes to execute. >>So far I have ... >> >>import time >>while True: >> myfunction() >> time.sleep(30*60) >> >>This executed "myfunction" 30 minuets after the last "myfunction" ended. >>Not quite the same. >> >>Is there an elegant way round this? >> >> > >of course you can compute the time the function actually has used: > >import time >while 1: > start = time.time() > raw_input("stops running on ENTER: ") > used = time.time() - start > time.sleep( 30*60 - used ) # can get negative ... > > >Here's another solution: > >import time >sleep_target = time.time() >while 1: > raw_input("stops running on ENTER: ") > sleep_target += 30*60 > sleep_time = sleep_target - time.time() # can get negative... > time.sleep(sleep_time) > > >this reduces the need of a time.time call to one and with >precalculated sleep_targets you can set them to a nice value >(running a job every half hour each 00 and 30 min) which is good in >some applications. > >Both ways will throw an Exception when the function runs longer than >the intervall and sleep is instructed to run for a negative time. >This must be catched, when your python-bash should be as good as the >real bash ;-) > Thats a neat way round it ... I like it. >Did I understand you right, that you want to "write a Python >equivalent of the bash prog"? Awefull. Or just an equivalent of this >bash snipplet? > > "write a Python equivalent of the bash prog" - no way :-D just an equiverlant of this BASH snippet ! Since I know BASH a lot better than Python I keep trying to convert ... with varying results. There seems such a lot to take in ... and i've been too chicken to even look at classes yet ;-) >Michael > > > > From alan.gauld at blueyonder.co.uk Sun Mar 21 14:00:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Mar 21 14:00:29 2004 Subject: [Tutor] How do I get exact function call timing in Python. References: <405D6A34.10905@pusspaws.net> Message-ID: <030401c40f76$cffc9110$6401a8c0@xp> > I am trying to write a Python equiverlant of the BASH prog ... > > while true; do > myfunctioninbackground & > sleep "30m" > done > > So that "myfunctioninbackground" is executed every 30mins on the dot, no > matter how long the function takes to execute. OK, lets understand the shell solution first. What happens is that you start a command in background mode then pause your loop. The background job could run for a few seconds, minutes or hours. It doesn't matter You will always launch a new copy every 30 minutes. > So far I have ... > > import time > while True: > myfunction() > time.sleep(30*60) > > This executed "myfunction" 30 minuets after the last "myfunction" ended. > Not quite the same. That's right. This os one area where Python has to get a bit complicated to compete with the shell (unless it really is an external command you want to execute, in which case os.system does nicely). We need to introduce a concept called threading. A thread is a sub process within our program which will run in the background just like the & in shell, but requires a bit more work to set up. More importantly you might have to watch how you close your program down - checking that all threads have completed first. I suggest you read the documentation on the threads module, but the good news is that yours is quite a simple case so we should get something to work... import thread import time import sys def myfunc(threadName): for n in range(10000): if n % 3000 == 0: print "%s : %d" % (threadName, n) print threadName,"finished" for n in range(5): name = "thread"+str(n) #thread0,thread1...thread4 thread.start_new_thread(myfunc,(name,)) #args passed in tuple time.sleep(0.005) Which on my PC gives the following output (you may need to alter the sleep times to get similar results) $ python threadtest.py thread0 : 0 thread0 : 3000 thread0 : 6000 thread1 : 0 thread0 : 9000 thread0 finished thread1 : 3000 thread2 : 0 thread1 : 6000 thread2 : 3000 thread3 : 0 thread1 : 9000 thread1 finished thread2 : 6000 thread4 : 0 thread3 : 3000 Notice that all threads started but only threads 0 and 1 finished before the program did. So if your function takes longer than the sleep period you will need to check for the status of all threads before closing. If the function time is always less than the sleep time then life becomes much much easier.... :-) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From anna at aleax.it Sat Mar 20 09:41:27 2004 From: anna at aleax.it (Anna Ravenscroft) Date: Sun Mar 21 19:55:28 2004 Subject: [Tutor] "hello, python world!" In-Reply-To: <20040320033139.34449.qmail@web61206.mail.yahoo.com> References: <20040320033139.34449.qmail@web61206.mail.yahoo.com> Message-ID: <200403201541.27133.anna@aleax.it> On Saturday 20 March 2004 04:31, python_simpleton wrote: > i downloaded the python 2.3 installer and did a quick install. Icons are > all over my desktop but I can get to all programs I need. I took a quick > look at IDLE 1.0 (guess they have not updated this program) IDLE is a separate development project from Python and IDLE version 1.0 is the updated version to run with Python 2.3 (I realize that's a little confusing but, basically, they left IDLE alone cuz it was working just fine for most of the time.) > I also opened > python command? It was black and white which brings me to my first > question. > Q. On my first night trying to learn Python 2.3, I noticed when I click on > the program it opens a window that lookes like DOS, is this because Python > for Windows is based on python for DOS?(Read that in the instalation) As someone else mentioned, what you're looking at is a shell. I recommend just using IDLE for now while you're learning. As you saw, you can open a new window and create a text file there. I do that all the time. It gives you simple color-coding and automagical indentation. > Q. Can python change the input or raw_input window to the size of a message > box with color? (pixels, percent ect.) Yes - but that's gui programming and you don't want to go there, yet. Later. > Q. I had a hard time figuring out how to do the password.py in the tutorial > Josh Cogliati made. it took me hours trying to use the command line and > IDLE and reading error after error to notice the text files that came with > 2.3 then i typed the program in Notepad and opened it with IDLE (now i find > you can just open new window!) Is Notepad suitable for programming on > Windows XP? I use the internest on a Windows ME. I've used notepad, but I recommend for now that you stick with IDLE's window and just use that. It'll give you a lot more help. > Q. Can I attach files, example code, print out of errors incountered? Don't attach them, cut and paste them into the email. > Q. Since indentation is very important where can i go to find the rules in > a way a non-programmer can understand(high school level) indent by 4 spaces whenever you indent. unindent when you're at the end of your block. (in IDLE, at the empty line after your block, just hit backspace once.) If you are "nesting" (putting one block of code inside another, just add another "level" of indentation. IDLE will help you do this.) That's about as basic (and as complicated) as indentation gets. Good luck and keep up the good work. You may also want to check out Alan Gauld's Learn to Program (just google for it). Anna From jeffpeery at yahoo.com Tue Mar 16 17:23:20 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Sun Mar 21 19:55:58 2004 Subject: [Tutor] (no subject) Message-ID: <20040316222320.18223.qmail@web60106.mail.yahoo.com> is there a general clear everything function - other than "del" which I think only works one variable at a time? I've used matlab and there is a function "clear" that I like to call at the beginning of my scripts. My problem is that sometimes in python I make changes to my script and I run it and the changes don't appear, python runs the old version. I'm saving all my scripts before I run them, but I still don't see python using my latest save. I thought that if there was a way to clear the variable list that that would solve my problem. Sometimes I have to close python IDLE and reopen it to get it to run my last save. I also noticed that python might be running off the *.pyc document and not the script itself, is there a way to prevent the *.pyc from being created? thanks! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040316/aef53fab/attachment.html From kiran at mhowlinux.org Fri Mar 19 08:33:04 2004 From: kiran at mhowlinux.org (kiran@mhowlinux.org) Date: Sun Mar 21 19:56:12 2004 Subject: [Tutor] Status Pippy Message-ID: <000401c40dd8$b0d5dfc0$081ee2dc@VULCAN> Hi, I was trying out pippy 1.0 (Palm Python) based on 1.5.2 couple of months back Has anyone got a clue about the status of that project...I was to move on to stackless python implementation. haven't seen any updates at SF though for quite sometime. Is there any other implementation of Python on Plam -kiran Beware of the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org- Helping Linux users in Mhow --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.624 / Virus Database: 401 - Release Date: 3/15/2004 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040319/e69dc90f/attachment.html From kiran at mhowlinux.org Fri Mar 19 08:46:13 2004 From: kiran at mhowlinux.org (kiran@mhowlinux.org) Date: Sun Mar 21 19:56:18 2004 Subject: [Tutor] Discrepancy Message-ID: <000701c40dd8$b4660b60$081ee2dc@VULCAN> hi what is the problem > x =1 >x is 1 1 > > (1 is 1) 1 > >x is (1 is 1) 0 once i set x=1 x is 1 returns true(1) (1 is 1) returns true(1) whereas x is (1 is 1) returns 0 Python Version 2.2.3 Beware of the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org- Helping Linux users in Mhow -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040319/72da1fff/attachment.html From vicki at stanfield.net Tue Mar 16 13:51:26 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Sun Mar 21 19:56:49 2004 Subject: [Tutor] Another parsing question In-Reply-To: <017501c40b84$54c37220$6401a8c0@xp> References: <CA3458C84C976E45B6372A6C14724C9F355EF2@ridmsem02.nala.roche.com> <017501c40b84$54c37220$6401a8c0@xp> Message-ID: <37827.206.53.226.235.1079463086.squirrel@www.thepenguin.org> > Vicki, > >> I have inherited a project which writes some data to a file >> in hexadecimal format as 0x11, 0x4, etc. The hex values are >> pipe-delimited as so: 0x11|0x4|0x14 > > Don't take this the wrong way, but it seems you really need to go > back to basics on how information is stored and represented in > computer systems. Most of your questions seem to be based on > confusion between strings and binary formats. I agree that I am missing a piece of the puzzle. I understand that they represent the same thing, but I get caught up in trying to use them appropriately. I knew that I was sending a string, but I didn't know how to get back to the numeric value. I see the int command does what I want. Thanks. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From klappnase at freenet.de Sun Mar 21 21:18:05 2004 From: klappnase at freenet.de (Michael Lange) Date: Sun Mar 21 21:27:57 2004 Subject: [Tutor] (no subject) In-Reply-To: <20040316222320.18223.qmail@web60106.mail.yahoo.com> References: <20040316222320.18223.qmail@web60106.mail.yahoo.com> Message-ID: <20040322031805.029d4daa.klappnase@freenet.de> On Tue, 16 Mar 2004 14:23:20 -0800 (PST) Jeff Peery <jeffpeery@yahoo.com> wrote: > is there a general clear everything function - other than "del" which I think only works one variable at a time? I've used matlab and there is a function "clear" that I like to call at the beginning of my scripts. My problem is that sometimes in python I make changes to my script and I run it and the changes don't appear, python runs the old version. I'm saving all my scripts before I run them, but I still don't see python using my latest save. I thought that if there was a way to clear the variable list that that would solve my problem. Sometimes I have to close python IDLE and reopen it to get it to run my last save. > > I also noticed that python might be running off the *.pyc document and not the script itself, is there a way to prevent the *.pyc from being created? > > thanks! > > Jeff > > Hi Jeff, This sounds like you are using IDLE-0.8 from a Python-2.2 install. With IDLE-1.0 that comes with Python-2.3 this problem has been fixed, when you run your scripts the PythonShell gets automatically restarted. If you don't want to upgrade the whole Python installation, you might have a look at Idlefork ( I think at <http://idlefork.sourceforge.net> ) which used to be an extended version of IDLE (and now actually *is* IDLE I think); they have a version there that runs with Python-2.2 and has this feature already included. I hope this helps Michael From tony at tcapp.com Mon Mar 22 03:24:29 2004 From: tony at tcapp.com (Tony Cappellini) Date: Mon Mar 22 03:24:52 2004 Subject: [Tutor] a question about exceptions Message-ID: <6.0.0.22.0.20040322001816.01c3d360@smtp.sbcglobal.net> Recently, I've found this code on the net- I think it was from the Python Cookbook. try: Celsius=float(string.atoi(CTemp)) except string.atoi_error: print repr(CTemp), "not a numeric value" else: I understand what's happening-in general. What I don't understand is the exception type string.atoi_error. Where is this type of exception defined ? I couldn't find anything on exceptions other than the built-in exception classes, in the Python docs, and the books I have on Python. So where is this type of exception defined and documented ? What other kinds of exception types like this exist ? This type of exception handling opens up a whole lot of possibilities, if I could only find out where to get documentation. thanks Tony -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040322/ebbd1924/attachment.html From dbroadwell at mindspring.com Mon Mar 22 04:55:25 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Mon Mar 22 04:52:18 2004 Subject: [Tutor] (no subject) In-Reply-To: <20040322031805.029d4daa.klappnase@freenet.de> Message-ID: <MBBBKPICGBKFODJNCCLJEEOFDCAA.dbroadwell@mindspring.com> > This sounds like you are using IDLE-0.8 from a Python-2.2 > install. With IDLE-1.0 that comes with Python-2.3 > this problem has been fixed, My fix was just to script a delete to the associated .pyc between changes ... But I'm glad to know upgrading will fix it. -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat (no this doesn't happen all at once, honest) David Broadwell From kp8 at mac.com Mon Mar 22 05:13:10 2004 From: kp8 at mac.com (kevin parks) Date: Mon Mar 22 05:14:39 2004 Subject: [Tutor] accessing items in nested structure In-Reply-To: <E1B2vUJ-0008Jq-51@mail.python.org> Message-ID: <857D2C24-7BE9-11D8-AF73-003065555ABC@mac.com> def datas(x): pg01 = [ { (1,0) : [8, 3, 5, 4] }, { (7,0) : [4, 3, 2, 2] }, { (14,0) : [8, 3, 5, 4] }, { (18,0) : [10, 2, 8, 7] }, { (20,0) : [10, 0, 5, 7] }, { (22,0) : [10, 2, 8, 7] }, { (24,0) : [7, 9, 3, 8] }, # { (25,0) : [5] }, # { (27,0) : [0] }, { (28,0) : [10, 0, 5, 7] }, { (29,0) : [10, 11] }, { (30,0) : [8, 3, 5, 4] }, { (32,0) : [5, 0, 10, 7] }, { (34,0) : [8, 3, 7, 9] }, { (36,0) : [5, 4, 3, 1] }, { (36,1) : [5, 4, 3, 1, 7] }, { (37,0) : [0, 8, 2, 4, 9, 10, 1] }, { (37,1) : [0, 8, 2, 4, 9, 10, 1, 6] }, { (39,0) : [8, 10, 1, 9] }, { (39,1) : [8, 10, 1, 9, 7] }, { (41,0) : [2, 0, 3, 1] }, { (41,1) : [2, 0, 3, 1, 6] }] return pg01[x] # def pctrans(seq, transposition): '''pctrans -- transposes pc sequence''' output = [] for item in seq: output.append((item + transposition) % 12) return output # Hi all. My data structure is getting a little complex with a list of dictionaries (which are made up of a tuple key and list value). Now i want to be able to access each key and its list, that its i want to be able to iterate through this pg01 list and do something to each key and value(list) in the list. Like for example print the key tuple and print the list followed by the list again but sorted, then list again modified by function call to the pctrans() func above (just to pick something at random for now) or sort or something. SO that i might get on output: 1,0 [8, 3, 5, 4] [3, 4, 5, 8 ] [4, 5, 6, 9] etc.... I can iterate over the list and print each item, like so in the interpreter: >>> import data >>> x = data.datas(1) >>> x {(7, 0): [4, 3, 2, 2]} but i am not sure how to get inside the dictionaries inside the pg01 and iterate over those and the nested list values. Also since my dictionary keys are not consecutive numbers how can i be sure to hit them all? cheers, -kp-- From magnus at thinkware.se Mon Mar 22 09:04:49 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Mar 22 09:05:08 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gImhlbGxvLCBweXRob24gd29ybGQhIg==?= Message-ID: <think001_405ee1ca78495@webmail.thinkware.se> > On Saturday 20 March 2004 04:31, python_simpleton wrote: > > Q. On my first night trying to learn Python 2.3, I noticed when I click on > > the program it opens a window that lookes like DOS, is this because Python > > for Windows is based on python for DOS?(Read that in the instalation) No, it looks more or less like that also on computers that are completely void of Microsoft code. I guess the similarities with the DOS port has more to do with Windows inheriting some peculiarities from DOS in the way it handles C programming, which are invisible to the normal Python user. Microsoft has really managed to confuse people regarding the distinction between operating system and graphical user interface by using the "Windows" label in such a strange way, implying that the GUI is the operating system. This is just a smoke screen. Windows 3.x, 95, 98 and ME, are all graphcal shells for MS DOS bundled with some features that are typically placed in the actual operating system, such as limited ability for multi-tasking and extended memory management. Later versions of these Windows products where always bundled with DOS, but only used the Windows name, and Microsoft certainly didn't want people to associate them with DOS. Microsoft NT (New Techology) was a completely new, and much more capable operating system for PCs, with a graphical user interface which was very similar to the DOS Windows shells. It's architectual roots came from a planned successor to the venerable VMS at Digital Equipment Corporation. See http://en.wikipedia.org/wiki/History_of_Microsoft_Windows for info if you are interested in this technology theft etc. The command line interface (CMD.EXE) in all versions of NT (whether it's NT 3.x, NT 4, NT 5.0 a.k.a. Windows 2000 or NT 5.1 a.k.a. Windows XP) is *not* DOS. It can emulate DOS to some extent, but there are certainly a number of command line based programs in NT that never existed in DOS and won't run there, and many DOS programs can't run in the NT command line interface. Don't confuse the lack of a GUI with the primitive properties of DOS. Python is designed to work on a large number of platforms. You can run it in many diverse environments such as mobile phones (Nokia 60 series), PDAs, personal computers of various kinds, as well as large servers such as IBM mainframes. Most Python programs can run without a graphical user interface, and the text based command line interface is a very robust and simple interface that I certainly prefer to use in many situations, but I do notice that end users often seem to dislike programs using a text based interface, even in cases where a GUI doesn't offer any real advantages. While many programmers prefer Python over other programming languages for developing GUI applications, I suggest that you leave that for later. GUI programming in Python is not really for beginners with todays tools. > > Q. I had a hard time figuring out how to do the password.py in the tutorial > > Josh Cogliati made. it took me hours trying to use the command line and > > IDLE and reading error after error to notice the text files that came with > > 2.3 then i typed the program in Notepad and opened it with IDLE (now i find > > you can just open new window!) Is Notepad suitable for programming on > > Windows XP? I use the internest on a Windows ME. Anna Ravenscroft replied: > I've used notepad, but I recommend for now that you stick with IDLE's window > and just use that. It'll give you a lot more help. Note that the IDLE window titled "Python Shell" is not the window where you write programs. This is just for direct execution of individual Python statements etc. This is very useful for some experimentation etc, but when you want to write a program, you open a separate editor window with "File->New" or "File->Open" just like you work with documents as in most other Windows programs. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From vicki at stanfield.net Mon Mar 22 09:48:21 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Mon Mar 22 09:48:26 2004 Subject: [Tutor] character that means beginning of line for readlines purposes Message-ID: <27326.206.53.226.235.1079966901.squirrel@www.thepenguin.org> I am parsing data from an input file. Sometimes the data must be converted and other times not. If for instance, the 0x11| comes at the beginning of a line, it gets converted and if it comes in the middle of the data line, it doesn't. I know how to do this with search in the vi editor; "^" means beginning of line. I found information that the same RE is used in Python. For some reason, I can't get it to work the way I want. I am using split to separate the line into tokens if that matters. Here is the code that isn't working: if tokens[i] == '0x11': if tokens[i-1]in ('0x3', '0x4','^'): new = "0x02|" else: new = "0x31|0x31|" outputfile.write(new) The first 0x11, is converted to "0x31|0x31| even though it begins a line. Can someone explain this? I know that I can toggle a flag to determine this, but I'd rather do it with a regular expression. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From Janssen at rz.uni-frankfurt.de Mon Mar 22 10:01:24 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon Mar 22 10:01:36 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gImhlbGxvLCBweXRob24gd29ybGQhIg==?= In-Reply-To: <think001_405ee1ca78495@webmail.thinkware.se> References: <think001_405ee1ca78495@webmail.thinkware.se> Message-ID: <Pine.A41.4.56.0403221549001.145558@hermes-22.rz.uni-frankfurt.de> On Mon, 22 Mar 2004, Magnus Lycka wrote: > > On Saturday 20 March 2004 04:31, python_simpleton wrote: > > > Q. On my first night trying to learn Python 2.3, I noticed when I click on > > > the program it opens a window that lookes like DOS, is this because Python > > > for Windows is based on python for DOS?(Read that in the instalation) > > No, it looks more or less like that also on computers that are completely > void of Microsoft code. I guess the similarities with the DOS port has more > to do with Windows inheriting some peculiarities from DOS in the way it > handles C programming, which are invisible to the normal Python user. > > Microsoft has really managed to confuse people regarding the distinction > between operating system and graphical user interface by using the "Windows" > label in such a strange way, implying that the GUI is the operating system. > This is just a smoke screen. Windows 3.x, 95, 98 and ME, are all graphcal > shells for MS DOS bundled with some features that are typically placed in > the actual operating system, such as limited ability for multi-tasking and > extended memory management. Later versions of these Windows products where > always bundled with DOS, but only used the Windows name, and Microsoft > certainly didn't want people to associate them with DOS. thanks for giving a little light into this "bundle", Magnus. I was thinking the whole weekend what and where the differences between MS-DOS and MS-Windows are... > Microsoft NT (New Techology) was a completely new, and much more capable > operating system for PCs, with a graphical user interface which was very > similar to the DOS Windows shells. It's architectual roots came from a > planned successor to the venerable VMS at Digital Equipment Corporation. > See http://en.wikipedia.org/wiki/History_of_Microsoft_Windows for info > if you are interested in this technology theft etc. > > The command line interface (CMD.EXE) in all versions of NT (whether it's > NT 3.x, NT 4, NT 5.0 a.k.a. Windows 2000 or NT 5.1 a.k.a. Windows XP) is > *not* DOS. It can emulate DOS to some extent, but there are certainly a > number of command line based programs in NT that never existed in DOS and > won't run there, and many DOS programs can't run in the NT command line > interface. > > Don't confuse the lack of a GUI with the primitive properties of DOS. I really like this sentence ;-) Michael From bgailer at alum.rpi.edu Mon Mar 22 10:27:03 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Mar 22 10:26:08 2004 Subject: [Tutor] Discrepancy In-Reply-To: <000701c40dd8$b4660b60$081ee2dc@VULCAN> References: <000701c40dd8$b4660b60$081ee2dc@VULCAN> Message-ID: <6.0.0.22.0.20040322082038.03865c40@mail.mric.net> At 06:46 AM 3/19/2004, kiran@mhowlinux.org wrote: >hi > >what is the problem > > > x =1 > >x is 1 >1 > > > > (1 is 1) >1 > > > >x is (1 is 1) >0 > >once i set x=1 >x is 1 returns true(1) >(1 is 1) returns true(1) > >whereas > x is (1 is 1) >returns 0 LangaugeReference: "The operators is and is not test for object identity: x is y is true if and only if x and y are the same object." Object identity is tested by comparing the ids of the 2 objects. >>> x = 1 >>> id(x) 3112784 >>> id(1 is 1) 504014296 # hmm - what's going on here? Wait a minute didn't it say " y is true" >>> id(True) 504014296 # Oh now I see. True and 1 are not the same object even though they have the same value Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040322/416f6873/attachment.html From sigurd at 12move.de Mon Mar 22 10:36:38 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Mar 22 10:41:15 2004 Subject: [Tutor] Discrepancy In-Reply-To: <000701c40dd8$b4660b60$081ee2dc@VULCAN> (kiran@mhowlinux.org's message of "Fri, 19 Mar 2004 19:16:13 +0530") References: <000701c40dd8$b4660b60$081ee2dc@VULCAN> Message-ID: <m3k71c3nwr.fsf@hamster.pflaesterer.de> An unnamed person wrote: > what is the problem >> x =1 >>x is 1 > 1 That may or may not be true. >> (1 is 1) > 1 That may or may not be true. >>x is (1 is 1) > 0 You mix booleans and numbers. Furthermore you don't seem to fully understand what `is' is for. If you're not sure which type of equality you're interested in, use `==' `is' tests for identity not only equality. The best is you should read in the Python reference about `is'. There was also in clp a long discussion about `is' and `=='. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Mon Mar 22 10:54:40 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Mar 22 10:56:41 2004 Subject: [Tutor] a question about exceptions In-Reply-To: <6.0.0.22.0.20040322001816.01c3d360@smtp.sbcglobal.net> (Tony Cappellini's message of "Mon, 22 Mar 2004 00:24:29 -0800") References: <6.0.0.22.0.20040322001816.01c3d360@smtp.sbcglobal.net> Message-ID: <m3fzc03naf.fsf@hamster.pflaesterer.de> On 22 Mar 2004, Tony Cappellini <- tony@tcapp.com wrote: > I've found this code on the net- I think it was from the Python Cookbook. > try: > Celsius=float(string.atoi(CTemp)) > except string.atoi_error: > print repr(CTemp), "not a numeric value" > else: This code is very outdated. Today with a recent python noone would write it like that. > I understand what's happening-in general. What I don't understand is > the exception type > string.atoi_error. This is from the string module. If you import it you will see that error. But `atoi' should no longer be used; `int' is better. [...] > So where is this type of exception defined and documented ? What other > kinds of exception types like this exist ? It's defined and documented in the string module. > This type of exception handling opens up a whole lot of possibilities, > if I could only find out where to get documentation. Perhaps you should read about how to subclass your own exceptions from existing exception classes (in the Python tutorial). Also read perhaps about `raise'. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Mon Mar 22 11:04:50 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Mar 22 11:06:50 2004 Subject: [Tutor] accessing items in nested structure In-Reply-To: <857D2C24-7BE9-11D8-AF73-003065555ABC@mac.com> (kevin parks's message of "Mon, 22 Mar 2004 05:13:10 -0500") References: <857D2C24-7BE9-11D8-AF73-003065555ABC@mac.com> Message-ID: <m3brmo3m9k.fsf@hamster.pflaesterer.de> On 22 Mar 2004, kevin parks <- kp8@mac.com wrote: > def datas(x): > pg01 = [ { (1,0) : [8, 3, 5, 4] }, > { (7,0) : [4, 3, 2, 2] }, [...] > { (41,1) : [2, 0, 3, 1, 6] }] > return pg01[x] > # [...] > Hi all. My data structure is getting a little complex with a list of > dictionaries (which are made up of a tuple key and list value). Now i Before we go into detail. Are you sure you need such a complex data structure? Why don't you just take one dictionary and put the key/value pairs in it? At the moment each dictionary has only one key. That's a huge overhead. If that is cleared it will be easier to answer your question how to iterate over the structure. Why do you write a function to store the structure? Karl -- Please do *not* send copies of replies to me. I read the list From tpc at csua.berkeley.edu Mon Mar 22 11:13:14 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon Mar 22 11:13:24 2004 Subject: [Tutor] a question about exceptions In-Reply-To: <6.0.0.22.0.20040322001816.01c3d360@smtp.sbcglobal.net> Message-ID: <20040322075747.G78310-100000@localhost.name> hi Tony, I don't know if you know this, but in the C programming language there is an atoi() function that converts an array to int. During runtime you will get an error if what is passed is not an array or, in the case of an array of chars, if not every char is a digit. I don't know enough of Python to say anymore than what I have learned in my community college C class. I hope this helps you. On Mon, 22 Mar 2004, Tony Cappellini wrote: > > > Recently, > > I've found this code on the net- I think it was from the Python Cookbook. > > try: > Celsius=float(string.atoi(CTemp)) > except string.atoi_error: > print repr(CTemp), "not a numeric value" > else: > > > I understand what's happening-in general. What I don't understand is the > exception type > string.atoi_error. > > Where is this type of exception defined ? I couldn't find anything on > exceptions other than the built-in exception classes, in the Python docs, > and the books I have on Python. > > So where is this type of exception defined and documented ? What other > kinds of exception types like this exist ? > > This type of exception handling opens up a whole lot of possibilities, if I > could only find out where to get documentation. > > thanks > > Tony From sigurd at 12move.de Mon Mar 22 11:14:15 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Mar 22 11:17:12 2004 Subject: [Tutor] character that means beginning of line for readlines purposes In-Reply-To: <27326.206.53.226.235.1079966901.squirrel@www.thepenguin.org> (Vicki Stanfield's message of "Mon, 22 Mar 2004 09:48:21 -0500 (EST)") References: <27326.206.53.226.235.1079966901.squirrel@www.thepenguin.org> Message-ID: <m37jxc3lxl.fsf@hamster.pflaesterer.de> On 22 Mar 2004, Vicki Stanfield <- vicki@stanfield.net wrote: > it doesn't. I know how to do this with search in the vi editor; "^" means > beginning of line. I found information that the same RE is used in Python. Yes, but you don't use a regexp here. > For some reason, I can't get it to work the way I want. I am using split > to separate the line into tokens if that matters. Here is the code that > isn't working: > if tokens[i] == '0x11': > if tokens[i-1]in ('0x3', '0x4','^'): That tests if the token before '0x11' is either equal '0x3', '0x4' or '^' (this is a literal character; it is here no meta character as in a regexp). [...] > The first 0x11, is converted to "0x31|0x31| even though it begins a line. > Can someone explain this? I know that I can toggle a flag to determine > this, but I'd rather do it with a regular expression. Well you didn't use a regexp at all, but you could do it simpler IMO. Since `i' seems to be an index the first token has index 0 or am I wrong? If not just test if i == 0 if tokens[i] == '0x11'. So the test would become: if tokens[i] == '0x11' and i == 0: ... Karl -- Please do *not* send copies of replies to me. I read the list From vicki at stanfield.net Mon Mar 22 11:32:58 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Mon Mar 22 11:33:07 2004 Subject: [Tutor] character that means beginning of line for readlinespurposes In-Reply-To: <m37jxc3lxl.fsf@hamster.pflaesterer.de> References: <27326.206.53.226.235.1079966901.squirrel@www.thepenguin.org> <m37jxc3lxl.fsf@hamster.pflaesterer.de> Message-ID: <38254.206.53.226.235.1079973178.squirrel@www.thepenguin.org> > That tests if the token before '0x11' is either equal '0x3', '0x4' or > '^' (this is a literal character; it is here no meta character as in a > regexp). > > [...] >> The first 0x11, is converted to "0x31|0x31| even though it begins a >> line. >> Can someone explain this? I know that I can toggle a flag to determine >> this, but I'd rather do it with a regular expression. > > > Well you didn't use a regexp at all, but you could do it simpler IMO. > Since `i' seems to be an index the first token has index 0 or am I > wrong? If not just test if i == 0 if tokens[i] == '0x11'. So the test > would become: if tokens[i] == '0x11' and i == 0: ... > > > > Karl Thanks Karl, I should have thought of that, but it didn't occur to me at all! ;-) Guess it's going to be a very long day! --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From tony at tcapp.com Mon Mar 22 13:13:22 2004 From: tony at tcapp.com (Tony Cappellini) Date: Mon Mar 22 13:13:26 2004 Subject: [Tutor] Re: Tutor Digest, Vol 1, Issue 2671 In-Reply-To: <E1B5S3O-0006C8-Al@mail.python.org> Message-ID: <20040322095727.Q14284-100000@yamato.yamato.com> > > Message: 7 > Date: Mon, 22 Mar 2004 16:54:40 +0100 > From: sigurd@12move.de ( Karl Pfl?sterer ) > Subject: Re: [Tutor] a question about exceptions > To: tutor@python.org > Message-ID: <m3fzc03naf.fsf@hamster.pflaesterer.de> > Content-Type: text/plain; charset=us-ascii > > On 22 Mar 2004, Tony Cappellini <- tony@tcapp.com wrote: > > > I've found this code on the net- I think it was from the Python Cookbook. > > > try: > > Celsius=float(string.atoi(CTemp)) > > except string.atoi_error: > > print repr(CTemp), "not a numeric value" > > else: > > This code is very outdated. Today with a recent python noone would > write it like that. > > > > I understand what's happening-in general. What I don't understand is > > the exception type > > string.atoi_error. Obviously this is from the string module. I failed to get the point across of which I am having difficulty with. What I don't understand is- when I looked in the Python documentation, under exceptions, only the built-in exceptions were listed. When I searched the searchable help file in Python 2.3, for string.atoi_error, nothing was matched. It doesn't state that exceptions other than the built-ins exist, in any of the modules. So- the documentation failed to explain what other types of exceptions are already included in Python- even if they are in modules, and not the built-ins. > This is from the string module. If you import it you will see that > error. But `atoi' should no longer be used; `int' is better. I will look into this I've already used raise, but without subclassing my own exceptions. I'll take a look at the string modeul again. thanks From project5 at redrival.net Mon Mar 22 13:20:04 2004 From: project5 at redrival.net (Andrei) Date: Mon Mar 22 13:20:42 2004 Subject: [Tutor] Re: accessing items in nested structure References: <E1B2vUJ-0008Jq-51@mail.python.org> <857D2C24-7BE9-11D8-AF73-003065555ABC@mac.com> Message-ID: <g0zv2cji1k70$.vbbj6mde92pv$.dlg@40tude.net> kevin parks wrote on Mon, 22 Mar 2004 05:13:10 -0500: > def datas(x): > pg01 = [ { (1,0) : [8, 3, 5, 4] }, > { (7,0) : [4, 3, 2, 2] }, <snip> > { (41,1) : [2, 0, 3, 1, 6] }] > return pg01[x] pg01 looks overly complicated to me - it's a very cumbersome way of writing a dictionary which could look like this: pg01 = { (1, 0): [8, 3, 5, 4], (7, 0): [4, 3, 2, 2], <etc.> } If you really need to access the keys by their number, you could use a sorted dictionary - there's code for it available which is easy to find if you google for "sorted dictionary python". Also doing this in a function might not be the best idea. Every time you call that function, pg01 must be rebuilt, which is not very efficient (unless Python optimizes it, I don't know). You could just have a global pg01 and ask for values from it directly in the code using pg01[x]. > want to be able to access each key and its list, that its i want to be > able to iterate through this pg01 list and do something to each key and > value(list) in the list. You can iterate over the keys in a dictionary quite easily: >>> mydict = {0: "a", 1:"b", 2:"c"} >>> for key in mydict: ... print key, mydict[key] ... 0 a 1 b 2 c Note that although in this case the keys appear to remain sorted, there is no guarantee that this will always be the case, so if you need them sorted, either use a sorteddict as mentioned above, or do something like this: >>> keys = mydict.keys() >>> keys.sort() # sorts in-place >>> for key in keys: ... print key, mydict[key] ... 0 a 1 b 2 c > but i am not sure how to get inside the dictionaries inside the pg01 > and iterate over those and the nested list values. Well, looping over an item inside some container is not that hard. E.g.: >>> nestedlist = [[0, 1], [2, 3], [4, 5]] >>> for element in nestedlist: ... print element, # element is now one item in nestedlist ... for subelement in element: ... print subelement, ... print '' ... [0, 1] 0 1 [2, 3] 2 3 [4, 5] 4 5 You can combine this with the keys thing I showed above for dictionaries to loop over keys in a dictionary inside a list or whatever else you might fancy. > Also since my dictionary keys are not consecutive numbers how can i be > sure to hit them all? Use - as demonstrated above - either 'for key in somedictionary' or 'for key in somedictionary.keys()'. That gives you each key in that dictionary exactly once. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From pythontut at pusspaws.net Mon Mar 22 13:33:45 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon Mar 22 14:02:16 2004 Subject: [Tutor] How do I get exact function call timing in Python. In-Reply-To: <030401c40f76$cffc9110$6401a8c0@xp> References: <405D6A34.10905@pusspaws.net> <030401c40f76$cffc9110$6401a8c0@xp> Message-ID: <405F3189.9050702@pusspaws.net> Alan Gauld wrote: >>I am trying to write a Python equiverlant of the BASH prog ... >> >>while true; do >>myfunctioninbackground & >>sleep "30m" >>done >> >>So that "myfunctioninbackground" is executed every 30mins on the >> >> >dot, no > > >>matter how long the function takes to execute. >> >> > >OK, lets understand the shell solution first. > >What happens is that you start a command in background mode >then pause your loop. The background job could run for a few >seconds, minutes or hours. It doesn't matter You will always >launch a new copy every 30 minutes. > > > >>So far I have ... >> >>import time >>while True: >> myfunction() >> time.sleep(30*60) >> >>This executed "myfunction" 30 minuets after the last "myfunction" >> >> >ended. > > >>Not quite the same. >> >> > >That's right. This os one area where Python has to get a bit >complicated to compete with the shell (unless it really is an >external command you want to execute, in which case os.system >does nicely). We need to introduce a concept called threading. > > Ahh ... anouther python concept .... :-) >A thread is a sub process within our program which will run in >the background just like the & in shell, but requires a bit more >work to set up. More importantly you might have to watch how you >close your program down - checking that all threads have >completed first. > >I suggest you read the documentation on the threads module, but >the good news is that yours is quite a simple case so we should >get something to work... > >import thread >import time >import sys > >def myfunc(threadName): > for n in range(10000): > if n % 3000 == 0: > print "%s : %d" % (threadName, n) > print threadName,"finished" > >for n in range(5): > name = "thread"+str(n) #thread0,thread1...thread4 > thread.start_new_thread(myfunc,(name,)) #args passed in tuple > time.sleep(0.005) > > > This doesn't seem too bad ... I'll delve into the threads module documentation ... but it seems to make sense. >Which on my PC gives the following output (you may need >to alter the sleep times to get similar results) > >$ python threadtest.py >thread0 : 0 >thread0 : 3000 >thread0 : 6000 >thread1 : 0 >thread0 : 9000 >thread0 finished >thread1 : 3000 >thread2 : 0 >thread1 : 6000 >thread2 : 3000 >thread3 : 0 >thread1 : 9000 >thread1 finished >thread2 : 6000 >thread4 : 0 >thread3 : 3000 > >Notice that all threads started but only threads 0 and 1 finished >before the program did. So if your function takes longer than the >sleep period you will need to check for the status of all threads >before closing. > > That would be an interesting "gotcha" ... Thanks for the tip. >If the function time is always less than the sleep time then life >becomes much much easier.... :-) > > As per the previous post ... :-) >HTH, > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > The above will prove very usefull for a project I am working on. I was starting to consider running a BASH Python hybrid program with BASH timeing & calling Python scripts with a & :-( . This is a lot lot neater. :-) Thanks for your input. Im still very much at the start of the learning curve, having experimented with the rc module and regular expressions (that was a challenge) to strip HTML Im now re-reading about classes, a totaly alien concept to me. Cheers Dave From dyoo at hkn.eecs.berkeley.edu Mon Mar 22 14:05:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 22 14:05:47 2004 Subject: [Tutor] [string.atoi_error, revisionism, and Python 1.0.2] In-Reply-To: <20040322095727.Q14284-100000@yamato.yamato.com> Message-ID: <Pine.LNX.4.44.0403221045110.24344-100000@hkn.eecs.berkeley.edu> On Mon, 22 Mar 2004, Tony Cappellini wrote: > > > I've found this code on the net- I think it was from the Python Cookbook. > > > > > try: > > > Celsius=float(string.atoi(CTemp)) > > > except string.atoi_error: > > > print repr(CTemp), "not a numeric value" > > > else: > > > > This code is very outdated. Today with a recent python noone would > > write it like that. [some text cut] > What I don't understand is- when I looked in the Python documentation, > under exceptions, only the built-in exceptions were listed. Hi Tony, Yes, the built-in exceptions in: http://www.python.org/doc/lib/module-exceptions.html do not have string.atoi_error, nor is 'string.atoi_error' documented in the 'string' module. http://www.python.org/doc/lib/module-string.html Interesting. Let me check something: ### >>> import string >>> string.atoi_error <class exceptions.ValueError at 0x40071b0c> ### Ah! string.atoi_error is an alias for the standard exception ValueError! Ok, I think I have a theory of what's happening. Let's assume for the moment that that celsius-calculation code was written a long time ago, since it uses the deprecated 'string' module. We can go back to Python 1.52's library documentation: http://python.org/doc/1.5.2p2/lib/lib.html ... but that's not far back enough. In reality, string.atoi_error is a REALLY OLD exception type from the 1.0.2 days! I can't even find that version of the documentation on Python.org anymore, but I did find it on a mirror site: http://www.informatik.hu-berlin.de/Themen/manuals/python/python-texinfo/top.html http://www.informatik.hu-berlin.de/Themen/manuals/python/python-texinfo/string.html I think we can now reconstruct a plausible guess what happened: Python 1.0.2 used to have a separate exception for each of the following: """ atof_error -- exception of module string Exception raised by atof when a non-float string argument is detected. The exception argument is the offending string. atoi_error -- exception of module string Exception raised by atoi when a non-integer string argument is detected. The exception argument is the offending string. atol_error -- exception of module string Exception raised by atol when a non-integer string argument is detected. The exception argument is the offending string. index_error -- exception of module string Exception raised by index when sub is not found. The exception argument is undefined (it may be a tuple containing the offending arguments to index or it may be the constant string 'substring not found'). """ But this specialization was probably considered a little overboard: exceptions should capture the exceptional situation itself --- having three separate exceptions for each of the conversion function is awkward. There appears to have been an effort to consolidate the exceptions to be a little more general, and so atof_error, atoi_eror, and atol_error were all condensed into the exception that we now know as ValueError. This consolidation appears to have taken place between Python 1.0.2 and Python 1.5.2, since there's no trace of it in 1.5.2. > So- the documentation failed to explain what other types of exceptions > are already included in Python- even if they are in modules, and not the > built-ins. I have to assume that 'atoi_error' was left in the string module simply for compatibility reasons, since there's really no mention of it in any modern Python docs now. Anyway, so in summary: your code snippet was really darn ancient, using very deprecated functions from at least 1994. Python has changed quite a bit since then, and it tries to maintain backwards compatibility, which is why string.atoi_error is still in that module. But the language also tries to keep folks from using the deprecated features, either by documenting them as 'deprecated' (as in the case of string.atoi())... or by not documenting them at all (as in the case of string.atoi_error). *grin* Hope this helps! From kp8 at mac.com Mon Mar 22 17:00:13 2004 From: kp8 at mac.com (kevin parks) Date: Mon Mar 22 17:01:45 2004 Subject: [Tutor] accessing items in nested structure In-Reply-To: <E1B5S3O-0006C8-Al@mail.python.org> Message-ID: <4BD51617-7C4C-11D8-9B5D-003065555ABC@mac.com> On Monday, March 22, 2004, at 11:13 AM, tutor-request@python.org wrote: > > > On 22 Mar 2004, kevin parks <- kp8@mac.com wrote: > >> def datas(x): >> pg01 = [ { (1,0) : [8, 3, 5, 4] }, >> { (7,0) : [4, 3, 2, 2] }, > [...] >> { (41,1) : [2, 0, 3, 1, 6] }] >> return pg01[x] >> # > > [...] >> Hi all. My data structure is getting a little complex with a list of >> dictionaries (which are made up of a tuple key and list value). Now i > > Before we go into detail. Are you sure you need such a complex data > structure? Why don't you just take one dictionary and put the > key/value > pairs in it? At the moment each dictionary has only one key. That's a > huge overhead. > Oh.... Uhmm, now that i think about it, there really isn't a good reason except that there are several pages (here is just a portion of page 01) and i just broke it up that way. You are right though it probably could be simpler. > If that is cleared it will be easier to answer your question how to > iterate over the structure. > > Why do you write a function to store the structure? just because it is huge. It is about 15 pages of data and this is only a small snippit of one list of one page to give an example. When the data gets like this i sometimes like to just put it in its own file and import it so that i can just see what my code is without all that data cluttering my screen. originally i was doing something like this: m1 = [8, 3, 5, 4] m7 = [4, 3, 2, 2] m14 = [8, 3, 5, 4] m18 = [10, 2, 8, 7] m20 = [10, 0, 5, 7] m22 = [10, 2, 8, 7] m24 = [7, 9, 3, 8] page01 = [m1, m7, m14, m18, m20, m22, m24] (followed by a bunch of code that munched on those lists) But then i realized that i wanted to use that variable name too since it is meaningful so i changed that to: pg01 = [ { (1,0) : [8, 3, 5, 4] }, { (7,0) : [4, 3, 2, 2] }, { (14,0) : [8, 3, 5, 4] }, { (18,0) : [10, 2, 8, 7] }, { (20,0) : [10, 0, 5, 7] }, { (22,0) : [10, 2, 8, 7] }, { (24,0) : [7, 9, 3, 8] }] So what i have here is page number (corresponds to another document being analyzed) a line number (1, 7, 14, .....) and an item number (1,0), (7,0), (14,0) .... in this case all 0, but in some cases there are several items like (82,0), (82,1), (82,3) for : (82,0) = [7,2,6,8] (82,1) = [10,9,0,11] (82,2) = [10,9,0,11,4] -kevin-- From kp8 at mac.com Mon Mar 22 17:22:12 2004 From: kp8 at mac.com (kevin parks) Date: Mon Mar 22 17:23:40 2004 Subject: [Tutor] getting names from other funcs In-Reply-To: <E1B5S3O-0006C8-Al@mail.python.org> Message-ID: <5D8C9AD1-7C4F-11D8-9B5D-003065555ABC@mac.com> Major brain fart here: I can't recall how you get to a name in another function. Let's say that i have a func called foo and it has certain variables and values held in it that i want to grab and use in test(): def foo(seq): '''foo -- makes foo of sequence''' output = [] bob = 32768 fred = ['a', 6, 'yo mama', 'c'] return fred def test(): # how can i get access to the names bob and fred in here? From sigurd at 12move.de Mon Mar 22 17:49:11 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Mar 22 17:52:48 2004 Subject: [Tutor] accessing items in nested structure In-Reply-To: <4BD51617-7C4C-11D8-9B5D-003065555ABC@mac.com> (kevin parks's message of "Mon, 22 Mar 2004 17:00:13 -0500") References: <4BD51617-7C4C-11D8-9B5D-003065555ABC@mac.com> Message-ID: <m33c8033wf.fsf@hamster.pflaesterer.de> On 22 Mar 2004, kevin parks <- kp8@mac.com wrote: > On Monday, March 22, 2004, at 11:13 AM, tutor-request@python.org wrote: (Only out of interest: how does it happen that an e-mail from me has such an from field? Is that the digest? The M-ID is also changed.) >> Before we go into detail. Are you sure you need such a complex data >> structure? Why don't you just take one dictionary and put the >> key/value >> pairs in it? At the moment each dictionary has only one key. That's a >> huge overhead. > Oh.... Uhmm, now that i think about it, there really isn't a good > reason except that there are > several pages (here is just a portion of page 01) and i just broke it > up that way. You are right > though it probably could be simpler. So it's perhaps better to take on step back and look at the way you organize your data. I remember you sent e-mails about that some time ago. But there's no sense IMO in speaking about efficient ways of iterating if perhaps your data structure has been chosen awkwardly. [...] >> Why do you write a function to store the structure? > just because it is huge. It is about 15 pages of data and this is only > a small snippit > of one list of one page to give an example. When the data gets like > this i sometimes like to > just put it in its own file and import it so that i can just see what > my code is without all that data > cluttering my screen. But that's no reason to put it in a function. You don't need a function to store static data. > originally i was doing something like this: > m1 = [8, 3, 5, 4] > m7 = [4, 3, 2, 2] > m14 = [8, 3, 5, 4] > m18 = [10, 2, 8, 7] > m20 = [10, 0, 5, 7] > m22 = [10, 2, 8, 7] > m24 = [7, 9, 3, 8] > page01 = [m1, m7, m14, m18, m20, m22, m24] > (followed by a bunch of code that munched on those lists) I vaguely remeber it. > But then i realized that i wanted to use that variable name too since > it is meaningful so i changed that to: > pg01 = [ { (1,0) : [8, 3, 5, 4] }, > { (7,0) : [4, 3, 2, 2] }, > { (14,0) : [8, 3, 5, 4] }, > { (18,0) : [10, 2, 8, 7] }, > { (20,0) : [10, 0, 5, 7] }, > { (22,0) : [10, 2, 8, 7] }, > { (24,0) : [7, 9, 3, 8] }] Perhaps it's better to make pg01 a dictionary. At the moment you have a dictionary for every tuple (which are item num,bers); with a lot of items you should perhaps first go to the next computer store and buy RAM :-) Or use just one dictionary. Perhaps it's worth talking about the way you organize your data before we talk about iterating. Also with a nicer data structure ietrating may become a lot easier. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Mon Mar 22 19:08:52 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon Mar 22 19:13:08 2004 Subject: [Tutor] getting names from other funcs In-Reply-To: <5D8C9AD1-7C4F-11D8-9B5D-003065555ABC@mac.com> (kevin parks's message of "Mon, 22 Mar 2004 17:22:12 -0500") References: <5D8C9AD1-7C4F-11D8-9B5D-003065555ABC@mac.com> Message-ID: <m3u10g1ll6.fsf@hamster.pflaesterer.de> On 22 Mar 2004, kevin parks <- kp8@mac.com wrote: > I can't recall how you get to a name in another function. Let's say > that i have a func called foo and it has certain variables and values > held in it that i want to grab and use in test(): > def foo(seq): > '''foo -- makes foo of sequence''' > output = [] > bob = 32768 > fred = ['a', 6, 'yo mama', 'c'] > return fred > def test(): > # how can i get access to the names bob and fred in here? `foo()' should return fred and bob. The alternative would be to use global variabels which is seldom a good idea. So you get: def foo(seq): '''foo -- makes foo of sequence''' output = [] bob = 32768 fred = ['a', 6, 'yo mama', 'c'] return fred, bob def test(): f, b = foo([]) f.append(1) return f Karl -- Please do *not* send copies of replies to me. I read the list From magnus at thinkware.se Mon Mar 22 19:22:53 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Mar 22 19:22:59 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRGlzY3JlcGFuY3k=?= Message-ID: <think001_405f10c9e1ac5@webmail.thinkware.se> Kiran wrote: > what is the problem > > > x =1 > >x is 1 > 1 > > > > (1 is 1) > 1 > > > >x is (1 is 1) > 0 > > once i set x=1 > x is 1 returns true(1) > (1 is 1) returns true(1) > > whereas > x is (1 is 1) > returns 0 Good question! First of all, you need to understand the difference between the 'is' operator, and the '==' operator. You could also note that: >>> 1 == 1.0 True >>> 1 is 1.0 False >>> a = [] >>> b = [] >>> a == b True >>> a is b False (This is in Python 2.3.2, where the logical True/False values have been more clearly distinguished from 1 and 0.) The equality operator (==) returns True (1 in older versions of Python) if both operands have the same value. Sometimes this means that type casting takes place, as you can see above. 1 and 1.0 are coerced into the same type and then the values are compared. The identity operator (is) returns True if both operands point to the same object. The distinction between equality and identity is particularly interesting for mutable objects, such as lists. Continuing with the lists a and b above... >>> c = a >>> c is a True >>> a.append(1) >>> a,b,c ([1], [], [1]) You see? Both a and b were initially empty lists. a == b evaluated to True. But since the assignment "c = a" makes c refer to the *same* list object as a, not just any empty list object. Thus a.append(1) is the same thing as c.append(1), and a==c will always continue to evaluate to true as long as you don't reassign or delete a or c. You can find out the memory address of an object using the builtin id() function, so "x is y" is actually the same as "id(x) == id(y)". I don't have Python 2.2 handy, but it seems there has been a distinction between the numerical integer value 1 and the boolean truth value True even when True was spelled "1"... I'm pretty sure this is intentional. There is certainly a semantic difference between 5 - 4 and 5 > 4. You can verify this by checking that id(1) is different then id(1==1). Note again that "is" is not the operator to use to verify that two values are equal. Its intention is to show that two variables (names) both refer to the same object in the computer's memory. It's really just a technicality that "1 is 1" evaluated to True all the time: Python interns some non-mutable objects, such as small integers and strings, i.e. if you use the same value two times in your code, Python will notice that this value is already defined, and reuse it, instead of wasting space with another, identical, object. (It's up to programmers to reuse code, but Python reuses data for us! :) Naturally, Python can't to this with mutable objects, such as lists, but for immutable objects such as strings and numerical values, it can be an efficient way to work. Don't rely on this to happen though. It's not something which is required of Python, it's just an implementation detail to improve performance. It might be gone in the next version. It's not even consistent over all values of a particular type in a given version of Python. >>> s1 = "Hello" >>> s2 = "Hello" >>> s1 is s2 True >>> s1 = "Hello"*999 >>> s2 = "Hello"*999 >>> s1 is s2 False >>> a = 123456789 >>> type(a) <type 'int'> >>> b = 123456789 >>> a is b False Even the same value might get different treatment! >>> 1234567890123456 is 1234567890123456 True >>> x = 1234567890123456 >>> y = 1234567890123456 >>> id(x) 9282744 >>> id(y) 9282672 >>> x is y False In conclusion, you should typically use '==' to compare things for equality. You might want to use 'is' to see that two names actually refer to the same object, but most of the time you know if they do. There is only one object of the NoneType, so it's completely correct to write "x is None", but "x is 5" is an error waiting to happen in a future Python version... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From python_simpleton at yahoo.com Mon Mar 22 23:47:48 2004 From: python_simpleton at yahoo.com (python_simpleton) Date: Mon Mar 22 23:47:53 2004 Subject: [Tutor] trying to understand the logic of functions Message-ID: <20040323044748.12254.qmail@web61204.mail.yahoo.com> I have been blown away by the complicated questions and answers, the deepth of python is staggering. And yes I am new at programming and python is my first. now to the questions. Oh by the way I have been sticking to Non-Programmers Tutorial for Python. I am sure i am thinking so unlogical compared to ya'll and i'm taking small "babysteps" but i am trying, sorry this is so long but i spent hours reading this tutorial at the airport. General Q. The : symbol is used at the end of the line in more than just a while statement. Is it just used after a control structure (while, if, else, elif in the most basic of uses is what i understand so for) is it used after a condition and keywords? what is the logic behind it? Functions So far in the tutorial variables like a have been given values through the = sign. I understand that. The while, if, count and max_count ideas have made sense, (except on question I will ask about "if" in another email) I have many notes when i tried to work this out here are some of them. a = 23 b = -23 def my_abs (num): if num < 0: num = -num return num if my_abs(a) ==my_abs(b): print "The absolute value of", a,"and",b,"are equal" else: print "The absolute values of a and b are different" I understand that def starts a function definition, my_abs is the function name (good name for absolute value example) Q. num is a parameter? I don't understand what one is really but is it getting the values of a = 23 and b = -23 as a local variable? like this num(a,b)? then go on to figure the rest of the code? or does num take the global variables one at a time to determine which side of 0 they are on. Does num gets if values because of my_abs(a) and my my_abs(b) and this means the function is being called(or whatever the correct word it) twice since it the function has only one parameter (num) and num can only handle on value at a time(a and b are arguments?) Q. return is "returning" a value (i guess that is what it is sup to do) but where does it return a value, what is the value and where is it going. Q. is a definition kind of like the rules the code follows in the sense that it defines what the function name is how many parameters this function can have "it could be" (width, height) and later on code gives arguments "values for parameters) in the respective order. ok here is the last exercise i even attempted in the tutorial def hello(): print "Hello" def area (width, height): return width*height def print_welcome(name): print "Welcome", name hello() hello() print_welcome("Fred") w = 4 h = 5 print "width =",w,"height =",h,"area =" area(w,h) okay here it goes Q. I pretty sure but the first section of code defines hello() as a function and every time that function is call like this hello() it prints the string "Hello" oh yeah this does not have a parameter because the () have nothing in them? Q. In the second section of code defines the function area() is given two parameters? width and height? and like i said before I don't understand what return does unless maybe width and height drive down in their hot rod and pick up (w,h) and w has 4 dollars and h has 5 dollars they return to the area's definition and are times by the code return width*height Q. in the third definition print_welcome is defined as a function with name as its parameter it prints "Welcome", name the value of name is got with the code print_welcome ("Fred") is this right? Q. And of course the code is read line by line and even though that is so the output is in the order that the functions are called. right? and only if that function makes out put (in this example with the print) but not all functions produce output? I bet that was as confusing to read for ya'll as it was for me to think up. maybe you can understand how i went wrong with some of my original notes Original notes(my confusion is as follows) "I think I have a hard time understanding return statement and parameter." "? Is the value of numa and b with a having its value and b having its own value? Def funtion_name code decides what function does or/and gets arguments (whatever that is) get a value? 0, or 5 or 10 or more? a parameter or however many there are are in the ( ) after the function name? so the : is used at the end of the line in more than just a while statement? why after a control structure? I don't understand how num gets the values given to a and b Is num given the value of a to see if greater than 0 then b? num = a or b? num(a) = 23 num(b) = -23 return i don't understand where the value goes does it go to the print statement? Final thought Choas is a world with rules that are not followed. Choas has a defination but cannot be understood by those that are strict and proper-------by me! Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040322/0b82d9e9/attachment.html From isrgish at fastem.com Tue Mar 23 00:40:41 2004 From: isrgish at fastem.com (Isr Gish) Date: Tue Mar 23 00:40:38 2004 Subject: [Tutor] (no subject) Message-ID: <E1B5eeR-0008Bj-DV@mail.python.org> -----Original Message----- >From: "Jeff Peery"<jeffpeery@yahoo.com> >Sent: 3/16/04 5:23:20 PM >To: "tutor@python.org"<tutor@python.org> >Subject: [Tutor] (no subject) > >is there a general clear everything function - other than "del" which I think only works one variable at a time? I've used matlab and there is a function "clear" that I like to call at the beginning of my scripts. My problem is that sometimes in python I make changes to my script and I run it and the changes don't appear, python runs the old version. I'm saving all my scripts before I run them, but I still don't see python using my latest save. I thought that if there was a way to clear the variable list that that would solve my problem. Sometimes I have to close python IDLE and reopen it to get it to run my last save. > You have to reload the module in order for it to use the newer version. There is a function called reload (for obvious reason) that reloads the module. >I also noticed that python might be running off the *.pyc document and not the script itself, is there a way to prevent the *.pyc from being created? > Actually every time you run a script (or module) it crrats a .pyc from the .pybfile and then runs the .pyc. When the .py module is newer the intepreter knows it and creates a new .pyc file from the new .py file. >thanks! > >Jeff > All the best, Isr Gish From isrgish at fastem.com Tue Mar 23 00:40:52 2004 From: isrgish at fastem.com (Isr Gish) Date: Tue Mar 23 00:40:47 2004 Subject: [Tutor] Discrepancy Message-ID: <E1B5eeZ-0008UH-SF@mail.python.org> Hi Kiran kiran@mhowlinux.org wrote: >hi > >what is the problem > >> x =1 >>x is 1 >1 >> >> (1 is 1) >1 This 1 here meens True (in 2.3 it actually returns True instead of 1) >> >>x is (1 is 1) >0 Therefore x which is the number 1 is not the same as True In other words "is" does not do the same as an "==" test. >>> (1 is 1) True >>> x = 1 >>> x is (1 is 1) False >>> x == (1 is 1) True > >once i set x=1 >x is 1 returns true(1) >(1 is 1) returns true(1) > >whereas > x is (1 is 1) >returns 0 > > > >Python Version 2.2.3 > > > > All the best Isr Gish From dyoo at hkn.eecs.berkeley.edu Tue Mar 23 04:37:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 23 04:37:50 2004 Subject: [Tutor] trying to understand the logic of functions In-Reply-To: <20040323044748.12254.qmail@web61204.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0403230102120.29862-100000@hkn.eecs.berkeley.edu> On Mon, 22 Mar 2004, python_simpleton wrote: > I have been blown away by the complicated questions and answers, the > deepth of python is staggering. Hello! No: if we're answering in a way that sounds complicated, then that means that we need to do better to make it less complicated. *grin* The syntax --- the rules for putting a computer program together --- should not be complicated in themselves. > Q. The : symbol is used at the end of the line in more than just a while > statement. Is it just used after a control structure (while, if, else, > elif in the most basic of uses is what i understand so for) is it used > after a condition and keywords? what is the logic behind it? The ':' colon shows up in statements like: for element in sequence: ... or while some_statement_is_true: ... or if some_statement_is_true: ... The colon is there just to make it easier to see the beginning of the block. In fact, you can think of it in the way that English uses: 1. Lists like this. *grin* Same idea. Technically, Python might have been able to do without them, since blocks are already indented. So the colon is not really for the machine, but more for us humans who are reading the program, since we're used to that kind of written convention already. > def my_abs (num): > if num < 0: > num = -num > return num [some text rearranged] > Q. num is a parameter? Yes, we'd say that 'num' here is a parameter of the my_abs function. That is, we can feed my_abs different 'num's. Let's try playing around with it: ### >>> def my_abs(num): ... if num < 0: ... return -num ... else: ... return num ... >>> my_abs(-42) 42 >>> my_abs(15) 15 >>> my_abs <function my_abs at 0x60470> ### Notice that in the last example, since we didn't feed in abs the argument that it expects, it stays inert. So only when we pass all the required arguments to a function, it'll fire off. If we try making it fire off without the argument, we'll get an error message: ### >> my_abs() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: my_abs() takes exactly 1 argument (0 given) ### But that's fine: we expected Python to say something about this, since it has no idea what 'num' should be until we tell it. > this means the function is being called(or whatever the correct word it) > twice since it the function has only one parameter (num) and num can > only handle on value at a time(a and b are arguments?) Whenever Python sees something like: ### >>> my_abs(-42) + my_abs(-43) 85 ### it can't call my_abs(-42) and my_abs(-43) simultaneously. Computers are stupider than that. *grin* What's going on behind the scenes is that Python is first calculating my_abs(-42), storing it temporarily, then calculating my_abs(-43), and storing that temporarily, and then finally adding those temporary variables together. When Python sees something like: my_abs(-42) + my_abs(-43) then it does something sorta like this: ### >>> x1 = my_abs(-42) >>> x2 = my_abs(-43) >>> x1 + x2 85 ### But it can get messy making all these temporary variables, which is why Python lets us say: my_abs(-42) + my_abs(-43) and let us just get back 85, without having to make more variables. > Q. is a definition kind of like the rules the code follows in the sense > that it defines what the function name is how many parameters this > function can have "it could be" (width, height) and later on code gives > arguments "values for parameters) in the respective order. Yes, that's one way to think of it. Functions let us add new commands to the Python system. For example, if we're doing some numerical stuff, we might want to make a squaring program. We'd like to be able to say: ### >>> square(12) ### and be able to get back 144. And we can do this, by defining a function: ### >>> def square(x): ... """Given a number 'x', returns back its squared value.""" ... return x * x ... >>> square(12) 144 ### So whenever we need to get the square of some value, we can now use the square()ing function to do this. We're giving a name to some kind of process. If we're saying something like: ### >>> 3*3 + 4*4 25 ### it's often worth it to make the human intent more clear by using a named function like square: ### >>> five_squared = square(3) + square(4) >>> five_squared 25 ### > def hello(): > print "Hello" > Q. I pretty sure but the first section of code defines hello() as a > function and every time that function is call like this hello() it > prints the string "Hello" oh yeah this does not have a parameter because > the () have nothing in them? Yeah, functions that don't have anything in the argument list are written this way. I haven't answered all of your questions yet, but let's stop for a moment and just make sure that things are making more sense now. *grin* Do you have questions on this so far? Good luck! From Janssen at rz.uni-frankfurt.de Tue Mar 23 04:52:14 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Tue Mar 23 04:52:41 2004 Subject: [Tutor] trying to understand the logic of functions In-Reply-To: <20040323044748.12254.qmail@web61204.mail.yahoo.com> References: <20040323044748.12254.qmail@web61204.mail.yahoo.com> Message-ID: <Pine.A41.4.56.0403230934410.106960@hermes-22.rz.uni-frankfurt.de> On Mon, 22 Mar 2004, python_simpleton wrote: > I am sure i am thinking so unlogical compared to ya'll I don't think its unlogical when one is uncomfortable with basic concepts at the first time. For me its rather refreshing when someone on turor@python asks questions that are that basically that I've long forgotten I had to learn those concepts in my first time also. > General > > Q. The : symbol is used at the end of the line in more than just > a while statement. Is it just used after a control structure > (while, if, else, elif in the most basic of uses is what i > understand so for) is it used after a condition and keywords? what > is the logic behind it? Not after any keyword. break, continue, import, del are all keywords that certainly takes no ":" behind. After conditions that's right, but not only after conditions: for i in range(10): So its rather that the ":" comes behind everything that starts a next level of indentation. Last explanation doesn't explain the problem but leave it to another problem "when to start a next level of indetation". You can learn this by expierence (there arn't much cases that takes a ":"). Or you can look it up in the Language Reference (cause it's rather basic): http://www.python.org/doc/current/ref/ref.html Section 7 deals with if, while, for ... It's named "Compound statements" in contrast to Section 6 "Simple statements". Here you find what you're asking for. But be warned: it's mostly a description of the Python language in a kind of grammar, that itself isn't trivial to understand. Further it's just an description not reason *why* something is like it is (there are no reasons just design decissions). To reword it simple you will leran from the Reference Manual, that if, while, for, try, Function-defintions and Class-definitions are "Compound Statements" that have a ":" followed by a "suite": keyword [anything what goes here]: suite "Simple Statements" like "del" or "break" arn't followed by a suite and doesn't take a ":" . What's a suite? It's a list of further statements. Perhaps it helps you, when looking into the Reference but I don't believe it would help many beginners... To repeat myself: you won't find their any reasons or logic - just definitions and words like "statement" or "suite" that have explanatorical power for some guys. What you will find is completeness and this is sometime helpful. > > Functions > So far in the tutorial variables like a have been given values > through the = sign. I understand that. The while, if, count and > max_count ideas have made sense, (except on question I will ask > about "if" in another email) I have many notes when i tried to > work this out here are some of them. > > a = 23 > b = -23 > > def my_abs (num): > if num < 0: > num = -num > return num > > if my_abs(a) ==my_abs(b): > print "The absolute value of", a,"and",b,"are equal" > else: > print "The absolute values of a and b are different" > I understand that def starts a function definition, my_abs is the > function name (good name for absolute value example) > Q. num is a parameter? I don't understand what one is really but > is it getting the values of a = 23 and b = -23 as a local > variable? like this num(a,b)? then go on to figure the rest of the > code? or does num take the global variables one at a time to > determine which side of 0 they are on. Does num gets if values > because of my_abs(a) and my my_abs(b) and this means the function > is being called(or whatever the correct word it) twice since it > the function has only one parameter (num) and num can only handle > on value at a time(a and b are arguments?) yes, my_abs gets called twice. Perhaps you feel like both function cals get mangled somehow beacuse thay are that near together. They don't get mangled. Both function calls are evaluated seperate and before the if-expression gets evaluated. You can think of it as it done in this order (AFAIK it's *realy* done in this order - but you don't have to care for): if my_abs(a) == my_abs(b): # eval the function calls one after another if 23 == 23: # eval (23 == 23) expression if True: # handle this > Q. return is "returning" a value (i guess that is what it is sup > to do) but where does it return a value, what is the value and > where is it going. as shown above both 23 gets into the if-expression (and is forgotten after). [this was probably very sloppy speaken ;-) Check the Reference Manual when you realy want to dive into this.] > Q. is a definition kind of like the rules the code follows in the > sense that it defines what the function name is how many > parameters this function can have "it could be" (width, height) > and later on code gives arguments "values for parameters) in the > respective order. when you type in "my_abs(-23)" Python runs my_abs with this one argument. When you type in "my_abs(-23, 23)" Python will run this also but it will fail, because my_abs is defined to take only one parameter. > ok here is the last exercise i even attempted in the tutorial > > def hello(): > print "Hello" > > def area (width, height): > return width*height > > def print_welcome(name): > print "Welcome", name > > hello() > hello() > > print_welcome("Fred") > w = 4 > h = 5 > print "width =",w,"height =",h,"area =" area(w,h) > > okay here it goes > Q. I pretty sure but the first section of code defines hello() as > a function and every time that function is call like this hello() > it prints the string "Hello" oh yeah this does not have a > parameter because the () have nothing in them? yes, no argument defined, no argument needed. "hello(somewhat)" would be even an error (try this an python will give you a helpful message). > Q. In the second section of code defines the function area() is > given two parameters? width and height? and like i said before I > don't understand what return does unless maybe width and height > drive down in their hot rod and pick up (w,h) and w has 4 dollars > and h has 5 dollars they return to the area's definition and are > times by the code return width*height area gets two arguments w and h in this order and put the values of both arguments into its defined variables named width and height in this order. "return width*height" gets "return 4*5" gets "return 20" which is given back. [There is a SyntaxError: print "width =",w,"height =",h,"area =" area(w,h) # comma missing print "width =",w,"height =",h,"area =", area(w,h) ] > Q. in the third definition print_welcome is defined as a function > with name as its parameter it prints "Welcome", name the value of > name is got with the code print_welcome ("Fred") is this right? yes > Q. And of course the code is read line by line and even though > that is so the output is in the order that the functions are > called. right? and only if that function makes out put (in this > example with the print) but not all functions produce output? print_welcome makes the print on its own. area returns a value and this is printed via the print statement. Again its like this: print area(4, 5) # eval the function call print 20 # handle this >From the "viewpoint" of print it's no difference if you do this way: a = area(4, 5) print a > I bet that was as confusing to read for ya'll as it was for me to > think up. maybe you can understand how i went wrong with some of > my original notes Perhaps most of the confusion (hey, it's not the worst to allways keep a bit of confusion...) will settle down, when you fire up the interactive python interpreter and test what's happens, when you feed functions like area with different numbers of arguments and tests like this. Michael From vicki at stanfield.net Tue Mar 23 10:13:45 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Tue Mar 23 10:13:57 2004 Subject: [Tutor] Another parsing question Message-ID: <20805.206.53.226.235.1080054825.squirrel@www.thepenguin.org> Once again, I appreciate your patience here. I finally got around to trying what Alan posted to solve my problem of sending a hexidecimal number out the serial port. I got an error. Here is his response to make this more clear. >That's because you have parsed a string - ie a series of characters. >You want to send a series of bytes. You need to convert the 4 >byte character strings into single byte numbers. >Try using the int() operaion: <snip> >>> int('12') >12 >>> int('0x12',16) >18 >>> print "As hex: %0X" % int('0x12',16) >As hex: 12 > >Now you can send that binary number down the pipe: > >for line in data_file.readlines(): > if len(line)>1: > tokens=line.split("|") > for piece in tokens: > port.write(int(piece,16)) # convert to number > time.sleep(S_INTERVAL) > >HTH, > >Alan G. Okay, when I use that code, with my data file which is formatted thusly: 0x02|0x34|0x45|...... I get this error. Just when I think I understand what is going on, something else throws me off. Traceback (most recent call last): File "F:\wxComTool10.py", line 2286, in CommandCallback self.SendCommand(self.selection, "") File "F:\wxComTool10.py", line 248, in SendCommand self.ProcessCommand(command, parameters) File "F:\wxComTool10.py", line 2078, in ProcessCommand port.write(int(piece,16)) File "C:\Python23\Lib\site-packages\serial\serialwin32.py", line 202, err, n = win32file.WriteFile(self.hComPort, s, self._overlappedWrite TypeError: Objects of type 'int' can not be directly written to a file I am not writing to a file, but I am writing to a serial port. Can someone tell me what I am doing wrong? Again, I can't control the inputfile. Thanks so much for not sending an assassin to keep me from posting this same topic over and over. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From bvande at po-box.mcgill.ca Tue Mar 23 13:05:43 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Mar 23 13:06:15 2004 Subject: [Tutor] trying to understand the logic of functions Message-ID: <40607C77.3040901@po-box.mcgill.ca> Date: Mon, 22 Mar 2004 20:47:48 -0800 (PST) From: python_simpleton <python_simpleton@yahoo.com> Subject: [Tutor] trying to understand the logic of functions > Q. return is "returning" a value (i guess that is what it is > sup to do) but where does it return a value, what is the value > and where is it going. Hi all, <Disclaimer> I'm fairly new to Python and programming myself. This is my first venture into responding rather than asking. So, take what I say with a grain of salt rather than as the truth. And watch the list for follow-up posts saying "that Brian guy is so wrong!" Also, this may be a bit long, but I sorted these issue out for myself recently enough that I recall where the newbie stumbling blocks are. Last, sorry for thread breaking -- I'm switching off digest so it won't happen again. </Disclaimer> Mathematically, a function is something that takes some input values and produces an output value. Python functions are more general. They take input values (possibly the empty input) and do stuff, possibly producing an output value as well. It can be a little confusing because the stuff done can look like the function has produced an output value when strictly speaking it has not. Consider the following >>> def redundant_print(z): print z >>> redundant_print(42) 42 It might look like the redundant_print function has produced 42 as a output value, but really the function just ran a print instruction. >>> 42 == redundant_print(42) 42 False This prints 42 as per the function's instruction and then produces 'False' because 42 is not the same as the function redundant_print. Now consider >>> 0 == redundant_print(42) 42 False >>> redundant_print(42) == redundant_print(42) 42 42 True >>> redundant_print(42) == redundant_print(13) 42 13 True >>> The first is false because 0 is not the same as the function. The last 2 both print the value passed into the function on the left, then the value passed into the function on the right (because the functions say to print that value) and then produce "True" because the functions are the same. (The functions are evaluated for whether they are the same function, and the difference of input in the third case doesn't change the fact that the redundant_print function is the redundant_print function.) Now try >>> def redundant_print_with_return(z): print z return z >>> redundant_print_with_return(42) 42 42 This prints 42 as per the function's instruction and then, as the function ends, returns ("sends back") 42 as the output. Since no instructions were given for what to do with the output, it is printed; thus the two output lines. (The first from the function's print instruction, the second from the return statement.) Now try >>> 42 == redundant_print_with_return(42) 42 True Again, it prints 42 as per the function. Having done that, the function returns 42 as the output. This returned 42 then plays its role in the expression that called the function. Since 42 equals 42, the expression 42 == redundant_print_with_return(42) produces 'True'. (The difference between this and the previous case is that this time we gave Python something to do with the returned value -- compare it to 42.) Returns are needed to get values out of a function by ways other than print or write to file instructions, etc. in a function. (I ignore the yield statement here as I'd likely mess the explanation up.) Consider what happens if you run the following script: x = 42 def multiply_by_2(x): print x x = x * 2 print x multiply_by_2(x) print x It produces the following: 42 84 42 Why? The script assigned 42 to x, then defined the function, and ran the function with x as input. The function prints its input (which it calls x) hence the first 42. Then it doubles its input and prints the result, hence the 84. Then, after the function ran, the print x produced 42 when you might have expected it to produce 84. After all, the function reassigned x, didn't it? Nope. The function reassigned the function's local version of x. The function has a different namespace from the script itself. So, the final print x statement says "print the script's version of x" and that was assigned 42 and never reassigned. By contrast, the function's print x statement say "print the function's version of x" and that was reassigned within the function. If you wanted the change to x within the function to be reflected outside the function you could make the name global (I'd surely get the details of this wrong if I tried to explain given my own level of understanding, so I defer). Or, you could use a return statement. Try this script: x = 42 def multiply_by_2(x): print x x = x * 2 print x return x x = multiply_by_2(x) print x This produces: 42 84 84 Why? Again, x is assigned 42 it the script's namespace, and x is passed into the function where, in effect, the value of the script's x is assigned to the value of the function's x. (The two x's being distinct as they "live" in different namespaces.) The final line of the function returns the value of the function's x (which at that point is 84). The return means that multiply_by_2(x) (x here again being the x from the script's namespace) serves as a name for the value of what the function returned (84 in this case). So, "x = multiply_by_2(x)" is a statement reassigning the script x to the value returned by the function. The tricky bit here is that the script's x appears on both the left and the right. But, as always in Python, assignment statements evaluate the right hand side before assigning that value to the left hand side. (This is just as x = x * 2 works.) So, the returned value goes to the context that called the function. In the first return example above the context was empty in that all it was was a function call. So the returned value was dealt with by the default process. The default is printing the value, much like how typing 42 at the interactive prompt has the same effect as typing "print 42". In subsequent cases the function was called within a larger context (assignment statements in the cases I gave). So, the returned value plays its role within those assignments. So, that was a lot of text! Hope it helped some. Best to all, Brian vdB From vicki at stanfield.net Tue Mar 23 16:23:46 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Tue Mar 23 16:23:52 2004 Subject: [Tutor] Another parsing question In-Reply-To: <20805.206.53.226.235.1080054825.squirrel@www.thepenguin.org> References: <20805.206.53.226.235.1080054825.squirrel@www.thepenguin.org> Message-ID: <34601.206.53.226.235.1080077026.squirrel@www.thepenguin.org> Okay, forget it again. For some reason this problem disappeared. I would love to understand it, but I will settle for blissful ignorance. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From amonroe at columbus.rr.com Tue Mar 23 16:40:30 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 23 16:34:27 2004 Subject: [Tutor] NT lockouts when spawning psexec from a multithreaded program? Message-ID: <8079608390.20040323164030@columbus.rr.com> Does anyone have any clue why my accounts get intermittently locked out when spawning psexec from a multithreaded Python program? I have a domain admin account in each of about a dozen domains. They all have the same username. I'm using the threading module, and each new thread spawns a .cmd file (using os.system() ) which runs psexec (the free utility from Sysinternals) as a domain\user. It's the first time I've tried threading - am I doing something obviously wrong? I'm running the main python script on my 2k workstation - would 2k server act any differently? The target server list is a mix of NT and 2k boxes, about 400 of them. I'm limiting the number of threads, while threading.activeCount() < MAXCONCURRENT: I started with a MAXCONCURRENT of 30, bumping it down to 9 didn't help. I would really hate to run them all sequentially. Has anyone tried this before? Alan From magnus at thinkware.se Tue Mar 23 16:59:47 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Mar 23 16:59:53 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gdHJ5aW5nIHRvIHVuZGVyc3RhbmQgdGhlIGxvZ2ljIG9mIGZ1bmN0aW9ucw==?= Message-ID: <think001_4060823eddcc9@webmail.thinkware.se> I'm not very good at short explanations... Sorry. > Q. The : symbol is used at the end of the line in more than just a while statement. Is it just used after a control structure (while, if, else, elif in the most basic of uses is what i understand so for) is it used after a condition and keywords? what is the logic behind it? The : is used in combination with increased indentation to show that a compound statement, or code block begins. It can be control structures such as if/while/for/try, but also code blocks that we use to form reusable chunks of code, i.e. functions and classes. There are also other (larger) chunks, called modules and packages, but modules are entire files, and packages are entire file system directories, so there : isn't appropriate. If a code block following a : is just one line long, you are actually allowed to put in on the same line, so you can type if x < 0: print "Too small" instead of if < 0: print "Too small" but it's not really recommended practice. The : is also used in dictionaries like this: scores = {'mike': 123, 'john': 32, 'glen': 12} In both cases the : is used in a way which is similar to how we use it in normal written text. In some other programming language, you might imagine a more varied syntax, like this... if x == 5 then bla bla while x > 0 do bla bla def f(x, y) as bla bla ..etc, but I think Python's more minimalistic and simple approach is better. There is less you need to remember, and fewer words that are reserved for such special duty, and thus barred from being used as names for variables and functions etc. As far as I understand, there where some research done about this when one of the main inspirational sources of Python, the teaching language ABC was developed. It seems a statement like: if a < 0: something was easier for people to read and understand than if a < 0 something I think this is particularly true if "something" is placed on the same line as the if statement. if a < 0: something seems clearer than if a < 0 something Or is that just me being very used to Python? (Seven years of exposure must have had some effect on me.) > Functions > > So far in the tutorial variables like a have been given values through the = sign. I understand that. The while, if, count and max_count ideas have made sense, (except on question I will ask about "if" in another email) I have many notes when i tried to work this out here are some of them. > > a = 23 > b = -23 > > def my_abs (num): > if num < 0: > num = -num > return num > > if my_abs(a) ==my_abs(b): > print "The absolute value of", a,"and",b,"are equal" > else: > print "The absolute values of a and b are different" > > I understand that def starts a function definition, my_abs is the function name (good name for absolute value example) > > Q. num is a parameter? I don't understand what one is really but is it getting the values of a = 23 and b = -23 as a local variable? like this > num(a,b)? then go on to figure the rest of the code? or does num take the global variables one at a time to determine which side of 0 they are on. > Does num gets if values because of my_abs(a) and my my_abs(b) > and this means the function is being called(or whatever the correct word it) twice since it the function has only one parameter (num) and num can only handle on value at a time(a and b are arguments?) Yes, in general, Python interprets: X() as call (it's just the correct word) X, and X(Y) as call X with Y as input parameter. You could almost imagine a function as a clerk sitting in a closed room with an incoming mail slot and an outgoing mail slot like two holes in the wall. The incoming mail slot is the area between the () in the def line, and the outgoing mail slot is whatever he writes on the return line. def function(incoming): do something in the function return outgoing Besides the incoming mailbox, the clerks office has one way windows which allows him to use more information than the parameters passed in. He can se what is outside the windows, but those outside can not see what is inside the window. >>> outside = 3 >>> def f(inparam): print outside print inparam inside = inparam * 2 return outside * inside >>> x = f(5) 3 5 >>> print x 30 >>> print inside Traceback (most recent call last): File "<pyshell#53>", line 1, in ? print inside NameError: name 'inside' is not defined But note that it's often better to pass in parameters than to get used to the idea if a function peeking outside its bounds. That way it's often easier to maintain the software. As programs grow, it's often problematic to understand what consequences a code change will have. The more isolated and local different parts of a program are, the less risk that a change in one place will have inadvertant effects somewhere else. > Q. return is "returning" a value (i guess that is what it is sup to do) but where does it return a value, what is the value and where is it going. Every time a function is called, it's given some free space in the memory to place its data in. The return statement will hand over a reference to the object listed after "return" to the code that called it. If you for instance do this... def f(x): y = 5 * x return y + 2 k = f(3) ..the following will (roughly) happen. As the program reaches the function definition, it registers f as a global variable, and binds it to the chunk of code inside the definition of f. When the program execution arrives to the line "k = f(3)" Python will create the integer object 3, if it hasn't done that already. It will create a new local namespace for this call to f, and define the local variables x and y there. It will then bind the variable x to the integer object 3, which was passed in with the function call. Next, it will create the object 5 and perform the multiplication. The result of this is 15, so we create a new integer object 15 somewhere in the computers memory, and bind y to that. The object 5 is no longer referenced by anyone, so if it's not used by any other part of the program, Python can make a note that 5's location in memory is no longer occupied. Since the local variables x and y are bound to 3 and 15 respectively, we can't reuse the place these objects use in memory. We might still need these. In the next line, we create the integer object 2, perform the operation 15 + 7, which is 22 and create the integer object 22. 22 is passed to the caller of f, and we're back at the line where we started. As we exit f, its local namespace is dropped, x and y are no longer in existence, so Python is free to use the memory space where the integer objects 3 and 15 reside for other business. It can't throw away 22 yet though. As we return to the line where we started, the global variable k is bound to the integer object 22. If that line had instead been "k = f(4) + f(3)", little would have been different. Function f had been called twice, and each invocation would have used a different namespace, but that doesn't matter much, since the second call to f had happened when the first was already finished. The two results would have been added, a new integer object created, and the sum of f(4) and f(3) bound to k. I tend to see objects like balloons floating around somewhere in the (memory) space, and variable names like tags or labels connected to the ballons with strings. These tags all live in compartments called namespaces, but the actual objects/ballons stay outside the compartments. The organisation we impose is just in our naming of objects, not in the objects themselves... a bit like the real world... The importance of separate namespaces for each call to a function and the need for "one way windows" only, i.e. making it impossible for code outside the function to peer into its interior becomes obvious if we introduce recursion. Remember factorials from school? The factorial F(5) is the product 1 * 2 * 3 * 4 * 5 = 120. You can define it mathematically as F(n) = n * F(n-1) for n > 1 and F(1) = 1, or in Python: def F(n): if n > 1: return n * F(n-1) else: # Assume that n is always a positive integer, i.e. # 1 if we get to this point. return 1 If we now do "x = F(3)", we will get inside the code of F where we will call F with 2 as parameter, and inside that call to F we will call F again with 1 as a parameter. Then we will return 1, and then we'll have returned to the previous incarnation if F where n = 2, and we'll return 2 * 1 = 2, to the first incarnation of F where n=3 and we'll return 3 * 2 = 6 to x. When we are in the middle of this, the local variable n will exist in three different namespaces and have a different value in each of them. This way of solving programming problems is very similar to mathematical induction, and it's often very useful in making an otherwise complex problem simpler. Whether you are using induiction or not, you will use functions to decompose problems to smaller pieces that you can solve one at a time. Note that all functions return a value. Not defining any return statement (or exiting the function another way than the return statement is equivalent with doing "return None". I.e. these are equivalent: def bigger(x, y): if x > y: return True def bigger(x, y): if x > y: return True else: return None or even def bigger(x, y): if x > y: return True return None > Q. is a definition kind of like the rules the code follows in the sense that it defines what the function name is how many parameters this function can have "it could be" (width, height) and later on code gives arguments "values for parameters) in the respective order. A function is mainly a tool that prevents repetition in the code and helps us solve problems a bit at the time in such a way that we don't have to care about more than a small part of the problem we're trying to solve at any particular time. Thus, the important part of a function definition is obviously the function body, the code to execute when the function is called. Parameters are defined, but it can be done in a very flexible way that allow you to call the same function with many different paramters in differnt situations. > ok here is the last exercise i even attempted in the tutorial > > def hello(): > print "Hello" > > def area (width, height): > return width*height > > def print_welcome(name): > print "Welcome", name > > hello() > hello() > > print_welcome("Fred") > w = 4 > h = 5 > print "width =",w,"height =",h,"area =" area(w,h) > > okay here it goes > > Q. I pretty sure but the first section of code defines hello() as a function and every time that function is call like this hello() it prints the string "Hello" oh yeah this does not have a parameter because the () have nothing in them? Correct. Some programming languages lets you skip the parenthesis when it's empty (some strange languages such as VB even lets you skip the parenthersis when you have parameters in some circumstances). Again, like with :, Python settles for consistency and simplicity. Putting () (with or without something inside them) after a name means that you call the object that this name is bound to. If you use a function without (), it means that you want to pass the function object around, or bind it to a new name. Here is an example of each, first an example of binding function objects to new names. >>> def extravagant_greeting(name): print "How are you my most wonderful", name >>> def simple_greeting(name): print "Hi,", name >>> def how_to_greet(): reply = raw_input("Want a long greeting? ") if reply.upper().startswith('Y'): return extravagant_greeting else: return simple_greeting >>> hi = how_to_greet() Want a long greeting? y >>> hi('Magnus') How are you my most wonderful Magnus >>> hi('Guido') How are you my most wonderful Guido >>> hi = how_to_greet() Want a long greeting? n >>> hi('Magnus') Hi, Magnus >>> hi('Guido') Hi, Guido As you see, you can pass functions just as you would pass any other object such as a string of a number. Now, lets pass a function as a parameter: >>> def time_it(f, x): import time start = time.clock() f(x) # Note that "time_it" doesn't know what f is/does. print "Elapsed time =",time.clock() - start, "seconds" >>> def F_rec(n): if n > 1: return n * F_rec(n-1) else: return 1 >>> def F_loop(n): res = 1 for i in range(1,n+1): res = res * i return res >>> time_it(F_rec, 100) Elapsed time = 0.00395413273145 seconds >>> time_it(F_loop, 100) Elapsed time = 0.00377142799698 seconds >>> time_it(F_rec, 900) Elapsed time = 0.00930285572758 seconds >>> time_it(F_loop, 900) Elapsed time = 0.00604937050593 seconds Cute, eh? > Q. In the second section of code defines the function area() is given two parameters? width and height? and like i said before I don't understand what return does unless maybe width and height drive down in their hot rod and pick up (w,h) and w has 4 dollars and h has 5 dollars they return to the area's definition and are times by the code > return width*height I hope I managed to answer this above. > Q. And of course the code is read line by line and even though that is so the output is in the order that the functions are called. right? and only if that function makes out put (in this example with the print) but not all functions produce output? Yes, as Python reads the code it sets up object in memory, checks syntax and defines names and namespaces etc, but the code in a function is not executed until the function is called. > I bet that was as confusing to read for ya'll as it was for me to think up. maybe you can understand how i went wrong with some of my original notes Nope! > Def funtion_name code decides what function does or/and gets arguments (whatever that is) get a value? 0, or 5 or 10 or more? > > a parameter or however many there are are in the ( ) after the function name? Actually, it's a bit more advanced than that. There are some differnt ways of allowing completely different parameters to be passed to the same function from call to call, but maybe this is complicated enough as it is right now... :) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Mar 23 17:25:03 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Mar 23 17:26:08 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gZ2V0dGluZyBuYW1lcyBmcm9tIG90aGVyIGZ1bmNz?= Message-ID: <think001_4060b445575c9@webmail.thinkware.se> > I can't recall how you get to a name in another function. Let's say > that i have a func called foo and it has certain variables and values > held in it that i want to grab and use in test(): The reason you can't recall it is that if you ever knew how to do it, heavens angels have come down from the sky and erased that particular section of your memory for your own protection. I don't have a clue on how to do it. Thank you angels! Local variables are not supposed to be avilable from outside a function, and they only have meaning in the scope of that function, and only retain a value while the function is executing. There are several imaginary scenarios where it might seem useful to know the values of local variables in another function, but none works. For instance, you might want to do something like this: def f(p): x = p def g(): f(5) print f.x # This doesn't really work g() 5 I.e. you want a local variable to remain after a function call, and be able to access it in a convenient way from the outside. First of all, this kind of coding would lead to maintenance hell in real code which tends to be much more complex than this. Just imagine a little change to the code. def g(): f(5) h() # Call another function. print f.x # This doesn't really work If h in turn calls f (maybe indirectly) the value of f.x will be different than you expected. Also, hanging on to all local variables of old function calls will mean that the programs will need much more memory. A simple solution to this is to use a pass the values you want to retain with the return statement as Karl suggested, or to use a class instead of a function. Then you have the tools to specifically decide what values should persist between calls, and a simple way to distinguish between different incarnations of the class. class F: def __init__(self, p): self.x = p def g(): f = F(5) print f.x # This will actually work! g() 5 Another scenario is that you would like to be able to access a local variable in a calling scope, like this: def x(): print y def f(): y = 5 x() f() 5 This is also bad, because it means that in order to be able to call the function x you need to have a certain set of local variables. What would be the point more than to complicate code maintenance once again? The simple solution here is to pass any value you want a function to know in as a parameter. If you feel that you will have a big burden passing so many parameters all over the place, you have probably divided your problem into pieces in a non-optimal way. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tony at tcapp.com Tue Mar 23 17:57:41 2004 From: tony at tcapp.com (Tony Cappellini) Date: Tue Mar 23 17:57:41 2004 Subject: [Tutor] [string.atoi_error, revisionism, and Python 1.0.2] In-Reply-To: <Pine.LNX.4.44.0403221045110.24344-100000@hkn.eecs.berkeley.edu> Message-ID: <20040323145659.R46717-100000@yamato.yamato.com> Thanks Danny. This clears things up quite well. On Mon, 22 Mar 2004, Danny Yoo wrote: > > > On Mon, 22 Mar 2004, Tony Cappellini wrote: > > > > > I've found this code on the net- I think it was from the Python Cookbook. > > > > > > > try: > > > > Celsius=float(string.atoi(CTemp)) > > > > except string.atoi_error: > > > > print repr(CTemp), "not a numeric value" > > > > else: > > > > > > This code is very outdated. Today with a recent python noone would > > > write it like that. > > [some text cut] > > > What I don't understand is- when I looked in the Python documentation, > > under exceptions, only the built-in exceptions were listed. > > > > Hi Tony, > > Yes, the built-in exceptions in: > > http://www.python.org/doc/lib/module-exceptions.html > > do not have string.atoi_error, nor is 'string.atoi_error' documented in > the 'string' module. > > http://www.python.org/doc/lib/module-string.html > > > Interesting. Let me check something: > > > ### > >>> import string > >>> string.atoi_error > <class exceptions.ValueError at 0x40071b0c> > ### > > Ah! string.atoi_error is an alias for the standard exception ValueError! > > > > Ok, I think I have a theory of what's happening. Let's assume for the > moment that that celsius-calculation code was written a long time ago, > since it uses the deprecated 'string' module. We can go back to Python > 1.52's library documentation: > > http://python.org/doc/1.5.2p2/lib/lib.html > Tony From jmatthew at columbus.rr.com Tue Mar 23 21:35:07 2004 From: jmatthew at columbus.rr.com (John Matthews) Date: Tue Mar 23 21:34:56 2004 Subject: [Tutor] How do I slice up a list of strings? Message-ID: <4060F3DB.4040507@columbus.rr.com> I read in data from a log file that looks like this: ['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 \n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] I want to slice the stings so that the list becomes: ['user1', 'user2', 'user2', 'user3', 'user4'] How do I do that? Thanks! -- John Matthews http://8ftarch.org REGIME CHANGE 2004 From gustabares at verizon.net Tue Mar 23 22:53:04 2004 From: gustabares at verizon.net (Gus Tabares) Date: Tue Mar 23 22:53:04 2004 Subject: [Tutor] How do I slice up a list of strings? In-Reply-To: <4060F3DB.4040507@columbus.rr.com> Message-ID: <000001c41153$83262750$0200a8c0@endor> There are multiple ways of doing this and they all vary depending on the data. For instance, let's use the list you've provided us: ['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 \n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] You have 27 characters that you don't care about, which is the date and time info. Then you have 5 (or more) characters that you DO want. OK, so let's try something like this: >>> list = ['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 \n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>> userlist = [] >>> for item in list: userlist.append(item[27:-2]) >>> print userlist ['user1', 'user2', 'user2', 'user3', 'user4'] This, of course, only works if you ALWAYS have those 27 characters in front of the username you want and you always have a space followed by a newline after the username. You could also split each string in the list by whitespace and grab the second-to-last item in the new list. But again, this is depends on the format of your data. HTH, /Gus Tabares -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of John Matthews Sent: Tuesday, March 23, 2004 9:35 PM To: tutor@python.org Subject: [Tutor] How do I slice up a list of strings? I read in data from a log file that looks like this: ['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 \n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] I want to slice the stings so that the list becomes: ['user1', 'user2', 'user2', 'user3', 'user4'] How do I do that? Thanks! -- John Matthews http://8ftarch.org REGIME CHANGE 2004 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jsh47 at cam.ac.uk Wed Mar 24 08:46:08 2004 From: jsh47 at cam.ac.uk (Jonathan Hayward) Date: Wed Mar 24 08:46:25 2004 Subject: [Tutor] file.write() blocking Message-ID: <40619120.3030504@cam.ac.uk> def save_entry(self, text, filename): debug_log("Reached 1") debug_log(DOCUMENT_ROOT + "entries/" + filename) output_file = file(DOCUMENT_ROOT + "entries/" + filename, "w") debug_log("Reached 2") #debug_log(text) file.write("") debug_log("Reached 2.5") file.write(text) debug_log("Reached 3") file.close() debug_log("Reached 4") When I get to this point in my code, it prints, "Reached 2" and hangs on file.write(""). The output directory has a zero-byte file created. When I try analogous test code from Python interactively, it works; does anyone see the glitch in this? (The text is a small webpage.) -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From johnp at HomeLumber.com Wed Mar 24 09:19:50 2004 From: johnp at HomeLumber.com (John Purser) Date: Wed Mar 24 09:19:57 2004 Subject: [Tutor] file.write() blocking Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D216@01-hl-prime.denver.homelmbr.com> I haven't played with the code but at a guess I'd say you were creating a new file every time you run this code. I think you want to change that "w" mode to "w+" I've never tried to write a zero length string to a file and that could also be an issue. What platform and verison of Python are you using? John Purser -----Original Message----- From: Jonathan Hayward [mailto:jsh47@cam.ac.uk] Sent: Wednesday, March 24, 2004 6:46 AM To: tutor@python.org Subject: [Tutor] file.write() blocking def save_entry(self, text, filename): debug_log("Reached 1") debug_log(DOCUMENT_ROOT + "entries/" + filename) output_file = file(DOCUMENT_ROOT + "entries/" + filename, "w") debug_log("Reached 2") #debug_log(text) file.write("") debug_log("Reached 2.5") file.write(text) debug_log("Reached 3") file.close() debug_log("Reached 4") When I get to this point in my code, it prints, "Reached 2" and hangs on file.write(""). The output directory has a zero-byte file created. When I try analogous test code from Python interactively, it works; does anyone see the glitch in this? (The text is a small webpage.) -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jsh47 at cam.ac.uk Wed Mar 24 09:34:14 2004 From: jsh47 at cam.ac.uk (Jonathan Hayward) Date: Wed Mar 24 09:34:27 2004 Subject: Never mind (was Re: [Tutor] file.write() blocking) In-Reply-To: <40619120.3030504@cam.ac.uk> References: <40619120.3030504@cam.ac.uk> Message-ID: <40619C66.6040002@cam.ac.uk> I found the error; I was calling file.write("") instead of output_file.write(argument). Thanks! Jonathan Hayward wrote: > def save_entry(self, text, filename): > debug_log("Reached 1") > debug_log(DOCUMENT_ROOT + "entries/" + filename) > output_file = file(DOCUMENT_ROOT + "entries/" + filename, "w") > debug_log("Reached 2") > #debug_log(text) > file.write("") > debug_log("Reached 2.5") > file.write(text) > debug_log("Reached 3") > file.close() > debug_log("Reached 4") > > When I get to this point in my code, it prints, "Reached 2" and hangs > on file.write(""). The output directory has a zero-byte file created. > When I try analogous test code from Python interactively, it works; > does anyone see the glitch in this? (The text is a small webpage.) > -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From sigurd at 12move.de Wed Mar 24 12:49:45 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Wed Mar 24 12:59:32 2004 Subject: [Tutor] How do I slice up a list of strings? In-Reply-To: <4060F3DB.4040507@columbus.rr.com> (John Matthews's message of "Tue, 23 Mar 2004 21:35:07 -0500") References: <4060F3DB.4040507@columbus.rr.com> Message-ID: <m3y8pqta51.fsf@hamster.pflaesterer.de> On 24 Mar 2004, John Matthews <- jmatthew@columbus.rr.com wrote: > I read in data from a log file that looks like this: > ['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 > user2 \n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 > 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] > I want to slice the stings so that the list becomes: > ['user1', 'user2', 'user2', 'user3', 'user4'] What you want is the last word of each line. So if you read the log file with: log = file('foo.log') users = [line.split()[-1] for line in log] log.close() What happens here is: (a) the file gets opened (b) a list gets build with a list comprehension o each line is read in the variable line o each line gets split on whitespace o from each splitted line the last item is saved as entry for the new build list (c) the file is closed Karl -- Please do *not* send copies of replies to me. I read the list From Doug.Gentry at comcast.net Wed Mar 24 13:29:15 2004 From: Doug.Gentry at comcast.net (Doug Gentry) Date: Wed Mar 24 13:29:20 2004 Subject: [Tutor] python virgin Message-ID: <E1B6D7t-0005Vs-Ge@mail.python.org> Heck, I'm a programming virgin too. I was browsing the net the other day and ran across a site about active state python. I had the "old Python loaded on here so I removed it and installed the new version on my XP computer. I'm trying to find some sites that has some info about how to use it. I think I've found a couple but the instructions in there seem to be for the older python I was using before. i.e.; click on file and then new window? Mine has File/new and then a choice of script or grep. I kind of figured that script is the same thing as what they wanted in the new window. Also when I opened notepad and did the little exercise of hello world and saved as hello.py I went back and ran it. I get a real quick flash of a cmd box running but that's it. I suppose because it's RUNNING the program hello.py and there really is nothing to see, except HELLO WORLD for a brief 1/60th of a second? So I guess my question should be. Does anyone know of a good website to go to learn this? Also I'd like to thank all you wonderful people for doing this tutoring thing. It's so nice to meet a group of people that have really nice intentions of helping people and learning! Thanks so much for being there! Doug -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040324/896b68f2/attachment.html From wilson at visi.com Wed Mar 24 13:37:52 2004 From: wilson at visi.com (Tim Wilson) Date: Wed Mar 24 13:38:04 2004 Subject: [Tutor] python virgin In-Reply-To: <E1B6D7t-0005Vs-Ge@mail.python.org> Message-ID: <BC8731A0.551A%wilson@visi.com> On 3/24/04 12:29 PM, "Doug Gentry" <Doug.Gentry@comcast.net> wrote: > I suppose because it?s RUNNING the program hello.py and there really is > nothing to see, except HELLO WORLD for a brief 1/60th of a second? The problem is that your shell is closing as soon as the program finishes. Not very helpful. One way to "fix" this is to include a line like the following at the very end of your program: end = raw_input("Hit 'Return' to close window.") The program will stop execution at this point and wait for you to hit your 'Return' key. -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From apqle75 at hotmail.com Wed Mar 24 14:13:11 2004 From: apqle75 at hotmail.com (APQ LE) Date: Wed Mar 24 14:13:15 2004 Subject: [Tutor] write a file Message-ID: <BAY16-F52TmbQLGvlnu00014261@hotmail.com> I'm trying to open a file, read its content and write its content to a new file. Pretty much like copying a file. Here is what I have ======== in = open ("a.txt", "r") out = open ("b.txt", "w") for line in in.readlines() out.write(line) in.close() out.close() ========== However, the output isn't as expected. There is additional empty line comes after every existing line. So, the output file is bigger than the original file. ~Megan _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page – FREE download! http://toolbar.msn.com/go/onm00200413ave/direct/01/ From johnp at HomeLumber.com Wed Mar 24 14:41:04 2004 From: johnp at HomeLumber.com (John Purser) Date: Wed Mar 24 14:41:28 2004 Subject: [Tutor] python virgin Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D222@01-hl-prime.denver.homelmbr.com> Morning Doug, Python is a great language to get started in programming with. I wish I had begun with it. To get that window to hang around a while try adding "raw_input()" without the quotes as the last line of your script. It will hold the window open until you hit enter. You can also run your scripts from the command prompt. Then any messages will remain on the screen. Especially handy for bug hunting. You might want to wander out to www.python.org (note the .org domain or you get a VERY different site) and look at the documentation. You can find a list of resources for non-programmers at: http://www.python.org/topics/learn/non-prog.html There's a very good tutorial written by GvR himself as well as a lot of links to other helpful sites. There's also the O'Reilly book "Learning Python" which is a good place to start as well. And recently I came across this site: http://www.freenetpages.co.uk/hp/alan.gauld/ In short there are a lot of internet sites out there as well as this mailing list to get you off the ground. Good luck and happy hacking. John Purser -----Original Message----- From: Doug Gentry [mailto:Doug.Gentry@comcast.net] Sent: Wednesday, March 24, 2004 11:29 AM To: tutor@python.org Subject: [Tutor] python virgin Heck, I'm a programming virgin too. I was browsing the net the other day and ran across a site about active state python. I had the "old Python loaded on here so I removed it and installed the new version on my XP computer. I'm trying to find some sites that has some info about how to use it. I think I've found a couple but the instructions in there seem to be for the older python I was using before. i.e.; click on file and then new window? Mine has File/new and then a choice of script or grep. I kind of figured that script is the same thing as what they wanted in the new window. Also when I opened notepad and did the little exercise of hello world and saved as hello.py I went back and ran it. I get a real quick flash of a cmd box running but that's it. I suppose because it's RUNNING the program hello.py and there really is nothing to see, except HELLO WORLD for a brief 1/60th of a second? So I guess my question should be. Does anyone know of a good website to go to learn this? Also I'd like to thank all you wonderful people for doing this tutoring thing. It's so nice to meet a group of people that have really nice intentions of helping people and learning! Thanks so much for being there! Doug From sigurd at 12move.de Wed Mar 24 14:52:38 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Wed Mar 24 14:54:48 2004 Subject: [Tutor] write a file In-Reply-To: <BAY16-F52TmbQLGvlnu00014261@hotmail.com> (APQ LE's message of "Wed, 24 Mar 2004 13:13:11 -0600") References: <BAY16-F52TmbQLGvlnu00014261@hotmail.com> Message-ID: <m3u10et4fk.fsf@hamster.pflaesterer.de> On 24 Mar 2004, APQ LE <- apqle75@hotmail.com wrote: > I'm trying to open a file, read its content and write its content to a > new file. Pretty much like copying a file. Here is what I have > ======== > in = open ("a.txt", "r") > out = open ("b.txt", "w") > for line in in.readlines() > out.write(line) > in.close() > out.close() > ========== > However, the output isn't as expected. There is additional empty line > comes after every existing line. So, the output file is bigger than > the original file. What OS are you working on? Furthermore the above code is overcomplicated; I assume you use a recent version of Python. Then you could write: inf = file('a.txt') out = file('b.txt', 'w') out.writelines(inf) out.close() inf.close() writelines() takes an iterator as argument: here the open file object. Karl -- Please do *not* send copies of replies to me. I read the list From johnp at HomeLumber.com Wed Mar 24 15:04:30 2004 From: johnp at HomeLumber.com (John Purser) Date: Wed Mar 24 15:04:35 2004 Subject: [Tutor] write a file Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D223@01-hl-prime.denver.homelmbr.com> Megan, I'd guess you were reading a file created on windows under Linux/Unix. When I run your code on a windows file under windows it works fine. It would help if you included the platform you are using. You might want to try: n = file('a.txt', 'r') o = file('b.txt', 'w') for line in n.readlines(): # print line o.write(line.rstrip() + '\n') n.close() o.close() which will strip the white characters off the right side of the line. Then the '\n' will put the correct line termination character for your system on it. And I think file is the same as open. I believe file is the new version and open links to it but I could have that backwards. Good Luck, John Purser -----Original Message----- From: APQ LE [mailto:apqle75@hotmail.com] Sent: Wednesday, March 24, 2004 12:13 PM To: tutor@python.org Subject: [Tutor] write a file I'm trying to open a file, read its content and write its content to a new file. Pretty much like copying a file. Here is what I have ======== in = open ("a.txt", "r") out = open ("b.txt", "w") for line in in.readlines() out.write(line) in.close() out.close() ========== However, the output isn't as expected. There is additional empty line comes after every existing line. So, the output file is bigger than the original file. ~Megan _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page - FREE download! http://toolbar.msn.com/go/onm00200413ave/direct/01/ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From johnp at HomeLumber.com Wed Mar 24 15:05:50 2004 From: johnp at HomeLumber.com (John Purser) Date: Wed Mar 24 15:06:01 2004 Subject: [Tutor] write a file Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D224@01-hl-prime.denver.homelmbr.com> Thanks Karl. I hadn't seen writelines() before. John -----Original Message----- From: Karl Pfl?sterer [mailto:sigurd@12move.de] Sent: Wednesday, March 24, 2004 12:53 PM To: tutor@python.org Subject: Re: [Tutor] write a file On 24 Mar 2004, APQ LE <- apqle75@hotmail.com wrote: > I'm trying to open a file, read its content and write its content to a > new file. Pretty much like copying a file. Here is what I have > ======== > in = open ("a.txt", "r") > out = open ("b.txt", "w") > for line in in.readlines() > out.write(line) > in.close() > out.close() > ========== > However, the output isn't as expected. There is additional empty line > comes after every existing line. So, the output file is bigger than > the original file. What OS are you working on? Furthermore the above code is overcomplicated; I assume you use a recent version of Python. Then you could write: inf = file('a.txt') out = file('b.txt', 'w') out.writelines(inf) out.close() inf.close() writelines() takes an iterator as argument: here the open file object. Karl -- Please do *not* send copies of replies to me. I read the list _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From idiot1 at netzero.net Wed Mar 24 15:13:00 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Mar 24 15:11:58 2004 Subject: [Tutor] usenet server quest Message-ID: <4061EBCC.4010604@netzero.net> OK, I want a usenet server. There is nothing in the library to facilitate this, so it might turn into an entire nre module. To start with, it can be a single group. It should not be a hairpull to install. And of course, written in python. Any discussion? -- Respectfully, Kirk D Bailey Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From project5 at redrival.net Wed Mar 24 15:15:02 2004 From: project5 at redrival.net (Andrei) Date: Wed Mar 24 15:15:12 2004 Subject: [Tutor] Re: python virgin References: <E1B6D7t-0005Vs-Ge@mail.python.org> Message-ID: <tleld02brbsx.15ewc1uz1pzt8.dlg@40tude.net> Doug Gentry wrote on Wed, 24 Mar 2004 10:29:15 -0800: > Heck, I'm a programming virgin too. I was browsing the net the other day and > ran across a site about active state python. I had the "old Python loaded > on here so I removed it and installed the new version on my XP computer. I too prefer the ActiveState distro over the default Python one. The docs are much better for one thing and it includes PythonWin which is better than IDLE IMO. > i.e.; click on file and then new window? Mine has File/new and then a choice > of script or grep. I kind of figured that script is the same thing as what > they wanted in the new window. Not sure if you're talking about IDLE, PythonWin or... > Also when I opened notepad and did the little exercise of hello world and > saved as hello.py I went back and ran it. I get a real quick flash of a cmd > box running but that's it. Except for that raw_input method that Tim Wilson mentioned, you could also open the program in PythonWin (as opposed to Notepad) and then run it from there. The output will be (and will remain) visible inside PythonWin itself. > So I guess my question should be. Does anyone know of a good website to go > to learn this? Alan Gauld's tutorial is nice (as linked by John Purser), How To Think Like A Computer Scientist in Python is nice too. Don't be fooled, by the name, it's a beginner-level tutorial: http://www.ibiblio.org/obp/thinkCSpy/ There are many more (I particularly liked http://www.hetland.org/python/instant-hacking.php, but it's down ATM of this writing), but which one is the best for you, depends on your style of learning. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From goki75 at vsnl.net Wed Mar 24 15:16:37 2004 From: goki75 at vsnl.net (G Kiran) Date: Wed Mar 24 15:17:48 2004 Subject: [Tutor] Re: How do I slice up a list of strings? References: <E1B6BnK-0006jO-Ab@mail.python.org> Message-ID: <001301c411dc$eeabcb90$4d2ee2dc@VULCAN> >>> l=['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 \n','Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>> l ['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 \n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>> a=[s[27:-2] for s in l] >>> a ['user1', 'user2', 'user2', 'user3', 'user4'] or >>> a=[s.strip().split()[-1] for s in l] >>> a ['user1', 'user2', 'user2', 'user3', 'user4'] >>> Beware of the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org- Helping Linux users in Mhow --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.624 / Virus Database: 401 - Release Date: 3/15/2004 From johnp at HomeLumber.com Wed Mar 24 15:18:34 2004 From: johnp at HomeLumber.com (John Purser) Date: Wed Mar 24 15:18:55 2004 Subject: [Tutor] usenet server quest Message-ID: <D0DD3F40FC3F714A88D0DB43BAE362565F0512@01-hl-prime.denver.homelmbr.com> Google = "nntp server", Python http://freshmeat.net/projects/papercut/ You might want to contribute to this existing project. John Purser -----Original Message----- From: Kirk Bailey [mailto:idiot1@netzero.net] Sent: Wednesday, March 24, 2004 1:13 PM To: tutor@python.org Subject: [Tutor] usenet server quest OK, I want a usenet server. There is nothing in the library to facilitate this, so it might turn into an entire nre module. To start with, it can be a single group. It should not be a hairpull to install. And of course, written in python. Any discussion? -- Respectfully, Kirk D Bailey Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From goki75 at vsnl.net Wed Mar 24 15:18:13 2004 From: goki75 at vsnl.net (G Kiran) Date: Wed Mar 24 15:19:21 2004 Subject: [Tutor] Re: How do I slice up a list of strings? (John Matthews) References: <E1B6BnK-0006jO-Ab@mail.python.org> Message-ID: <001e01c411dd$271bbb70$4d2ee2dc@VULCAN> >>> l=['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 \n','Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>> l ['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 \n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>> a=[s[27:-2] for s in l] >>> a ['user1', 'user2', 'user2', 'user3', 'user4'] or >>> a=[s.strip().split()[-1] for s in l] >>> a ['user1', 'user2', 'user2', 'user3', 'user4'] >>> Beware of the lollipop of mediocrity: lick it once and you suck forever www.mhowlinux.org- Helping Linux users in Mhow --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.624 / Virus Database: 401 - Release Date: 3/15/2004 From project5 at redrival.net Wed Mar 24 15:25:56 2004 From: project5 at redrival.net (Andrei) Date: Wed Mar 24 15:26:05 2004 Subject: [Tutor] Re: write a file References: <BAY16-F52TmbQLGvlnu00014261@hotmail.com> <m3u10et4fk.fsf@hamster.pflaesterer.de> Message-ID: <b4a67ddg3mz0$.1gpjh4rtzrv7g.dlg@40tude.net> Karl Pfl?sterer wrote on Wed, 24 Mar 2004 20:52:38 +0100: >> I'm trying to open a file, read its content and write its content to a >> new file. Pretty much like copying a file. Here is what I have > >> ======== >> in = open ("a.txt", "r") >> out = open ("b.txt", "w") >> for line in in.readlines() >> out.write(line) > >> in.close() >> out.close() That code works?? Never gives stuff names that are already used by Python. 'in' is a kewyword used in e.g. 'for something in whatever', so you shouldn't be able to name a file 'in'. It's also a bad idea to override built-ins, like range, file or open - even though you don't do that in that particular piece of code :). >> ========== >> However, the output isn't as expected. There is additional empty line >> comes after every existing line. So, the output file is bigger than >> the original file. That might happen especially on Windows where lines end in '\r\n'. Let's see if I get this right... '\n' gets expanded to '\r\n' as well and '\n' means on its own that a new line is required, so you end up with an extra empty line. The line ends are very pesky, because different platforms use different line endings (on Linux lines end in \n, on Mac I believe in \r and on Windows in both). I think that if you open the file with "rU" instead of "r" you might get better results. (not available in Pythons older than 2.3) -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From amonroe at columbus.rr.com Wed Mar 24 16:02:30 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Mar 24 15:56:19 2004 Subject: [Tutor] pickle broken for strings in 2.3? Message-ID: <181163728348.20040324160230@columbus.rr.com> Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x={1:2, 'a':'b'} >>> import pickle >>> pickle.dump(x, 'test.pik') Traceback (most recent call last): File "<stdin>", line 1, in ? File "c:\python23\lib\pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "c:\python23\lib\pickle.py", line 210, in __init__ self.write = file.write AttributeError: 'str' object has no attribute 'write' From tony at tcapp.com Wed Mar 24 16:01:45 2004 From: tony at tcapp.com (Tony Cappellini) Date: Wed Mar 24 16:01:46 2004 Subject: [Tutor] Re: Tutor Digest, Vol 1, Issue 2678 In-Reply-To: <E1B6EjP-00033d-US@mail.python.org> Message-ID: <20040324125738.M71236-100000@yamato.yamato.com> Doug One good place to start is at many of the Python Tutorials (google will help you find them). Another good starting point for non-programmers is http://www.python.org/topics/learn/non-prog.html A very good Online book (free) is Dive Into Python (assumes some programming knowledge, but still a great place to learn Python) http://diveintopython.org/ Of course- this list is an excellent resource too. It has been a big help to me. Tony From johnp at HomeLumber.com Wed Mar 24 16:06:20 2004 From: johnp at HomeLumber.com (John Purser) Date: Wed Mar 24 16:06:24 2004 Subject: [Tutor] pickle broken for strings in 2.3? Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D226@01-hl-prime.denver.homelmbr.com> You passed a file name to pickle, not an opened file object. So when pickle tried to "test.pik.write(x)" it couldn't do it because the string test.pik has no write method. try: f = file("test.pik", "w") pickle.dump(x, f) and see if that works better. John Purser -----Original Message----- From: R. Alan Monroe [mailto:amonroe@columbus.rr.com] Sent: Wednesday, March 24, 2004 2:03 PM To: tutor@python.org Subject: [Tutor] pickle broken for strings in 2.3? Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x={1:2, 'a':'b'} >>> import pickle >>> pickle.dump(x, 'test.pik') Traceback (most recent call last): File "<stdin>", line 1, in ? File "c:\python23\lib\pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "c:\python23\lib\pickle.py", line 210, in __init__ self.write = file.write AttributeError: 'str' object has no attribute 'write' _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From aschmidt at fredericksburg.com Wed Mar 24 16:09:46 2004 From: aschmidt at fredericksburg.com (Allen Schmidt) Date: Wed Mar 24 16:10:51 2004 Subject: [Tutor] Once again....HTTP Digest Authentication In-Reply-To: <181163728348.20040324160230@columbus.rr.com> References: <181163728348.20040324160230@columbus.rr.com> Message-ID: <4061F91A.3020206@fredericksburg.com> Howdy folks, I did another google search on what I needed and danged if my original question months ago was what popped up. Back at it again and I need to know (examples, etc) how to call a URL that requires a userid and password using digest authentication to proceed with the request. I just need a tutor-simplisitic approach as to how to get started. How do I pass a URL so that I get 'asked' for the userid and pwd? Or how do I pass it all at once? I am just lost as to how to proceed. If someone might be able to help but feels this outside of tutor type answers, I am willing to PayPal you for your time. Just let me know. Thanks!!! Allen From johnp at HomeLumber.com Wed Mar 24 16:20:31 2004 From: johnp at HomeLumber.com (John Purser) Date: Wed Mar 24 16:20:40 2004 Subject: [Tutor] Once again....HTTP Digest Authentication Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D227@01-hl-prime.denver.homelmbr.com> Alan, Take a look at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267197 There seems to be an example there that passes a username and password to a URL. I found it by Goggling = http, Python, username, password. Lots of other links listed as well. Good Luck, John Purser -----Original Message----- From: Allen Schmidt [mailto:aschmidt@fredericksburg.com] Sent: Wednesday, March 24, 2004 2:10 PM To: tutor@python.org Subject: [Tutor] Once again....HTTP Digest Authentication Howdy folks, I did another google search on what I needed and danged if my original question months ago was what popped up. Back at it again and I need to know (examples, etc) how to call a URL that requires a userid and password using digest authentication to proceed with the request. I just need a tutor-simplisitic approach as to how to get started. How do I pass a URL so that I get 'asked' for the userid and pwd? Or how do I pass it all at once? I am just lost as to how to proceed. If someone might be able to help but feels this outside of tutor type answers, I am willing to PayPal you for your time. Just let me know. Thanks!!! Allen _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From apqle75 at hotmail.com Wed Mar 24 16:45:34 2004 From: apqle75 at hotmail.com (APQ LE) Date: Wed Mar 24 16:45:40 2004 Subject: [Tutor] write a file Message-ID: <BAY16-F79NMjiGwYt7y00014a47@hotmail.com> Thanks for all the responses. Here is what I have. OS: Win 2k File: French context (French strings) Encoding: Unicode ----- The output file that I got contains a bunch of question marks after every strings that I have. For example, the original string is Le fichier local n'a pas pu être créé. output: Le fichier local n'a pas pu être créé. ???????????????????????????????? ~Megan >From: sigurd@12move.de (Karl Pflästerer) >To: tutor@python.org >Subject: Re: [Tutor] write a file >Date: Wed, 24 Mar 2004 20:52:38 +0100 > >On 24 Mar 2004, APQ LE <- apqle75@hotmail.com wrote: > > > I'm trying to open a file, read its content and write its content to a > > new file. Pretty much like copying a file. Here is what I have > > > ======== > > in = open ("a.txt", "r") > > out = open ("b.txt", "w") > > for line in in.readlines() > > out.write(line) > > > in.close() > > out.close() > > > ========== > > However, the output isn't as expected. There is additional empty line > > comes after every existing line. So, the output file is bigger than > > the original file. > >What OS are you working on? > >Furthermore the above code is overcomplicated; I assume you use a recent >version of Python. Then you could write: > >inf = file('a.txt') >out = file('b.txt', 'w') >out.writelines(inf) >out.close() >inf.close() > >writelines() takes an iterator as argument: here the open file object. > > > > > Karl >-- >Please do *not* send copies of replies to me. >I read the list > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page – FREE download! http://toolbar.msn.com/go/onm00200413ave/direct/01/ From apqle75 at hotmail.com Wed Mar 24 16:51:47 2004 From: apqle75 at hotmail.com (APQ LE) Date: Wed Mar 24 16:51:53 2004 Subject: [Tutor] Re: write a file Message-ID: <BAY16-F35LtosJ3Ih7j0001514b@hotmail.com> 'rU' works better, but not completely. Now, I get two trailing question marks at the end of every line rather than an additional line with only question marks. what is 'U'? thanks. >From: Andrei <project5@redrival.net> >To: tutor@python.org >Subject: [Tutor] Re: write a file >Date: Wed, 24 Mar 2004 21:25:56 +0100 > >Karl Pflästerer wrote on Wed, 24 Mar 2004 20:52:38 +0100: > > >> I'm trying to open a file, read its content and write its content to a > >> new file. Pretty much like copying a file. Here is what I have > > > >> ======== > >> in = open ("a.txt", "r") > >> out = open ("b.txt", "w") > >> for line in in.readlines() > >> out.write(line) > > > >> in.close() > >> out.close() > >That code works?? Never gives stuff names that are already used by Python. >'in' is a kewyword used in e.g. 'for something in whatever', so you >shouldn't be able to name a file 'in'. It's also a bad idea to override >built-ins, like range, file or open - even though you don't do that in that >particular piece of code :). > > >> ========== > >> However, the output isn't as expected. There is additional empty line > >> comes after every existing line. So, the output file is bigger than > >> the original file. > >That might happen especially on Windows where lines end in '\r\n'. Let's >see if I get this right... '\n' gets expanded to '\r\n' as well and '\n' >means on its own that a new line is required, so you end up with an extra >empty line. The line ends are very pesky, because different platforms use >different line endings (on Linux lines end in \n, on Mac I believe in \r >and on Windows in both). > >I think that if you open the file with "rU" instead of "r" you might get >better results. (not available in Pythons older than 2.3) > >-- >Yours, > >Andrei > >===== >Real contact info (decode with rot13): >cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq >gur yvfg, fb gurer'f ab arrq gb PP. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Get tax tips, tools and access to IRS forms – all in one place at MSN Money! http://moneycentral.msn.com/tax/home.asp From alan.gauld at blueyonder.co.uk Wed Mar 24 18:06:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Mar 24 18:07:40 2004 Subject: [Tutor] Another parsing question References: <20805.206.53.226.235.1080054825.squirrel@www.thepenguin.org> Message-ID: <00c501c411f4$b1664ae0$6401a8c0@xp> > Once again, I appreciate your patience here. I finally got around to > trying what Alan posted to solve my problem of sending a hexidecimal > number out the serial port. I got an error. Oops! > >for line in data_file.readlines(): > > if len(line)>1: > > tokens=line.split("|") > > for piece in tokens: > > port.write(int(piece,16)) # convert to number You apparently need to convert the number back to a string to write it to the port. I'm not sure why because I'd have thought writing binary data should be OK... Is there a mode when you open the port? Like with a file you have to specifically request binary mode? > File "F:\wxComTool10.py", line 2078, in ProcessCommand > port.write(int(piece,16)) > File "C:\Python23\Lib\site-packages\serial\serialwin32.py", line 202, > err, n = win32file.WriteFile(self.hComPort, s, self._overlappedWrite > TypeError: Objects of type 'int' can not be directly written to a file > > I am not writing to a file, but I am writing to a serial port. Can someone > tell me what I am doing wrong? Again, I can't control the inputfile. Not too sure but it looks like your port can only accept text! Which is, frankly, quite strange. And somewhat defeats what you are trying to do! Alan G. From magnus at thinkware.se Wed Mar 24 18:31:38 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Mar 24 18:33:05 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQW5vdGhlciBwYXJzaW5nIHF1ZXN0aW9u?= Message-ID: <think001_406217b4df9ac@webmail.thinkware.se> Vicki Stanfield wrote: > > TypeError: Objects of type 'int' can not be directly written to a > file > > > > I am not writing to a file, but I am writing to a serial port. Can > someone > > tell me what I am doing wrong? Again, I can't control the inputfile. Alan Gauld replied: > Not too sure but it looks like your port can only accept text! > Which is, frankly, quite strange. And somewhat defeats what you are > trying to do! Isn't it just that the serial port tries to behave like a file object. That's fairly normal I think. So do most other byte streams that are used in Python, and it's common to transfer text over serial lines. Also, a serial port using RS-232 is set up to send chunks of 7 or 8 bits, which fits 8 bit characters better than integers which are 32 (or 64 if you're lucky) bits wide. I assume that you just send chr(x) where x is your 8 bit unsigned integer, and to read, you call ord() on the byte you read to convert it to an integer in the range 0 to 255. Files behave like this in Python. >>> f = file('c:/test.dat', 'wb') >>> f.write(65) Traceback (most recent call last): File "<pyshell#21>", line 1, in -toplevel- f.write(65) TypeError: argument 1 must be string or read-only buffer, not int >>> f.write(chr(65)) >>> f.close() >>> f = file('c:/test.dat', 'r') >>> print f.read() A >>> f.seek(0) >>> print ord(f.read()) 65 -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From marilyn at deliberate.com Wed Mar 24 19:08:53 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Mar 24 19:08:59 2004 Subject: [Tutor] exception details Message-ID: <Pine.LNX.4.44.0403241608260.9416-100000@Kuna> Hi, I'm trying to get a strong handle on exception mechanism details. Note that there are three try/except's and that the 1st 2 work fine. But the third one doesn't catch the random exception generated. Do I have a typo? Thank you for any help you can give. Marilyn Davis #!/usr/bin/env python2.2 '''Ways to get more info about your caught exception.''' import exceptions # to get a list of built-in exceptions import random import sys # gives info -- you can use the traceback module but # it uses sys. def ok(msg): raise ValueError, msg def fun(msg): '''Raises a random built-in exception.''' excepts = dir(exceptions) while excepts[-1][0] == '_': # Getting rid of __doc__ and __name__ excepts.pop() raise_this = excepts[random.randrange(len(excepts))] print 'Raising', str(raise_this), 'To', msg raise raise_this, msg if __name__ == '__main__': try: ok('this works ok') except Exception, exception: print 'exception.args = ', exception.args print 'exception = ', exception try: fun('catch with "except:" on random exception works') except: print 'Caught: sys.exc_type =', sys.exc_type,\ 'sys.exc_value =', sys.exc_value print 'sys.exc_traceback =', sys.exc_traceback print sys.exc_info() try: fun('''catch with "Exception, exception: on random exception doesn't work"''') except Exception, exception: print 'exception.args = ', exception.args print 'exception = ', exception ############################################################ # OUTPUT: # bash-2.05a$ ./x.py # exception.args = ('this works ok',) # exception = this works ok # Raising UnboundLocalError To catch with "except:" on random exception works # Caught: sys.exc_type = UnboundLocalError sys.exc_value = catch with "except:" on random exception works # sys.exc_traceback = <traceback object at 0x81522f4> # ('UnboundLocalError', 'catch with "except:" on random exception works', <traceback object at 0x81522f4>) # Raising Exception To catch with "Exception, exception: on random exception doesn't work" # Traceback (most recent call last): # File "./x.py", line 37, in ? # fun('''catch with "Exception, exception: on random exception doesn't work"''') # File "./x.py", line 19, in fun # raise raise_this, msg # Exception: catch with "Exception, exception: on random exception doesn't work" # bash-2.05a$ -- From AJGables at cs.com Wed Mar 24 21:27:18 2004 From: AJGables at cs.com (AJGables@cs.com) Date: Wed Mar 24 21:27:33 2004 Subject: [Tutor] 'help' remove me from you list immediately. Message-ID: <28E24375.449540BB.0063AD5D@cs.com> help unsubscribe me immediately. I do not wish to receive any further communication from you. aj >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@python.org > >You can reach the person managing the list at > ? ?tutor-owner@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: python virgin (Andrei) > ? 2. Re: How do I slice up a list of strings? (G Kiran) > ? 3. RE: usenet server quest (John Purser) > ? 4. Re: How do I slice up a list of strings? (John Matthews) (G Kiran) > ? 5. Re: write a file (Andrei) > ? 6. pickle broken for strings in 2.3? (R. Alan Monroe) > ? 7. Re: Tutor Digest, Vol 1, Issue 2678 (Tony Cappellini) > ? 8. RE: pickle broken for strings in 2.3? (John Purser) > ? 9. Once again....HTTP Digest Authentication (Allen Schmidt) > ?10. RE: Once again....HTTP Digest Authentication (John Purser) > ?11. Re: write a file (APQ LE) > ?12. RE: Re: write a file (APQ LE) > > >---------------------------------------------------------------------- > >Message: 1 >Date: Wed, 24 Mar 2004 21:15:02 +0100 >From: Andrei <project5@redrival.net> >Subject: [Tutor] Re: python virgin >To: tutor@python.org >Message-ID: <tleld02brbsx.15ewc1uz1pzt8.dlg@40tude.net> >Content-Type: text/plain; charset="us-ascii" > >Doug Gentry wrote on Wed, 24 Mar 2004 10:29:15 -0800: > >> Heck, I'm a programming virgin too. I was browsing the net the other day and >> ran across a site about active ?state python. I had the "old Python loaded >> on here so I removed it and installed the new version on my XP computer. > >I too prefer the ActiveState distro over the default Python one. The docs >are much better for one thing and it includes PythonWin which is better >than IDLE IMO. > >> i.e.; click on file and then new window? Mine has File/new and then a choice >> of script or grep. I kind of figured that script is the same thing as what >> they wanted in the new window. > >Not sure if you're talking about IDLE, PythonWin or... > >> ?Also when I opened notepad and did the little exercise of hello world and >> saved as hello.py ?I went back and ran it. I get a real quick flash of a cmd >> box running but that's it. > >Except for that raw_input method that Tim Wilson mentioned, you could also >open the program in PythonWin (as opposed to Notepad) and then run it from >there. The output will be (and will remain) visible inside PythonWin >itself. > >> So I guess my question should be. Does anyone know of a good website to go >> to learn this? > >Alan Gauld's tutorial is nice (as linked by John Purser), How To Think Like >A Computer Scientist in Python is nice too. Don't be fooled, by the name, >it's a beginner-level tutorial: http://www.ibiblio.org/obp/thinkCSpy/ > >There are many more (I particularly liked >http://www.hetland.org/python/instant-hacking.php, but it's down ATM of >this writing), but which one is the best for you, depends on your style of >learning. > >-- >Yours, > >Andrei > >===== >Real contact info (decode with rot13): >cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq >gur yvfg, fb gurer'f ab arrq gb PP. > > > > >------------------------------ > >Message: 2 >Date: Thu, 25 Mar 2004 01:46:37 +0530 >From: "G Kiran" <goki75@vsnl.net> >Subject: [Tutor] Re: How do I slice up a list of strings? >To: <tutor@python.org> >Message-ID: <001301c411dc$eeabcb90$4d2ee2dc@VULCAN> >Content-Type: text/plain; ? charset="iso-8859-1" > >>>> l=['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 >user2 \n','Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 >user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>>> l >['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 >\n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 >user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>>> a=[s[27:-2] for s in l] >>>> a >['user1', 'user2', 'user2', 'user3', 'user4'] > > >or > >>>> a=[s.strip().split()[-1] for s in l] >>>> a >['user1', 'user2', 'user2', 'user3', 'user4'] >>>> > > > >Beware of the lollipop of mediocrity: lick it once and you suck forever >www.mhowlinux.org- Helping Linux users in Mhow > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.624 / Virus Database: 401 - Release Date: 3/15/2004 > > > > >------------------------------ > >Message: 3 >Date: Wed, 24 Mar 2004 13:18:34 -0700 >From: "John Purser" <johnp@HomeLumber.com> >Subject: RE: [Tutor] usenet server quest >To: <tutor@python.org> >Message-ID: > ? ?<D0DD3F40FC3F714A88D0DB43BAE362565F0512@01-hl-prime.denver.homelmbr.com> > ? ? >Content-Type: text/plain; ? charset="iso-8859-1" > >Google = "nntp server", Python > >http://freshmeat.net/projects/papercut/ > >You might want to contribute to this existing project. > >John Purser > >-----Original Message----- >From: Kirk Bailey [mailto:idiot1@netzero.net] >Sent: Wednesday, March 24, 2004 1:13 PM >To: tutor@python.org >Subject: [Tutor] usenet server quest > > >OK, I want a usenet server. There is nothing in the library to >facilitate this, so it might turn into an entire nre module. > >To start with, it can be a single group. It should not be a hairpull to >install. And of course, written in python. > >Any discussion? > >-- > > >Respectfully, > ? ? ? ? ? ? ?Kirk D Bailey > ? ? ? ? ? ? ?Pinellas county Florida USA > > ? think ? http://www.tinylist.org/ - $FREE$ software for liberty >+-------+ http://www.pinellasintergroupsociety.org/ - In Her Service >| ?BOX ?| http://www.listville.net/ - $FREE$ list hosting services >+-------+ http://www.howlermonkey.net/ - $FREE$ email service > ? kniht ? http://www.sacredelectron.org/ - My personal SCREED pit > > ? ? ? ? ?(C)2004 Kirk D Bailey, all rights reserved- but ask! > > > > > > >_______________________________________________ >Tutor maillist ?- ?Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > >------------------------------ > >Message: 4 >Date: Thu, 25 Mar 2004 01:48:13 +0530 >From: "G Kiran" <goki75@vsnl.net> >Subject: [Tutor] Re: How do I slice up a list of strings? (John > ? ?Matthews) >To: <tutor@python.org> >Message-ID: <001e01c411dd$271bbb70$4d2ee2dc@VULCAN> >Content-Type: text/plain; ? charset="iso-8859-1" > > >>>> l=['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 >user2 \n','Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 >user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>>> l >['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34 user2 >\n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004 14:22:08.45 >user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n'] >>>> a=[s[27:-2] for s in l] >>>> a >['user1', 'user2', 'user2', 'user3', 'user4'] > > >or > >>>> a=[s.strip().split()[-1] for s in l] >>>> a >['user1', 'user2', 'user2', 'user3', 'user4'] >>>> > > > >Beware of the lollipop of mediocrity: lick it once and you suck forever >www.mhowlinux.org- Helping Linux users in Mhow > > > > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.624 / Virus Database: 401 - Release Date: 3/15/2004 > > > > >------------------------------ > >Message: 5 >Date: Wed, 24 Mar 2004 21:25:56 +0100 >From: Andrei <project5@redrival.net> >Subject: [Tutor] Re: write a file >To: tutor@python.org >Message-ID: <b4a67ddg3mz0$.1gpjh4rtzrv7g.dlg@40tude.net> >Content-Type: text/plain; charset="iso-8859-1" > >Karl Pfl?sterer wrote on Wed, 24 Mar 2004 20:52:38 +0100: > >>> I'm trying to open a file, read its content and write its content to a >>> new file. ?Pretty much like copying a file. ?Here is what I have >> >>> ======== >>> in = open ("a.txt", "r") >>> out = open ("b.txt", "w") >>> for line in in.readlines() >>> ? ?out.write(line) >> >>> in.close() >>> out.close() > >That code works?? Never gives stuff names that are already used by Python. >'in' is a kewyword used in e.g. 'for something in whatever', so you >shouldn't be able to name a file 'in'. It's also a bad idea to override >built-ins, like range, file or open - even though you don't do that in that >particular piece of code :). > >>> ========== >>> However, the output isn't as expected. ?There is additional empty line >>> comes after every existing line. ?So, the output file is bigger than >>> the original file. > >That might happen especially on Windows where lines end in '\r\n'. Let's >see if I get this right... '\n' gets expanded to '\r\n' as well and '\n' >means on its own that a new line is required, so you end up with an extra >empty line. The line ends are very pesky, because different platforms use >different line endings (on Linux lines end in \n, on Mac I believe in \r >and on Windows in both). > >I think that if you open the file with "rU" instead of "r" you might get >better results. (not available in Pythons older than 2.3) > >-- >Yours, > >Andrei > >===== >Real contact info (decode with rot13): >cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq >gur yvfg, fb gurer'f ab arrq gb PP. > > > > >------------------------------ > >Message: 6 >Date: Wed, 24 Mar 2004 16:02:30 -0500 >From: "R. Alan Monroe" <amonroe@columbus.rr.com> >Subject: [Tutor] pickle broken for strings in 2.3? >To: tutor@python.org >Message-ID: <181163728348.20040324160230@columbus.rr.com> >Content-Type: text/plain; charset=us-ascii > > > > >Python 2.3.2 (#49, Oct ?2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> x={1:2, 'a':'b'} >>>> import pickle >>>> pickle.dump(x, 'test.pik') >Traceback (most recent call last): > ?File "<stdin>", line 1, in ? > ?File "c:\python23\lib\pickle.py", line 1382, in dump > ? ?Pickler(file, protocol, bin).dump(obj) > ?File "c:\python23\lib\pickle.py", line 210, in __init__ > ? ?self.write = file.write >AttributeError: 'str' object has no attribute 'write' > > > > >------------------------------ > >Message: 7 >Date: Wed, 24 Mar 2004 13:01:45 -0800 (PST) >From: Tony Cappellini <tony@tcapp.com> >Subject: [Tutor] Re: Tutor Digest, Vol 1, Issue 2678 >To: <Doug.Gentry@comcast.net> >Cc: tutor@python.org >Message-ID: <20040324125738.M71236-100000@yamato.yamato.com> >Content-Type: TEXT/PLAIN; charset=US-ASCII > > >Doug > >One good place to start is at many of the Python Tutorials (google will >help you find them). Another good starting point for non-programmers is >http://www.python.org/topics/learn/non-prog.html > >A very good Online book (free) is Dive Into Python >(assumes some programming knowledge, but still a great place to learn >Python) >http://diveintopython.org/ > > >Of course- this list is an excellent resource too. It has been a big >help to me. > > > >Tony > > > > > > > >------------------------------ > >Message: 8 >Date: Wed, 24 Mar 2004 14:06:20 -0700 >From: "John Purser" <johnp@HomeLumber.com> >Subject: RE: [Tutor] pickle broken for strings in 2.3? >To: <tutor@python.org> >Message-ID: > ? ?<D0DD3F40FC3F714A88D0DB43BAE3625686D226@01-hl-prime.denver.homelmbr.com> > ? ? >Content-Type: text/plain; ? charset="iso-8859-1" > >You passed a file name to pickle, not an opened file object. ?So when pickle tried to "test.pik.write(x)" it couldn't do it because the string test.pik has no write method. >try: >f = file("test.pik", "w") >pickle.dump(x, f) > >and see if that works better. > >John Purser > >-----Original Message----- >From: R. Alan Monroe [mailto:amonroe@columbus.rr.com] >Sent: Wednesday, March 24, 2004 2:03 PM >To: tutor@python.org >Subject: [Tutor] pickle broken for strings in 2.3? > > > > > >Python 2.3.2 (#49, Oct ?2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> x={1:2, 'a':'b'} >>>> import pickle >>>> pickle.dump(x, 'test.pik') >Traceback (most recent call last): > ?File "<stdin>", line 1, in ? > ?File "c:\python23\lib\pickle.py", line 1382, in dump > ? ?Pickler(file, protocol, bin).dump(obj) > ?File "c:\python23\lib\pickle.py", line 210, in __init__ > ? ?self.write = file.write >AttributeError: 'str' object has no attribute 'write' > > >_______________________________________________ >Tutor maillist ?- ?Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > >------------------------------ > >Message: 9 >Date: Wed, 24 Mar 2004 16:09:46 -0500 >From: Allen Schmidt <aschmidt@fredericksburg.com> >Subject: [Tutor] Once again....HTTP Digest Authentication >To: tutor@python.org >Message-ID: <4061F91A.3020206@fredericksburg.com> >Content-Type: text/plain; charset=us-ascii; format=flowed > >Howdy folks, > >I did another google search on what I needed and danged if my original question months ago was what popped up. > >Back at it again and I need to know (examples, etc) how to call a URL that requires a userid and password using digest authentication to proceed with the request. > >I just need a tutor-simplisitic approach as to how to get started. > >How do I pass a URL so that I get 'asked' for the userid and pwd? Or how do I pass it all at once? I am just lost as to how to proceed. > >If someone might be able to help ?but feels this outside of tutor type answers, I am willing to PayPal you for your time. Just let me know. > >Thanks!!! > >Allen > > > > >------------------------------ > >Message: 10 >Date: Wed, 24 Mar 2004 14:20:31 -0700 >From: "John Purser" <johnp@HomeLumber.com> >Subject: RE: [Tutor] Once again....HTTP Digest Authentication >To: <tutor@python.org> >Message-ID: > ? ?<D0DD3F40FC3F714A88D0DB43BAE3625686D227@01-hl-prime.denver.homelmbr.com> > ? ? >Content-Type: text/plain; ? charset="iso-8859-1" > >Alan, > >Take a look at: >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267197 >There seems to be an example there that passes a username and password to a URL. > >I found it by Goggling = http, Python, username, password. ?Lots of other links listed as well. > >Good Luck, > >John Purser > >-----Original Message----- >From: Allen Schmidt [mailto:aschmidt@fredericksburg.com] >Sent: Wednesday, March 24, 2004 2:10 PM >To: tutor@python.org >Subject: [Tutor] Once again....HTTP Digest Authentication > > >Howdy folks, > >I did another google search on what I needed and danged if my original question months ago was what popped up. > >Back at it again and I need to know (examples, etc) how to call a URL that requires a userid and password using digest authentication to proceed with the request. > >I just need a tutor-simplisitic approach as to how to get started. > >How do I pass a URL so that I get 'asked' for the userid and pwd? Or how do I pass it all at once? I am just lost as to how to proceed. > >If someone might be able to help ?but feels this outside of tutor type answers, I am willing to PayPal you for your time. Just let me know. > >Thanks!!! > >Allen > > >_______________________________________________ >Tutor maillist ?- ?Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > >------------------------------ > >Message: 11 >Date: Wed, 24 Mar 2004 15:45:34 -0600 >From: "APQ LE" <apqle75@hotmail.com> >Subject: Re: [Tutor] write a file >To: tutor@python.org >Message-ID: <BAY16-F79NMjiGwYt7y00014a47@hotmail.com> >Content-Type: text/plain; format=flowed > >Thanks for all the responses. ?Here is what I have. > >OS: Win 2k >File: French context (French strings) >Encoding: Unicode > >----- >The output file that I got contains a bunch of question marks after every >strings that I have. ?For example, the original string is > >Le fichier local n'a pas pu ?tre cr??. > >output: >Le fichier local n'a pas pu ?tre cr??. >???????????????????????????????? > >~Megan > >>From: sigurd@12move.de (Karl Pfl?sterer) >>To: tutor@python.org >>Subject: Re: [Tutor] write a file >>Date: Wed, 24 Mar 2004 20:52:38 +0100 >> >>On 24 Mar 2004, APQ LE <- apqle75@hotmail.com wrote: >> >> > I'm trying to open a file, read its content and write its content to a >> > new file. ?Pretty much like copying a file. ?Here is what I have >> >> > ======== >> > in = open ("a.txt", "r") >> > out = open ("b.txt", "w") >> > for line in in.readlines() >> > ? ?out.write(line) >> >> > in.close() >> > out.close() >> >> > ========== >> > However, the output isn't as expected. ?There is additional empty line >> > comes after every existing line. ?So, the output file is bigger than >> > the original file. >> >>What OS are you working on? >> >>Furthermore the above code is overcomplicated; I assume you use a recent >>version of Python. ?Then you could write: >> >>inf = file('a.txt') >>out = file('b.txt', 'w') >>out.writelines(inf) >>out.close() >>inf.close() >> >>writelines() takes an iterator as argument: here the open file object. >> >> >> >> >> ? ?Karl >>-- >>Please do *not* send copies of replies to me. >>I read the list >> >> >>_______________________________________________ >>Tutor maillist ?- ?Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_________________________________________________________________ >MSN Toolbar provides one-click access to Hotmail from any Web page ? FREE >download! http://toolbar.msn.com/go/onm00200413ave/direct/01/ > > > > >------------------------------ > >Message: 12 >Date: Wed, 24 Mar 2004 15:51:47 -0600 >From: "APQ LE" <apqle75@hotmail.com> >Subject: RE: [Tutor] Re: write a file >To: tutor@python.org >Message-ID: <BAY16-F35LtosJ3Ih7j0001514b@hotmail.com> >Content-Type: text/plain; format=flowed > >'rU' works better, but not completely. ?Now, I get two trailing question >marks at the end of every line rather than an additional line with only >question marks. > >what is 'U'? > >thanks. > > >>From: Andrei <project5@redrival.net> >>To: tutor@python.org >>Subject: [Tutor] Re: write a file >>Date: Wed, 24 Mar 2004 21:25:56 +0100 >> >>Karl Pfl?sterer wrote on Wed, 24 Mar 2004 20:52:38 +0100: >> >> >> I'm trying to open a file, read its content and write its content to a >> >> new file. ?Pretty much like copying a file. ?Here is what I have >> > >> >> ======== >> >> in = open ("a.txt", "r") >> >> out = open ("b.txt", "w") >> >> for line in in.readlines() >> >> ? ?out.write(line) >> > >> >> in.close() >> >> out.close() >> >>That code works?? Never gives stuff names that are already used by Python. >>'in' is a kewyword used in e.g. 'for something in whatever', so you >>shouldn't be able to name a file 'in'. It's also a bad idea to override >>built-ins, like range, file or open - even though you don't do that in that >>particular piece of code :). > From isrgish at fastem.com Thu Mar 25 01:23:00 2004 From: isrgish at fastem.com (Isr Gish) Date: Thu Mar 25 01:22:48 2004 Subject: [Tutor] file.write() blocking Message-ID: <E1B6OGK-000561-1a@mail.python.org> What seems to be wrong here is, that you are using file.write() but you don't have a file object named file. (which anyway would be a bad idea). Your file object is called output_file, therefore you should do output_file.write("") -----Original Message----- >From: "Jonathan Hayward"<jsh47@cam.ac.uk> >Sent: 3/24/04 8:46:08 AM >To: "tutor@python.org"<tutor@python.org> >Subject: [Tutor] file.write() blocking > > def save_entry(self, text, filename): > debug_log("Reached 1") > debug_log(DOCUMENT_ROOT + "entries/" + filename) > output_file = file(DOCUMENT_ROOT + "entries/" + filename, "w") > debug_log("Reached 2") > #debug_log(text) > file.write("") > debug_log("Reached 2.5") > file.write(text) > debug_log("Reached 3") > file.close() > debug_log("Reached 4") > >When I get to this point in my code, it prints, "Reached 2" and hangs on >file.write(""). The output directory has a zero-byte file created. When >I try analogous test code from Python interactively, it works; does >anyone see the glitch in this? (The text is a small webpage.) > >-- >++ Jonathan Hayward, jonathan.hayward@pobox.com >** To see an award-winning website with stories, essays, artwork, >** games, and a four-dimensional maze, why not visit my home page? >** All of this is waiting for you at http://JonathansCorner.com > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Thu Mar 25 02:21:29 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Mar 25 02:21:10 2004 Subject: [Tutor] Another parsing question References: <think001_406217b4df9ac@webmail.thinkware.se> Message-ID: <013101c41239$cac46180$6401a8c0@xp> > Isn't it just that the serial port tries to behave like a file > object. That's fairly normal I think. So do most other byte > streams that are used in Python, and it's common to transfer > text over serial lines. Also, a serial port using RS-232 is set > up to send chunks of 7 or 8 bits, which fits 8 bit characters > better than integers which are 32 (or 64 if you're lucky) bits > wide. Behaving like a file is one thing, insisting on text is another. I think it might be the last point thats key, it needs to be an 8 bit unit so we need to convert the 32 bit int to 4 8 bit chunks. But normally thats handled by the IO routines... > I assume that you just send chr(x) where x is your 8 bit > unsigned integer, and to read, you call ord() on the > byte you read to convert it to an integer in the range > 0 to 255. Yep, thats what I thought initially, then realised thats chr() and ord() are just representational issues, its exactly the same bit pattern so why should the serial port care! > Files behave like this in Python. >>> f = file('c:/test.dat', 'wb') >>> f.write(65) > Traceback (most recent call last): > File "<pyshell#21>", line 1, in -toplevel- > f.write(65) >TypeError: argument 1 must be string or read-only buffer, not int Which raised alarm bells in my head because what do you do if the integer is bigger than 255, or its a float? Converting these to string format and back is horribly inefficient. That sent my off to the docs... where I rediscovered the struct module... To write an integer using struct we can do this: >>> import struct >>> f.write(struct.pack('i',42)) >>> f.close <built-in method close of file object at 0xa04ed60> >>> f.close() >>> f = file("bin.bin",'rb') >>> n = f.read() >>> n '*\x00\x00\x00' >>> i = struct.unpack('i',n) >>> print i (42,) >>> Its a messy intermediate step but at least you can write binary data to a file object. If you know the data is byte sized then using chr()/ord() will be the easiest route, if its bigger than a byte struct is the way to go. - I never thought I'd be wishing for C's ability to cast data types in Python!!! Alan G. From johnp at HomeLumber.com Thu Mar 25 10:34:22 2004 From: johnp at HomeLumber.com (John Purser) Date: Thu Mar 25 10:34:34 2004 Subject: [Tutor] file.write() blocking Message-ID: <D0DD3F40FC3F714A88D0DB43BAE362565F0513@01-hl-prime.denver.homelmbr.com> Well thanks for ruining my morning! I thought adding the '+' to a 'w' mode wouldn't truncate the file if it already existed. I was quite spectacularly wrong! You have to use 'r+' if you want to open an existing file and write to it without wiping out the original contents. Which is exactly what the python documentation says it will do. Damned tricky of them! There's also an 'a' mode for appending but apparently it's effects can vary with the operating system. John Purser -----Original Message----- From: Jonathan Hayward [mailto:jsh47@cam.ac.uk] Sent: Thursday, March 25, 2004 3:59 AM To: John Purser Subject: Re: [Tutor] file.write() blocking John Purser wrote: >I haven't played with the code but at a guess I'd say you were creating a new file every time you run this code. I think you want to change that "w" mode to "w+" > > > What's the exact difference between w and w+? >I've never tried to write a zero length string to a file and that could also be an issue. > >What platform and verison of Python are you using? > >John Purser > >-----Original Message----- >From: Jonathan Hayward [mailto:jsh47@cam.ac.uk] >Sent: Wednesday, March 24, 2004 6:46 AM >To: tutor@python.org >Subject: [Tutor] file.write() blocking > > > def save_entry(self, text, filename): > debug_log("Reached 1") > debug_log(DOCUMENT_ROOT + "entries/" + filename) > output_file = file(DOCUMENT_ROOT + "entries/" + filename, "w") > debug_log("Reached 2") > #debug_log(text) > file.write("") > debug_log("Reached 2.5") > file.write(text) > debug_log("Reached 3") > file.close() > debug_log("Reached 4") > >When I get to this point in my code, it prints, "Reached 2" and hangs on >file.write(""). The output directory has a zero-byte file created. When >I try analogous test code from Python interactively, it works; does >anyone see the glitch in this? (The text is a small webpage.) > > > -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From bgailer at alum.rpi.edu Thu Mar 25 11:07:56 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Mar 25 11:06:15 2004 Subject: [Tutor] python virgin In-Reply-To: <E1B6D7t-0005Vs-Ge@mail.python.org> References: <E1B6D7t-0005Vs-Ge@mail.python.org> Message-ID: <6.0.0.22.0.20040325090554.0381e988@mail.mric.net> <flame> A virgin is one who has not had sexual intercourse, or in other words, has not been f***ed. The sense of being a virgin with Python lasts longer than when working with M$soft "developer" tools! <\flame> Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From glingl at aon.at Thu Mar 25 11:56:08 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Mar 25 11:55:20 2004 Subject: [Tutor] exception details In-Reply-To: <Pine.LNX.4.44.0403241608260.9416-100000@Kuna> References: <Pine.LNX.4.44.0403241608260.9416-100000@Kuna> Message-ID: <40630F28.5030005@aon.at> Marilyn Davis schrieb: >Hi, > >I'm trying to get a strong handle on exception mechanism details. > >Note that there are three try/except's and that the 1st 2 work >fine. But the third one doesn't catch the random exception >generated. > >Do I have a typo? > >Thank you for any help you can give. > >Marilyn Davis > >#!/usr/bin/env python2.2 >'''Ways to get more info about your caught exception.''' > >import exceptions # to get a list of built-in exceptions >... > > try: > fun('''catch with "Exception, exception: on random exception doesn't work"''') > except Exception, exception: > > ########### here Exception has to be an expression that matches an exception ########### object that propagates from the try clause ########### in your code a string propagates from the try clause > print 'exception.args = ', exception.args > print 'exception = ', exception > so I converted this string to an exception object (maybe there is a better way doing this than using eval) and now it works: import exceptions # to get a list of built-in exceptions import random import sys # gives info -- you can use the traceback module but # it uses sys. def ok(msg): raise ValueError, msg def fun(msg): '''Raises a random built-in exception.''' excepts = dir(exceptions)[:-2] raise_this = random.choice(excepts) # a string raise_this = eval(raise_this) # an exception object print 'Raising', raise_this, 'To', msg raise raise_this, msg if __name__ == '__main__': try: ok('this works ok') except Exception, exception: print 'exception.args = ', exception.args print 'exception = ', exception print try: fun('catch with "except:" on random exception works') except: print 'Caught: sys.exc_type =', sys.exc_type,\ 'sys.exc_value =', sys.exc_value print 'sys.exc_traceback =', sys.exc_traceback print sys.exc_info() print try: fun('catch with "Exception, exception: on random exception does equally work"') except Exception, exception: print 'exception.args = ', exception.args print 'exception = ', exception Hope that gives you a clue (together with Python Docs, Library Reference 2.4) Gregor From marilyn at deliberate.com Thu Mar 25 12:09:43 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Mar 25 12:11:24 2004 Subject: [Tutor] exception details In-Reply-To: <40630F28.5030005@aon.at> Message-ID: <Pine.LNX.4.44.0403250908170.9416-100000@Kuna> YES! Thank you. That's it. Also, thank you for the reminder about random.choice! Whew. Lovely when things make sense again. Marilyn On Thu, 25 Mar 2004, Gregor Lingl wrote: > > > Marilyn Davis schrieb: > > >Hi, > > > >I'm trying to get a strong handle on exception mechanism details. > > > >Note that there are three try/except's and that the 1st 2 work > >fine. But the third one doesn't catch the random exception > >generated. > > > >Do I have a typo? > > > >Thank you for any help you can give. > > > >Marilyn Davis > > > >#!/usr/bin/env python2.2 > >'''Ways to get more info about your caught exception.''' > > > >import exceptions # to get a list of built-in exceptions > >... > > > > > try: > > fun('''catch with "Exception, exception: on random exception doesn't work"''') > > except Exception, exception: > > > > > ########### here Exception has to be an expression that matches an exception > ########### object that propagates from the try clause > ########### in your code a string propagates from the try clause > > > print 'exception.args = ', exception.args > > print 'exception = ', exception > > > so I converted this string to an exception object > (maybe there is a better way doing this than using eval) > and now it works: > > import exceptions # to get a list of built-in exceptions > import random > import sys # gives info -- you can use the traceback module but > # it uses sys. > > def ok(msg): > raise ValueError, msg > > def fun(msg): > '''Raises a random built-in exception.''' > excepts = dir(exceptions)[:-2] > raise_this = random.choice(excepts) # a string > raise_this = eval(raise_this) # an exception object > print 'Raising', raise_this, 'To', msg > raise raise_this, msg > > if __name__ == '__main__': > try: > ok('this works ok') > except Exception, exception: > print 'exception.args = ', exception.args > print 'exception = ', exception > print > > try: > fun('catch with "except:" on random exception works') > except: > print 'Caught: sys.exc_type =', sys.exc_type,\ > 'sys.exc_value =', sys.exc_value > print 'sys.exc_traceback =', sys.exc_traceback > print sys.exc_info() > print > > try: > fun('catch with "Exception, exception: on random exception does > equally work"') > except Exception, exception: > print 'exception.args = ', exception.args > print 'exception = ', exception > > > Hope that gives you a clue (together with Python Docs, Library Reference > 2.4) > Gregor > > -- From tpc at csua.berkeley.edu Thu Mar 25 17:15:23 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Mar 25 17:15:36 2004 Subject: [Tutor] Python time hour formatting Message-ID: <20040325141424.I10080-100000@localhost.name> hi everyone, quick question. I currently have this: time.strftime("%a %b %d, %Y %I:%M:%S %p",time.localtime(time.time())) to print out: 'Thu Mar 25, 2004 02:19:23 PM' However, I don't want a leading zero in the hour column if there is only one digit. Is there a way to do this: 'Thu Mar 25, 2004 2:19:23 PM' ? I already tried '%1I' to no avail. From eculpepper at hcc-care.com Thu Mar 25 17:23:49 2004 From: eculpepper at hcc-care.com (Eric Culpepper) Date: Thu Mar 25 17:20:20 2004 Subject: [Tutor] Python time hour formatting Message-ID: <48CA63C679F03D4187762B7CE066AAD2018DB143@hccexchange.hcccorp.hcc-care.com> Check the http://www.python.org/doc/current/lib/module-time.html document for the time module for all the different options for strftime.. but to directly answer your question you can use %H for 24 hour format, %I is for 12 hour format. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of tpc@csua.berkeley.edu Sent: Thursday, March 25, 2004 4:15 PM To: tutor@python.org Subject: [Tutor] Python time hour formatting hi everyone, quick question. I currently have this: time.strftime("%a %b %d, %Y %I:%M:%S %p",time.localtime(time.time())) to print out: 'Thu Mar 25, 2004 02:19:23 PM' However, I don't want a leading zero in the hour column if there is only one digit. Is there a way to do this: 'Thu Mar 25, 2004 2:19:23 PM' ? I already tried '%1I' to no avail. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From eculpepper at hcc-care.com Thu Mar 25 17:45:15 2004 From: eculpepper at hcc-care.com (Eric Culpepper) Date: Thu Mar 25 17:42:06 2004 Subject: [Tutor] Python time hour formatting Message-ID: <48CA63C679F03D4187762B7CE066AAD2018DB144@hccexchange.hcccorp.hcc-care.com> I re-read what I wrote and I realized that I didn't answer the question at all actually.. :) You can try to put a minus (-) between the % and I. I tried this in Linux and it works, but it did not work in Windows. Linux: >>> time.strftime("%a %b %d, %Y %-I:%M:%S %p",time.localtime(time.time())) 'Thu Mar 25, 2004 4:49:45 PM' Windows: >>> time.strftime("%a %b %d, %Y %-I:%M:%S %p",time.localtime(time.time())) 'Thu Mar 25, 2004 I:37:32 PM' Sorry about not paying attention the first time. :) -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Eric Culpepper Sent: Thursday, March 25, 2004 4:24 PM To: tutor@python.org Subject: RE: [Tutor] Python time hour formatting Check the http://www.python.org/doc/current/lib/module-time.html document for the time module for all the different options for strftime.. but to directly answer your question you can use %H for 24 hour format, %I is for 12 hour format. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of tpc@csua.berkeley.edu Sent: Thursday, March 25, 2004 4:15 PM To: tutor@python.org Subject: [Tutor] Python time hour formatting hi everyone, quick question. I currently have this: time.strftime("%a %b %d, %Y %I:%M:%S %p",time.localtime(time.time())) to print out: 'Thu Mar 25, 2004 02:19:23 PM' However, I don't want a leading zero in the hour column if there is only one digit. Is there a way to do this: 'Thu Mar 25, 2004 2:19:23 PM' ? I already tried '%1I' to no avail. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Thu Mar 25 18:58:47 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Mar 25 18:52:35 2004 Subject: [Tutor] Is this a job for zip(), or some other way? Message-ID: <174260704913.20040325185847@columbus.rr.com> Given: [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576), .... arbitrary n number of tuples in this list] I want to return: [ ['bob', 'mike', 'steve',... up to n elements], [24, 20, 30, .... n], [457, 4567, 576, .... n] ] I played around with zip and list comprehensions but I was too burnt out to get it, today. Any ideas? Alan From fredm at smartypantsco.com Thu Mar 25 19:11:32 2004 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Thu Mar 25 19:13:01 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <174260704913.20040325185847@columbus.rr.com> Message-ID: <5.1.0.14.0.20040326110815.035009b0@192.168.1.1> At 06:58 PM 25/03/04 -0500, R. Alan Monroe wrote: >Given: >[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576), .... >arbitrary n number of tuples in this list] > >I want to return: >[ ['bob', 'mike', 'steve',... up to n elements], > [24, 20, 30, .... n], > [457, 4567, 576, .... n] ] > >I played around with zip and list comprehensions but I was too burnt >out to get it, today. Any ideas? >Alan If you can be sure you always have the same format in the tuples, then list comprehension can do it, relatively easily: original = [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576),] result = [[a[0] for a in original], [a[1] for a in original], [a[2] for a in original]] print result [['bob', 'mike', 'steve'], [24, 20, 30], [457, 4567, 576]] (I don't know enough about zip to do it another way :) Hope this helps, Fred Milgrom From bgailer at alum.rpi.edu Thu Mar 25 19:16:18 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Mar 25 19:14:30 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <174260704913.20040325185847@columbus.rr.com> References: <174260704913.20040325185847@columbus.rr.com> Message-ID: <6.0.0.22.0.20040325171514.039ffe58@mail.mric.net> At 04:58 PM 3/25/2004, R. Alan Monroe wrote: >Given: >[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576), .... >arbitrary n number of tuples in this list] > >I want to return: >[ ['bob', 'mike', 'steve',... up to n elements], > [24, 20, 30, .... n], > [457, 4567, 576, .... n] ] > > >I played around with zip and list comprehensions but I was too burnt >out to get it, today. Any ideas? >>> apply(zip, [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) [('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From amonroe at columbus.rr.com Thu Mar 25 19:37:50 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Mar 25 19:31:31 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <6.0.0.22.0.20040325171514.039ffe58@mail.mric.net> References: <174260704913.20040325185847@columbus.rr.com> <6.0.0.22.0.20040325171514.039ffe58@mail.mric.net> Message-ID: <58263048063.20040325193750@columbus.rr.com> > >>> apply(zip, [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) > [('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] Slick, exactly what I had in mind. Alan From sigurd at 12move.de Thu Mar 25 19:45:09 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Thu Mar 25 19:51:36 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <58263048063.20040325193750@columbus.rr.com> (R. Alan Monroe's message of "Thu, 25 Mar 2004 19:37:50 -0500") References: <174260704913.20040325185847@columbus.rr.com> <6.0.0.22.0.20040325171514.039ffe58@mail.mric.net> <58263048063.20040325193750@columbus.rr.com> Message-ID: <m3wu58jv4a.fsf@hamster.pflaesterer.de> On 26 Mar 2004, R. Alan Monroe <- amonroe@columbus.rr.com wrote: >> >>> apply(zip, [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) >> [('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] > Slick, exactly what I had in mind. Or if you want to be really modern: >>> zip(* [('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) [('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] Karl -- Please do *not* send copies of replies to me. I read the list From glingl at aon.at Thu Mar 25 20:16:21 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Mar 25 20:15:42 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <6.0.0.22.0.20040325171514.039ffe58@mail.mric.net> References: <174260704913.20040325185847@columbus.rr.com> <6.0.0.22.0.20040325171514.039ffe58@mail.mric.net> Message-ID: <40638465.8090200@aon.at> Bob Gailer schrieb: > .... > >>> apply(zip, [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, > 576)]) > [('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] > > This works also: >>> zip(('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)) [('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] So in your case >>> zip(*[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) [('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] would also be appropriate. Gregor P.S.: *zip*( seq1, ...) This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences. At least one sequence is required, otherwise a TypeError is raised. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple argument sequences which are all of the same length, zip() is similar to map() with an initial argument of |None|. With a single sequence argument, it returns a list of 1-tuples. New in version 2.0. From bgailer at alum.rpi.edu Thu Mar 25 20:45:40 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Mar 25 20:44:32 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <40638465.8090200@aon.at> References: <174260704913.20040325185847@columbus.rr.com> <6.0.0.22.0.20040325171514.039ffe58@mail.mric.net> <40638465.8090200@aon.at> Message-ID: <6.0.0.22.0.20040325184350.03821c90@mail.mric.net> At 06:16 PM 3/25/2004, Gregor Lingl wrote: >Bob Gailer schrieb: > >>.... >> >>> apply(zip, [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) >>[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] >> >This works also: > > >>> zip(('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)) >[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] > >So in your case > > >>> zip(*[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) >[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] Yah, Ich habe geschrieben und Zie Zind correct. I was trying to remember the * approach, my head would not deliver it in time. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From marilyn at deliberate.com Thu Mar 25 21:52:47 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Mar 25 21:52:56 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <6.0.0.22.0.20040325184350.03821c90@mail.mric.net> Message-ID: <Pine.LNX.4.44.0403251848210.9416-100000@Kuna> On Thu, 25 Mar 2004, Bob Gailer wrote: > At 06:16 PM 3/25/2004, Gregor Lingl wrote: > > > >Bob Gailer schrieb: > > > >>.... > >> >>> apply(zip, [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) > >>[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] > >> > >This works also: > > > > >>> zip(('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)) > >[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] > > > >So in your case > > > > >>> zip(*[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) > >[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] > > Yah, Ich habe geschrieben und Zie Zind correct. I was trying to remember > the * approach, my head would not deliver it in time. What was gained with the *? Is it that if you have: L = [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)] You can then zip(*L) ? Or is there something else? Marilyn > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From amonroe at columbus.rr.com Fri Mar 26 08:52:47 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Mar 26 08:46:22 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <Pine.LNX.4.44.0403251848210.9416-100000@Kuna> References: <Pine.LNX.4.44.0403251848210.9416-100000@Kuna> Message-ID: <91310745488.20040326085247@columbus.rr.com> >> > >>> zip(*[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) >> >[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] > What was gained with the *? > Is it that if you have: > L = [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)] > You can then zip(*L) ? > Or is there something else? I'd like to know too how the * does what it does here. It works, but I can't tell WHY it works. Alan From glingl at aon.at Fri Mar 26 09:33:31 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Mar 26 09:32:40 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <91310745488.20040326085247@columbus.rr.com> References: <Pine.LNX.4.44.0403251848210.9416-100000@Kuna> <91310745488.20040326085247@columbus.rr.com> Message-ID: <40643F3B.6040407@aon.at> R. Alan Monroe schrieb: >>>>>>>zip(*[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) >>>>>>> >>>>>>> >>>>[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] >>>> >>>> > > > > >>What was gained with the *? >>Is it that if you have: >>L = [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)] >>You can then zip(*L) ? >>Or is there something else? >> >> > >I'd like to know too how the * does what it does here. It works, but I >can't tell WHY it works. > > > Hi all of you! In Python this sort of * is used in two ways, and actually in the above example it is also used in two ways: (1) use with starred parameters: >>> def startest(*args): ... print args ... >>> startest(1,2,3) (1, 2, 3) >>> startest(8,9,0,1,2) (8, 9, 0, 1, 2) >>> startest((8,9,0,1,2)) ((8, 9, 0, 1, 2),) this lets startest accept an arbitrary number of arguments, and indeed zip is just a function with a starred arg, so accepts an arbitrary number of lists as arguments. But if you insert a single sequence as argument, args becomes a one-element tuple whose only argument is this sequence. This is not needed here. In contrast to the former situation now we need to bind the elements of a single sequence to a given (or arbitrary) number of parameters. (This is a sort of sequence-unpacking to the parameters) (1) "given number of arguments" - example: >>> def sum3(a,b,c): ... print a, b, c ... return a+b+c ... >>> sum3(4,5,6) 4 5 6 15 >>> sum3( [4,5,6] ) Now we use a starred argument to bind the elements of a len-3-list to a,b,c: >>> def sum3(a,b,c): ... print a, b, c ... return a+b+c ... >>> sum3(4,5,6) 4 5 6 15 >>> sum3( [4,5,6] ) This also works with other types of sequences: >>> sum3( *(0,1,2) ) 0 1 2 3 >>> sum3( *'012' ) 0 1 2 '012' # ;-) >>> (2) "arbitrary number of arguments" -example: Suppose we have a function with a starred Parameter: >>> def mysum(*args): ... print args ... s = 0 ... for item in args: s+=item ... return s # needs Python 2.3 ... We can use it this way: >>> mysum(1,2,3,4,5) (1, 2, 3, 4, 5) 15 >>> mysum(1,2,3,4,5,7,8,9,10) (1, 2, 3, 4, 5, 7, 8, 9, 10) 49 But what if we have a list of numbers and wnat to know the sum (and we don't know that there is a built in sum in Python 2.3 ;-) ) >>> mysum(range(10)) ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],) Traceback (most recent call last): File "<interactive input>", line 1, in ? File "<interactive input>", line 4, in mysum TypeError: unsupported operand type(s) for +=: 'int' and 'list' because args now is a tuple containing one and only one list. But: >>> mysum(*range(10)) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 45 >>> Exactly the same thing happens with zip(*L) HTH, Gregor From tpc at csua.berkeley.edu Fri Mar 26 11:20:11 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Fri Mar 26 11:20:20 2004 Subject: [Tutor] Python time hour formatting In-Reply-To: <48CA63C679F03D4187762B7CE066AAD2018DB144@hccexchange.hcccorp.hcc-care.com> Message-ID: <20040326081259.C16723-100000@localhost.name> hi Eric, argh! You're right. What's frustrating is that I would like to implement this feature on a Window's machine, to print at the beginning of each error log entry. It works just fine in Linux as you say, but not at all in Windows. Arrgh I say ! On Thu, 25 Mar 2004, Eric Culpepper wrote: > > I re-read what I wrote and I realized that I didn't answer the question at all actually.. :) > > You can try to put a minus (-) between the % and I. I tried this in Linux and it works, but it did not work in Windows. > > > Linux: > >>> time.strftime("%a %b %d, %Y %-I:%M:%S %p",time.localtime(time.time())) > 'Thu Mar 25, 2004 4:49:45 PM' > > Windows: > >>> time.strftime("%a %b %d, %Y %-I:%M:%S %p",time.localtime(time.time())) > 'Thu Mar 25, 2004 I:37:32 PM' > > > Sorry about not paying attention the first time. :) > > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On > Behalf Of Eric Culpepper > Sent: Thursday, March 25, 2004 4:24 PM > To: tutor@python.org > Subject: RE: [Tutor] Python time hour formatting > > > > Check the http://www.python.org/doc/current/lib/module-time.html document for the time module for all the different options for strftime.. but to directly answer your question you can use %H for 24 hour format, %I is for 12 hour format. > > > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On > Behalf Of tpc@csua.berkeley.edu > Sent: Thursday, March 25, 2004 4:15 PM > To: tutor@python.org > Subject: [Tutor] Python time hour formatting > > > > > hi everyone, quick question. I currently have this: > > time.strftime("%a %b %d, %Y %I:%M:%S %p",time.localtime(time.time())) > > to print out: > > 'Thu Mar 25, 2004 02:19:23 PM' > > However, I don't want a leading zero in the hour column if > there is only one digit. Is there a way to do this: > > 'Thu Mar 25, 2004 2:19:23 PM' > > ? > > I already tried '%1I' to no avail. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Janssen at rz.uni-frankfurt.de Sat Mar 27 10:47:36 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sat Mar 27 10:47:44 2004 Subject: [Tutor] Python time hour formatting In-Reply-To: <20040326081259.C16723-100000@localhost.name> References: <20040326081259.C16723-100000@localhost.name> Message-ID: <Pine.A41.4.56.0403271638250.194560@hermes-22.rz.uni-frankfurt.de> On Fri, 26 Mar 2004 tpc@csua.berkeley.edu wrote: > argh! You're right. What's frustrating is that I would like to implement > this feature on a Window's machine, to print at the beginning of each > error log entry. BTW: having a leading 0 in log entries is a very good thing when it ever comes to automated loganalyzing. With leading zeros you can do things as easy as cutting off the time with just a slice: line[26:] Where this is especially usefull while analyzing the data on commandline it's allways not that bad to have a fixed-sized time format. Don't try to do it the same way as syslog - syslog's time format is broken in respect of missing leading 0 and missing year. Michael From flaxeater at yahoo.com Sat Mar 27 21:26:30 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Mar 27 21:26:35 2004 Subject: [Tutor] A de-aliaser for large projects. Message-ID: <20040328022630.30027.qmail@web11603.mail.yahoo.com> I've had this idea for a de-aliaser for large projects. In the past when if have tried to learn the sourcecode of a large project (in a specific case lyntin) I was counfounded by the aliasing of modules or functions. for example from FTP import * #now the namespace is the same. connect=blah blah so on and so fourth. If you are not intimatly aware of the module api's and names then it's easy to get lost. Especially if you are really only interested in one class in a large file. I propose making a program that will turn the above call to connection back to ftp.connection=blah blah So that one could more easily understand references to other modules or if the programer decided he wanted to change the name of a function previous to the item of interest. If there is already one of these please let me know. Other wise I would appreciate a little input on how I might use the introspection available to do this. I was thinking about using dir(). for modules maybe with type checking to see if dir shows reference to another class or what ever. In addition keeping a dictionary holding all assignments and then chekcing to see if one name really equals another. Thanks for your input. __________________________________ Do you Yahoo!? Yahoo! Finance Tax Center - File online. File on time. http://taxes.yahoo.com/filing.html From isrgish at fastem.com Sun Mar 28 01:48:29 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun Mar 28 01:49:24 2004 Subject: [Tutor] Is this a job for zip(), or some other way? Message-ID: <E1B7U6i-0002Hm-Fj@mail.python.org> Where does this * thing come from I don,t remmember seeing it in the docs. -----Original Message----- >From: "Bob Gailer"<bgailer@alum.rpi.edu> >Sent: 3/25/04 8:45:40 PM >To: "tutor@python.org"<tutor@python.org> >Subject: Re: [Tutor] Is this a job for zip(), or some other way? > >At 06:16 PM 3/25/2004, Gregor Lingl wrote: > > >>Bob Gailer schrieb: >> >>>.... >>> >>> apply(zip, [ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) >>>[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] >>> >>This works also: >> >> >>> zip(('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)) >>[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] >> >>So in your case >> >> >>> zip(*[ ('bob', 24, 457), ('mike', 20, 4567), ('steve', 30, 576)]) >>[('bob', 'mike', 'steve'), (24, 20, 30), (457, 4567, 576)] > >Yah, Ich habe geschrieben und Zie Zind correct. I was trying to remember >the * approach, my head would not deliver it in time. > >Bob Gailer >bgailer@alum.rpi.edu >303 442 2625 home >720 938 2625 cell > All the best Isr From kp8 at mac.com Sun Mar 28 03:28:30 2004 From: kp8 at mac.com (kevin parks) Date: Sun Mar 28 03:30:02 2004 Subject: [Tutor] iterating over sorted dictionary keys (this right?) Message-ID: <E4B4D03D-8091-11D8-82F4-003065555ABC@mac.com> hi. I'd like to check and see if i am on the right path and that i am understanding things. I have a hard time getting my head around dictionaries as Python is the first language that i have used that has them and as i result i almost always use lists... Still it is clear to me that dictionaries are helpful and sometimes have advantages so i am forcing myself to learn and use them. I need to iterate over a dictionary, but since my key is a time value, order matters. So i am trying to iterate over a sorted copy of my keys. I am guessing that i can no longer use the items method: for key, value in page02.items(): as i have now sorted my keys (is that right, or am i misunderstanding how items() works?) In any case i am getting (i think) the right thing by changing : print len(page02) line_num = 1 for key, value in page02.items(): print line_num,"\tKey = %s" %str(key), "\tValue = %s" %str(value) line_num = line_num + 1 # to mykeys = page02.keys() # first make a copy of the keys print '-+' * 26 print mykeys # print it and take a look print '-+' * 26 mykeys.sort() # now sort that copy in place print mykeys line_num = 1 # let's count our lines print '-+' * 26 # iterate over the sorted keys for key in mykeys: print line_num,"\tKey = %s" %str(key), "\tValue = %s" %str(page02[key]) line_num = line_num + 1 here is the whole ball of wax: #!/usr/bin/env python def test(): page02 = { (1,0) : [8, 3, 5, 4], (7,0) : [4, 3, 2, 2], (14,0) : [8, 3, 5, 4], (18,0) : [10, 2, 8, 7], (20,0) : [10, 0, 5, 7], (22,0) : [10, 2, 8, 7], (24,0) : [7, 9, 3, 8], # (25,0) : [5], # (27,0) : [0], (28,0) : [10, 0, 5, 7], (29,0) : [10, 11], (30,0) : [8, 3, 5, 4], (32,0) : [5, 0, 10, 7], (34,0) : [8, 3, 7, 9], (36,0) : [5, 4, 3, 1], (36,1) : [5, 4, 3, 1, 7], (37,0) : [0, 8, 2, 4, 9, 10, 1], (37,1) : [0, 8, 2, 4, 9, 10, 1, 6], (39,0) : [8, 10, 1, 9], (39,1) : [8, 10, 1, 9, 7], (41,0) : [2, 0, 3, 1], (41,1) : [2, 0, 3, 1, 6] } print len(page02) line_num = 1 for key, value in page02.items(): print line_num,"\tKey = %s" %str(key), "\tValue = %s" %str(value) line_num = line_num + 1 # -- ---- mykeys = page02.keys() # first make a copy of the keys print '-+' * 26 print mykeys # print it and take a look print '-+' * 26 mykeys.sort() # now sort that copy in place print mykeys line_num = 1 # let's count our lines print '-+' * 26 # iterate over the sorted keys for key in mykeys: print line_num,"\tKey = %s" %str(key), "\tValue = %s" %str(page02[key]) line_num = line_num + 1 # -- -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- if __name__ == "__main__": test() From magnus at thinkware.se Sun Mar 28 04:40:45 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Mar 28 04:40:29 2004 Subject: [Tutor] Where are Python classes being taught? In-Reply-To: <think001_406217b4df9ac@webmail.thinkware.se> Message-ID: <5.2.1.1.0.20040328113502.02e0edd0@www.thinkware.se> I'm trying to help finding places where Python is being taught in classes. I know of these places. Does anyone of you know of other places? Please let me know. >>Lewis & Clark State College, Idaho >>Capitol University, Ohio >>Wartburg College, Iowa >>Georgia Tech >>Mt Hood Community College >>Minnesota State at Bemidji >>Bryn Mawr College >>Morehead State, Kentucky >>Mississippi College >>Southeast Missouri State >>University of Florida >>Kalamazoo College >>University of Iowa >>Hampshire College >>Kent State >>University of Northern Colorado -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From marilyn at deliberate.com Sun Mar 28 09:23:16 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Mar 28 09:23:21 2004 Subject: [Tutor] Where are Python classes being taught? In-Reply-To: <5.2.1.1.0.20040328113502.02e0edd0@www.thinkware.se> Message-ID: <Pine.LNX.4.44.0403280622280.16516-100000@Kuna> University of California Santa Cruz Extension in Sunnyvale CA On Sun, 28 Mar 2004, Magnus Lyck? wrote: > I'm trying to help finding places where Python is being > taught in classes. I know of these places. Does anyone > of you know of other places? Please let me know. > > >>Lewis & Clark State College, Idaho > >>Capitol University, Ohio > >>Wartburg College, Iowa > >>Georgia Tech > >>Mt Hood Community College > >>Minnesota State at Bemidji > >>Bryn Mawr College > >>Morehead State, Kentucky > >>Mississippi College > >>Southeast Missouri State > >>University of Florida > >>Kalamazoo College > >>University of Iowa > >>Hampshire College > >>Kent State > >>University of Northern Colorado > > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From glingl at aon.at Sun Mar 28 12:51:51 2004 From: glingl at aon.at (Gregor Lingl) Date: Sun Mar 28 12:51:09 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <E1B7U6i-0002Hm-Fj@mail.python.org> References: <E1B7U6i-0002Hm-Fj@mail.python.org> Message-ID: <406710B7.6030502@aon.at> Isr Gish schrieb: >Where does this * thing come from I don,t remmember seeing it in the docs. > > > See Python Tutorial 4.7, especially 4.7.3 and 4.7.4 Gregor From sigurd at 12move.de Sun Mar 28 13:51:06 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Sun Mar 28 13:54:07 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <E1B7U6i-0002Hm-Fj@mail.python.org> (Isr Gish's message of "Sun, 28 Mar 2004 01:48:29 -0500") References: <E1B7U6i-0002Hm-Fj@mail.python.org> Message-ID: <m3r7vcrexh.fsf@hamster.pflaesterer.de> On 28 Mar 2004, Isr Gish <- isrgish@fastem.com wrote: > Where does this * thing come from I don,t remmember seeing it in the docs. You can find it e.g. in the Python library reference (section calls) ,---- | Calls | ----- | | A call calls a callable object (e.g., a function) with a possibly empty | series of arguments: | | `call `primary' "(" [`argument_list' [","]] ")"' | | `argument_list `positional_arguments' ["," `keyword_arguments']' | | ` ["," "*" `expression']' | | ` ["," "**" `expression']' | | ` | `keyword_arguments' ["," "*" `expression']' | | ` ["," "**" `expression']' | | ` | "*" `expression' ["," "**" `expression']' | | ` | "**" `expression'' | | `positional_arguments `expression' ("," `expression')*' | | `keyword_arguments `keyword_item' ("," `keyword_item')*' | | `keyword_item `identifier' "=" `expression'' | A trailing comma may be present after an argument list but does not | affect the semantics. | | [...] | | If the syntax `*expression' appears in the function call, `expression' | must evaluate to a sequence. Elements from this sequence are treated | as if they were additional positional arguments; if there are postional | arguments X1,...,XN , and `expression' evaluates to a sequence | Y1,...,YM, this is equivalent to a call with M+N positional arguments | X1,...,XN,Y1,...,YM. | | A consequence of this is that although the `*expression' syntax appears | _after_ any keyword arguments, it is processed _before_ the keyword | arguments (and the `**expression' argument, if any - see below). So: | | >>> def f(a, b): | ... print a, b | ... | >>> f(b=1, *(2,)) | 2 1 | >>> f(a=1, *(2,)) | Traceback (most recent call last): | File "<stdin>", line 1, in ? | TypeError: f() got multiple values for keyword argument 'a' | >>> f(1, *(2,)) | 1 2 `---- I see it as analogue to the definition of functions where something like def f(*args): pass means to collect all arguments in a tuple. Using that syntax in a call does the opposite (people who know Lisp may know that from macros where you can slice a sequence with `,@'). Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Sun Mar 28 14:06:02 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Sun Mar 28 14:09:06 2004 Subject: [Tutor] iterating over sorted dictionary keys (this right?) In-Reply-To: <E4B4D03D-8091-11D8-82F4-003065555ABC@mac.com> (kevin parks's message of "Sun, 28 Mar 2004 03:28:30 -0500") References: <E4B4D03D-8091-11D8-82F4-003065555ABC@mac.com> Message-ID: <m3n060re4h.fsf@hamster.pflaesterer.de> On 28 Mar 2004, kevin parks <- kp8@mac.com wrote: > I need to iterate over a dictionary, but since my key is a time value, > order matters. So i am trying to iterate over a sorted copy of my > keys. I am guessing that i can no longer use the items method: Right. > for key, value in page02.items(): > as i have now sorted my keys (is that right, or am i misunderstanding > how items() works?) No you are right. > In any case i am getting (i think) the right thing by changing : [...] > # to > mykeys = page02.keys() # first make a copy of the keys > print '-+' * 26 > print mykeys # print it and take a look > print '-+' * 26 > mykeys.sort() # now sort that copy in place > print mykeys > line_num = 1 # let's count our lines > print '-+' * 26 > # iterate over the sorted keys > for key in mykeys: > print line_num,"\tKey = %s" %str(key), "\tValue = %s" > %str(page02[key]) > line_num = line_num + 1 That's absolutely right. (the data structure looks now much cleaner). Karl -- Please do *not* send copies of replies to me. I read the list From glingl at aon.at Sun Mar 28 14:52:45 2004 From: glingl at aon.at (Gregor Lingl) Date: Sun Mar 28 14:51:53 2004 Subject: [Tutor] Is this a job for zip(), or some other way? In-Reply-To: <m3r7vcrexh.fsf@hamster.pflaesterer.de> References: <E1B7U6i-0002Hm-Fj@mail.python.org> <m3r7vcrexh.fsf@hamster.pflaesterer.de> Message-ID: <40672D0D.7080708@aon.at> > >I see it as analogue to the definition of functions where something >like > def f(*args): pass >means to collect all arguments in a tuple. Using that syntax in a call >does the opposite (people who know Lisp may know that from macros where >you can slice a sequence with `,@'). > > > > And people who know only Python may know that from sequence unpacking: >>> u,v,w="abc" >>> print u,v,w a b c >>> def fun(u,v,w): print u,v,w >>> fun(*"abc") a b c Right? Gregor > Karl > > From photonuv at kudos.net Sun Mar 28 16:52:24 2004 From: photonuv at kudos.net (Gerald Wann) Date: Sun Mar 28 16:50:41 2004 Subject: [Tutor] end execution programmatically? Message-ID: <6.0.1.1.1.20040328164948.01ad26c0@127.0.0.1> Hi - Is there any way (built-in function etc.) to end the execution of a .py script from inside the code; specifically with a try: except: error handler? Does the interpreter have to do it for you? I'm a relative newbie to Python, in case it's not obvious;-) Thanks. Jerry From mwagman at charter.net Sun Mar 28 16:54:51 2004 From: mwagman at charter.net (Mike Wagman) Date: Sun Mar 28 16:57:17 2004 Subject: [Tutor] end execution programmatically? In-Reply-To: <6.0.1.1.1.20040328164948.01ad26c0@127.0.0.1> References: <6.0.1.1.1.20040328164948.01ad26c0@127.0.0.1> Message-ID: <1080510891.4171.0.camel@66-168-61-47.jvl.wi.charter.com> sys.exit() On Sun, 2004-03-28 at 15:52, Gerald Wann wrote: > Hi - > > Is there any way (built-in function etc.) to end the execution of a .py > script from inside the code; specifically with a try: except: error > handler? Does the interpreter have to do it for you? I'm a relative newbie > to Python, in case it's not obvious;-) > > Thanks. > > Jerry > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From isrgish at fastem.com Sun Mar 28 18:00:09 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun Mar 28 18:00:25 2004 Subject: [Tutor] Is this a job for zip(), or some other way? Message-ID: <E1B7jGP-0000pM-A3@mail.python.org> Thanks Karl All the best Isr From cspears2002 at yahoo.com Sun Mar 28 21:56:37 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sun Mar 28 21:56:41 2004 Subject: [Tutor] converting an integer to a string Message-ID: <20040329025637.32315.qmail@web12407.mail.yahoo.com> Is there some function that will convert an integer into a string? For example, x = 4 will become x = '4'. From gustabares at verizon.net Sun Mar 28 22:06:02 2004 From: gustabares at verizon.net (Gus Tabares) Date: Sun Mar 28 22:06:03 2004 Subject: [Tutor] converting an integer to a string In-Reply-To: <20040329025637.32315.qmail@web12407.mail.yahoo.com> References: <20040329025637.32315.qmail@web12407.mail.yahoo.com> Message-ID: <200403282206.02459.gustabares@verizon.net> On Sunday 28 March 2004 21:56, Christopher Spears wrote: > Is there some function that will convert an integer > into a string? For example, x = 4 will become x = '4'. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor >>> num = 3 >>> str(num) '3' >>> Good luck. -- Gus Tabares From kp8 at mac.com Mon Mar 29 03:13:54 2004 From: kp8 at mac.com (kevin parks) Date: Mon Mar 29 03:15:26 2004 Subject: [Tutor] histogram type thingy for dict items Message-ID: <04D29EB3-8159-11D8-8F55-003065555ABC@mac.com> Hi all... Me again... *^-^* ... i'll try to make this the last one for a while. I've been at it pretty hard and one more important question. As you know.. :] i have been mucking with a lot of data in a dictionary that looks like: page08 = { (287, 0) : [0, 7], (287, 1) : [0, 7, 2], (288, 0) : [ 3, 8 ], (288, 1) : [ 3, 8, 6 ], (291, 0) : [ 3, 7 ], (291, 1) : [ 6, 3, 7 ], (292, 0) : [ 3, 7 ], (293, 0) : [0, 7], (294, 0) : [ 3, 8 ], (295, 0) : [ 3, 4 ], (295, 1) : [0, 7], } pages and pages of it. The tuple represents a point time and the lists are my values for that time. It happens that there are many times that have the same data values [the list items are the same]... what i want to do now is take each unique value list (there are only 57 of them as my unique.py mod reports) and tell me where they occur so that (just looking at that little slice above) i would get (hope i don't mess thus up): [0, 7] --> (287, 0), (293, 0), (295, 1) [0, 7, 2] --> (287, 1) [ 3, 8 ] --> (288, 0), (294, 0) [ 3, 8, 6 ] --> (288, 1) [ 3, 7 ] --> (291, 0), (292, 0) [ 6, 3, 7] --> (291,1) [ 3, 4 ] --> (295, 0) I other words i want a sort of histogram of each unique event telling me at what key they happen and how many of each unique event there is. Now... I know that i used to have a magic little piece of code that does that very thing ... and i am pretty sure that it was Danny Yoo that help me with that, or posted it, wonderfully commented, to the list. I save all kind of things from this list! But not too long ago i lost everything when my hard drive gave out and not all my python stuff was backed up. i've searched http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor and the cookbook and i don't see anything and a google turns up some crazy incomprehensible very advanced bells and whistles graphic things that just is a heck of a lot more than i can wrap my pea sized brain around and is just way more than i need. So, if anyone has such a beast or wants to help me get started i would be grateful. To be honest i am kind of sending this in desperation *^-^* (no it's not for homework) incidentally there used to be a humongous mbox file of the entire tutor list archive that you could grep, is that gone? cheers, kevin From clavezza at hotmail.com Mon Mar 29 09:48:05 2004 From: clavezza at hotmail.com (christopher lavezza) Date: Mon Mar 29 09:48:09 2004 Subject: [Tutor] Taking an online class about object oriented programming using Python Message-ID: <BAY8-F43qunLOyDc41W00014dd3@hotmail.com> Dear Tutor, I am taking an online class through Tourou University International dealing with Python programming. I have no previous experience with computer programming and when I looked over the assignments and trying out the tutorials. I am lost already. Can anyone help me out by calling me to walk me through each assignments. This class is an core requirement for my degree plan. I am very desperate in finding help. I am willing to pay someone to tutor me through this course. Thank You Chris Lavezza 580-354-9408 home 580-442-5640 work _________________________________________________________________ All the action. All the drama. Get NCAA hoops coverage at MSN Sports by ESPN. http://msn.espn.go.com/index.html?partnersite=espn From johnp at HomeLumber.com Mon Mar 29 09:59:44 2004 From: johnp at HomeLumber.com (John Purser) Date: Mon Mar 29 09:59:52 2004 Subject: [Tutor] Taking an online class about object oriented programming using Python Message-ID: <D0DD3F40FC3F714A88D0DB43BAE362565F0515@01-hl-prime.denver.homelmbr.com> Chris, You'll probably get plenty of help from this forum just by asking reasonably clear questions about specific topics. Post your platform (Windows, Linux, unix, Mac, etc.) and the version of Python you're using. And put a good subject on your letters so we have some clue what you want to know about. There are also a lot of online resources that can get you up and running. If you installed Linux on your computer you should have a copy of the Python Tutorial. It's available online at: http://www.python.org/doc/current/tut/tut.html Here's another link to a How-To for non-programmers: http://www.freenetpages.co.uk/hp/alan.gauld/ I think you'll find Python very easy to learn as long as you take it one step at a time. Welcome to the list and start asking questions. John Purser -----Original Message----- From: christopher lavezza [mailto:clavezza@hotmail.com] Sent: Monday, March 29, 2004 7:48 AM To: tutor@python.org Subject: [Tutor] Taking an online class about object oriented programmingusing Python Dear Tutor, I am taking an online class through Tourou University International dealing with Python programming. I have no previous experience with computer programming and when I looked over the assignments and trying out the tutorials. I am lost already. Can anyone help me out by calling me to walk me through each assignments. This class is an core requirement for my degree plan. I am very desperate in finding help. I am willing to pay someone to tutor me through this course. Thank You Chris Lavezza 580-354-9408 home 580-442-5640 work _________________________________________________________________ All the action. All the drama. Get NCAA hoops coverage at MSN Sports by ESPN. http://msn.espn.go.com/index.html?partnersite=espn _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From tpc at csua.berkeley.edu Mon Mar 29 10:28:30 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon Mar 29 10:28:42 2004 Subject: [Tutor] Taking an online class about object oriented programming using Python In-Reply-To: <BAY8-F43qunLOyDc41W00014dd3@hotmail.com> Message-ID: <20040329072634.I44881-100000@localhost.name> hi Chris, you might consider one of the many Linux users groups out in your area: http://www.ssc.com:8080/glue/groups/us/oklahoma I hope that helps you. On Mon, 29 Mar 2004, christopher lavezza wrote: > Dear Tutor, > > I am taking an online class through Tourou University International dealing > with Python programming. I have no previous experience with computer > programming and when I looked over the assignments and trying out the > tutorials. I am lost already. Can anyone help me out by calling me to walk > me through each assignments. This class is an core requirement for my > degree plan. I am very desperate in finding help. I am willing to pay > someone to tutor me through this course. > > > Thank You > > Chris Lavezza > > 580-354-9408 home > 580-442-5640 work > > _________________________________________________________________ > All the action. All the drama. Get NCAA hoops coverage at MSN Sports by > ESPN. http://msn.espn.go.com/index.html?partnersite=espn > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From johnp at HomeLumber.com Mon Mar 29 10:38:10 2004 From: johnp at HomeLumber.com (John Purser) Date: Mon Mar 29 10:38:20 2004 Subject: [Tutor] histogram type thingy for dict items Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D241@01-hl-prime.denver.homelmbr.com> Kevin, I didn't see the original post but I think this is pretty straight forward and works on windows, Python 2.3. p = { (287, 0) : [0, 7],(287, 1) : [0, 7, 2],(288, 0) : [ 3, 8 ],(288, 1) : [ 3, 8, 6 ],(291, 0) : [ 3, 7 ],(291, 1) : [ 6, 3, 7 ],(292, 0) : [ 3, 7 ],(293, 0) : [0, 7],(294, 0) : [ 3, 8 ],(295, 0) : [ 3, 4 ],(295, 1) : [0, 7] } >>> n = {} >>> for key in p.keys(): ... try: ... n[tuple(p[key])].append(key) ... except KeyError: ... n[tuple(p[key])] = [key] ... >>> n {(3, 7): [(291, 0), (292, 0)], (3, 4): [(295, 0)], (3, 8): [(294, 0), (288, 0)], (0, 7, 2): [(287, 1)], (0, 7): [(287, 0), (295, 1), (293, 0)], (3, 8, 6): [(288, 1)], (6, 3, 7): [(291, 1)]} John Purser -----Original Message----- From: kevin parks [mailto:kp8@mac.com] Sent: Monday, March 29, 2004 1:14 AM To: tutor@python.org Subject: [Tutor] histogram type thingy for dict items Hi all... Me again... *^-^* ... i'll try to make this the last one for a while. I've been at it pretty hard and one more important question. As you know.. :] i have been mucking with a lot of data in a dictionary that looks like: page08 = { (287, 0) : [0, 7], (287, 1) : [0, 7, 2], (288, 0) : [ 3, 8 ], (288, 1) : [ 3, 8, 6 ], (291, 0) : [ 3, 7 ], (291, 1) : [ 6, 3, 7 ], (292, 0) : [ 3, 7 ], (293, 0) : [0, 7], (294, 0) : [ 3, 8 ], (295, 0) : [ 3, 4 ], (295, 1) : [0, 7], } pages and pages of it. The tuple represents a point time and the lists are my values for that time. It happens that there are many times that have the same data values [the list items are the same]... what i want to do now is take each unique value list (there are only 57 of them as my unique.py mod reports) and tell me where they occur so that (just looking at that little slice above) i would get (hope i don't mess thus up): [0, 7] --> (287, 0), (293, 0), (295, 1) [0, 7, 2] --> (287, 1) [ 3, 8 ] --> (288, 0), (294, 0) [ 3, 8, 6 ] --> (288, 1) [ 3, 7 ] --> (291, 0), (292, 0) [ 6, 3, 7] --> (291,1) [ 3, 4 ] --> (295, 0) I other words i want a sort of histogram of each unique event telling me at what key they happen and how many of each unique event there is. Now... I know that i used to have a magic little piece of code that does that very thing ... and i am pretty sure that it was Danny Yoo that help me with that, or posted it, wonderfully commented, to the list. I save all kind of things from this list! But not too long ago i lost everything when my hard drive gave out and not all my python stuff was backed up. i've searched http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor and the cookbook and i don't see anything and a google turns up some crazy incomprehensible very advanced bells and whistles graphic things that just is a heck of a lot more than i can wrap my pea sized brain around and is just way more than i need. So, if anyone has such a beast or wants to help me get started i would be grateful. To be honest i am kind of sending this in desperation *^-^* (no it's not for homework) incidentally there used to be a humongous mbox file of the entire tutor list archive that you could grep, is that gone? cheers, kevin _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From Doug.Shawhan at ge.com Mon Mar 29 11:20:17 2004 From: Doug.Shawhan at ge.com (Shawhan, Doug (EM, ITS)) Date: Mon Mar 29 11:22:50 2004 Subject: [Tutor] string.replace() question Message-ID: <CE88C8D948CCBE4EB0104ACDC79F299ED96087@CINMLVEM04.e2k.ad.ge.com> I have a need to replace charachters *after* a certain point in a string: To wit: "c:\\tmp\\howdy\joe\howdy\moe" becomes "c:\\tmp\\howdy\\joe\\howdy\\moe" is it possible somehow to use bitwise operations in string.replace()? Something along the lines of: addrbook=string.replace(addrbook,"\\","\\\\",[skip first two instances]) Thanks! d From dyoo at hkn.eecs.berkeley.edu Mon Mar 29 13:37:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 29 13:37:41 2004 Subject: [Tutor] string.replace() question [lookahead/lookbehind] In-Reply-To: <CE88C8D948CCBE4EB0104ACDC79F299ED96087@CINMLVEM04.e2k.ad.ge.com> Message-ID: <Pine.LNX.4.44.0403291028010.24584-100000@hkn.eecs.berkeley.edu> On Mon, 29 Mar 2004, Shawhan, Doug (EM, ITS) wrote: > > I have a need to replace charachters *after* a certain point in a string: > > To wit: > > "c:\\tmp\\howdy\joe\howdy\moe" > becomes > "c:\\tmp\\howdy\\joe\\howdy\\moe" > > is it possible somehow to use bitwise operations in string.replace()? > > Something along the lines of: > addrbook=string.replace(addrbook,"\\","\\\\",[skip first two instances]) Hi Doug, Question: why do you want to skip the first two instances? Is it because the blackslashes are already doubled up there? If so, you can write a regular expression that detects the standalone backslashes, by using 'lookbehind' and 'lookahead' assertions. Here's a small example: ### >>> import re >>> regex = re.compile(r"""(?<!0) ## negative lookbehind for zero ... 0 ... (?!0) ## negative lookahead for zero ... """, re.VERBOSE) >>> regex.sub('1', '0 000 0 00 0 0') '1 000 1 00 1 1' ### Here, we use negative lookbehind and negative lookahead to make sure we're only matching against solo zeros. By pairing those two assertions around the zero, we make sure here that there are no other zeros that surround that zero. Hmmm... well, it made more sense when I wrote the code. *grin* See: http://www.python.org/doc/lib/re-syntax.html for more details about the (?<!...) and (?!...) regular expression patterns. Of course, there are other ways of doing similar things. That's the joy and torment in regular expressions. Hope this helps! From kp8 at mac.com Mon Mar 29 16:16:39 2004 From: kp8 at mac.com (kevin parks) Date: Mon Mar 29 16:18:16 2004 Subject: [Tutor] histogram type thingy for dict items In-Reply-To: <E1B80DS-0004df-RR@mail.python.org> Message-ID: <5E494C92-81C6-11D8-98A7-003065555ABC@mac.com> John Purser (& co.) This is wonderful. It has certainly put me on the right path and i am getting quite a lot of my code to work, but only one problem, the output gives me several different entries for what is the same input set set so that not all my time value pairs are accounted for properly. Ideally all the keys (locations/times) that fit the same values would be grouped together so that the input of: foo = { (5, 138, 1) : [ 0, 2, 7 ], (7, 264, 1) : [ 0, 2, 7 ], (9, 367, 0) : [ 0, 2, 7 ], [(5, 156, 1) : [ 0, 7, 2 ], (8, 315, 1) : [ 0, 7, 2 ], (8, 317, 1) : [ 0, 7, 2 ] } would give me the unique sorted value with all the applicable locations. set (value of dict input) -- > all locations (0, 2, 7) --> [(7, 264, 1), (5, 138, 1), (5, 156, 1), ,(8, 315, 1), (8, 317, 1), (9, 367, 0)] instead i get some locations listed for set (0, 2, 7) # even though the output is a tuple this is actually the list (value) part of the input dictionary (0, 7, 2) # i am getting locations (2, 0, 7) # and times for all of these (2, 7, 0) # but they are really the same set. (7, 0, 2) # some how i need to tell python that this! i know that if it was i list on input i can do this: # Now sort each individual set, but we don't want to have dupl. elements either so we call unique here too for each_event2 in all_events2: ndupes = unique(each_event2) ndupes.sort() outlist.append(ndupes) # find only the unique sets unique_items = unique(outlist) unique_item_count = 1 but i am not sure how to handle this in the dictionary scenario. > ---------------------------------------------------------------------- > > > Message: 2 > Date: Mon, 29 Mar 2004 08:38:10 -0700 > From: "John Purser" <johnp@HomeLumber.com> > Subject: RE: [Tutor] histogram type thingy for dict items > To: "kevin parks" <kp8@mac.com>, <tutor@python.org> > Message-ID: > <D0DD3F40FC3F714A88D0DB43BAE3625686D241@01-hl- > prime.denver.homelmbr.com> > > Content-Type: text/plain; charset="iso-8859-1" > > Kevin, > > I didn't see the original post but I think this is pretty straight > forward and works on windows, Python 2.3. > > p = { (287, 0) : [0, 7],(287, 1) : [0, 7, 2],(288, 0) : [ 3, 8 ],(288, > 1) : [ 3, 8, 6 ],(291, 0) : [ 3, 7 ],(291, 1) : [ 6, 3, 7 ],(292, 0) : > [ 3, 7 ],(293, 0) : [0, 7],(294, 0) : [ 3, 8 ],(295, 0) : [ 3, 4 > ],(295, 1) : [0, 7] } >>>> n = {} >>>> for key in p.keys(): > ... try: > ... n[tuple(p[key])].append(key) > ... except KeyError: > ... n[tuple(p[key])] = [key] > ... >>>> n > {(3, 7): [(291, 0), (292, 0)], (3, 4): [(295, 0)], (3, 8): [(294, 0), > (288, 0)], (0, 7, 2): [(287, 1)], (0, 7): [(287, 0), (295, 1), (293, > 0)], (3, 8, 6): [(288, 1)], (6, 3, 7): [(291, 1)]} > > John Purser > > -----Original Message----- > From: kevin parks [mailto:kp8@mac.com] > Sent: Monday, March 29, 2004 1:14 AM > To: tutor@python.org > Subject: [Tutor] histogram type thingy for dict items > > > Hi all... Me again... *^-^* ... i'll try to make this the last one for > a while. I've been at it pretty > hard and one more important question. > > As you know.. :] i have been mucking with a lot of data in a dictionary > that looks like: > > > page08 = { (287, 0) : [0, 7], > (287, 1) : [0, 7, 2], > (288, 0) : [ 3, 8 ], > (288, 1) : [ 3, 8, 6 ], > (291, 0) : [ 3, 7 ], > (291, 1) : [ 6, 3, 7 ], > (292, 0) : [ 3, 7 ], > (293, 0) : [0, 7], > (294, 0) : [ 3, 8 ], > (295, 0) : [ 3, 4 ], > (295, 1) : [0, 7], > } > > pages and pages of it. The tuple represents a point time and the lists > are my values for that time. It happens > that there are many times that have the same data values [the list > items are the same]... what i want to do > now is take each unique value list (there are only 57 of them as my > unique.py mod reports) and tell me > where they occur so that (just looking at that little slice above) i > would get (hope i don't mess thus up): > > [0, 7] --> (287, 0), (293, 0), (295, 1) > [0, 7, 2] --> (287, 1) > [ 3, 8 ] --> (288, 0), (294, 0) > [ 3, 8, 6 ] --> (288, 1) > [ 3, 7 ] --> (291, 0), (292, 0) > [ 6, 3, 7] --> (291,1) > [ 3, 4 ] --> (295, 0) > > > I other words i want a sort of histogram of each unique event telling > me at what key they happen > and how many of each unique event there is. > > Now... I know that i used to have a magic little piece of code that > does that very thing ... and i am pretty sure > that it was Danny Yoo that help me with that, or posted it, wonderfully > commented, to the list. I save all kind > of things from this list! But not too long ago i lost everything when > my hard drive gave out and not all > my python stuff was backed up. > > i've searched > http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor and > the cookbook > and i don't see anything and a google turns up some crazy > incomprehensible very advanced bells and > whistles graphic things that just is a heck of a lot more than i can > wrap my pea sized brain around and is > just way more than i need. > > So, if anyone has such a beast or wants to help me get started i would > be grateful. To be honest i am > kind of sending this in desperation *^-^* (no it's not for homework) > > incidentally there used to be a humongous mbox file of the entire tutor > list archive that you could grep, > is that gone? > > cheers, > kevin From lum.sau.fong at undp.org Mon Mar 29 18:31:40 2004 From: lum.sau.fong at undp.org (Lum Sau Fong) Date: Mon Mar 29 18:25:03 2004 Subject: [Tutor] forum Message-ID: <000001c415e5$fd210430$cc00a8c0@LumSauFong> 1. no doubt Python appears to be a programming language which uses "normal" English language, instructions on its usage is still too technical for a beginner. 2. documentation found on the Help within the Python GUI does not provide the help needed, from a beginner's point of view. 3. it has been fun using Python, and it is exciting when the simple programme worked! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040330/83698535/attachment.html From Jan.Wilhelmsen at bilia.no Tue Mar 30 06:05:42 2004 From: Jan.Wilhelmsen at bilia.no (Wilhelmsen Jan) Date: Tue Mar 30 06:14:02 2004 Subject: [Tutor] Python and Active directory Message-ID: <9DB3344EC407D311A0A500508B0963E402AF0E6D@bilia.net> Hi! Is there any module or other ways of extracting/listing/modifying users/person account information from Active directory? If there is? Where can I find information about this? I need to make a script that exports all users in all OU's to a formatted textfile. Thanks! Jan Wilhelmsen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040330/cc22467c/attachment.html From amonroe at columbus.rr.com Tue Mar 30 06:48:10 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 30 06:41:17 2004 Subject: [Tutor] Python and Active directory In-Reply-To: <9DB3344EC407D311A0A500508B0963E402AF0E6D@bilia.net> References: <9DB3344EC407D311A0A500508B0963E402AF0E6D@bilia.net> Message-ID: <77648868153.20040330064810@columbus.rr.com> > Is there any module or other ways of extracting/listing/modifying > users/person account information from Active directory? > If there is? Where can I find information about this? > I need to make a script that exports all users in all OU's to a formatted > textfile. While we're at it, I could really use one that listed all folders on a server and which users have been given rights to each of them. How similar would that be to the first request, above? Alan From jmpurser at comcast.net Tue Mar 30 06:59:10 2004 From: jmpurser at comcast.net (John M. Purser) Date: Tue Mar 30 06:59:02 2004 Subject: [Tutor] Python and Active directory In-Reply-To: <77648868153.20040330064810@columbus.rr.com> Message-ID: <KPEHKAGJNANNKCCCIIGPKELGDGAD.jmpurser@comcast.net> You might want to take a look at the windows help file for "Command Reference". Specifically the "Net User" command and "Net Group". Have your python script attach to the output of these commands and work with the string it creates. There's also the windows scripting host, about which I know very little, but which may offer much more functionality than these command.com options. For permissions, assuming we're talking windows look at the Cacls command which "Displays or modifies access control lists (ACLs) of files." On Unix you can do the same thing with ls -al and parse the result. John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of R. Alan Monroe Sent: Tuesday, March 30, 2004 4:48 AM To: tutor-bounces@python.org; Wilhelmsen Jan Cc: tutor@python.org Subject: Re: [Tutor] Python and Active directory > Is there any module or other ways of extracting/listing/modifying > users/person account information from Active directory? > If there is? Where can I find information about this? > I need to make a script that exports all users in all OU's to a formatted > textfile. While we're at it, I could really use one that listed all folders on a server and which users have been given rights to each of them. How similar would that be to the first request, above? Alan _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From melis at uni-muenster.de Tue Mar 30 09:07:03 2004 From: melis at uni-muenster.de (Udo Melis) Date: Tue Mar 30 09:07:01 2004 Subject: [Tutor] starting script from within VIM Message-ID: <40697F07.5090706@uni-muenster.de> I cannot find any information on the web ;-( How can i start the script i am editing in VIM. I have compiled vim with python support and installed vim-python. I tried :make etc. but nothing works. THX in advance! From johnp at HomeLumber.com Tue Mar 30 09:10:51 2004 From: johnp at HomeLumber.com (John Purser) Date: Tue Mar 30 09:11:16 2004 Subject: [Tutor] starting script from within VIM Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D256@01-hl-prime.denver.homelmbr.com> Just started doing this myself and man is it slick. <ESC>!python script.py On windows this opens up a command prompt, runs the code (GUI or terminal), and leaves the window open so you can see what happened. Two returns and you're back in Vim editing away. I love it! John Purser -----Original Message----- From: Udo Melis [mailto:melis@uni-muenster.de] Sent: Tuesday, March 30, 2004 7:07 AM To: tutor@python.org Subject: [Tutor] starting script from within VIM I cannot find any information on the web ;-( How can i start the script i am editing in VIM. I have compiled vim with python support and installed vim-python. I tried :make etc. but nothing works. THX in advance! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From johnp at HomeLumber.com Tue Mar 30 09:13:19 2004 From: johnp at HomeLumber.com (John Purser) Date: Tue Mar 30 09:13:45 2004 Subject: [Tutor] starting script from within VIM Message-ID: <D0DD3F40FC3F714A88D0DB43BAE3625686D257@01-hl-prime.denver.homelmbr.com> Sorry, that's: <ESC>:!python script.py -----Original Message----- From: John Purser Sent: Tuesday, March 30, 2004 7:11 AM To: Udo Melis; tutor@python.org Subject: RE: [Tutor] starting script from within VIM Just started doing this myself and man is it slick. <ESC>!python script.py On windows this opens up a command prompt, runs the code (GUI or terminal), and leaves the window open so you can see what happened. Two returns and you're back in Vim editing away. I love it! John Purser -----Original Message----- From: Udo Melis [mailto:melis@uni-muenster.de] Sent: Tuesday, March 30, 2004 7:07 AM To: tutor@python.org Subject: [Tutor] starting script from within VIM I cannot find any information on the web ;-( How can i start the script i am editing in VIM. I have compiled vim with python support and installed vim-python. I tried :make etc. but nothing works. THX in advance! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From melis at uni-muenster.de Tue Mar 30 11:20:52 2004 From: melis at uni-muenster.de (Udo Melis) Date: Tue Mar 30 11:20:56 2004 Subject: [Tutor] starting script from within VIM In-Reply-To: <D0DD3F40FC3F714A88D0DB43BAE3625686D257@01-hl-prime.denver.homelmbr.com> References: <D0DD3F40FC3F714A88D0DB43BAE3625686D257@01-hl-prime.denver.homelmbr.com> Message-ID: <40699E64.5020106@uni-muenster.de> John Purser schrieb: >Sorry, that's: ><ESC>:!python script.py > > > Thanks! I found that you dont have to wirte script.py so: :w !python will do. But :com P w: !python will make a user command called P and :P will execute your script. Cheers - Udo - From melis at uni-muenster.de Tue Mar 30 11:31:33 2004 From: melis at uni-muenster.de (Udo Melis) Date: Tue Mar 30 11:31:30 2004 Subject: [Tutor] starting script from within VIM In-Reply-To: <40699E64.5020106@uni-muenster.de> References: <D0DD3F40FC3F714A88D0DB43BAE3625686D257@01-hl-prime.denver.homelmbr.com> <40699E64.5020106@uni-muenster.de> Message-ID: <4069A0E5.9010204@uni-muenster.de> >:com P w: !python > > > > P wont work, but Py works. So put com Py :w !python in your .vimrc and you are set! CU From dyoo at hkn.eecs.berkeley.edu Tue Mar 30 13:09:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 30 13:09:27 2004 Subject: [Tutor] forum In-Reply-To: <000001c415e5$fd210430$cc00a8c0@LumSauFong> Message-ID: <Pine.LNX.4.44.0403301001050.24991-100000@hkn.eecs.berkeley.edu> On Tue, 30 Mar 2004, Lum Sau Fong wrote: > 1. no doubt Python appears to be a programming language which uses > "normal" English language, instructions on its usage is still too > technical for a beginner. Hi Lum Sau Fong, Some of the tutorials are targeted toward people who have already programmed in another language. You may want to look at: http://www.python.org/topics/learn/non-prog.html The tutorials on that page are a bit more gentler than the official Python Tutorial, and you might like them more. Programming languages are superficially "English" since they use English keywords, but it's not really English at all!. Be careful, because there are some places where English usage and Python programming usage will collide. One notorious example of this is: if x == 5 or 6 or 7: ... This is syntactically valid, but has a very different effect in Python than in English. Python does not check to see if x is equal to 5, 6, or 7, but instead does something very different. To get the effect we want, we should say, instead: if x in (5, 6, 7): ... which asks Python, "Is 'x' one of the following elements?" > 3. it has been fun using Python, and it is exciting when the simple > programme worked! That's great! If you have questions, please feel free to ask. Good luck! From nick at javacat.f2s.com Tue Mar 30 14:08:24 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 30 14:07:38 2004 Subject: [Tutor] Off Topic: Revision control system Message-ID: <1080673704.951.6.camel@localhost.localdomain> Hi Folks, I hope you don't mind me sending this but I thought I'd ask for your advice :) I run linux and have a bucket load of python scripts that I regularly amend and it's starting to get annoying, ie vi testfile.py ./testfile.py cp testfile.py testfile2.py vi testfile2.py ./testfile2.py cp testfile2.py testfile3.py vi testfile3.py etc I keep copying so I don't destroy something that works. Now my question is, do you folks use any sort of revision control system on linux ? I've had a look at CVS and RCS but both seem a bit over the top for my needs. Can anyone recommend a simpler solution please ? Or should I write my own (ha I wish). Many thanks Nick. ps if this does annoy anyone then I apologise. From sigurd at 12move.de Tue Mar 30 14:51:47 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue Mar 30 14:56:31 2004 Subject: [Tutor] Off Topic: Revision control system In-Reply-To: <1080673704.951.6.camel@localhost.localdomain> (Nick Lunt's message of "Tue, 30 Mar 2004 20:08:24 +0100") References: <1080673704.951.6.camel@localhost.localdomain> Message-ID: <m31xna3yx1.fsf@hamster.pflaesterer.de> On 30 Mar 2004, Nick Lunt <- nick@javacat.f2s.com wrote: > I run linux and have a bucket load of python scripts that I regularly > amend and it's starting to get annoying, ie > vi testfile.py > ./testfile.py > cp testfile.py testfile2.py > vi testfile2.py > ./testfile2.py > cp testfile2.py testfile3.py > vi testfile3.py > etc > I keep copying so I don't destroy something that works. The easiest way would be to tell VO to make numbered copies of each file you open (with (X)Emacs no problem, it should also work with Vi; if not that's the right time to change your editor :-) ) > Now my question is, do you folks use any sort of revision control system > on linux ? I've had a look at CVS and RCS but both seem a bit over the > top for my needs. But CVS is for local use very simple. It has a extremly good manual which explains how to start from scratch. If you have created your local cvs repository you only have to checkin the files (no need to tell that the right editor can be a great help there). I use it not only for programm files but also for all sort of ini files. If you somehow manage to delete the wrong ini file you praise the inventor of CVS. Also if you are interested in open source software sooner or later you will need CVS or its successsor subversion (I didn't try it yet, but it seems that subversion will replace CVS). So start getting familiar with something like that. > Can anyone recommend a simpler solution please ? Did you try out CVS locally? It's as simple as it can be. Karl -- Please do *not* send copies of replies to me. I read the list From op73418 at mail.telepac.pt Tue Mar 30 16:21:51 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Mar 30 16:25:55 2004 Subject: [Tutor] Off Topic: Revision control system In-Reply-To: <1080673704.951.6.camel@localhost.localdomain> References: <1080673704.951.6.camel@localhost.localdomain> Message-ID: <h0pj60t1dt0olqquuihn89b0jad9udjer1@4ax.com> Em Tue, 30 Mar 2004 20:08:24 +0100, Nick Lunt <nick@javacat.f2s.com> atirou este peixe aos pinguins: >Hi Folks, > >I hope you don't mind me sending this but I thought I'd ask for your >advice :) > >I run linux and have a bucket load of python scripts that I regularly >amend and it's starting to get annoying, ie > >vi testfile.py >./testfile.py >cp testfile.py testfile2.py >vi testfile2.py >./testfile2.py >cp testfile2.py testfile3.py >vi testfile3.py >etc > >I keep copying so I don't destroy something that works. > >Now my question is, do you folks use any sort of revision control system >on linux ? I've had a look at CVS and RCS but both seem a bit over the >top for my needs. > >Can anyone recommend a simpler solution please ? >Or should I write my own (ha I wish). > Karl recommended CVS, I recommend subversion. See http://subversion.tigris.org/ It's an improvement over CVS, very easy to use locally. There are also (at least) two projects for GUI clients, TortoiseSVN (Only for windoze, *I think*) and RapidSVN which was still pretty alpha last time I looked. The docs explain all that you need to set up a local repository and work out from there. You can also look up http://www.onlamp.com/pub/a/onlamp/2002/10/31/subversion.html With my best regards, G. Rodrigues From Doug.Shawhan at ge.com Tue Mar 30 18:18:07 2004 From: Doug.Shawhan at ge.com (Shawhan, Doug (EM, ITS)) Date: Tue Mar 30 18:18:18 2004 Subject: [Tutor] glob is driving me berserk Message-ID: <CE88C8D948CCBE4EB0104ACDC79F299ED96089@CINMLVEM04.e2k.ad.ge.com> I am having some difficulty with glob.glob() This is the beginning of a simple mailbox backup program for multiple hosts. Each of the mail directories has at least one username.pst mailbox in the proper directory. Can anyone see why this is not working? ---------------------------------------------------------------------- import glob import string hosts=["Shared_host"] for host in hosts: #first we collect the users on the host users=glob.glob("\\\\%s\\d$\\users\\*"%host) #<-- works great! for user in users: #strip extraneous pathname info from username. All hostnames are the same length username=user[21:] print "Collecting mailboxes for %s"%username mailboxes_path="%s\\MYDOCU~1\\Exchange\\"%user mailboxes_path=string.replace(mailboxes_path,'\\','\\\\') mailboxes=glob.glob('%s*.pst'%mailboxes_path) #~ print mailboxes_path print '%s*.pst'%mailboxes_path #<--this looks perfect in the output! print mailboxes --------------------------------------------------------------- output -------------------------------------------------------------- Collecting mailboxes for guy1 \\\\Shared_host\\d$\\users\\guy1\\MYDOCU~1\\Exchange\\*.pst [] Collecting mailboxes for guy2 \\\\Shared_host\\d$\\users\\guy2\\MYDOCU~1\\Exchange\\*.pst [] Collecting mailboxes for guy3 \\\\Shared_host\\d$\\users\\guy3\\MYDOCU~1\\Exchange\\*.pst [] ----------------------------------------------------------------- I have tried just typing in the full UNC path wit glob in a python shell and it works fine! Where am I getting twisted up here? From dyoo at hkn.eecs.berkeley.edu Tue Mar 30 18:28:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 30 18:29:01 2004 Subject: [Tutor] glob is driving me berserk In-Reply-To: <CE88C8D948CCBE4EB0104ACDC79F299ED96089@CINMLVEM04.e2k.ad.ge.com> Message-ID: <Pine.LNX.4.44.0403301525130.27134-100000@hkn.eecs.berkeley.edu> On Tue, 30 Mar 2004, Shawhan, Doug (EM, ITS) wrote: > I am having some difficulty with glob.glob() [some text cut] > users=glob.glob("\\\\%s\\d$\\users\\*"%host) #<-- works great! > for user in users: > username=user[21:] > print "Collecting mailboxes for %s"%username > mailboxes_path="%s\\MYDOCU~1\\Exchange\\"%user > mailboxes_path=string.replace(mailboxes_path,'\\','\\\\') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Hi Doug, Are you sure you need to double up the backslashes again? You don't do so universally on your first glob, > users=glob.glob("\\\\%s\\d$\\users\\*"%host) #<-- works great! Perhaps you may want to do: mailboxes_path = "%s\\\\MYDOCU~1\\Exchange\\" % user mailboxes = glob.glob('%s*.pst' % mailboxes_path) instead? Good luck to you. From Doug.Shawhan at ge.com Tue Mar 30 18:35:36 2004 From: Doug.Shawhan at ge.com (Shawhan, Doug (EM, ITS)) Date: Tue Mar 30 18:35:50 2004 Subject: [Tutor] glob is driving me berserk Message-ID: <CE88C8D948CCBE4EB0104ACDC79F299E0D91942B@CINMLVEM04.e2k.ad.ge.com> I am officially going insane. Really. I am sitting in a corner picking my nails and singing "que sera sera.". This worked. May the lord smile on me and put me to work on an os that does not require such a skull-melting gymkhana to SIMPLY READ A PATH *&^*^%$&^%&%&%$!!!!! *ahem* Excuse the outburst. I think I see what was happening now. Thanks very much, Danny. ---------------------------------------------- Hi Doug, Are you sure you need to double up the backslashes again? You don't do so universally on your first glob, > users=glob.glob("\\\\%s\\d$\\users\\*"%host) #<-- works great! Perhaps you may want to do: mailboxes_path = "%s\\\\MYDOCU~1\\Exchange\\" % user mailboxes = glob.glob('%s*.pst' % mailboxes_path) instead? Good luck to you. From dyoo at hkn.eecs.berkeley.edu Tue Mar 30 18:54:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 30 18:54:33 2004 Subject: [Tutor] glob is driving me berserk [os.path.join] In-Reply-To: <CE88C8D948CCBE4EB0104ACDC79F299E0D91942B@CINMLVEM04.e2k.ad.ge.com> Message-ID: <Pine.LNX.4.44.0403301537200.27896-100000@hkn.eecs.berkeley.edu> On Tue, 30 Mar 2004, Shawhan, Doug (EM, ITS) wrote: > I am officially going insane. Really. I am sitting in a corner picking > my nails and singing "que sera sera.". > > This worked. > > May the lord smile on me and put me to work on an os that does not > require such a skull-melting gymkhana to SIMPLY READ A PATH > *&^*^%$&^%&%&%$!!!!! Hi Doug, Yeah, this is something that really should not be so difficult. Had people really thought things through, we'd never run into such a silly issue. *sigh* What you ran into is an intersection of our use, as programmers, of the backslash character to increase the number of characters we can type directly from the keyboard. This conflicts slightly with the use of the literal backslash character as the path separator on the Windows platform. So we have to be a bit careful about paths. But by the way: using os.path.join() and the other os.path functions may help to avoid these kinds of silly issues: http://www.python.org/doc/lib/module-os.path.html On a Unix system, here's a sample of what os.path can do: ### >>> os.path.expanduser(os.path.join("~dyoo", "public_html")) '/home2/dyoo/public_html' ### You may want to see if os.path will be useful for you, as it's a better platform-independent way of building paths reliably, so that you should hopefully not have to worry about backslashes so much. Good luck! From brandon_cole at adelphia.net Tue Mar 30 19:28:20 2004 From: brandon_cole at adelphia.net (Brandon) Date: Tue Mar 30 19:28:26 2004 Subject: [Tutor] (no subject) Message-ID: <20040331002820.ZVFV23599.mta10.adelphia.net@mail.adelphia.net> How do you make a .exe for python in windows? From brandon_cole at adelphia.net Tue Mar 30 19:30:53 2004 From: brandon_cole at adelphia.net (Brandon) Date: Tue Mar 30 19:30:58 2004 Subject: [Tutor] Python exes Message-ID: <20040331003053.PFTB28815.mta13.adelphia.net@mail.adelphia.net> I've tried all I can about creating a .exe file in python. I've googled, searched, and found everything I could, but I still can not get anything to work. Can someone point me in the right direction? From hall at nhn.ou.edu Tue Mar 30 19:41:15 2004 From: hall at nhn.ou.edu (Ike Hall) Date: Tue Mar 30 19:41:48 2004 Subject: [Tutor] plotting Message-ID: <406A13AB.70300@nhn.ou.edu> Hi list :) alright, a long time ago I created this nice little widget for plotting stripcharts using Python Mega Widgets (Pmw). It has grown and expanded over the years, but it may now be comming to the end of its useful life. I really really really need to give it the functionality to put vertical error bars on every point (its basically a glorified Pmw.blt.graph), and I can't for the life of me figure out how to do this. I have seen a nice method to change the fill color of symbols based on a weight, and its **almost** the thing I need to do...except instead of changing colors, I need error bars corresponding to the weight. can anyone help me with this? Ike -- ---------------------------------------- | Isaac N. Hall | | Graduate Student | | University of Oklahoma/D0 Experiment | | (630)840-3724 | ---------------------------------------- From magnus at thinkware.se Tue Mar 30 21:13:56 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Mar 30 21:14:04 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHl0aG9uIGV4ZXM=?= Message-ID: <think001_406a27fc05261@webmail.thinkware.se> Brandon wrote: > I've tried all I can about creating a .exe file in python. I've googled, searched, and found everything I could, but I still can not get anything to work. Can someone point me in the right direction? You're not very explicit with what you tried, and what your problems were, but I've had memory errors with py2exe and McMillan installer that disappeared when I used cx_Freeze instead. See http://starship.python.net/crew/atuining/cx_Freeze/ -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From mlc99 at bellsouth.net Tue Mar 30 23:51:27 2004 From: mlc99 at bellsouth.net (mike) Date: Tue Mar 30 23:48:09 2004 Subject: [Tutor] forum In-Reply-To: <Pine.LNX.4.44.0403301001050.24991-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0403301001050.24991-100000@hkn.eecs.berkeley.edu> Message-ID: <200403301801.50692.mlc99@bellsouth.net> On Tuesday 30 March 2004 12:09 pm, Danny Yoo wrote: > On Tue, 30 Mar 2004, Lum Sau Fong wrote: > > 1. no doubt Python appears to be a programming language which uses > > "normal" English language, instructions on its usage is still too > > technical for a beginner. > I would suggest a copy of the following book: Python Programming: An Introduction to Computer Science. It is an introduction to computer science textbook that uses Python as a beginner language to teach computer science and assumes you know nothing about programming. This is a new book that has only been in print a couple of months. It is available at www.fbeedle.com -- Mike Cates *****LINUX***** ~Mandrake 9.2~ *Kmail 1.5.3*** *************** From brassy19 at hotmail.com Wed Mar 31 02:05:35 2004 From: brassy19 at hotmail.com (Chris C.) Date: Wed Mar 31 02:05:45 2004 Subject: [Tutor] help with IDLE Message-ID: <BAY1-F155xz6ZqoZvSK0001b8da@hotmail.com> Newbie here. I just downloaded python v.2.3 onto windows xp, into directory C:\python23 (the default). The command line opens up and works great, but the IDLE script doesn't. When I try to open it, it seems to try to start up, but nothing is displayed on the screen. Is anyone else having this problem? I'd love to get started learning the language if I could fix this. Any help is greatly appreciated! Thanks for your time, -Chris p.s. sorry if I didn't provide enough info- if more info is needed, just tell me... _________________________________________________________________ Check out MSN PC Safety & Security to help ensure your PC is protected and safe. http://specials.msn.com/msn/security.asp From jmpurser at comcast.net Wed Mar 31 06:48:47 2004 From: jmpurser at comcast.net (John M. Purser) Date: Wed Mar 31 06:48:44 2004 Subject: Py2exe - Was RE: [Tutor] (no subject) In-Reply-To: <20040331002820.ZVFV23599.mta10.adelphia.net@mail.adelphia.net> Message-ID: <KPEHKAGJNANNKCCCIIGPGENPDGAD.jmpurser@comcast.net> Check out: http://starship.python.net/crew/theller/py2exe/ It's easier to help you if you put a good subject on your letters to the list. John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Brandon Sent: Tuesday, March 30, 2004 5:28 PM To: Tutor@python.org Subject: [Tutor] (no subject) How do you make a .exe for python in windows? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From Christian.Wyglendowski at greenville.edu Wed Mar 31 11:14:02 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Mar 31 11:14:11 2004 Subject: [Tutor] Python and Active directory Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A38F3@empex.greenville.edu> Here is something to start with (code courtesy of http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=2f3c ef424c.tim%40worthy.demon.co.uk&rnum=2&prev=/groups%3Fq%3Dwin32com.clien t.getobject%2520ldap%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26sa%3D N%26tab%3Dwg ): #begin code import win32com.client #from Mark Hammond's pywin32 module def do_onecontainer(Container): for oneobject in Container: if oneobject.Class.lower()=='user': #found a user! do what you want here (print, write to file, add to database, etc) print oneobject.cn if oneobject.Class.lower()=="organizationalunit" or \ oneobject.Class.lower()== "container": #found a subcontainer - search it for users by recursively calling do_onecontainer() do_onecontainer(oneobject) startContainer=win32com.client.GetObject("LDAP://DC=yourdomain,DC=suffix ") #make sure to set your domain info do_onecontainer(startContainer) #end code There is probably a way to do this with ADODB and LDAP queries, but this works. Christian http://www.dowski.com -----Original Message----- From: Wilhelmsen Jan [mailto:Jan.Wilhelmsen@bilia.no] Sent: Tuesday, March 30, 2004 5:06 AM To: tutor@python.org Subject: [Tutor] Python and Active directory Hi! Is there any module or other ways of extracting/listing/modifying users/person account information from Active directory? If there is? Where can I find information about this? I need to make a script that exports all users in all OU's to a formatted textfile. Thanks! Jan Wilhelmsen From Doug.Shawhan at ge.com Wed Mar 31 13:25:55 2004 From: Doug.Shawhan at ge.com (Shawhan, Doug (EM, ITS)) Date: Wed Mar 31 13:26:25 2004 Subject: [Tutor] Good threading tutorial Message-ID: <CE88C8D948CCBE4EB0104ACDC79F299E0D919438@CINMLVEM04.e2k.ad.ge.com> I have googled up a few examples of threading in python. I am still a little unclear on the concept. Are there any good hand-holding threading tutorials around? Thanks! d From vicki at stanfield.net Wed Mar 31 13:33:27 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Wed Mar 31 13:33:39 2004 Subject: [Tutor] Good threading tutorial In-Reply-To: <CE88C8D948CCBE4EB0104ACDC79F299E0D919438@CINMLVEM04.e2k.ad.ge.com> References: <CE88C8D948CCBE4EB0104ACDC79F299E0D919438@CINMLVEM04.e2k.ad.ge.com> Message-ID: <60258.206.53.226.235.1080758007.squirrel@www.thepenguin.org> > I have googled up a few examples of threading in python. I am still a > little unclear on the concept. Are there any good hand-holding threading > tutorials around? > > Thanks! > > d I looked for some a while back and never found any, however there is a reasonable amount of understandable example code. See if this helps you. ----------- import threading class TaskThread(threading.Thread): """Thread that executes a task every N seconds""" def __init__(self): threading.Thread.__init__(self) self._finished = threading.Event() #self._interval = 15.0 self._interval = 5.0 self.num = 0 def setInterval(self, interval): """Set the number of seconds we sleep between executing our task""" self._interval = interval def shutdown(self): """Stop this thread""" self._finished.set() def run(self): while 1: if self._finished.isSet(): return self.task() # sleep for interval or until shutdown self._finished.wait(self._interval) def task(self): """The task done by this thread - override in subclasses""" pass if __name__ == '__main__': global num class printTaskThread(TaskThread): def task(self): print 'running %d' %self.num self.num = self.num + 1 time.sleep(3) tt = printTaskThread() tt.setInterval(3) print 'starting' tt.start() print 'started, wait now' import time time.sleep(60) print 'killing the thread' tt.shutdown() print 'killed and done' ----------- Playing with this code made it a bit clearer for me, so maybe it will help. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From tpc at csua.berkeley.edu Wed Mar 31 13:43:05 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Mar 31 13:43:15 2004 Subject: [Tutor] Good threading tutorial In-Reply-To: <CE88C8D948CCBE4EB0104ACDC79F299E0D919438@CINMLVEM04.e2k.ad.ge.com> Message-ID: <20040331103445.F66207-100000@localhost.name> hi Doug, I've been looking at Aahz's tutorial: http://starship.python.net/crew/aahz/OSCON2001/index.html though I benefit from being present when he used slides from the page above to give his presentation on Python multithreading at the January 2004 Bay Area Python Interest Group meeting. I hope that helps you. On Wed, 31 Mar 2004, Shawhan, Doug (EM, ITS) wrote: > I have googled up a few examples of threading in python. I am still a little unclear on the concept. Are there any good hand-holding threading tutorials around? > > Thanks! > > d > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From amonroe at columbus.rr.com Wed Mar 31 13:57:28 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Mar 31 13:50:48 2004 Subject: [Tutor] Good threading tutorial In-Reply-To: <CE88C8D948CCBE4EB0104ACDC79F299E0D919438@CINMLVEM04.e2k.ad.ge.com> References: <CE88C8D948CCBE4EB0104ACDC79F299E0D919438@CINMLVEM04.e2k.ad.ge.com> Message-ID: <148761025977.20040331135728@columbus.rr.com> > I have googled up a few examples of threading in python. I am still > a little unclear on the concept. Are there any good hand-holding > threading tutorials around? >From what little I've played with it: - def a function that you want to get executed in a subthread - create a new thread, feed it the name of the function above - start the new thread at this point, you need not execute any further statements in your program. The main program will wait indefinitely for the child thread to complete. Once it's done, the main program will exit too. It's kind of neat to watch, the first time you try it. I haven't reached the level of locking or semaphores, myself. Alan From Doug.Shawhan at ge.com Wed Mar 31 13:54:26 2004 From: Doug.Shawhan at ge.com (Shawhan, Doug (EM, ITS)) Date: Wed Mar 31 13:54:44 2004 Subject: [Tutor] Good threading tutorial Message-ID: <CE88C8D948CCBE4EB0104ACDC79F299E0D919439@CINMLVEM04.e2k.ad.ge.com> How about a nice "hello threads" example? :-) -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of R. Alan Monroe Sent: Wednesday, March 31, 2004 12:57 PM To: tutor@python.org Subject: Re: [Tutor] Good threading tutorial > I have googled up a few examples of threading in python. I am still > a little unclear on the concept. Are there any good hand-holding > threading tutorials around? >From what little I've played with it: - def a function that you want to get executed in a subthread - create a new thread, feed it the name of the function above - start the new thread at this point, you need not execute any further statements in your program. The main program will wait indefinitely for the child thread to complete. Once it's done, the main program will exit too. It's kind of neat to watch, the first time you try it. I haven't reached the level of locking or semaphores, myself. Alan _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From vicki at stanfield.net Wed Mar 31 15:15:28 2004 From: vicki at stanfield.net (Vicki Stanfield) Date: Wed Mar 31 15:15:46 2004 Subject: [Tutor] Good threading tutorial In-Reply-To: <CE88C8D948CCBE4EB0104ACDC79F299E0D919439@CINMLVEM04.e2k.ad.ge.com> References: <CE88C8D948CCBE4EB0104ACDC79F299E0D919439@CINMLVEM04.e2k.ad.ge.com> Message-ID: <47867.12.223.198.92.1080764128.squirrel@www.thepenguin.org> > How about a nice "hello threads" example? :-) > How about this one? ----- import threading class TaskThread(threading.Thread): """Thread that executes a task every N seconds""" def __init__(self): threading.Thread.__init__(self) self._finished = threading.Event() #self._interval = 15.0 self._interval = 5.0 self.num = 0 def setInterval(self, interval): """Set the number of seconds we sleep between executing our task""" self._interval = interval def shutdown(self): """Stop this thread""" self._finished.set() def run(self): while 1: if self._finished.isSet(): return self.task() # sleep for interval or until shutdown self._finished.wait(self._interval) def task(self): """The task done by this thread - override in subclasses""" pass if __name__ == '__main__': global num class printTaskThread(TaskThread): def task(self): print 'running %d' %self.num self.num = self.num + 1 time.sleep(3) tt = printTaskThread() tt.setInterval(3) print 'starting' tt.start() print 'started, wait now' import time time.sleep(60) print 'killing the thread' tt.shutdown() print 'killed and done' ------- I played with it a while back to get the feel of threads in Python. --vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From glingl at aon.at Wed Mar 31 16:18:32 2004 From: glingl at aon.at (Gregor Lingl) Date: Wed Mar 31 16:17:45 2004 Subject: [Tutor] Good threading tutorial In-Reply-To: <CE88C8D948CCBE4EB0104ACDC79F299E0D919439@CINMLVEM04.e2k.ad.ge.com> References: <CE88C8D948CCBE4EB0104ACDC79F299E0D919439@CINMLVEM04.e2k.ad.ge.com> Message-ID: <406B35A8.9010900@aon.at> Shawhan, Doug (EM, ITS) schrieb: >How about a nice "hello threads" example? :-) > >- > I use this as a "hello threads" example in my classes: #### EXAMPLE: from threading import Thread from random import random from time import sleep # COMPARE THE OUTPUT OF REPEATED RUNS OF THIS PROGRAM def drop(char): for i in range(10): t = 0.5 * random() sleep(t) print char, thr1 = Thread(target=drop, args=("+",)) thr2 = Thread(target=drop, args=("-",)) thr1.start() thr2.start() drop(":") sleep(3.0) # comment out this line, run the program repeatedly # and see what happens now #### END OF EXAMPLE Alas, it doesn't show what one needs to program with threads. Id' prefer to have implementations of some classic examples as for instance the producer consumer problem. (Don't know if one could find some in the Python Docs) TIM PETERS pointed someone (that was me) to his implementation of the "dining philosophers problem" (from May 2000). http://aspn.activestate.com/ASPN/Mail/Message/249937 If you know how beautiful and readable Tim's code uses to be, you can't avoid reading it. (I don't *know* if it is still "state of the art" with Python 2.3. but I'd expect yes.) To see how it works I recommend to run it with less than 1000 philosophers. ;-) Regards, Gregor P.S. Under windows: It doesn't run properly from IDLE - I think because Tkinter is not "thread safe". On my machine in one test-run it even killed IDLE. From blakeg.NOSPAM at freeshell.org Wed Mar 24 15:52:13 2004 From: blakeg.NOSPAM at freeshell.org (Blake Garretson) Date: Thu Apr 1 18:11:18 2004 Subject: [Tutor] usenet server quest Message-ID: <20040324205213.GA20142@SDF.LONESTAR.ORG> Kirk Bailey <idiot1@netzero.net> wrote: >OK, I want a usenet server. There is nothing in the library to >facilitate this, so it might turn into an entire nre module. > >To start with, it can be a single group. It should not be a hairpull >to >install. And of course, written in python. > >Any discussion? Why not look at existing Python NNTP servers? Check out Papercut (http://papercut.org/). Of course, Twisted (http://twistedmatrix.com/) has one too, but Twisted does LOTS of stuff and the source might be more difficult to sort through. -- Blake Garretson --- http://blakeg.freeshell.org From Chad.Crabtree at nationalcity.com Tue Mar 23 10:47:18 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Thu Apr 1 18:11:44 2004 Subject: [Tutor] accessing items in nested structure Message-ID: <66F587DFDD46D511B65200508B6F8DD60EF88EBA@nt-kalopsapp07.ntl-city.com> -----Original Message----- From: kevin parks [mailto:kp8@mac.com] Sent: Monday, March 22, 2004 5:13 PM To: Crabtree, Chad Subject: Re: [Tutor] accessing items in nested structure Hi Chad, Thanks for this. I really appreciate your taking the time to answer. However i get the impression that there is something here i don't get. I think when you say dict.items(): that is kind of an abstraction right? Cause if i type that actually thing in the interpreter i get: >>> data.datas() Traceback (most recent call last): File "<stdin>", line 1, in ? File "/Users/kevin/Desktop/data.py", line 27, in datas for key,value in dict.items(): TypeError: descriptor 'items' of 'dict' object needs an argument clearly i am supposed to plug something in someplace right? This doesn't seem to work either: def datas(): page02 = [ { (1,0) : [8, 3, 5, 4] }, { (7,0) : [4, 3, 2, 2] }, { (14,0) : [8, 3, 5, 4] }, { (18,0) : [10, 2, 8, 7] }, { (20,0) : [10, 0, 5, 7] }, { (22,0) : [10, 2, 8, 7] }, { (24,0) : [7, 9, 3, 8] }, # { (25,0) : [5] }, # { (27,0) : [0] }, { (28,0) : [10, 0, 5, 7] }, { (29,0) : [10, 11] }, { (30,0) : [8, 3, 5, 4] }, { (32,0) : [5, 0, 10, 7] }, { (34,0) : [8, 3, 7, 9] }, { (36,0) : [5, 4, 3, 1] }, { (36,1) : [5, 4, 3, 1, 7] }, { (37,0) : [0, 8, 2, 4, 9, 10, 1] }, { (37,1) : [0, 8, 2, 4, 9, 10, 1, 6] }, { (39,0) : [8, 10, 1, 9] }, { (39,1) : [8, 10, 1, 9, 7] }, { (41,0) : [2, 0, 3, 1] }, { (41,1) : [2, 0, 3, 1, 6] }] for x in page02: for key,value in dict.items(): print "Key=%s" %key print "Value=%s" %str(value) Okay I'm sory. 'Dict' is the name of the viarble dictionary. So it should by <anydictionaryname>.items() I'll try again. I failed to paste all the pertinent iformation. >>> dict={'h':[1,1,1,1],'e':[2,2,2,2],'l':[3,3,3,3],'o':[4,4,4,4]} >>> for key,value in dict.items(): print "Key=%s" %key, print "\tValue=%s" %str(value) Key=h Value=[1, 1, 1, 1] Key=e Value=[2, 2, 2, 2] Key=l Value=[3, 3, 3, 3] Key=o Value=[4, 4, 4, 4] >>> I'v made some changes to you dictionary >>> page02 = { (1,0) : [8, 3, 5, 4] , (7,0) : [4, 3, 2, 2] , (14,0) : [8, 3, 5, 4] , (18,0) : [10, 2, 8, 7] , (20,0) : [10, 0, 5, 7] , (22,0) : [10, 2, 8, 7] , (24,0) : [7, 9, 3, 8] , (28,0) : [10, 0, 5, 7] , (29,0) : [10, 11] , (30,0) : [8, 3, 5, 4] , (32,0) : [5, 0, 10, 7] , (34,0) : [8, 3, 7, 9] , (36,0) : [5, 4, 3, 1] , (36,1) : [5, 4, 3, 1, 7] , (37,0) : [0, 8, 2, 4, 9, 10, 1] , (37,1) : [0, 8, 2, 4, 9, 10, 1, 6] , (39,0) : [8, 10, 1, 9] , (39,1) : [8, 10, 1, 9, 7] , (41,0) : [2, 0, 3, 1] , (41,1) : [2, 0, 3, 1, 6] } >>> for key, value in page02.items(): print "Key=%s" %str(key), print "\tValue=%s" %str(value) Key=(30, 0) Value=[8, 3, 5, 4] Key=(41, 0) Value=[2, 0, 3, 1] Key=(37, 1) Value=[0, 8, 2, 4, 9, 10, 1, 6] Key=(37, 0) Value=[0, 8, 2, 4, 9, 10, 1] Key=(36, 0) Value=[5, 4, 3, 1] Key=(36, 1) Value=[5, 4, 3, 1, 7] Key=(18, 0) Value=[10, 2, 8, 7] Key=(39, 1) Value=[8, 10, 1, 9, 7] Key=(7, 0) Value=[4, 3, 2, 2] Key=(14, 0) Value=[8, 3, 5, 4] Key=(24, 0) Value=[7, 9, 3, 8] Key=(20, 0) Value=[10, 0, 5, 7] Key=(22, 0) Value=[10, 2, 8, 7] Key=(1, 0) Value=[8, 3, 5, 4] Key=(32, 0) Value=[5, 0, 10, 7] Key=(39, 0) Value=[8, 10, 1, 9] Key=(34, 0) Value=[8, 3, 7, 9] Key=(29, 0) Value=[10, 11] Key=(28, 0) Value=[10, 0, 5, 7] Key=(41, 1) Value=[2, 0, 3, 1, 6] what you had was a list of single key dictionaries. Which was obfuscating the data abstraction. What I chaged it to was a dictionary with each key pointing to a List. This way you will not have to first (as you had it) Iterate of a list, each item being a single item dictionary. Then find the key with some function then iterate of the list example def runOverit(aList): for x in aList: for k in x.keys(): for z in k: print z # or do something with this value. I believe you where improperly nesting the container types for the job you are trying to do. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From jb at riseup.net Tue Mar 30 16:20:21 2004 From: jb at riseup.net (jb) Date: Thu Apr 1 18:12:43 2004 Subject: [Tutor] Off Topic: Revision control system In-Reply-To: <1080673704.951.6.camel@localhost.localdomain> References: <1080673704.951.6.camel@localhost.localdomain> Message-ID: <20040330212020.GA28045@mubai.sakeos.net> On Tue, Mar 30, 2004 at 08:08:24PM +0100, Nick Lunt wrote: > Hi Folks, > > I hope you don't mind me sending this but I thought I'd ask for your > advice :) > > I run linux and have a bucket load of python scripts that I regularly > amend and it's starting to get annoying, ie > > vi testfile.py > ./testfile.py > cp testfile.py testfile2.py > vi testfile2.py > ./testfile2.py > cp testfile2.py testfile3.py > vi testfile3.py > etc > > I keep copying so I don't destroy something that works. > > Now my question is, do you folks use any sort of revision control system > on linux ? I've had a look at CVS and RCS but both seem a bit over the > top for my needs. > > Can anyone recommend a simpler solution please ? > Or should I write my own (ha I wish). > well, maybe this reply wont be very helpfull, but i would say look again at rcs: the 3 commands here are about everything one needs to know about it - basic usage: in the directory where testfile.py lives, do a "mkdir RCS", then "ci -l testfile.py". that's it. you can see diffs between the current version and the last one with "rcsdiff testfile.py". if you break your work later, do a "co -l testfile.py" and you will revert to the last working version. ci is for "check in", co for "check out" and "-l" to say you want to continue to work on this file (lock it, is rcs vocabulary). when basic usage isn't enougth, the next best thing is to use the "-r" option, which allows you to check out or diff between your old work and your present work: "rcsdiff -r1.1 testfile.py" (first version is 1.1, second 1.2, etc). i did not find a simpler solution than that -- all the other had testfile.bck, testfile.bak2, testfile.old.tuesday and friends involved :) the rcs man page doesnt give a warm feeling at first, but the tool really simplify things when you need to deal with a couple of individual files in a directory. i hope this helps, jb From kim.branson at csiro.au Mon Mar 22 07:10:34 2004 From: kim.branson at csiro.au (Kim Branson) Date: Thu Apr 1 18:13:50 2004 Subject: [Tutor] object oriented programming In-Reply-To: <MBBBKPICGBKFODJNCCLJEEOFDCAA.dbroadwell@mindspring.com> References: <MBBBKPICGBKFODJNCCLJEEOFDCAA.dbroadwell@mindspring.com> Message-ID: <EC0DC220-7BF9-11D8-8DC0-000A9579AE94@csiro.au> Hi all, I'm trying to get some understanding of object oriented programming. I've found python a very useful language to do things in rapidly. I'm writing a few scientific applications for my research, and the programs have grown to be quite complex. A programmer friend has convinced me i should be using object oriented programming. (He also pointed out there is a place for both styles...) I've looked at some of the chapters in the learning python book, but the oo sections are very brief. I'm having difficulty thinking in the oo way. I think procedurally about my code and the object way seems hard to grasp. I'd appreciate it if anyone can point me at some good books, or tutorials (preferably python based) cheers Kim From py at humnet.ucla.edu Sun Mar 28 03:25:37 2004 From: py at humnet.ucla.edu (peter hodgson) Date: Thu Apr 1 18:14:45 2004 Subject: [Tutor] first steps Message-ID: <200403280825.i2S8Pb80000854@violet.noc.ucla.edu> hello; i've done my first forty or so tutorial programs; please take a look at and tell me if i'm on track; A. I DON'T UNDERSTAND THIS: Here is another example of variable usage: a = 1 print a a = a + 1 print a a = a * 2 print a And of course here is the output: 1 2 4 Even if it is the same variable on both sides [OF THE '='] the computer still reads it as: First find out the data to store [RIGHT SIDE OF THE '='?] and than [THEN] find out where the data goes [PRINT COMMAND?]. ---------------------- B. WHY WON'T THIS RUN? ----------------------- #while 1 == 1: would perpetuate the printing of "help..." #l3 - l6 [extracted from another program] should limit it to five times count = 0 max_count = 5 while count > max_count: count = count + 1 print "help, i'm caught in a loop" #but the program won't run ----------------------------- C.HAVE I PARSED THIS RIGHT? ----------------------------- #values into/out of a pail; #this is l1 a = 1 #this means a = non-zero, that it is; s = 0 #empty pail print "enter numbers to add to the sum" #plus or minus print "enter 0 to quit" #end the game while a != 0: #i.e., you're still playing the game; print "current sum:", s #so we start at 0 a = input("nmber? ") #and we alter s by a, superceding a = 1 s = s + a #and a is the increment #reducing s to 0 won't close program print "total sum = ", s #not indented cause it only runs at the end #l2, l3 provide the contents and the pail; #l5, l6 provide for a way to end the game; #playing the game is l4, plus the indented lines l7 - l9; From py at humnet.ucla.edu Mon Mar 29 13:39:16 2004 From: py at humnet.ucla.edu (peter hodgson) Date: Thu Apr 1 18:14:51 2004 Subject: [Tutor] embedding an if Message-ID: <200403291839.i2TIdG9a018758@periwinkle.noc.ucla.edu> hello; 2.3 on a gentoo box; tutorial assignment; what am i doing wrong? thanks #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 "you're screwed, buddy!", or something like that; passwd = "foobar" #a dummy passwd count = 3 current_count = 0 while passwd != "unicorn": current_count = current_count + 1 passwd = raw_input("Passwd: ") if current_count < count: print "no, stupid! try again;" else print "three times, you're out!" print "welcome in" #without 'count': keep asking for password until the jerk gets it right; #with 'count': he only gets three chances; From robichon at esrf.fr Mon Mar 22 10:03:05 2004 From: robichon at esrf.fr (Marie Robichon) Date: Thu Apr 1 18:15:07 2004 Subject: [Tutor] checking variable types Message-ID: <5.1.0.14.1.20040322160047.00ac67d0@mailserv.esrf.fr> Hi, I have a mutliple select box in html which (unfortunately) returns a list if someone makes a multiple selection but returns a string if someone selects one item only. How in my python script do I test whether it is a list or a string before I do my processing ? Thanks in advance from a newbie, Marie From santhosho at it.iitb.ac.in Thu Mar 25 02:28:06 2004 From: santhosho at it.iitb.ac.in (Santhosh.o.m) Date: Thu Apr 1 18:15:54 2004 Subject: [Tutor] request for help Message-ID: <52543.10.129.1.22.1080199686.squirrel@www.it.iitb.ac.in> Respected sir, i am doing my final year mca project in IIT,bombay,India. My paln is to enhance one allready exist sytem.that is written in python.but my paln is to do enhance code in JSP. sir, is it possible for me to correlate python code with jsp code.that is if i call allready exist python code from the jsp interface it will work. sir if it possible please send me with deatils thanking you yours faithfully santhoshom From shaleh at speakeasy.net Tue Mar 23 01:20:15 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Thu Apr 1 18:16:30 2004 Subject: [Tutor] trying to understand the logic of functions In-Reply-To: <20040323044748.12254.qmail@web61204.mail.yahoo.com> References: <20040323044748.12254.qmail@web61204.mail.yahoo.com> Message-ID: <200403222220.15658.shaleh@speakeasy.net> On Monday 22 March 2004 20:47, python_simpleton wrote: > I have been blown away by the complicated questions and answers, the deepth > of python is staggering. And yes I am new at programming and python is my > first. now to the questions. Oh by the way I have been sticking to > Non-Programmers Tutorial for Python. I am sure i am thinking so unlogical > compared to ya'll and i'm taking small "babysteps" but i am trying, sorry > this is so long but i spent hours reading this tutorial at the airport. > no worries. Programming is a mindset. For some it comes really easy, for others it takes work. Just remember -- if it ain't fun you need to find a new hobby. > General > > Q. The : symbol is used at the end of the line in more than just a while > statement. Is it just used after a control structure (while, if, else, elif > in the most basic of uses is what i understand so for) is it used after a > condition and keywords? what is the logic behind it? > in most other languages blocks of code are clearly delineated. Here is an example in C: int main(int argc, char* argv[]) { if (argc == 1) { /* in C, there is always one argument, the program's name */ printf("no arguments given"); else { printf("%d arguments were given", argc); } exit(0); } In Python, blocks are simply marked by indentation so the colon acts as a "please start here" indicator to make parsing easier for the interpreter. > Functions > > > I understand that def starts a function definition, my_abs is the function > name (good name for absolute value example) > > Q. num is a parameter? I don't understand what one is really but is it > getting the values of a = 23 and b = -23 as a local variable? like this > num(a,b)? then go on to figure the rest of the code? or does num take the > global variables one at a time to determine which side of 0 they are on. > Does num gets if values because of my_abs(a) and my my_abs(b) > and this means the function is being called(or whatever the correct word > it) twice since it the function has only one parameter (num) and num can > only handle on value at a time(a and b are arguments?) > a function is defined by your code. At that point it is sitting there idly on the sidelines waiting to be called -- just like a player on a sports team. So the coach (python) says "my_abs, take 'a' and do your thing". At which point my_abs performs whatever operations it was defined to do earlier. When a function is executed, everything stops and waits for the function to finish. Think of it as a relay sport. Player 1 grabs the baton ('a') and runs his distance. Then he passes his return value to Player 2. Player 2 does his thing and on it goes. If player 2 fails down, the whole team has to wait for him to get up. Player 3 can't continue the race without the baton. > Q. return is "returning" a value (i guess that is what it is sup to do) but > where does it return a value, what is the value and where is it going. > it means 'leave this block and get back to where we started'. The value of the return is an extra parting gift. > Q. is a definition kind of like the rules the code follows in the sense > that it defines what the function name is how many parameters this function > can have "it could be" (width, height) and later on code gives arguments > "values for parameters) in the respective order. > basically. You know how to add right? Take two numbers and you end up with one number which is their result. def add(num1, num2): return num1 + num2 A function is the idea, when you call it you make it real. > okay here it goes > > Q. I pretty sure but the first section of code defines hello() as a > function and every time that function is call like this hello() it prints > the string "Hello" oh yeah this does not have a parameter because the () > have nothing in them? > correct, empty parens means no parameters. A function need not return a value, it may just have an internal action. What if you had code to lock/unlock a door: def lock(enable): if enable == True: # do something to make the door not open else: # reverse the above In programming texts, this is called a side effect. The function changes something each time it is called. a = 0 def side_effect(num): global a a += 1 return num + 1 thing = 6 thing = side_effect(thing) thing = side_effect(thing) print thing print "We changed thing %d times" % a Notice the function did not actually change thing, we did by assigning the result back to thing. However, it did modify the global variable 'a'. > Q. In the second section of code defines the function area() is given two > parameters? width and height? and like i said before I don't understand > what return does unless maybe width and height drive down in their hot rod > and pick up (w,h) and w has 4 dollars and h has 5 dollars they return to > the area's definition and are times by the code return width*height > hopefully this makes sense by now ..... > Q. in the third definition print_welcome is defined as a function with name > as its parameter it prints "Welcome", name the value of name is got with > the code print_welcome ("Fred") is this right? > yep > Q. And of course the code is read line by line and even though that is so > the output is in the order that the functions are called. right? and only > if that function makes out put (in this example with the print) but not all > functions produce output? > unless you have a control structure you start at the top and read to the bottom. Output only happens by print or some other similar structure. > I bet that was as confusing to read for ya'll as it was for me to think up. > maybe you can understand how i went wrong with some of my original notes > nah, many many people have asked these questions before. Programming is like learning a new language. You have to learn the grammar and the parts of speech and the vocabularly. Watch out for no-nos (like say double negatives in English) and remember that like in spoken language there are idioms and slang. Finally, one of the coolest parts of Python is the fact that you can play in the interpreter. python >>> def my_abs(num): ... if num < 0: ... num = -num ... return num ... >>> my_abs <function my_abs at 0x4021bcdc> >>> my_abs(6) 6 >>> my_abs(-6) 6 >>> my_abs(0) 0 Notice my_abs was defined but did nothing until I gave it some input.