From grouch at gmail.com Sat Oct 1 00:02:45 2005 From: grouch at gmail.com (Andrew P) Date: Fri, 30 Sep 2005 17:02:45 -0500 Subject: [Tutor] Book recommendations In-Reply-To: References: Message-ID: Thanks Danny. That outline of How to Solve It reminded me of an idea that resonated strongly with me in Programming Pearls, and I just looked it up and sure enough, Bentley was referencing the same Polya book: "Most of the structures exemplify what Polya calls the Inventor's Paradox in his How To Solve It: "the more general problem may be easier to solve". In programming this means that it may be harder to solve a 73-case problem directly than to write a general program to handle the N-case version, and then apply it to the case that N=73. " So, you definitely felt where I'm coming from. I've only programmed in Python and Perl, and BBC BASIC on my Amstrad NC100, but I've already intuited that procedural languages share more in common than not. So old books are fine, and Cobol and Fortran with bits next to them explaining what they do shouldn't be too hard to figure out :) Thanks again. Andrew On 9/30/05, Danny Yoo wrote: > > Hi Andrew, > > Another book that I enjoy is Gerald Weinberg's "The Psychology of Computer > Programming": > > http://www.dorsethouse.com/books/psy.html > > because when we write computer programs, we should recognize that although > technique plays a large part in a program, so does the personality behind > the keyboard. > > Weinberg's demonstrations of how people's ego come into play during the > creative act of programming are realy eye-openers, and even though the > examples in his book use *gasp* Fortran and Cobol, they're still very very > relevant. > > The mathematician George Polya wrote an excellent book on problem solving > called: "How to Solve It". Definitely look at this one; his insights into > problem solving apply very well to computer programming. An outline > summary of his book is here: > > http://www.cis.usouthal.edu/misc/polya.html > > Hope this helps! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050930/fd305f60/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Oct 1 01:14:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 30 Sep 2005 16:14:42 -0700 (PDT) Subject: [Tutor] Alan's responce frustrated beginner (fwd) Message-ID: [Rosalee] >>> I want to save this file, import it and make the changes, eggs = >>> toast, . spam = jelly and change the values if needed. [Danny] >> It sounds like you're still stuck trying to input programs into Python. >> Are you using a "programming text editor"? If not, then you may want >> to look at: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ [Rosalee] > Thanks for your help, you guys are great!!! Also, a blessing to > programming illerates like me!!! Hi Rosalee, I'm forwarding this to the other tutors here too. In general, in replies to Tutor messages, try to make sure to "Reply to All" with your email client. That way, the others can see your thanks. *grin* Anyway, I'm glad you found things out. Please feel free to continue to ask questions on Tutor! From andrade1 at umbc.edu Sat Oct 1 03:29:12 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Fri, 30 Sep 2005 21:29:12 -0400 (EDT) Subject: [Tutor] lonely snowman Message-ID: <1166.172.149.161.55.1128130152.squirrel@172.149.161.55> Hello I have a snowman who would like a nose. I have tried the following to make a triangle and all I get is a little green line. would anyone have any suggestions as to why? from graphics import * def main(): win = GraphWin("Triangle") triangle = Polygon(Point(4,8), Point(2,10), Point(6,3)) triangle.setFill("purple") triangle.setOutline("green") triangle.draw(win) win.getMouse() win.close() main() From kent37 at tds.net Sat Oct 1 03:50:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 Sep 2005 21:50:30 -0400 Subject: [Tutor] lonely snowman In-Reply-To: <1166.172.149.161.55.1128130152.squirrel@172.149.161.55> References: <1166.172.149.161.55.1128130152.squirrel@172.149.161.55> Message-ID: <433DEB66.8090300@tds.net> andrade1 at umbc.edu wrote: > Hello > > I have a snowman who would like a nose. I have tried the following to make > a triangle and all I get is a little green line. would anyone have any > suggestions as to why? > > > from graphics import * > > def main(): > win = GraphWin("Triangle") > > triangle = Polygon(Point(4,8), Point(2,10), Point(6,3)) Try making the triangle bigger and maybe you will see what is happening... triangle = Polygon(Point(40,80), ... Kent > triangle.setFill("purple") > triangle.setOutline("green") > triangle.draw(win) > > > win.getMouse() > win.close() > > main() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sat Oct 1 04:54:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 Sep 2005 22:54:21 -0400 Subject: [Tutor] More than one thing at a time? In-Reply-To: <433B2C6E.5070501@gmail.com> References: <433B2C6E.5070501@gmail.com> Message-ID: <433DFA5D.8090701@tds.net> Joseph Quigley wrote: > Hi, I've got a problem: > I've got a semi working IRC client. There's a function that is for > receiving and one for sending. How can I have a loop where I can receive > messages, yet still have a send prompt? you need to learn about threads. which I don't seem to have the energy to explain this week, but hopefully a tiny pointer helps. There have been a few discussions recently on the list. Kent From kent37 at tds.net Sat Oct 1 13:36:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Oct 2005 07:36:02 -0400 Subject: [Tutor] More than one thing at a time? In-Reply-To: <433DFA5D.8090701@tds.net> References: <433B2C6E.5070501@gmail.com> <433DFA5D.8090701@tds.net> Message-ID: <433E74A2.4030800@tds.net> Kent Johnson wrote: > Joseph Quigley wrote: > >>Hi, I've got a problem: >>I've got a semi working IRC client. There's a function that is for >>receiving and one for sending. How can I have a loop where I can receive >>messages, yet still have a send prompt? > > > you need to learn about threads. which I don't seem to have the > energy to explain this week, but hopefully a tiny pointer helps. > There have been a few discussions recently on the list. Here are a couple of tutor threads with good material about Python threads: http://mail.python.org/pipermail/tutor/2005-August/040831.html http://mail.python.org/pipermail/tutor/2004-November/033247.html Another way to do what you want is to use Twisted; this is touched on in the second thread above. Kent From zathras at thwackety.com Sat Oct 1 16:24:07 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 1 Oct 2005 15:24:07 +0100 Subject: [Tutor] More than one thing at a time? In-Reply-To: <433E74A2.4030800@tds.net> References: <433B2C6E.5070501@gmail.com> <433DFA5D.8090701@tds.net> <433E74A2.4030800@tds.net> Message-ID: <200510011524.08048.zathras@thwackety.com> On Saturday 01 October 2005 12:36, Kent Johnson wrote: > Another way to do what you want is to use Twisted; this is touched on in > the second thread above. Another way is to use Kamaelia - its' specifically aimed at making it easy for newbies (and everyone else, me especially :-) do more than one thing at a time. If you understand unix pipelines you already understand the core ideas. (or indeed, how to wire a battery to a bulb :) Though until we've had a number newbies do the mini-axon tutorial and say what they wold like to see improved (in terms of clarity, ease of use), I'd hesitate suggestng it. (People who write things have already by definition gone up the learning curve and hence can't truly evaluate ease no matter how hard they try). However logically using Kamaelia (or any other system) you have 3 concurrent activities/3 things happening at a time here: * Handling sending & receiving of data * Accepting user input to send * Displaying output from the connection In Kamaelia we would /directly/ wrap this as 3 hypothetical components with a top level that might look like this: pipeline( TkTextInputWidget(mode="lineatatime"), IRCClient(host="server", port = 6667, nick = "userid", nickinfo = "myclient 1.0", defaultChannel = "#test" ), TkDisplayWidget(), ).run() Or using a more explicit/low level description of the same system: Graphline( IRC = IRCClient(host="server", port = 6667, nick = "userid", nickinfo = "myclient 1.0", defaultChannel = "#test" ), TOIRC = TkTextInputWidget(mode="lineatatime"), FROMIRC = TkDisplayWidget(), linkages = { ("IRC", "outbox") : ("FROMIRC", "inbox"), ("TOIRC", "outbox") : ("IRC", "inbox"), } ).run() (personally I prefer the latter implementation here since it's more clear the 3 things are relatively independent rather than dependent on the start of the chain. They are both equivalent though.) We've got a nascent IRCClient component in /Sketches of our codebase, and there's display & type in code in the PipeBuilder code in /Sketches that could serve as a starting point. Writing TkDIsplayWidget should be trivial - since it's equivalent if a "hello world" program (more or less) in Tk, and the TkTextInputWidget should also be trivial since it's a matter of writing a Tk based program that allows you to say "What is your name" and have a type in box to answer. In the mainloop, the display widget would check its inbox for data, grab it and display it. The input widget would send data to it's outbox when some types something in. We'd normally recommend writing standalone small scripts for each of these interacting with stdin (instead of an inbox) and stdout (instead of an outbox) - say via "print" when writing them and then turn them into components and then wire everything together. Also aside from a tutorial on how to build the system itself (it's not really that complex) at: * http://kamaelia.sourceforge.net/MiniAxon. We've also got a tutorilal on writing components here: * http://kamaelia.sourceforge.net/cgi-bin/blog/blog.cgi?rm=viewpost&postid=1113495151 If the OP does choose to take this approach, they'd need to use a CVS checkout rather than the main release though since we haven't done a release yet including the TK stuff (Though one is imminent). One key aim of Kamaelia is to make it simple & easy to make it possible to have more than one thing at a time to be dealt with - especially with regard to networking things, so I'd //hope// that using Kamaelia here might be the easiest place to start. Hoping this was useful, Michael. From ml.cyresse at gmail.com Sun Oct 2 09:05:19 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 2 Oct 2005 20:05:19 +1300 Subject: [Tutor] Struct and UTF-16 Message-ID: Hi all, Just got a bit of confusion with trying to use struct with unicode. What's the difference between x = "Hi" y = x.encode("UTF-16") and y = unicode(x, "UTF-16") Regards, Liam Clarke From m.moghimi at gmail.com Sun Oct 2 13:22:33 2005 From: m.moghimi at gmail.com (Mohammad Moghimi) Date: Sun, 2 Oct 2005 15:22:33 +0400 Subject: [Tutor] installing pydev Message-ID: Hi I have download pydev(org.python.pydev.feature-0_9_8_2.zip) from sourceforge. Then I extract it to my eclipse directory. But When I try to create a new project, there isn't any python related project to select. I have installed python interpreter before. What is my problem and how can I fix it? should I donwload other files to install python plugin properly? -- -- Mohammad do you Python?!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051002/66b74faa/attachment.html From ajikoe at gmail.com Sun Oct 2 13:38:25 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Sun, 2 Oct 2005 13:38:25 +0200 Subject: [Tutor] installing pydev In-Reply-To: References: Message-ID: I think you should use simple project, and then add a file with extention py Cheers, pujo On 10/2/05, Mohammad Moghimi wrote: > > Hi > I have download pydev(org.python.pydev.feature-0_9_8_2.zip) from > sourceforge. Then I extract it to my eclipse directory. But When I try to > create a new project, there isn't any python related project to select. I > have installed python interpreter before. What is my problem and how can I > fix it? should I donwload other files to install python plugin properly? > > -- > -- Mohammad > do you Python?!! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051002/c64ba81d/attachment.htm From kent37 at tds.net Sun Oct 2 15:24:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Oct 2005 09:24:04 -0400 Subject: [Tutor] Struct and UTF-16 In-Reply-To: References: Message-ID: <433FDF74.30304@tds.net> Liam Clarke wrote: > What's the difference between > > x = "Hi" > y = x.encode("UTF-16") > > and > > y = unicode(x, "UTF-16") They are more-or-less opposite. encode() converts away from unicode. (Think of unicode as the 'normal' format, anything else in 'encoded'.) Normally it is used on a unicode string, not a byte string. It means, "interpret this string as unicode, then convert it to an encoded byte string using the given encoding". When you encode a non-unicode string (like "Hi"), the string is first converted to unicode (decoded) using sys.getdefaultencoding(), then encoded using the supplied encoding. So 'Hi'.encode('utf-16') is the same as 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') In either case, the result is a string in UTF-16 encoding: >>> 'Hi'.encode('UTF-16') '\xff\xfeH\x00i\x00' >>> 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') '\xff\xfeH\x00i\x00' Note that the utf-16 codec puts a byte-order mark ('\xff\xfe') in the output; then 'H' becomes 'H\x00' and 'i' becomes 'i\x00'. Because sys.getdefaultencoding() is used to convert to unicode, you will get an error if the original string cannot be decoded with this encoding: >>> '\xe3'.encode('utf-16') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) What about unicode('Hi', 'utf-16')? This doesn't do anything useful: >>> unicode('Hi', 'UTF-16') u'\u6948' unicode('Hi', 'utf-16') means the same as 'Hi'.decode('utf-16'). In this case we are saying, "Interpret this string as an encoded byte string in the given encoding, and convert it to a unicode string." Since 'Hi' is not, in fact, a byte string encoded in UTF-16, the results are not very useful. To summarize: If you have an encoded byte string and you want a unicode string, use str.decode() or unicode() If you have a unicode string and you want an encoded byte string, use unicode.encode(). If you are using str.encode() you probably haven't though through your problem completely and you will likely get UnicodeDecodeErrors when you have non-ASCII data. If you are writing a unicode-aware application, a good strategy is to keep all strings internally as unicode and to convert to and from the required encodings at the boundaries. Kent From cpu.crazy at gmail.com Sun Oct 2 16:20:36 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 02 Oct 2005 08:20:36 -0600 Subject: [Tutor] More than one thing at a time? Message-ID: <433FECB4.9070302@gmail.com> Hi Michael, You're explanation helped a lot, however, I'm really not good at gui programming and the irc client was supposed to be a console application, but: Would it be hard to just have a send texbox and receive read-only text box? I'll try this, but I think I should mention that I'm using python-irclib from sourceforge. I'll try Kamaelia, thanks a lot. Joe From 3dbernard at gmail.com Sun Oct 2 16:48:02 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Sun, 2 Oct 2005 10:48:02 -0400 Subject: [Tutor] pywin32 under Win64 Message-ID: <61d0e2b40510020748w619cf412g6dc1246c06d78335@mail.gmail.com> Hello, I'm considering switching to Windows 64bit. However I was wondering if anyone on this list have been using the pywin32 extension (or any win32com-related package/distribution for that matter) on Win64. Possibly the pywin*32* thing is making me cautious, but that not be nice if I find out I can't use the package after I have done all the OS installation :-) Thanks Bernard From dyoo at hkn.eecs.berkeley.edu Sun Oct 2 20:34:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 2 Oct 2005 11:34:41 -0700 (PDT) Subject: [Tutor] pywin32 under Win64 In-Reply-To: <61d0e2b40510020748w619cf412g6dc1246c06d78335@mail.gmail.com> Message-ID: On Sun, 2 Oct 2005, Bernard Lebel wrote: > I'm considering switching to Windows 64bit. However I was wondering if > anyone on this list have been using the pywin32 extension (or any > win32com-related package/distribution for that matter) on Win64. > Possibly the pywin*32* thing is making me cautious, but that not be nice > if I find out I can't use the package after I have done all the OS > installation :-) Hi Bernard, This is a big unknown, and specialized enough that I'd recommend asking on the python-win32 mailing list; they'd have a better idea how compatible win32api would be with 64-bit Windows. http://mail.python.org/mailman/listinfo/python-win32 Good luck! From 3dbernard at gmail.com Sun Oct 2 20:53:00 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Sun, 2 Oct 2005 14:53:00 -0400 Subject: [Tutor] pywin32 under Win64 In-Reply-To: References: <61d0e2b40510020748w619cf412g6dc1246c06d78335@mail.gmail.com> Message-ID: <61d0e2b40510021153v63f38a6dha04fe0e669c20799@mail.gmail.com> Oh, thanks Danny! Bernard On 10/2/05, Danny Yoo wrote: > > > On Sun, 2 Oct 2005, Bernard Lebel wrote: > > > I'm considering switching to Windows 64bit. However I was wondering if > > anyone on this list have been using the pywin32 extension (or any > > win32com-related package/distribution for that matter) on Win64. > > Possibly the pywin*32* thing is making me cautious, but that not be nice > > if I find out I can't use the package after I have done all the OS > > installation :-) > > Hi Bernard, > > This is a big unknown, and specialized enough that I'd recommend asking on > the python-win32 mailing list; they'd have a better idea how compatible > win32api would be with 64-bit Windows. > > http://mail.python.org/mailman/listinfo/python-win32 > > Good luck! > > From 3dbernard at gmail.com Sun Oct 2 22:52:05 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Sun, 2 Oct 2005 16:52:05 -0400 Subject: [Tutor] pywin32 under Win64 In-Reply-To: <61d0e2b40510021153v63f38a6dha04fe0e669c20799@mail.gmail.com> References: <61d0e2b40510020748w619cf412g6dc1246c06d78335@mail.gmail.com> <61d0e2b40510021153v63f38a6dha04fe0e669c20799@mail.gmail.com> Message-ID: <61d0e2b40510021352x29287c6dv6d3d43a7762d018b@mail.gmail.com> Still, anyone has tried Python on Win64? Thanks Berrnard On 10/2/05, Bernard Lebel <3dbernard at gmail.com> wrote: > Oh, thanks Danny! > > Bernard > > > On 10/2/05, Danny Yoo wrote: > > > > > > On Sun, 2 Oct 2005, Bernard Lebel wrote: > > > > > I'm considering switching to Windows 64bit. However I was wondering if > > > anyone on this list have been using the pywin32 extension (or any > > > win32com-related package/distribution for that matter) on Win64. > > > Possibly the pywin*32* thing is making me cautious, but that not be nice > > > if I find out I can't use the package after I have done all the OS > > > installation :-) > > > > Hi Bernard, > > > > This is a big unknown, and specialized enough that I'd recommend asking on > > the python-win32 mailing list; they'd have a better idea how compatible > > win32api would be with 64-bit Windows. > > > > http://mail.python.org/mailman/listinfo/python-win32 > > > > Good luck! > > > > > From zathras at thwackety.com Mon Oct 3 02:41:36 2005 From: zathras at thwackety.com (Michael Sparks) Date: Mon, 3 Oct 2005 01:41:36 +0100 Subject: [Tutor] More than one thing at a time? Message-ID: <200510030141.36474.zathras@thwackety.com> [ cc'ing the Kamaelia list in case it makes sense to move this conversation ?there. ] On Sunday 02 October 2005 15:20, Joseph Quigley wrote: > Hi Michael, > You're explanation helped a lot, however, I'm really not good at gui > programming and the irc client was supposed to be a console application, > but: Would it be hard to just have a send texbox and receive read-only > text box? It shouldn't be difficult at all really. If you find an example of a hello world program, and a "hello who are you" program, then it's just a simple matter of using that. If you're happy using pygame as a display, then you could use our Ticker component already. Example 11 shows how to use the Ticker. (Essentially though it takes text strings on it's inbox and displays them. Which gives you a read-only text box) I should've thought of it sooner though, but you //could// do this: pipeline( ? ? ConsoleReader(), ? ? IRCClient(host="server", ? ? ? ? ? ? ? ? ? ? ?port = 6667, ? ? ? ? ? ? ? ? ? ? ?nick = "userid", ? ? ? ? ? ? ? ? ? ? ?nickinfo = "myclient 1.0", ? ? ? ? ? ? ? ? ? ? ?defaultChannel = "#test" ), ? ? Ticker(background_colour=(128,48,128), ? ? ? ? ? ? ? ? ?render_left = 1, ? ? ? ? ? ? ? ? ?render_top = 1, ? ? ? ? ? ? ? ? ?render_right = 600, ? ? ? ? ? ? ? ? ?render_bottom = 200, ? ? ? ? ? ? ? ? ?position = (100, 300), ? ? ) ).run() We don't actually have a console reader component, but it's simple to knock one up. The only complicating factor here is that reading from the console can be blocking which would lock up the whole system. As a result you'd want that to be a threaded component. (The API for those needs cleaning up admittedly) However the code and simple system test for that looks like this: ################################ # Tested on my machine just now and works :-):-) from Axon.ThreadedComponent import threadedcomponent from Kamaelia.Util.ConsoleEcho import consoleEchoer from Kamaelia.Util.PipelineComponent import pipeline class ConsoleReader(threadedcomponent): ? ?def run(self): ?# Threaded components use this method instead of "main" ? ? ? while 1: ? ? ? ? ?line = raw_input() ? ? ? ? ?line = line + "\n" ? ? ? ? ?self.outqueues["outbox"].put(line) pipeline(ConsoleReader(), ? ? ? ? ?consoleEchoer() ).run() ####################### Considering we do have a nascent IRClient component in /Sketches, the Ticker exists and the above ConsoleReader exists, this might speed things up for you. > I'll try this, but I think I should mention that I'm using python-irclib > from sourceforge. I'd suggest that our IRCClient code is nowhere near complete though, and whilst I've not tried python-irclib, I'd suggest looking at our IRCClient component to see how you might want to rewrite it to use python-irclib. > I'll try Kamaelia, thanks a lot. Please do. If you're willing to wait 24 hours we're doing the 0.3 release, which is a much expanded base to work with. If you can't wait, do a cvs checkout of the whole tree - ie: mkdir kamaelia cd kamaelia ?# So easy to forget to do this, leaving clutter everywhere :-):-) cvs -d:pserver:anonymous at cvs.sourceforge.net:/cvsroot/kamaelia login cvs -z3 -d:pserver:anonymous at cvs.sourceforge.net:/cvsroot/kamaelia co -d . That'll leave you with a full check out. You'll need to then install Axon: cd Code/Python/Axon python setup.py install Similarly to install Kamaelia: cd Code/Python/Kamaelia python setup.py install You'll then find an example program using the ticker in: Code/Python/Kamaelia/Examples/example11 You might also find Code/Python/Kamaelia/Examples/example9 of interest given your query on the pygame list regarding moving pictures about. :):) It's a **simple** game designed to amuse very young children bouncing sprites around the screen. It demonstrates very simple keyboard handling as well - specifically pausing, unpausing and toggling movement. As I say to everyone who looks at Kamaelia - if you find it useful, that's great - if you have any ideas for improvement, please let us know. If you have any criticisms (postive or negative - especially if negative) please let us know. Finally if you want to share any components back to the project we'd be happy to merge them first into sketches and then into the main tree if there's a logical fit. Even a trivial component (such as the one above) has a useful place in the tree - as you can see from this reply :-):-) Best Regards, Michael. -- "Though we are not now that which in days of old moved heaven and earth, ? ?that which we are, we are: one equal temper of heroic hearts made ? ? ?weak by time and fate but strong in will to strive, to seek, ? ? ? ? ? to find and not to yield" -- "Ulysses", Tennyson From ml.cyresse at gmail.com Mon Oct 3 10:03:10 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 3 Oct 2005 21:03:10 +1300 Subject: [Tutor] Struct and UTF-16 In-Reply-To: <433FDF74.30304@tds.net> References: <433FDF74.30304@tds.net> Message-ID: Thanks Kent, My first time dealing with Python and unicode vs 'normal' strings, I do look forward to Python 3.0... at the moment I'm just trying to understand how to use UTF-16. Basically, I have data which is coming straight from struct.unpack() and it's an UTF-16 string, and I'm just trying to get my head around dealing with the data coming in from struct, and putting my data out through struct. It doesn't help overly that struct considers all strings to consist of one byte per char, whereas UTF-16 is two. And I was having trouble as to how to write UTF-16 stuff out properly. But, if I understand it correctly, I could use j = #some unicode string out = j.encode("UTF-16") pattern = "%ds" % len(out) struct.pack(pattern, out) without too much difficulty. Regards, Liam Clarke On 10/3/05, Kent Johnson wrote: > Liam Clarke wrote: > > What's the difference between > > > > x = "Hi" > > y = x.encode("UTF-16") > > > > and > > > > y = unicode(x, "UTF-16") > > They are more-or-less opposite. > > encode() converts away from unicode. (Think of unicode as the 'normal' format, anything else in 'encoded'.) Normally it is used on a unicode string, not a byte string. It means, "interpret this string as unicode, then convert it to an encoded byte string using the given encoding". > > When you encode a non-unicode string (like "Hi"), the string is first converted to unicode (decoded) using sys.getdefaultencoding(), then encoded using the supplied encoding. So > 'Hi'.encode('utf-16') > is the same as > 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') > > In either case, the result is a string in UTF-16 encoding: > >>> 'Hi'.encode('UTF-16') > '\xff\xfeH\x00i\x00' > >>> 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') > '\xff\xfeH\x00i\x00' > > Note that the utf-16 codec puts a byte-order mark ('\xff\xfe') in the output; then 'H' becomes 'H\x00' and 'i' becomes 'i\x00'. > > Because sys.getdefaultencoding() is used to convert to unicode, you will get an error if the original string cannot be decoded with this encoding: > > >>> '\xe3'.encode('utf-16') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) > > > What about unicode('Hi', 'utf-16')? This doesn't do anything useful: > >>> unicode('Hi', 'UTF-16') > u'\u6948' > > unicode('Hi', 'utf-16') means the same as 'Hi'.decode('utf-16'). In this case we are saying, "Interpret this string as an encoded byte string in the given encoding, and convert it to a unicode string." Since 'Hi' is not, in fact, a byte string encoded in UTF-16, the results are not very useful. > > > To summarize: > If you have an encoded byte string and you want a unicode string, use str.decode() or unicode() > > If you have a unicode string and you want an encoded byte string, use unicode.encode(). > > If you are using str.encode() you probably haven't though through your problem completely and you will likely get UnicodeDecodeErrors when you have non-ASCII data. > > > If you are writing a unicode-aware application, a good strategy is to keep all strings internally as unicode and to convert to and from the required encodings at the boundaries. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lists at olivermaunder.co.uk Mon Oct 3 11:10:07 2005 From: lists at olivermaunder.co.uk (Oliver Maunder) Date: Mon, 3 Oct 2005 10:10:07 +0100 Subject: [Tutor] Finding libraries Message-ID: Hi all I'm pretty new to Python - I've worked through Dive Into Python, but not done a lot else. One thing I have realised is that pretty much whatever you want to do in Python, someone else has already done it and stuck it in a library. My question is, how do you find these libraries. Here's an example - I want to write a program that downloads large files from a website and stores them in a specified directory - preferably with some kind of progress indicator. I'm pretty sure I can do this with urllib, sgmllib (or just regular expressions to extract the links), basic python file handling, and maybe some threading so I can download more than one file at a time. Should be straightforward, but I don't want to do it only to find there's a module with a get_file_from_web(url, destination, progress_callback) function in it. So, what ways are there to find out which modules are out there (other than reading this list, which I'm already doing)? Also, does anyone have specific suggestions for the program I'm working on? Thanks for your help Olly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051003/544c444f/attachment.html From ml.cyresse at gmail.com Mon Oct 3 11:50:31 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 3 Oct 2005 22:50:31 +1300 Subject: [Tutor] Struct and UTF-16 In-Reply-To: References: <433FDF74.30304@tds.net> Message-ID: Hi, If I can just beat this horse one more time, can I just get confirmation that I'm going about this the right way? I have a base object, which reads the unicode string as bytes like so, this ignores all but important bits. class Mhod: def __init__(self, f): self.payload = struct.unpack("36s", f.read(36)) Which in turn, is utilised in a Song object, which works like this - class Song: def __init__(self, mhod): self.location = unicode(mhod.payload, "UTF-16") self.mhod = mhod def gLoc(self): return self.location def sLoc(self, value): #Need to coerce data into UTF-16 here self.mhod.payload = value.encode("UTF-16") location = property(gLoc, sLoc) If I were to do a >>>x = Mhod(open("test", "rb")) >>>y = Song(x) I get >>>x.payload ':\x00i\x00P\x00o\x00d\x00_\x00C\x00o\x00n\x00t\x00r\x00o\x00l \x00:\x00M\x00u\x00s\x00i\x00c\x00:\x00F\x004\x004\x00:\x00L \x00W\x00B\x00R\x00.\x00m\x00p\x003\x00' #Line breaks added. >>>y.location u':iPod_Control:Music:F44:LWBR.mp3' Which is what I'm after. What I'm struggling with is coercing the string that's being passed to sLoc() into UTF-16, and actually creating any form of unicode string at all without using >>>foo = u'Monkies!' Which I'm sure is going to be in UTF-8, just to spite me. So far, the best I've come up with is - >>> foo = unicode("Hi Bob!".encode("UTF-16"), "UTF-16") Which, as you mention above, is likely to cause me errors. And apparently "Hi Bob!" is an 8 bit string encoded in UTF-16... *sigh* I suppose I could go the XP route and expect any further users to just deal with it and pass in a UTF-16 string, but there's got to be a simple way to handle it., and I'm not having too much luck with this. I've been working from the below document, if anyone can recommend something further, I'd much appreciate it. http://www.amk.ca/python/howto/unicode Regards, Liam Clarke On 10/3/05, Liam Clarke wrote: > Thanks Kent, > > My first time dealing with Python and unicode vs 'normal' strings, I > do look forward to Python 3.0... at the moment I'm just trying to > understand how to use UTF-16. > > Basically, I have data which is coming straight from struct.unpack() > and it's an UTF-16 string, and I'm just trying to get my head around > dealing with the data coming in from struct, and putting my data out > through struct. > > It doesn't help overly that struct considers all strings to consist of > one byte per char, whereas UTF-16 is two. And I was having trouble as > to how to write UTF-16 stuff out properly. > > But, if I understand it correctly, I could use > > j = #some unicode string > out = j.encode("UTF-16") > pattern = "%ds" % len(out) > struct.pack(pattern, out) > > without too much difficulty. > > Regards, > > Liam Clarke > > On 10/3/05, Kent Johnson wrote: > > Liam Clarke wrote: > > > What's the difference between > > > > > > x = "Hi" > > > y = x.encode("UTF-16") > > > > > > and > > > > > > y = unicode(x, "UTF-16") > > > > They are more-or-less opposite. > > > > encode() converts away from unicode. (Think of unicode as the 'normal' format, anything else in 'encoded'.) Normally it is used on a unicode string, not a byte string. It means, "interpret this string as unicode, then convert it to an encoded byte string using the given encoding". > > > > When you encode a non-unicode string (like "Hi"), the string is first converted to unicode (decoded) using sys.getdefaultencoding(), then encoded using the supplied encoding. So > > 'Hi'.encode('utf-16') > > is the same as > > 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') > > > > In either case, the result is a string in UTF-16 encoding: > > >>> 'Hi'.encode('UTF-16') > > '\xff\xfeH\x00i\x00' > > >>> 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') > > '\xff\xfeH\x00i\x00' > > > > Note that the utf-16 codec puts a byte-order mark ('\xff\xfe') in the output; then 'H' becomes 'H\x00' and 'i' becomes 'i\x00'. > > > > Because sys.getdefaultencoding() is used to convert to unicode, you will get an error if the original string cannot be decoded with this encoding: > > > > >>> '\xe3'.encode('utf-16') > > Traceback (most recent call last): > > File "", line 1, in ? > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) > > > > > > What about unicode('Hi', 'utf-16')? This doesn't do anything useful: > > >>> unicode('Hi', 'UTF-16') > > u'\u6948' > > > > unicode('Hi', 'utf-16') means the same as 'Hi'.decode('utf-16'). In this case we are saying, "Interpret this string as an encoded byte string in the given encoding, and convert it to a unicode string." Since 'Hi' is not, in fact, a byte string encoded in UTF-16, the results are not very useful. > > > > > > To summarize: > > If you have an encoded byte string and you want a unicode string, use str.decode() or unicode() > > > > If you have a unicode string and you want an encoded byte string, use unicode.encode(). > > > > If you are using str.encode() you probably haven't though through your problem completely and you will likely get UnicodeDecodeErrors when you have non-ASCII data. > > > > > > If you are writing a unicode-aware application, a good strategy is to keep all strings internally as unicode and to convert to and from the required encodings at the boundaries. > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From ml.cyresse at gmail.com Mon Oct 3 11:53:21 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 3 Oct 2005 22:53:21 +1300 Subject: [Tutor] Finding libraries In-Reply-To: References: Message-ID: Hi Olly, I'd recommend http://www.python.org/pypi and http://www.vex.net/parnassus/ Regards, Liam Clarke On 10/3/05, Oliver Maunder wrote: > Hi all > > I'm pretty new to Python - I've worked through Dive Into Python, but not > done a lot else. One thing I have realised is that pretty much whatever you > want to do in Python, someone else has already done it and stuck it in a > library. My question is, how do you find these libraries. > > Here's an example - I want to write a program that downloads large files > from a website and stores them in a specified directory - preferably with > some kind of progress indicator. I'm pretty sure I can do this with urllib, > sgmllib (or just regular expressions to extract the links), basic python > file handling, and maybe some threading so I can download more than one file > at a time. Should be straightforward, but I don't want to do it only to find > there's a module with a get_file_from_web(url, destination, > progress_callback) function in it. > > So, what ways are there to find out which modules are out there (other than > reading this list, which I'm already doing)? Also, does anyone have specific > suggestions for the program I'm working on? > > Thanks for your help > > Olly > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Mon Oct 3 12:07:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Oct 2005 06:07:38 -0400 Subject: [Tutor] Struct and UTF-16 In-Reply-To: References: <433FDF74.30304@tds.net> Message-ID: <434102EA.20301@tds.net> Liam Clarke wrote: > Basically, I have data which is coming straight from struct.unpack() > and it's an UTF-16 string, and I'm just trying to get my head around > dealing with the data coming in from struct, and putting my data out > through struct. > > It doesn't help overly that struct considers all strings to consist of > one byte per char, whereas UTF-16 is two. And I was having trouble as > to how to write UTF-16 stuff out properly. > > But, if I understand it correctly, I could use > > j = #some unicode string > out = j.encode("UTF-16") > pattern = "%ds" % len(out) > struct.pack(pattern, out) Yes that looks good. Note that you will get a byte-order-mark as the first two bytes. If you don't want that, use utf-16le or utf-16be. The correct choice depends on what the consumer of the data expects / can deal with. >>> 'Hi'.encode('utf-16le') 'H\x00i\x00' >>> 'Hi'.encode('utf-16be') '\x00H\x00i' >>> 'Hi'.encode('utf-16') '\xff\xfeH\x00i\x00' Kent From ml.cyresse at gmail.com Mon Oct 3 12:11:04 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 3 Oct 2005 23:11:04 +1300 Subject: [Tutor] Struct and UTF-16 In-Reply-To: References: <433FDF74.30304@tds.net> Message-ID: OK, one last kick. So, using val = unicode(value) self._slaveMap[attr].setPayload(value.encode("UTF-16")) I can stick normal strings in happily. Of course, as you mentioned, Kent, this leaves me vulnerable if the string differs to sys.getdefaultencoding(). Other than directly from the user, the most likely source of data will be from pyid3lib, which for the time being assumes all strings are ISO-8859-1. http://pyid3lib.sourceforge.net Erk. Talk about big design up front. Would you recommend a different method of dealing with this? Basically, most of the strings in the database are UTF-16, and I just need to make them readable, and make sure any of the strings going in are UTF-16 as well. Alternatively, I've thought about just cycling through the various 100 codecs until I don't get any UnicodeDecodeErrors, but that's no guarantee that it'll be human readble...oh dear. Thanks for any assistance offered. Liam Clarke On 10/3/05, Liam Clarke wrote: > Hi, > > If I can just beat this horse one more time, can I just get > confirmation that I'm going about this the right way? > > I have a base object, which reads the unicode string as bytes like so, > this ignores all but important bits. > > class Mhod: > def __init__(self, f): > self.payload = struct.unpack("36s", f.read(36)) > > Which in turn, is utilised in a Song object, which works like this - > > class Song: > def __init__(self, mhod): > self.location = unicode(mhod.payload, "UTF-16") > self.mhod = mhod > def gLoc(self): > return self.location > def sLoc(self, value): > #Need to coerce data into UTF-16 here > self.mhod.payload = value.encode("UTF-16") > > location = property(gLoc, sLoc) > > If I were to do a > > >>>x = Mhod(open("test", "rb")) > >>>y = Song(x) > > I get > > >>>x.payload > ':\x00i\x00P\x00o\x00d\x00_\x00C\x00o\x00n\x00t\x00r\x00o\x00l > \x00:\x00M\x00u\x00s\x00i\x00c\x00:\x00F\x004\x004\x00:\x00L > \x00W\x00B\x00R\x00.\x00m\x00p\x003\x00' #Line breaks added. > > >>>y.location > u':iPod_Control:Music:F44:LWBR.mp3' > > Which is what I'm after. What I'm struggling with is coercing the > string that's being passed to sLoc() into UTF-16, and actually > creating any form of unicode string at all without using > > >>>foo = u'Monkies!' > > Which I'm sure is going to be in UTF-8, just to spite me. > > So far, the best I've come up with is - > > >>> foo = unicode("Hi Bob!".encode("UTF-16"), "UTF-16") > > Which, as you mention above, is likely to cause me errors. And > apparently "Hi Bob!" is an 8 bit string encoded in UTF-16... > *sigh* I suppose I could go the XP route and expect any further users > to just deal with it and pass in a UTF-16 string, but there's got to > be a simple way to handle it., and I'm not having too much luck with > this. > > I've been working from the below document, if anyone can recommend > something further, I'd much appreciate it. > > http://www.amk.ca/python/howto/unicode > > Regards, > > Liam Clarke > On 10/3/05, Liam Clarke wrote: > > Thanks Kent, > > > > My first time dealing with Python and unicode vs 'normal' strings, I > > do look forward to Python 3.0... at the moment I'm just trying to > > understand how to use UTF-16. > > > > Basically, I have data which is coming straight from struct.unpack() > > and it's an UTF-16 string, and I'm just trying to get my head around > > dealing with the data coming in from struct, and putting my data out > > through struct. > > > > It doesn't help overly that struct considers all strings to consist of > > one byte per char, whereas UTF-16 is two. And I was having trouble as > > to how to write UTF-16 stuff out properly. > > > > But, if I understand it correctly, I could use > > > > j = #some unicode string > > out = j.encode("UTF-16") > > pattern = "%ds" % len(out) > > struct.pack(pattern, out) > > > > without too much difficulty. > > > > Regards, > > > > Liam Clarke > > > > On 10/3/05, Kent Johnson wrote: > > > Liam Clarke wrote: > > > > What's the difference between > > > > > > > > x = "Hi" > > > > y = x.encode("UTF-16") > > > > > > > > and > > > > > > > > y = unicode(x, "UTF-16") > > > > > > They are more-or-less opposite. > > > > > > encode() converts away from unicode. (Think of unicode as the 'normal' format, anything else in 'encoded'.) Normally it is used on a unicode string, not a byte string. It means, "interpret this string as unicode, then convert it to an encoded byte string using the given encoding". > > > > > > When you encode a non-unicode string (like "Hi"), the string is first converted to unicode (decoded) using sys.getdefaultencoding(), then encoded using the supplied encoding. So > > > 'Hi'.encode('utf-16') > > > is the same as > > > 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') > > > > > > In either case, the result is a string in UTF-16 encoding: > > > >>> 'Hi'.encode('UTF-16') > > > '\xff\xfeH\x00i\x00' > > > >>> 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') > > > '\xff\xfeH\x00i\x00' > > > > > > Note that the utf-16 codec puts a byte-order mark ('\xff\xfe') in the output; then 'H' becomes 'H\x00' and 'i' becomes 'i\x00'. > > > > > > Because sys.getdefaultencoding() is used to convert to unicode, you will get an error if the original string cannot be decoded with this encoding: > > > > > > >>> '\xe3'.encode('utf-16') > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) > > > > > > > > > What about unicode('Hi', 'utf-16')? This doesn't do anything useful: > > > >>> unicode('Hi', 'UTF-16') > > > u'\u6948' > > > > > > unicode('Hi', 'utf-16') means the same as 'Hi'.decode('utf-16'). In this case we are saying, "Interpret this string as an encoded byte string in the given encoding, and convert it to a unicode string." Since 'Hi' is not, in fact, a byte string encoded in UTF-16, the results are not very useful. > > > > > > > > > To summarize: > > > If you have an encoded byte string and you want a unicode string, use str.decode() or unicode() > > > > > > If you have a unicode string and you want an encoded byte string, use unicode.encode(). > > > > > > If you are using str.encode() you probably haven't though through your problem completely and you will likely get UnicodeDecodeErrors when you have non-ASCII data. > > > > > > > > > If you are writing a unicode-aware application, a good strategy is to keep all strings internally as unicode and to convert to and from the required encodings at the boundaries. > > > > > > Kent > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > From ml.cyresse at gmail.com Mon Oct 3 12:18:46 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 3 Oct 2005 23:18:46 +1300 Subject: [Tutor] Struct and UTF-16 In-Reply-To: References: <433FDF74.30304@tds.net> Message-ID: Hmm, looking at this, it seems I'm not the only one with this sort of problem. http://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf Maybe I will just build a wall around these objects and declare "none but unicode shall pass." On 10/3/05, Liam Clarke wrote: > OK, one last kick. > > So, using > > val = unicode(value) > self._slaveMap[attr].setPayload(value.encode("UTF-16")) > > I can stick normal strings in happily. Of course, as you mentioned, > Kent, this leaves me vulnerable if the string differs to > sys.getdefaultencoding(). > > Other than directly from the user, the most likely source of data will > be from pyid3lib, which for the time being assumes all strings are > ISO-8859-1. > > http://pyid3lib.sourceforge.net > > Erk. Talk about big design up front. Would you recommend a different > method of dealing with this? Basically, most of the strings in the > database are UTF-16, and I just need to make them readable, and make > sure any of the strings going in are UTF-16 as well. > > Alternatively, I've thought about just cycling through the various 100 > codecs until I don't get any UnicodeDecodeErrors, but that's no > guarantee that it'll be human readble...oh dear. > > Thanks for any assistance offered. > > Liam Clarke > > On 10/3/05, Liam Clarke wrote: > > Hi, > > > > If I can just beat this horse one more time, can I just get > > confirmation that I'm going about this the right way? > > > > I have a base object, which reads the unicode string as bytes like so, > > this ignores all but important bits. > > > > class Mhod: > > def __init__(self, f): > > self.payload = struct.unpack("36s", f.read(36)) > > > > Which in turn, is utilised in a Song object, which works like this - > > > > class Song: > > def __init__(self, mhod): > > self.location = unicode(mhod.payload, "UTF-16") > > self.mhod = mhod > > def gLoc(self): > > return self.location > > def sLoc(self, value): > > #Need to coerce data into UTF-16 here > > self.mhod.payload = value.encode("UTF-16") > > > > location = property(gLoc, sLoc) > > > > If I were to do a > > > > >>>x = Mhod(open("test", "rb")) > > >>>y = Song(x) > > > > I get > > > > >>>x.payload > > ':\x00i\x00P\x00o\x00d\x00_\x00C\x00o\x00n\x00t\x00r\x00o\x00l > > \x00:\x00M\x00u\x00s\x00i\x00c\x00:\x00F\x004\x004\x00:\x00L > > \x00W\x00B\x00R\x00.\x00m\x00p\x003\x00' #Line breaks added. > > > > >>>y.location > > u':iPod_Control:Music:F44:LWBR.mp3' > > > > Which is what I'm after. What I'm struggling with is coercing the > > string that's being passed to sLoc() into UTF-16, and actually > > creating any form of unicode string at all without using > > > > >>>foo = u'Monkies!' > > > > Which I'm sure is going to be in UTF-8, just to spite me. > > > > So far, the best I've come up with is - > > > > >>> foo = unicode("Hi Bob!".encode("UTF-16"), "UTF-16") > > > > Which, as you mention above, is likely to cause me errors. And > > apparently "Hi Bob!" is an 8 bit string encoded in UTF-16... > > *sigh* I suppose I could go the XP route and expect any further users > > to just deal with it and pass in a UTF-16 string, but there's got to > > be a simple way to handle it., and I'm not having too much luck with > > this. > > > > I've been working from the below document, if anyone can recommend > > something further, I'd much appreciate it. > > > > http://www.amk.ca/python/howto/unicode > > > > Regards, > > > > Liam Clarke > > On 10/3/05, Liam Clarke wrote: > > > Thanks Kent, > > > > > > My first time dealing with Python and unicode vs 'normal' strings, I > > > do look forward to Python 3.0... at the moment I'm just trying to > > > understand how to use UTF-16. > > > > > > Basically, I have data which is coming straight from struct.unpack() > > > and it's an UTF-16 string, and I'm just trying to get my head around > > > dealing with the data coming in from struct, and putting my data out > > > through struct. > > > > > > It doesn't help overly that struct considers all strings to consist of > > > one byte per char, whereas UTF-16 is two. And I was having trouble as > > > to how to write UTF-16 stuff out properly. > > > > > > But, if I understand it correctly, I could use > > > > > > j = #some unicode string > > > out = j.encode("UTF-16") > > > pattern = "%ds" % len(out) > > > struct.pack(pattern, out) > > > > > > without too much difficulty. > > > > > > Regards, > > > > > > Liam Clarke > > > > > > On 10/3/05, Kent Johnson wrote: > > > > Liam Clarke wrote: > > > > > What's the difference between > > > > > > > > > > x = "Hi" > > > > > y = x.encode("UTF-16") > > > > > > > > > > and > > > > > > > > > > y = unicode(x, "UTF-16") > > > > > > > > They are more-or-less opposite. > > > > > > > > encode() converts away from unicode. (Think of unicode as the 'normal' format, anything else in 'encoded'.) Normally it is used on a unicode string, not a byte string. It means, "interpret this string as unicode, then convert it to an encoded byte string using the given encoding". > > > > > > > > When you encode a non-unicode string (like "Hi"), the string is first converted to unicode (decoded) using sys.getdefaultencoding(), then encoded using the supplied encoding. So > > > > 'Hi'.encode('utf-16') > > > > is the same as > > > > 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') > > > > > > > > In either case, the result is a string in UTF-16 encoding: > > > > >>> 'Hi'.encode('UTF-16') > > > > '\xff\xfeH\x00i\x00' > > > > >>> 'Hi'.decode(sys.getdefaultencoding()).encode('utf-16') > > > > '\xff\xfeH\x00i\x00' > > > > > > > > Note that the utf-16 codec puts a byte-order mark ('\xff\xfe') in the output; then 'H' becomes 'H\x00' and 'i' becomes 'i\x00'. > > > > > > > > Because sys.getdefaultencoding() is used to convert to unicode, you will get an error if the original string cannot be decoded with this encoding: > > > > > > > > >>> '\xe3'.encode('utf-16') > > > > Traceback (most recent call last): > > > > File "", line 1, in ? > > > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) > > > > > > > > > > > > What about unicode('Hi', 'utf-16')? This doesn't do anything useful: > > > > >>> unicode('Hi', 'UTF-16') > > > > u'\u6948' > > > > > > > > unicode('Hi', 'utf-16') means the same as 'Hi'.decode('utf-16'). In this case we are saying, "Interpret this string as an encoded byte string in the given encoding, and convert it to a unicode string." Since 'Hi' is not, in fact, a byte string encoded in UTF-16, the results are not very useful. > > > > > > > > > > > > To summarize: > > > > If you have an encoded byte string and you want a unicode string, use str.decode() or unicode() > > > > > > > > If you have a unicode string and you want an encoded byte string, use unicode.encode(). > > > > > > > > If you are using str.encode() you probably haven't though through your problem completely and you will likely get UnicodeDecodeErrors when you have non-ASCII data. > > > > > > > > > > > > If you are writing a unicode-aware application, a good strategy is to keep all strings internally as unicode and to convert to and from the required encodings at the boundaries. > > > > > > > > Kent > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > From kent37 at tds.net Mon Oct 3 12:20:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Oct 2005 06:20:24 -0400 Subject: [Tutor] Finding libraries In-Reply-To: References: Message-ID: <434105E8.5040701@tds.net> Oliver Maunder wrote: > Hi all > > I'm pretty new to Python - I've worked through Dive Into Python, but not > done a lot else. One thing I have realised is that pretty much whatever > you want to do in Python, someone else has already done it and stuck it > in a library. My question is, how do you find these libraries. I usually google for 'python' plus some keywords describing the problem. Searching comp.lang.python also works. And feel free to ask here or on c.l.python. > Here's an example - I want to write a program that downloads large files > from a website and stores them in a specified directory - preferably > with some kind of progress indicator. I'm pretty sure I can do this with > urllib, sgmllib (or just regular expressions to extract the links), > basic python file handling, and maybe some threading so I can download > more than one file at a time. Should be straightforward, but I don't > want to do it only to find there's a module with a > get_file_from_web(url, destination, progress_callback) function in it. That is spelled urllib.urlretrieve(url, destination, progress_callback) :-) Also Naja http://www.keyphrene.com/products/naja/ Kent From kent37 at tds.net Mon Oct 3 12:38:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Oct 2005 06:38:47 -0400 Subject: [Tutor] Struct and UTF-16 In-Reply-To: References: <433FDF74.30304@tds.net> Message-ID: <43410A37.6050909@tds.net> Liam Clarke wrote: > I have a base object, which reads the unicode string as bytes like so, > this ignores all but important bits. > > class Mhod: > def __init__(self, f): > self.payload = struct.unpack("36s", f.read(36)) > > Which in turn, is utilised in a Song object, which works like this - > > class Song: > def __init__(self, mhod): > self.location = unicode(mhod.payload, "UTF-16") > self.mhod = mhod > def gLoc(self): > return self.location > def sLoc(self, value): > #Need to coerce data into UTF-16 here > self.mhod.payload = value.encode("UTF-16") I'm confused about what sLoc is supposed to do. Shouldn't it be setting self.location? ISTM sLoc should parallel what __init__ does. What is value here? If it is an Mhod then you should just do self.location = unicode(mhod.payload, "UTF-16") again. OTOH if you are trying to modify Mhod.payload then you should make a method in mhod and (assuming value is ascii texs) it should be something like self.payload = unicode(value, 'ascii').encode('UTF-16') (though see my previous reply about utf-16 vs utf-16be and utf-16le) > > location = property(gLoc, sLoc) > > If I were to do a > > >>>>x = Mhod(open("test", "rb")) >>>>y = Song(x) > > > I get > > >>>>x.payload > > ':\x00i\x00P\x00o\x00d\x00_\x00C\x00o\x00n\x00t\x00r\x00o\x00l > \x00:\x00M\x00u\x00s\x00i\x00c\x00:\x00F\x004\x004\x00:\x00L > \x00W\x00B\x00R\x00.\x00m\x00p\x003\x00' #Line breaks added. This is utf-16le > > >>>>y.location > > u':iPod_Control:Music:F44:LWBR.mp3' > > Which is what I'm after. What I'm struggling with is coercing the > string that's being passed to sLoc() into UTF-16, and actually > creating any form of unicode string at all without using > > >>>>foo = u'Monkies!' > > > Which I'm sure is going to be in UTF-8, just to spite me. No, it will be a unicode string, and what's wrong with that as a way to create a unicode string anyway? > > So far, the best I've come up with is - > > >>>>foo = unicode("Hi Bob!".encode("UTF-16"), "UTF-16") You are still confused about when to use encode vs decode encode goes *away* from unicode decode goes *towards* unicode So any of these will work: foo = u'Hi Bob!' foo = 'Hi Bob!'.decode('ascii') foo = unicode('Hi Bob!', 'ascii') and, assuming sys.defaultencoding is set to 'ascii', the last can be written foo = unicode('Hi Bob!') > Which, as you mention above, is likely to cause me errors. And > apparently "Hi Bob!" is an 8 bit string encoded in UTF-16... No, what gives you that idea? It is an 8-bit string encoded in ASCII. > *sigh* I suppose I could go the XP route and expect any further users > to just deal with it and pass in a UTF-16 string, but there's got to > be a simple way to handle it., and I'm not having too much luck with > this. > > I've been working from the below document, if anyone can recommend > something further, I'd much appreciate it. > > http://www.amk.ca/python/howto/unicode The references are good too, particularly Roman Czyborra wrote another explanation of Unicode's basic principles; it's at . Czyborra has written a number of other Unicode-related documentation, available from . Two other good introductory articles were written by Joel Spolsky and Jason Orendorff . If this introduction didn't make things clear to you, you should try reading one of these alternate articles before continuing. And my own essay has more references at the end: http://personalpages.tds.net/~kent37/blog/stories/14.html Keep trying, eventually the mists will clear...this is confusing stuff. Kent From jramirez08063 at yahoo.com Mon Oct 3 12:41:30 2005 From: jramirez08063 at yahoo.com (Pepe Pena) Date: Mon, 3 Oct 2005 03:41:30 -0700 (PDT) Subject: [Tutor] Load PDF Message-ID: <20051003104130.61589.qmail@web35001.mail.mud.yahoo.com> Hello, I am attempting to load a pdf file programatically within Adobe Reader using the Adobe Acrobat 7.0 Browser Control Type Library. If I run this code PythonWin terminates abruptly, can anyone suggest any changes I should make to the following lines of code, thanks. import win32com.client test = win32com.client.Dispatch("AcroPDF.PDF.1") test.LoadFile("D:\\sql.pdf") --------------------------------- Yahoo! for Good Click here to donate to the Hurricane Katrina relief effort. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051003/ce2365b2/attachment.htm From ml.cyresse at gmail.com Mon Oct 3 13:03:07 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 4 Oct 2005 00:03:07 +1300 Subject: [Tutor] Struct and UTF-16 In-Reply-To: <43410A37.6050909@tds.net> References: <433FDF74.30304@tds.net> <43410A37.6050909@tds.net> Message-ID: Hi Kent, > > return self.location > > def sLoc(self, value): > > #Need to coerce data into UTF-16 here > > self.mhod.payload = value.encode("UTF-16") > > I'm confused about what sLoc is supposed to do. Shouldn't it be setting self.location? ISTM sLoc should parallel what __init__ does. What is value here? If it is an Mhod then you should just do > self.location = unicode(mhod.payload, "UTF-16") > again. Sorry, that's some bad typos. Value should be val, but I've changed that anyway. Yeah, sLoc should set self.location, but I also want it to feed the "'\xff\xfe:\x00i\x00P\x00o\x00d\x00_\x00C" string into the Mhod object to be written out into a binary file later. Using if not isinstance(value, unicode): value = unicode(value) self.mhod.setPayload(value.encode("UTF-16")) seems to do the job nicely, so far for my limited test runs. Basically, I want the Mhod object to be naive as to what encoding the data it's carrying is, so I want all encoding/decoding issues handled at the Song object level. > self.payload = unicode(value, 'ascii').encode('UTF-16') > (though see my previous reply about utf-16 vs utf-16be and utf-16le) > >>>>x.payload > > > > ':\x00i\x00P\x00o\x00d\x00_\x00C\x00o\x00n\x00t\x00r\x00o\x00l > > \x00:\x00M\x00u\x00s\x00i\x00c\x00:\x00F\x004\x004\x00:\x00L > > \x00W\x00B\x00R\x00.\x00m\x00p\x003\x00' #Line breaks added. > > This is utf-16le Hmm... interesting. As I may have mentioned, the knowledge of the file structure I'm working with is incomplete. Thanks for that. > > Which, as you mention above, is likely to cause me errors. And > > apparently "Hi Bob!" is an 8 bit string encoded in UTF-16... > > No, what gives you that idea? It is an 8-bit string encoded in ASCII. Oops, sorry, it's all becoming clear now. >You are still confused about when to use encode vs decode >encode goes *away* from unicode >decode goes *towards* unicode I can't believe how dense I am. I think I'll blow that up and stick it on my wall, for any further Unicode work. (I'd like to blame the fact that I'm giving up smoking, but it was just me not seeing the wood for the trees.) > The references are good too, particularly > Roman Czyborra wrote another explanation of Unicode's basic principles; it's at . Czyborra has written a number of other Unicode-related documentation, available from . > > Two other good introductory articles were written by Joel Spolsky and Jason Orendorff . If this introduction didn't make things clear to you, you should try reading one of these alternate articles before continuing. > > And my own essay has more references at the end: > http://personalpages.tds.net/~kent37/blog/stories/14.html > > Keep trying, eventually the mists will clear...this is confusing stuff. Thanks, I've got some light reading for work tomorrow. *grin* As for the confusion, much thanks for your patience and effort, it's making a lot more sense now. I can see potential problems with converting unexpected encodings to unicode, but according to what I'm reading, that seems to be an issue that's not easily resolved, so hey, I can rest easy that I'm not alone, and while I wait for the 0.01% when it throws an error, work out a way to fix it, patent it and try to make millions by suing anyone who incorporates it into an open-source project, just like SCO. ;-) Thanks once again, Liam Clarke From kent37 at tds.net Mon Oct 3 14:10:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Oct 2005 08:10:14 -0400 Subject: [Tutor] Struct and UTF-16 In-Reply-To: References: <433FDF74.30304@tds.net> Message-ID: <43411FA6.5090601@tds.net> Liam Clarke wrote: > So, using > > val = unicode(value) > self._slaveMap[attr].setPayload(value.encode("UTF-16")) > > I can stick normal strings in happily. Of course, as you mentioned, > Kent, this leaves me vulnerable if the string differs to > sys.getdefaultencoding(). > > Other than directly from the user, the most likely source of data will > be from pyid3lib, which for the time being assumes all strings are > ISO-8859-1. You can decode with iso-8859-1 instead of ascii: val = unicode(value, 'iso-8859-1') self._slaveMap[attr].setPayload(value.encode("UTF-16")) you could even allow client code to tell you the encoding: def setPayload(self, val, encoding='iso-8859-1'): if not isinstance(value, unicode): value = unicode(value, encoding) self._slaveMap[attr].setPayload(value.encode("UTF-16")) Kent From webmeister8f at web.de Mon Oct 3 15:01:11 2005 From: webmeister8f at web.de (webmeister8f@web.de) Date: Mon, 03 Oct 2005 15:01:11 +0200 Subject: [Tutor] icq library Message-ID: <433254550@web.de> Is there an library to communicate with an ICQ-server including the most important features line sending and receiving messages? I have already searched with google but i am not really able to find exactrly that what i'm looking for. I hope you can help me, tobias. --- I hope my english is not too bad, i'm not an native speaker ______________________________________________________________ Verschicken Sie romantische, coole und witzige Bilder per SMS! Jetzt bei WEB.DE FreeMail: http://f.web.de/?mc=021193 From RPhillips at engineer.co.summit.oh.us Mon Oct 3 16:17:10 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Mon, 03 Oct 2005 10:17:10 -0400 Subject: [Tutor] Thanks, you prevented "Coder's Remorse" Message-ID: Thanks to everyone who responded to my "Prevent Coder's Remorse" posting; the result of combining the ideas that you contributed is below. It's a little long, but I'm delighted with it so far, and maybe someone else can use it. It's nice for representing a sparse table, where all the records share columns, but a lot of the values in any given column are the same. Geographic points (my original question) are just a special case. One example is a table where the Null value isn't predefined but is represented by a 'magic value' that means null in that table. I realize now that I might have been better off just to use a database; they know all about nulls, tables. types, defaults, etc. Still, I learned a LOT. So, no remorse! Thanks again, Ron #magicvaluetable.py ################################### # -*- coding: utf-8 -*- #may use a guid to keep things straight import guid # Make it work with Python 2.3 try: set except NameError: from sets import Set as set class MVTRecord(dict): """A record belonging to a magic value table (MVTable). Requires a parent MVTable and an id assigned by it. Other attributes (column values) may be assigned. Attributes not specifically assigned at the record level are deferred to the parent MVTable's attDict.""" def __init__(self,mvtParent,id,**args): dict.__init__(self) self.mvtParent = mvtParent self.id = id for arg in args: self[arg]=args[arg] def __getitem__(self, key): if key in self.keys(): return dict.__getitem__(self, key) else: return self.mvtParent.attDict[key] raise KeyError,'Key "%s" was not found in MVTRecord or MVTable'%key def __setitem__(self, key, value): (nullValue,valueType)=self.__testType(value) if key not in self.mvtParent.attDict.keys(): self.mvtParent.addAttribute(key,nullValue) (whoCares,columnType)=self.__testType(self.mvtParent.attDict[key]) # make sure what's set is proper type or can degrade to proper type if valueType == columnType: dict.__setitem__(self, key, value) else: if columnType == 'float'and valueType=='int': dict.__setitem__(self, key, float(value)) elif columnType == 'string': dict.__setitem__(self, key, str(value)) else: msg = 'The %s attribute requires %s data'%(key, columnType) raise ValueError,msg def __delitem__(self, key): if key in self.keys(): dict.__delitem__(self, key) elif key in self.mvtParent.attDict.keys(): pass else: raise KeyError,'Key "%s" was not found in MVTRecord or MVTable'%key def __testType(self, value): try: if str(value)==str(int(value)): test = (self.mvtParent.nullInt,'int') else: test = (self.mvtParent.nullFloat,'float') except ValueError: test=(self.mvtParent.nullString,'string') return test class MVTable(object): """Defines a group of records (MVTRecord) with common columns. Attributes (record values in a given column) which are not specified at the record level are deferred to the MVTable attDict. Note: the nullInt, nullFloat, and nullString are designed to hold 'magic values' for use with data structures(CSV, DBF) having no defined 'null'.""" def __init__(self, nullInt=0, nullFloat=0.0, nullString='null'): self.nullInt=nullInt self.nullFloat = nullFloat self.nullString = nullString self.attDict = {} self.membersDict = {} def addMember(self,id=None,**args): if not id: id = guid.generate() self.membersDict[id]=MVTRecord(self,id=id,**args) return self.membersDict[id] def delMember(self,member): del self.membersDict[member.id] def addAttribute(self, name, nullValue=None): if nullValue == None:nullValue=self.nullString self.attDict[name]=nullValue def delAttribute(self, name): for member in self.membersDict: if member.has_key(name):del member[name] del self.attDict[name] def compactAttributesDictionary(self): """removes unreferenced attributes""" newkeys = set() for member in self.membersDict: for key in self.membersDict[member].keys(): newkeys.add(key) for key in self.attDict.keys(): if key not in newkeys: del self.attDict[key] if __name__ == "__main__": mvt = MVTable() me=mvt.addMember() he=mvt.addMember(third=3, fourth=4) mvt.addAttribute('first', 5) #print basic functionality outputs for column in mvt.attDict: print 'Column:%s, me:%s, he:%s'%(column,me[column],he[column]) ########################### From jerl.simpso at gmail.com Mon Oct 3 17:23:12 2005 From: jerl.simpso at gmail.com (Jerl Simpson) Date: Mon, 3 Oct 2005 10:23:12 -0500 Subject: [Tutor] HTTP GET Request In-Reply-To: <4339AB23.9050507@tds.net> References: <4339AB23.9050507@tds.net> Message-ID: I wanted to post a follow up to this thread. I figured out what I needed and Python was it. The plan was to not use a web server, but to write my own...which I did with Python. Basically all I did was put a listen() into a while loop. Once I got the connection, I created a thread to read the socket. Once I could read the socket, I read the data in, parsed it, and now I can use it for what I want. In this case, MySQL calls. All I had to do was import socket and threading modules to get the base of it. I was hoping for a module that had been written to make it nice and neat, but turns out it was easy enough with out one. I'm now a fan of Python. Thanks for the replies and suggestions. jerl On 9/27/05, Kent Johnson wrote: > > Jerl Simpson wrote: > > The only piece I don't have going the Python route is actually > > getting the GET > > Which pieces do you have so far? If it is just Python, then you don't have > all the pieces yet. If you already have a server, which one are you using? > > > Sorry, accidentally sent the last one before I was finished. > > I was saying, I just lack getting the GET URI into a variable, and then > > finding out the best way to parse it into it's components using Python. > > The GET URI doesn't just magically appear - you need a webserver somewhere > in the picture. If you have written a webserver in C you must know a bit > about what is involved. It's not just getting a query parameter into a > variable, somewhere you have to implement the HTTP protocol. > > There are many, many choices for how to do this in Python. Several have > already been pointed out to you - > Apache + Python CGI - simple way to get started > Apache + mod_python - runs Python in the same process as Apache, > industrial-strength and faster than CGI > CherryPy - All-Python solution, fairly easy to get started with though for > high-volume deployments it is recommended to run it behind Apache with > mod_rewrite. > > Here is a long list of other possibilities: > http://wiki.python.org/moin/WebProgramming > > Maybe you should ask your friend what server he recommends? > > Kent > > > > Thanks again, > > > > Jerl > > > > On 9/27/05, *Jerl Simpson* > > wrote: > > > > I don't think I explained my situation clearly enough. > > > > Let me tell you what I'm doing. > > First, I'm looking for an excuse to learn Python. > > > > Second, I'm running a server that takes request from a remote > > server. This request is an HTTP GET request. I used to have (lost > > the source) a C program I wrote that functions as a web server. > > It takes the request on port 80, parses the GET. From the GET I > > construct a MySQL query and spit the results back out. > > > > Now, the logical solution is to run Apache to handle the webserver > > aspect, and have it hand off to a CGI to run the MySQL query and > > spit the results back out to the requesting server. In this > > situation, I could have thousands of requests per minute, and it > > bogs the server down. To much overhead when Apache calls the CGI. > > I've tried using several different setups with Apache, and C, Perl, > > and PHP CGIs. > > > > I found it to be much faster if I wrote the webserver, and handle > > the MySQL call within the same thread. > > > > I was told by a friend of mine that Python is good for creating > > network servers. So I thought I'd give it a try...instead of > > rewriting my C program I wanted to take the opportunity to learn a > > bit of Python. > > > > The only piece I don't have going the Python route is actually > > getting the GET > > > > > > On 9/27/05, *paul brian* < paul1brian at gmail.com > > > wrote: > > > >> Basicall, what I need is a stand alone CGI. Instead of the > > program passing > >> the data off to a CGI, I want it to parse and handle the > > request directly. > > > > instead of which program ? > > > > Http requests are served by a web server (ie Apache), which > > depending > > on the type of request passes the request to wherever. > > > > As such any HTTP request *must* be handled first by a web > > server, and > > cgi scripts traditionally lived in cgi-bin directory on the > > server so > > a URL would look like http://www.example.com/cgi-bin/myscript.py > > > > I think you have 3 options > > > > 1. use the cgi module in python to create scripts like the one > > above. > > They will not be fast but it gives you a lowlevel access to > > the request > > However cgi was out of date about 8 years ago - it has some > > serious limitations mostly on speed/capacity. > > > > 2. use a system like mod_python. This is better than cgi for > > lots of reasons, > > mostly to do with speed. Here you also have access to the > > request > > objects, but there is a bit of a learning curve. > > > > 3. Zope - higher level than even mod_python and still more of a > > learning curve > > > > (there is a multitude of python based cgi repalcements, Django, > > webware and others spring to mind. But there is no clear "winner" > > amoungst the community) > > > > I would recommend that you look at taking a weekend to install > > apache, > > and play with both the cgi module and mod_python. mod_python is > > pretty good and fairly well documented, as well as being pretty low > > level. > > > > I think there is a lot to do here - perhaps if you tell us exactly > > what you need we can point you at a solution. Some web hosters > > provide > > mod_python or zope hosting and that might be a way to get up and > > running faster. > > > > > > > > > > > > On 9/27/05, Jerl Simpson > > wrote: > >> Hello, > >> > >> I have been looking through some of the HTTP projects and > > haven't quite > >> found what I'm looking for. > >> Basicall, what I need is a stand alone CGI. Instead of the > > program passing > >> the data off to a CGI, I want it to parse and handle the > > request directly. > >> > >> The part I'm having trouble with is actually getting the > > request and parsing > >> it. > >> > >> Let's say I have a URI that looks like: > >> ?var1=val1&var2=val2&...varn=valn > >> > >> I'd like to find a way to get these into some datastructure so > > I can use > >> them to generate my output. > >> > >> It seems like a simple thing, but as I'm new to python, I > > don't know where > >> to start. > >> > >> Thank you for any help you can give. > >> > >> > >> Jerl > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > >> > >> > > > > > > -- > > -------------------------- > > Paul Brian > > m. 07875 074 534 > > t. 0208 352 1741 > > > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051003/a260ee49/attachment.htm From kent37 at tds.net Mon Oct 3 17:40:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Oct 2005 11:40:40 -0400 Subject: [Tutor] HTTP GET Request In-Reply-To: References: <4339AB23.9050507@tds.net> Message-ID: <434150F8.5070206@tds.net> Jerl Simpson wrote: > The plan was to not use a web server, but to write my own...which I did > with Python. > > Basically all I did was put a listen() into a while loop. Once I got > the connection, I created a thread to read the socket. Once I could > read the socket, I read the data in, parsed it, and now I can use it for > what I want. In this case, MySQL calls. > > All I had to do was import socket and threading modules to get the base > of it. > I was hoping for a module that had been written to make it nice and > neat, but turns out it was easy enough with out one. You might want to look at BaseHTTPServer in the std lib, and SimpleHTTPServer as an example of how to use it - or maybe SocketServer for even lower-level support. > > I'm now a fan of Python. Welcome! Kent > > Thanks for the replies and suggestions. > > > jerl > > > On 9/27/05, *Kent Johnson* > wrote: > > Jerl Simpson wrote: > > The only piece I don't have going the Python route is actually > > getting the GET > > Which pieces do you have so far? If it is just Python, then you > don't have all the pieces yet. If you already have a server, which > one are you using? > > > Sorry, accidentally sent the last one before I was finished. > > I was saying, I just lack getting the GET URI into a variable, > and then > > finding out the best way to parse it into it's components using > Python. > > The GET URI doesn't just magically appear - you need a webserver > somewhere in the picture. If you have written a webserver in C you > must know a bit about what is involved. It's not just getting a > query parameter into a variable, somewhere you have to implement the > HTTP protocol. > > There are many, many choices for how to do this in Python. Several > have already been pointed out to you - > Apache + Python CGI - simple way to get started > Apache + mod_python - runs Python in the same process as Apache, > industrial-strength and faster than CGI > CherryPy - All-Python solution, fairly easy to get started with > though for high-volume deployments it is recommended to run it > behind Apache with mod_rewrite. > > Here is a long list of other possibilities: > http://wiki.python.org/moin/WebProgramming > > Maybe you should ask your friend what server he recommends? > > Kent > > > > Thanks again, > > > > Jerl > > > > On 9/27/05, *Jerl Simpson* > > >> > wrote: > > > > I don't think I explained my situation clearly enough. > > > > Let me tell you what I'm doing. > > First, I'm looking for an excuse to learn Python. > > > > Second, I'm running a server that takes request from a remote > > server. This request is an HTTP GET request. I used to have > (lost > > the source) a C program I wrote that functions as a web server. > > It takes the request on port 80, parses the GET. From the GET I > > construct a MySQL query and spit the results back out. > > > > Now, the logical solution is to run Apache to handle the > webserver > > aspect, and have it hand off to a CGI to run the MySQL query and > > spit the results back out to the requesting server. In this > > situation, I could have thousands of requests per minute, and it > > bogs the server down. To much overhead when Apache calls the > CGI. > > I've tried using several different setups with Apache, and C, > Perl, > > and PHP CGIs. > > > > I found it to be much faster if I wrote the webserver, and > handle > > the MySQL call within the same thread. > > > > I was told by a friend of mine that Python is good for creating > > network servers. So I thought I'd give it a try...instead of > > rewriting my C program I wanted to take the opportunity to > learn a > > bit of Python. > > > > The only piece I don't have going the Python route is actually > > getting the GET > > > > > > On 9/27/05, *paul brian* < paul1brian at gmail.com > > > >> > wrote: > > > >> Basicall, what I need is a stand alone CGI. Instead of the > > program passing > >> the data off to a CGI, I want it to parse and handle the > > request directly. > > > > instead of which program ? > > > > Http requests are served by a web server (ie Apache), which > > depending > > on the type of request passes the request to wherever. > > > > As such any HTTP request *must* be handled first by a web > > server, and > > cgi scripts traditionally lived in cgi-bin directory on the > > server so > > a URL would look like > http://www.example.com/cgi-bin/myscript.py > > > > I think you have 3 options > > > > 1. use the cgi module in python to create scripts like > the one > > above. > > They will not be fast but it gives you a lowlevel > access to > > the request > > However cgi was out of date about 8 years ago - it > has some > > serious limitations mostly on speed/capacity. > > > > 2. use a system like mod_python. This is better than cgi for > > lots of reasons, > > mostly to do with speed. Here you also have access to the > > request > > objects, but there is a bit of a learning curve. > > > > 3. Zope - higher level than even mod_python and still > more of a > > learning curve > > > > (there is a multitude of python based cgi repalcements, > Django, > > webware and others spring to mind. But there is no clear > "winner" > > amoungst the community) > > > > I would recommend that you look at taking a weekend to > install > > apache, > > and play with both the cgi module and > mod_python. mod_python is > > pretty good and fairly well documented, as well as being > pretty low > > level. > > > > I think there is a lot to do here - perhaps if you tell > us exactly > > what you need we can point you at a solution. Some web > hosters > > provide > > mod_python or zope hosting and that might be a way to get > up and > > running faster. > > > > > > > > > > > > On 9/27/05, Jerl Simpson < jerl.simpso at gmail.com > > > >> wrote: > >> Hello, > >> > >> I have been looking through some of the HTTP projects and > > haven't quite > >> found what I'm looking for. > >> Basicall, what I need is a stand alone CGI. Instead of the > > program passing > >> the data off to a CGI, I want it to parse and handle the > > request directly. > >> > >> The part I'm having trouble with is actually getting the > > request and parsing > >> it. > >> > >> Let's say I have a URI that looks like: > >> ?var1=val1&var2=val2&...varn=valn > >> > >> I'd like to find a way to get these into some datastructure so > > I can use > >> them to generate my output. > >> > >> It seems like a simple thing, but as I'm new to python, I > > don't know where > >> to start. > >> > >> Thank you for any help you can give. > >> > >> > >> Jerl > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > > > >> http://mail.python.org/mailman/listinfo/tutor > >> > >> > >> > > > > > > -- > > -------------------------- > > Paul Brian > > m. 07875 074 534 > > t. 0208 352 1741 > > > > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From lists at olivermaunder.co.uk Mon Oct 3 18:22:52 2005 From: lists at olivermaunder.co.uk (Oliver Maunder) Date: Mon, 3 Oct 2005 17:22:52 +0100 Subject: [Tutor] Finding libraries In-Reply-To: <434105E8.5040701@tds.net> References: <434105E8.5040701@tds.net> Message-ID: On 10/3/05, Kent Johnson wrote: > > > Should be straightforward, but I don't > > want to do it only to find there's a module with a > > get_file_from_web(url, destination, progress_callback) function in it. > > That is spelled urllib.urlretrieve(url, destination, progress_callback) > :-) Proves my point - if you can think of it, it's probably already in a library! Olly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051003/044d26ef/attachment.htm From bgailer at alum.rpi.edu Mon Oct 3 18:43:14 2005 From: bgailer at alum.rpi.edu (bob) Date: Mon, 03 Oct 2005 09:43:14 -0700 Subject: [Tutor] Load PDF In-Reply-To: <20051003104130.61589.qmail@web35001.mail.mud.yahoo.com> References: <20051003104130.61589.qmail@web35001.mail.mud.yahoo.com> Message-ID: <6.1.2.0.0.20051003092001.03481750@mail.mric.net> I am moving this to the python-win32 list where we can better handle it. Please send further replies there. At 03:41 AM 10/3/2005, Pepe Pena wrote: >I am attempting to load a pdf file programatically within Adobe Reader >using the Adobe Acrobat 7.0 Browser Control Type Library. If I run this >code PythonWin terminates abruptly, can anyone suggest any changes I >should make to the following lines of code, thanks. > >import win32com.client >test = win32com.client.Dispatch("AcroPDF.PDF.1") >test.LoadFile("D:\\sql.pdf") I confirm the behavior. I have no explanation. From mail at olivermaunder.co.uk Mon Oct 3 18:21:30 2005 From: mail at olivermaunder.co.uk (Oliver Maunder) Date: Mon, 3 Oct 2005 17:21:30 +0100 Subject: [Tutor] Finding libraries In-Reply-To: References: Message-ID: On 10/3/05, Liam Clarke wrote: > > I'd recommend http://www.python.org/pypi and > http://www.vex.net/parnassus/ > Thanks for those - they're both full of possibilities. Olly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051003/ded25b12/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Oct 3 18:58:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Oct 2005 09:58:53 -0700 (PDT) Subject: [Tutor] icq library In-Reply-To: <433254550@web.de> Message-ID: On Mon, 3 Oct 2005 webmeister8f at web.de wrote: > > Is there an library to communicate with an ICQ-server including the most > important features line sending and receiving messages? > > I have already searched with google but i am not really able to find > exactrly that what i'm looking for. The Twisted Python network framework provides pluggable support for different transport layers, and someone has written an ICQ-to-Jabber transport for it: http://pyicq-t.blathersource.org/ It may be what you're looking for. Hope this helps! From mjcother at yahoo.com Tue Oct 4 07:26:52 2005 From: mjcother at yahoo.com (Michael Cotherman) Date: Mon, 3 Oct 2005 22:26:52 -0700 (PDT) Subject: [Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help Message-ID: <20051004052652.90167.qmail@web31809.mail.mud.yahoo.com> Hello, I am really new to python and really have not programmed much since college, I played with it a little now, and it seems to be a tool I feel comfortable implementing a personal project in. I wish to communicate via a serial port to a device that is using COBS. I wish to configure it and then receive data at an interval and store it in a rrd. The device itself receives telemetry information from other devices, and this telemetry info is going to get graphed and made available via a web page. The serial port will be com or tty, for which I prepped by playing with pygarmin and miniterm. The device is working and communicable? via a program written in .NET by a friend of the friend who gave it to me. The program has so many things I wish to change that it would be easiest to start from scratch. I have some of the source for bits and pieces that may be needed. The data coming in/going out will be COBS encoded, which changes/escapes all 0x00 bytes, then uses a 0x00 byte for the framing. COBS theory is explained here: http://www.stuartcheshire.org/papers/COBSforToN.pdf and it looks like a version written in c is at: http://gtk-gnutella.sourceforge.net/doxygen/cobs_8c.htm I would initially be happy creating a cobs.py and then modding the initial 1.1 release of miniterm and seeing if I could listen to the device... The device will be sending packets of 2-12 bytes at regular intervals (99% will be 7 byte packets every minute or so), and I can just move the serial cable over from the com port with the working application to the cobs-miniterm one to see if I am getting the right. Thanks in advance! -mike clearwater, fl __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From cpu.crazy at gmail.com Tue Oct 4 17:17:44 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 04 Oct 2005 09:17:44 -0600 Subject: [Tutor] Making a character jump with pygame Message-ID: <43429D18.6000401@gmail.com> Hi, I've edited the aliens.py example to make my character just move back and forth. However I can't make him jump! Here's my code (attached). I'm trying to make a platformer Mario style game. Thanks, Joe -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: main.py Url: http://mail.python.org/pipermail/tutor/attachments/20051004/cb499ad0/main.asc From davholla2002 at yahoo.co.uk Tue Oct 4 18:41:25 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Tue, 4 Oct 2005 17:41:25 +0100 (BST) Subject: [Tutor] Beautiful soup Message-ID: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> I tried to use this script which I found on the web :- import urllib2, pprint from BeautifulSoup import BeautifulSoup def cellToWord(cell): """Given a table cell, return the word in that cell.""" # Some words are in bold. if cell('b'): return cell.first('b').string.strip() # Return the bold piece. else: return cell.string.split('.')[1].strip() # Remove the number. def parse(url): """Parse the given URL and return a dictionary mapping US words to foreign words.""" # Read the URL and pass it to BeautifulSoup. html = urllib2.urlopen(url).read() soup = BeautifulSoup() soup.feed(html) # Read the main table, extracting the words from the table cells. USToForeign = {} mainTable = soup.first('table') rows = mainTable('tr') for row in rows[1:]: # Exclude the first (headings) row. cells = row('td') if len(cells) == 3: # Some rows have a single colspan="3" cell. US = cellToWord(cells[0]) foreign = cellToWord(cells[1]) USToForeign[US] = foreign return USToForeign if __name__ == '__main__': url = 'http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm' USToForeign = parse(url) pairs = USToForeign.items() pairs.sort(lambda a, b: cmp(a[0].lower(), b[0].lower())) # Web page order pprint.pprint(pairs) and it works well. However I change it to get it to look at a file on my PC, then I get this message :- Traceback (most recent call last): File "C:\Python24\beaexp2", line 43, in -toplevel- USToForeign = parse(url) File "C:\Python24\beaexp2", line 20, in parse html = urllib2.urlopen(url).read() File "C:\Python24\lib\urllib2.py", line 130, in urlopen return _opener.open(url, data) File "C:\Python24\lib\urllib2.py", line 358, in open response = self._open(req, data) File "C:\Python24\lib\urllib2.py", line 376, in _open '_open', req) File "C:\Python24\lib\urllib2.py", line 337, in _call_chain result = func(*args) File "C:\Python24\lib\urllib2.py", line 1119, in file_open return self.open_local_file(req) File "C:\Python24\lib\urllib2.py", line 1135, in open_local_file stats = os.stat(localfile) OSError: [Errno 2] No such file or directory: '\\C:\\Python24\\FRE_word_list.htm Any idea how to solve it ? The file is on my PC. I am using Python 2.4 on Win XP. Thanks in advance. David ___________________________________________________________ How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com From paul1brian at gmail.com Tue Oct 4 19:13:45 2005 From: paul1brian at gmail.com (paul brian) Date: Tue, 4 Oct 2005 18:13:45 +0100 Subject: [Tutor] Beautiful soup In-Reply-To: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> References: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> Message-ID: How did you change it to look at the file on your PC? You appear to have told urllib2 to use "FRE_word_list.htm", it cannot find that online so tried to look for it on your local disk at '\\C:\\Python24\\FRE_word_list.htm I would suggest that you either put your local html on a web server and send in that local URL or replace html = urllib2.urlopen(url).read() with html = open(r'c:\myfolder\myfile.html').read() and see where that takes you. cheers On 10/4/05, David Holland wrote: > I tried to use this script which I found on the web :- > import urllib2, pprint > from BeautifulSoup import BeautifulSoup > > > def cellToWord(cell): > """Given a table cell, return the word in that > cell.""" > # Some words are in bold. > if cell('b'): > return cell.first('b').string.strip() # > Return the bold piece. > else: > return cell.string.split('.')[1].strip() # > Remove the number. > > > def parse(url): > """Parse the given URL and return a dictionary > mapping US words to > foreign words.""" > > > # Read the URL and pass it to BeautifulSoup. > html = urllib2.urlopen(url).read() > soup = BeautifulSoup() > soup.feed(html) > > > # Read the main table, extracting the words from > the table cells. > USToForeign = {} > mainTable = soup.first('table') > rows = mainTable('tr') > for row in rows[1:]: # Exclude the first > (headings) row. > cells = row('td') > if len(cells) == 3: # Some rows have a > single colspan="3" cell. > US = cellToWord(cells[0]) > foreign = cellToWord(cells[1]) > USToForeign[US] = foreign > > > return USToForeign > > > if __name__ == '__main__': > url = > 'http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm' > > USToForeign = parse(url) > pairs = USToForeign.items() > pairs.sort(lambda a, b: cmp(a[0].lower(), > b[0].lower())) # Web page order > pprint.pprint(pairs) > > and it works well. However I change it to get it to > look at a file on my PC, then I get this message :- > Traceback (most recent call last): > File "C:\Python24\beaexp2", line 43, in -toplevel- > USToForeign = parse(url) > File "C:\Python24\beaexp2", line 20, in parse > html = urllib2.urlopen(url).read() > File "C:\Python24\lib\urllib2.py", line 130, in > urlopen > return _opener.open(url, data) > File "C:\Python24\lib\urllib2.py", line 358, in open > response = self._open(req, data) > File "C:\Python24\lib\urllib2.py", line 376, in > _open > '_open', req) > File "C:\Python24\lib\urllib2.py", line 337, in > _call_chain > result = func(*args) > File "C:\Python24\lib\urllib2.py", line 1119, in > file_open > return self.open_local_file(req) > File "C:\Python24\lib\urllib2.py", line 1135, in > open_local_file > stats = os.stat(localfile) > OSError: [Errno 2] No such file or directory: > '\\C:\\Python24\\FRE_word_list.htm > Any idea how to solve it ? The file is on my PC. > > I am using Python 2.4 on Win XP. > > Thanks in advance. > > David > > > > ___________________________________________________________ > How much free photo storage do you get? Store your holiday > snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From grouch at gmail.com Tue Oct 4 19:25:14 2005 From: grouch at gmail.com (Andrew P) Date: Tue, 4 Oct 2005 12:25:14 -0500 Subject: [Tutor] Beautiful soup In-Reply-To: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> References: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> Message-ID: With error messages like that, the interesting bits are usually at the end: OSError: [Errno 2] No such file or directory: '\\C:\\Python24\\FRE_word_list.htm That should read "C:\\Python24\\FRE_word_list.htm". I use UNIX-style paths, which work fine for me under Windows, so it would just be "/Python24/FRE_word_list.htm" which is a bit cleaner. I am not sure if that is dependable behavior, however. Andrew On 10/4/05, David Holland wrote: > > I tried to use this script which I found on the web :- > import urllib2, pprint > from BeautifulSoup import BeautifulSoup > > > def cellToWord(cell): > """Given a table cell, return the word in that > cell.""" > # Some words are in bold. > if cell('b'): > return cell.first('b').string.strip() # > Return the bold piece. > else: > return cell.string.split('.')[1].strip() # > Remove the number. > > > def parse(url): > """Parse the given URL and return a dictionary > mapping US words to > foreign words.""" > > > # Read the URL and pass it to BeautifulSoup. > html = urllib2.urlopen(url).read() > soup = BeautifulSoup() > soup.feed(html) > > > # Read the main table, extracting the words from > the table cells. > USToForeign = {} > mainTable = soup.first('table') > rows = mainTable('tr') > for row in rows[1:]: # Exclude the first > (headings) row. > cells = row('td') > if len(cells) == 3: # Some rows have a > single colspan="3" cell. > US = cellToWord(cells[0]) > foreign = cellToWord(cells[1]) > USToForeign[US] = foreign > > > return USToForeign > > > if __name__ == '__main__': > url = > 'http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm' > > USToForeign = parse(url) > pairs = USToForeign.items() > pairs.sort(lambda a, b: cmp(a[0].lower(), > b[0].lower())) # Web page order > pprint.pprint(pairs) > > and it works well. However I change it to get it to > look at a file on my PC, then I get this message :- > Traceback (most recent call last): > File "C:\Python24\beaexp2", line 43, in -toplevel- > USToForeign = parse(url) > File "C:\Python24\beaexp2", line 20, in parse > html = urllib2.urlopen(url).read() > File "C:\Python24\lib\urllib2.py", line 130, in > urlopen > return _opener.open(url, data) > File "C:\Python24\lib\urllib2.py", line 358, in open > response = self._open(req, data) > File "C:\Python24\lib\urllib2.py", line 376, in > _open > '_open', req) > File "C:\Python24\lib\urllib2.py", line 337, in > _call_chain > result = func(*args) > File "C:\Python24\lib\urllib2.py", line 1119, in > file_open > return self.open_local_file(req) > File "C:\Python24\lib\urllib2.py", line 1135, in > open_local_file > stats = os.stat(localfile) > OSError: [Errno 2] No such file or directory: > '\\C:\\Python24\\FRE_word_list.htm > Any idea how to solve it ? The file is on my PC. > > I am using Python 2.4 on Win XP. > > Thanks in advance. > > David > > > > ___________________________________________________________ > How much free photo storage do you get? Store your holiday > snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051004/25015af1/attachment.html From grouch at gmail.com Tue Oct 4 19:37:45 2005 From: grouch at gmail.com (Andrew P) Date: Tue, 4 Oct 2005 12:37:45 -0500 Subject: [Tutor] Beautiful soup In-Reply-To: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> References: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> Message-ID: Oops, Paul is probably right. I thought urllib2 opened local files in the absence of an identifier like "http://". Bad assumption on my part. I remembered that behavior from somewhere else, maybe urllib. That path beginning with "\\C:\\" could still bite you, however. Good luck, Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051004/6f0682d5/attachment-0001.htm From mjcother at yahoo.com Tue Oct 4 21:26:16 2005 From: mjcother at yahoo.com (Michael Cotherman) Date: Tue, 4 Oct 2005 12:26:16 -0700 (PDT) Subject: [Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help In-Reply-To: <20051004052652.90167.qmail@web31809.mail.mud.yahoo.com> Message-ID: <20051004192616.35792.qmail@web31804.mail.mud.yahoo.com> A little more info is below: With miniterm modified to output hex to the screen, here is the data coming in unformatted. (note zero bytes delimit end of packet): c:\Python23>python miniterm1.1a.py --- Miniterm --- type ESC to quit 0002860104DB203F01000002860504CB1A7401000002860504CB1B7401000002860504CB1B740100 0002860504CB1B7401000002860504CB1B7401000002860504CB1B7401000002860504CB1B740100 0002860504CB1B7401000002860504CB1B7401000002860504CB1B740100 Here I have formatted it(one line equals a packet, currently about every 30 seconds): c:\Python23>python miniterm1.1a.py --- Miniterm --- type ESC to quit 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-01-04-DB-20-3E-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 here is what the data will look like after COBS decoding (the zero bytes are real data): 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 For those who are curious as to what I am doing, here is what telemetry is in the packet: packe type = 0x86 Device ID = 0x0004 Payload: ----Batt Volt. = 0xCB ----Pot Volt. = 0x1B ----Temp Volt. = 0x74 ----sw 1 = 0 ----sw 2 = 0 ----sw 3 = 0 ----sw 4 = 0 ----Btn 1 = 0 ----Btn 2 = 0 ----Yel LED = 0 ----Red LED = 0 Thanks, mike ______________________________________________________ Yahoo! for Good Donate to the Hurricane Katrina relief effort. http://store.yahoo.com/redcross-donate3/ From caphrim007 at gmail.com Tue Oct 4 21:20:12 2005 From: caphrim007 at gmail.com (Tim Rupp) Date: Tue, 04 Oct 2005 14:20:12 -0500 Subject: [Tutor] Trying to prevent ftplib from locking my script Message-ID: <4342D5EC.3000606@gmail.com> Hi list, I'm trying to write a python script that uses ftplib to send items to a local server I have. I want to be able to give ftplib a file to send, and then just have it sort of go into the background and do its thing while the script does other "stuff" My attempts at it so far have caused the whole script to wait until the ftp transfer finishes (essentially pausing the rest of the script). Any ideas on how I can just make it go away, allowing me to do other stuff like output various info? Can threads be used? If so, does anyone have good resources to point me to for python threading? Thanks in advance! Tim From kent37 at tds.net Tue Oct 4 21:49:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Oct 2005 15:49:04 -0400 Subject: [Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help In-Reply-To: <20051004052652.90167.qmail@web31809.mail.mud.yahoo.com> References: <20051004052652.90167.qmail@web31809.mail.mud.yahoo.com> Message-ID: <4342DCB0.8010500@tds.net> I'm not sure what the question is here. It looks like you need to write a COBS encoder / decoder in Python, maybe using your .NET code as a model. Then you can integrate that with comms code taken from miniterm. What help do you need? Kent Michael Cotherman wrote: > Hello, I am really new to python and really have not > programmed much since college, I played with it a > little now, and it seems to be a tool I feel > comfortable implementing a personal project in. > > I wish to communicate via a serial port to a device > that is using COBS. I wish to configure it and then > receive data at an interval and store it in a rrd. > The device itself receives telemetry information from > other devices, and this telemetry info is going to get > graphed and made available via a web page. > > The serial port will be com or tty, for which I > prepped by playing with pygarmin and miniterm. The > device is working and communicable? via a program > written in .NET by a friend of the friend who gave it > to me. The program has so many things I wish to change > that it would be easiest to start from scratch. I have > some of the source for bits and pieces that may be > needed. > > The data coming in/going out will be COBS encoded, > which changes/escapes all 0x00 bytes, then uses a 0x00 > byte for the framing. > > > COBS theory is explained here: > http://www.stuartcheshire.org/papers/COBSforToN.pdf > > and it looks like a version written in c is at: > http://gtk-gnutella.sourceforge.net/doxygen/cobs_8c.htm > > > I would initially be happy creating a cobs.py and then > modding the initial 1.1 release of miniterm and seeing > if I could listen to the device... The device will be > sending packets of 2-12 bytes at regular intervals > (99% will be 7 byte packets every minute or so), and I > can just move the serial cable over from the com port > with the working application to the cobs-miniterm one > to see if I am getting the right. > > Thanks in advance! > > -mike > clearwater, fl > > > > __________________________________ > Yahoo! Mail - PC Magazine Editors' Choice 2005 > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Tue Oct 4 21:54:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Oct 2005 15:54:23 -0400 Subject: [Tutor] Trying to prevent ftplib from locking my script In-Reply-To: <4342D5EC.3000606@gmail.com> References: <4342D5EC.3000606@gmail.com> Message-ID: <4342DDEF.3070906@tds.net> Tim Rupp wrote: > Hi list, > > I'm trying to write a python script that uses ftplib to send items to a > local server I have. I want to be able to give ftplib a file to send, > and then just have it sort of go into the background and do its thing > while the script does other "stuff" > > My attempts at it so far have caused the whole script to wait until the > ftp transfer finishes (essentially pausing the rest of the script). > > Any ideas on how I can just make it go away, allowing me to do other > stuff like output various info? Can threads be used? If so, does anyone > have good resources to point me to for python threading? Yes, threads are one solution to this problem. Twisted and Kamaelia are two other solutions. See this msg for links to some helpful discussions: http://mail.python.org/pipermail/tutor/2005-October/041866.html Kent From lists at olivermaunder.co.uk Tue Oct 4 22:49:23 2005 From: lists at olivermaunder.co.uk (Oliver Maunder) Date: Tue, 4 Oct 2005 21:49:23 +0100 Subject: [Tutor] Beautiful soup In-Reply-To: References: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> Message-ID: On 10/4/05, Andrew P wrote: > > Oops, Paul is probably right. I thought urllib2 opened local files in the > absence of an identifier like "http://". Bad assumption on my part. I > remembered that behavior from somewhere else, maybe urllib. The following function could be useful here - I got it from Dive Into Python - http://diveintopython.org/scripts_and_streams/index.html#kgp.openanything It tries to open a file with urllib, and if that fails it uses open(): def openAnything(source): # try to open with urllib (if source is http, ftp, or file URL) import urllib try: return urllib.urlopen (source) except (IOError, OSError): pass # try to open with native open function (if source is pathname) try: return open(source) except (IOError, OSError): pass # treat source as string import StringIO return StringIO.StringIO(str(source)) Olly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051004/9097fdbe/attachment.html From grouch at gmail.com Tue Oct 4 23:26:25 2005 From: grouch at gmail.com (Andrew P) Date: Tue, 4 Oct 2005 16:26:25 -0500 Subject: [Tutor] Trying to prevent ftplib from locking my script In-Reply-To: <4342D5EC.3000606@gmail.com> References: <4342D5EC.3000606@gmail.com> Message-ID: Normally I wouldn't pipe up here because threads really can be very tricky. But check out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883 I use this recipe, originally from "Python in a Nutshell", all the time, to solve exactly your problem. Slow network stuff that I don't have to/want to babysit. The recipe is well-commented, with an easy-to-follow usage example. Basically though, Python's Queue module really takes away a lot of the trickiness here, acting as a thread-safe place to put jobs, and put results, without worrying about locks or sephamores or whatever it is people worry about. And the callback functions you can pass in with the job may be all you really need to report success/failure of the jobs. All in all, it's probably easier to just read the code. Good luck. On 10/4/05, Tim Rupp wrote: > > Hi list, > > I'm trying to write a python script that uses ftplib to send items to a > local server I have. I want to be able to give ftplib a file to send, > and then just have it sort of go into the background and do its thing > while the script does other "stuff" > > My attempts at it so far have caused the whole script to wait until the > ftp transfer finishes (essentially pausing the rest of the script). > > Any ideas on how I can just make it go away, allowing me to do other > stuff like output various info? Can threads be used? If so, does anyone > have good resources to point me to for python threading? > > Thanks in advance! > Tim > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051004/9b55a93f/attachment.htm From ljholish at speakeasy.net Wed Oct 5 02:12:49 2005 From: ljholish at speakeasy.net (Larry Holish) Date: Tue, 4 Oct 2005 19:12:49 -0500 Subject: [Tutor] Python equiv to PHP "include" ? In-Reply-To: <200509291716.57780.python@jayloden.com> References: <200509290955.17763.python@jayloden.com> <004d01c5c51e$66ef80b0$0201a8c0@xp> <200509291716.57780.python@jayloden.com> Message-ID: <20051005001249.GA27821@localhost> On Thu, Sep 29, 2005 at 05:16:57PM -0400, Jay Loden wrote: > Does anyone know of any soup-to-nuts CGI programming examples online for > Python that might make this clearer so I can bug the list less and just read > some example code? You might also want to take a look at cgi_app, a simple python web framework that works in either a plain old CGI environment, or can easily be adapted to mod_python. This page includes a basic usage example: http://thraxil.org/code/cgi_app/ -- Larry Holish From python at jayloden.com Wed Oct 5 07:27:39 2005 From: python at jayloden.com (Jay Loden) Date: Wed, 5 Oct 2005 01:27:39 -0400 Subject: [Tutor] Mod_python greedy url matching Message-ID: <200510050127.39278.python@jayloden.com> I'm having trouble with Apache and Mod_python - mod_python is set to use /var/www/html and pass all *.htm files on to the handler I wrote. Unfortunately, mod_python does a greedy match, so /var/www/html/subdirectory/file.htm still gets passed to the handler! Is there some way to limit the handler to the directory and NOT include subdirectories? -Jay From dyoo at hkn.eecs.berkeley.edu Wed Oct 5 09:21:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 5 Oct 2005 00:21:04 -0700 (PDT) Subject: [Tutor] Mod_python greedy url matching In-Reply-To: <200510050127.39278.python@jayloden.com> Message-ID: On Wed, 5 Oct 2005, Jay Loden wrote: > I'm having trouble with Apache and Mod_python - mod_python is set to use > /var/www/html and pass all *.htm files on to the handler I wrote. > Unfortunately, mod_python does a greedy match, so > /var/www/html/subdirectory/file.htm still gets passed to the handler! > Is there some way to limit the handler to the directory and NOT include > subdirectories? Hi Jay, You may want to ask the Apache folks about this one. Your question specific enough that the Apache folks will probably be better at this one than Python-Tutor. If you strip your question to its essentials, it really is an Apache configuration problem more than anything else; it really isn't related to Python except from the tangential relation to mod_python. The behavior you're seeing is how Apache deals with all Directory-specific directives: subdirectories "acquire" the properties of their parent directory. But from the notes in: http://httpd.apache.org/docs/2.0/sections.html http://httpd.apache.org/docs/2.0/mod/core.html#directory http://httpd.apache.org/docs/2.0/mod/mod_mime.html#removehandler it sounds possible for you to apply a RemoveHandler directive on the subdirectories of whatever parent directory you're trying not to handle. However, since we're really straying away from programming topics and into web-server system administration, I'd strongly recommend continuing this question on a mailing list like the one listed in: http://httpd.apache.org/lists.html#http-users From craigm543 at yahoo.com Tue Oct 4 04:20:51 2005 From: craigm543 at yahoo.com (Craig MacFarlane) Date: Mon, 3 Oct 2005 19:20:51 -0700 (PDT) Subject: [Tutor] Line continuation with readlines Message-ID: <20051004022051.65716.qmail@web52710.mail.yahoo.com> Hello, Is there a way to make line continuation work with the readlines function? i.e. this is \ one line. Thank you, Craig ______________________________________________________ Yahoo! for Good Donate to the Hurricane Katrina relief effort. http://store.yahoo.com/redcross-donate3/ From mail at olivermaunder.co.uk Tue Oct 4 22:47:27 2005 From: mail at olivermaunder.co.uk (Oliver Maunder) Date: Tue, 4 Oct 2005 21:47:27 +0100 Subject: [Tutor] Beautiful soup In-Reply-To: References: <20051004164125.65574.qmail@web25902.mail.ukl.yahoo.com> Message-ID: On 10/4/05, Andrew P wrote: > > Oops, Paul is probably right. I thought urllib2 opened local files in the > absence of an identifier like "http://". Bad assumption on my part. I > remembered that behavior from somewhere else, maybe urllib. > The following function could be useful here - I got it from Dive Into Python - http://diveintopython.org/scripts_and_streams/index.html#kgp.openanything It tries to open a file with urllib, and if that fails it uses open(): def openAnything(source): # try to open with urllib (if source is http, ftp, or file URL) import urllib try: return urllib.urlopen(source) except (IOError, OSError): pass # try to open with native open function (if source is pathname) try: return open(source) except (IOError, OSError): pass # treat source as string import StringIO return StringIO.StringIO(str(source)) Olly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051004/25d7d431/attachment.html From sfhaley at earthlink.net Wed Oct 5 07:15:38 2005 From: sfhaley at earthlink.net (Steve Haley) Date: Wed, 5 Oct 2005 01:15:38 -0400 Subject: [Tutor] Help Needed Message-ID: Hello, I am trying to learn Python which I am brand new to. I have run into a problem that I would appreciate help with. When I am in Python Shell of the IDLE GUI, when I click Edit/Run Script, I am getting a dialog box that is titled "Not saved" and states "The buffer for Python shell is not saved. Please save it first." With an "OK" button that just takes me back to the Shell window. I am going through a book (which suggests this resource as a good place to ask questions) and Edit/Run Script was working just fine the other day. I don't have a clue what is wrong or how to fix it. I have searched the Python.org website but was unable to find any reference to this. Any help would be greatly appreciated. Thanks very much, Steve sfhaley at earthlink.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051005/4b154325/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Oct 5 09:28:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 5 Oct 2005 00:28:10 -0700 (PDT) Subject: [Tutor] Line continuation with readlines In-Reply-To: <20051004022051.65716.qmail@web52710.mail.yahoo.com> Message-ID: On Mon, 3 Oct 2005, Craig MacFarlane wrote: > Is there a way to make line continuation work with > the readlines function? > > i.e. > > this is \ > one line. Hi Craig, readline() doesn't look at the content of lines, so no, not out of the box. However, would it be satisfactory if you wrote a function to define that behavior? Good luck to you! From daniel at thewatkins.org.uk Wed Oct 5 09:32:35 2005 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Wed, 05 Oct 2005 08:32:35 +0100 Subject: [Tutor] FW: Help Needed In-Reply-To: <9AA4216B8A36B9429BB00C546DF6D27201B882@schubert.OxbridgeTechnology.local> References: <9AA4216B8A36B9429BB00C546DF6D27201B882@schubert.OxbridgeTechnology.local> Message-ID: <1128497555.15926.1.camel@amdbert.oxbridgetechnology.local> When I am in Python Shell of the IDLE GUI, when I click Edit/Run Script, I am getting a dialog box that is titled ?Not saved? and states ?The buffer for Python shell is not saved. Please save it first.? With an ?OK? button that just takes me back to the Shell window. I am going through a book (which suggests this resource as a good place to ask questions) and Edit/Run Script was working just fine the other day. Go to File > Save As... and save the file somewhere. Then attempt to run the script. If this still doesn't work, I'm stumped, but it really should... Dan From ajikoe at gmail.com Wed Oct 5 09:38:30 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 5 Oct 2005 09:38:30 +0200 Subject: [Tutor] Help Needed In-Reply-To: References: Message-ID: hi, make sure in the option/general/Startup preferences/at startup/open edit window option/general/Startup preferences/autosave preferences/NoPrompt run the program by clicking F5 Cheers, pujo On 10/5/05, Steve Haley wrote: > > Hello, > > I am trying to learn Python which I am brand new to. I have run into a > problem that I would appreciate help with. > > When I am in Python Shell of the IDLE GUI, when I click Edit/Run Script, > I am getting a dialog box that is titled "Not saved" and states "The buffer > for Python shell is not saved. Please save it first." With an "OK" button > that just takes me back to the Shell window. I am going through a book > (which suggests this resource as a good place to ask questions) and Edit/Run > Script was working just fine the other day. > > I don't have a clue what is wrong or how to fix it. I have searched the > Python.org website but was unable to find any > reference to this. Any help would be greatly appreciated. > > Thanks very much, > > Steve > > sfhaley at earthlink.net > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051005/5e42482b/attachment.html From hameed.u.khan at gmail.com Wed Oct 5 10:55:43 2005 From: hameed.u.khan at gmail.com (Hameed U. Khan) Date: Wed, 5 Oct 2005 13:55:43 +0500 Subject: [Tutor] need help to understand terms for desinging a program Message-ID: <70576bd20510050155t54f94ed7ie6f6b1c7e2f7aeb1@mail.gmail.com> Hi, I need to make a program which will accomplish following. I dont need the code. I want to make it myself. But I need guidance from you people because I am not a good programmer. I need help in understanding following terms. " qmail-queue reads a mail message from descriptor 0. It then reads envelope information from descriptor 1. It places the message into the outgoing queue for future delivery by qmail-send. The envelope information is an envelope sender address followed by a list of envelope recipient addresses. The sender address is preceded by the letter F and terminated by a 0 byte. Each recipient address is preceded by the letter T and terminated by a 0 byte. The list of recipi- ent addresses is terminated by an extra 0 byte. If qmail- queue sees end-of-file before the extra 0 byte, it aborts without placing the message into the queue." I want to inspect messages before passing them to actuall qmail-queue program. Thanks in advance for your help. -- Regards, Hameed U. Khan Registered Linux User #: 354374 From paul1brian at gmail.com Wed Oct 5 11:22:48 2005 From: paul1brian at gmail.com (paul brian) Date: Wed, 5 Oct 2005 10:22:48 +0100 Subject: [Tutor] need help to understand terms for desinging a program In-Reply-To: <70576bd20510050155t54f94ed7ie6f6b1c7e2f7aeb1@mail.gmail.com> References: <70576bd20510050155t54f94ed7ie6f6b1c7e2f7aeb1@mail.gmail.com> Message-ID: This is a pretty big question, and it would be easier to answer if you can give us more details about what you want to do. It seems you want to inspect outgoing mails (possibly rewrite their addresses?) before the mails are sent out. If you are looking to send out emails to a list then I suggest looking at mailman - a python mailing list manager. If you want to use python to examine mail messages and do not care what mailserver (MTA) you use you could try exim instead of qmail and then try exim-python. http://botanicus.net/dw/exim-python/exim-4.32py1.html On 10/5/05, Hameed U. Khan wrote: > Hi, > I need to make a program which will accomplish following. I dont > need the code. I want to make it myself. But I need guidance from you > people because I am not a good programmer. I need help in > understanding following terms. > > " qmail-queue reads a mail message from descriptor 0. It > then reads envelope information from descriptor 1. It > places the message into the outgoing queue for future > delivery by qmail-send. > > The envelope information is an envelope sender address > followed by a list of envelope recipient addresses. The > sender address is preceded by the letter F and terminated > by a 0 byte. Each recipient address is preceded by the > letter T and terminated by a 0 byte. The list of recipi- > ent addresses is terminated by an extra 0 byte. If qmail- > queue sees end-of-file before the extra 0 byte, it aborts > without placing the message into the queue." > > I want to inspect messages before passing them to actuall qmail-queue > program. > Thanks in advance for your help. > -- > Regards, > Hameed U. Khan > Registered Linux User #: 354374 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From alan.gauld at freenet.co.uk Wed Oct 5 11:44:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Oct 2005 10:44:09 +0100 Subject: [Tutor] FW: Help Needed References: <9AA4216B8A36B9429BB00C546DF6D27201B882@schubert.OxbridgeTechnology.local> <1128497555.15926.1.camel@amdbert.oxbridgetechnology.local> Message-ID: <003d01c5c991$55cd0e70$0c01a8c0@xp> > When I am in Python Shell of the IDLE GUI, when I click Edit/Run You shouldn't be running scripts when in the shell, it executes them immediately. You use edit/run when working in a script file window. HTH, Alan G From rdm at rcblue.com Wed Oct 5 11:43:47 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 05 Oct 2005 02:43:47 -0700 Subject: [Tutor] How to strip both single and double quotes Message-ID: <6.2.1.2.2.20051005022639.05d1a050@rcblue.com> I'm writing a script that takes any text and outputs to a file a list of duples (k, word) where k is the number of occurrences of word in the text. The text will contain "words" beginning or ending with non-alphabetic characters. To strip them off I use string.strip([chars]). My question is how to use strip just once to get rid of both kinds of quotes, single and double. It seems necessary to do it something like this: # L is the original list of "words" in the text. newL = [] for word in L: word = lower(word) newWord = word.strip(".,!?;:&*'=-> References: <4342D5EC.3000606@gmail.com> Message-ID: <4343A6AF.2020804@tds.net> Andrew P wrote: > Normally I wouldn't pipe up here because threads really can be very > tricky. But check out: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883 > > I use this recipe, originally from "Python in a Nutshell", all the time, > to solve exactly your problem. Slow network stuff that I don't have > to/want to babysit. There are also several recipes showing how to use a worker thread from a GUI program, for example this one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 Kent From kent37 at tds.net Wed Oct 5 12:29:19 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 06:29:19 -0400 Subject: [Tutor] Help Needed In-Reply-To: References: Message-ID: <4343AAFF.9040703@tds.net> Steve Haley wrote: > When I am in Python Shell of the IDLE GUI, when I click Edit/Run Script, > I am getting a dialog box that is titled ?Not saved? and states ?The > buffer for Python shell is not saved. Please save it first.? With an > ?OK? button that just takes me back to the Shell window. I am going > through a book (which suggests this resource as a good place to ask > questions) and Edit/Run Script was working just fine the other day. This sounds kind of strange. I don't see an Edit / Run Script menu in IDLE for Python 2.3 or 2.4. I have a Run / Run Module command that is only available in the edit windows, not in the shell. What version of Python are you using? Maybe you have a version with this menu. Normally you don't run directly from the shell window, it is for typing in commands interactively. You should open a new window and do your editing there. Danny Yoo has a good introduction to IDLE here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html Kent From singletoned at gmail.com Wed Oct 5 13:21:42 2005 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 5 Oct 2005 12:21:42 +0100 Subject: [Tutor] htmllib Message-ID: <34bb7f5b0510050421s50a162b6n@mail.gmail.com> I want to dump a html file into a python object. Each nested tag would be a sub-object, attributes would be properties. So that I can use Python in a similar way to the way I use JavaScript within a web page. I looked at htmllib, but the documentation seems quite limited, and as far as I can tell, I would have to write code for every single potential tag in my page. Is there a way to do this, or access the DOM through Python or something? Thanks Ed From alan.gauld at freenet.co.uk Wed Oct 5 13:38:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Oct 2005 12:38:53 +0100 Subject: [Tutor] How to strip both single and double quotes References: <6.2.1.2.2.20051005022639.05d1a050@rcblue.com> Message-ID: <005201c5c9a1$5d1768a0$0c01a8c0@xp> > how to use strip just once to get rid of both kinds of quotes, single and > double. It seems necessary to do it something like this: JUst escape the quote character: s.strip('\'"') HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Oct 5 13:52:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 07:52:36 -0400 Subject: [Tutor] htmllib In-Reply-To: <34bb7f5b0510050421s50a162b6n@mail.gmail.com> References: <34bb7f5b0510050421s50a162b6n@mail.gmail.com> Message-ID: <4343BE84.7090904@tds.net> Ed Singleton wrote: > I want to dump a html file into a python object. Each nested tag > would be a sub-object, attributes would be properties. So that I can > use Python in a similar way to the way I use JavaScript within a web > page. I don't know of a way to run Python from within a web page. But if you want to fetch an HTML page from a server and work with it (for example a web-scraping app), many people use BeautifulSoup for this. If you have well-formed HTML or XHTML you can use an XML parser as well but BS has the advantage of coping with badly-formed HTML. http://www.crummy.com/software/BeautifulSoup/ Kent From thomas.s.mark at gmail.com Wed Oct 5 13:56:13 2005 From: thomas.s.mark at gmail.com (Mark Thomas) Date: Wed, 5 Oct 2005 07:56:13 -0400 Subject: [Tutor] How to strip both single and double quotes In-Reply-To: <6.2.1.2.2.20051005022639.05d1a050@rcblue.com> References: <6.2.1.2.2.20051005022639.05d1a050@rcblue.com> Message-ID: <7b9699030510050456x6e921b86k14467c78646c4b2@mail.gmail.com> On 10/5/05, Dick Moores wrote: > The text will contain "words" beginning or ending with non-alphabetic > characters. To strip them off I use string.strip([chars]). My question is > how to use strip just once to get rid of both kinds of quotes, single and > double. It seems necessary to do it something like this: Not sure what you mean by 'words' but how about something like this. [x.strip('\' \" () * & ^ % $ # < ') for x in word.split()] Example: >>> str = 'this has special characters \" \' ()*&^%$# << ' >>> [x.strip('\' \" () * & ^ % $ # < ') for x in str.split()] ['this', 'has', 'special', 'characters', '', '', '', ''] -- _ ( ) Mark Thomas ASCII ribbon campaign X www.theswamp.org - against HTML email / \ From singletoned at gmail.com Wed Oct 5 14:02:40 2005 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 5 Oct 2005 13:02:40 +0100 Subject: [Tutor] htmllib In-Reply-To: <4343BE84.7090904@tds.net> References: <34bb7f5b0510050421s50a162b6n@mail.gmail.com> <4343BE84.7090904@tds.net> Message-ID: <34bb7f5b0510050502u71a303cl@mail.gmail.com> You're like some kind of god! That's exactly what I need. Thanks Ed On 05/10/05, Kent Johnson wrote: > Ed Singleton wrote: > > I want to dump a html file into a python object. Each nested tag > > would be a sub-object, attributes would be properties. So that I can > > use Python in a similar way to the way I use JavaScript within a web > > page. > > I don't know of a way to run Python from within a web page. But if you want to fetch an HTML page from a server and work with it (for example a web-scraping app), many people use BeautifulSoup for this. If you have well-formed HTML or XHTML you can use an XML parser as well but BS has the advantage of coping with badly-formed HTML. > http://www.crummy.com/software/BeautifulSoup/ > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Wed Oct 5 14:53:55 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 05 Oct 2005 05:53:55 -0700 Subject: [Tutor] How to strip both single and double quotes In-Reply-To: <005201c5c9a1$5d1768a0$0c01a8c0@xp> References: <6.2.1.2.2.20051005022639.05d1a050@rcblue.com> <005201c5c9a1$5d1768a0$0c01a8c0@xp> Message-ID: <6.2.1.2.2.20051005055109.05adf8c0@rcblue.com> Alan Gauld wrote at 04:38 10/5/2005: > > how to use strip just once to get rid of both kinds of quotes, single > and > > double. It seems necessary to do it something like this: > >JUst escape the quote character: > >s.strip('\'"') That did it! Thanks, Dick Moores From kent37 at tds.net Wed Oct 5 14:59:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 08:59:05 -0400 Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS) algorithm help] Message-ID: <4343CE19.7020500@tds.net> Forwarding to the list -------- Original Message -------- Subject: Re: [Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help Date: Tue, 4 Oct 2005 13:20:18 -0700 (PDT) From: Michael Cotherman To: Kent Johnson Thanks for the response, the .NET code is really a cluster, the whole cobs.cpp is below if needed. I would think just by following the spec I could write a cleaner program.. I am a noob to converting pointers in C++ to arrays in python, although the first time I see it done, I will have no problem. Can you help converting the below (what I think is the 'decoder' section) to python? even just comments to what is going on at each line... -mike UINT CCobsPackets::UnStuffData(unsigned char *src, unsigned char *dst, UINT length) { unsigned char *dstStart = dst; unsigned char *end = src + length; while (src < end) { int i, code = *src++; for (i=1; ipacketData){ delete [](delPacket->packetData); delPacket->packetData = NULL; } delete delPacket; } } while (!m_OutPacketList.IsEmpty()) { ListPacket *delPacket = (ListPacket *)m_OutPacketList.RemoveTail(); if (delPacket) { if (delPacket->packetData){ delete [](delPacket->packetData); delPacket->packetData = NULL; } delete delPacket; } } } bool CCobsPackets::Init(HWND hwndDest, UINT nCobsMsg, LPARAM lParam, UINT nMaxPacketSize) { m_hMsgWnd = hwndDest; m_nCobsMsg = nCobsMsg?nCobsMsg:mg_nDefaultCobsMsg; m_lParam = lParam; m_nMaxPacketSize = nMaxPacketSize; m_nInPacketPos = 0; if (m_pInPacketData){ delete []m_pInPacketData; m_pInPacketData = NULL; } m_pInPacketData = new unsigned char[m_nMaxPacketSize]; //TRACE0("create m_pInPacketData\n"); if (!m_pInPacketData) return false; return true; } ListPacket* CCobsPackets::NewPacket() { ListPacket *newPacket = NULL; if (m_nMaxPacketSize) { newPacket = new ListPacket; if (newPacket) { newPacket->packetData = new unsigned char[m_nMaxPacketSize]; if (newPacket->packetData) { newPacket->packetLength = 0; memset(newPacket->packetData, 0x00, m_nMaxPacketSize); } else { delete newPacket; newPacket = NULL; } } } return newPacket; } void CCobsPackets::SendEvent (EEvent eEvent, EError eError) { // Post message to the client window ::PostMessage(m_hMsgWnd,m_nCobsMsg,MAKEWPARAM(eEvent,eError),LPARAM(m_lParam)); } void CCobsPackets::DataReceived(unsigned char *src, UINT length) { while (m_pInPacketData && length) { if (m_nInPacketPos < m_nMaxPacketSize) { if (*src == 0x00) { if (m_nInPacketPos) { ListPacket *decodePacket = NewPacket(); if (decodePacket) { decodePacket->packetLength = UnStuffData(m_pInPacketData, decodePacket->packetData, m_nInPacketPos); m_InPacketList.AddTail(decodePacket); decodePacket->packetCommand = *(decodePacket->packetData); SendEvent(EEventReceivedPacket); } else { // Unable to decode Packet Error SendEvent(EEventPacketError, EErrorPacketDecode); } } else { // throw away zero-byte packets } memset(m_pInPacketData, 0x00, m_nMaxPacketSize); m_nInPacketPos = 0; } else { m_pInPacketData[m_nInPacketPos++] = *src; } src++; } else { // Packet Overrun Error SendEvent(EEventPacketError, EErrorPacketOverrun); memset(m_pInPacketData, 0x00, m_nMaxPacketSize); m_nInPacketPos = 0; return; } length--; } } void CCobsPackets::SendPacket(unsigned char *src, UINT length) { ListPacket *encodePacket = NewPacket(); if (encodePacket) { encodePacket->packetCommand = *src; encodePacket->packetLength = StuffData(src, encodePacket->packetData, length); m_OutPacketList.AddTail(encodePacket); SendEvent(EEventSendPacket); } else { // Unable to decode Packet Error SendEvent(EEventPacketError, EErrorPacketDecode); } } BYTE CCobsPackets::GetPacket(EEvent eEvent, unsigned char *data, UINT *length) { ListPacket *pPacket = NULL; BYTE packetCommand = 0; switch (eEvent) { case EEventReceivedPacket: if (!m_InPacketList.IsEmpty()) pPacket = (ListPacket *) m_InPacketList.RemoveHead(); break; case EEventSendPacket: if (!m_OutPacketList.IsEmpty()) pPacket = (ListPacket *) m_OutPacketList.RemoveHead(); break; } if (pPacket) { packetCommand = pPacket->packetCommand; if (pPacket->packetData) { if (data && *length && pPacket->packetLength) { *length = (*length < pPacket->packetLength) ? *length : pPacket->packetLength; memcpy(data, pPacket->packetData, *length); } else { *length = 0; } delete [](pPacket->packetData); pPacket->packetData = NULL; } else { *length = 0; } delete pPacket; } return packetCommand; } #define FinishBlock(_x_) (*code_ptr = (_x_), \ code_ptr = dst++, \ code = 0x01 ) UINT CCobsPackets::StuffData(unsigned char *src, unsigned char *dst, UINT length) { unsigned char *dstStart = dst; unsigned char *end = src + length; unsigned char *code_ptr = dst++; unsigned char code = 0x01; while (src < end) { if (*src == 0) FinishBlock(code); else { *dst++ = *src; code++; if (code == 0xFF) FinishBlock(code); } src++; } FinishBlock(code); return (UINT)(dst - dstStart); } UINT CCobsPackets::UnStuffData(unsigned char *src, unsigned char *dst, UINT length) { unsigned char *dstStart = dst; unsigned char *end = src + length; while (src < end) { int i, code = *src++; for (i=1; i References: <20051004202018.29251.qmail@web31809.mail.mud.yahoo.com> Message-ID: <4343CE1D.5010705@tds.net> Michael Cotherman wrote: > I am a noob to converting pointers in C++ to arrays in > python, although the first time I see it done, I will > have no problem. Can you help converting the below > (what I think is the 'decoder' section) to python? OK I'll bite. Your code is copying from a src buffer to a dst buffer. The src buffer has a count byte followed by count-1 bytes of data. If the count is less that 0xFF, a zero byte has to be inserted into the dst. So the decode loop gets a count, copies that many bytes to the dst buffer, then optionally appends a 0. Python doesn't have a direct equivalent to this sort of manipulation of memory pointers and raw memory buffers. They are commonly replaced by strings or lists. My function takes a string as an input argument, builds the output as string fragments in a list, then builds a string to return. Note that Python strings include an implicit length so there is no need to pass and return a length argument. I included a test case with the data from your previous email. Your data is evidently hex-encoded as well as COBS encoded - in other words your strings are hex values where each two chars represent a single byte. I have converted to and from byte strings to feed this to the decoder. Kent PS Please send your replies to the whole list, not to me personally. Thanks! def unstuff(src): # src is a COBS compressed string current = 0 # index into src dst = [] # a list that will build the result while current < len(src): # Get the count and convert it to an integer count = ord(src[current]) # Append count-1 chars from src to dst dst.append(src[current+1:current+count]) # Do we need to add a zero byte? if count < 0xFF: dst.append('\x00') # Bump the counter and continue if count>0: current += count else: current += 1 # dst is a list of string fragments; this converts it to a single string return ''.join(dst) def hexToString(hexStr): ''' Convert a string of two-digit hex values to a string of bytes with those values ''' return ''.join([chr(int(hexStr[i:i+2], 16)) for i in range(0, len(hexStr), 2)]) def stringToHex(src): ''' Convert a byte string to a string of two-digit hex values ''' return ''.join([ '%02x' % ord(s) for s in src ]) if __name__ == '__main__': data = '0002860104DB203F0100' print data data = hexToString(data) print newData = unstuff(data) print stringToHex(newData) > UINT CCobsPackets::UnStuffData(unsigned char *src, > unsigned char *dst, UINT length) > { > unsigned char *dstStart = dst; > unsigned char *end = src + length; > > while (src < end) > { > int i, code = *src++; > > for (i=1; i { > *dst++ = *src++; > } > > if (code < 0xFF) > { > *dst++ = 0; > } > } > > return (UINT)(dst - dstStart); > } From alan.gauld at freenet.co.uk Wed Oct 5 16:42:01 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Oct 2005 15:42:01 +0100 Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] References: <4343CE19.7020500@tds.net> Message-ID: <007901c5c9ba$f5985b70$0c01a8c0@xp> > I am a noob to converting pointers in C++ to arrays in > python, although the first time I see it done, I will > have no problem. Can you help converting the below > (what I think is the 'decoder' section) to python? It won't be working code but I think this is whats happening... > UINT CCobsPackets::UnStuffData(unsigned char *src, > unsigned char *dst, UINT length) def UnStuffData(src,dst,len): > { > unsigned char *dstStart = dst; > unsigned char *end = src + length; # I don't think these are needed for Pyhon. > while (src < end) for code in src: > { > int code = *src++; > for (int i=1; i { > *dst++ = *src++; > } for i in range(1,code): dst.append(i) > if (code < 0xFF) > { > *dst++ = 0; > } if code < 0xff dst.append('\0') # may not be needed in python... > } > return (UINT)(dst - dstStart); > } This looks odd, I don't think I understand what it does. It seems to return an address thats potentially (probably?!) before the start of the original dst... I think it should probably translate to return dst Does that help? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Oct 5 16:46:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 10:46:54 -0400 Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] In-Reply-To: <007901c5c9ba$f5985b70$0c01a8c0@xp> References: <4343CE19.7020500@tds.net> <007901c5c9ba$f5985b70$0c01a8c0@xp> Message-ID: <4343E75E.3010504@tds.net> Alan Gauld wrote: >> return (UINT)(dst - dstStart); >> } > > > This looks odd, I don't think I understand what it does. > It seems to return an address thats potentially (probably?!) > before the start of the original dst... It's returning the length of dst. Kent From bgailer at alum.rpi.edu Wed Oct 5 16:56:52 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 05 Oct 2005 07:56:52 -0700 Subject: [Tutor] Line continuation with readlines In-Reply-To: <20051004022051.65716.qmail@web52710.mail.yahoo.com> References: <20051004022051.65716.qmail@web52710.mail.yahoo.com> Message-ID: <6.1.2.0.0.20051005074733.03564ab8@mail.mric.net> At 07:20 PM 10/3/2005, Craig MacFarlane wrote: >Hello, > >Is there a way to make line continuation work with >the readlines function? > >i.e. Do you mean e.g.? > this is \ > one line. I assume the above is a 2 line file you wish to read using a file object's readlines method. There is nothing native to help you. I suggest you use the read method, then remove any sequence of \ followed by \n then split at \n. input = file('c:/foo.txt').read() input2 = input.replace('\\\n', '') input3 = input2.split('\n') Now you have a list of "logical" lines. Note there are no \n at the end. readlines leaves the \n at the end of the lines. From mjcother at yahoo.com Wed Oct 5 18:25:11 2005 From: mjcother at yahoo.com (Michael Cotherman) Date: Wed, 5 Oct 2005 09:25:11 -0700 (PDT) Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] In-Reply-To: <007901c5c9ba$f5985b70$0c01a8c0@xp> Message-ID: <20051005162511.39943.qmail@web31809.mail.mud.yahoo.com> This is exactly what i was looking for.... For those following, the \x00 added at the end of the packet is just imaginary and represents in the meantime, I made the following that just 'decobs' a series of packets (only 8-10 bytes) that are coming in over the com port. (my incoming packets also begin with x00 for some reason) It accurately decodes that data stream (same result as when I esc out and connect with the dev kit program) I need to use what you have given me to make it scalable for size #!/usr/bin/env python #MJC 20051004 baudrate = 115200 port = 'com4' echo = 1 convert_outgoing_cr = 1 import sys, serial, threading s = serial.Serial(port,baudrate) def reader(): """loop forever and copy serial->console""" cobspacket = [0,0,0,0,0,0,0,0,0,0] while 1: i = 0 cobschar = s.read() cobspacket[i] = ord(cobschar) if cobschar == '\x00': cobschar = s.read() cobspacket[i] = ord(cobschar) codebyte = int(cobspacket[i]) while cobschar != '\x00': if i == codebyte: d = 0 codebyte = codebyte + cobspacket[i] else: d = cobspacket[i] if i>0: sys.stdout.write('%02X' % (d)) i+=1 cobschar = s.read() cobspacket[i] = ord(cobschar) sys.stdout.write('\n') def writer(): """loop forever and copy console->serial""" while 1: c = getkey() if c == '\x1b': break #exit on esc s.write(c) #send character if convert_outgoing_cr and c == '\r': s.write('\n') if echo: sys.stdout.write('\n') print "--- Mikey's interface --- type ESC to quit" #start serial->console thread r = threading.Thread(target=reader) r.setDaemon(1) r.start() #enter console->serial loop writer() print "\n--- exit ---" --- Alan Gauld wrote: > > I am a noob to converting pointers in C++ to > arrays in > > python, although the first time I see it done, I > will > > have no problem. Can you help converting the below > > (what I think is the 'decoder' section) to python? > > It won't be working code but I think this is whats > happening... > > > UINT CCobsPackets::UnStuffData(unsigned char *src, > > unsigned char *dst, UINT length) > > def UnStuffData(src,dst,len): -snip- ______________________________________________________ Yahoo! for Good Donate to the Hurricane Katrina relief effort. http://store.yahoo.com/redcross-donate3/ From Barry.Carroll at psc.com Wed Oct 5 18:36:10 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 5 Oct 2005 09:36:10 -0700 Subject: [Tutor] FW: Help Needed Message-ID: Alan is right. According to section 3.5.2 of "Learning Python, 2nd Edition", by David Ascher and Mark Lutz: Run scripts from text edit windows, not the interactive window. To run a file of code under IDLE, always select the Edit/RunScript menu option from within the text edit window where you are editing the code to be run-not from within the main interactive window where the >>> prompt appears. The RunScript option should arguably not be available in the interactive window at all (and in fact seems to have disappeared in the recent release); if you select it there, you'll wind up trying to run a log of your interactive session, with less than desirable results! Regards, Barry >Date: Wed, 5 Oct 2005 10:44:09 +0100 >From: "Alan Gauld" >Subject: Re: [Tutor] FW: Help Needed >To: "Daniel Watkins" , >Message-ID: <003d01c5c991$55cd0e70$0c01a8c0 at xp> >Content-Type: text/plain; format=flowed; charset="UTF-8"; > reply-type=original > >> When I am in Python Shell of the IDLE GUI, when I click Edit/Run > >You shouldn't be running scripts when in the shell, it executes them >immediately. >You use edit/run when working in a script file window. > >HTH, > >Alan G From mjcother at yahoo.com Wed Oct 5 19:55:21 2005 From: mjcother at yahoo.com (Michael Cotherman) Date: Wed, 5 Oct 2005 10:55:21 -0700 (PDT) Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] In-Reply-To: <007901c5c9ba$f5985b70$0c01a8c0@xp> Message-ID: <20051005175521.73181.qmail@web31807.mail.mud.yahoo.com> def UnStuffData(src,dst,len): for code in src: for i in range(1,code): dst.append(i) if code < 0xff dst.append('\0') the above is the below code uncommented... it(and the original code) just seem to find the end and puts a zero there... I do not see the existing zeroes replaced..... this is kinda why I wanted to start from the specification... here is how i see the laymans verson of the spec: get a packet (or the first 254 bytes of it) if 254 bytes, put an FF in front of them and send it on its way as a 255 byte packet, repeat this until less than 254 bytes remain. Place a byte in front of the packet that is equal to the count until the first x00 byte is found. At the location where that x00 byte was, put the count until the next x00 byte... and so on and so on... (this is where the imaginary x00 at the end comes in) decoding is: pop the first byte of the packet off and place subsequent bytes into the output until you get to the byte pointed to by the popped byte. When you reach that byte, read its value as the new 'relative' pointer, and copy x00 to the output. Proceed as above, placing bytes to the output until the relative pointer is reached or the end of the packet occurrs. I guess I need to look if I wish for this part of the program to handle the input as one big existing string, or work on it a byte at a time as it comes in. -mike c --- Alan Gauld wrote: > > I am a noob to converting pointers in C++ to > arrays in > > python, although the first time I see it done, I > will > > have no problem. Can you help converting the below > > (what I think is the 'decoder' section) to python? > > It won't be working code but I think this is whats > happening... > > > UINT CCobsPackets::UnStuffData(unsigned char *src, > > unsigned char *dst, UINT length) > > def UnStuffData(src,dst,len): > > > { > > unsigned char *dstStart = dst; > > unsigned char *end = src + length; > > # I don't think these are needed for Pyhon. > > > while (src < end) > > for code in src: > > > { > > int code = *src++; > > for (int i=1; i > { > > *dst++ = *src++; > > } > > for i in range(1,code): > dst.append(i) > > > if (code < 0xFF) > > { > > *dst++ = 0; > > } > > if code < 0xff > dst.append('\0') # may not be needed in > python... > > > } > > return (UINT)(dst - dstStart); > > } > > This looks odd, I don't think I understand what it > does. > It seems to return an address thats potentially > (probably?!) > before the start of the original dst... > > I think it should probably translate to > return dst > > Does that help? > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From rdm at rcblue.com Wed Oct 5 19:56:17 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 05 Oct 2005 10:56:17 -0700 Subject: [Tutor] New Python book Message-ID: <6.2.1.2.2.20051005105008.06a3be10@rcblue.com> Magnus Lie Hetland's new book, _Beginning Python: From Novice to Professional_ was published by Apress on Sept. 26 (in the U.S.). Very much worth a look, IMHO. But what do the tutors think? Dick Moores rdm at rcblue.com From lists at olivermaunder.co.uk Wed Oct 5 20:13:18 2005 From: lists at olivermaunder.co.uk (Oliver Maunder) Date: Wed, 5 Oct 2005 19:13:18 +0100 Subject: [Tutor] Console output Message-ID: Does anyone know how I can update a line of console output without creating a new line? I'm not explaning this too well, so here's an example. When you download a file with wget, the console display looks like this: 14% [=======> ] 344,192 16.28K/s ETA 02:19 All the figures and the progress bar get continously updated. The only way I know of sending output to the console is to use print or sys.stdout.write(), but that would give me: 14% [=======> ] 344,192 16.28K/s ETA 02:19 18% [=========> ] 344,192 16.28K/s ETA 02:19 20% [============> ] 344,192 16.28K/s ETA 02:19 ...and that's really not what I'm after! Any help and ideas would be appreciated Olly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051005/c0bd09b0/attachment-0001.htm From kent37 at tds.net Wed Oct 5 20:20:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 14:20:14 -0400 Subject: [Tutor] New Python book In-Reply-To: <6.2.1.2.2.20051005105008.06a3be10@rcblue.com> References: <6.2.1.2.2.20051005105008.06a3be10@rcblue.com> Message-ID: <4344195E.50708@tds.net> Dick Moores wrote: > Magnus Lie Hetland's new book, _Beginning Python: From Novice to > Professional_ was published by Apress on Sept. 26 (in the U.S.). Very > much worth a look, IMHO. But what do the tutors think? > > This seems to be an update to his previous book, "Practical Python", rather than a completely new book. The TOC is almost identical. I haven't read the earlier book, either, so I don't have an opinion. The same sample chapter is available for each if anyone wants to compare. (see www.apress.com) Kent From fant at pobox.com Wed Oct 5 20:41:20 2005 From: fant at pobox.com (Andrew Fant) Date: Wed, 05 Oct 2005 14:41:20 -0400 Subject: [Tutor] New Python book In-Reply-To: <4344195E.50708@tds.net> References: <6.2.1.2.2.20051005105008.06a3be10@rcblue.com> <4344195E.50708@tds.net> Message-ID: <43441E50.9010908@pobox.com> Kent Johnson wrote: > Dick Moores wrote: > >>Magnus Lie Hetland's new book, _Beginning Python: From Novice to >>Professional_ was published by Apress on Sept. 26 (in the U.S.). Very >>much worth a look, IMHO. But what do the tutors think? >> >> > > > This seems to be an update to his previous book, "Practical Python", rather than a completely new book. The TOC is almost identical. I haven't read the earlier book, either, so I don't have an opinion. The same sample chapter is available for each if anyone wants to compare. (see www.apress.com) > > Kent Has he at least changed the GUI chapters away from AnyGUI to one of the standard toolkits? The last edition would have been more use to me if it didn't do all of its GUI programming in a toolkit that the author has removed from circulation. Andy From Christian.Wyglendowski at greenville.edu Wed Oct 5 20:53:02 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed, 5 Oct 2005 13:53:02 -0500 Subject: [Tutor] Console output Message-ID: > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Oliver Maunder > Sent: Wednesday, October 05, 2005 1:13 PM > To: tutor at python.org > Subject: [Tutor] Console output > > Does anyone know how I can update a line of console output > without creating a new line? Hi Oliver, If you are on a *nix system, check out the "curses" package in the standard library. I have never used it, but it provides ways to accomplish what you are after. HTH, Christian http://www.dowski.com From rschroev_nospam_ml at fastmail.fm Wed Oct 5 20:53:32 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 05 Oct 2005 20:53:32 +0200 Subject: [Tutor] Console output In-Reply-To: References: Message-ID: Oliver Maunder wrote: > Does anyone know how I can update a line of console output without > creating a new line? I'm not explaning this too well, so here's an example. > > When you download a file with wget, the console display looks like this: > > 14% [=======> ] > 344,192 16.28K/s ETA 02:19 > > All the figures and the progress bar get continously updated. The only > way I know of sending output to the console is to use print or > sys.stdout.write(), but that would give me: > 14% [=======> ] > 344,192 16.28K/s ETA 02:19 > 18% [=========> ] > 344,192 16.28K/s ETA 02:19 > 20% [============> ] > 344,192 16.28K/s ETA 02:19 > > ...and that's really not what I'm after! > > Any help and ideas would be appreciated You need to: - not write a newline - backup to the beginning of the line Simple example: import sys import time def progress(n): for i in range(n+1): sys.stdout.write('\r%3s%% [%s>%s]' % (i, '='*i, ' '*(n-i))) sys.stdout.flush() time.sleep(0.5) progress(60) No newline is written, and the program backs up to the beginning of the line using carriage return, '\r'. You can also put the carriage return at the end of the line; the difference is that the cursor will be left at the beginning of the line instead of at the end. It's also possible to back up using backspaces ('\b'), but then you need to count how many characters you wrote and use the equal amount of backslashes. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From python-tutor at toddmaynard.com Wed Oct 5 21:10:18 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Wed, 5 Oct 2005 15:10:18 -0400 Subject: [Tutor] Console output In-Reply-To: References: Message-ID: <200510051510.18961.python-tutor@toddmaynard.com> >>> import sys >>> import time >>> myList=range(10) >>> for x in myList: ... sys.stdout.write(str(x) + "\r") ... sys.stdout.flush() ... time.sleep(1) The "\r" causes a return without a newline feed. Flush forces the text to be output (instead of getting buffered) Enjoy! Todd Maynard On Wednesday 05 October 2005 02:13 pm, Oliver Maunder wrote: > Does anyone know how I can update a line of console output without creating > a new line? I'm not explaning this too well, so here's an example. > > When you download a file with wget, the console display looks like this: > > 14% [=======> ] 344,192 16.28K/s ETA 02:19 > > All the figures and the progress bar get continously updated. The only way > I know of sending output to the console is to use print or > sys.stdout.write(), but that would give me: > 14% [=======> ] 344,192 16.28K/s ETA 02:19 > 18% [=========> ] 344,192 16.28K/s ETA 02:19 > 20% [============> ] 344,192 16.28K/s ETA 02:19 > > ...and that's really not what I'm after! > > Any help and ideas would be appreciated > > Olly From hameed.u.khan at gmail.com Wed Oct 5 21:16:10 2005 From: hameed.u.khan at gmail.com (Hameed U. Khan) Date: Thu, 6 Oct 2005 01:16:10 +0600 Subject: [Tutor] need help to understand terms for desinging a program In-Reply-To: References: <70576bd20510050155t54f94ed7ie6f6b1c7e2f7aeb1@mail.gmail.com> Message-ID: <70576bd20510051216g6896af60m738ac3ae8dfeb032@mail.gmail.com> On 10/5/05, paul brian wrote: > This is a pretty big question, and it would be easier to answer if you > can give us more details about what you want to do. > > It seems you want to inspect outgoing mails (possibly rewrite their > addresses?) before the mails are sent out. > > If you are looking to send out emails to a list then I suggest looking > at mailman - a python mailing list manager. > > If you want to use python to examine mail messages and do not care > what mailserver (MTA) you use you could try exim instead of qmail and > then try exim-python. > http://botanicus.net/dw/exim-python/exim-4.32py1.html > > > > > > On 10/5/05, Hameed U. Khan wrote: > > Hi, > > I need to make a program which will accomplish following. I dont > > need the code. I want to make it myself. But I need guidance from you > > people because I am not a good programmer. I need help in > > understanding following terms. > > > > " qmail-queue reads a mail message from descriptor 0. It > > then reads envelope information from descriptor 1. It > > places the message into the outgoing queue for future > > delivery by qmail-send. > > > > The envelope information is an envelope sender address > > followed by a list of envelope recipient addresses. The > > sender address is preceded by the letter F and terminated > > by a 0 byte. Each recipient address is preceded by the > > letter T and terminated by a 0 byte. The list of recipi- > > ent addresses is terminated by an extra 0 byte. If qmail- > > queue sees end-of-file before the extra 0 byte, it aborts > > without placing the message into the queue." > > > > I want to inspect messages before passing them to actuall qmail-queue > > program. > > Thanks in advance for your help. > > -- > > Regards, > > Hameed U. Khan > > Registered Linux User #: 354374 > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > -------------------------- > Paul Brian > m. 07875 074 534 > t. 0208 352 1741 > Thanks paul for you quick reply but I have to stick with qmail. I want to check envelopes when user attempts to send message. Because our company want to restrict some users to send message to selected domains only. I've been given this task. Anyway thanks again for your time. -- Regards, Hameed U. Khan Registered Linux User #: 354374 - *Computer without Linux is just like the world without computer.* From johan at accesstel.co.za Wed Oct 5 21:26:20 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 05 Oct 2005 21:26:20 +0200 Subject: [Tutor] Console output In-Reply-To: References: Message-ID: <434428DC.8050102@accesstel.co.za> This might help. Never used it though. Johan Christian Wyglendowski wrote: > > -----Original Message----- > > >>From: tutor-bounces at python.org >>[mailto:tutor-bounces at python.org] On Behalf Of Oliver Maunder >>Sent: Wednesday, October 05, 2005 1:13 PM >>To: tutor at python.org >>Subject: [Tutor] Console output >> >>Does anyone know how I can update a line of console output >>without creating a new line? >> >> > >Hi Oliver, > >If you are on a *nix system, check out the "curses" package in the >standard library. I have never used it, but it provides ways to >accomplish what you are after. > >HTH, > >Christian >http://www.dowski.com >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: progressbar.py Type: text/x-python Size: 2270 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051005/77bf6ec6/progressbar.py From rdm at rcblue.com Wed Oct 5 21:30:09 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 05 Oct 2005 12:30:09 -0700 Subject: [Tutor] New Python book In-Reply-To: <43441E50.9010908@pobox.com> References: <6.2.1.2.2.20051005105008.06a3be10@rcblue.com> <4344195E.50708@tds.net> <43441E50.9010908@pobox.com> Message-ID: <6.2.1.2.2.20051005122856.0792ea60@rcblue.com> Andrew Fant wrote at 11:41 10/5/2005: >Kent Johnson wrote: > > Dick Moores wrote: > > > >>Magnus Lie Hetland's new book, _Beginning Python: From Novice to > >>Professional_ was published by Apress on Sept. 26 (in the U.S.). Very > >>much worth a look, IMHO. But what do the tutors think? > >> > >> > > > > > > This seems to be an update to his previous book, "Practical Python", > rather than a completely new book. The TOC is almost identical. I > haven't read the earlier book, either, so I don't have an opinion. The > same sample chapter is available for each if anyone wants to compare. > (see www.apress.com) > > > > Kent > >Has he at least changed the GUI chapters away from AnyGUI to one of the >standard >toolkits? The last edition would have been more use to me if it didn't >do all >of its GUI programming in a toolkit that the author has removed from >circulation. No AnyGUI. Emphasis on wxPython. Dick Moores From lists at olivermaunder.co.uk Wed Oct 5 21:57:59 2005 From: lists at olivermaunder.co.uk (Oliver Maunder) Date: Wed, 5 Oct 2005 20:57:59 +0100 Subject: [Tutor] Console output In-Reply-To: <434428DC.8050102@accesstel.co.za> References: <434428DC.8050102@accesstel.co.za> Message-ID: Just what I needed - thanks everyone. I never realised '\r' was actually good for something other than Windows line breaks! Olly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051005/b7431ba7/attachment-0001.htm From alan.gauld at freenet.co.uk Wed Oct 5 22:09:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Oct 2005 21:09:27 +0100 Subject: [Tutor] Console output References: Message-ID: <00c801c5c9e8$b0591170$0c01a8c0@xp> > 14% [=======> ] 344,192 16.28K/s ETA 02:19 > > All the figures and the progress bar get continously updated. The only way > I > know of sending output to the console is to use print or > sys.stdout.write(), > but that would give me: > 14% [=======> ] 344,192 16.28K/s ETA 02:19 > 18% [=========> ] 344,192 16.28K/s ETA 02:19 > 20% [============> ] 344,192 16.28K/s ETA 02:19 Usually thats done using curses which allows ypu to address the cursor on the screen using coordinates. However for a single line you can fake it using control codes for the specific terminal. For example (as any vi user knows!) Ctrl J is line feed, Ctrl H is backspace Ctrl G is beep(I think?), Ctrl U is delete to start of line, etc You can use Ctrl H as a way of backspacing on the same line to the point you want then inserying the updated text, or just use Ctrl U to delete the line and rewrite it. You need to write to sys.stdout to do this properly and of course don't ever write a newline until you are done! HTH, Alan G. From matthew.williams at cancer.org.uk Wed Oct 5 23:13:45 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Wed, 05 Oct 2005 22:13:45 +0100 Subject: [Tutor] Accessing Variables Message-ID: <1128546825.4675.9.camel@localhost.localdomain> Dear List, I'm trying to clarify something about accessing variables. If I have ONE.py file with some variable a, and ONE imports TWO, which has a variable b, can TWO access variable a (I don't think so, but I just thought I'd check). I guess the way round this is just to make some classes & objects, and then they can easily pass parameters to each other, but I just thought I'd check. Matt From paul1brian at gmail.com Wed Oct 5 23:31:52 2005 From: paul1brian at gmail.com (paul brian) Date: Wed, 5 Oct 2005 22:31:52 +0100 Subject: [Tutor] need help to understand terms for desinging a program In-Reply-To: <70576bd20510051216g6896af60m738ac3ae8dfeb032@mail.gmail.com> References: <70576bd20510050155t54f94ed7ie6f6b1c7e2f7aeb1@mail.gmail.com> <70576bd20510051216g6896af60m738ac3ae8dfeb032@mail.gmail.com> Message-ID: I would suggest that you look firstly at qmails own built in ruleset. something like that must be achieveable without writing a special plugin. qmail control files are usually in /var/qmail/control. Nothing obvious in the man pages i am afraid. Good luck On 10/5/05, Hameed U. Khan wrote: > On 10/5/05, paul brian wrote: > > This is a pretty big question, and it would be easier to answer if you > > can give us more details about what you want to do. > > > > It seems you want to inspect outgoing mails (possibly rewrite their > > addresses?) before the mails are sent out. > > > > If you are looking to send out emails to a list then I suggest looking > > at mailman - a python mailing list manager. > > > > If you want to use python to examine mail messages and do not care > > what mailserver (MTA) you use you could try exim instead of qmail and > > then try exim-python. > > http://botanicus.net/dw/exim-python/exim-4.32py1.html > > > > > > > > > > > > On 10/5/05, Hameed U. Khan wrote: > > > Hi, > > > I need to make a program which will accomplish following. I dont > > > need the code. I want to make it myself. But I need guidance from you > > > people because I am not a good programmer. I need help in > > > understanding following terms. > > > > > > " qmail-queue reads a mail message from descriptor 0. It > > > then reads envelope information from descriptor 1. It > > > places the message into the outgoing queue for future > > > delivery by qmail-send. > > > > > > The envelope information is an envelope sender address > > > followed by a list of envelope recipient addresses. The > > > sender address is preceded by the letter F and terminated > > > by a 0 byte. Each recipient address is preceded by the > > > letter T and terminated by a 0 byte. The list of recipi- > > > ent addresses is terminated by an extra 0 byte. If qmail- > > > queue sees end-of-file before the extra 0 byte, it aborts > > > without placing the message into the queue." > > > > > > I want to inspect messages before passing them to actuall qmail-queue > > > program. > > > Thanks in advance for your help. > > > -- > > > Regards, > > > Hameed U. Khan > > > Registered Linux User #: 354374 > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > > -------------------------- > > Paul Brian > > m. 07875 074 534 > > t. 0208 352 1741 > > > > Thanks paul for you quick reply but I have to stick with qmail. I want > to check envelopes when user attempts to send message. Because our > company want to restrict some users to send message to selected > domains only. I've been given this task. Anyway thanks again for your > time. > -- > Regards, > Hameed U. Khan > Registered Linux User #: 354374 > - > *Computer without Linux is just like the world without computer.* > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From ewalker at micron.com Wed Oct 5 23:41:59 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 5 Oct 2005 15:41:59 -0600 Subject: [Tutor] Handling Objects Message-ID: <200510051541.59404.ewalker@micron.com> New to Python and trying to do some class stuff with a simple task. Problem: 1) get a list of file names in a directory 2) create variables with the same name of each filename pulled from the directory. 3) Create an object for each and pass into the __init__ method the stringname of the file name. This way I get a collection of objects that are the same name as the file name and within each instance of the class , a particular attribute will have the string name of the object. Hope this isn't too confusing.. example. class TPROJ: def __init__(self,value):#createMethod auto executes since it has __ self.BASENAME = value def display(self):#display method print self.BASENAME def getNames(): import os currentDir=os.getcwd() temp=currentDir + '/TEMP' os.chdir(temp) baseList=os.listdir(".") for name in baseList: name = TPROJ(name) print name Can anyone see what I am trying to do? Python Newbie....... From adam.jtm30 at gmail.com Wed Oct 5 23:42:26 2005 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 5 Oct 2005 22:42:26 +0100 Subject: [Tutor] Accessing Variables In-Reply-To: <1128546825.4675.9.camel@localhost.localdomain> References: <1128546825.4675.9.camel@localhost.localdomain> Message-ID: What you can do is if ONE.py has a class with the variable a, in it, you can pass the class instance (ie. self) and then you can call any function or get any global class variable. eg def foo(parent): print parent.a On 05/10/05, Matt Williams wrote: > > Dear List, > > I'm trying to clarify something about accessing variables. > > If I have ONE.py file with some variable a, and ONE imports TWO, which > has a variable b, can TWO access variable a (I don't think so, but I > just thought I'd check). > > I guess the way round this is just to make some classes & objects, and > then they can easily pass parameters to each other, but I just thought > I'd check. > > Matt > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051005/70c22171/attachment.html From paul1brian at gmail.com Wed Oct 5 23:51:43 2005 From: paul1brian at gmail.com (paul brian) Date: Wed, 5 Oct 2005 22:51:43 +0100 Subject: [Tutor] Accessing Variables In-Reply-To: <1128546825.4675.9.camel@localhost.localdomain> References: <1128546825.4675.9.camel@localhost.localdomain> Message-ID: Sort of....not really When a module is imported the following things happen import ONE a module object (dict essentially) named ONE is created. This is the module ONE.py's namespace. The module object is added to sys.modules the code in the object is executed inside the ONE dict (namespace) now if ONE has at the top import os ONE is able to use the line os.path.join (mydir, "foo.txt") If however we do not have the line import os we will get an error as the namespace of one does not have a reference to the module object of os as an example import your one.py and run pprint.pprint(sys.modules['one'].__dict__) You will see what a virgin namesapce looks like - there is a lot in there but it boils down to __builtins__, __doc__, __file__, __name__ and whatever you define (_-dict__) care notes --------------- You can easily get into circular references with imports, simply because code at the module level (ie not in a function or class) will be executed at the first import - and if it calls code that is in the next module which waits on code in the first etc etc. So as you said, put everything into classes or functions or be very careful with your imports. (I am not sure I answered the question but it is late now...:-) yrs On 10/5/05, Matt Williams wrote: > Dear List, > > I'm trying to clarify something about accessing variables. > > If I have ONE.py file with some variable a, and ONE imports TWO, which > has a variable b, can TWO access variable a (I don't think so, but I > just thought I'd check). > > I guess the way round this is just to make some classes & objects, and > then they can easily pass parameters to each other, but I just thought > I'd check. > > Matt > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From sfhaley at earthlink.net Thu Oct 6 00:21:27 2005 From: sfhaley at earthlink.net (Steve Haley) Date: Wed, 5 Oct 2005 18:21:27 -0400 Subject: [Tutor] Python Shell Not Saved Problem Message-ID: Dear folks, Just wanted to thank everyone for the help. I think I know what was going on with that "The buffer for Python Shell is not saved" message I was getting when I tried to run a script. Apparently you need to open the module before you run the script and also to re-open it each time you want to run the script. That seems a little strange to me but it appears to work that way. By the way, a couple of folks said their screen didn't look like what I described and wondered what version I was using. It is version 2.1 which I have because it that version is bundled with ESRI ArcGIS 9 which I have. I have been wondering if I can update that version but am afraid that it might be customized to ArcGIS somehow and I might mess that up if I upgrade just the Python portion. Also, someone advised that the Shell window not be used that way anyway. I think I agree and will operate from Pythonwin from now on. A couple of folks also mentioned a book, Beginning Python: From Novice to Professional. I think I might try that. Again, thanks everyone for all the help. I was very impressed with the response to my cry for help. - Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051005/d4db57af/attachment.htm From kent37 at tds.net Thu Oct 6 00:29:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 18:29:39 -0400 Subject: [Tutor] Handling Objects In-Reply-To: <200510051541.59404.ewalker@micron.com> References: <200510051541.59404.ewalker@micron.com> Message-ID: <434453D3.2020402@tds.net> Eric Walker wrote: > New to Python and trying to do some class stuff with a simple task. > Problem: > 1) get a list of file names in a directory > 2) create variables with the same name of each filename pulled from the > directory. > 3) Create an object for each and pass into the __init__ method the stringname > of the file name. > > This way I get a collection of objects that are the same name as the file name > and within each instance of the class , a particular attribute will have the > string name of the object. Hope this isn't too confusing.. example. What will you do with the names and objects once you have them? A better approach is probably to keep a dictionary that maps names to objects. If your object is really just storing the name you might as well just keep a list of names - the object isn't adding any value. If the object is going to have more behaviour then use a dict. If you really just want to print the names then you don't need to store them at all. For example with a dict: class TPROJ: # as before def getNames(): import os currentDir=os.getcwd() temp=currentDir + '/TEMP' os.chdir(temp) baseList=os.listdir(".") nameDict = {} for name in baseList: nameDict[name] = TPROJ(name) print name return nameDict HTH, Kent > > > class TPROJ: > def __init__(self,value):#createMethod auto executes since it has __ > self.BASENAME = value > > def display(self):#display method > print self.BASENAME > > def getNames(): > import os > currentDir=os.getcwd() > temp=currentDir + '/TEMP' > os.chdir(temp) > baseList=os.listdir(".") > for name in baseList: > name = TPROJ(name) > print name > > Can anyone see what I am trying to do? > > Python Newbie....... > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Oct 6 00:33:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 18:33:15 -0400 Subject: [Tutor] Accessing Variables In-Reply-To: <1128546825.4675.9.camel@localhost.localdomain> References: <1128546825.4675.9.camel@localhost.localdomain> Message-ID: <434454AB.10801@tds.net> Matt Williams wrote: > Dear List, > > I'm trying to clarify something about accessing variables. > > If I have ONE.py file with some variable a, and ONE imports TWO, which > has a variable b, can TWO access variable a (I don't think so, but I > just thought I'd check). You are right. TWO can import ONE to get access to ONE.a but circular imports are usually a bad idea and can cause subtle bugs. > > I guess the way round this is just to make some classes & objects, and > then they can easily pass parameters to each other, but I just thought > I'd check. That is a good solution. An alternative is to make a module THREE that both ONE and TWO import. Kent > > Matt > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From ewalker at micron.com Thu Oct 6 00:41:02 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 5 Oct 2005 16:41:02 -0600 Subject: [Tutor] Handling Objects In-Reply-To: <434453D3.2020402@tds.net> References: <200510051541.59404.ewalker@micron.com> <434453D3.2020402@tds.net> Message-ID: <200510051641.03012.ewalker@micron.com> Well, I think I probably can do this easier in perl but I took a vow I would try and learn python. I know I am using classes here and really don't need objects. This is just another way for me to learn how to work with classes within python. My object actually will be storing like 5 or 6 different attributes but I didn't include them in the example. These attributes will be certain things that are read from the file. Once I get the objects i want to create in another directory the same files with the same names but put different data into the new files depending on what I read from the original files. Python Newbie.... On Wednesday 05 October 2005 04:29 pm, Kent Johnson wrote: > Eric Walker wrote: > > New to Python and trying to do some class stuff with a simple task. > > Problem: > > 1) get a list of file names in a directory > > 2) create variables with the same name of each filename pulled from the > > directory. > > 3) Create an object for each and pass into the __init__ method the > > stringname of the file name. > > > > This way I get a collection of objects that are the same name as the file > > name and within each instance of the class , a particular attribute will > > have the string name of the object. Hope this isn't too confusing.. > > example. > > What will you do with the names and objects once you have them? A better > approach is probably to keep a dictionary that maps names to objects. If > your object is really just storing the name you might as well just keep a > list of names - the object isn't adding any value. If the object is going > to have more behaviour then use a dict. If you really just want to print > the names then you don't need to store them at all. For example with a > dict: > > class TPROJ: > # as before > > def getNames(): > import os > currentDir=os.getcwd() > temp=currentDir + '/TEMP' > os.chdir(temp) > baseList=os.listdir(".") > nameDict = {} > for name in baseList: > nameDict[name] = TPROJ(name) > print name > return nameDict > > HTH, > Kent > > > class TPROJ: > > def __init__(self,value):#createMethod auto executes since it has __ > > self.BASENAME = value > > > > def display(self):#display method > > print self.BASENAME > > > > def getNames(): > > import os > > currentDir=os.getcwd() > > temp=currentDir + '/TEMP' > > os.chdir(temp) > > baseList=os.listdir(".") > > for name in baseList: > > name = TPROJ(name) > > print name > > > > Can anyone see what I am trying to do? > > > > Python Newbie....... > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From marcink at ieee.org Thu Oct 6 00:43:14 2005 From: marcink at ieee.org (Marcin Komorowski) Date: Wed, 5 Oct 2005 18:43:14 -0400 Subject: [Tutor] Console output References: Message-ID: <00f701c5c9fe$2efb6270$2bf6a8c0@zobook> ----- Original Message ----- From: "Roel Schroeven" To: Sent: Wednesday, October 05, 2005 2:53 PM Subject: Re: [Tutor] Console output > Oliver Maunder wrote: >> Does anyone know how I can update a line of console output without >> creating a new line? I'm not explaning this too well, so here's an >> example. >> >> When you download a file with wget, the console display looks like this: >> >> 14% [=======> ] >> 344,192 16.28K/s ETA 02:19 >> >> All the figures and the progress bar get continously updated. The only >> way I know of sending output to the console is to use print or >> sys.stdout.write(), but that would give me: >> 14% [=======> ] >> 344,192 16.28K/s ETA 02:19 >> 18% [=========> ] >> 344,192 16.28K/s ETA 02:19 >> 20% [============> ] >> 344,192 16.28K/s ETA 02:19 >> >> ...and that's really not what I'm after! >> >> Any help and ideas would be appreciated > > You need to: > - not write a newline > - backup to the beginning of the line > > Simple example: > > import sys > import time > > def progress(n): > for i in range(n+1): > sys.stdout.write('\r%3s%% [%s>%s]' % (i, '='*i, ' '*(n-i))) > sys.stdout.flush() > time.sleep(0.5) > > progress(60) > This works nicely, but do not forget that \r does not clear what you already have on the line, so you are safe if every time you re-write the line, you output the same number of characters, but if it is less, you will have residual from previous line. The way around it is to output a line of spaces that overwrites the previous line. > No newline is written, and the program backs up to the beginning of the > line using carriage return, '\r'. You can also put the carriage return > at the end of the line; the difference is that the cursor will be left > at the beginning of the line instead of at the end. > > It's also possible to back up using backspaces ('\b'), but then you need > to count how many characters you wrote and use the equal amount of > backslashes. > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Oct 6 00:48:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 18:48:55 -0400 Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] In-Reply-To: <20051005175521.73181.qmail@web31807.mail.mud.yahoo.com> References: <20051005175521.73181.qmail@web31807.mail.mud.yahoo.com> Message-ID: <43445857.8030602@tds.net> Michael Cotherman wrote: > def UnStuffData(src,dst,len): > > for code in src: > for i in range(1,code): > dst.append(i) > > if code < 0xff > dst.append('\0') > > the above is the below code uncommented... > it(and the original code) just seem to find the end > and puts a zero there... > > I do not see the existing zeroes replaced..... this is > kinda why I wanted to start from the specification... The above is the decoding code, it does what you describe below. It is adding the zeros back in, that is the dst.append('\0') Kent > decoding is: > pop the first byte of the packet off and place > subsequent bytes into the output until you get to the > byte pointed to by the popped byte. When you reach > that byte, read its value as the new 'relative' > pointer, and copy x00 to the output. Proceed as above, > placing bytes to the output until the relative pointer > is reached or the end of the packet occurrs. > > I guess I need to look if I wish for this part of the > program to handle the input as one big existing > string, or work on it a byte at a time as it comes in. > > > -mike c From alan.gauld at freenet.co.uk Thu Oct 6 01:08:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Oct 2005 00:08:25 +0100 Subject: [Tutor] Accessing Variables References: <1128546825.4675.9.camel@localhost.localdomain> Message-ID: <001301c5ca01$b0cb03c0$0c01a8c0@xp> > If I have ONE.py file with some variable a, and ONE imports TWO, which > has a variable b, can TWO access variable a (I don't think so, but I > just thought I'd check). Correct you can't do it. And quite rightly so because trying to do so would indicate a faulty design! When we import a module it can be one of two things: 1) A generic reusable bit of code written by someone else which has no knowledge of the internal structure of our code, therefore it can never attempt to access our code. 2) A module that we have written as part of an overall solution. If that module tries to access code in our module it means we have not factored our code properly to produce reusable modules(in fact the moduile is not modular! Modules should only access their own data or the data in other modules that they import, there should not be cyclic dependencies. If there are, we have a faulty design. > I guess the way round this is just to make some classes & objects, and > then they can easily pass parameters to each other, but I just thought > I'd check. You can pass parameters between modules without resorting to classes, thats an entirely different animal; ###### ONE.py ##### import TWO onevar = TWO.twovar TWO.init(onevar) TWO.foo() ######## TWO.py #### class UninitialisedModuleError(Exception) twovar = 77 importer = None #placeholder variable def init(aValue): global onevar onevar = aValue def foo(): if onevar: print onevar else: raise UninitialisedModuleError ############# So by using an init function TWO can grab a value from whatever module imports TWO. If the module is not initialised an exception gets raised. This mechanism provides a safe way to avoid circular dependencies by keeping TWO ignorant of the innards of the importing module. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Oct 6 01:14:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Oct 2005 00:14:32 +0100 Subject: [Tutor] Python Shell Not Saved Problem References: Message-ID: <002101c5ca02$8b6bf2a0$0c01a8c0@xp> > Also, someone advised that the Shell window not be used that way anyway. > I > think I agree and will operate from Pythonwin from now on. The same applies in Pythonwin. You cannot run the interactive shell buffer because Python will try to execute all the output from the commands - they get executed as soon as you type them. You run programs from the text buffers and the output appears in the shell window. The typical way of working is: - start the IDE(IDLE or Pythonwin) - from the Shell buffer default window use File->Open(or New) to open a new code editor window - from the new window use Run to execute the code in the current edit pane. - look at the output in the shell window/pane You don't need to close the window between runs just save the code and rerun it. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Thu Oct 6 01:18:28 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 05 Oct 2005 16:18:28 -0700 Subject: [Tutor] How to write this to a file? Message-ID: <6.2.1.2.2.20051005161428.042f2a80@rcblue.com> I have a script that writes it's output to a file. I also print the time with print "Time was %.4g seconds" % (timeEnd - timeStart) How could I also have the same output of the print expression, written to the file? Thanks, Dick Moores From kent37 at tds.net Thu Oct 6 01:20:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 19:20:55 -0400 Subject: [Tutor] Handling Objects In-Reply-To: <200510051641.03012.ewalker@micron.com> References: <200510051541.59404.ewalker@micron.com> <434453D3.2020402@tds.net> <200510051641.03012.ewalker@micron.com> Message-ID: <43445FD7.6060404@tds.net> Eric Walker wrote: > Well, > I think I probably can do this easier in perl but I took a vow I would try and > learn python. I know I am using classes here and really don't need objects. > This is just another way for me to learn how to work with classes within > python. My object actually will be storing like 5 or 6 different attributes > but I didn't include them in the example. These attributes will be certain > things that are read from the file. Once I get the objects i want to create > in another directory the same files with the same names but put different > data into the new files depending on what I read from the original files. OK, I would just make a list of the objects, since one of the attributes is the name you have everything you need in the object. def getNames(): import os currentDir=os.getcwd() temp=currentDir + '/TEMP' os.chdir(temp) baseList=os.listdir(".") data = [] for name in baseList: data.append(TPROJ(name)) print name return data then to use the data something like for datum in data: f = open(datum.name, 'w') #etc Kent > > Python Newbie.... > > > On Wednesday 05 October 2005 04:29 pm, Kent Johnson wrote: > >>Eric Walker wrote: >> >>>New to Python and trying to do some class stuff with a simple task. >>>Problem: >>>1) get a list of file names in a directory >>>2) create variables with the same name of each filename pulled from the >>>directory. >>>3) Create an object for each and pass into the __init__ method the >>>stringname of the file name. >>> >>>This way I get a collection of objects that are the same name as the file >>>name and within each instance of the class , a particular attribute will >>>have the string name of the object. Hope this isn't too confusing.. >>>example. >> >>What will you do with the names and objects once you have them? A better >>approach is probably to keep a dictionary that maps names to objects. If >>your object is really just storing the name you might as well just keep a >>list of names - the object isn't adding any value. If the object is going >>to have more behaviour then use a dict. If you really just want to print >>the names then you don't need to store them at all. For example with a >>dict: >> >>class TPROJ: >> # as before >> >>def getNames(): >> import os >> currentDir=os.getcwd() >> temp=currentDir + '/TEMP' >> os.chdir(temp) >> baseList=os.listdir(".") >> nameDict = {} >> for name in baseList: >> nameDict[name] = TPROJ(name) >> print name >> return nameDict >> >>HTH, >>Kent >> >> >>>class TPROJ: >>> def __init__(self,value):#createMethod auto executes since it has __ >>> self.BASENAME = value >>> >>> def display(self):#display method >>> print self.BASENAME >>> >>>def getNames(): >>> import os >>> currentDir=os.getcwd() >>> temp=currentDir + '/TEMP' >>> os.chdir(temp) >>> baseList=os.listdir(".") >>> for name in baseList: >>> name = TPROJ(name) >>> print name >>> >>>Can anyone see what I am trying to do? >>> >>>Python Newbie....... >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Oct 6 01:22:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 19:22:22 -0400 Subject: [Tutor] Console output In-Reply-To: References: <434428DC.8050102@accesstel.co.za> Message-ID: <4344602E.5000101@tds.net> Oliver Maunder wrote: > Just what I needed - thanks everyone. I never realised '\r' was actually > good for something other than Windows line breaks! Hmm, just have to say something about the old days when 'carriage return' and 'line feed' really meant something :-) Kent From kent37 at tds.net Thu Oct 6 01:32:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 19:32:52 -0400 Subject: [Tutor] How to write this to a file? In-Reply-To: <6.2.1.2.2.20051005161428.042f2a80@rcblue.com> References: <6.2.1.2.2.20051005161428.042f2a80@rcblue.com> Message-ID: <434462A4.6000308@tds.net> Dick Moores wrote: > I have a script that writes it's output to a file. I also print the time with > > print "Time was %.4g seconds" % (timeEnd - timeStart) > > How could I also have the same output of the print expression, written to > the file? The formatting part of the print is just an expression with a string value, you can assign it to a variable and write it to your file. You might want to add a newline: timeMsg = "Time was %.4g seconds\n" % (timeEnd - timeStart) f.write(timeMsg) If you have a lot of output that you want to put to the console and to a log file you might like to look at the logging module. A single line of logging can be written to multiple places by the module. Kent From ewalker at micron.com Thu Oct 6 01:44:01 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 5 Oct 2005 17:44:01 -0600 Subject: [Tutor] Handling Objects In-Reply-To: <43445FD7.6060404@tds.net> References: <200510051541.59404.ewalker@micron.com> <200510051641.03012.ewalker@micron.com> <43445FD7.6060404@tds.net> Message-ID: <200510051744.01628.ewalker@micron.com> Thanks Kent.. I think that would work for what I am doing. So is it safe to say that python doesn't do variable interpolation like perl..? Thanks in advance. Python Newbie... On Wednesday 05 October 2005 05:20 pm, Kent Johnson wrote: > Eric Walker wrote: > > Well, > > I think I probably can do this easier in perl but I took a vow I would > > try and learn python. I know I am using classes here and really don't > > need objects. This is just another way for me to learn how to work with > > classes within python. My object actually will be storing like 5 or 6 > > different attributes but I didn't include them in the example. These > > attributes will be certain things that are read from the file. Once I > > get the objects i want to create in another directory the same files with > > the same names but put different data into the new files depending on > > what I read from the original files. > > OK, I would just make a list of the objects, since one of the attributes is > the name you have everything you need in the object. > > def getNames(): > import os > currentDir=os.getcwd() > temp=currentDir + '/TEMP' > os.chdir(temp) > baseList=os.listdir(".") > data = [] > for name in baseList: > data.append(TPROJ(name)) > print name > return data > > then to use the data something like > for datum in data: > f = open(datum.name, 'w') > #etc > > Kent > > > Python Newbie.... > > > > On Wednesday 05 October 2005 04:29 pm, Kent Johnson wrote: > >>Eric Walker wrote: > >>>New to Python and trying to do some class stuff with a simple task. > >>>Problem: > >>>1) get a list of file names in a directory > >>>2) create variables with the same name of each filename pulled from the > >>>directory. > >>>3) Create an object for each and pass into the __init__ method the > >>>stringname of the file name. > >>> > >>>This way I get a collection of objects that are the same name as the > >>> file name and within each instance of the class , a particular > >>> attribute will have the string name of the object. Hope this isn't too > >>> confusing.. example. > >> > >>What will you do with the names and objects once you have them? A better > >>approach is probably to keep a dictionary that maps names to objects. If > >>your object is really just storing the name you might as well just keep a > >>list of names - the object isn't adding any value. If the object is going > >>to have more behaviour then use a dict. If you really just want to print > >>the names then you don't need to store them at all. For example with a > >>dict: > >> > >>class TPROJ: > >> # as before > >> > >>def getNames(): > >> import os > >> currentDir=os.getcwd() > >> temp=currentDir + '/TEMP' > >> os.chdir(temp) > >> baseList=os.listdir(".") > >> nameDict = {} > >> for name in baseList: > >> nameDict[name] = TPROJ(name) > >> print name > >> return nameDict > >> > >>HTH, > >>Kent > >> > >>>class TPROJ: > >>> def __init__(self,value):#createMethod auto executes since it has __ > >>> self.BASENAME = value > >>> > >>> def display(self):#display method > >>> print self.BASENAME > >>> > >>>def getNames(): > >>> import os > >>> currentDir=os.getcwd() > >>> temp=currentDir + '/TEMP' > >>> os.chdir(temp) > >>> baseList=os.listdir(".") > >>> for name in baseList: > >>> name = TPROJ(name) > >>> print name > >>> > >>>Can anyone see what I am trying to do? > >>> > >>>Python Newbie....... > >>>_______________________________________________ > >>>Tutor maillist - Tutor at python.org > >>>http://mail.python.org/mailman/listinfo/tutor > >> > >>_______________________________________________ > >>Tutor maillist - Tutor at python.org > >>http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From kent37 at tds.net Thu Oct 6 01:52:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 19:52:40 -0400 Subject: [Tutor] Handling Objects In-Reply-To: <200510051744.01628.ewalker@micron.com> References: <200510051541.59404.ewalker@micron.com> <200510051641.03012.ewalker@micron.com> <43445FD7.6060404@tds.net> <200510051744.01628.ewalker@micron.com> Message-ID: <43446748.3020709@tds.net> Eric Walker wrote: > Thanks Kent.. I think that would work for what I am doing. So is it safe to > say that python doesn't do variable interpolation like perl..? I think so, though I don't really speak perl. The closest approximation is the string formatting operation and the string.Template class. http://docs.python.org/lib/typesseq-strings.html http://docs.python.org/lib/node109.html Kent > > Thanks in advance. > > Python Newbie... > > > On Wednesday 05 October 2005 05:20 pm, Kent Johnson wrote: > >>Eric Walker wrote: >> >>>Well, >>>I think I probably can do this easier in perl but I took a vow I would >>>try and learn python. I know I am using classes here and really don't >>>need objects. This is just another way for me to learn how to work with >>>classes within python. My object actually will be storing like 5 or 6 >>>different attributes but I didn't include them in the example. These >>>attributes will be certain things that are read from the file. Once I >>>get the objects i want to create in another directory the same files with >>>the same names but put different data into the new files depending on >>>what I read from the original files. >> >>OK, I would just make a list of the objects, since one of the attributes is >>the name you have everything you need in the object. >> >>def getNames(): >> import os >> currentDir=os.getcwd() >> temp=currentDir + '/TEMP' >> os.chdir(temp) >> baseList=os.listdir(".") >> data = [] >> for name in baseList: >> data.append(TPROJ(name)) >> print name >> return data >> >>then to use the data something like >>for datum in data: >> f = open(datum.name, 'w') >> #etc >> >>Kent >> >> >>>Python Newbie.... >>> >>>On Wednesday 05 October 2005 04:29 pm, Kent Johnson wrote: >>> >>>>Eric Walker wrote: >>>> >>>>>New to Python and trying to do some class stuff with a simple task. >>>>>Problem: >>>>>1) get a list of file names in a directory >>>>>2) create variables with the same name of each filename pulled from the >>>>>directory. >>>>>3) Create an object for each and pass into the __init__ method the >>>>>stringname of the file name. >>>>> >>>>>This way I get a collection of objects that are the same name as the >>>>>file name and within each instance of the class , a particular >>>>>attribute will have the string name of the object. Hope this isn't too >>>>>confusing.. example. >>>> >>>>What will you do with the names and objects once you have them? A better >>>>approach is probably to keep a dictionary that maps names to objects. If >>>>your object is really just storing the name you might as well just keep a >>>>list of names - the object isn't adding any value. If the object is going >>>>to have more behaviour then use a dict. If you really just want to print >>>>the names then you don't need to store them at all. For example with a >>>>dict: >>>> >>>>class TPROJ: >>>> # as before >>>> >>>>def getNames(): >>>> import os >>>> currentDir=os.getcwd() >>>> temp=currentDir + '/TEMP' >>>> os.chdir(temp) >>>> baseList=os.listdir(".") >>>> nameDict = {} >>>> for name in baseList: >>>> nameDict[name] = TPROJ(name) >>>> print name >>>> return nameDict >>>> >>>>HTH, >>>>Kent >>>> >>>> >>>>>class TPROJ: >>>>> def __init__(self,value):#createMethod auto executes since it has __ >>>>> self.BASENAME = value >>>>> >>>>> def display(self):#display method >>>>> print self.BASENAME >>>>> >>>>>def getNames(): >>>>> import os >>>>> currentDir=os.getcwd() >>>>> temp=currentDir + '/TEMP' >>>>> os.chdir(temp) >>>>> baseList=os.listdir(".") >>>>> for name in baseList: >>>>> name = TPROJ(name) >>>>> print name >>>>> >>>>>Can anyone see what I am trying to do? >>>>> >>>>>Python Newbie....... >>>>>_______________________________________________ >>>>>Tutor maillist - Tutor at python.org >>>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor at python.org >>>>http://mail.python.org/mailman/listinfo/tutor >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > From ewalker at micron.com Thu Oct 6 01:52:53 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 5 Oct 2005 17:52:53 -0600 Subject: [Tutor] regExpress Message-ID: <200510051752.54061.ewalker@micron.com> All, If I have something like this: import re sample = 'myboss:isbad' express = re.compile('(.*):(.*)) answer = re.match(express,sample) how do I get it to tell me if it was a match or not. I have tried answer.match . It just gives me an object pointer or something. Thanks Python Newbie... From rdm at rcblue.com Thu Oct 6 02:05:08 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 05 Oct 2005 17:05:08 -0700 Subject: [Tutor] How to write this to a file? In-Reply-To: <434462A4.6000308@tds.net> References: <6.2.1.2.2.20051005161428.042f2a80@rcblue.com> <434462A4.6000308@tds.net> Message-ID: <6.2.1.2.2.20051005164635.02ae5e60@rcblue.com> Kent Johnson wrote at 16:32 10/5/2005: >Dick Moores wrote: > > I have a script that writes it's output to a file. I also print the > time with > > > > print "Time was %.4g seconds" % (timeEnd - timeStart) > > > > How could I also have the same output of the print expression, > written to > > the file? > >The formatting part of the print is just an expression with a string >value, you can assign it to a variable and write it to your file. You >might want to add a newline: > >timeMsg = "Time was %.4g seconds\n" % (timeEnd - timeStart) >f.write(timeMsg) Thanks, Kent, that works! >If you have a lot of output that you want to put to the console and to a >log file you might like to look at the logging module. A single line of >logging can be written to multiple places by the module. I'll check out the logging module. Dick From kent37 at tds.net Thu Oct 6 02:06:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 20:06:23 -0400 Subject: [Tutor] regExpress In-Reply-To: <200510051752.54061.ewalker@micron.com> References: <200510051752.54061.ewalker@micron.com> Message-ID: <43446A7F.4030400@tds.net> Eric Walker wrote: > All, > If I have something like this: > import re > sample = 'myboss:isbad' > express = re.compile('(.*):(.*)) > answer = re.match(express,sample) > > how do I get it to tell me if it was a match or not. I have tried > answer.match . It just gives me an object pointer or something. re.match() will return None if there is no match, or a match object if it succeeds. And your syntax isn't quite right, if you compile the re then call match() directly on the compiled object. With re.match() you pass the re string as the first arg and you don't have to compile it. In either case, the methods of the match object give details of the match. http://docs.python.org/lib/match-objects.html Finally, you may want to use re.search() instead of match(); match will only match the re at the beginning of the string, kind of like if the re started with '^'. >>> import re >>> sample = 'myboss:isbad' >>> express = re.compile('(.*):(.*)') >>> answer = express.match(sample) >>> answer <_sre.SRE_Match object at 0x008C4A40> >>> answer.groups() ('myboss', 'isbad') >>> answer = express.match('No colon here, move along') >>> answer >>> print answer None Kent From 3dbernard at gmail.com Thu Oct 6 03:22:23 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 5 Oct 2005 21:22:23 -0400 Subject: [Tutor] Getting name scope Message-ID: <61d0e2b40510051822w128852a2jb3bd2b8e8cf80a36@mail.gmail.com> Hello, Anyone know if it is possible to find out in what scope lies a name? For instance, let say I'm using a name in a function, but the name is actually in the global scope. I would like to know if this name was found in what scope. Is it possible at all? Thanks Bernard From kent37 at tds.net Thu Oct 6 03:30:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 21:30:51 -0400 Subject: [Tutor] Embedding In-Reply-To: <433AAC5A.2030208@gmail.com> References: <433AAC5A.2030208@gmail.com> Message-ID: <43447E4B.1050608@tds.net> You might be interested in this article about making a game in a week using Python and Pygame: http://www.gamedev.net/reference/articles/article2259.asp Joseph Quigley wrote: > Hi, > Ok, I'll try to convince them to try python... but still, would it be > best to just: > Program in C with Python and Java scripts > Program in Python with a little bit of C? > > The game we're trying to make is a Super Mario type game (or super tux > for you like linux games). > I suppose pygame would make it a breeze for video, sound and graphics! > My only problem is I haven't done any games withy pygame at all and > can't find any pygame tutorials (when I google). > Thanks, > Joe > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Oct 6 03:47:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Oct 2005 21:47:39 -0400 Subject: [Tutor] Getting name scope In-Reply-To: <61d0e2b40510051822w128852a2jb3bd2b8e8cf80a36@mail.gmail.com> References: <61d0e2b40510051822w128852a2jb3bd2b8e8cf80a36@mail.gmail.com> Message-ID: <4344823B.4050601@tds.net> Bernard Lebel wrote: > Hello, > > Anyone know if it is possible to find out in what scope lies a name? > For instance, let say I'm using a name in a function, but the name is > actually in the global scope. I would like to know if this name was > found in what scope. Is it possible at all? Look for the name in locals() and globals()? But why do you care? >>> a=1 >>> def scopeOf(name): ... x=3 ... if name in locals(): ... print name, 'is local' ... elif name in globals(): ... print name, 'is global' ... else: ... print 'I don\'t know about', name ... >>> scopeOf('x') x is local >>> scopeOf('a') a is global >>> scopeOf('foo') I don't know about foo This assumes that you actually know the name as a string. If you are trying to find out something about the variable in the calling scope then it is harder. There are hacks to find out the name of the variable in the calling scope but why? Kent From 3dbernard at gmail.com Thu Oct 6 04:15:13 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 5 Oct 2005 22:15:13 -0400 Subject: [Tutor] Getting name scope In-Reply-To: <4344823B.4050601@tds.net> References: <61d0e2b40510051822w128852a2jb3bd2b8e8cf80a36@mail.gmail.com> <4344823B.4050601@tds.net> Message-ID: <61d0e2b40510051915n592ef056i17804a738f0a40a3@mail.gmail.com> Thanks for the answer. I have to confess this question is driven only by curiosity, I was not even hoping to get such a function. I was reading some stuff about the scopes in JScript and somehow this question arose in my mind. For the record, the tutorial I am watching said that a name exists *only* inside a block, wich is a local scope itself. So that statement defied my experience with JScript so I wanted to put it to the test: (this is JScript code ran into a 3D application that embeds Python, JScript and few other activeX-capable langages). var oSel = selection(0); if ( oSel.type == 'polymsh' ) { var oMesh = oSel; } logmessage( oMesh.name ); //Output //INFO : sphere Then I was curious if it would have been the same in Python (I knew it was not, but tested it nonetheless): oSel = Application.selection(0) if oSel.type == 'polymsh': oMesh = oSel Application.logmessage( oMesh.name ) #Output #INFO : sphere So then the question arised if it was possible in Python to know to what scope a name belongs. I don't know any use for this, but I just wanted to know it was possible. Thanks! Bernard On 10/5/05, Kent Johnson wrote: > Bernard Lebel wrote: > > Hello, > > > > Anyone know if it is possible to find out in what scope lies a name? > > For instance, let say I'm using a name in a function, but the name is > > actually in the global scope. I would like to know if this name was > > found in what scope. Is it possible at all? > > Look for the name in locals() and globals()? But why do you care? > > >>> a=1 > >>> def scopeOf(name): > ... x=3 > ... if name in locals(): > ... print name, 'is local' > ... elif name in globals(): > ... print name, 'is global' > ... else: > ... print 'I don\'t know about', name > ... > >>> scopeOf('x') > x is local > >>> scopeOf('a') > a is global > >>> scopeOf('foo') > I don't know about foo > > This assumes that you actually know the name as a string. If you are trying to find out something about the variable in the calling scope then it is harder. There are hacks to find out the name of the variable in the calling scope but why? > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sli1que at yahoo.com Thu Oct 6 05:29:06 2005 From: sli1que at yahoo.com (Eric Walker) Date: Wed, 5 Oct 2005 20:29:06 -0700 (PDT) Subject: [Tutor] regExpress In-Reply-To: <43446A7F.4030400@tds.net> Message-ID: <20051006032906.99256.qmail@web60122.mail.yahoo.com> Thanks so much Kent.. Eric ... --- Kent Johnson wrote: > Eric Walker wrote: > > All, > > If I have something like this: > > import re > > sample = 'myboss:isbad' > > express = re.compile('(.*):(.*)) > > answer = re.match(express,sample) > > > > how do I get it to tell me if it was a match or > not. I have tried > > answer.match . It just gives me an object pointer > or something. > > re.match() will return None if there is no match, or > a match object if it succeeds. And your syntax isn't > quite right, if you compile the re then call match() > directly on the compiled object. With re.match() you > pass the re string as the first arg and you don't > have to compile it. In either case, the methods of > the match object give details of the match. > http://docs.python.org/lib/match-objects.html > > Finally, you may want to use re.search() instead of > match(); match will only match the re at the > beginning of the string, kind of like if the re > started with '^'. > > >>> import re > >>> sample = 'myboss:isbad' > >>> express = re.compile('(.*):(.*)') > >>> answer = express.match(sample) > >>> answer > <_sre.SRE_Match object at 0x008C4A40> > >>> answer.groups() > ('myboss', 'isbad') > >>> answer = express.match('No colon here, move > along') > >>> answer > >>> print answer > None > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From grouch at gmail.com Thu Oct 6 05:35:57 2005 From: grouch at gmail.com (Andrew P) Date: Wed, 5 Oct 2005 22:35:57 -0500 Subject: [Tutor] Handling Objects In-Reply-To: <200510051744.01628.ewalker@micron.com> References: <200510051541.59404.ewalker@micron.com> <200510051641.03012.ewalker@micron.com> <43445FD7.6060404@tds.net> <200510051744.01628.ewalker@micron.com> Message-ID: To do: $color = "Green"; print "$color apple.\n"; You would want: color = "Green" print "%s apple." % color Both of which would print "Green apple." That is actually something I like about Perl, but it reinforces some bad habits, at least for me. Boilerplate coding, as it were, when doing quick and dirty web stuff, which always ends up growing! That and inline regex will probably be the hardest thing to get used to. Good luck with Python, but you really won't need it. I wrote a script in Perl today to show a friend how to do something, and it reinforced the amazing amount of -stuff- you need to remember to use Perl, and the mind-draining way you can't type without thinking about which way you will type it. I swear it scares people away from other languages for life :) Python will be much, much easier to learn. And hopefully you'll spend more time typing what you want, than deciding how you should type it, while doing the exact same things you always did. On 10/5/05, Eric Walker wrote: > > Thanks Kent.. I think that would work for what I am doing. So is it safe > to > say that python doesn't do variable interpolation like perl..? > > Thanks in advance. > > Python Newbie... > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051005/5ffc07db/attachment.htm From dubberlyr at msn.com Thu Oct 6 00:15:00 2005 From: dubberlyr at msn.com (Rosalee Dubberly) Date: Wed, 05 Oct 2005 15:15:00 -0700 Subject: [Tutor] still not getting 'it' Message-ID: I am having problems with changing the parameters in my second function. I want the second function to run the same as the first, but take different parameters. What am I doing wrong???? def firstpart(): """Define a function that takes no parameters and does the following: Returns (not prints) a list of 512 items, each consisting of the string, 'passed', unless the index of the item is a multiple of 3, 7, or 11, in which case the string for that index is 'tryagain'""" for n in range( 0, 55 ): if n % 3 == 0 or n % 7 == 0 or n % 11 == 0: print 'passed,', else: print 'tryagain,', return firstpart def changes(passed=success, tryagain=fail): """Define a second function that acts in the same way as the first function, except that it takes parameters whose values replace 'passed' and 'tryagain' in the first function.""" for n in range ( 0, 55 ): if n % 3 == 0 or n % 7 == 0 or n % 11 == 0: print ' passed,', else: print 'tryagain,', alist.append(['success', 'fail']) return alist thelist = changes('success', 'fail') _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From dyoo at hkn.eecs.berkeley.edu Thu Oct 6 09:12:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Oct 2005 00:12:49 -0700 (PDT) Subject: [Tutor] still not getting 'it' In-Reply-To: Message-ID: On Wed, 5 Oct 2005, Rosalee Dubberly wrote: > I am having problems with changing the parameters in my second function. > I want the second function to run the same as the first, but take > different parameters. What am I doing wrong???? Hi Rosalee, [First, make sure you're subscribed to Tutor; it appears that you're still not subscribed, so every post that you've made to the list so far has been manually moderated. See: http://mail.python.org/mailman/listinfo/tutor for details on how to subscribe.] It sounds like you might be a little confused about how to write functions that take arguments. Let's go through a few examples and see where you get stuck. First, let's try a simpler problem: let's say that we'd like to make function that "doubles" whatever we give it. For example, if we imagine that we have this function already, we might be able to use it like this: ###### >>> double(5) 10 >>> double(75) 150 ###### Would you be able to write a function to do this? If the question seems simple, please forgive me: I'm just trying to trace where exactly you start getting stuck,. It does feel like you're missing something fundamental, so we have to start somewhere. *grin* Best of wishes to you! From alan.gauld at freenet.co.uk Thu Oct 6 10:09:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Oct 2005 09:09:51 +0100 Subject: [Tutor] Console output References: <434428DC.8050102@accesstel.co.za> <4344602E.5000101@tds.net> Message-ID: <004601c5ca4d$540fa090$0c01a8c0@xp> > Hmm, just have to say something about the old days when > 'carriage return' and 'line feed' really meant something :-) Yep, and on a teleype were two physically separate keys! Alan G From kent37 at tds.net Thu Oct 6 13:48:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 07:48:26 -0400 Subject: [Tutor] Python Shell Not Saved Problem In-Reply-To: References: Message-ID: <43450F0A.2010209@tds.net> Steve Haley wrote: > A > couple of folks also mentioned a book, Beginning Python: From Novice to > Professional. I think I might try that. There are many good beginner's resources, both on-line and print. Here are a couple of good lists: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers?highlight=%28BeginnersGuide%2F%29 http://wiki.python.org/moin/IntroductoryBooks > Again, thanks everyone for all the help. I was very impressed with the > response to my cry for help. You're welcome. The Python community is a pretty friendly bunch and the tutor list is for newbie questions so come back next time you are stumped. Kent From dollar0613 at yahoo.com Thu Oct 6 18:27:53 2005 From: dollar0613 at yahoo.com (jake skipper) Date: Thu, 6 Oct 2005 09:27:53 -0700 (PDT) Subject: [Tutor] Tutor Digest, Vol 20, Issue 11 In-Reply-To: Message-ID: <20051006162753.77742.qmail@web53507.mail.yahoo.com> Please take me off of your mailing list. tutor-request at python.org wrote:Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: need help to understand terms for desinging a program (paul brian) 2. Re: FW: Help Needed (Alan Gauld) 3. How to strip both single and double quotes (Dick Moores) ---------------------------------------------------------------------- Message: 1 Date: Wed, 5 Oct 2005 10:22:48 +0100 From: paul brian Subject: Re: [Tutor] need help to understand terms for desinging a program To: "Hameed U. Khan" Cc: tutor at python.org Message-ID: Content-Type: text/plain; charset=ISO-8859-1 This is a pretty big question, and it would be easier to answer if you can give us more details about what you want to do. It seems you want to inspect outgoing mails (possibly rewrite their addresses?) before the mails are sent out. If you are looking to send out emails to a list then I suggest looking at mailman - a python mailing list manager. If you want to use python to examine mail messages and do not care what mailserver (MTA) you use you could try exim instead of qmail and then try exim-python. http://botanicus.net/dw/exim-python/exim-4.32py1.html On 10/5/05, Hameed U. Khan wrote: > Hi, > I need to make a program which will accomplish following. I dont > need the code. I want to make it myself. But I need guidance from you > people because I am not a good programmer. I need help in > understanding following terms. > > " qmail-queue reads a mail message from descriptor 0. It > then reads envelope information from descriptor 1. It > places the message into the outgoing queue for future > delivery by qmail-send. > > The envelope information is an envelope sender address > followed by a list of envelope recipient addresses. The > sender address is preceded by the letter F and terminated > by a 0 byte. Each recipient address is preceded by the > letter T and terminated by a 0 byte. The list of recipi- > ent addresses is terminated by an extra 0 byte. If qmail- > queue sees end-of-file before the extra 0 byte, it aborts > without placing the message into the queue." > > I want to inspect messages before passing them to actuall qmail-queue > program. > Thanks in advance for your help. > -- > Regards, > Hameed U. Khan > Registered Linux User #: 354374 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 ------------------------------ Message: 2 Date: Wed, 5 Oct 2005 10:44:09 +0100 From: "Alan Gauld" Subject: Re: [Tutor] FW: Help Needed To: "Daniel Watkins" , Message-ID: <003d01c5c991$55cd0e70$0c01a8c0 at xp> Content-Type: text/plain; format=flowed; charset="UTF-8"; reply-type=original > When I am in Python Shell of the IDLE GUI, when I click Edit/Run You shouldn't be running scripts when in the shell, it executes them immediately. You use edit/run when working in a script file window. HTH, Alan G ------------------------------ Message: 3 Date: Wed, 05 Oct 2005 02:43:47 -0700 From: Dick Moores Subject: [Tutor] How to strip both single and double quotes To: tutor at python.org Message-ID: <6.2.1.2.2.20051005022639.05d1a050 at rcblue.com> Content-Type: text/plain; charset="iso-8859-1"; format=flowed I'm writing a script that takes any text and outputs to a file a list of duples (k, word) where k is the number of occurrences of word in the text. The text will contain "words" beginning or ending with non-alphabetic characters. To strip them off I use string.strip([chars]). My question is how to use strip just once to get rid of both kinds of quotes, single and double. It seems necessary to do it something like this: # L is the original list of "words" in the text. newL = [] for word in L: word = lower(word) newWord = word.strip(".,!?;:&*'=-> newWord2 = newWord.strip('.,!?;:&*"=-> word = newWord2 newL.append(word) But is it? Have I missed something? Thanks, Dick Moores ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 20, Issue 11 ************************************* --------------------------------- Yahoo! for Good Click here to donate to the Hurricane Katrina relief effort. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051006/4f6d7ebd/attachment.html From ewalker at micron.com Thu Oct 6 19:20:50 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 6 Oct 2005 11:20:50 -0600 Subject: [Tutor] class and methods/functions Message-ID: <200510061120.50425.ewalker@micron.com> I have a class I am defining and then I call a function within that class. Getting error that function call is not defined. Does the function have to be created anywhere within a class or does it have to be defined before the call within the class. -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From kent37 at tds.net Thu Oct 6 19:33:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 13:33:42 -0400 Subject: [Tutor] class and methods/functions In-Reply-To: <200510061120.50425.ewalker@micron.com> References: <200510061120.50425.ewalker@micron.com> Message-ID: <43455FF6.3070106@tds.net> Eric Walker wrote: > I have a class I am defining and then I call a function within that class. > Getting error that function call is not defined. Does the function have to be > created anywhere within a class or does it have to be defined before the call > within the class. Actual code and the error message (including the traceback) would be helpful here. Generally functions (usually called methods in this context) are defined within the body of a class and then called from outside the class. Functions have to be defined before they are called but not before they are referenced. Very simple example: >>> class B: ... def foo(self): ... print 'foo' ... self.bar() ... def bar(self): ... print 'bar' ... >>> b=B() >>> b.foo() foo bar Kent From ewalker at micron.com Thu Oct 6 19:47:22 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 6 Oct 2005 11:47:22 -0600 Subject: [Tutor] class and methods/functions In-Reply-To: <43455FF6.3070106@tds.net> References: <200510061120.50425.ewalker@micron.com> <43455FF6.3070106@tds.net> Message-ID: <200510061147.22853.ewalker@micron.com> Kent, Where I think my problem maybe in how I am running this. I want to eventually run from the command line. I started python idle from my linux command line and I was cut and pasting from my text file and seeing things work. Now i want to run it from the command line and its complaining. in my file I have something of the following. class yes: def func1 temp = re.match ##### return str(tempREG != 'None' def display(self): print all the class attributes.... def __init__(self,value): name = func1(value) other stuff def func2(): a = yes() try: func2() except: print "error" On Thursday 06 October 2005 11:33 am, Kent Johnson wrote: > Eric Walker wrote: > > I have a class I am defining and then I call a function within that > > class. Getting error that function call is not defined. Does the function > > have to be created anywhere within a class or does it have to be defined > > before the call within the class. > > Actual code and the error message (including the traceback) would be > helpful here. > > Generally functions (usually called methods in this context) are defined > within the body of a class and then called from outside the class. > Functions have to be defined before they are called but not before they > are referenced. > > Very simple example: > >>> class B: > > ... def foo(self): > ... print 'foo' > ... self.bar() > ... def bar(self): > ... print 'bar' > ... > > >>> b=B() > >>> b.foo() > > foo > bar > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Thu Oct 6 20:05:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 14:05:12 -0400 Subject: [Tutor] class and methods/functions In-Reply-To: <200510061147.22853.ewalker@micron.com> References: <200510061120.50425.ewalker@micron.com> <43455FF6.3070106@tds.net> <200510061147.22853.ewalker@micron.com> Message-ID: <43456758.8020004@tds.net> Eric Walker wrote: > Kent, > Where I think my problem maybe in how I am running this. I want to eventually > run from the command line. I started python idle from my linux command line > and I was cut and pasting from my text file and seeing things work. Now i > want to run it from the command line and its complaining. in my file I have > something of the following. This is full of syntax errors... > > class yes: > def func1 should be def func1(self): > temp = re.match ##### OK but not used for anything > return str(tempREG != 'None' Missing close paren and tempREG is not defined so you will get a NameError at runtime > def display(self): This should have the same indentation as def func1; indentation is significant! > print all the class attributes.... > def __init__(self,value): > name = func1(value) probably you want self.func1(value) - to call a member function from inside another member function you have to prefix the name with self. > other stuff > > def func2(): > a = yes() > > try: > func2() > except: > print "error" Generic except: blocks like this are a bad idea, it hides useful information without providing any benefit. The traceback that Python prints on an uncaught exception may look like a lot of gibberish at first but it contains a wealth of useful information that is thrown away by this handler. HTH, Kent > > > On Thursday 06 October 2005 11:33 am, Kent Johnson wrote: > >>Eric Walker wrote: >> >>>I have a class I am defining and then I call a function within that >>>class. Getting error that function call is not defined. Does the function >>>have to be created anywhere within a class or does it have to be defined >>>before the call within the class. >> >>Actual code and the error message (including the traceback) would be >>helpful here. >> >>Generally functions (usually called methods in this context) are defined >>within the body of a class and then called from outside the class. >>Functions have to be defined before they are called but not before they >>are referenced. >> >>Very simple example: >> >>> class B: >> >> ... def foo(self): >> ... print 'foo' >> ... self.bar() >> ... def bar(self): >> ... print 'bar' >> ... >> >> >>> b=B() >> >>> b.foo() >> >>foo >>bar >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From ewalker at micron.com Thu Oct 6 20:05:27 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 6 Oct 2005 12:05:27 -0600 Subject: [Tutor] class and methods/functions In-Reply-To: <200510061156.30138.ewalker@micron.com> References: <200510061120.50425.ewalker@micron.com> <200510061147.22853.ewalker@micron.com> <200510061156.30138.ewalker@micron.com> Message-ID: <200510061205.27253.ewalker@micron.com> Its working now. the moving of the function outside of the class allows me to run it from the command line. Thanks On Thursday 06 October 2005 11:56 am, Eric Walker wrote: > Kent, > I made a correction the func1 I moved out of the class definition since it > wasn't really a method. so it should look like this. > > > class yes: > > def display(self): > > print all the class attributes.... > > def __init__(self,value): > > name = func1(value) > > other stuff > > > > def func1 > > temp = re.match ##### > > return str(tempREG != 'None' > > > > def func2(): > > a = yes() > > > > try: > > func2() > > except: > > print "error" > > On Thursday 06 October 2005 11:47 am, Eric Walker wrote: > > Kent, > > Where I think my problem maybe in how I am running this. I want to > > eventually run from the command line. I started python idle from my linux > > command line and I was cut and pasting from my text file and seeing > > things work. Now i want to run it from the command line and its > > complaining. in my file I have something of the following. > > > > class yes: > > def func1 > > temp = re.match ##### > > return str(tempREG != 'None' > > def display(self): > > print all the class attributes.... > > def __init__(self,value): > > name = func1(value) > > other stuff > > > > def func2(): > > a = yes() > > > > try: > > func2() > > except: > > print "error" > > > > On Thursday 06 October 2005 11:33 am, Kent Johnson wrote: > > > Eric Walker wrote: > > > > I have a class I am defining and then I call a function within that > > > > class. Getting error that function call is not defined. Does the > > > > function have to be created anywhere within a class or does it have > > > > to be defined before the call within the class. > > > > > > Actual code and the error message (including the traceback) would be > > > helpful here. > > > > > > Generally functions (usually called methods in this context) are > > > defined within the body of a class and then called from outside the > > > class. Functions have to be defined before they are called but not > > > before they are referenced. > > > > > > Very simple example: > > > >>> class B: > > > > > > ... def foo(self): > > > ... print 'foo' > > > ... self.bar() > > > ... def bar(self): > > > ... print 'bar' > > > ... > > > > > > >>> b=B() > > > >>> b.foo() > > > > > > foo > > > bar > > > > > > Kent > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor From ewalker at micron.com Thu Oct 6 20:21:43 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 6 Oct 2005 12:21:43 -0600 Subject: [Tutor] class and methods/functions In-Reply-To: <43456758.8020004@tds.net> References: <200510061120.50425.ewalker@micron.com> <200510061147.22853.ewalker@micron.com> <43456758.8020004@tds.net> Message-ID: <200510061221.43938.ewalker@micron.com> Sorry Kent, In my haste to just simulate I did make the example with syntax errors. Let me try this again and I guess your teaching me how to use this mailing list the correct way also. Ok this is the actual code. I am able to get it to run from the command line. Thanks kent for your patience with this Python Newbie.... class TPROJ: import re import string def display(self):#display method print self.BASENAME print self.PROJECT print self.REV print self.DESIGNATOR print self.TYPE def __init__(self,value):#createMethod auto executes since it has __ name = nameCheck(value) if name: self.BASENAME = value self.PROJECT = value.split(':')[0] self.REV = value.split(':')[1] self.DESIGNATOR = "NOVALUE" self.TYPE = ('SW','TMOD','SWA','TMODA')#constant tuple if not name: print "found a bad name: %s" % value def nameCheck(value):#checks to see if filename is valid. Has a colon for split import re tempREG = re.match('.*:.*',value) return str(tempREG) != 'None' def getProjectNames(): import os currentDir=os.getcwd() nameTable = {} temp=currentDir + '/TEMP' print temp os.chdir(temp) baseList=os.listdir(".") baseObjectList = [] for name in baseList: baseObjectList.append(TPROJ(name)) os.chdir(currentDir) for item in baseObjectList: print item.BASENAME try: getProjectNames() except: print "Got an Error" On Thursday 06 October 2005 12:05 pm, Kent Johnson wrote: > Eric Walker wrote: > > Kent, > > Where I think my problem maybe in how I am running this. I want to > > eventually run from the command line. I started python idle from my linux > > command line and I was cut and pasting from my text file and seeing > > things work. Now i want to run it from the command line and its > > complaining. in my file I have something of the following. > > This is full of syntax errors... > > > class yes: > > def func1 > > should be > > def func1(self): > > temp = re.match ##### > > OK but not used for anything > > > return str(tempREG != 'None' > > Missing close paren and tempREG is not defined so you will get a NameError > at runtime > > > def display(self): > > This should have the same indentation as def func1; indentation is > significant! > > > print all the class attributes.... > > def __init__(self,value): > > name = func1(value) > > probably you want self.func1(value) - to call a member function from inside > another member function you have to prefix the name with self. > > > other stuff > > > > def func2(): > > a = yes() > > > > try: > > func2() > > except: > > print "error" > > Generic except: blocks like this are a bad idea, it hides useful > information without providing any benefit. The traceback that Python prints > on an uncaught exception may look like a lot of gibberish at first but it > contains a wealth of useful information that is thrown away by this > handler. > > HTH, > Kent > > > On Thursday 06 October 2005 11:33 am, Kent Johnson wrote: > >>Eric Walker wrote: > >>>I have a class I am defining and then I call a function within that > >>>class. Getting error that function call is not defined. Does the > >>> function have to be created anywhere within a class or does it have to > >>> be defined before the call within the class. > >> > >>Actual code and the error message (including the traceback) would be > >>helpful here. > >> > >>Generally functions (usually called methods in this context) are defined > >>within the body of a class and then called from outside the class. > >>Functions have to be defined before they are called but not before they > >>are referenced. > >> > >>Very simple example: > >> >>> class B: > >> > >> ... def foo(self): > >> ... print 'foo' > >> ... self.bar() > >> ... def bar(self): > >> ... print 'bar' > >> ... > >> > >> >>> b=B() > >> >>> b.foo() > >> > >>foo > >>bar > >> > >>Kent > >> > >>_______________________________________________ > >>Tutor maillist - Tutor at python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From dyoo at hkn.eecs.berkeley.edu Thu Oct 6 20:42:40 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Oct 2005 11:42:40 -0700 (PDT) Subject: [Tutor] class and methods/functions In-Reply-To: <200510061221.43938.ewalker@micron.com> Message-ID: Hi Eric, Quick comment on the last part of your program: > try: > getProjectNames() > except: > print "Got an Error" Don't do that. *grin* This is considered a misuse of exceptions. As a concrete example, say that we have a buggy program like this: ###### >>> def showDivisions(n): ... for x in range(n): ... print n / x ... ###### If we run this on a few arguments, we can see good error messages: ###### >>> showDivisions(0) >>> showDivisions(1) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in showDivisions ZeroDivisionError: integer division or modulo by zero ###### So here, the error message is very clear that we're doing something silly with a division. The error message itself looks a little scary at first, but it's chock full of information. But contrast this with what happens if we use an exception handler: ###### >>> try: ... showDivisions(1) ... except: ... print "error" ... error ###### The word 'error' might be less intimidating than a full stack trace, but it's also useless in terms of helping us figure out the real reason why showDivisions is broken. The lesson from this is: don't use exception handlers to hide errors like that, at least, not without a strong overriding reason. Once you've dropped the exception handler, try rerunning your program again: you should get much better error messages, and we can start from there. One other comment: module import is usually done at toplevel. You're importing modules within classes: ###### class TPROJ: import re ... ###### and although this works, idiomatically, it's unusual enough that you may want to avoid doing that. Your code uses the 're' module a lot anyway, so it makes sense to let 're' live at the toplevel, like this: ###### import re class TPROJ: ... ###### Best of wishes to you! From kent37 at tds.net Thu Oct 6 20:48:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 14:48:24 -0400 Subject: [Tutor] class and methods/functions In-Reply-To: <200510061221.43938.ewalker@micron.com> References: <200510061120.50425.ewalker@micron.com> <200510061147.22853.ewalker@micron.com> <43456758.8020004@tds.net> <200510061221.43938.ewalker@micron.com> Message-ID: <43457178.4070807@tds.net> Eric Walker wrote: > Sorry Kent, > In my haste to just simulate I did make the example with syntax errors. Let me > try this again and I guess your teaching me how to use this mailing list the > correct way also. Yes. > Ok this is the actual code. I am able to get it to run > from the command line. > > Thanks kent for your patience with this Python Newbie.... You're welcome. A few notes below. > > class TPROJ: > import re > import string Common usage is to put all the imports at the top of the module. There are circumstances where you will put them inside a function but not in this case. > def display(self):#display method > print self.BASENAME > print self.PROJECT > print self.REV > print self.DESIGNATOR > print self.TYPE It's your choice, but all caps for attribute values is unusual in Python. > > def __init__(self,value):#createMethod auto executes since it has __ > name = nameCheck(value) My guess is that nameCheck is the function that you moved out of the class. If you want it to be part of the class, you have to call it with self.nameCheck(value) > if name: > self.BASENAME = value > self.PROJECT = value.split(':')[0] > self.REV = value.split(':')[1] > self.DESIGNATOR = "NOVALUE" > self.TYPE = ('SW','TMOD','SWA','TMODA')#constant tuple > if not name: could be else: > print "found a bad name: %s" % value > > > > def nameCheck(value):#checks to see if filename is valid. Has a colon for > split To put this in the class you would declare it as def nameCheck(self, value): > import re > tempREG = re.match('.*:.*',value) > return str(tempREG) != 'None' Still a syntax error here! > > def getProjectNames(): > import os > currentDir=os.getcwd() > nameTable = {} > temp=currentDir + '/TEMP' > print temp > os.chdir(temp) > baseList=os.listdir(".") > baseObjectList = [] > for name in baseList: > baseObjectList.append(TPROJ(name)) > > os.chdir(currentDir) > for item in baseObjectList: > print item.BASENAME > > > try: > getProjectNames() > except: > print "Got an Error" Still recommend removing this try / except. Or you could wait until you actually get an exception and ask here for help ;-) cuz we will ask you for the traceback. Kent From dyoo at hkn.eecs.berkeley.edu Thu Oct 6 20:58:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Oct 2005 11:58:19 -0700 (PDT) Subject: [Tutor] still not getting 'it' (fwd) Message-ID: Hi Rosalee, [Keeping tutor in the conversation. Please make sure you're using the "Reply-to-All" feature of your email client.] I'll respond to the message once it reaches the mailing list. ---------- Forwarded message ---------- Date: Thu, 06 Oct 2005 11:49:44 -0700 From: Rosalee Dubberly To: dyoo at hkn.eecs.berkeley.edu Subject: Re: [Tutor] still not getting 'it' No the question doesn't seem to simple at all, I appreciate your help. I have totally confused myself and I need to start from the beginning to sort things out. Thanks for you time and help. >>>double = 2 * 5 >>>print 'The sum of 2 times 5 equals', double The sum of 2 times 5 equals 10 >>> From ewalker at micron.com Thu Oct 6 21:15:22 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 6 Oct 2005 13:15:22 -0600 Subject: [Tutor] class and methods/functions In-Reply-To: <43457178.4070807@tds.net> References: <200510061120.50425.ewalker@micron.com> <200510061221.43938.ewalker@micron.com> <43457178.4070807@tds.net> Message-ID: <200510061315.22601.ewalker@micron.com> On Thursday 06 October 2005 12:48 pm, Kent Johnson wrote > > class TPROJ: > > import re > > import string > > Common usage is to put all the imports at the top of the module. There are > circumstances where you will put them inside a function but not in this > case. I moved them all to the top before the class definition > > > def display(self):#display method > > print self.BASENAME > > print self.PROJECT > > print self.REV > > print self.DESIGNATOR > > print self.TYPE > > It's your choice, but all caps for attribute values is unusual in Python. > Ok, I want to follow normal python protocol. I changed them to lower case. > > def __init__(self,value):#createMethod auto executes since it has __ > > name = nameCheck(value) > > My guess is that nameCheck is the function that you moved out of the class. > If you want it to be part of the class, you have to call it with > self.nameCheck(value) > > > if name: > > self.BASENAME = value > > self.PROJECT = value.split(':')[0] > > self.REV = value.split(':')[1] > > self.DESIGNATOR = "NOVALUE" > > self.TYPE = ('SW','TMOD','SWA','TMODA')#constant tuple > > if not name: > > could be else: > > print "found a bad name: %s" % value > > yes, I did remove this from the class. I really didn't need it in there. I moved the check outside under the main running function. To check the name before I even create the object. The way I had it before it would create an object regardless if the name had a colon or not. > def nameCheck(self, value): > > import re > > tempREG = re.match('.*:.*',value) > > return str(tempREG) != 'None' > > Still a syntax error here! > Code is working as I thought it would. What syntax error do I have? > Still recommend removing this try / except. Or you could wait until you > actually get an exception and ask here for help ;-) cuz we will ask you for > the traceback. yes, I did remove the try except. Man this group is great. I am going to be a python coder yet..... current code sample follows: import re import string import os class TPROJ: def display(self):#display method print self.basename print self.project print self.rev print self.designator print self.type def __init__(self,value):#createMethod auto executes since it has __ self.basename = value self.project = value.split(':')[0] self.rev = value.split(':')[1] self.designator = "NOVALUE" self.type = ('SW','TMOD','SWA','TMODA')#constant tuple def nameCheck(value): tempREG = re.match('.*:.*',value) return str(tempREG) != 'None' def getProjectNames(): currentDir=os.getcwd() nameTable = {} temp=currentDir + '/TEMP' print temp os.chdir(temp) baseList=os.listdir(".") baseObjectList = [] for name in baseList: if nameCheck(name): baseObjectList.append(TPROJ(name)) Python Newbie... From dyoo at hkn.eecs.berkeley.edu Thu Oct 6 21:27:16 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Oct 2005 12:27:16 -0700 (PDT) Subject: [Tutor] still not getting 'it' (fwd) In-Reply-To: Message-ID: > No the question doesn't seem to simple at all, I appreciate your help. I > have totally confused myself and I need to start from the beginning to > sort things out. Thanks for you time and help. > > >>>double = 2 * 5 > >>>print 'The sum of 2 times 5 equals', double > The sum of 2 times 5 equals 10 Hi Rosalee, Ok, that's probably the problem then: it sounds like you might not be familiar with writing and using functions. Let's do a quick primer. For the purposes of trying to connecting to things that you should know about, I'll borrow a math example, but if you want, we can make examples using different domains besides math. In algebra math classes, we may have seen things like: f(x) = 2 * x We might write on a blackboard such things like: f(2) = 2 * 2 = 4 f(8) = 2 * 8 = 16 In a math function definition like "f(x) = 2 * x", we're trying to capture the concept of doubling something, and we give that particular concept the name 'f', just so we can talk about it later. A "function" in Python is sorta like a "function" in mathematics. (It's not quite the same, and we'll can talk about this in more detail later.) But anyway, the doubling function above can be written in Python like this: ###### def f(x): return 2 * x ###### In a Python function definition like "def f(x): return 2 * x", we're trying to capture the process of doubling something, and we give that particular process the name 'f', just so we can use it later on. Let's play with this 'f' function that we've defined. From the interactive interpreter, we can enter in the function, and then test it out on a few inputs: ###### >>> def f(x): ... return 2 * x ... >>> >>> f ###### When we say 'f', Python knows that we're talking about some function. (Um... ignore the weird '0x403a6ae4' thing for now. *grin*) The main concept here is that 'f' is now a name for some thing that we can hold and use, just like a number or a string. Let's try using 'f': ###### >>> f(2) 4 >>> f(3) 6 >>> f(8) 16 ###### We can use 'f' with different inputs, and we get back different outputs. And we can even use f() like this: ###### >>> f(f(2)) 8 ###### Usually, programmers like to give their functions nicer names than 'f': mathematicians like brevity, but programmers often like to be able to read their programs. We can name 'f' as 'double': ###### >>> def double(x): ... return 2 * x ... >>> double(double(2)) 8 ###### And we can follow this naming idea a bit further, and rename 'x' to something else, like 'something': ###### >>> def double(something): ... return 2 * something ... >>> double(42) 84 ###### "To double something, just multiply 2 to that something." Does this make sense so far? Please feel free to ask questions on this: this is very fundamental stuff, and if you're getting stuck here, we need to figure out what we can to do help get you unstuck. Good luck! From kent37 at tds.net Thu Oct 6 21:39:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 15:39:53 -0400 Subject: [Tutor] class and methods/functions In-Reply-To: <200510061315.22601.ewalker@micron.com> References: <200510061120.50425.ewalker@micron.com> <200510061221.43938.ewalker@micron.com> <43457178.4070807@tds.net> <200510061315.22601.ewalker@micron.com> Message-ID: <43457D89.3040207@tds.net> Eric Walker wrote: > On Thursday 06 October 2005 12:48 pm, Kent Johnson wrote > yes, I did remove this from the class. I really didn't need it in there. I > moved the check outside under the main running function. To check the name > before I even create the object. The way I had it before it would create an > object regardless if the name had a colon or not. That makes sense. > > >> def nameCheck(self, value): >> >>> import re >>> tempREG = re.match('.*:.*',value) >>> return str(tempREG) != 'None' >> >>Still a syntax error here! >> > > Code is working as I thought it would. What syntax error do I have? Oops, I was still *reading* a syntax error :-) > > Man this group is great. I am going to be a > python coder yet..... Yep :-) > current code sample follows: A few more advanced notes for you below, just in case your brain hasn't exploded yet :-) Kent > > > import re > import string > import os > > class TPROJ: Tproj or TProj would be a more idiomatic name... > > def display(self):#display method > print self.basename > print self.project > print self.rev > print self.designator > print self.type > > def __init__(self,value):#createMethod auto executes since it has __ > self.basename = value > self.project = value.split(':')[0] > self.rev = value.split(':')[1] If you are sure there will be just one colon this can be written as self.project, self.rev = value.split(':') Tuple assignment rocks! If you try this with more than one colon you will get an error. > self.designator = "NOVALUE" > self.type = ('SW','TMOD','SWA','TMODA')#constant tuple > > > > def nameCheck(value): > tempREG = re.match('.*:.*',value) > return str(tempREG) != 'None' > > def getProjectNames(): > currentDir=os.getcwd() > nameTable = {} > temp=currentDir + '/TEMP' > print temp > os.chdir(temp) > baseList=os.listdir(".") > baseObjectList = [] > for name in baseList: > if nameCheck(name): > baseObjectList.append(TPROJ(name)) The above four lines could be replaced with a single list comprehension if you like: baseObjectList = [ TPROJ(name) for name in baseList if nameCheck(name) ] http://www.amk.ca/python/2.0/index.html#SECTION000600000000000000000 Kent > > Python Newbie... > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dubberlyr at msn.com Thu Oct 6 21:41:34 2005 From: dubberlyr at msn.com (Rosalee Dubberly) Date: Thu, 06 Oct 2005 12:41:34 -0700 Subject: [Tutor] still not getting 'it' (fwd) In-Reply-To: Message-ID: I am going to 'play' with this in IDLE. I have used your tutorial posted on the Net. Good stuff!! Thanks for breaking this down into different examples. You are a great instructor. >From: Danny Yoo >To: Tutor >CC: dubberlyr at msn.com >Subject: Re: [Tutor] still not getting 'it' (fwd) >Date: Thu, 6 Oct 2005 12:27:16 -0700 (PDT) > > > > > No the question doesn't seem to simple at all, I appreciate your help. I > > have totally confused myself and I need to start from the beginning to > > sort things out. Thanks for you time and help. > > > > >>>double = 2 * 5 > > >>>print 'The sum of 2 times 5 equals', double > > The sum of 2 times 5 equals 10 > > >Hi Rosalee, > >Ok, that's probably the problem then: it sounds like you might not be >familiar with writing and using functions. > > >Let's do a quick primer. For the purposes of trying to connecting to >things that you should know about, I'll borrow a math example, but if you >want, we can make examples using different domains besides math. > >In algebra math classes, we may have seen things like: > > f(x) = 2 * x > >We might write on a blackboard such things like: > > f(2) = 2 * 2 = 4 > f(8) = 2 * 8 = 16 > >In a math function definition like "f(x) = 2 * x", we're trying to capture >the concept of doubling something, and we give that particular concept the >name 'f', just so we can talk about it later. > > >A "function" in Python is sorta like a "function" in mathematics. (It's >not quite the same, and we'll can talk about this in more detail later.) >But anyway, the doubling function above can be written in Python like >this: > >###### >def f(x): > return 2 * x >###### > >In a Python function definition like "def f(x): return 2 * x", we're >trying to capture the process of doubling something, and we give that >particular process the name 'f', just so we can use it later on. > > >Let's play with this 'f' function that we've defined. From the >interactive interpreter, we can enter in the function, and then test it >out on a few inputs: > >###### > >>> def f(x): >... return 2 * x >... > >>> > >>> f > >###### > >When we say 'f', Python knows that we're talking about some function. >(Um... ignore the weird '0x403a6ae4' thing for now. *grin*) The main >concept here is that 'f' is now a name for some thing that we can hold and >use, just like a number or a string. > > >Let's try using 'f': > >###### > >>> f(2) >4 > >>> f(3) >6 > >>> f(8) >16 >###### > >We can use 'f' with different inputs, and we get back different outputs. > >And we can even use f() like this: > >###### > >>> f(f(2)) >8 >###### > > > >Usually, programmers like to give their functions nicer names than 'f': >mathematicians like brevity, but programmers often like to be able to read >their programs. We can name 'f' as 'double': > >###### > >>> def double(x): >... return 2 * x >... > >>> double(double(2)) >8 >###### > > >And we can follow this naming idea a bit further, and rename 'x' to >something else, like 'something': > >###### > >>> def double(something): >... return 2 * something >... > >>> double(42) >84 >###### > >"To double something, just multiply 2 to that something." > >Does this make sense so far? > > >Please feel free to ask questions on this: this is very fundamental >stuff, and if you're getting stuck here, we need to figure out what we can >to do help get you unstuck. > > >Good luck! > _________________________________________________________________ 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 ateeqahmad at gmail.com Thu Oct 6 22:17:35 2005 From: ateeqahmad at gmail.com (Ateeq Ahmad) Date: Thu, 6 Oct 2005 13:17:35 -0700 Subject: [Tutor] unsubcribe Message-ID: <105f5bfc0510061317hc82d5b1hfa467a1a6fdd7e3b@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051006/e35163cf/attachment.htm From Hans.Dushanthakumar at navman.com Thu Oct 6 22:37:22 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Fri, 7 Oct 2005 09:37:22 +1300 Subject: [Tutor] How to write this to a file? Message-ID: <5667508E43F1B740BCFA57FF46E3530001EFE1B1@nav-akl-exch-c.newton.navman.com> print outputs the string to the std output (sys.stdout). You could redirect the std output to a file instead of the screen as follows, but it's a bit clumsy. fptr = open("hans.log", "a+") import sys sys.stdout = fptr print "Hi there" This will output the string into the file hans.log. However, to get it to print to the screen again, u will need to have stored the original contents of sys.stdout somewhere and then redirected sys.stdout to that again. TCL provides a more handy way of doing this: print $fptr "Hi there" Cheers Hans -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Dick Moores Sent: Thursday, 6 October 2005 12:18 p.m. To: tutor at python.org Subject: [Tutor] How to write this to a file? I have a script that writes it's output to a file. I also print the time with print "Time was %.4g seconds" % (timeEnd - timeStart) How could I also have the same output of the print expression, written to the file? Thanks, Dick Moores _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ewalker at micron.com Thu Oct 6 22:40:22 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 6 Oct 2005 14:40:22 -0600 Subject: [Tutor] class and methods/functions In-Reply-To: <43457D89.3040207@tds.net> References: <200510061120.50425.ewalker@micron.com> <200510061315.22601.ewalker@micron.com> <43457D89.3040207@tds.net> Message-ID: <200510061440.22223.ewalker@micron.com> > The above four lines could be replaced with a single list comprehension if > you like: baseObjectList = [ TPROJ(name) for name in baseList if > nameCheck(name) ] > http://www.amk.ca/python/2.0/index.html#SECTION000600000000000000000 > > Kent > BOOOOOOOM!!!!!!!!!!!!!!!! Let me pick up my skull fragments.... Ok I understand all but one. Having trouble understanding list comprehension. I thought I understood but its barking at me. I would think that this would make mytest the same values as test? >>> test ['a', 'b', 'c', 'd'] >>> mytest[name for name in test:] File "", line 1 mytest[name for name in test:] ^ SyntaxError: invalid syntax >>> > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From ewalker at micron.com Thu Oct 6 22:56:33 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 6 Oct 2005 14:56:33 -0600 Subject: [Tutor] class and methods/functions In-Reply-To: <200510061440.22223.ewalker@micron.com> References: <200510061120.50425.ewalker@micron.com> <43457D89.3040207@tds.net> <200510061440.22223.ewalker@micron.com> Message-ID: <200510061456.33130.ewalker@micron.com> DUH.. I found the answer.... mytest = [name for name in test] Thanks again.. > > The above four lines could be replaced with a single list comprehension > > if you like: baseObjectList = [ TPROJ(name) for name in baseList if > > nameCheck(name) ] > > http://www.amk.ca/python/2.0/index.html#SECTION000600000000000000000 > > > > Kent > > BOOOOOOOM!!!!!!!!!!!!!!!! > Let me pick up my skull fragments.... > Ok I understand all but one. Having trouble understanding list > comprehension. I thought I understood but its barking at me. I would think > that this would make mytest the same values as test? > > >>> test > > ['a', 'b', 'c', 'd'] > > >>> mytest[name for name in test:] > > File "", line 1 > mytest[name for name in test:] > ^ > SyntaxError: invalid syntax > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Oct 7 00:43:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 18:43:45 -0400 Subject: [Tutor] How to write this to a file? In-Reply-To: <5667508E43F1B740BCFA57FF46E3530001EFE1B1@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530001EFE1B1@nav-akl-exch-c.newton.navman.com> Message-ID: <4345A8A1.4070102@tds.net> Hans Dushanthakumar wrote: > print outputs the string to the std output (sys.stdout). You could > redirect the std output to a file instead of the screen as follows, but > it's a bit clumsy. > > TCL provides a more handy way of doing this: > print $fptr "Hi there" In Python you can say print >>fptr, "Hi there" Kent > > Cheers > Hans > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Dick Moores > Sent: Thursday, 6 October 2005 12:18 p.m. > To: tutor at python.org > Subject: [Tutor] How to write this to a file? > > I have a script that writes it's output to a file. I also print the time > with > > print "Time was %.4g seconds" % (timeEnd - timeStart) > > How could I also have the same output of the print expression, written > to the file? > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From amonroe at columbus.rr.com Fri Oct 7 01:13:47 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 6 Oct 2005 19:13:47 -0400 Subject: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? In-Reply-To: <200509302251.07797.michaels@rd.bbc.co.uk> References: <200509302251.07797.michaels@rd.bbc.co.uk> Message-ID: <1541654098007.20051006191347@columbus.rr.com> I was working through their tutorial: > * http://kamaelia.sourceforge.net/MiniAxon/ Chapter 5 claims the output should be: Hello World 2 Hello World 3 ... Hello World 97 Hello World 98 But mine outputs only: Hello World 2 (no further output) I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with the hundred or so messages intended for display, but they never get displayed. I suspect an indentation problem, but I can't spot it, even stepping through in the debugger. Alan -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: microprocess2.py Url: http://mail.python.org/pipermail/tutor/attachments/20051006/ed86dffe/microprocess2.asc From kent37 at tds.net Fri Oct 7 01:31:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 19:31:10 -0400 Subject: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? In-Reply-To: <1541654098007.20051006191347@columbus.rr.com> References: <200509302251.07797.michaels@rd.bbc.co.uk> <1541654098007.20051006191347@columbus.rr.com> Message-ID: <4345B3BE.1010804@tds.net> R. Alan Monroe wrote: > I was working through their tutorial: > > >> * http://kamaelia.sourceforge.net/MiniAxon/ > > > Chapter 5 claims the output should be: > Hello World 2 > Hello World 3 > ... > Hello World 97 > Hello World 98 > > But mine outputs only: > Hello World 2 > (no further output) > > I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with > the hundred or so messages intended for display, but they never get > displayed. I suspect an indentation problem, but I can't spot it, even > stepping through in the debugger. I made exactly the same mistake! You have to put an infinite loop in postman.main(). It's in the directions but I guess it's easy to miss. Kent > > Alan > > > ------------------------------------------------------------------------ > > #============================================= > class microprocess(object): > > def __init__(self): > super(microprocess, self).__init__() > > def main(self): > yield 1 > > #============================================= > class scheduler(microprocess): > > def __init__(self): > super(scheduler, self).__init__() > self.active = [] > self.newqueue = [] > > def main(self): > for x in xrange(100): > for current in self.active: > yield 1 > try: > result = current.next() > if result is not -1: > self.newqueue.append(current) > except StopIteration: > pass > self.active = self.newqueue > self.newqueue = [] > > def activateMicroprocess(self, someprocess): > microthread = someprocess.main() > self.newqueue.append(microthread) > > #============================================= > class postman(microprocess): > > def __init__(self, source, sourcebox, sink, sinkbox): > super(postman, self).__init__() > self.source = source > self.sourcebox = sourcebox > self.sink = sink > self.sinkbox = sinkbox > > def main(self): > yield 1 > if self.source.dataReady(self.sourcebox): > postdata = self.source.recv(self.sourcebox) > self.sink.send(postdata, self.sinkbox) > > #============================================= > class component(microprocess): > > def __init__(self): > super(component, self).__init__() > self.boxes = { 'inbox': [], 'outbox': [] } > > def send(self, value, boxname): > self.boxes[boxname].append(value) > > def recv(self, boxname): > return self.boxes[boxname].pop(0) > > def dataReady(self, boxname): > return len( self.boxes[boxname] ) > > #============================================= > class Producer(component): > > def __init__(self, message): > super(Producer, self).__init__() > self.message = message > > def main(self): > while 1: > yield 1 > self.send(self.message, "outbox") > > #============================================= > class Consumer(component): > > #~ def __init__(self, tag): > #~ super(Consumer, self).__init__() > > def main(self): > count = 0 > while 1: > yield 1 > count += 1 > if self.dataReady("inbox"): > data = self.recv("inbox") > print data, count > > > p = Producer("Hello World") > c = Consumer() > postie = postman(p, "outbox", c, "inbox") > > myscheduler = scheduler() > myscheduler.activateMicroprocess(p) > myscheduler.activateMicroprocess(c) > myscheduler.activateMicroprocess(postie) > > for _ in myscheduler.main(): > pass > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Fri Oct 7 01:45:10 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 6 Oct 2005 19:45:10 -0400 Subject: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? In-Reply-To: <4345B3BE.1010804@tds.net> References: <200509302251.07797.michaels@rd.bbc.co.uk> <1541654098007.20051006191347@columbus.rr.com> <4345B3BE.1010804@tds.net> Message-ID: <371655980944.20051006194510@columbus.rr.com> >> I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with >> the hundred or so messages intended for display, but they never get >> displayed. I suspect an indentation problem, but I can't spot it, even >> stepping through in the debugger. > I made exactly the same mistake! You have to put an infinite loop in > postman.main(). It's in the directions but I guess it's easy to > miss. Bingo, you da man. Alan From daniel at thewatkins.org.uk Fri Oct 7 02:18:24 2005 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Fri, 07 Oct 2005 01:18:24 +0100 Subject: [Tutor] Importing Modules Within Classes Message-ID: <1128644304.31050.3.camel@amdbert.oxbridgetechnology.local> Recently, there has been an example of someone importing modules within a class definition. eg: class Exemplar: import re ...use re... It seems obvious to me that this is incorrect, though more through training than actual observation on my part, and it should be: import re class Exemplar: ...use re... However, someone (I don't recall who) said that there were occasions when it would be appropriate to import modules the former way. I was just wondering under what circumstances importing should be done this way? Cheers, Dan From zathras at thwackety.com Fri Oct 7 03:23:32 2005 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 7 Oct 2005 02:23:32 +0100 Subject: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? In-Reply-To: <1541654098007.20051006191347@columbus.rr.com> References: <200509302251.07797.michaels@rd.bbc.co.uk> <1541654098007.20051006191347@columbus.rr.com> Message-ID: <200510070223.33116.zathras@thwackety.com> On Friday 07 October 2005 00:13, R. Alan Monroe wrote: ... > I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with > the hundred or so messages intended for display, but they never get > displayed. I suspect an indentation problem, but I can't spot it, even > stepping through in the debugger. Hi! First of all thanks for trying the tutorial - hope it's been interesting. I'm sorry you hit a problem with it - it looks like the HTML formatting has caused some issues :-( All the code and examples used were tested before the being placed into the "tabbed" version of the tutorial. In this case it looks like the whitespace has gone horribly horribly wrong on that tab :-((( I'll sort it out. In the meantime though, In case of precisely this problem occuring, I also placed that source for all 4 main sections (Standing, Walking, Talking, Conversing) in the following page here: http://kamaelia.sourceforge.net/MiniAxonFull.html I've just double checked what happens when running the contents of that page, and it works as expected (here at least), so I suspect the problems you're seeing are simply due to "code being in HTML" issues. Also, the entire tutorial is available as a single page here, rather than tabbed: * http://kamaelia.sourceforge.net/MiniAxon.html But that has the answers inline, which is why I didn't mention it before. That *does* appear to have formatting preserved correctly in firefox, and I've also just double checked that when copying and pasting that the stated results were the ones stated. Hoping this helps, and thanks! If you're willing to spare a few sentances of how you found the tutorial (on or off list), I'd be really interested in hearing. If it's difficult, what was difficult (naff HTML for example...), if it was clear/unclear, that sort of thing. That said, this query is useful feedback in itself :) Best Regards, (and apologies for the HTML formatting ... :-( Michael. -- Michael Sparks, Senior R&D Engineer, Digital Media Group Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This e-mail may contain personal views which are not the views of the BBC. From amonroe at columbus.rr.com Fri Oct 7 04:04:43 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 6 Oct 2005 22:04:43 -0400 Subject: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? In-Reply-To: <200510070223.33116.zathras@thwackety.com> References: <200509302251.07797.michaels@rd.bbc.co.uk> <1541654098007.20051006191347@columbus.rr.com> <200510070223.33116.zathras@thwackety.com> Message-ID: <151664353784.20051006220443@columbus.rr.com> > I've just double checked what happens when running the contents of that > page, and it works as expected (here at least), so I suspect the problems > you're seeing are simply due to "code being in HTML" issues. Yeah I was writing as much as I was able on my own rather than copying/pasting the code, so it was mainly an oversight in my own work. Alan From william.ohiggins at utoronto.ca Fri Oct 7 04:08:02 2005 From: william.ohiggins at utoronto.ca (William O'Higgins Witteman) Date: Thu, 6 Oct 2005 22:08:02 -0400 Subject: [Tutor] Matching dictionary entries by partial key Message-ID: <20051007020802.GA5679@sillyrabbi.dyndns.org> I'm trying to traverse a dictionary looking for partial matches of the key, and I'm not sure how. Here's a sample dictionary: dict = {00001234 : value1, 20051234 : value2, 20071234 : value3} Here's what I'm trying to do: for key in dict: if key == 0000???? or key == 2005????: do something with dict[key] The challenge is that I only care about the first four digits of the key for the purpose of this match - is there a way to express this? I could probably create a wrapper dictionary using just the first four digits of the key as they key, and containing the original key:value pair as a list within it, but that seems cumbersome. Any one have a suggestion? Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20051006/7007a205/attachment.pgp From kent37 at tds.net Fri Oct 7 04:21:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 22:21:21 -0400 Subject: [Tutor] Importing Modules Within Classes In-Reply-To: <1128644304.31050.3.camel@amdbert.oxbridgetechnology.local> References: <1128644304.31050.3.camel@amdbert.oxbridgetechnology.local> Message-ID: <4345DBA1.2000006@tds.net> Daniel Watkins wrote: > Recently, there has been an example of someone importing modules within > a class definition. eg: > > class Exemplar: > import re > ...use re... > > It seems obvious to me that this is incorrect, though more through > training than actual observation on my part, and it should be: > > import re > > class Exemplar: > ...use re... It's not really incorrect, it is legal syntax and it will do what you expect. It is not idiomatic and in general it is simpler to just put all the imports at the top. > However, someone (I don't recall who) said that there were occasions > when it would be appropriate to import modules the former way. I was > just wondering under what circumstances importing should be done this > way? That was me. I nest imports quite frequently in Jython code where the first import of a module is fairly expensive in time. Putting the import in the function that needs it delays the import and perhaps the module won't be imported at all. import is an executable statement. When it runs, the interpreter first looks to see if the module has already been imported. If so, the existing module is bound to the import name in the current namespace. If the module has not yet been imported, it is loaded *and executed*, then bound to the name in the current namespace. So if module A imports B which imports C and D, then importing A will also load and execute B, C and D. If any of these are time-consuming you may want to defer them. I found with my Jython programs that I could shorten start-up time quite a bit by deferring some imports until they were needed. Another reason for the nested style of imports is to resolve problems with circular imports. There are some subtle problems that can occur when A imports B and B imports A. By nesting one of the imports you can defer it and sometimes avoid the problem. In this case I think removing the circular import is a much better solution - circular dependencies are evil! Kent > > Cheers, > Dan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Fri Oct 7 04:28:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Oct 2005 22:28:23 -0400 Subject: [Tutor] Matching dictionary entries by partial key In-Reply-To: <20051007020802.GA5679@sillyrabbi.dyndns.org> References: <20051007020802.GA5679@sillyrabbi.dyndns.org> Message-ID: <4345DD47.4080406@tds.net> William O'Higgins Witteman wrote: > I'm trying to traverse a dictionary looking for partial matches of the > key, and I'm not sure how. Here's a sample dictionary: > > dict = {00001234 : value1, 20051234 : value2, 20071234 : value3} > > Here's what I'm trying to do: > > for key in dict: > if key == 0000???? or key == 2005????: if key.startswith('0000') or key.startswith('2005'): or with a regular expresion: if re.match('0000|2005', key): > do something with dict[key] > > The challenge is that I only care about the first four digits of the key > for the purpose of this match - is there a way to express this? I could > probably create a wrapper dictionary using just the first four digits of > the key as they key, and containing the original key:value pair as a > list within it, but that seems cumbersome. Any one have a suggestion? If you have a *lot* of keys and need more speed, that might be a good optimization. For a small dict, just use startswith(). Kent > Thanks. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From mac at Wireless.Com Fri Oct 7 05:31:59 2005 From: mac at Wireless.Com (Mike Cheponis) Date: Thu, 6 Oct 2005 20:31:59 -0700 (PDT) Subject: [Tutor] Simple Tkinter question Message-ID: I'm trying to update an Entry's textvariable several times within my Button handler, like so: from Tkinter import * from time import * def my_update(): for i in range(3): tv.set("Now it's %d"%i) sleep(1) root=Tk() tv=StringVar() Entry(textvariable=tv).pack() tv.set("Initial Value of StringVar") Button(text="Update", command=my_update).pack() root.mainloop() What happens when I hit the Update button is a 3-second pause, then "Now it's 2" is displayed. What I expected to see in the Entry was: "Now it's 0" (right away) "Now it's 1" (after 1 second pause) "Now it's 2" (after another 1 second pause) Any idea what's going on here? Why doesn't "tv.set("") happen immediately? Thanks, -Mike From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 06:35:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Oct 2005 21:35:13 -0700 (PDT) Subject: [Tutor] Matching dictionary entries by partial key In-Reply-To: <20051007020802.GA5679@sillyrabbi.dyndns.org> Message-ID: On Thu, 6 Oct 2005, William O'Higgins Witteman wrote: > I'm trying to traverse a dictionary looking for partial matches of the > key, and I'm not sure how. Here's a sample dictionary: > > dict = {00001234 : value1, 20051234 : value2, 20071234 : value3} > > Here's what I'm trying to do: > > for key in dict: > if key == 0000???? or key == 2005????: > do something with dict[key] > > The challenge is that I only care about the first four digits of the key > for the purpose of this match - is there a way to express this? I could > probably create a wrapper dictionary using just the first four digits of > the key as they key, and containing the original key:value pair as a > list within it, but that seems cumbersome. Hi William, The dictionary (hashtable) data structure is really meant for exact key match: it does not do partial keyword match well at all, and trying to bend it to do so is going against its grain. But using the first four digits as the key sounds right for your application: from what you've told us so far, you're trying to express a quick dictionary lookup using the first four digits as the key. If we do take this route, doing this is not too bad, especially if we take advantage of a dictionary's setdefault() method: ####### >>> words = 'this is a test of the emergency broadcast system'.split() >>> words ['this', 'is', 'a', 'test', 'of', 'the', 'emergency', 'broadcast', 'system'] >>> >>> d = {} >>> for word in words: ... d.setdefault(word[0], []).append(word) ... >>> >>> d {'a': ['a'], 'b': ['broadcast'], 'e': ['emergency'], 'i': ['is'], 'o': ['of'], 's': ['system'], 't': ['this', 'test', 'the']} ####### But as Kent mentioned, though, perhaps the easiest thing to implement is a simple linear scan across all your key-values, and not worry until we know this is a performance hotspot. *grin* It really depends on how many entries we're searching against. From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 06:54:01 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Oct 2005 21:54:01 -0700 (PDT) Subject: [Tutor] Simple Tkinter question In-Reply-To: Message-ID: On Thu, 6 Oct 2005, Mike Cheponis wrote: > I'm trying to update an Entry's textvariable several times within my > Button handler, like so: > > from Tkinter import * > from time import * > > def my_update(): > for i in range(3): > tv.set("Now it's %d"%i) > sleep(1) > > root=Tk() > tv=StringVar() > Entry(textvariable=tv).pack() > tv.set("Initial Value of StringVar") > Button(text="Update", command=my_update).pack() > root.mainloop() Hi Mike, The problem is that the GUI needs control back to be able to update the GUI display. At the moment, there's only one thread of execution, and the call to time.sleep() deprives the GUI of the control it needs to draw things. Tkinter has a particular way of doing sleep()-like behavior that interacts better with the GUI. We can use the "after()" method to tell the GUI to do some action after some period of time. Here's a quick-and-dirty example: ###### import Tkinter root = Tkinter.Tk() label = Tkinter.Label(root, text="hello") label.pack() def doCountUpdate(n): label['text'] = n label.after(1000, doCountUpdate, n + 1) doCountUpdate(0) root.mainloop() ###### The initial call to doCountUpdate() updates the label text, and then tells the label: "after 1000 milliseconds (one second), call doCountUpdate again, and with n+1 as its argument." After we schedule this next update, we give control back to the GUI, and trust that the GUI will keep its promise to call our function after the timeout period. For reference information on this, see: http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm This isn't the only way to handle this sort of problem: another possible approach involves the use of threads. But you may want to try using 'after()' first, since I think it has an easier learning curve than threads. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 07:15:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Oct 2005 22:15:05 -0700 (PDT) Subject: [Tutor] Simple Tkinter question (fwd) Message-ID: ---------- Forwarded message ---------- Date: Thu, 6 Oct 2005 22:07:50 -0700 (PDT) From: Mike Cheponis To: Danny Yoo Subject: Re: [Tutor] Simple Tkinter question On Thu, 6 Oct 2005, Danny Yoo wrote: >> from Tkinter import * >> from time import * >> >> def my_update(): >> for i in range(3): >> tv.set("Now it's %d"%i) >> sleep(1) >> >> root=Tk() >> tv=StringVar() >> Entry(textvariable=tv).pack() >> tv.set("Initial Value of StringVar") >> Button(text="Update", command=my_update).pack() >> root.mainloop() > > > Hi Mike, > > The problem is that the GUI needs control back to be able to update the > GUI display. Thanks, but what I don't understand is: Why doesn't the call tv.set("string") update what's on the screen. Clearly, Tkinter has control at that point, and there's no reason to delay updating the screen, is there? What I'm really trying to do is: I have a bunch of lines selected on the screen. I'm using Pmw. This returned tuple has a number of items I need to play. While the sound is playing, I want to display the name of the sound on the GUI. (The playing is done by a routine that writes to the serial port - that is, I call a function with the filename of the sound, and it plays it). I'll see if I can get something from the URL you mention, perhaps calling after_idle(). Thanks again! -Mike > Tkinter has a particular way of doing sleep()-like behavior that interacts > better with the GUI. We can use the "after()" method to tell the GUI to > do some action after some period of time. > > Here's a quick-and-dirty example: > > ###### > import Tkinter > root = Tkinter.Tk() > label = Tkinter.Label(root, text="hello") > label.pack() > > def doCountUpdate(n): > label['text'] = n > label.after(1000, doCountUpdate, n + 1) > > doCountUpdate(0) > root.mainloop() > ###### > > > The initial call to doCountUpdate() updates the label text, and then tells > the label: "after 1000 milliseconds (one second), call doCountUpdate > again, and with n+1 as its argument." After we schedule this next update, > we give control back to the GUI, and trust that the GUI will keep its > promise to call our function after the timeout period. > > For reference information on this, see: > > http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm > > This isn't the only way to handle this sort of problem: another possible > approach involves the use of threads. But you may want to try using > 'after()' first, since I think it has an easier learning curve than > threads. > > > Best of wishes to you! > From mjcother at yahoo.com Fri Oct 7 07:54:49 2005 From: mjcother at yahoo.com (Michael Cotherman) Date: Thu, 6 Oct 2005 22:54:49 -0700 (PDT) Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] In-Reply-To: <43445857.8030602@tds.net> Message-ID: <20051007055449.96239.qmail@web31805.mail.mud.yahoo.com> > ....... is the decoding code, it does what you > describe below. It is adding the zeros back in, that > is the dst.append('\0') > > Kent Really??? I am a noob, but it looks like it only puts a \0 at the end if code (the length) is less than 255, as the if statement is out of the for loop? this would be part of the coding algorithm, no? In that theme of writing, here is what I would do to make it decode: def UnStuffData(src,dst,len): if code == 0xFF: pass else: x = src(0) for code in src: for i in range(1,code): if i == x: dst.append('\0') x = src(i) else: dst.append(i) dst.pop(0) #remove first byte # if code < 0xff # dst.append('\0') -mike --- Kent Johnson wrote: > Michael Cotherman wrote: > > def UnStuffData(src,dst,len): > > > > for code in src: > > for i in range(1,code): > > dst.append(i) > > > > if code < 0xff > > dst.append('\0') > > > > the above is the below code uncommented... > > it(and the original code) just seem to find the > end > > and puts a zero there... > > > > I do not see the existing zeroes replaced..... > this is > > kinda why I wanted to start from the > specification... > > The above is the decoding code, it does what you > describe below. It is adding the zeros back in, that > is the dst.append('\0') > > Kent > > > decoding is: > > pop the first byte of the packet off and place > > subsequent bytes into the output until you get to > the > > byte pointed to by the popped byte. When you reach > > that byte, read its value as the new 'relative' > > pointer, and copy x00 to the output. Proceed as > above, > > placing bytes to the output until the relative > pointer > > is reached or the end of the packet occurrs. > > > > I guess I need to look if I wish for this part of > the > > program to handle the input as one big existing > > string, or work on it a byte at a time as it comes > in. > > > > > > -mike c > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From sanju_nic at yahoo.com Fri Oct 7 08:28:36 2005 From: sanju_nic at yahoo.com (sanjay sinha) Date: Thu, 6 Oct 2005 23:28:36 -0700 (PDT) Subject: [Tutor] Tutor Digest, Vol 20, Issue 22 In-Reply-To: Message-ID: <20051007062836.29221.qmail@web60313.mail.yahoo.com> Is there any work done in language convirsion from endlish to hindi and vice versa please let me know tutor-request at python.org wrote: Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: Did anyone get the Kamaelia "Conversing" chapter 5 to work? (R. Alan Monroe) 2. Importing Modules Within Classes (Daniel Watkins) 3. Re: Did anyone get the Kamaelia "Conversing" chapter 5 to work? (Michael Sparks) 4. Re: Did anyone get the Kamaelia "Conversing" chapter 5 to work? (R. Alan Monroe) 5. Matching dictionary entries by partial key (William O'Higgins Witteman) 6. Re: Importing Modules Within Classes (Kent Johnson) 7. Re: Matching dictionary entries by partial key (Kent Johnson) 8. Simple Tkinter question (Mike Cheponis) 9. Re: Matching dictionary entries by partial key (Danny Yoo) 10. Re: Simple Tkinter question (Danny Yoo) ---------------------------------------------------------------------- Message: 1 Date: Thu, 6 Oct 2005 19:45:10 -0400 From: "R. Alan Monroe" Subject: Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? To: tutor at python.org Message-ID: <371655980944.20051006194510 at columbus.rr.com> Content-Type: text/plain; charset=us-ascii >> I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with >> the hundred or so messages intended for display, but they never get >> displayed. I suspect an indentation problem, but I can't spot it, even >> stepping through in the debugger. > I made exactly the same mistake! You have to put an infinite loop in > postman.main(). It's in the directions but I guess it's easy to > miss. Bingo, you da man. Alan ------------------------------ Message: 2 Date: Fri, 07 Oct 2005 01:18:24 +0100 From: "Daniel Watkins" Subject: [Tutor] Importing Modules Within Classes To: Message-ID: <1128644304.31050.3.camel at amdbert.oxbridgetechnology.local> Content-Type: text/plain; charset="iso-8859-1" Recently, there has been an example of someone importing modules within a class definition. eg: class Exemplar: import re ...use re... It seems obvious to me that this is incorrect, though more through training than actual observation on my part, and it should be: import re class Exemplar: ...use re... However, someone (I don't recall who) said that there were occasions when it would be appropriate to import modules the former way. I was just wondering under what circumstances importing should be done this way? Cheers, Dan ------------------------------ Message: 3 Date: Fri, 7 Oct 2005 02:23:32 +0100 From: Michael Sparks Subject: Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? To: "R. Alan Monroe" , tutor at python.org Message-ID: <200510070223.33116.zathras at thwackety.com> Content-Type: text/plain; charset="utf-8" On Friday 07 October 2005 00:13, R. Alan Monroe wrote: ... > I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with > the hundred or so messages intended for display, but they never get > displayed. I suspect an indentation problem, but I can't spot it, even > stepping through in the debugger. Hi! First of all thanks for trying the tutorial - hope it's been interesting. I'm sorry you hit a problem with it - it looks like the HTML formatting has caused some issues :-( All the code and examples used were tested before the being placed into the "tabbed" version of the tutorial. In this case it looks like the whitespace has gone horribly horribly wrong on that tab :-((( I'll sort it out. In the meantime though, In case of precisely this problem occuring, I also placed that source for all 4 main sections (Standing, Walking, Talking, Conversing) in the following page here: http://kamaelia.sourceforge.net/MiniAxonFull.html I've just double checked what happens when running the contents of that page, and it works as expected (here at least), so I suspect the problems you're seeing are simply due to "code being in HTML" issues. Also, the entire tutorial is available as a single page here, rather than tabbed: * http://kamaelia.sourceforge.net/MiniAxon.html But that has the answers inline, which is why I didn't mention it before. That *does* appear to have formatting preserved correctly in firefox, and I've also just double checked that when copying and pasting that the stated results were the ones stated. Hoping this helps, and thanks! If you're willing to spare a few sentances of how you found the tutorial (on or off list), I'd be really interested in hearing. If it's difficult, what was difficult (naff HTML for example...), if it was clear/unclear, that sort of thing. That said, this query is useful feedback in itself :) Best Regards, (and apologies for the HTML formatting ... :-( Michael. -- Michael Sparks, Senior R&D Engineer, Digital Media Group Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This e-mail may contain personal views which are not the views of the BBC. ------------------------------ Message: 4 Date: Thu, 6 Oct 2005 22:04:43 -0400 From: "R. Alan Monroe" Subject: Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? To: tutor at python.org Message-ID: <151664353784.20051006220443 at columbus.rr.com> Content-Type: text/plain; charset=us-ascii > I've just double checked what happens when running the contents of that > page, and it works as expected (here at least), so I suspect the problems > you're seeing are simply due to "code being in HTML" issues. Yeah I was writing as much as I was able on my own rather than copying/pasting the code, so it was mainly an oversight in my own work. Alan ------------------------------ Message: 5 Date: Thu, 6 Oct 2005 22:08:02 -0400 From: William O'Higgins Witteman Subject: [Tutor] Matching dictionary entries by partial key To: tutor at python.org Message-ID: <20051007020802.GA5679 at sillyrabbi.dyndns.org> Content-Type: text/plain; charset="us-ascii" I'm trying to traverse a dictionary looking for partial matches of the key, and I'm not sure how. Here's a sample dictionary: dict = {00001234 : value1, 20051234 : value2, 20071234 : value3} Here's what I'm trying to do: for key in dict: if key == 0000???? or key == 2005????: do something with dict[key] The challenge is that I only care about the first four digits of the key for the purpose of this match - is there a way to express this? I could probably create a wrapper dictionary using just the first four digits of the key as they key, and containing the original key:value pair as a list within it, but that seems cumbersome. Any one have a suggestion? Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20051006/7007a205/attachment-0001.pgp ------------------------------ Message: 6 Date: Thu, 06 Oct 2005 22:21:21 -0400 From: Kent Johnson Subject: Re: [Tutor] Importing Modules Within Classes Cc: tutor at python.org Message-ID: <4345DBA1.2000006 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Daniel Watkins wrote: > Recently, there has been an example of someone importing modules within > a class definition. eg: > > class Exemplar: > import re > ...use re... > > It seems obvious to me that this is incorrect, though more through > training than actual observation on my part, and it should be: > > import re > > class Exemplar: > ...use re... It's not really incorrect, it is legal syntax and it will do what you expect. It is not idiomatic and in general it is simpler to just put all the imports at the top. > However, someone (I don't recall who) said that there were occasions > when it would be appropriate to import modules the former way. I was > just wondering under what circumstances importing should be done this > way? That was me. I nest imports quite frequently in Jython code where the first import of a module is fairly expensive in time. Putting the import in the function that needs it delays the import and perhaps the module won't be imported at all. import is an executable statement. When it runs, the interpreter first looks to see if the module has already been imported. If so, the existing module is bound to the import name in the current namespace. If the module has not yet been imported, it is loaded *and executed*, then bound to the name in the current namespace. So if module A imports B which imports C and D, then importing A will also load and execute B, C and D. If any of these are time-consuming you may want to defer them. I found with my Jython programs that I could shorten start-up time quite a bit by deferring some imports until they were needed. Another reason for the nested style of imports is to resolve problems with circular imports. There are some subtle problems that can occur when A imports B and B imports A. By nesting one of the imports you can defer it and sometimes avoid the problem. In this case I think removing the circular import is a much better solution - circular dependencies are evil! Kent > > Cheers, > Dan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------ Message: 7 Date: Thu, 06 Oct 2005 22:28:23 -0400 From: Kent Johnson Subject: Re: [Tutor] Matching dictionary entries by partial key Cc: tutor at python.org Message-ID: <4345DD47.4080406 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed William O'Higgins Witteman wrote: > I'm trying to traverse a dictionary looking for partial matches of the > key, and I'm not sure how. Here's a sample dictionary: > > dict = {00001234 : value1, 20051234 : value2, 20071234 : value3} > > Here's what I'm trying to do: > > for key in dict: > if key == 0000???? or key == 2005????: if key.startswith('0000') or key.startswith('2005'): or with a regular expresion: if re.match('0000|2005', key): > do something with dict[key] > > The challenge is that I only care about the first four digits of the key > for the purpose of this match - is there a way to express this? I could > probably create a wrapper dictionary using just the first four digits of > the key as they key, and containing the original key:value pair as a > list within it, but that seems cumbersome. Any one have a suggestion? If you have a *lot* of keys and need more speed, that might be a good optimization. For a small dict, just use startswith(). Kent > Thanks. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor ------------------------------ Message: 8 Date: Thu, 6 Oct 2005 20:31:59 -0700 (PDT) From: Mike Cheponis Subject: [Tutor] Simple Tkinter question To: tutor at python.org Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed I'm trying to update an Entry's textvariable several times within my Button handler, like so: from Tkinter import * from time import * def my_update(): for i in range(3): tv.set("Now it's %d"%i) sleep(1) root=Tk() tv=StringVar() Entry(textvariable=tv).pack() tv.set("Initial Value of StringVar") Button(text="Update", command=my_update).pack() root.mainloop() What happens when I hit the Update button is a 3-second pause, then "Now it's 2" is displayed. What I expected to see in the Entry was: "Now it's 0" (right away) "Now it's 1" (after 1 second pause) "Now it's 2" (after another 1 second pause) Any idea what's going on here? Why doesn't "tv.set("") happen immediately? Thanks, -Mike ------------------------------ Message: 9 Date: Thu, 6 Oct 2005 21:35:13 -0700 (PDT) From: Danny Yoo Subject: Re: [Tutor] Matching dictionary entries by partial key To: William O'Higgins Witteman Cc: tutor at python.org Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII On Thu, 6 Oct 2005, William O'Higgins Witteman wrote: > I'm trying to traverse a dictionary looking for partial matches of the > key, and I'm not sure how. Here's a sample dictionary: > > dict = {00001234 : value1, 20051234 : value2, 20071234 : value3} > > Here's what I'm trying to do: > > for key in dict: > if key == 0000???? or key == 2005????: > do something with dict[key] > > The challenge is that I only care about the first four digits of the key > for the purpose of this match - is there a way to express this? I could > probably create a wrapper dictionary using just the first four digits of > the key as they key, and containing the original key:value pair as a > list within it, but that seems cumbersome. Hi William, The dictionary (hashtable) data structure is really meant for exact key match: it does not do partial keyword match well at all, and trying to bend it to do so is going against its grain. But using the first four digits as the key sounds right for your application: from what you've told us so far, you're trying to express a quick dictionary lookup using the first four digits as the key. If we do take this route, doing this is not too bad, especially if we take advantage of a dictionary's setdefault() method: ####### >>> words = 'this is a test of the emergency broadcast system'.split() >>> words ['this', 'is', 'a', 'test', 'of', 'the', 'emergency', 'broadcast', 'system'] >>> >>> d = {} >>> for word in words: ... d.setdefault(word[0], []).append(word) ... >>> >>> d {'a': ['a'], 'b': ['broadcast'], 'e': ['emergency'], 'i': ['is'], 'o': ['of'], 's': ['system'], 't': ['this', 'test', 'the']} ####### But as Kent mentioned, though, perhaps the easiest thing to implement is a simple linear scan across all your key-values, and not worry until we know this is a performance hotspot. *grin* It really depends on how many entries we're searching against. ------------------------------ Message: 10 Date: Thu, 6 Oct 2005 21:54:01 -0700 (PDT) From: Danny Yoo Subject: Re: [Tutor] Simple Tkinter question To: Mike Cheponis Cc: tutor at python.org Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII On Thu, 6 Oct 2005, Mike Cheponis wrote: > I'm trying to update an Entry's textvariable several times within my > Button handler, like so: > > from Tkinter import * > from time import * > > def my_update(): > for i in range(3): > tv.set("Now it's %d"%i) > sleep(1) > > root=Tk() > tv=StringVar() > Entry(textvariable=tv).pack() > tv.set("Initial Value of StringVar") > Button(text="Update", command=my_update).pack() > root.mainloop() Hi Mike, The problem is that the GUI needs control back to be able to update the GUI display. At the moment, there's only one thread of execution, and the call to time.sleep() deprives the GUI of the control it needs to draw things. Tkinter has a particular way of doing sleep()-like behavior that interacts better with the GUI. We can use the "after()" method to tell the GUI to do some action after some period of time. Here's a quick-and-dirty example: ###### import Tkinter root = Tkinter.Tk() label = Tkinter.Label(root, text="hello") label.pack() def doCountUpdate(n): label['text'] = n label.after(1000, doCountUpdate, n + 1) doCountUpdate(0) root.mainloop() ###### The initial call to doCountUpdate() updates the label text, and then tells the label: "after 1000 milliseconds (one second), call doCountUpdate again, and with n+1 as its argument." After we schedule this next update, we give control back to the GUI, and trust that the GUI will keep its promise to call our function after the timeout period. For reference information on this, see: http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm This isn't the only way to handle this sort of problem: another possible approach involves the use of threads. But you may want to try using 'after()' first, since I think it has an easier learning curve than threads. Best of wishes to you! ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 20, Issue 22 ************************************* --------------------------------- Yahoo! for Good Click here to donate to the Hurricane Katrina relief effort. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051006/4b9a3ae5/attachment-0001.html From servando at mac.com Fri Oct 7 08:32:38 2005 From: servando at mac.com (Servando Garcia) Date: Fri, 7 Oct 2005 01:32:38 -0500 Subject: [Tutor] pylibpcap Message-ID: <8608d6e15531bfeb3dfb4cbdf42e99d8@mac.com> Hello List I need to use pylibpcap. I am looking for any documentation at all, tutorial would be nice. From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 09:26:29 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Oct 2005 00:26:29 -0700 (PDT) Subject: [Tutor] Simple Tkinter question (fwd) Message-ID: ---------- Forwarded message ---------- Date: Thu, 6 Oct 2005 23:55:26 -0700 (PDT) From: Mike Cheponis To: Danny Yoo Subject: Re: [Tutor] Simple Tkinter question Danny, I got it: from Tkinter import * from time import * def my_update(): for i in range(3): tv.set("Now it's %d"%i) root.update() sleep(1) root=Tk() tv=StringVar() Entry(textvariable=tv).pack() tv.set("Initial Value of StringVar") Button(text="Update", command=my_update).pack() root.mainloop() Trick is call to update() - which I found by looking at a few pages before the one your URL pointed me to, so THANKS!!! again. Detail is here: http://www.pythonware.com/library/tkinter/introduction/x9374-event-processing.htm -Mike From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 09:43:07 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Oct 2005 00:43:07 -0700 (PDT) Subject: [Tutor] Tutor Digest, Vol 20, Issue 22 In-Reply-To: <20051007062836.29221.qmail@web60313.mail.yahoo.com> Message-ID: On Thu, 6 Oct 2005, sanjay sinha wrote: > Is there any work done in language convirsion from endlish to hindi and > vice versa Hi Sanjay, Machine Translation (MT) is Hard. I believe you're asking for some kind of automatic language translator, and I'm sure there is work being done, but it's an active research topic. If you are here because of the NTLK toolkit: http://nltk.sourceforge.net/ please be aware that just because something is written in Python doesn't meant that folks on Tutor know all about it. *grin* We can try to help you understand how to program in Python, but that's pretty much it. For anything more specific than that, you have to be more targetted toward the people you talk to. See: http://www.catb.org/~esr/faqs/smart-questions.html We here at Python-tutor can't give you much insight on Machine Translation, especially since your question really doesn't seem much related to Python or learning Python. Basically, you are posting on the wrong forum. Instead, try your favorite search engine on something like "statistical natural language processing" systems, and you should be able to find useful resources. For example, the GATE project: http://www.gate.ac.uk/ might be useful, as their page talks about integrating with many different languages including Hindi. But other than that, we can not help you: we really do not have expertise in this area. From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 09:54:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Oct 2005 00:54:19 -0700 (PDT) Subject: [Tutor] Simple Tkinter question (fwd) In-Reply-To: Message-ID: > Danny, I got it: > > from Tkinter import * > from time import * > > def my_update(): > for i in range(3): > tv.set("Now it's %d"%i) > root.update() > sleep(1) > > root=Tk() > tv=StringVar() > Entry(textvariable=tv).pack() > tv.set("Initial Value of StringVar") > Button(text="Update", command=my_update).pack() > root.mainloop() > > Trick is call to update() - which I found by looking at a few pages > before the one your URL pointed me to, so THANKS!!! again. Hi Mike, Ok, that works too. Another variation on your approach is the update_idletasks() method, which like update() should handle all the graphic-updating commands that are queued up for the GUI. There's a little more in: http://effbot.org/zone/tkinter-performance.htm http://mail.python.org/pipermail/tkinter-discuss/2005-June/000464.html that talks about what kind of GUI tasks are considered "idle", and when you might want to call update() or update_idletasks(). The issue with update() is that while the program is sleeping, GUI interaction, like button presses, will be ineffective, since we're still not relinquishing control back to the GUI. This may or may not be a problem for you. You've probably seen programs in the real world whose GUIs lag and drag when they do a lot of work. If that kind of program behavior annoys you, then you'll probably want to search for another solution in your own programs. *grin* From alan.gauld at freenet.co.uk Fri Oct 7 10:26:07 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 7 Oct 2005 09:26:07 +0100 Subject: [Tutor] Simple Tkinter question References: Message-ID: <007f01c5cb18$c51ec970$0c01a8c0@xp> > def my_update(): > for i in range(3): > tv.set("Now it's %d"%i) > sleep(1) > > Button(text="Update", command=my_update).pack() > root.mainloop() > > > What happens when I hit the Update button is a 3-second pause, then "Now > it's 2" is displayed. This is a common gotcha in GUI programming. The function executes but the GUI doesn't redraw itself on the screen until the function completes. Normally there is a GUI function you can call to force a redraw (or repaint or refresh) of the screeen before each sleep which should fix this. Unfortunately I can't see one for Tkinter. Another approach is to use a timer which creates its own events and catch them in your original function rather than using a loop, thus you change the value in the field and create a one second timer calling yourself, repeat the process until the value is where you want and stop creating timers! Finally you can bypass the timer by sending an event to yourself which is also associated with your callback, so after each sleep you post an event. But the simplest solution if you can find the function is to simply force a redraw after each loop iteration. There is a downside to this approach which may be why Tkinter doesn't appear to support it - if your function had a long loop the user would lose control of the application while the metod executed - you effctively make the app modal, which is "A Bad Thing". Thats why GUI purists prefer the timer/event techniques described above. HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Oct 7 10:31:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 7 Oct 2005 09:31:39 +0100 Subject: [Tutor] Simple Tkinter question (fwd) References: Message-ID: <008c01c5cb19$89fac0a0$0c01a8c0@xp> >> The problem is that the GUI needs control back to be able to update the >> GUI display. > > Thanks, but what I don't understand is: > > Why doesn't the call tv.set("string") update what's on the screen. > Clearly, > Tkinter has control at that point, and there's no reason to delay updating > the screen, > is there? The way most GUIs work is that the display is held in a buffer in memory. The buffer gets updated by commands then between events the GUI reftreshes the display. In most cases this results in smoother operation with less flicker on the screen. Unfortunately when a method wants to do lots of updates to the same field the intermediate values are lost so you need some way of allowing the refresh to take place. > I have a bunch of lines selected on the screen. I'm using Pmw. This > returned > tuple has a number of items I need to play. While the sound is playing, I > want > to display the name of the sound on the GUI. (The playing is done by a > routine > that writes to the serial port - that is, I call a function with the > filename of > the sound, and it plays it). The best approach to anything in GUI programming(and in real-time work of any sort!) is to propcess things one at a time, avoiding loops of any kind. When you have multiple items to process create an event for each subsequent action and allow the event loop to act as your loop. Thats what the after() function does (Thanks Danny I hadn't seen that one!). HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Oct 7 12:13:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Oct 2005 06:13:47 -0400 Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] In-Reply-To: <20051007055449.96239.qmail@web31805.mail.mud.yahoo.com> References: <20051007055449.96239.qmail@web31805.mail.mud.yahoo.com> Message-ID: <43464A5B.7080507@tds.net> Michael Cotherman wrote: >>....... is the decoding code, it does what you >>describe below. It is adding the zeros back in, that >>is the dst.append('\0') >> >>Kent > > Really??? I am a noob, but it looks like it only puts > a \0 at the end if code (the length) is less than 255, > as the if statement is out of the for loop? this would > be part of the coding algorithm, no? It puts 0 at the end of each segment if the length of the segment is less than FF. In the original C code, the for loop is copying the data of a segment. The while loop in both codes is looping over segments. Here is my understanding of the algorithm (with maybe a few fine details left out): To encode: - look for the first 0 byte in the data - if it is more than FE bytes from the start, write out and FF and the first FE bytes. This is a segment that *doesn't* end with a 0. - otherwise write out (1+the number of bytes before the 0), then all the bytes before the zero. Skip the input pointer to the byte after the 0. - repeat until no more data To decode: - get the next byte from the data. This is the count - get the next (count-1) bytes from the data and append to the output - if count < FF then this segment ends with a 0, so append a 0 to the output. - repeat until no more data Oh, I see you already wrote the same thing in your previous email! Kent > > In that theme of writing, here is what I would do to > make it decode: > > > def UnStuffData(src,dst,len): > if code == 0xFF: > pass > else: > x = src(0) > for code in src: > for i in range(1,code): > if i == x: > dst.append('\0') > x = src(i) > else: > dst.append(i) > > dst.pop(0) #remove first byte > # if code < 0xff > # dst.append('\0') > > > > > -mike > > > > --- Kent Johnson wrote: > > >>Michael Cotherman wrote: >> >>>def UnStuffData(src,dst,len): >>> >>> for code in src: >>> for i in range(1,code): >>> dst.append(i) >>> >>> if code < 0xff >>> dst.append('\0') >>> >>>the above is the below code uncommented... >>> it(and the original code) just seem to find the >> >>end >> >>>and puts a zero there... >>> >>>I do not see the existing zeroes replaced..... >> >>this is >> >>>kinda why I wanted to start from the >> >>specification... >> >>The above is the decoding code, it does what you >>describe below. It is adding the zeros back in, that >>is the dst.append('\0') >> >>Kent >> >> >>>decoding is: >>>pop the first byte of the packet off and place >>>subsequent bytes into the output until you get to >> >>the >> >>>byte pointed to by the popped byte. When you reach >>>that byte, read its value as the new 'relative' >>>pointer, and copy x00 to the output. Proceed as >> >>above, >> >>>placing bytes to the output until the relative >> >>pointer >> >>>is reached or the end of the packet occurrs. >>> >>>I guess I need to look if I wish for this part of >> >>the >> >>>program to handle the input as one big existing >>>string, or work on it a byte at a time as it comes >> >>in. >> >>> >>> >>>-mike c >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > > __________________________________ > Yahoo! Mail - PC Magazine Editors' Choice 2005 > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From missive at hotmail.com Fri Oct 7 13:57:01 2005 From: missive at hotmail.com (Lee Harr) Date: Fri, 07 Oct 2005 16:27:01 +0430 Subject: [Tutor] Making a character jump with pygame Message-ID: > I've edited the aliens.py example to make my character just move >back and forth. However I can't make him jump! It is not really clear to me from your code where you expect the character to jump. I do not see the word "jump" anywhere. I do see the word "bounce" and one reference to the top of the image so I will figure that is where you are working. You have a .move method for your Player sprite: def move(self, direction): if direction: self.facing = direction self.rect.move_ip(direction*self.speed, 0) self.rect = self.rect.clamp(SCREENRECT) if direction < 0: self.image = self.images[0] elif direction > 0: self.image = self.images[1] self.rect.top = self.origtop - (self.rect.left/self.bounce%2) origtop is set to the original value of top when the sprite is created, and bounce = 1 and never changes. What are you hoping this code will do? Just as an experiment (to test that changes to self.rect.top will actually make the sprite move up) I changed self.rect.top = self.origtop - (self.rect.left/self.bounce%2) to self.rect.top -= 1 You might want to look at that. Help us to help you. Name something "jump" or put in some comments about what you are expecting, and what is not working. >Here's my code (attached). I'm trying to make a platformer Mario style >game. The other thing I notice is that in the controls section... #handle player input direction = keystate[K_RIGHT] - keystate[K_LEFT] player.move(direction) You handle K_LEFT and K_RIGHT but there is nothing to handle any "jump" event. How does the user cause the Player to jump? _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kent37 at tds.net Fri Oct 7 14:03:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Oct 2005 08:03:27 -0400 Subject: [Tutor] Matching dictionary entries by partial key In-Reply-To: References: Message-ID: <4346640F.1020203@tds.net> Danny Yoo wrote: > But as Kent mentioned, though, perhaps the easiest thing to implement is a > simple linear scan across all your key-values, and not worry until we know > this is a performance hotspot. *grin* It really depends on how many > entries we're searching against. Another alternative is just a list of (key, value) pairs, that is easy to search with linear search. The only reason to keep a dict is if you are at some point doing a lookup by key. Without knowing more about your app I don't know if that is a requirement or not. Kent From ewalker at micron.com Fri Oct 7 16:03:21 2005 From: ewalker at micron.com (Eric Walker) Date: Fri, 7 Oct 2005 08:03:21 -0600 Subject: [Tutor] Importing Modules Within Classes In-Reply-To: <4345DBA1.2000006@tds.net> References: <1128644304.31050.3.camel@amdbert.oxbridgetechnology.local> <4345DBA1.2000006@tds.net> Message-ID: <200510070803.21747.ewalker@micron.com> That was me using the import within the class. I only did it due to my ignorance. I am not advanced enough to use it like that and know what I am doing, so as suggested I just moved all of my imports to the top. Python Newbie..... On Thursday 06 October 2005 08:21 pm, Kent Johnson wrote: > Daniel Watkins wrote: > > Recently, there has been an example of someone importing modules within > > a class definition. eg: > > > > class Exemplar: > > import re > > ...use re... > > > > It seems obvious to me that this is incorrect, though more through > > training than actual observation on my part, and it should be: > > > > import re > > > > class Exemplar: > > ...use re... > > It's not really incorrect, it is legal syntax and it will do what you > expect. It is not idiomatic and in general it is simpler to just put all > the imports at the top. > > > However, someone (I don't recall who) said that there were occasions > > when it would be appropriate to import modules the former way. I was > > just wondering under what circumstances importing should be done this > > way? > > That was me. I nest imports quite frequently in Jython code where the first > import of a module is fairly expensive in time. Putting the import in the > function that needs it delays the import and perhaps the module won't be > imported at all. > > import is an executable statement. When it runs, the interpreter first > looks to see if the module has already been imported. If so, the existing > module is bound to the import name in the current namespace. If the module > has not yet been imported, it is loaded *and executed*, then bound to the > name in the current namespace. > > So if module A imports B which imports C and D, then importing A will also > load and execute B, C and D. If any of these are time-consuming you may > want to defer them. > > I found with my Jython programs that I could shorten start-up time quite a > bit by deferring some imports until they were needed. > > Another reason for the nested style of imports is to resolve problems with > circular imports. There are some subtle problems that can occur when A > imports B and B imports A. By nesting one of the imports you can defer it > and sometimes avoid the problem. In this case I think removing the circular > import is a much better solution - circular dependencies are evil! > > Kent > > > Cheers, > > Dan > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From william.ohiggins at utoronto.ca Fri Oct 7 16:26:35 2005 From: william.ohiggins at utoronto.ca (William O'Higgins Witteman) Date: Fri, 7 Oct 2005 10:26:35 -0400 Subject: [Tutor] Matching dictionary entries by partial key In-Reply-To: <4345DD47.4080406@tds.net> References: <20051007020802.GA5679@sillyrabbi.dyndns.org> <4345DD47.4080406@tds.net> Message-ID: <20051007142635.GA3691@sillyrabbi.dyndns.org> On Thu, Oct 06, 2005 at 10:28:23PM -0400, Kent Johnson wrote: >William O'Higgins Witteman wrote: >> I'm trying to traverse a dictionary looking for partial matches of the >> key, and I'm not sure how. Here's a sample dictionary: >> >> dict = {00001234 : value1, 20051234 : value2, 20071234 : value3} >> >> Here's what I'm trying to do: >> >> for key in dict: >> if key == 0000???? or key == 2005????: > > if key.startswith('0000') or key.startswith('2005'): This is perfect! Where do I read about things like this? I've been spending a bunch of time with the python.org documentation, "A Byte of Python" and "Dive Into Python", but I didn't run across this. >or with a regular expresion: > if re.match('0000|2005', key): This is good too, and it shows me the syntax (which I had trouble with). >> do something with dict[key] >> >> The challenge is that I only care about the first four digits of the key >> for the purpose of this match - is there a way to express this? I could >> probably create a wrapper dictionary using just the first four digits of >> the key as they key, and containing the original key:value pair as a >> list within it, but that seems cumbersome. Any one have a suggestion? > >If you have a *lot* of keys and need more speed, that might be a good optimization. For a small dict, just use startswith(). Should I compile the regex to further increase the speed? Thanks for the help. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20051007/64f81b6b/attachment.pgp From pierre.barbier at cirad.fr Fri Oct 7 16:45:58 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 07 Oct 2005 16:45:58 +0200 Subject: [Tutor] Importing Modules Within Classes In-Reply-To: <4345DBA1.2000006@tds.net> References: <1128644304.31050.3.camel@amdbert.oxbridgetechnology.local> <4345DBA1.2000006@tds.net> Message-ID: <43468A26.1060303@cirad.fr> Kent Johnson a ?crit : > Daniel Watkins wrote: > >[...] > >>However, someone (I don't recall who) said that there were occasions >>when it would be appropriate to import modules the former way. I was >>just wondering under what circumstances importing should be done this >>way? > > > That was me. I nest imports quite frequently in Jython code where the first import of a module is fairly expensive in time. Putting the import in the function that needs it delays the import and perhaps the module won't be imported at all. > > import is an executable statement. When it runs, the interpreter first looks to see if the module has already been imported. If so, the existing module is bound to the import name in the current namespace. If the module has not yet been imported, it is loaded *and executed*, then bound to the name in the current namespace. > > So if module A imports B which imports C and D, then importing A will also load and execute B, C and D. If any of these are time-consuming you may want to defer them. > > I found with my Jython programs that I could shorten start-up time quite a bit by deferring some imports until they were needed. > > Another reason for the nested style of imports is to resolve problems with circular imports. There are some subtle problems that can occur when A imports B and B imports A. By nesting one of the imports you can defer it and sometimes avoid the problem. In this case I think removing the circular import is a much better solution - circular dependencies are evil! > A third reason is not to load module that will probably not be used :) In my code, I have objects that have geometrical representations. My objects can produce images of themselves using differente libraries. Some are huge and takes time and memory to load ... also one specific user will probably use only one such library at a time (and will probably load it before ...) As each function run is quite time consuming, adding the module check is not a problem also ! (never import a module in a small function likely to be called in an inner-loop !) Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From surangasa at gmail.com Fri Oct 7 11:20:40 2005 From: surangasa at gmail.com (Suranga Sarukkali) Date: Fri, 7 Oct 2005 15:20:40 +0600 Subject: [Tutor] Is it Posible? To Crack And HowTo Message-ID: <000401c5cb4e$e729c890$8bc045ca@computer01> All this could look mostly like any of a question of a idiot! sorry for that. I've heard that Python is good for hacking and when I ask how to here on python tutor mailing list answers were all about reading some article I've already read before, it's not hacking I'm into now but a similar thing, Cracking and I've got lots of software by these we call proprietary software developers who are some greedy people having fun licensing software. Can I get help to this using python and if how to? or elif can't how to? else where can I get started and going? Thanks for all other questions you've answered! reply to me on surangasa at gmail.com at your earliest convenience. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051007/12edafc0/attachment-0001.html -------------- next part -------------- A non-text attachment was scrubbed... Name: Suranga Sarukkali.vcf Type: text/x-vcard Size: 414 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051007/12edafc0/SurangaSarukkali-0001.vcf From kent37 at tds.net Fri Oct 7 17:02:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Oct 2005 11:02:01 -0400 Subject: [Tutor] Matching dictionary entries by partial key In-Reply-To: <20051007142635.GA3691@sillyrabbi.dyndns.org> References: <20051007020802.GA5679@sillyrabbi.dyndns.org> <4345DD47.4080406@tds.net> <20051007142635.GA3691@sillyrabbi.dyndns.org> Message-ID: <43468DE9.6010606@tds.net> William O'Higgins Witteman wrote: > On Thu, Oct 06, 2005 at 10:28:23PM -0400, Kent Johnson wrote: >> if key.startswith('0000') or key.startswith('2005'): > > > This is perfect! Where do I read about things like this? I've been > spending a bunch of time with the python.org documentation, "A Byte of > Python" and "Dive Into Python", but I didn't run across this. Chapter 2 of the Python Library Reference is recommended reading. It documents all the builtin functions (e.g. int(), chr(), enumerate()...) and types (list, dict, str...). In particular section 2.3.6.1 documents string methods such as startswith(). It's worth browsing the table of contents, too - it gives a subject-oriented catalog of all the standard library modules. http://docs.python.org/lib/builtin.html http://docs.python.org/lib/string-methods.html > Should I compile the regex to further increase the speed? Yes, compile it outside the loop and use the compiled regex for the match: import re myRe = re.compile('0000|2005') for key in dict: if myRe.match(key): BTW dict is a bad name for a dict, it is the name of the actual dict class. In general you should avoid using the names of built-ins as variable names because your variable will shadow the builtin. It's particularly easy to make this mistake with the names 'list', 'dict' and 'file'. Kent From kent37 at tds.net Fri Oct 7 17:09:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Oct 2005 11:09:16 -0400 Subject: [Tutor] Is it Posible? To Crack And HowTo In-Reply-To: <000401c5cb4e$e729c890$8bc045ca@computer01> References: <000401c5cb4e$e729c890$8bc045ca@computer01> Message-ID: <43468F9C.3000705@tds.net> Suranga Sarukkali wrote: > All this could look mostly like any of a question of a idiot! sorry for > that. > I've heard that Python is good for hacking and when I ask how to here on > python tutor mailing list answers were all about reading some article > I've already read before, it's not hacking I'm into now but a similar > thing, Cracking and I've got lots of software by these we call > proprietary software developers who are some greedy people having fun > licensing software. Can I get help to this using python and if how to? > or elif can't how to? else where can I get started and going? No, you can't get help cracking proprietary software on this list. Many of us are professional software developers who make a living as "greedy people having fun licensing software". Kent From kent37 at tds.net Fri Oct 7 17:12:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Oct 2005 11:12:15 -0400 Subject: [Tutor] Importing Modules Within Classes In-Reply-To: <43468A26.1060303@cirad.fr> References: <1128644304.31050.3.camel@amdbert.oxbridgetechnology.local> <4345DBA1.2000006@tds.net> <43468A26.1060303@cirad.fr> Message-ID: <4346904F.1090403@tds.net> Pierre Barbier de Reuille wrote: > (never import > a module in a small function likely to be called in an inner-loop !) That's good advice, but I would say "in a *time-critical* inner-loop". After the first import, importing a module is fast, it is just a few dictionary lookups (looking up the module in sys.modules) and a dictionary write (to the local namespace). It's only the first import that is potentially expensive. Kent From daniel at thewatkins.org.uk Fri Oct 7 17:27:47 2005 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Fri, 07 Oct 2005 16:27:47 +0100 Subject: [Tutor] FW: Is it Posible? To Crack And HowTo In-Reply-To: <9AA4216B8A36B9429BB00C546DF6D27210879E@schubert.OxbridgeTechnology.local> References: <9AA4216B8A36B9429BB00C546DF6D27210879E@schubert.OxbridgeTechnology.local> Message-ID: <1128698867.14474.5.camel@amdbert.oxbridgetechnology.local> > > I've already read before, it's not hacking I'm into now but a > similar thing, Cracking Hacking and cracking are two completely different things. Hacking is a developer with some real talent actually making a contribution to computing by writing something of use. Cracking is a jackass who's too cheap to buy some proprietary software and/or too lazy/stupid to learn how to do what he wants to do in OSS. With the utmost respect, obviously. However, I don't want to use up the list, so if you want to comment on anything I just wrote, feel free to email me personally (daniel at thewatkins.org.uk as opposed to tutor at python.org) > No, you can't get help cracking proprietary software on this list. > Many of us are professional software developers who make a living as > "greedy people having fun licensing software". How do you sleep at night? ;) Dan From kent37 at tds.net Fri Oct 7 17:47:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Oct 2005 11:47:34 -0400 Subject: [Tutor] FW: Is it Posible? To Crack And HowTo In-Reply-To: <1128698867.14474.5.camel@amdbert.oxbridgetechnology.local> References: <9AA4216B8A36B9429BB00C546DF6D27210879E@schubert.OxbridgeTechnology.local> <1128698867.14474.5.camel@amdbert.oxbridgetechnology.local> Message-ID: <43469896.4090203@tds.net> Daniel Watkins wrote: >>No, you can't get help cracking proprietary software on this list. >>Many of us are professional software developers who make a living as >>"greedy people having fun licensing software". > > How do you sleep at night? ;) On a good day the fun of creating all those licenses lets me sleep with a smile on my face. On a bad day, I have nightmares about all the hungry children caused by my greed. ;-) From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 19:40:27 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Oct 2005 10:40:27 -0700 (PDT) Subject: [Tutor] Simple Tkinter question (fwd) Message-ID: [Keeping Tutor in CC] ---------- Forwarded message ---------- Date: Fri, 7 Oct 2005 01:25:26 -0700 (PDT) From: Mike Cheponis To: Danny Yoo Subject: Re: [Tutor] Simple Tkinter question (fwd) On Fri, 7 Oct 2005, Danny Yoo wrote: > Ok, that works too. Another variation on your approach is the > update_idletasks() method, which like update() should handle all the > graphic-updating commands that are queued up for the GUI. There's a > little more in: Yeah, the instant after I sent you that msg, I tried update_idletasks and it worked, too, so I switched to using that. > http://effbot.org/zone/tkinter-performance.htm > http://mail.python.org/pipermail/tkinter-discuss/2005-June/000464.html Thanks, very helpful. > that talks about what kind of GUI tasks are considered "idle", and when > you might want to call update() or update_idletasks(). > > > The issue with update() is that while the program is sleeping, GUI > interaction, like button presses, will be ineffective, since we're still > not relinquishing control back to the GUI. > This may or may not be a problem for you. You've probably seen programs > in the real world whose GUIs lag and drag when they do a lot of work. If > that kind of program behavior annoys you, then you'll probably want to > search for another solution in your own programs. *grin* Yeah, one of those references says to _insert_ calls to update_idletasks to get the GUI to be more responsive. I wish I understood Tkinter better; I've looked at most of the on-line stuff, and I think I have every Python book ever printed, but some Tk stuff still seems mysterious. well, after I deliver this one program with Tk, I think I'm going to switch to wxPython for future GUI front-ends. Thanks again, -Mike From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 19:47:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Oct 2005 10:47:42 -0700 (PDT) Subject: [Tutor] pylibpcap In-Reply-To: <8608d6e15531bfeb3dfb4cbdf42e99d8@mac.com> Message-ID: On Fri, 7 Oct 2005, Servando Garcia wrote: > I need to use pylibpcap. I am looking for any documentation at > all, tutorial would be nice. Hi Servando, Have you looked at the python-libpcap forum? That's probably be a better place to ask questions on pylibpcap: http://sourceforge.net/forum/forum.php?forum_id=44279 Good luck! From dyoo at hkn.eecs.berkeley.edu Fri Oct 7 20:07:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Oct 2005 11:07:39 -0700 (PDT) Subject: [Tutor] Is it Posible? To Crack And HowTo In-Reply-To: <000401c5cb4e$e729c890$8bc045ca@computer01> Message-ID: On Fri, 7 Oct 2005, Suranga Sarukkali wrote: > I've heard that Python is good for hacking and when I ask how to here on > python tutor mailing list answers were all about reading some article > I've already read before, [text cut] Here, read a little more. ESR has written an article on the kind of "hacking" that we do here on Tutor: http://www.catb.org/~esr/faqs/hacker-howto.html > I've got lots of software by these we call proprietary software > developers who are some greedy people having fun licensing software. It is not polite to call people "greedy" when you do not know who they are. And unfortunately, your ethics system is different from that of professional software developers. For a concrete example, see Section 1.5 of the ACM Code of Ethics: http://www.acm.org/constitution/code.html The whole Open Source movement is based on the power of copyright law and software licenses: http://www.opensource.org/licenses/ so I'm not sure I'm following the implication about proprietary software developent and licenses: the OSS folks have licenses too. From bill at celestial.net Fri Oct 7 21:00:43 2005 From: bill at celestial.net (Bill Campbell) Date: Fri, 7 Oct 2005 12:00:43 -0700 Subject: [Tutor] Importing Modules Within Classes In-Reply-To: <4346904F.1090403@tds.net> References: <1128644304.31050.3.camel@amdbert.oxbridgetechnology.local> <4345DBA1.2000006@tds.net> <43468A26.1060303@cirad.fr> <4346904F.1090403@tds.net> Message-ID: <20051007190043.GB53506@alexis.mi.celestial.com> On Fri, Oct 07, 2005, Kent Johnson wrote: >Pierre Barbier de Reuille wrote: >> (never import >> a module in a small function likely to be called in an inner-loop !) > >That's good advice, but I would say "in a *time-critical* inner-loop". After the first import, importing a module is fast, it is just a few dictionary lookups (looking up the module in sys.modules) and a dictionary write (to the local namespace). It's only the first import that is potentially expensive. Another way that I use this is to handle parts of a module that may not always be used (e.g. curses routines for interactive use). In this case we have a module that provides our curses interactive screen routines, and it has something like this: import os os.environ['cursesstuff'] = True Then in the more general purpose routines: # stuff goes here that's not interactive if os.environ.get('cursestuff']: import ... class ... # other things that don't need the extra functions. All that's necessary to activate the interactive classes and other related stuff is to include the curses routines before importing the modules that may or may not use them. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``It wasn't raining when Noah built the ark.'' From zathras at thwackety.com Fri Oct 7 23:15:35 2005 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 7 Oct 2005 22:15:35 +0100 Subject: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? In-Reply-To: <151664353784.20051006220443@columbus.rr.com> References: <200509302251.07797.michaels@rd.bbc.co.uk> <200510070223.33116.zathras@thwackety.com> <151664353784.20051006220443@columbus.rr.com> Message-ID: <200510072215.35495.zathras@thwackety.com> On Friday 07 October 2005 03:04, R. Alan Monroe wrote: > > I've just double checked what happens when running the contents of that > > page, and it works as expected (here at least), so I suspect the problems > > you're seeing are simply due to "code being in HTML" issues. > > Yeah I was writing as much as I was able on my own rather than > copying/pasting the code, so it was mainly an oversight in my own > work. That's great to hear - not the oversight part but the fact you were talking about your work. Out of interest, how did you find the tutorial/exercises and what level of experience would you say you have? (I know some people find such questions rude and impertinent though so if you want to not say, I don't have a problem, I just hope you found it useful/interesting) Also, if there were bits you found odd, broken, etc, we'd be really interested in hearing things. Specifically I'm more interested in knowing whether a) the approach is compehensible based on the tutorial b) whether the tutorial sucks over some momentary twinge of personal ego. I lived in the North of England for several years (not recently, but...) , so strong language/views won't offend ;-) We're going to be making a 0.3 release of Kamaelia this weekend which has a lot more facilities than the previous releases, but the core approach remains the same - bolting together things. Anyway, thanks for the feedback, it's useful - very useful - and I hope the tutorial helped with understanding generators, how to use them and what they could be used for (if you weren't already comfortable with them :-) Best regards, Michael. -- "Though we are not now that which in days of old moved heaven and earth, that which we are, we are: one equal temper of heroic hearts made weak by time and fate but strong in will to strive, to seek, to find and not to yield" -- "Ulysses", Tennyson From zathras at thwackety.com Fri Oct 7 23:57:29 2005 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 7 Oct 2005 22:57:29 +0100 Subject: [Tutor] New Python book In-Reply-To: <4344195E.50708@tds.net> References: <6.2.1.2.2.20051005105008.06a3be10@rcblue.com> <4344195E.50708@tds.net> Message-ID: <200510072257.29250.zathras@thwackety.com> On Wednesday 05 October 2005 19:20, Kent Johnson wrote: > This seems to be an update to his previous book, "Practical Python", rather > than a completely new book. The TOC is almost identical. I haven't read the > earlier book, either, so I don't have an opinion. The same sample chapter > is available for each if anyone wants to compare. (see www.apress.com) My wife bought me 'Practical Python' for my birthday last year. I found it to be a very readable style and interesting. I quite like reading books aimed at beginners/novices/etc because it normally results in a fresh view of subjects that I feel are done and dusted. The thing I find particularly interesting about the approach is the 'project oriented' approach in the latter half of the book. I found the GUI chapters to be relatively useless to me. Having downloaded the sources to the examples for this update though it looks like he's using wx extensively throughout, which strikes me as both a good & bad choice. Good in that wx is pretty good, bad in that using Tk would IMO be better since python ships with Tk. That's highly subjective though. Best Regards, Michael. From alberto.troiano at gmail.com Sat Oct 8 00:06:16 2005 From: alberto.troiano at gmail.com (Alberto Troiano) Date: Fri, 7 Oct 2005 18:06:16 -0400 Subject: [Tutor] Config Parser question Message-ID: Hey tutors I'm trying to make a configuration file I know how to read the sections and options (using ConfigParser module from Python 2.3.4 on Win XP) What I wanted to know is that eventually I will need to add sections and options or change values or erase options or , etc Is there any way that I can do this changes to the config.ini file? Thanks in advanced Alberto -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051007/99ea7a9e/attachment.html From alan.gauld at freenet.co.uk Sat Oct 8 00:11:55 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 7 Oct 2005 23:11:55 +0100 Subject: [Tutor] Simple Tkinter question (fwd) References: Message-ID: <007c01c5cb8c$20ef70b0$0c01a8c0@xp> > I wish I understood Tkinter better; I've looked at most of the on-line > stuff, ... > well, after I deliver this one program with Tk, I think I'm going to > switch > to wxPython for future GUI front-ends. Most of the issues discssed on this thread apply to every GUI environment. They all basically work the same way with the GUI providing an event loop which calls callback functions in response to an event. If a callback handler goes into a long loop the GUI app will freeze. THats how GUIs work, Tlinter vv wxPython won't change that. wxPython will give a slightly nicer look n feel to your apps though (especially on Windows). Alan G. From zathras at thwackety.com Sat Oct 8 00:16:50 2005 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 7 Oct 2005 23:16:50 +0100 Subject: [Tutor] Is it Posible? To Crack And HowTo In-Reply-To: <000401c5cb4e$e729c890$8bc045ca@computer01> References: <000401c5cb4e$e729c890$8bc045ca@computer01> Message-ID: <200510072316.50481.zathras@thwackety.com> On Friday 07 October 2005 10:20, Suranga Sarukkali wrote: > All this could look mostly like any of a question of a idiot! sorry for > that. I've heard that Python is good for hacking and when I ask how to here > on python tutor mailing list answers were all about reading some article > I've already read before, it's not hacking I'm into now but a similar > thing, Cracking and I've got lots of software by these we call proprietary > software developers who are some greedy people having fun licensing > software. Can I get help to this using python and if how to? or elif can't > how to? else where can I get started and going? > > Thanks for all other questions you've answered! > reply to me on surangasa at gmail.com at your earliest convenience. People who license software are well within their rights to do so. It took them time, effort and hence money to produce the software, and they deserve recompense. You wouldn't *demand* that the people emptying the bins in offces the code was developed in work for no wages would you? If you can't afford the software at their prices, I would suggest that it is they who have a problem rather than you. After all you have a wide variety of alternatives available. I don't however respect anyone who doesn't respect the rights of others. Sure, I don't agree with the poltics of party X and partly that's to do with not agreeing with their views on what is/isn't greedy. That doesn't give me the right to damage their livelihood. If you can't afford their software, then can I request you sta,rt using Free Software instead? You will still be complying with greedy people's licenses (they're greedy for freedom), but you will be helping people rather than hurting people. You might ask who am I to ask this question this way - a fair question. I'm a person who was once a student, and when unable to pay for a commercial C compiler (neither Microsoft's or Borland's) chose the route of using DJGPP - a Free alternative. I didn't consider rogue copying then acceptable, despite a need, and lack of finance, and nor do I now. There are alternatives. Also, finally consider this: the required ability to *make* a crack (rather than follow a script) is normally pretty high. You /could/ apply that ability soley to destroying the incomes of people (which is what you do if you /release. a crack) . Alternatively you could take that energy and ability into building better things. Destruction or construction? your choice. I doubt you'll find many, if any, people to aid you in a destructive task. Regards, Michael. From alan.gauld at freenet.co.uk Sat Oct 8 00:20:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 7 Oct 2005 23:20:54 +0100 Subject: [Tutor] Is it Posible? To Crack And HowTo References: <000401c5cb4e$e729c890$8bc045ca@computer01> <43468F9C.3000705@tds.net> Message-ID: <008401c5cb8d$620be0a0$0c01a8c0@xp> > Suranga Sarukkali wrote: >> thing, Cracking and I've got lots of software by these we call >> proprietary software developers who are some greedy people having fun >> licensing software. Define greedy. Is it reasonable to get paid for the several years worth of effort that goes into creating the proprietary software? Some of the projects I've been involved with have entailed over 1000 man years of effort. If we sell 1 million copies then each copy must cover the physical production costs plus at least 1000th of a man-years wage - around $50-100 in the US. So a factory price of $100-150 would result in a retail price of $200-300 per package. Is that being greedy? It only just covers the cost of production and distribution with nothing for future investment and research. And in practice not that many programs sell 1 million copies! > > Can I get help to this using python and if how to? or elif can't how to? > > else where can I get started and going? You are unlikely to get help from a public forum to pursue criminal activities that could land you in court or even prison in most countries. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Oct 8 00:35:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Oct 2005 18:35:59 -0400 Subject: [Tutor] Config Parser question In-Reply-To: References: Message-ID: <4346F84F.4080700@tds.net> Alberto Troiano wrote: > I?m trying to make a configuration file > > I know how to read the sections and options (using ConfigParser module > from Python 2.3.4 on Win XP) > > What I wanted to know is that eventually I will need to add sections and > options or change values or erase options or , etc > > Is there any way that I can do this changes to the config.ini file? Sure. See the docs for RawConfigParser add_section(), set() and write(). ConfigParser is a subclass of RawConfigParser so you can use any of these methods. http://docs.python.org/lib/RawConfigParser-objects.html Kent From alberto.troiano at gmail.com Sat Oct 8 00:45:01 2005 From: alberto.troiano at gmail.com (Alberto Troiano) Date: Fri, 7 Oct 2005 18:45:01 -0400 Subject: [Tutor] Config Parser question In-Reply-To: <4346F84F.4080700@tds.net> Message-ID: Hey Kent Thank you for the reply Let me get this straight.. In order to store the new configuration I would have to make something like this? import ConfigParser f=open("config.ini","w+") c=ConfigParser.ConfigParser() c.add_section("foo") c.write(f) Please let me know if this is correct Thank you Alberto -----Mensaje original----- De: Kent Johnson [mailto:kent37 at tds.net] Enviado el: Viernes, 07 de Octubre de 2005 18:36 Para: Alberto Troiano CC: tutor at python.org Asunto: Re: [Tutor] Config Parser question Alberto Troiano wrote: > I'm trying to make a configuration file > > I know how to read the sections and options (using ConfigParser module > from Python 2.3.4 on Win XP) > > What I wanted to know is that eventually I will need to add sections and > options or change values or erase options or , etc > > Is there any way that I can do this changes to the config.ini file? Sure. See the docs for RawConfigParser add_section(), set() and write(). ConfigParser is a subclass of RawConfigParser so you can use any of these methods. http://docs.python.org/lib/RawConfigParser-objects.html Kent From dyoo at hkn.eecs.berkeley.edu Sat Oct 8 01:37:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Oct 2005 16:37:53 -0700 (PDT) Subject: [Tutor] Is it Posible? To Crack And HowTo In-Reply-To: Message-ID: > > I've heard that Python is good for hacking and when I ask how to here > > on python tutor mailing list answers were all about reading some > > article I've already read before, Hi Suranga, I thought I already read this before too. http://mail.python.org/pipermail/tutor/2005-July/040002.html http://mail.python.org/pipermail/tutor/2005-August/040791.html As a list administrator, I have the responsiblity to warn you in public: your behavior on the list will not be tolerated much longer if you continue on this course. Please reconsider your actions. From kent37 at tds.net Sat Oct 8 03:21:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Oct 2005 21:21:29 -0400 Subject: [Tutor] Config Parser question In-Reply-To: References: Message-ID: <43471F19.4070300@tds.net> Alberto Troiano wrote: > Let me get this straight.. In order to store the new configuration I would > have to make something like this? > > import ConfigParser > > f=open("config.ini","w+") I would use 'w' but to tell the truth I'm not to clear on the difference between 'w' and 'w+' > c=ConfigParser.ConfigParser() > c.add_section("foo") you might want c.set('foo', 'bar', 'baz') > c.write(f) > > Please let me know if this is correct I think so. Why not try it? Kent > > Thank you > > Alberto > > -----Mensaje original----- > De: Kent Johnson [mailto:kent37 at tds.net] > Enviado el: Viernes, 07 de Octubre de 2005 18:36 > Para: Alberto Troiano > CC: tutor at python.org > Asunto: Re: [Tutor] Config Parser question > > Alberto Troiano wrote: > >>I'm trying to make a configuration file >> >>I know how to read the sections and options (using ConfigParser module >>from Python 2.3.4 on Win XP) >> >>What I wanted to know is that eventually I will need to add sections and >>options or change values or erase options or , etc >> >>Is there any way that I can do this changes to the config.ini file? > > > Sure. See the docs for RawConfigParser add_section(), set() and write(). > ConfigParser is a subclass of RawConfigParser so you can use any of these > methods. > http://docs.python.org/lib/RawConfigParser-objects.html > > Kent > > > > From mjcother at yahoo.com Sat Oct 8 05:39:40 2005 From: mjcother at yahoo.com (Michael Cotherman) Date: Fri, 7 Oct 2005 20:39:40 -0700 (PDT) Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] In-Reply-To: <007901c5c9ba$f5985b70$0c01a8c0@xp> Message-ID: <20051008033940.88140.qmail@web31803.mail.mud.yahoo.com> The c code seems to be walking through the list moving bytes from src to dst, but the python code below seems to take one byte from src, start counitng up to the value from 1 and appending each and every value along the way to dst, no? -mike --- Alan Gauld wrote: > > I am a noob to converting pointers in C++ to > arrays in > > python, although the first time I see it done, I > will > > have no problem. Can you help converting the below > > (what I think is the 'decoder' section) to python? > > It won't be working code but I think this is whats > happening... > > > UINT CCobsPackets::UnStuffData(unsigned char *src, > > unsigned char *dst, UINT length) > > def UnStuffData(src,dst,len): > > > { > > unsigned char *dstStart = dst; > > unsigned char *end = src + length; > > # I don't think these are needed for Pyhon. > > > while (src < end) > > for code in src: > > > { > > int code = *src++; > > for (int i=1; i > { > > *dst++ = *src++; > > } > > for i in range(1,code): > dst.append(i) > > > if (code < 0xFF) > > { > > *dst++ = 0; > > } > > if code < 0xff > dst.append('\0') # may not be needed in > python... > > > } > > return (UINT)(dst - dstStart); > > } __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From broek at cc.umanitoba.ca Sat Oct 8 08:56:05 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 08 Oct 2005 01:56:05 -0500 Subject: [Tutor] subclass problem: __names and type-checking Message-ID: <43476D85.2050806@cc.umanitoba.ca> Hi all, I'm having an issue which resists my attempts to give a snappy label to it. I have a solution that doesn't feel entirely correct, and which I cannot actual apply to my original case. The Issue: I have a class which I want to subclass. The subclass adds some additional arguments to __init__. I want both classes to run a sanity check on their arguments before leaving their respective __init__ methods. I need both to do so, as the _BaseClass may be directly instantiated. I need to ask permission for the arguments on instance creation rather than for forgiveness later, as bad arguments passed to __init__ could take many cpu cycles of other code before they manifested themselves. Here's a sketch of where I'm at: class _BaseClass(object): def __init__(self, arg1, arg2): self.arg1 = arg1 self.arg2 = arg2 if type(self) == _BaseClass: # Problem (2) mentioned below shows up here. # # type test needed otherwise Subclass._validate_args # will be called before all subclass args processed by # SubClass.__init__, causing AttriuteError self._validate_args() def _validate_args(self): '''Performs sanity check on arguments''' if not type(self.arg1) in (int, long): raise TypeError # etc class SubClass(_BaseClass): def __init__(self, arg1, arg2, arg3, arg4): super(SubClass, self).__init__(arg1, arg2) self.arg3 = arg3 self.arg4 = arg4 if type(self) == SubClass: # same reasoning as before -- leaving room for further # subclassing. self._validate_args() def _validate_args(self): super(SubClass, self)._validate_args() if not isinstance(self.arg3, basestring): raise TypeError # etc This works as desired, but leaves two problems: 1) I suspect there may be a better way, as a) this doesn't feel quite right and b) in general with Python, it seems that if you are tempted to type test, you should rethink, and 2) I originally had __BaseClass rather than _BaseClass. But, with that naming, cannot figure out how to write the line if type(self) == __BaseClass: so as to make it work. I know about the name mangling with __somename names, but I don't know how to manage it in this case. The attempt of 4 lines up produces: NameError: global name '_BaseClass__BaseClass' is not defined This confuses me. I don't see why the error msg prepends '_BaseClass' as that name appears nowhere. That confusion aside, I've no idea how to effect what I want. I think I won't want __BaseClass in the end, as I do expect it is possible that it will be instantiated directly, so the '__' seems inappropriate. But, the issue of how to do it remains. So, details of '_' vs '__' aside, is my approach sound? And, how to deal with __BaseClass? Best to all, Brian vdB From matthew.williams at cancer.org.uk Sat Oct 8 12:27:38 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Sat, 08 Oct 2005 11:27:38 +0100 Subject: [Tutor] Tutor Digest, Vol 20, Issue 26: New Python Book In-Reply-To: References: Message-ID: <1128767257.2850.4.camel@localhost.localdomain> IMHO, as regards the book using wxPython, rather than Tkinter: I've failed to get Tkinter to compile on several installs, whereas I can usually get wxPython to work. Also, wx seems to be better documented.....I know it's not ideal to pick one platform, but I would guess that wx would be a reasonable default. Matt From samrobertsmith at gmail.com Sat Oct 8 13:40:08 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 8 Oct 2005 04:40:08 -0700 Subject: [Tutor] is there any Python code for spatial tessellation? Message-ID: <1d987df30510080440n28576b4cxd0394dfefa68e63c@mail.gmail.com> is there any Python code for spatial tessellation? thanks a lot! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051008/98df0e22/attachment.html From kent37 at tds.net Sat Oct 8 13:55:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 08 Oct 2005 07:55:15 -0400 Subject: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help] In-Reply-To: <20051008033940.88140.qmail@web31803.mail.mud.yahoo.com> References: <20051008033940.88140.qmail@web31803.mail.mud.yahoo.com> Message-ID: <4347B3A3.3040706@tds.net> Michael Cotherman wrote: > The c code seems to be walking through the list moving > bytes from src to dst, but the python code below seems > to take one byte from src, start counitng up to the > value from 1 and appending each and every value along > the way to dst, no? Ah, right you are. You are commenting on Alan's code and I am replying thinking you are commenting on my code. Doh! Sorry about that! Alan was just trying to sketch out the Python equivalent to the C code and his translation has a bug - the line dst.append(i) should be dst.append(src[i]) But...I posted complete, working code that duplicates your results. Did you see it? Does it work for you? In my code instead of the loop to copy the fragment from src to dst I just copy the complete chunk in one go: dst.append(src[current+1:current+count]) I'll repeat my original reply below in case you lost it. Kent Michael Cotherman wrote: > I am a noob to converting pointers in C++ to arrays in > python, although the first time I see it done, I will > have no problem. Can you help converting the below > (what I think is the 'decoder' section) to python? OK I'll bite. Your code is copying from a src buffer to a dst buffer. The src buffer has a count byte followed by count-1 bytes of data. If the count is less that 0xFF, a zero byte has to be inserted into the dst. So the decode loop gets a count, copies that many bytes to the dst buffer, then optionally appends a 0. Python doesn't have a direct equivalent to this sort of manipulation of memory pointers and raw memory buffers. They are commonly replaced by strings or lists. My function takes a string as an input argument, builds the output as string fragments in a list, then builds a string to return. Note that Python strings include an implicit length so there is no need to pass and return a length argument. I included a test case with the data from your previous email. Your data is evidently hex-encoded as well as COBS encoded - in other words your strings are hex values where each two chars represent a single byte. I have converted to and from byte strings to feed this to the decoder. Kent def unstuff(src): # src is a COBS compressed string current = 0 # index into src dst = [] # a list that will build the result while current < len(src): # Get the count and convert it to an integer count = ord(src[current]) # Append count-1 chars from src to dst dst.append(src[current+1:current+count]) # Do we need to add a zero byte? if count < 0xFF: dst.append('\x00') # Bump the counter and continue if count>0: current += count else: current += 1 # dst is a list of string fragments; this converts it to a single string return ''.join(dst) def hexToString(hexStr): ''' Convert a string of two-digit hex values to a string of bytes with those values ''' return ''.join([chr(int(hexStr[i:i+2], 16)) for i in range(0, len(hexStr), 2)]) def stringToHex(src): ''' Convert a byte string to a string of two-digit hex values ''' return ''.join([ '%02x' % ord(s) for s in src ]) if __name__ == '__main__': data = '0002860104DB203F0100' print data data = hexToString(data) print newData = unstuff(data) print stringToHex(newData) > > -mike > > > --- Alan Gauld wrote: > > >>>I am a noob to converting pointers in C++ to >> >>arrays in >> >>>python, although the first time I see it done, I >> >>will >> >>>have no problem. Can you help converting the below >>>(what I think is the 'decoder' section) to python? >> >>It won't be working code but I think this is whats >>happening... >> >> >>>UINT CCobsPackets::UnStuffData(unsigned char *src, >>>unsigned char *dst, UINT length) >> >>def UnStuffData(src,dst,len): >> >> >>>{ >>>unsigned char *dstStart = dst; >>>unsigned char *end = src + length; >> >># I don't think these are needed for Pyhon. >> >> >>>while (src < end) >> >>for code in src: >> >> >>>{ >>>int code = *src++; >>>for (int i=1; i>>{ >>>*dst++ = *src++; >>>} >> >> for i in range(1,code): >> dst.append(i) >> >> >>>if (code < 0xFF) >>>{ >>>*dst++ = 0; >>>} >> >> if code < 0xff >> dst.append('\0') # may not be needed in >>python... >> >> >>>} >>>return (UINT)(dst - dstStart); >>>} > > > > > > > __________________________________ > Yahoo! Mail - PC Magazine Editors' Choice 2005 > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sat Oct 8 14:08:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 08 Oct 2005 08:08:14 -0400 Subject: [Tutor] subclass problem: __names and type-checking In-Reply-To: <43476D85.2050806@cc.umanitoba.ca> References: <43476D85.2050806@cc.umanitoba.ca> Message-ID: <4347B6AE.9040408@tds.net> Brian van den Broek wrote: > I have a class which I want to subclass. The subclass adds some > additional arguments to __init__. I want both classes to run a sanity > check on their arguments before leaving their respective __init__ > methods. I need both to do so, as the _BaseClass may be directly > instantiated. I need to ask permission for the arguments on instance > creation rather than for forgiveness later, as bad arguments passed to > __init__ could take many cpu cycles of other code before they > manifested themselves. > > Here's a sketch of where I'm at: > > class _BaseClass(object): > > def __init__(self, arg1, arg2): > self.arg1 = arg1 > self.arg2 = arg2 > if type(self) == _BaseClass: > # Problem (2) mentioned below shows up here. > # > # type test needed otherwise Subclass._validate_args > # will be called before all subclass args processed by > # SubClass.__init__, causing AttriuteError > self._validate_args() > > def _validate_args(self): > '''Performs sanity check on arguments''' > if not type(self.arg1) in (int, long): > raise TypeError > # etc > > class SubClass(_BaseClass): > > def __init__(self, arg1, arg2, arg3, arg4): > super(SubClass, self).__init__(arg1, arg2) > self.arg3 = arg3 > self.arg4 = arg4 > if type(self) == SubClass: > # same reasoning as before -- leaving room for further > # subclassing. > self._validate_args() > > def _validate_args(self): > super(SubClass, self)._validate_args() > if not isinstance(self.arg3, basestring): > raise TypeError > # etc > > > This works as desired, but leaves two problems: > > 1) I suspect there may be a better way, as a) this doesn't feel quite > right and b) in general with Python, it seems that if you are tempted > to type test, you should rethink, and I can think of two alternatives: - If you don't need to call _validate_args() outside of __init__(), just put the code inline in __init__(). Not as clean a class structure but it's a simple solution to the problem. - Have two validate functions in each class - the shared _validate_args() and a class-specific _validate_SubClassArgs(). Call the class-specific version from __init__() and the shared one from other clients. Then you would have class _BaseClass(object): def __init__(self): ... self._validate_BaseClass() def _validate_args(self): super(_BaseClass, self)._validate_args() self._validate_BaseClass() and similar code in SubClass. > > 2) I originally had __BaseClass rather than _BaseClass. But, with that > naming, cannot figure out how to write the line > > if type(self) == __BaseClass: > > so as to make it work. I know about the name mangling with __somename > names, but I don't know how to manage it in this case. > > The attempt of 4 lines up produces: > > NameError: global name '_BaseClass__BaseClass' is not defined > > This confuses me. I don't see why the error msg prepends '_BaseClass' > as that name appears nowhere. That confusion aside, I've no idea how > to effect what I want. The __ name only gets mangled inside the class definition. The class name itself is not getting mangled. From the language reference: Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. Kent > > I think I won't want __BaseClass in the end, as I do expect it is > possible that it will be instantiated directly, so the '__' seems > inappropriate. But, the issue of how to do it remains. > > So, details of '_' vs '__' aside, is my approach sound? And, how to > deal with __BaseClass? > > > Best to all, > > Brian vdB > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From me at scottoertel.info Sat Oct 8 16:02:36 2005 From: me at scottoertel.info (Scott Oertel) Date: Sat, 08 Oct 2005 17:02:36 +0300 Subject: [Tutor] Opening files, finding their location Message-ID: <4347D17C.1050500@scottoertel.info> I have a small problem with one of my scripts currently, I'm using the config parser to open a config.ini file, but this program is going to be designed to be used as a cron job, currently i made a work around.. ./program.py config.ini is how you run it from the command line I'm looking for an easy way to find the current directory location of my program so I can include the config.ini file correctly without having to pass command line args. here is my work around, try: config.readfp(open(argv[1])) except (IndexError, IOError): print "Config.ini file not found." exit() thanks! From amonroe at columbus.rr.com Sat Oct 8 16:40:45 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 8 Oct 2005 10:40:45 -0400 Subject: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work? In-Reply-To: <200510072215.35495.zathras@thwackety.com> References: <200509302251.07797.michaels@rd.bbc.co.uk> <200510070223.33116.zathras@thwackety.com> <151664353784.20051006220443@columbus.rr.com> <200510072215.35495.zathras@thwackety.com> Message-ID: <261796116398.20051008104045@columbus.rr.com> > On Friday 07 October 2005 03:04, R. Alan Monroe wrote: > That's great to hear - not the oversight part but the fact you were talking > about your work. Out of interest, how did you find the tutorial/exercises and > what level of experience would you say you have? Around 2-3 years with Python. But I had never used generators (was aware of them but never had a need) so that was the primary chunk of the learning curve. Alan From matthew.williams at cancer.org.uk Sat Oct 8 16:51:25 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Sat, 08 Oct 2005 15:51:25 +0100 Subject: [Tutor] Listing all of an instances variables Message-ID: <1128783085.2850.87.camel@localhost.localdomain> Dear List, I'm stuck on trying to write a generic 'report' function: Class SomeClass: def __init__(self,a,b): self.a = a self.b = b def report(self): for i in dir(self): print self.i This is where I run into problems: How do I return all of the variables in an instance? I'm sure I'm not the first person to ask, but I couldn't find an answer anywhere else... Thanks, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7384 899570 From chris.arndt at web.de Sat Oct 8 17:19:36 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Sat, 08 Oct 2005 16:19:36 +0100 Subject: [Tutor] Opening files, finding their location In-Reply-To: <4347D17C.1050500@scottoertel.info> References: <4347D17C.1050500@scottoertel.info> Message-ID: <4347E388.9050208@web.de> Scott Oertel schrieb: > I'm looking for an easy way to find the current directory location of my > program so I can include the config.ini file correctly without having to > pass command line args. So, do you want to find out, where your script is living, or the directory from which it was called (the "working directory")? The former can be found out like this: Assuming cron calls your script with the full path name (which should be the case because it uses the shell to execute your script): >>> import os, sys >>> mydir = os.path.dirname(sys.argv[0]) When you want the current working directory: >>> import os >>> mydir = os.getcwd() Then to get the path to your config file, either: config_path = os.path.join(mydir, 'config.ini') HTH, Chris From broek at cc.umanitoba.ca Sat Oct 8 19:08:37 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 08 Oct 2005 12:08:37 -0500 Subject: [Tutor] subclass problem: __names and type-checking In-Reply-To: <4347B6AE.9040408@tds.net> References: <43476D85.2050806@cc.umanitoba.ca> <4347B6AE.9040408@tds.net> Message-ID: <4347FD15.9000703@cc.umanitoba.ca> Kent Johnson said unto the world upon 2005-10-08 07:08: > Brian van den Broek wrote: >> >>Here's a sketch of where I'm at: >>class _BaseClass(object): >> >> def __init__(self, arg1, arg2): >> self.arg1 = arg1 >> self.arg2 = arg2 >> if type(self) == _BaseClass: >> self._validate_args() >> >> def _validate_args(self): >> if not type(self.arg1) in (int, long): >> raise TypeError >> >>class SubClass(_BaseClass): >> >> def __init__(self, arg1, arg2, arg3, arg4): >> super(SubClass, self).__init__(arg1, arg2) >> self.arg3 = arg3 >> self.arg4 = arg4 >> if type(self) == SubClass: >> self._validate_args() >> >> def _validate_args(self): >> super(SubClass, self)._validate_args() >> if not isinstance(self.arg3, basestring): >> raise TypeError >> >> >>This works as desired, but leaves two problems: >> >>1) I suspect there may be a better way, as a) this doesn't feel quite >>right and b) in general with Python, it seems that if you are tempted >>to type test, you should rethink, and Thanks for the reply, Kent. > I can think of two alternatives: > - Have two validate functions in each class - the shared _validate_args() and a class-specific _validate_SubClassArgs(). Call the class-specific version from __init__() and the shared one from other clients. Then you would have > > class _BaseClass(object): > def __init__(self): > ... > self._validate_BaseClass() > > def _validate_args(self): > super(_BaseClass, self)._validate_args() > self._validate_BaseClass() > > and similar code in SubClass. I think I see the idea. But I take it you didn't mean to have: > def _validate_args(self): > super(_BaseClass, self)._validate_args() within a method of _BaseClass (a subclass of object), as that will produce: AttributeError: 'super' object has no attribute '_validate_args' >>2) I originally had __BaseClass rather than _BaseClass. But, with that >>naming, cannot figure out how to write the line >> >> if type(self) == __BaseClass: >> >>so as to make it work. I know about the name mangling with __somename >>names, but I don't know how to manage it in this case. >> >>The attempt of 4 lines up produces: >> >>NameError: global name '_BaseClass__BaseClass' is not defined >> >>This confuses me. I don't see why the error msg prepends '_BaseClass' >>as that name appears nowhere. That confusion aside, I've no idea how >>to effect what I want. > > > The __ name only gets mangled inside the class definition. The > class name itself is not getting mangled. From the language > reference: > > Private name mangling: When an identifier that textually occurs in > a class definition begins with two or more underscore characters > and does not end in two or more underscores, it is considered a > private name of that class. Private names are transformed to a > longer form before code is generated for them. OK, thanks. But I'm still not quite there. Consider this example code: class _OneUnderBase(object): def __init__(self): if type(self) == _OneUnderBase: print "From _OneUnderBase" else: print "From subclass", class __TwoUnderBase(object): def __init__(self): if type(self) == __TwoUnderBase: # What to write here print "From __TwoUnderBase" else: print "From subclass", class Sub1(_OneUnderBase): def __init__(self): super(Sub1, self).__init__() print "Sub1" class Sub2(__TwoUnderBase): def __init__(self): super(Sub2, self).__init__() print "Sub2" s1 = Sub1() s2 = Sub2() When run, this gives: From subclass Sub1 Traceback (most recent call last): File "C:/Python24/foofoofoo.py", line 26, in -toplevel- s2 = Sub2() File "C:/Python24/foofoofoo.py", line 22, in __init__ super(Sub2, self).__init__() File "C:/Python24/foofoofoo.py", line 10, in __init__ if type(self) == __TwoUnderBase: # What to write here NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined >>> What should I write in the if test of __TwoUnderBase.__init__() to make it work? (Nevermind the desired behaviour here could be obtained without the type test. How to work that test is the point I'm interested in.) Thanks, Brian vdB From khp at pflaesterer.de Sat Oct 8 19:13:27 2005 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sat, 08 Oct 2005 19:13:27 +0200 Subject: [Tutor] Listing all of an instances variables In-Reply-To: <1128783085.2850.87.camel@localhost.localdomain> (Matt Williams's message of "Sat, 08 Oct 2005 15:51:25 +0100") References: <1128783085.2850.87.camel@localhost.localdomain> Message-ID: On 8 Okt 2005, matthew.williams at cancer.org.uk wrote: > Class SomeClass: > def __init__(self,a,b): > self.a = a > self.b = b > > def report(self): > for i in dir(self): > print self.i > > > > > This is where I run into problems: How do I return all of the variables > in an instance? You can use the `__dict__' method. >>> class Someclass (object): def __init__(self,a,b): self.a = a self.b = b def report(self): for k, v in self.__dict__.items(): print "Variable %s -> %s" % (k, v) ... ... ... ... ... ... ... >>> >>> c = Someclass(1,2) >>> c.report() Variable a -> 1 Variable b -> 2 >>> c.c = 3 >>> c.report() Variable a -> 1 Variable c -> 3 Variable b -> 2 >>> Karl -- Please do *not* send copies of replies to me. I read the list From python at venix.com Sat Oct 8 19:32:26 2005 From: python at venix.com (Python) Date: Sat, 08 Oct 2005 13:32:26 -0400 Subject: [Tutor] subclass problem: __names and type-checking Message-ID: <1128792746.13446.37.camel@www.venix.com> I think that a sub-class *needs* to support the same programming interface as the parent class. Bertrand Meyer has written about programming by contract and the implications for object oriented design. http://archive.eiffel.com/doc/oosc/ http://se.ethz.ch/~meyer/ If B inherits from A then every context where A or an A instance appears should work correctly with B or a B instance. Since the B constructor *requires* more arguments, it violates that ideal. In other words, it would be OK to allow additional arguments. It is not OK to require them. In other words sub-class should really be a different class that adapts or possibly acts as a proxy for the _BaseClass. Obviously you have picked names that presuppose inheritance. I've abused inheritance in the past in an attempt to reuse code and have usually regretted it. An alternative is to create a new class that "fronts" for the class with the code we want to reuse. The __getattr__ method provides a real simple way to redirect references from our new class to the original class. class Base: def __init__(self, arg1,arg2): ... class Adapt: def __init__(self,arg1,arg2,arg3,arg4): self._base = Base(arg1,arg2) ... # this provides reuse of those Base methods that can be reused directly def __getattr__(self,attrname): return getattr(self._base, attrname) Without knowing more about what you are doing, I could be sending you off in the wrong direction, but hopefully this is relevant. -- Lloyd Kvam Venix Corp From python at venix.com Sat Oct 8 19:40:32 2005 From: python at venix.com (Python) Date: Sat, 08 Oct 2005 13:40:32 -0400 Subject: [Tutor] subclass problem: __names and type-checking In-Reply-To: 4347B6AE.9040408@tds.net Message-ID: <1128793232.13446.44.camel@www.venix.com> Traceback (most recent call last): File "C:/Python24/foofoofoo.py", line 26, in -toplevel- s2 = Sub2() File "C:/Python24/foofoofoo.py", line 22, in __init__ super(Sub2, self).__init__() File "C:/Python24/foofoofoo.py", line 10, in __init__ if type(self) == __TwoUnderBase: # What to write here NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined Within a class, __ prefixes mangle the name to include the class name as part of the name. However, it appears that within a class statement, the __ prefix is not mangled. This is good for you because otherwise the inheritance would not work. However, it appears to make it impossible to directly reference the class name from within the class. You may want to rethink the idea of using __ prefixes in the class name. Normally __ is used to "privatize" attributes within a class. -- Lloyd Kvam Venix Corp From python at venix.com Sat Oct 8 19:59:54 2005 From: python at venix.com (Python) Date: Sat, 08 Oct 2005 13:59:54 -0400 Subject: [Tutor] Listing all of an instances variables Message-ID: <1128794394.13446.47.camel@www.venix.com> def report(self): for i in dir(self): # use the getattr function print getattr(self, i) -- Lloyd Kvam Venix Corp From me at scottoertel.info Sat Oct 8 20:00:04 2005 From: me at scottoertel.info (Scott Oertel) Date: Sat, 08 Oct 2005 21:00:04 +0300 Subject: [Tutor] Opening files, finding their location In-Reply-To: <4347E388.9050208@web.de> References: <4347D17C.1050500@scottoertel.info> <4347E388.9050208@web.de> Message-ID: <43480924.9020709@scottoertel.info> Christopher Arndt wrote: >Scott Oertel schrieb: > > >>I'm looking for an easy way to find the current directory location of my >>program so I can include the config.ini file correctly without having to >>pass command line args. >> >> > >So, do you want to find out, where your script is living, or the directory from >which it was called (the "working directory")? > >The former can be found out like this: > >Assuming cron calls your script with the full path name (which should be the >case because it uses the shell to execute your script): > > > >>>>import os, sys >>>>mydir = os.path.dirname(sys.argv[0]) >>>> >>>> > >When you want the current working directory: > > > >>>>import os >>>>mydir = os.getcwd() >>>> >>>> > >Then to get the path to your config file, either: > >config_path = os.path.join(mydir, 'config.ini') > >HTH, Chris >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > > It was this one: mydir = os.path.dirname(sys.argv[0]) thanks man, it was starting to drive me nuts :) -Scott Oertel -Gawr.com! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051008/42b52908/attachment.htm From lopoff at gmx.net Sat Oct 8 20:27:43 2005 From: lopoff at gmx.net (lmac) Date: Sat, 08 Oct 2005 20:27:43 +0200 Subject: [Tutor] code improvement for beginner ? Message-ID: <43480F9F.3000706@gmx.net> Hi there, i wonder if i could post some of my scripts and anyone can tell me if there is a better way for coding the problem. In the way of some teaching class. ;-) Or is this mailing-list only for specific questions ? Thanks. From dyoo at hkn.eecs.berkeley.edu Sat Oct 8 20:43:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Oct 2005 11:43:23 -0700 (PDT) Subject: [Tutor] code improvement for beginner ? In-Reply-To: <43480F9F.3000706@gmx.net> Message-ID: On Sat, 8 Oct 2005, lmac wrote: > i wonder if i could post some of my scripts and anyone can tell me if > there is a better way for coding the problem. In the way of some > teaching class. ;-) Sure, that's perfectly fine. If the script is very large, you may want to post it on the web and send the mailing list a URL instead. If there's anything in particular that you want us to look at, point it out. From dyoo at hkn.eecs.berkeley.edu Sat Oct 8 20:56:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Oct 2005 11:56:21 -0700 (PDT) Subject: [Tutor] is there any Python code for spatial tessellation? In-Reply-To: <1d987df30510080440n28576b4cxd0394dfefa68e63c@mail.gmail.com> Message-ID: On Sat, 8 Oct 2005, Shi Mu wrote: > is there any Python code for spatial tessellation? Are you looking for code to generate voronoi diagrams? http://en.wikipedia.org/wiki/Voronoi_diagram >From initial Google searches, it appears that there is a package called Qhull that pepole use to do Voronoi tesselations. http://www.qhull.org/ and Chris Myers has written a module around Qhull: http://www.tc.cornell.edu/~myers/PyXL/ Otherwise, I don't think we at Tutor can help you that much; you may want to ask on a more math-oriented forum. Good luck to you! From cpu.crazy at gmail.com Sat Oct 8 21:13:48 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sat, 8 Oct 2005 13:13:48 -0600 Subject: [Tutor] AttributeError: 'str' object has no attribute 'geturl' Message-ID: <66ca60fc0510081213k6b8aa0eewfa35daf9a3b5275@mail.gmail.com> Well, I'm back to coding more on my comic downloader and viewer and I keep getting this error: Traceback (most recent call last): File "F:\Gacor\getgarf.py", line 244, in ? getImg(Data.todayStrip) File "F:\Gacor\getgarf.py", line 127, in getImg Data.f.geturl() AttributeError: 'str' object has no attribute 'geturl' My code is attached (sorry, but it's got lot's of text) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051008/e30b1a8e/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: getgarf.py Type: text/x-python Size: 8474 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051008/e30b1a8e/getgarf-0001.py From javier at ruere.com.ar Sat Oct 8 21:59:24 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sat, 08 Oct 2005 16:59:24 -0300 Subject: [Tutor] AttributeError: 'str' object has no attribute 'geturl' In-Reply-To: <66ca60fc0510081213k6b8aa0eewfa35daf9a3b5275@mail.gmail.com> References: <66ca60fc0510081213k6b8aa0eewfa35daf9a3b5275@mail.gmail.com> Message-ID: Joseph Quigley wrote: > Well, I'm back to coding more on my comic downloader and viewer and I > keep getting this error: > > Traceback (most recent call last): > File "F:\Gacor\getgarf.py", line 244, in ? > getImg(Data.todayStrip) > File "F:\Gacor\getgarf.py", line 127, in getImg > Data.f.geturl() > AttributeError: 'str' object has no attribute 'geturl' > Class Data has a class attribute, 'f', defined as an empty string. Check if Data.f is initialized before calling getImg. Also, why initialize with an empty str? Put a None in there or don't define the attribute at all. A tip: in line 126 there is a print Data.f. This will show nothing in this case. When printing for debugging, error reporting or user input, always place quotes around values so that it is easier to spot empty strings or non printable characters. Finally, keep in mind that you can always use pdb to see what's up. Javier From lopoff at gmx.net Sat Oct 8 22:50:21 2005 From: lopoff at gmx.net (lmac) Date: Sat, 08 Oct 2005 22:50:21 +0200 Subject: [Tutor] code improvement for beginner ? Message-ID: <4348310D.7080602@gmx.net> Ok. Here we go. Wanted to start my page long ago. Now is the right time. http://daderoid.freewebspace24.de/python/python1.html Thank you. From alan.gauld at freenet.co.uk Sat Oct 8 23:46:50 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Oct 2005 22:46:50 +0100 Subject: [Tutor] subclass problem: __names and type-checking References: <1128792746.13446.37.camel@www.venix.com> Message-ID: <002b01c5cc51$ca8f3f90$0a01a8c0@xp> > If B inherits from A then every context where A or an A instance appears > should work correctly with B or a B instance. Since the B constructor > *requires* more arguments, it violates that ideal. In other words, it > would be OK to allow additional arguments. It is not OK to require > them. Which is all true but it should be pointed out that *allowing* them includes such devices as constructor overloading (in Java/C++ etc) or using default values for the additional parameters. The latter is obviously a possible option in Python. > In other words sub-class should really be a different class that adapts > or possibly acts as a proxy for the _BaseClass. Not necessarily, it may just provide alternate construction semantics. > I've abused inheritance in the past in an attempt to reuse code and have > usually regretted it But this is always trure. Inheritance for code reuse is usually a bad idea that comes back to bite you later. Inheritance implies an 'is-a' relationship. If the sub class is not really the same kinde of thing as the superclass then inheritance is probably the wrong solution. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From frank.hoffsummer at gmx.de Sat Oct 8 20:32:05 2005 From: frank.hoffsummer at gmx.de (=?ISO-8859-1?Q?Frank_Hoffs=FCmmer?=) Date: Sat, 8 Oct 2005 20:32:05 +0200 Subject: [Tutor] handling of tabular data Message-ID: <2E24B41B-DBEE-4B5B-8A6F-05CAE57041B6@gmx.de> Hello I often find myself writing python programs to compute averages, min, max, top10 etc of columns in a table of data In these programs, I always capture each row of the table in a tuple the table is then represented by a list of tuples computing averages, min, max and other meta-information is then done with for loops or some list comprehension. now I wonder, whether I shouldn't be using classes instead of lists to capture the table rows with the little I know about classes, I assume that then I would have a list of class instances as representation of my tabular data but given such a list of class instances, i would still need for loops to get to e.g. the minimal value of a certain attribute in all classes in that list. OR? and what would be the benefit of using classes then? what is the best practice, can anyone shed some light on this thanks -frank From ml.cyresse at gmail.com Sun Oct 9 02:47:41 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 9 Oct 2005 13:47:41 +1300 Subject: [Tutor] FW: Is it Posible? To Crack And HowTo In-Reply-To: <43469896.4090203@tds.net> References: <9AA4216B8A36B9429BB00C546DF6D27210879E@schubert.OxbridgeTechnology.local> <1128698867.14474.5.camel@amdbert.oxbridgetechnology.local> <43469896.4090203@tds.net> Message-ID: > > On a good day the fun of creating all those licenses lets me sleep with a smile on my face. On a bad day, I have nightmares about all the hungry children caused by my greed. ;-) Really? I was of the impression that proprietory code developers *ate* small children. Goes to show, can't believe everything you read on Slashdot. From dyoo at hkn.eecs.berkeley.edu Sun Oct 9 06:24:18 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Oct 2005 21:24:18 -0700 (PDT) Subject: [Tutor] handling of tabular data In-Reply-To: <2E24B41B-DBEE-4B5B-8A6F-05CAE57041B6@gmx.de> Message-ID: On Sat, 8 Oct 2005, [ISO-8859-1] Frank Hoffsümmer wrote: > I often find myself writing python programs to compute averages, min, > max, top10 etc of columns in a table of data In these programs, I always > capture each row of the table in a tuple the table is then represented > by a list of tuples computing averages, min, max and other > meta-information is then done with for loops or some list comprehension. Hi Frank, This doesn't quite answer your question in favor of Python, but have you already considered using something like a relational database? It provides support for doing those kind of operations on tabular data. I'm not certain that applying an OOP approach on table-centric data will be too effective for solving the kinds of problems you're doing. However, I have seen that relational databases support operations like extracting min, max, and average information with relative ease. Best of wishes to you! From daniel at thewatkins.org.uk Sun Oct 9 07:07:34 2005 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Sun, 09 Oct 2005 06:07:34 +0100 Subject: [Tutor] FW: FW: Is it Posible? To Crack And HowTo [horribly OT] In-Reply-To: <9AA4216B8A36B9429BB00C546DF6D2721087F0@schubert.OxbridgeTechnology.local> References: <9AA4216B8A36B9429BB00C546DF6D2721087F0@schubert.OxbridgeTechnology.local> Message-ID: <1128834454.17324.7.camel@amdbert.oxbridgetechnology.local> > Really? I was of the impression that proprietory code developers *ate* > small children. Goes to show, can't believe everything you read on > Slashdot. I heard that they write all their programs using the blood of cute-looking puppies (though how that doesn't short-circuit anything I'd like to know (although I can't, because it'll be proprietary))... And, no, I really can't see any way of crow-barring this back on-topic. :P Dan From dyoo at hkn.eecs.berkeley.edu Sun Oct 9 08:00:40 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Oct 2005 23:00:40 -0700 (PDT) Subject: [Tutor] code improvement for beginner ? In-Reply-To: <4348310D.7080602@gmx.net> Message-ID: On Sat, 8 Oct 2005, lmac wrote: > Ok. Here we go. Wanted to start my page long ago. Now is the right time. > > http://daderoid.freewebspace24.de/python/python1.html Hi lmac, I'll pick out some stuff that I see; I'm sure others will be happy to give comments too. I'll try to make sure that all the criticism I give is constructive in nature, and if you have questions on any of it, please feel free to ask about it. I'll concentrate on the imgreg() function first. The declaration of 'images' as a global variable looks a little weird. I do see that 'imgreg' feeds into 'images'. Not a major issue so far, but you might want to see if it's possible to do without the global, and explicitly pass in 'images' as another parameter to imgreg. Globals just bother me on principle. *grin* You may want to document what 'patt' and 'search' are meant to be. A comment at the top of imgreg, like: """imgreg searches for a pattern 'patt' within the text 'search'. If a match exists, adds it to the set of images, and returns 1. Else, returns 0.""" will help a lot. Documenting the intent of a function is important, because people are forgetful. No programming language can prevent memory loss: what we should try to do is to compensate for our forgetfulness. *grin* Looking at pageimgs(): I'm not sure what 't' means in the open statement: f = open(filename, "rt") and I think that 't' might be a typo: I'm surprised that Python doesn't complain. Can anyone confirm this? I think you may have tried to do "r+" mode, but even then, you probably don't: you're just reading from the file, and don't need to write back to it. Looking further into pageimgs(): again, I get nervous about globals. The use of the 'r1' global variable is mysterious. I had to hunt around to figure out what it was it near the middle of the program. If anything, I'd recommend naming your global variables with more meaning. A name like 'image_regex_patterns' will work better than 'r1'. Also, it looks like pageimgs() is hardcoded to assume 'r1' has three regular expressions in it, as it calls imgreg three times for each pattern in r1. if imgreg(r1[0],a) == 1: continue if imgreg(r1[1],a) == 1: continue imgreg(r1[2],a) and that looks peculiar. Because this snippet of code is also copy-and-pasted around line 106, it appears to be a specific kind of conceptual task that you're doing to register images. I think that the use of 'r1' and 'imgreg' should be intrinsically tied. I'd recommend revising imgreg() so that when we register images, we don't have to worry that we've called it on all the regular expressions in r1. That is, let imgreg worry about it, not clients: have imgreg go through r1[0:3] by itself. If we incorporate these changes, the result might look something like this: ################################################### image_regex_patterns = map(re.compile, [r'http://\w+.\w+.\w+/i.+.gif', r'http://\w+.\w+.\w+/i.+.jpg', r'http://\w+.\w+.\w+/i.+.png']) def imgreg(search): """Given a search text, looks for image urls for registration. If a new one can be found, returns 1. Otherwise, returns 0. Possible bug: does not register all images in the search text, but only the first new one it can find. """ for r in image_regex_patterns: z = r.search(search) if z != None: x = z.group(0) if x not in images: images.append(x) return 1 return 0 ################################################### Does this make sense? The point of this restructuring is to allow you to add more image types without too much pain, since there's no more hardcoded array indexing against r1. It also simplifies to calls to imgreg from: if imgreg(r1[0],a) == 1: continue if imgreg(r1[1],a) == 1: continue imgreg(r1[2],a) to the simpler: imgreg(a) I think I'll stop there and look at the program again later. *grin* Hope this helps! From ukc802591034 at btconnect.com Sun Oct 9 01:45:22 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sun, 9 Oct 2005 00:45:22 +0100 Subject: [Tutor] handling of tabular data References: <2E24B41B-DBEE-4B5B-8A6F-05CAE57041B6@gmx.de> Message-ID: > with the little I know about classes, I assume that then I would have > a list of class instances as representation of my tabular data > but given such a list of class instances, i would still need for > loops to get to e.g. the minimal value of a certain attribute in all > classes in that list. OR? OR you could define class level member for the stats and have the constructors update those values at instance creation time. A very simple totaling example: class Number: total = 0 def __init__(self, n): self.value = n Number.total += n def __del__(self): Number.total -= self.value # now create some instances: numbers = [] for n in range(10): numbers.append(Number(n)) print Number.total > and what would be the benefit of using classes then? Actually not that much for this kind of app and personally I rarely use OOP for MIS type functions, SQL is usually more powerful, either direct;ly or mixed with a scripting language like Python. But if the class could be used for other functions within the application - ie MIS was only one aspect - then classes could be a very useful single mechanism to crack both problems in one go. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rschroev_nospam_ml at fastmail.fm Sun Oct 9 11:01:21 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 09 Oct 2005 11:01:21 +0200 Subject: [Tutor] code improvement for beginner ? In-Reply-To: References: <4348310D.7080602@gmx.net> Message-ID: Danny Yoo wrote: > Looking at pageimgs(): I'm not sure what 't' means in the open statement: > > f = open(filename, "rt") > > and I think that 't' might be a typo: I'm surprised that Python doesn't > complain. Can anyone confirm this? I think you may have tried to do "r+" > mode, but even then, you probably don't: you're just reading from the > file, and don't need to write back to it. It's not a typo. 't' opens the file in text mode. It doesn't make any difference on Unix, but it does on Windows. As you might know, lines in text file end with '\r\n' in Windows rather than only '\n'. If you open a file in text mode, the line endings are translated to '\n' on input and back to '\r\n' on output. One can also specify 'b' instead to open the file in binary mode instead, which will not do any translation. I'm not sure which one of the two is the default. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From ajikoe at gmail.com Sun Oct 9 11:16:18 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Sun, 9 Oct 2005 11:16:18 +0200 Subject: [Tutor] handling of tabular data In-Reply-To: <2E24B41B-DBEE-4B5B-8A6F-05CAE57041B6@gmx.de> References: <2E24B41B-DBEE-4B5B-8A6F-05CAE57041B6@gmx.de> Message-ID: Hi Frank, you can use Numeric.py it is also powerfull to handle averages, min, max, matrix algebra, etc.. see: http://www.pfdubois.com/numpy/ You just need to use a list. If your data is big and you need more power I suggest you use database like mysqldb for python. It is also fun to combine database and python all together. Cheers, pujo On 10/8/05, Frank Hoffs?mmer wrote: > > Hello > I often find myself writing python programs to compute averages, min, > max, top10 etc of columns in a table of data > In these programs, I always capture each row of the table in a tuple > the table is then represented by a list of tuples > computing averages, min, max and other meta-information is then done > with for loops or some list comprehension. > > now I wonder, whether I shouldn't be using classes instead of lists > to capture the table rows > with the little I know about classes, I assume that then I would have > a list of class instances as representation of my tabular data > but given such a list of class instances, i would still need for > loops to get to e.g. the minimal value of a certain attribute in all > classes in that list. OR? > and what would be the benefit of using classes then? > > what is the best practice, can anyone shed some light on this > thanks > -frank > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051009/f2330875/attachment.html From cpu.crazy at gmail.com Sun Oct 9 16:54:54 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 09 Oct 2005 08:54:54 -0600 Subject: [Tutor] AttributeError: 'str' object has no attribute 'geturl' In-Reply-To: References: Message-ID: <43492F3E.9060100@gmail.com> Javier wrote: > Class Data has a class attribute, 'f', defined as an empty string. Check if Data.f is initialized before calling getImg. > Also, why initialize with an empty str? Put a None in there or don't define the attribute at all. > A tip: in line 126 there is a print Data.f. This will show nothing in this case. When printing for debugging, error reporting or user input, always place quotes around values so that it is easier to spot empty strings or non printable characters. > Finally, keep in mind that you can always use pdb to see what's up. > >Javier > > Thanks, I'll try to clean up what had gotten past me. From cpu.crazy at gmail.com Sun Oct 9 17:23:24 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 09 Oct 2005 09:23:24 -0600 Subject: [Tutor] AttributeError: 'str' object has no attribute 'geturl' Message-ID: <434935EC.8020806@gmail.com> Ok, new version (sorry to bug you). This time I've edited the program so that you can only download todays (it won't work for any other date). Now I can connect to the server but it sticks on "Downloading image!" Thanks for your prevoius help. Joe -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: getgarf.py Url: http://mail.python.org/pipermail/tutor/attachments/20051009/0b997d98/getgarf.asc From daniel at thewatkins.org.uk Sun Oct 9 18:27:20 2005 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Sun, 09 Oct 2005 17:27:20 +0100 Subject: [Tutor] Code Inspection Message-ID: <1128875240.23968.3.camel@amdbert.oxbridgetechnology.local> Hey list, I've been working on my spider program (albeit not very much :P) and I would appreciate it if I could get some comments on the code. I'm fairly sure I haven't chosen the best method to do what I want to do, but if we can just assume that I have, that'll make things easier. ;) In particular, comments on the "Things to do" list at the end would be much appreciated. The file is attached. Cheers, Dan -------------- next part -------------- A non-text attachment was scrubbed... Name: spider.py Type: text/x-python Size: 3294 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051009/8ac6e904/spider.py From broek at cc.umanitoba.ca Sun Oct 9 23:09:05 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 09 Oct 2005 16:09:05 -0500 Subject: [Tutor] subclass problem: __names and type-checking In-Reply-To: <1128792746.13446.37.camel@www.venix.com> References: <1128792746.13446.37.camel@www.venix.com> Message-ID: <434986F1.8070806@cc.umanitoba.ca> Python said unto the world upon 2005-10-08 12:32: Thanks for the response, Llyod. (And to Alan, too.) > I think that a sub-class *needs* to support the same programming > interface as the parent class. > If B inherits from A then every context where A or an A instance appears > should work correctly with B or a B instance. Since the B constructor > *requires* more arguments, it violates that ideal. In other words, it > would be OK to allow additional arguments. It is not OK to require > them. The code I posted was an abstracted example. What I actually have is a base class with 2 arguments with default values and the subclass having those 2 (different defaults) and two more, again with defaults. So, unless I misunderstand, what I have meets the ideal here. > In other words sub-class should really be a different class that adapts > or possibly acts as a proxy for the _BaseClass. Obviously you have > picked names that presuppose inheritance. > > I've abused inheritance in the past in an attempt to reuse code and have > usually regretted it. My actual context is a pretty central case of inheritance, I think. I'm making a Counter class will all sorts of bells and whistles that I've found myself deploying in other programs. Counter inherits from a sparse _Basic_Counter class. _Basic_Counter gives the common minimal interface I want, while not including the CPU-cycle consuming bells added in the subclass Counter. I'm doing things like this because usually the cpu-cycles for the bells won't matter. But, with _Basic_Counter, for the cases where I do want something more efficient, the basic interface will remain the same. So, I believe that your good advice was already being headed. Thanks, though! Brian vdB From broek at cc.umanitoba.ca Mon Oct 10 01:24:44 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 09 Oct 2005 18:24:44 -0500 Subject: [Tutor] subclass problem: __names and type-checking In-Reply-To: <1128793232.13446.44.camel@www.venix.com> References: <1128793232.13446.44.camel@www.venix.com> Message-ID: <4349A6BC.1090708@cc.umanitoba.ca> Python said unto the world upon 2005-10-08 12:40: > Traceback (most recent call last): > File "C:/Python24/foofoofoo.py", line 26, in -toplevel- > s2 = Sub2() > File "C:/Python24/foofoofoo.py", line 22, in __init__ > super(Sub2, self).__init__() > File "C:/Python24/foofoofoo.py", line 10, in __init__ > if type(self) == __TwoUnderBase: # What to write here > NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined > > Within a class, __ prefixes mangle the name to include the class name as > part of the name. However, it appears that within a class statement, > the __ prefix is not mangled. This is good for you because otherwise > the inheritance would not work. However, it appears to make it > impossible to directly reference the class name from within the class. > You may want to rethink the idea of using __ prefixes in the class name. > Normally __ is used to "privatize" attributes within a class. Hi all, I did give up the use of __ names in the case at hand. But I just posted a question about how to reference a __ class name from with the class on comp.lang.python. I used the code up-thread here. The F-bot suggested: class __TwoUnderBase(object): def __init__(self): if self.__class__.__name__ == "__TwoUnderBase": print "From __TwoUnderBase" else: print "From subclass", which does the trick. Thought I'd post it here in case of future googling. Best to all, Brian From billburns at pennswoods.net Mon Oct 10 06:10:58 2005 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 10 Oct 2005 00:10:58 -0400 Subject: [Tutor] Regex help Message-ID: <4349E9D2.10407@pennswoods.net> I'm looking to get the size (width, length) of a PDF file. Every pdf file has a 'tag' (in the file) that looks similar to this Example #1 MediaBox [0 0 612 792] or this Example #2 MediaBox [ 0 0 612 792 ] I figured a regex might be a good way to get this data but the whitespace (or no whitespace) after the left bracket has me stumped. If I do this pattern = re.compile('MediaBox \[\d+ \d+ \d+ \d+') I can find the MediaBox in Example #1 but I have to do this pattern = re.compile('MediaBox \[ \d+ \d+ \d+ \d+') to find it for Example #2. How can I make *one* regex that will match both cases? Thanks for the help, Bill From samrobertsmith at gmail.com Mon Oct 10 07:22:29 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 9 Oct 2005 22:22:29 -0700 Subject: [Tutor] is there any Python code for spatial tessellation? In-Reply-To: References: <1d987df30510080440n28576b4cxd0394dfefa68e63c@mail.gmail.com> Message-ID: <1d987df30510092222y15003158r71412ba6a272f8e@mail.gmail.com> There are four points with coordinates: 2,3;4,9;1,6;3,10. How to use Python to draw one perpendicular bisector between (2,3) and (4,9); the other perpendicular bisector between (1,6)?(3,10); then, makes the output like: l1 a b c l2 a b c (Note: l indicates the perpendicular bisector with equation ax + by = c.) Plus the intersection coordinates of the two perpendicular bisectors: x,y On 10/8/05, Danny Yoo wrote: > > > On Sat, 8 Oct 2005, Shi Mu wrote: > > > is there any Python code for spatial tessellation? > > Are you looking for code to generate voronoi diagrams? > > http://en.wikipedia.org/wiki/Voronoi_diagram > > From initial Google searches, it appears that there is a package called > Qhull that pepole use to do Voronoi tesselations. > > http://www.qhull.org/ > > and Chris Myers has written a module around Qhull: > > http://www.tc.cornell.edu/~myers/PyXL/ > > > Otherwise, I don't think we at Tutor can help you that much; you may want > to ask on a more math-oriented forum. Good luck to you! > > > From samrobertsmith at gmail.com Mon Oct 10 07:24:51 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 9 Oct 2005 22:24:51 -0700 Subject: [Tutor] line question Message-ID: <1d987df30510092224i506ebe65uf2f82285746a1a36@mail.gmail.com> There are four points with coordinates: 2,3;4,9;1,6;3,10. How to use Python to draw one perpendicular bisector between (2,3) and (4,9); the other perpendicular bisector between (1,6)?(3,10); then, makes the output like: l1 a b c l2 a b c (Note: l indicates the perpendicular bisector with equation ax + by = c.) Plus the intersection coordinates of the two perpendicular bisectors: x,y From bgailer at alum.rpi.edu Mon Oct 10 08:23:52 2005 From: bgailer at alum.rpi.edu (bob) Date: Sun, 09 Oct 2005 23:23:52 -0700 Subject: [Tutor] Regex help In-Reply-To: <4349E9D2.10407@pennswoods.net> References: <4349E9D2.10407@pennswoods.net> Message-ID: <6.1.2.0.0.20051009231617.0352ace0@mail.mric.net> At 09:10 PM 10/9/2005, Bill Burns wrote: >I'm looking to get the size (width, length) of a PDF file. Every pdf >file has a 'tag' (in the file) that looks similar to this > >Example #1 >MediaBox [0 0 612 792] > >or this > >Example #2 >MediaBox [ 0 0 612 792 ] > >I figured a regex might be a good way to get this data but the >whitespace (or no whitespace) after the left bracket has me stumped. > >If I do this > >pattern = re.compile('MediaBox \[\d+ \d+ \d+ \d+') > >I can find the MediaBox in Example #1 but I have to do this > >pattern = re.compile('MediaBox \[ \d+ \d+ \d+ \d+') > >to find it for Example #2. > >How can I make *one* regex that will match both cases? pattern = re.compile('MediaBox \[ *\d+ \d+ \d+ \d+') From grouch at gmail.com Mon Oct 10 08:26:33 2005 From: grouch at gmail.com (Andrew P) Date: Mon, 10 Oct 2005 01:26:33 -0500 Subject: [Tutor] Regex help In-Reply-To: <4349E9D2.10407@pennswoods.net> References: <4349E9D2.10407@pennswoods.net> Message-ID: If the format is consistent enough, you might get away with something like: >>> p = re.compile('MediaBox \[ ?\d+ \d+ (\d+) (\d+) ?\]') >>> print p.search(s).groups() ('612', '792') The important bits being: ? means "0 or 1 occurences", and you can use parentheses to group matches, and they get put into the tuple returned by the .groups() function. So you can match and extract what you want in one go. http://www.amk.ca/python/howto/regex/ is a fairly gentle introduction to regular expressions in Python if you want to learn more. Having said all that, usually you would use a library of some sort to access header information, although I'm not sure what Python has for PDF support, and if that's -all- the information you need, and the -only- variation you'll see, regex probably won't be too bad :) On 10/9/05, Bill Burns wrote: > > I'm looking to get the size (width, length) of a PDF file. Every pdf > file has a 'tag' (in the file) that looks similar to this > > Example #1 > MediaBox [0 0 612 792] > > or this > > Example #2 > MediaBox [ 0 0 612 792 ] > > I figured a regex might be a good way to get this data but the > whitespace (or no whitespace) after the left bracket has me stumped. > > If I do this > > pattern = re.compile('MediaBox \[\d+ \d+ \d+ \d+') > > I can find the MediaBox in Example #1 but I have to do this > > pattern = re.compile('MediaBox \[ \d+ \d+ \d+ \d+') > > to find it for Example #2. > > How can I make *one* regex that will match both cases? > > Thanks for the help, > > Bill > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051010/f6ed08aa/attachment.htm From janos.juhasz at VELUX.com Mon Oct 10 09:30:19 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 10 Oct 2005 09:30:19 +0200 Subject: [Tutor] is there any Python code for spatial tessellation? In-Reply-To: Message-ID: Dear Danny, take a look to http://public.kitware.com/VTK/ I have seen visualization for voronoi and delaunay in that package. I have seen also good programming samples mainly in C for calculating perpedincular and so on at: http://www.graphicsgems.org/ I know it is about 10 years old, but very usable for this topic. VTK was very good and easy, ( when I downloaded the correct binaries :) ) Yours sincerely, ______________________________ J?nos Juh?sz > Message: 7 > Date: Sun, 9 Oct 2005 22:22:29 -0700 > From: Shi Mu > Subject: Re: [Tutor] is there any Python code for spatial > tessellation? > To: Danny Yoo > Cc: Tutor > Message-ID: > <1d987df30510092222y15003158r71412ba6a272f8e at mail.gmail.com> > Content-Type: text/plain; charset=ISO-2022-JP > There are four points with coordinates: > 2,3;4,9;1,6;3,10. > How to use Python to draw one perpendicular bisector between (2,3) and (4,9); > the other perpendicular bisector between (1,6)?(3,10); > then, makes the output like: > l1 a b c > l2 a b c > (Note: l indicates the perpendicular bisector with equation ax + by = c.) > Plus the intersection coordinates of the two perpendicular bisectors: > x,y > > On 10/8/05, Danny Yoo wrote: > > > > > > On Sat, 8 Oct 2005, Shi Mu wrote: > > > > > is there any Python code for spatial tessellation? > > > > Are you looking for code to generate voronoi diagrams? > > > > http://en.wikipedia.org/wiki/Voronoi_diagram > > > > From initial Google searches, it appears that there is a package called > > Qhull that pepole use to do Voronoi tesselations. > > > > http://www.qhull.org/ > > > > and Chris Myers has written a module around Qhull: > > > > http://www.tc.cornell.edu/~myers/PyXL/ > > > > > > Otherwise, I don't think we at Tutor can help you that much; you may want > > to ask on a more math-oriented forum. Good luck to you! > > > > > > From duncan at thermal.esa.int Mon Oct 10 10:41:58 2005 From: duncan at thermal.esa.int (Duncan Gibson) Date: Mon, 10 Oct 2005 10:41:58 +0200 Subject: [Tutor] is there any Python code for spatial tessellation? In-Reply-To: References: Message-ID: <20051010104158.73f4a0f3.duncan@thermal.esa.int> This is off-topic for Python: I've seen this on the FLTK mailing list, but you might find some of the links under this page useful: http://myweb.tiscali.co.uk/oaktree/nshea/tesselsphere/tesselsphere_index.html "OpenGL spherical subdivision utility. Currently employs particle and geodesic modules. GUI morphers can split Delaunay and Voronoi hulls to create new cells in the lattice. Additionally, morphers can target individual cells to split or stellate. Can be used to generate vertices for geodesic spheres, pollen, radiolaria, viruses and other polyhedra. Saves VRML 1.0 and POV-Ray inc file." Disclaimer: This isn't my field of expertise. I haven't used this software. Don't ask me any questions about it. From billburns at pennswoods.net Mon Oct 10 12:42:33 2005 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 10 Oct 2005 06:42:33 -0400 Subject: [Tutor] Regex help In-Reply-To: <6.1.2.0.0.20051009231617.0352ace0@mail.mric.net> References: <4349E9D2.10407@pennswoods.net> <6.1.2.0.0.20051009231617.0352ace0@mail.mric.net> Message-ID: <434A4599.2050907@pennswoods.net> >> I'm looking to get the size (width, length) of a PDF file. Every pdf >> file has a 'tag' (in the file) that looks similar to this >> >> Example #1 >> MediaBox [0 0 612 792] >> >> or this >> >> Example #2 >> MediaBox [ 0 0 612 792 ] >> >> I figured a regex might be a good way to get this data but the >> whitespace (or no whitespace) after the left bracket has me stumped. >> >> If I do this >> >> pattern = re.compile('MediaBox \[\d+ \d+ \d+ \d+') >> >> I can find the MediaBox in Example #1 but I have to do this >> >> pattern = re.compile('MediaBox \[ \d+ \d+ \d+ \d+') >> >> to find it for Example #2. >> >> How can I make *one* regex that will match both cases? > > > pattern = re.compile('MediaBox \[ *\d+ \d+ \d+ \d+') Bob, Thanks that works perfectly! Bill From alan.gauld at freenet.co.uk Mon Oct 10 12:46:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 10 Oct 2005 11:46:21 +0100 Subject: [Tutor] line question References: <1d987df30510092224i506ebe65uf2f82285746a1a36@mail.gmail.com> Message-ID: <00db01c5cd87$db2b3c50$0a01a8c0@xp> Hi, Can you describe how you would solve the problem without Python first of all? Just so we understand what you want to do and how much is a Python problem and how much a basic understanding issue. Often once you think through how to do it without Python the programming becomes easier. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "Shi Mu" To: Sent: Monday, October 10, 2005 6:24 AM Subject: [Tutor] line question > There are four points with coordinates: > 2,3;4,9;1,6;3,10. > How to use Python to draw one perpendicular bisector between (2,3) and > (4,9); > the other perpendicular bisector between (1,6)?(3,10); > then, makes the output like: > l1 a b c > l2 a b c > (Note: l indicates the perpendicular bisector with equation ax + by = c.) > Plus the intersection coordinates of the two perpendicular bisectors: > x,y > > From billburns at pennswoods.net Mon Oct 10 13:02:00 2005 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 10 Oct 2005 07:02:00 -0400 Subject: [Tutor] Regex help In-Reply-To: References: <4349E9D2.10407@pennswoods.net> Message-ID: <434A4A28.90005@pennswoods.net> [Andrew] > If the format is consistent enough, you might get away with something like: > > >>> p = re.compile('MediaBox \[ ?\d+ \d+ (\d+) (\d+) ?\]') > >>> print p.search(s).groups() > ('612', '792') > > The important bits being: ? means "0 or 1 occurences", and you can use > parentheses to group matches, and they get put into the tuple returned > by the .groups() function. So you can match and extract what you want in > one go. > > http://www.amk.ca/python/howto/regex/ is a fairly gentle introduction to > regular expressions in Python if you want to learn more. > > Having said all that, usually you would use a library of some sort to > access header information, although I'm not sure what Python has for PDF > support, and if that's -all- the information you need, and the -only- > variation you'll see, regex probably won't be too bad :) > Thanks, Andrew! Yes, the format is consistent (I believe the whitespace I mentioned is the only difference you may find). I'll take a look at your use of group matches tonight, looks like a really easy way to return the two numbers I need. Yeah, I was hoping to find a python PDF library that could do this, but things seem a little sparse in this area. The only info I need is the PDF size and it's consistently located (and tagged) in the MediaBox so I figured it was a good way to get the data. Bill From calvinkrishy at gmail.com Mon Oct 10 14:28:09 2005 From: calvinkrishy at gmail.com (Krishna) Date: Mon, 10 Oct 2005 17:58:09 +0530 Subject: [Tutor] and-or precedence Message-ID: >>> 1 or 2 and 3 1 Why does the above expression return 1? As per my understanding of boolean operations, this is what should have happaned: 1 or 2 => 1 and then 1 and 3 => 3 The library reference also suggests that 'or' has higher priority than 'and'. http://docs.python.org/lib/boolean.html Thanks From paul1brian at gmail.com Mon Oct 10 14:58:33 2005 From: paul1brian at gmail.com (paul brian) Date: Mon, 10 Oct 2005 13:58:33 +0100 Subject: [Tutor] and-or precedence In-Reply-To: References: Message-ID: has a higher priority than (as shown on the page you referenced -its "ascending priority"). Perhaps that could be clearer. I find that brackets always make life easier in these cases (a rare statement in the Python world :-), and on a personal note I would always always comment heavily boolean operations that are not immediately obvious. it saves brain ache later on. >>> ((1 or 2) and 3) 3 However 1 or 2 and 3 is <1> if is evaluated first. cheers On 10/10/05, Krishna wrote: > >>> 1 or 2 and 3 > 1 > > Why does the above expression return 1? As per my understanding of > boolean operations, this is what should have happaned: > > 1 or 2 => 1 and then > 1 and 3 => 3 > > The library reference also suggests that 'or' has higher priority than 'and'. > http://docs.python.org/lib/boolean.html > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From raduzator at volny.cz Mon Oct 10 15:27:53 2005 From: raduzator at volny.cz (Raduz) Date: Mon, 10 Oct 2005 15:27:53 +0200 Subject: [Tutor] Stopping function after given time Message-ID: <200510101527.53670.raduzator@volny.cz> Hi all Simple question: Is it possible to stop a running function after certain predefined time? Right now I have some home-made bash scripts for recording shows from net broadcasted ogg stream, that use wget for stream downloading, and two "at" jobs - one for first script (which prepares directory it's going to save to, dumps info about it's own PID, and execs wget for actual download), second for another script (which reads PID info dumped by the first script, uses it to kill wget and performs some clean-up tasks). I would like to convert this routine to Python using pycurl module, or maybe even standard urllib.urlretrieve. Problem is, downloaded file is a stream without end, so I have to stop the downloader manually, and I would prefer to drop the "two scripts" approach - no more PID saving and process killing. I want one clean package, which will start the download, let it run for some time, and then stop it correctly. I just don't know how to time the download. Can anybody give some sugestions, please? Is the threading way to go? Thanks. -- Raduz From daniel at thewatkins.org.uk Mon Oct 10 16:43:49 2005 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Mon, 10 Oct 2005 15:43:49 +0100 Subject: [Tutor] line question In-Reply-To: <9AA4216B8A36B9429BB00C546DF6D272108807@schubert.OxbridgeTechnology.local> References: <9AA4216B8A36B9429BB00C546DF6D272108807@schubert.OxbridgeTechnology.local> Message-ID: <1128955429.15296.9.camel@amdbert.oxbridgetechnology.local> > There are four points with coordinates: > 2,3;4,9;1,6;3,10. > How to use Python to draw one perpendicular bisector between (2,3) and > (4,9); > the other perpendicular bisector between (1,6)?(3,10); > then, makes the output like: > l1 a b c > l2 a b c > (Note: l indicates the perpendicular bisector with equation ax + by = > c.) > Plus the intersection coordinates of the two perpendicular bisectors: > x,y What code do you have thus far? Dan From johan at accesstel.co.za Mon Oct 10 16:45:44 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon, 10 Oct 2005 16:45:44 +0200 Subject: [Tutor] Stopping function after given time In-Reply-To: <200510101527.53670.raduzator@volny.cz> References: <200510101527.53670.raduzator@volny.cz> Message-ID: <434A7E98.1060101@accesstel.co.za> You can use the Timer in threading. Look at what is done in the attached script. You can basically use three functions to start the timer, stop the timer and do what ever it is to be done upon expiring. There maybe easier ways, but this will work. You can call the start_timer with a time in seconds and then it will terminate and there you can call a different function that does the rest of your stuff. Johan. Raduz wrote: >Hi all >Simple question: Is it possible to stop a running function after certain >predefined time? > >Right now I have some home-made bash scripts for recording shows from net >broadcasted ogg stream, that use wget for stream downloading, and two "at" >jobs - one for first script (which prepares directory it's going to save to, >dumps info about it's own PID, and execs wget for actual download), second for >another script (which reads PID info dumped by the first script, uses it to >kill wget and performs some clean-up tasks). >I would like to convert this routine to Python using pycurl module, or maybe >even standard urllib.urlretrieve. Problem is, downloaded file is a stream >without end, so I have to stop the downloader manually, and I would prefer to >drop the "two scripts" approach - no more PID saving and process killing. I >want one clean package, which will start the download, let it run for some >time, and then stop it correctly. I just don't know how to time the download. >Can anybody give some sugestions, please? Is the threading way to go? Thanks. > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: timertest.py Type: text/x-python Size: 3206 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051010/6114888a/timertest.py From zamb at saudi.net.sa Mon Oct 10 17:35:24 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Mon, 10 Oct 2005 18:35:24 +0300 Subject: [Tutor] and-or precedence In-Reply-To: References: Message-ID: <1128958524.7261.27.camel@localhost.localdomain> On Mon, 2005-10-10 at 17:58 +0530, Krishna wrote: > >>> 1 or 2 and 3 > 1 > > Why does the above expression return 1? As per my understanding of > boolean operations, this is what should have happaned: > > 1 or 2 => 1 and then > 1 and 3 => 3 > > The library reference also suggests that 'or' has higher priority than 'and'. > http://docs.python.org/lib/boolean.html > > Thanks This is called "lazy evaluation"? and is used in a lot in computer world. Here's how it work (I'll use your example with Python): What Python sees is this: "1 or (2 and 3)" (because of the "Left to Right" evaluation rule). Now, Python evaluate that first step: 1 or (something else). What's the outcome of that evaluation? Remember, Python tries hard so that the output is True. "1" in this case is True. For that reason Python doesn't have an obligation to continue as it got what it wants, a True. No matter what the outcome of "2 and 3" is, the result is always True. So, it stops right there (yes, it doesn't even evaluate "2 and 3" at all!). To illustrate: >>> 0 or 2 and 3 3 Applying what I said above: 0 or (something else) is not guaranteed to be True since 0 is False and there's a possibility (or "hope") that "something else" will evaluate to True, and that's the reason Python will continue to evaluate "2 and 3" which will give us "3". The same thing applies when using "and" instead of "or": >>> 1 and 2 or 3 2 "1 and 2" is always "2" which is True. Python stops right there. >>> 0 and 2 or 3 3 In this example, what Python sees is (0 and 2) or (3). "0 and 2" is "0" which is False, but since there's hope because of the "or", Python continues to evaluate the rest. (It will be like: "0 or 3" I'm very bad at explaining and to tip-it-off, English isn't my native language, but I hope it was clear enough and it was helpful for you. Ziyad. References: 1. http://en.wikipedia.org/wiki/Lazy_evaluation From cpu.crazy at gmail.com Mon Oct 10 19:36:22 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 10 Oct 2005 11:36:22 -0600 Subject: [Tutor] New image with Tkinter? Message-ID: <66ca60fc0510101036j285f20b3u97b239f9023061d0@mail.gmail.com> Hi, I've written an image reader that uses the PIL module. I have a variable that uses os.listdir('mydir') to make a list of all the pictures in the folder... here's what I'm talking about: pics = os.listdir(imgDir) pics.remove('license.txt') pics.remove('gacor.py') class Data: pic = 0 print "There are %s saved images in the image folder." % len(pics) def newPic(): Data.pic += 1 def quitProg(): raise SystemExit def Dsp_Image(): root = Tk() root.title("GaCoR Image Browser") app = Frame(root) app.grid() img = Image.open('%s%s' % (imgDir, pics[Data.pic])) imgPrep = ImageTk.PhotoImage(img) imgShow = Label(app, image=imgPrep).grid() info = Label(app, text="Displaying %s" % pics[Data.pic]).grid() next = Button(app, text="Next Image", command=newPic).grid() close = Button(app, text="Close", command=quitProg).grid() print Data.pic app.mainloop() Dsp_Image() The image won't refresh when I click on 'Next'! Any help would be appreciated. Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051010/d7ce931e/attachment.htm From mail at olivermaunder.co.uk Mon Oct 10 20:10:56 2005 From: mail at olivermaunder.co.uk (Oliver Maunder) Date: Mon, 10 Oct 2005 19:10:56 +0100 Subject: [Tutor] Stopping function after given time In-Reply-To: <434A7E98.1060101@accesstel.co.za> References: <200510101527.53670.raduzator@volny.cz> <434A7E98.1060101@accesstel.co.za> Message-ID: > > >Simple question: Is it possible to stop a running function after certain > >predefined time? > > > >I would like to convert this routine to Python using pycurl module, or > maybe > >even standard urllib.urlretrieve. If you use urllib.urlretrieve, you can pass in a callback function that gets called after every few blocks are downloaded. In that function, you could check how much time has passed since the download started, and quit the download if necessary. You should be able to do this without threads. I'm not sure how you stop a download once it's started though! Olly -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051010/40eb4637/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Oct 10 21:11:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Oct 2005 12:11:56 -0700 (PDT) Subject: [Tutor] is there any Python code for spatial tessellation? In-Reply-To: <1d987df30510092222y15003158r71412ba6a272f8e@mail.gmail.com> Message-ID: On Sun, 9 Oct 2005, Shi Mu wrote: > There are four points with coordinates: > 2,3;4,9;1,6;3,10. > How to use Python to draw one perpendicular bisector between (2,3) and (4,9); > the other perpendicular bisector between (1,6)$BOB(B(3,10); > then, makes the output like: > l1 a b c > l2 a b c > (Note: l indicates the perpendicular bisector with equation ax + by = c.) > Plus the intersection coordinates of the two perpendicular bisectors: > x,y Hi Shi Mu, I am having a hard time understanding the relationship between your first slightly scary question --- spatial tesselation --- with the second, much more basic question --- perpendicular bisectors. I'm not getting any good sense of what you know. And the core of your question has nothing to do with Python: it's more an elementary algebra/geometry homework assignment. Frankly speaking, for the kind of geometry questions you've asked so far, I believe you should already know how do that. You haven't said anything about what you've tried, or what difficulties you're running into. As far as I can tell, you haven't put in any effort into anything except for repeating a problem statement. See: http://www.catb.org/~esr/faqs/smart-questions.html#homework We're not going to do your homework. Show us what you're really having trouble with, and if it's programming related, we will try to help point things out. But other than that, you really have to do your own work. From lopoff at gmx.net Mon Oct 10 21:50:37 2005 From: lopoff at gmx.net (lmac) Date: Mon, 10 Oct 2005 21:50:37 +0200 Subject: [Tutor] code improvement for beginner ? In-Reply-To: References: Message-ID: <434AC60D.1050209@gmx.net> Danny Yoo wrote: > > On Sat, 8 Oct 2005, lmac wrote: > > >>Ok. Here we go. Wanted to start my page long ago. Now is the right time. >> >>http://daderoid.freewebspace24.de/python/python1.html > > > Hi lmac, > > I'll pick out some stuff that I see; I'm sure others will be happy to give > comments too. I'll try to make sure that all the criticism I give is > constructive in nature, and if you have questions on any of it, please > feel free to ask about it. > > > I'll concentrate on the imgreg() function first. The declaration of > 'images' as a global variable looks a little weird. I do see that > 'imgreg' feeds into 'images'. Not a major issue so far, but you might > want to see if it's possible to do without the global, and explicitly pass > in 'images' as another parameter to imgreg. Globals just bother me on > principle. *grin* > The thing is i want to download the images after i got the pages. So i thought i use an global var that it is in scope at the end of the script. > > You may want to document what 'patt' and 'search' are meant to be. A > comment at the top of imgreg, like: > > """imgreg searches for a pattern 'patt' within the text 'search'. If > a match exists, adds it to the set of images, and returns 1. Else, > returns 0.""" > > will help a lot. Documenting the intent of a function is important, > because people are forgetful. No programming language can prevent memory > loss: what we should try to do is to compensate for our forgetfulness. > *grin* > > > Looking at pageimgs(): I'm not sure what 't' means in the open statement: > > f = open(filename, "rt") > > and I think that 't' might be a typo: I'm surprised that Python doesn't > complain. Can anyone confirm this? I think you may have tried to do "r+" > mode, but even then, you probably don't: you're just reading from the > file, and don't need to write back to it. > > > Looking further into pageimgs(): again, I get nervous about globals. The > use of the 'r1' global variable is mysterious. I had to hunt around to > figure out what it was it near the middle of the program. > > If anything, I'd recommend naming your global variables with more meaning. > A name like 'image_regex_patterns' will work better than 'r1'. Also, it > looks like pageimgs() is hardcoded to assume 'r1' has three regular > expressions in it, as it calls imgreg three times for each pattern in r1. > > if imgreg(r1[0],a) == 1: > continue > if imgreg(r1[1],a) == 1: > continue > imgreg(r1[2],a) > > and that looks peculiar. Because this snippet of code is also > copy-and-pasted around line 106, it appears to be a specific kind of > conceptual task that you're doing to register images. > > I think that the use of 'r1' and 'imgreg' should be intrinsically tied. > I'd recommend revising imgreg() so that when we register images, we don't > have to worry that we've called it on all the regular expressions in r1. > That is, let imgreg worry about it, not clients: have imgreg go through > r1[0:3] by itself. > > > If we incorporate these changes, the result might look something like > this: > > ################################################### > image_regex_patterns = map(re.compile, > [r'http://\w+.\w+.\w+/i.+.gif', > r'http://\w+.\w+.\w+/i.+.jpg', > r'http://\w+.\w+.\w+/i.+.png']) This one is very good. I stumbled sometimes over map() but didn't know how to use it. This makes it easier. > def imgreg(search): > """Given a search text, looks for image urls for registration. If > a new one can be found, returns 1. Otherwise, returns 0. > > Possible bug: does not register all images in the search text, but only > the first new one it can find. > """ > for r in image_regex_patterns: > z = r.search(search) > if z != None: > x = z.group(0) > if x not in images: > images.append(x) > return 1 > return 0 > ################################################### The purpose for storing the images in an global list was to download all images after the pages were saved and don't download an image again if it was already saved and downloaded on disk. So with this list i have an good overview. > > Does this make sense? > Yes. Thats good. > The point of this restructuring is to allow you to add more image types > without too much pain, since there's no more hardcoded array indexing > against r1. It also simplifies to calls to imgreg from: > > if imgreg(r1[0],a) == 1: > continue > if imgreg(r1[1],a) == 1: > continue > imgreg(r1[2],a) > > to the simpler: > > imgreg(a) > > > I think I'll stop there and look at the program again later. *grin* Hope > this helps! > > I made some significant changes ;-) http://daderoid.freewebspace24.de/python/python1.html#version2 --------------- The problem with downloading the images is this: ------------- http://images.nfl.com/images/globalnav-shadow-gray.gif Traceback (most recent call last): File "/home/internet/bin/nflgrab.py", line 167, in ? urllib.urlretrieve(img,img[f:]) File "/usr/lib/python2.3/urllib.py", line 83, in urlretrieve return _urlopener.retrieve(url, filename, reporthook, data) File "/usr/lib/python2.3/urllib.py", line 216, in retrieve tfp = open(filename, 'wb') IOError: [Errno 13] Permission denied: '/globalnav-shadow-gray.gif' ------------- Is there any solution to know if i can download the image ? Thanks. From rdm at rcblue.com Mon Oct 10 21:53:23 2005 From: rdm at rcblue.com (Dick Moores) Date: Mon, 10 Oct 2005 12:53:23 -0700 Subject: [Tutor] Please look at my wordFrequency.py Message-ID: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Script is at: Example text file for input: (142 kb) (from ) Example output in file: (40 kb) (Execution took about 30 sec. with my computer.) I worked on this a LONG time for something I expected to just be an easy and possibly useful exercise. Three times I started completely over with a new approach. Had a lot of trouble removing exactly the characters I didn't want to appear in the output. Wished I knew how to debug other than just by using a lot of print statements. Specifically, I'm hoping for comments on or help with: 1) How to debug. I'm using v2.4, IDLE on Win XP. 2) I've tried to put in remarks that will help most anyone to understand what the code is doing. Have I succeeded? 3) No modularization. Couldn't see a reason to do so. Is there one or two? Specifically, what sections should become modules, if any? 4) Variable names. I gave up on making them self-explanatory. Instead, I put in some remarks near the top of the script (lines 6-10) that I hope do the job. Do they? In the code, does the "L to newL to L to newL to L" kind of thing remain puzzling? (lines 6-10) # meaning of short variable names: # S is a string # c is a character of a string # L, F are lists # e is an element of a list 5) Ideally, abbreviations that end in a period, such as U.N., e.g., i.e., viz. op. cit., Mr. (Am. E.), etc., should not be stripped of their final periods (whereas other words that end a sentence SHOULD be stripped). I tried making and using a Python list of these, but it was too tough to write the code to use it. Any ideas? (I can live very easily without a solution to point 5, because if the output shows there are 10 "e.g"s, I'll just assume, and I think safely, that there actually are 10 "e.g."s. But I am curious, Pythonically.) Thanks very much in advance, tutors. Dick Moores rdm at rcblue.com From kent37 at tds.net Mon Oct 10 22:01:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Oct 2005 16:01:54 -0400 Subject: [Tutor] Listing all of an instances variables In-Reply-To: <1128783085.2850.87.camel@localhost.localdomain> References: <1128783085.2850.87.camel@localhost.localdomain> Message-ID: <434AC8B2.2070705@tds.net> Matt Williams wrote: > Dear List, > > I'm stuck on trying to write a generic 'report' function: > > Class SomeClass: > def __init__(self,a,b): > self.a = a > self.b = b > > def report(self): > for i in dir(self): > print self.i > > > > > This is where I run into problems: How do I return all of the variables > in an instance? If you are trying to show the data attributes of an instance then Karl's suggestion of self.__dict__.items() is probably the best. dir() attempts to show all accessible attributes, which may be instance variables, class methods, class attributes, etc. For example: >>> class F(object): ... def __init__(self): ... self.data = 1 ... def show(self): ... print 'data =', self.data ... >>> f=F() >>> dir(f) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__' , '__repr__', '__setattr__', '__str__', '__weakref__', 'data', 'show'] >>> f.__dict__ {'data': 1} In this case f.__dict__ is probably what you want, not dir(f). However it's easy to make an example where __dict__ doesn't contain all accessible attributes, for example in a class that defines __slots__: >>> class G(object): ... __slots__ = ['data'] ... def __init__(self): ... self.data = 1 ... >>> g=G() >>> g.__dict__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'G' object has no attribute '__dict__' >>> dir(g) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__' , '__setattr__', '__slots__', '__str__', 'data'] >>> g.__slots__ ['data'] >>> A class that defines __getattr__ or __getattribute__ could have attributes that don't appear in dir(), __dict__ or __slots__. So in general I think what you want is hard. For common cases __dict__ will work. Kent From dyoo at hkn.eecs.berkeley.edu Mon Oct 10 22:19:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Oct 2005 13:19:21 -0700 (PDT) Subject: [Tutor] handling of tabular data In-Reply-To: <3AB38F69-4552-4BDF-BD9D-928DBB12E2C8@gmx.de> Message-ID: On Sun, 9 Oct 2005, [ISO-8859-1] Frank Hoffsümmer wrote: > thanks for your answers looks like SQL is the ticket for such > problems... because my data is updated quite often, it feels like an > overhead for me to store the data persistently, because then I would > have to manage updates to individual rows and columns right now, I > simply construct the latest version of my data table from my source > data, whenever the script is run this is also the reason why I am using > python in the first place: to extract the data of interest from other > (non-SQL) sources and then create that data table as the basis for my > queries. does python have a simple build in SQL engine that would allow > for the creation of a throw-away, in-memory table that I could then > query with SQL? Hi Frank, Try looking at: http://www.sqlite.org/ It should be fairly easy to install, and comes with Python bindings: http://initd.org/tracker/pysqlite The tutorial shows how to build an in-memory database (Example 2 of Chapter 2): http://initd.org/pub/software/pysqlite/doc/usage-guide.html Best of wishes! From klappnase at freenet.de Mon Oct 10 22:27:47 2005 From: klappnase at freenet.de (Michael Lange) Date: Mon, 10 Oct 2005 22:27:47 +0200 Subject: [Tutor] New image with Tkinter? In-Reply-To: <66ca60fc0510101036j285f20b3u97b239f9023061d0@mail.gmail.com> References: <66ca60fc0510101036j285f20b3u97b239f9023061d0@mail.gmail.com> Message-ID: <20051010222747.46a416ec.klappnase@freenet.de> On Mon, 10 Oct 2005 11:36:22 -0600 Joseph Quigley wrote: > Hi, > I've written an image reader that uses the PIL module. > I have a variable that uses os.listdir('mydir') to make a list of all the > pictures in the folder... here's what I'm talking about: (...) > The image won't refresh when I click on 'Next'! Any help would be > appreciated. > Joe > Hi Joe, the image won't refresh until you explicitely tell Tk to do so, so you would have to do some more in newPic(); btw, it looks overly complicated to me to use a "Data" class where a simple variable will do the trick, so I would suggest to change the code like this: pics = os.listdir(imgDir) pics.remove('license.txt') pics.remove('gacor.py') print "There are %s saved images in the image folder." % len(pics) pic = 0 root = Tk() root.title("GaCoR Image Browser") app = Frame(root) app.grid() imgPrep = ImageTk.PhotoImage(file=os.path.join(imgDir, pics[pic])) imgShow = Label(app, image=imgPrep).grid() info = Label(app, text="Displaying %s" % pics[Data.pic]) info.grid() def newPic(): global pic pic = pic + 1 imgPrep.configure(file=os.path.join(imgDir, pics[pic])) Button(app, text="Next Image", command=newPic).grid() Button(app, text="Close", command=quitProg).grid() app.mainloop() I hope this helps Michael From alan.gauld at freenet.co.uk Mon Oct 10 23:22:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 10 Oct 2005 22:22:54 +0100 Subject: [Tutor] New image with Tkinter? References: <66ca60fc0510101036j285f20b3u97b239f9023061d0@mail.gmail.com> Message-ID: <011e01c5cde0$c7428140$0a01a8c0@xp> def newPic(): Data.pic += 1 def Dsp_Image(): ...... imgPrep = ImageTk.PhotoImage(img) imgShow = Label(app, image=imgPrep).grid() ... next = Button(app, text="Next Image", command=newPic).grid() app.mainloop() Dsp_Image() > The image won't refresh when I click on 'Next'! > Any help would be appreciated. You never ask it to refresh. The GUI displays the image that you pass to it, you then call newPic which only increments the data counter but does nothing to change the image being displayed. You need to make your Photoimage object visible to newPic (by making it global say?) and then in newPic acyually update the image being displayed. visible BTW you seem to be callingmainloop within the DSpImage function, thats probably a bad idea, mainloop should only be called once which means you could never call DspImage a second time should you ever need to... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Oct 10 23:25:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Oct 2005 17:25:23 -0400 Subject: [Tutor] code improvement for beginner ? In-Reply-To: References: <4348310D.7080602@gmx.net> Message-ID: <434ADC43.7040600@tds.net> Roel Schroeven wrote: > Danny Yoo wrote: > >>Looking at pageimgs(): I'm not sure what 't' means in the open statement: >> >> f = open(filename, "rt") > > It's not a typo. 't' opens the file in text mode. Are you sure? Is that documented anywhere? Text mode is the default, you have to specify the 'b' if you want binary mode. And open() seems to accept any mode quite happily: >>> f=open('build.xml', 'rt') >>> f >>> f.close() >>> f=open('build.xml', 'rabcd') >>> f Kent From alan.gauld at freenet.co.uk Mon Oct 10 23:33:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 10 Oct 2005 22:33:53 +0100 Subject: [Tutor] Please look at my wordFrequency.py References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Message-ID: <012601c5cde2$50b417d0$0a01a8c0@xp> > didn't want to appear in the output. Wished I knew how to debug other than > just by using a lot of print statements. When you need to get to the nitty gritty you need to use a realdebugger. The best GUI one is probably the one in Pythonwin. The standard one is PDB and the tutorial on it is OK. I find the most useful approach is to set a breakpoint on the function I'm interested in (or a control point within that - a loop or significant branch say) then set a watch point on any variables I'm interested in. Then step through the function remembering that 'step' will step into any functions called by the function under test and 'next' will step over the called functions, ie: def foo(): x = aFunction() x = another() return x to step through foo will require 3 'next's but could involve dozens of 'steps' depending on how long 'aFunction' and 'another' are... > 1) How to debug. I'm using v2.4, IDLE on Win XP. IDLE's debugger isn't pretty but it does work, try it. Use the context menus and mouse to set a break point, then just step through using the step and next buttons. IDLE debugger displays the variable values as you go... If you can't get it to work you know where to ask for help :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld > 2) I've tried to put in remarks that will help most anyone to understand > what the code is doing. Have I succeeded? > 3) No modularization. Couldn't see a reason to do so. Is there one or two? > Specifically, what sections should become modules, if any? > 4) Variable names. I gave up on making them self-explanatory. Instead, I > put in some remarks near the top of the script (lines 6-10) that I hope do > the job. Do they? In the code, does the "L to newL to L to newL to L" kind > of thing remain puzzling? > > (lines 6-10) > # meaning of short variable names: > # S is a string > # c is a character of a string > # L, F are lists > # e is an element of a list > > 5) Ideally, abbreviations that end in a period, such as U.N., e.g., i.e., > viz. op. cit., Mr. (Am. E.), etc., should not be stripped of their final > periods (whereas other words that end a sentence SHOULD be stripped). I > tried making and using a Python list of these, but it was too tough to > write the code to use it. Any ideas? (I can live very easily without a > solution to point 5, because if the output shows there are 10 "e.g"s, I'll > just assume, and I think safely, that there actually are 10 "e.g."s. But I > am curious, Pythonically.) > > Thanks very much in advance, tutors. > > Dick Moores > rdm at rcblue.com > > > > > From dyoo at hkn.eecs.berkeley.edu Mon Oct 10 23:38:55 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Oct 2005 14:38:55 -0700 (PDT) Subject: [Tutor] Undocumented 't' mode flag for open() [Was: Re: code improvement for beginner ?] In-Reply-To: Message-ID: On Sun, 9 Oct 2005, Roel Schroeven wrote: > Danny Yoo wrote: > > Looking at pageimgs(): I'm not sure what 't' means in the open statement: > > > > f = open(filename, "rt") > > > > and I think that 't' might be a typo: I'm surprised that Python doesn't > > complain. Can anyone confirm this? I think you may have tried to do "r+" > > mode, but even then, you probably don't: you're just reading from the > > file, and don't need to write back to it. > > It's not a typo. 't' opens the file in text mode. It doesn't make any > difference on Unix, but it does on Windows. Hi Roel, Ah, ok, thank you! Even so, I don't see this 't' option documented in the reference docs though, although now I see a reference to this on: http://mail.python.org/pipermail/python-list/2004-September/241444.html This is odd that it's not documented in the reference manual. >From the thread on python-list, it sounded like they left it at depending on the user to know that 't' is a Windows-specific thing. But that just feels off to me: Python's open(), I think, should at least generalize it so that 't' is explicitely defined in the documentation. ... Wow. open() actually does seem like a VERY thin wrapper around the underlying platforms fopen(). For example, on my Linux 2.6 system: ###### >>> open("/etc/passwd", "rfoobar!") ###### So if the underlying fopen() is permissive, we don't see errors. But I really think Python should be more strict than the platform. I'll put it on my TODO to check to see if this is registered as a bug in SF. From alan.gauld at freenet.co.uk Mon Oct 10 23:41:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 10 Oct 2005 22:41:22 +0100 Subject: [Tutor] handling of tabular data References: Message-ID: <013701c5cde3$5bc0a7f0$0a01a8c0@xp> > overhead for me to store the data persistently, because then I would > have to manage updates to individual rows and columns right now, I > simply construct the latest version of my data table from my source > data, whenever the script is run this is also the reason why I am using > python in the first place: to extract the data of interest from other > (non-SQL) sources and then create that data table as the basis for my > queries. does python have a simple build in SQL engine that would allow > for the creation of a throw-away, in-memory table that I could then > query with SQL? You could look at the database topic in my tutor which both gives an intro to SQL and how to use it from Python with the sqlite database. It really is pretty easy once you adjust to the SQL mindset. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From amonroe at columbus.rr.com Mon Oct 10 23:40:07 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 10 Oct 2005 17:40:07 -0400 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <012601c5cde2$50b417d0$0a01a8c0@xp> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> <012601c5cde2$50b417d0$0a01a8c0@xp> Message-ID: <581994078533.20051010174007@columbus.rr.com> > IDLE's debugger isn't pretty but it does work, try it. > Use the context menus and mouse to set a break point, > then just step through using the step and next buttons. Has anyone else experienced this? I tried debugging in IDLE with the source checkbox enabled, but when the sourcecode window lost focus as I clicked back on the debugger window to hit the step button, the highlight indicating the current line of source was no longer visible. It's probably a fluke of Windows XP's GUI theme system, but I was curious if anyone else had seen it. Alan From dyoo at hkn.eecs.berkeley.edu Mon Oct 10 23:46:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Oct 2005 14:46:21 -0700 (PDT) Subject: [Tutor] Regex help In-Reply-To: <4349E9D2.10407@pennswoods.net> Message-ID: On Mon, 10 Oct 2005, Bill Burns wrote: > I'm looking to get the size (width, length) of a PDF file. Hi Bill, Just as a side note: you may want to look into using the 'pdfinfo' utility that comes as part of the xpdf package: http://www.foolabs.com/xpdf/ For example: ####################################################################### [dyoo at shoebox ~]$ pdfinfo 05-lexparse.pdf Producer: Acrobat Distiller Command 3.0 for Solaris 2.3 and later (SPARC) CreationDate: Tue Jul 1 18:36:35 1913 Tagged: no Pages: 12 Encrypted: no Page size: 612 x 792 pts (letter) File size: 191874 bytes Optimized: no PDF version: 1.2 ####################################################################### > Every pdf file has a 'tag' (in the file) that looks similar to this > > Example #1 > MediaBox [0 0 612 792] > > or this > > Example #2 > MediaBox [ 0 0 612 792 ] > > I figured a regex might be a good way to get this data but the > whitespace (or no whitespace) after the left bracket has me stumped. I think you might want to look for the whitespace metacharacter '\s'. Also, you can consider using '*' to qualify a previous pattern: it stands for "zero or more of the pattern." For example: ##################################### >>> re.search("a*b", "aab") <_sre.SRE_Match object at 0x403ae250> >>> re.search("a*b", "ab") <_sre.SRE_Match object at 0x403ae138> >>> re.search("a*b", "b") <_sre.SRE_Match object at 0x403ae250> >>> re.search("a*b", "") >>> ##################################### In comparison: ##################################### >>> re.search("a+b", "aab") <_sre.SRE_Match object at 0x403ae138> >>> re.search("a+b", "ab") <_sre.SRE_Match object at 0x403ae250> >>> re.search("a+b", "b") >>> ##################################### Good luck to you! From john at fouhy.net Mon Oct 10 23:47:57 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 11 Oct 2005 10:47:57 +1300 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Message-ID: <5e58f2e40510101447n4da4484cw@mail.gmail.com> On 11/10/05, Dick Moores wrote: > I worked on this a LONG time for something I expected to just be an easy > and possibly useful exercise. Three times I started completely over with > a new approach. Had a lot of trouble removing exactly the characters I > didn't want to appear in the output. Wished I knew how to debug other > than just by using a lot of print statements. I like pdb to debug, but I don't know how that works with IDLE.. (I don't use IDLE) Some comments: ---- textAsString = input.read() S = "" for c in textAsString: if c == "\n": S += ' ' else: S += c ---- You could write this more concisely as: S = textAsString.replace('\n', ' ') ---- # At this point, each element ("word" in code below) of L is # a string containing a real word such as "dog", # where "dog" may be prefixed and/or suffixed by strings of # non-alphanumeric characters. So, for example, word could be "'dog?!". # The following code first strips these prefixed or suffixed non-alphanumeric # characters and then finds any words with dashes ("--") or forward slashes ("/"), # such as in "and/or". These then become 2 or more words without the # dashes or slashes. ---- What about using regular expressions? re.sub('\W+', ' ') will replace all non-alphanumeric characters with a single ' '. By the looks of things, the only difference is that if you had something like 'foo.bar' or 'foo&bar', your code would leave that as one word, whereas using the regex would convert it into two words. If you want to keep the meaning of your code intact, you could still use a regex to do it. Something like (untested) re.sub('\b\W+|\W+\b|-+|/+', ' ') might work. ---- # Remove all empty elements of L, if any while "" in L: L.remove("") for e in saveRemovedForLaterL: L.append(e) F = [] for word in L: k = L.count(word) if (k,word) not in F: F.append((k,word)) ---- There are a lot of hidden loops in here: 1. '' in L This will look at every element of L, until it finds "" or it gets to the end. 2. L.count(word) This will also look at every element of L. If you combine your loops into one, you should be able to save a lot of time. eg: for e in saveRemovedForLaterL: L.append(e) counts = {} for word in L: if not word: # This skips empty words. continue try: counts[word] += 1 except KeyError: counts[word] = 1 F = [(count, word) for word, count in counts.iteritems()] -- John. From alan.gauld at freenet.co.uk Tue Oct 11 00:08:33 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 10 Oct 2005 23:08:33 +0100 Subject: [Tutor] Please look at my wordFrequency.py References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com><012601c5cde2$50b417d0$0a01a8c0@xp> <581994078533.20051010174007@columbus.rr.com> Message-ID: <015601c5cde7$27fabb50$0a01a8c0@xp> > Has anyone else experienced this? I tried debugging in IDLE with the > source checkbox enabled, but when the sourcecode window lost focus as > I clicked back on the debugger window to hit the step button, the > highlight indicating the current line of source was no longer visible. > It's probably a fluke of Windows XP's GUI theme system, but I was > curious if anyone else had seen it. Yes I get that too, I just watch the current source line being displayed in the debugger window. But frankly IDLEs debugger sucks! I prefer to use text mode pdb for most things!! Which is a pretty bad inditement... Alan g From kent37 at tds.net Tue Oct 11 00:25:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Oct 2005 18:25:03 -0400 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Message-ID: <434AEA3F.4040304@tds.net> Dick Moores wrote: > Specifically, I'm hoping for comments on or help with: > 1) How to debug. I'm using v2.4, IDLE on Win XP. I have been using winpdb recently, it is a pretty decent standalone Python debugger for Windows. Start it with the -t switch so you don't need the Python Cryptographic Toolkit. http://www.digitalpeers.com/pythondebugger/ Kent From dyoo at hkn.eecs.berkeley.edu Tue Oct 11 00:47:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Oct 2005 15:47:09 -0700 (PDT) Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Message-ID: > 3) No modularization. Couldn't see a reason to do so. Is there one or > two? Specifically, what sections should become modules, if any? Hi Dick, My recommendation is to practice using and writing functions. For example, this block here is a good candidate to box off as a named function: ####### F = [] for word in L: k = L.count(word) if (k,word) not in F: F.append((k,word)) # F is a list of duples (k, word), where k is the frequency of word F.sort() ####### That block can be treated as a function that takes in a list of words, and returns a list of duples. ###### def doFrequencyCalculation(L): # F is a list of duples (k, word), where k is the frequency of word F = [] for word in L: k = L.count(word) if (k,word) not in F: F.append((k,word)) F.sort() return F ###### Here, we explicitly say that frequence calculation depends on having a list L of words, and that the result should be a list of duples. Functions allow us to "scope" variables into different kinds of roles. We'd say in doFrequenceCalculation that 'word' and 'k' are "temporary" variables. If we write programs using functions, we can express that "temporary" role as a real part of the program. As it stands, in the original code, we have to watch that 'word' or 'k' isn't being used by anyone else: like all the other variables in your program, they're all global and given equal status. You're using lowercase as an informal way to remind yourself that those variables are meant to be temporary, but that approach can be error prone. Conceptually, your program appears to work in four stages: 1. Read lines of a file 2. Extract list of words from the lines 3. Do histogram frequency count on those lines 4. Report frequency results and it would be great if we could see this program flow as an explicit sequence of function calls: ################################## ## Pseudocode def program(): L = readLinesInFile() W = extractWordsFromLines(L) F = doFrequencyCalculation(W) reportFrequencyResults(F) ################################## This allows one to see the overall program plan without having to read the whole program. It also allows you to do some experimentation later on by letting you plugging in different functions in the overall program() plan. As a concrete example: once we have a program in this form, it's easy to swap in a different algorithm for doing frequency calculation: ###### def program(): L = readLinesInFile() W = extractWordsFromLines(L) ## F = doFrequencyCalculation(W) F = doFrequencyCalculationWithDifferentAlgorithm(W) reportFrequencyResults(F) ###### Does this make sense? Please feel free to ask more questions about this. From cpu.crazy at gmail.com Tue Oct 11 01:07:47 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 10 Oct 2005 17:07:47 -0600 Subject: [Tutor] Tutor Digest, Vol 20, Issue 37 In-Reply-To: References: Message-ID: <434AF443.2000409@gmail.com> Michael Wrote: >Hi Joe, > >the image won't refresh until you explicitely tell Tk to do so, so you would have to do some more >in newPic(); btw, it looks overly complicated to me to use a "Data" class where a simple variable >will do the trick, so I would suggest to change the code like this: > >pics = os.listdir(imgDir) >pics.remove('license.txt') >pics.remove('gacor.py') >print "There are %s saved images in the image folder." % len(pics) >pic = 0 > >root = Tk() >root.title("GaCoR Image Browser") >app = Frame(root) >app.grid() > >imgPrep = ImageTk.PhotoImage(file=os.path.join(imgDir, pics[pic])) >imgShow = Label(app, image=imgPrep).grid() >info = Label(app, text="Displaying %s" % pics[Data.pic]) >info.grid() > >def newPic(): > global pic > pic = pic + 1 > imgPrep.configure(file=os.path.join(imgDir, pics[pic])) > >Button(app, text="Next Image", command=newPic).grid() >Button(app, text="Close", command=quitProg).grid() >app.mainloop() > >I hope this helps > >Michael > > > > Hi, Unfortunately I get this error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "Programming/Gacor/tmp.py", line 83, in newPic imgPrep.configure(file=os.path.join(imgDir, pics[pic])) AttributeError: PhotoImage instance has no attribute 'configure' I think I should mention that I'm completely in the dark when it comes to GUI programming (and I don't have much time to learn it... or do I?) Thanks for the help so far, Joe From john at fouhy.net Tue Oct 11 01:15:05 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 11 Oct 2005 12:15:05 +1300 Subject: [Tutor] Tutor Digest, Vol 20, Issue 37 In-Reply-To: <434AF443.2000409@gmail.com> References: <434AF443.2000409@gmail.com> Message-ID: <5e58f2e40510101615o1aec072dw@mail.gmail.com> On 11/10/05, Joseph Quigley wrote: > I think I should mention that I'm completely in the dark when it comes > to GUI programming (and I don't have much time to learn it... or do I?) You're likely to have more success with your programming if you do learn what you're doing :-) I recommend Thinking in Tkinter: http://www.ferg.org/thinking_in_tkinter/ -- John. From dyoo at hkn.eecs.berkeley.edu Tue Oct 11 01:41:18 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Oct 2005 16:41:18 -0700 (PDT) Subject: [Tutor] code improvement for beginner ? In-Reply-To: <434AC60D.1050209@gmx.net> Message-ID: > > The point of this restructuring is to allow you to add more image > > types without too much pain, since there's no more hardcoded array > > indexing against r1. It also simplifies to calls to imgreg from: > > > > if imgreg(r1[0],a) == 1: > > continue > > if imgreg(r1[1],a) == 1: > > continue > > imgreg(r1[2],a) > > > > to the simpler: > > > > imgreg(a) > > Yes. Thats good. Check your code: pageimgs() is calling imgreg three times. > The problem with downloading the images is this: > > ------------- > http://images.nfl.com/images/globalnav-shadow-gray.gif > Traceback (most recent call last): > File "/home/internet/bin/nflgrab.py", line 167, in ? > urllib.urlretrieve(img,img[f:]) > File "/usr/lib/python2.3/urllib.py", line 83, in urlretrieve > return _urlopener.retrieve(url, filename, reporthook, data) > File "/usr/lib/python2.3/urllib.py", line 216, in retrieve > tfp = open(filename, 'wb') > IOError: [Errno 13] Permission denied: '/globalnav-shadow-gray.gif' One bug is that Python is trying to write those image files to the root directory. Your operating system's file system is saying that it won't allow you to write files to that location. urllib.urlretrieve saves those files with the path given in the second parameter: urllib.urlretrieve(img, img[f:]) ^^^^^^^ You may want to change this so that it stores those files in a particular directory. Something like: urllib.urlretrieve(img, os.path.join("/tmp", img[f+1:])) may work better. The main idea is that you should explicitly control where the files are being downloaded to. Another bug: you will probably still run into problems because 'img' must be a URL, and each 'img' is instead a line that contains a URL. The difference is between having a string like: http://python.org. and: This line contains a url to the python web site: http://python.org. and images, as far as I can tell, is storing a list of the lines, not the image urls. So you may want to make appropriate changes to imgreg() so that it maintains a list of image urls. From billburns at pennswoods.net Tue Oct 11 06:11:05 2005 From: billburns at pennswoods.net (Bill Burns) Date: Tue, 11 Oct 2005 00:11:05 -0400 Subject: [Tutor] Regex help In-Reply-To: References: Message-ID: <434B3B59.2010108@pennswoods.net> > On Mon, 10 Oct 2005, Bill Burns wrote: > > >>I'm looking to get the size (width, length) of a PDF file. > > Hi Bill, > > Just as a side note: you may want to look into using the 'pdfinfo' utility > that comes as part of the xpdf package: > > http://www.foolabs.com/xpdf/ > > For example: > > ####################################################################### > [dyoo at shoebox ~]$ pdfinfo 05-lexparse.pdf > Producer: Acrobat Distiller Command 3.0 for Solaris 2.3 and later > (SPARC) > CreationDate: Tue Jul 1 18:36:35 1913 > Tagged: no > Pages: 12 > Encrypted: no > Page size: 612 x 792 pts (letter) > File size: 191874 bytes > Optimized: no > PDF version: 1.2 > ####################################################################### > > > > >>Every pdf file has a 'tag' (in the file) that looks similar to this >> >>Example #1 >>MediaBox [0 0 612 792] >> >>or this >> >>Example #2 >>MediaBox [ 0 0 612 792 ] >> >>I figured a regex might be a good way to get this data but the >>whitespace (or no whitespace) after the left bracket has me stumped. > > > > I think you might want to look for the whitespace metacharacter '\s'. > Also, you can consider using '*' to qualify a previous pattern: it stands > for "zero or more of the pattern." For example: > > ##################################### > >>>>re.search("a*b", "aab") > > <_sre.SRE_Match object at 0x403ae250> > >>>>re.search("a*b", "ab") > > <_sre.SRE_Match object at 0x403ae138> > >>>>re.search("a*b", "b") > > <_sre.SRE_Match object at 0x403ae250> > >>>>re.search("a*b", "") >>>> > > ##################################### > > In comparison: > > > ##################################### > >>>>re.search("a+b", "aab") > > <_sre.SRE_Match object at 0x403ae138> > >>>>re.search("a+b", "ab") > > <_sre.SRE_Match object at 0x403ae250> > >>>>re.search("a+b", "b") >>>> > > ##################################### > Danny, Thank you for the information. Bill From javier at ruere.com.ar Tue Oct 11 08:04:53 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Tue, 11 Oct 2005 03:04:53 -0300 Subject: [Tutor] AttributeError: 'str' object has no attribute 'geturl' In-Reply-To: <434935EC.8020806@gmail.com> References: <434935EC.8020806@gmail.com> Message-ID: Joseph Quigley wrote: > Ok, new version (sorry to bug you). > This time I've edited the program so that you can only download todays > (it won't work for any other date). Now I can connect to the server but > it sticks on "Downloading image!" > > Thanks for your prevoius help. > Joe You are welcome. This time I would like to help you but the code is incomplete (import error for Image) and I have never used urllib2 so I don't really know what to do. Again, try to debug it with pdb. Place "import pdb; pdb.set_trace()" where you want the break point and see what's going on. Javier From grouch at gmail.com Tue Oct 11 08:58:47 2005 From: grouch at gmail.com (Andrew P) Date: Tue, 11 Oct 2005 01:58:47 -0500 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Message-ID: If it makes you feel any better, this isn't an easy problem to get 100% right, traditionally. Heck, it might not even be possible. A series of compromises might be the best you can hope for. Some things to think about, however. Can you choose the characters you want, instead of the (many, many) characters you don't want? This might simplify matters. What do most words look like in English? When is a hyphen part of a word, what about dashes? A dash in the middle of a sentence means something different than one at the end of line. As far as other special/impossible cases...what is the difference between dogs' and 'the dogs' when you are counting words? What about acronyms written like S.P.E.C.T.R.E, or words that include a number like 1st? You can add point 5 to the list. Which are more common cases, which collide with other rules. What's the minimum amount of rules you can define to take the maximum chunk out of the problem? That is enough of my random rambling. A lot of it might magically fall into place once you try what Danny suggested. He is a smart guy. Doing my best to have clearly defined, self-contained functions that do a specific task usually helps to reduce a problem to more manageable steps, and visualize what is happening more clearly. Good luck, Andrew On 10/10/05, Dick Moores wrote: > > Script is at: > > > Example text file for input: > < > http://www.rcblue.com/Python/wordFrequency/first3000linesOfDavidCopperfield.txt > > > (142 kb) > (from ) > > Example output in file: > > (40 kb) > > (Execution took about 30 sec. with my computer.) > > I worked on this a LONG time for something I expected to just be an easy > and possibly useful exercise. Three times I started completely over with > a new approach. Had a lot of trouble removing exactly the characters I > didn't want to appear in the output. Wished I knew how to debug other > than just by using a lot of print statements. > > Specifically, I'm hoping for comments on or help with: > 1) How to debug. I'm using v2.4, IDLE on Win XP. > 2) I've tried to put in remarks that will help most anyone to understand > what the code is doing. Have I succeeded? > 3) No modularization. Couldn't see a reason to do so. Is there one or two? > Specifically, what sections should become modules, if any? > 4) Variable names. I gave up on making them self-explanatory. Instead, I > put in some remarks near the top of the script (lines 6-10) that I hope > do the job. Do they? In the code, does the "L to newL to L to newL to L" > kind of thing remain puzzling? > > (lines 6-10) > # meaning of short variable names: > # S is a string > # c is a character of a string > # L, F are lists > # e is an element of a list > > 5) Ideally, abbreviations that end in a period, such as U.N., e.g., i.e., > viz. op. cit., Mr. (Am. E.), etc., should not be stripped of their final > periods (whereas other words that end a sentence SHOULD be stripped). I > tried making and using a Python list of these, but it was too tough to > write the code to use it. Any ideas? (I can live very easily without a > solution to point 5, because if the output shows there are 10 "e.g"s, > I'll just assume, and I think safely, that there actually are 10 "e.g."s. > But I am curious, Pythonically.) > > Thanks very much in advance, tutors. > > Dick Moores > rdm at rcblue.com > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051011/f58d5339/attachment.html From alan.gauld at freenet.co.uk Tue Oct 11 09:39:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Oct 2005 08:39:11 +0100 Subject: [Tutor] Please look at my wordFrequency.py References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> <434AEA3F.4040304@tds.net> Message-ID: <001601c5ce36$df8cf540$0a01a8c0@xp> > I have been using winpdb recently, it is a pretty decent standalone Python > debugger for Windows. http://www.digitalpeers.com/pythondebugger/ It looks the part and I've downloaded a copy. Thamks for the tip, Alan g From negroup at gmail.com Tue Oct 11 09:53:44 2005 From: negroup at gmail.com (Negroup -) Date: Tue, 11 Oct 2005 09:53:44 +0200 Subject: [Tutor] Walk a dictionary recursively Message-ID: <2fdabf190510110053y1a673346i@mail.gmail.com> Hi tutors, in my application I found convenient to store all the data in a data structure based on a dictionary containing a lot of keys, and each of them host other dictionary with lists and dictionaries nested inside and so on... First of all I'd like to know if it is normal to use so complex data structures in which store data, or if it possible in some way to organize them using smaller "organizational units". This is instead the problem I should solve as soon as possible: I should apply a function, exactly the string's method decode('utf-8'), to each key and value of the above descripted dictionary. Consider that the keys are integers or strings, and if a key is a list, I need to decode each contained element. Is there a way to walk recursively the dictionary, or should I write my own walk function? Thanks in advance, negroup From raduzator at volny.cz Tue Oct 11 10:05:58 2005 From: raduzator at volny.cz (Raduz) Date: Tue, 11 Oct 2005 10:05:58 +0200 Subject: [Tutor] Stopping function after given time In-Reply-To: References: <200510101527.53670.raduzator@volny.cz> <434A7E98.1060101@accesstel.co.za> Message-ID: <200510111005.58369.raduzator@volny.cz> On Monday 10 of October 2005 20:10, Oliver Maunder wrote: > > >Simple question: Is it possible to stop a running function after certain > > >predefined time? > > > > > >I would like to convert this routine to Python using pycurl module, or > > > > maybe > > > > >even standard urllib.urlretrieve. > > If you use urllib.urlretrieve, you can pass in a callback function that > gets called after every few blocks are downloaded. In that function, you > could check how much time has passed since the download started, and quit > the download if necessary. You should be able to do this without threads. > I'm not sure how you stop a download once it's started though! > > Olly Thanks for an idea, I will look into it. I'm not sure how to stop running download, but at least I have something to start with :-) -- Raduz From rdm at rcblue.com Tue Oct 11 10:29:09 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 11 Oct 2005 01:29:09 -0700 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Message-ID: <6.2.1.2.2.20051011001657.0489f840@rcblue.com> Thank you, Andrew, for your wise and thoughtful comments. Andrew P wrote at 23:58 10/10/2005: >If it makes you feel any better, this isn't an easy problem to get 100% >right, traditionally. Heck, it might not even be possible. A series of >compromises might be the best you can hope for. Yes, I gradually began to realize that. And after hearing from you, even more so. >Some things to think about, however. Can you choose the characters you >want, instead of the (many, many) characters you don't want? This might >simplify matters. I tried it both ways, and settled on specifying the characters I don't want. chars = ".,!?;:&*'\"=\\+-><][/#@$%)(" and then newWord = word.strip(chars) This way I could first get rid of all those non-alphanumeric characters on the outsides of words, and leave alone the ones inside words, such as hyphens (man-eating), periods (S.P.E.C.T.R.E), and apostrophes (dog's). This seemed simpler and easier to visualize. >What do most words look like in English? Yes, I gave that a lot of thought. > When is a hyphen part of a word, > what about dashes? A dash in the middle of a sentence means something > different than one at the end of line. "A dash in the middle gets replaced by a space--creating two words." Thus "space--creating" becomes "space creating" (two words). A dash at the end of a line is also removed. Now hyphens are a different problem, one I didn't solve. "man-eating tiger": A hyphen in the middle of a word gets the hyphen left in place ("man-eating tiger"). All others would be removed. I decided to not try to handle those cases where a hyphen is used at the end of a line to place the first syllable or two of a long word at the end of a line, and the remaining syllables at the beginning of the next line. Impressionistically, it seemed to me that most text in digital form doesn't split words this way. Take, for example, articles on newspaper websites. In their tree-wasting form, with narrow columns, the reverse is true: many word-splitting hyphens at the ends of lines. >As far as other special/impossible cases...what is the difference >between dogs' and 'the dogs' when you are counting words? Dogs' stays as dogs'; 'the dogs' becomes the two words the and dogs'. Although the text in my example, David Copperfield, is BE, I am actually aiming at AE, where most quotes are double. Thus dogs' and "the dogs". For these, dogs' stays as the word dogs', and "the dogs" is the two words, the and dog. But now I'm not sure this is correct. I'd rather the possessive of dogs be treated as just another instance of dogs. But then possibly the plural dogs should be treated as an instance of dog. I realize now, thanks to you, that I didn't think this through sufficiently at all. Should knives be an instance of knife? And so on. > What about acronyms written like S.P.E.C.T.R.E S.P.E.C.T.R.E --> s.p.e.c.t.r.e I can live with the lower case. >or words that include a number like 1st? 1st, 2nd remain as 1st, 2nd . > You can add point 5 to the list. Which are more common cases, which > collide with other rules. What's the minimum amount of rules you can > define to take the maximum chunk out of the problem? I believe that's point 6. Yes, I've thought about that. But probably not well-enough. >That is enough of my random rambling. > >A lot of it might magically fall into place once you try what Danny >suggested. He is a smart guy. Doing my best to have clearly defined, >self-contained functions that do a specific task usually helps to reduce >a problem to more manageable steps, and visualize what is happening more >clearly. Yes, I'm certainly going to follow Danny's advice. Dick >On 10/10/05, Dick Moores <rdm at rcblue.com> wrote: >Script is at: ><http://www.rcblue.com/Python/wordFrequency/wordFrequency.txt> > >Example text file for input: >< >http://www.rcblue.com/Python/wordFrequency/first3000linesOfDavidCopperfield.txt> >(142 kb) >(from ><http://www.gutenberg.org/etext/766>) > >Example output in file: ><http://www.rcblue.com/Python/wordFrequency/outputToFile.txt> >(40 kb) > >(Execution took about 30 sec. with my computer.) > >I worked on this a LONG time for something I expected to just be an easy >and possibly useful exercise. Three times I started completely over with >a new approach. Had a lot of trouble removing exactly the characters I >didn't want to appear in the output. Wished I knew how to debug other >than just by using a lot of print statements. > >Specifically, I'm hoping for comments on or help with: >1) How to debug. I'm using v2.4, IDLE on Win XP. >2) I've tried to put in remarks that will help most anyone to understand >what the code is doing. Have I succeeded? >3) No modularization. Couldn't see a reason to do so. Is there one or two? >Specifically, what sections should become modules, if any? >4) Variable names. I gave up on making them self-explanatory. Instead, I >put in some remarks near the top of the script (lines 6-10) that I hope >do the job. Do they? In the code, does the "L to newL to L to newL to L" >kind of thing remain puzzling? > >(lines 6-10) ># meaning of short variable names: ># S is a string ># c is a character of a string ># L, F are lists ># e is an element of a list > >5) Ideally, abbreviations that end in a period, such as U.N., e.g., i.e., >viz. op. cit., Mr. (Am. E.), etc., should not be stripped of their final >periods (whereas other words that end a sentence SHOULD be stripped). I >tried making and using a Python list of these, but it was too tough to >write the code to use it. Any ideas? (I can live very easily without a >solution to point 5, because if the output shows there are 10 "e.g"s, >I'll just assume, and I think safely, that there actually are 10 "e.g."s. >But I am curious, Pythonically.) > >Thanks very much in advance, tutors. > >Dick Moores >rdm at rcblue.com From rschroev_nospam_ml at fastmail.fm Tue Oct 11 10:28:30 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 11 Oct 2005 10:28:30 +0200 Subject: [Tutor] code improvement for beginner ? In-Reply-To: <434ADC43.7040600@tds.net> References: <4348310D.7080602@gmx.net> <434ADC43.7040600@tds.net> Message-ID: Kent Johnson wrote: > Roel Schroeven wrote: > >> Danny Yoo wrote: >> >> >>> Looking at pageimgs(): I'm not sure what 't' means in the open >>> statement: >>> >>> f = open(filename, "rt") >> >> It's not a typo. 't' opens the file in text mode. > > > Are you sure? Is that documented anywhere? I thought it was, but actually it seems it's not. I know it from fopen in C on Windows; it is documented in MSDN. > Text mode is the default, you have to specify the 'b' if you want > binary mode. Indeed, so it seems. I just always use 't' since I do that in C too, and Python never complained about it. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From raduzator at volny.cz Tue Oct 11 10:05:58 2005 From: raduzator at volny.cz (Raduz) Date: Tue, 11 Oct 2005 10:05:58 +0200 Subject: [Tutor] Stopping function after given time In-Reply-To: References: <200510101527.53670.raduzator@volny.cz> <434A7E98.1060101@accesstel.co.za> Message-ID: <200510111005.58369.raduzator@volny.cz> On Monday 10 of October 2005 20:10, Oliver Maunder wrote: > > >Simple question: Is it possible to stop a running function after certain > > >predefined time? > > > > > >I would like to convert this routine to Python using pycurl module, or > > > > maybe > > > > >even standard urllib.urlretrieve. > > If you use urllib.urlretrieve, you can pass in a callback function that > gets called after every few blocks are downloaded. In that function, you > could check how much time has passed since the download started, and quit > the download if necessary. You should be able to do this without threads. > I'm not sure how you stop a download once it's started though! > > Olly Thanks for an idea, I will look into it. I'm not sure how to stop running download, but at least I have something to start with :-) -- Raduz From rdm at rcblue.com Tue Oct 11 10:43:44 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 11 Oct 2005 01:43:44 -0700 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <5e58f2e40510101447n4da4484cw@mail.gmail.com> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> <5e58f2e40510101447n4da4484cw@mail.gmail.com> Message-ID: <6.2.1.2.2.20051011013433.05598670@rcblue.com> John Fouhy wrote at 14:47 10/10/2005: >Some comments: > >---- >textAsString = input.read() > >S = "" >for c in textAsString: > if c == "\n": > S += ' ' > else: > S += c >---- > >You could write this more concisely as: > >S = textAsString.replace('\n', ' ') Yes! Thanks. That should have occurred to me. >---- ># At this point, each element ("word" in code below) of L is ># a string containing a real word such as "dog", ># where "dog" may be prefixed and/or suffixed by strings of ># non-alphanumeric characters. So, for example, word could be "'dog?!". ># The following code first strips these prefixed or suffixed >non-alphanumeric ># characters and then finds any words with dashes ("--") or forward >slashes ("/"), ># such as in "and/or". These then become 2 or more words without the ># dashes or slashes. >---- > >What about using regular expressions? > >re.sub('\W+', ' ') will replace all non-alphanumeric characters with a >single ' '. By the looks of things, the only difference is that if >you had something like 'foo.bar' or 'foo&bar', your code would leave >that as one word, whereas using the regex would convert it into two >words. Well, I'll have to learn the re module first. But I will. >If you want to keep the meaning of your code intact, you could still >use a regex to do it. Something like (untested) >re.sub('\b\W+|\W+\b|-+|/+', ' ') might work. > >---- ># Remove all empty elements of L, if any >while "" in L: > L.remove("") > >for e in saveRemovedForLaterL: > L.append(e) > >F = [] > >for word in L: > k = L.count(word) > if (k,word) not in F: > F.append((k,word)) >---- > >There are a lot of hidden loops in here: > >1. '' in L >This will look at every element of L, until it finds "" or it gets to >the end. >2. L.count(word) >This will also look at every element of L. > >If you combine your loops into one, you should be able to save a lot of >time. > >eg: > >for e in saveRemovedForLaterL: > L.append(e) > >counts = {} >for word in L: > if not word: # This skips empty words. > continue > try: > counts[word] += 1 > except KeyError: > counts[word] = 1 >F = [(count, word) for word, count in counts.iteritems()] Things there I don't understand yet, I'm afraid. But I'll get to them. Thanks for pushing me, John. Dick From rdm at rcblue.com Tue Oct 11 10:45:50 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 11 Oct 2005 01:45:50 -0700 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <434AEA3F.4040304@tds.net> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> <434AEA3F.4040304@tds.net> Message-ID: <6.2.1.2.2.20051011014450.081751b0@rcblue.com> Kent Johnson wrote at 15:25 10/10/2005: >Dick Moores wrote: > > Specifically, I'm hoping for comments on or help with: > > 1) How to debug. I'm using v2.4, IDLE on Win XP. > >I have been using winpdb recently, it is a pretty decent standalone >Python debugger for Windows. Start it with the -t switch so you don't >need the Python Cryptographic Toolkit. >http://www.digitalpeers.com/pythondebugger/ > >Kent Thanks, Kent. I'm looking forward to trying this out. Dick From rdm at rcblue.com Tue Oct 11 10:53:43 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 11 Oct 2005 01:53:43 -0700 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Message-ID: <6.2.1.2.2.20051011014625.0824c7e0@rcblue.com> Danny Yoo wrote at 15:47 10/10/2005: > > 3) No modularization. Couldn't see a reason to do so. Is there one or > > two? Specifically, what sections should become modules, if any? > > >Hi Dick, > >My recommendation is to practice using and writing functions. I certainly will, Danny. You've convinced me. And thanks very much for the detailed examples. Dick > For >example, this block here is a good candidate to box off as a named >function: > >####### >F = [] >for word in L: > k = L.count(word) > if (k,word) not in F: > F.append((k,word)) ># F is a list of duples (k, word), where k is the frequency of word >F.sort() >####### > > >That block can be treated as a function that takes in a list of words, and >returns a list of duples. > >###### >def doFrequencyCalculation(L): > # F is a list of duples (k, word), where k is the frequency of word > F = [] > for word in L: > k = L.count(word) > if (k,word) not in F: > F.append((k,word)) > F.sort() > return F >###### > >Here, we explicitly say that frequence calculation depends on having a >list L of words, and that the result should be a list of duples. > >Functions allow us to "scope" variables into different kinds of roles. >We'd say in doFrequenceCalculation that 'word' and 'k' are "temporary" >variables. If we write programs using functions, we can express that >"temporary" role as a real part of the program. > >As it stands, in the original code, we have to watch that 'word' or 'k' >isn't being used by anyone else: like all the other variables in your >program, they're all global and given equal status. You're using >lowercase as an informal way to remind yourself that those variables are >meant to be temporary, but that approach can be error prone. > > >Conceptually, your program appears to work in four stages: > > 1. Read lines of a file > 2. Extract list of words from the lines > 3. Do histogram frequency count on those lines > 4. Report frequency results > >and it would be great if we could see this program flow as an explicit >sequence of function calls: > >################################## >## Pseudocode >def program(): > L = readLinesInFile() > W = extractWordsFromLines(L) > F = doFrequencyCalculation(W) > reportFrequencyResults(F) >################################## > > >This allows one to see the overall program plan without having to read the >whole program. It also allows you to do some experimentation later on by >letting you plugging in different functions in the overall program() plan. > >As a concrete example: once we have a program in this form, it's easy to >swap in a different algorithm for doing frequency calculation: > >###### >def program(): > L = readLinesInFile() > W = extractWordsFromLines(L) > ## F = doFrequencyCalculation(W) > F = doFrequencyCalculationWithDifferentAlgorithm(W) > reportFrequencyResults(F) >###### > > >Does this make sense? Sure does. > Please feel free to ask more questions about this. None right now, thanks. But I can see I need to study the difference between local and global variables. Dick From klappnase at freenet.de Tue Oct 11 11:17:39 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue, 11 Oct 2005 11:17:39 +0200 Subject: [Tutor] Tutor Digest, Vol 20, Issue 37 In-Reply-To: <434AF443.2000409@gmail.com> References: <434AF443.2000409@gmail.com> Message-ID: <20051011111739.43f10b29.klappnase@freenet.de> On Mon, 10 Oct 2005 17:07:47 -0600 Joseph Quigley wrote: > Hi, > > Unfortunately I get this error: > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "Programming/Gacor/tmp.py", line 83, in newPic > imgPrep.configure(file=os.path.join(imgDir, pics[pic])) > AttributeError: PhotoImage instance has no attribute 'configure' > > I think I should mention that I'm completely in the dark when it comes > to GUI programming (and I don't have much time to learn it... or do I?) Oops, sorry for that; in fact it looks like you will have to define a new PhotoImage instance, like: def newPic(): global pic, imgPrep pic = pic + 1 imgPrep = ImageTk.PhotoImage(file=file=os.path.join(imgDir, pics[pic])) imgShow.configure(image=imgPrep) The configure() method works for Tkinter.PhotoImage, but obviously not for ImageTk.PhotoImage, so I got trapped here. Regards Michael From ldapguru at yahoo.com Tue Oct 11 11:16:13 2005 From: ldapguru at yahoo.com (iPlanetLDAP) Date: Tue, 11 Oct 2005 02:16:13 -0700 (PDT) Subject: [Tutor] Please look at my wordFrequency.py (Alan Darwish) Message-ID: <20051011091613.92475.qmail@web54404.mail.yahoo.com> Exceptional Python Ladies and Gents How about to make this great wordFrequency.py script to support Unicode/Locale wordFrequency.py for example this is an Arabic code page 1256 windows I guess it is a matter of character encoding. Try execute the following command before running wordFrequency.py (in the same DOS console): chcp 1256 Also this a sample from some other code sent to me for anoher script to support Arabic written by Lion (a close friend who was the first to arabize Linux os) import sys import codecs import re TYPE_MULTILINE=0x1 class ReaderBase: def __init__(self): self.callbacks={} def addCommand(self,command,callback,flags): self.callbacks[command]={'callback':callback,'command':command,'flags':flags} def findCallback(self,command): try: return self.callbacks[command[0]] except KeyError: return None def processFile(self,path): #f=open(path, 'r') f = codecs.open(path,encoding='CP1256', mode='r') This is arabic numbers 1234567890 This is arabic (letters) Text let us add it to the English text and process wordFrequency.py |B الأدب المفرد للبخاري|A البخاري dod ### |V 2-3 لعن الله من سرق منار الأرض لعن الله من لعن والديه لعن الله من آوى محدثا باب يبر والديه ما لم يكن معصية حدثنا محمد بن عبد العزيز قال حدثنا عبد الملك بن الخطاب بن عبيد الله بن أبى بكرة البصري لقيته بالرملة قال حدثني راشد أبو محمد عن شهر بن حوشب عن أم الدرداء عن أبى الدرداء قال أوصانى رسول الله بتسع لا تشرك بالله شيئا وإن قطعت أو حرقت ولا تتركن الصلاة المكتوبة متعمدا ومن تركها متعمدا برئت منه الذمة ولا تشربن الخمر فإنها مفتاح كل شر وأطع والديك وإن أمراك أن تخرج من دنياك فاخرج لهما ولا تنازعن ولاة الأمر وإن رأيت أنك أنت ولا تفرر من الزحف وإن هلكت وفر أصحابك وأنفق من طولك على أهلك ولا ترفع عصاك على أهلك وأخفهم في |B الأدب المفرد للبخاري|A البخاري dod ### |V 3-3 وصاحبهما في الدنيا معروفا والثانية إني كنت أخذت سيفا أعجبنى فقلت يا رسول الله هب لي هذا فنزلت يسألونك عن الأنفال والثالثة إني مرضت فأتاني رسول الله فقلت يا رسول الله إني أريد أن أقسم مالي أفأوصى بالنصف فقال لا فقلت الثلث فسكت فكان الثلث بعده جائزا والرابعة إني شربت الخمر مع قوم من الأنصار فضرب رجل منهم أنفى بلحيى جمل فأتيت النبي فأنزل تحريم الخمر حدثنا الحميدي قال حدثنا بن عيينة قال حدثنا هشام بن عروة قال أخبرني أبى قال أخبرتنى |B الأدب المفرد للبخاري|A البخاري dod ### |V 3-3 هذا فنزلت يسألونك عن الأنفال والثالثة إني مرضت فأتاني رسول الله فقلت يا رسول الله إني أريد أن أقسم مالي أفأوصى بالنصف فقال لا فقلت الثلث فسكت فكان الثلث بعده جائزا والرابعة إني شربت الخمر مع قوم من الأنصار فضرب رجل منهم أنفى بلحيى جمل فأتيت النبي فأنزل تحريم الخمر حدثنا الحميدي قال حدثنا بن عيينة قال حدثنا هشام بن عروة قال أخبرني أبى قال أخبرتنى Have fun Alan Darwish www.Muhammad.com From alan.gauld at freenet.co.uk Tue Oct 11 11:29:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Oct 2005 10:29:27 +0100 Subject: [Tutor] Walk a dictionary recursively References: <2fdabf190510110053y1a673346i@mail.gmail.com> Message-ID: <003701c5ce46$48181ea0$0a01a8c0@xp> > First of all I'd like to know if it is normal to use so complex data > structures in which store data, or if it possible in some way to > organize them using smaller "organizational units". Its not uncommon but often it can be simplified by using classes. In particular the classes can expose an interface that makes the structures appear simpler by providing the access mechanisms needed so that the outer code is ignorant of the structural complexity. > to decode each contained element. Is there a way to walk recursively > the dictionary, or should I write my own walk function? Not for an arbitrarily complex structure such as you have defined. You will need to write your own I fear. HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From paul1brian at gmail.com Tue Oct 11 11:58:30 2005 From: paul1brian at gmail.com (paul brian) Date: Tue, 11 Oct 2005 10:58:30 +0100 Subject: [Tutor] Walk a dictionary recursively In-Reply-To: <2fdabf190510110053y1a673346i@mail.gmail.com> References: <2fdabf190510110053y1a673346i@mail.gmail.com> Message-ID: Firstly are you using this to store or alter data regarding Microsoft Active Directory?. If so I suggest you look at some of their ADSI / WMI interfaces for COM (if you use win32com from Mark Hammond or activeState life becomes a lot easier. Well the Windows programming part of it does) As for the particulars of your question, you might find life simpler if you created a "parentID" (and/or childID) for each unique entry in the tree. As you are going to be growing the data list in size one other area to look at is generators - this will enable you to walk arbitrarily large trees but with a far lower memory footprint and hence a lot faster. A generator class returns an object that will walk through an iteration set (like a for loop) but at the end of every step will "disappear" from the stack and when it is called again it starts exactly where it left off. So I would suggest you create generaotr based classes to store your data, using an explicit parent/child relationship rather than relying on the implicit relationships of which dictionary is stored inside which dictionary. It is still a far chunk of work. I suggest you start on the parent child thing first. Think about having a single point of entry that creates a new object and then "hangs" it on the tree. I hope that helps and do please come back to the list with how you are gettng on. On 10/11/05, Negroup - wrote: > Hi tutors, in my application I found convenient to store all the data > in a data structure based on a dictionary containing a lot of keys, > and each of them host other dictionary with lists and dictionaries > nested inside and so on... > > First of all I'd like to know if it is normal to use so complex data > structures in which store data, or if it possible in some way to > organize them using smaller "organizational units". > > This is instead the problem I should solve as soon as possible: I > should apply a function, exactly the string's method decode('utf-8'), > to each key and value of the above descripted dictionary. Consider > that the keys are integers or strings, and if a key is a list, I need > to decode each contained element. Is there a way to walk recursively > the dictionary, or should I write my own walk function? > > Thanks in advance, > negroup > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From negroup at gmail.com Tue Oct 11 12:23:26 2005 From: negroup at gmail.com (Negroup -) Date: Tue, 11 Oct 2005 12:23:26 +0200 Subject: [Tutor] Walk a dictionary recursively In-Reply-To: References: <2fdabf190510110053y1a673346i@mail.gmail.com> Message-ID: <2fdabf190510110323v5ad9cd3aq@mail.gmail.com> 2005/10/11, paul brian : > Firstly are you using this to store or alter data regarding Microsoft > Active Directory?. If so I suggest you look at some of their ADSI / > WMI interfaces for COM (if you use win32com from Mark Hammond or > activeState life becomes a lot easier. Well the Windows programming > part of it does) Hi Paul, this is not my particular case, but your answer still has been precious! Really dictionaries might result in a poor solution in some cases. I think that I will face my problem using a dedicated class (thanks Alan for this suggestion), implementing an "expandable" tree structure where items will be related via parent/child relation. The idea of using generator is whetting too. Actually I have no time (hrm.. call it skills?) to make up all these things togheter! However, considering that in the near future I shall rewrite this application for a bunch of good reasons, I'll ask for help again, count on it ;-) Thanks. From kent37 at tds.net Tue Oct 11 12:24:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Oct 2005 06:24:29 -0400 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> Message-ID: <434B92DD.9000402@tds.net> Dick Moores wrote: > (Execution took about 30 sec. with my computer.) That's way too long > > Specifically, I'm hoping for comments on or help with: > 2) I've tried to put in remarks that will help most anyone to understand > what the code is doing. Have I succeeded? Yes, i think so > 3) No modularization. Couldn't see a reason to do so. Is there one or two? > Specifically, what sections should become modules, if any? As Danny says, breaking it up into functions makes it easier to understand and test > 4) Variable names. I gave up on making them self-explanatory. Instead, I > put in some remarks near the top of the script (lines 6-10) that I hope > do the job. Do they? In the code, does the "L to newL to L to newL to L" > kind of thing remain puzzling? Some of your variables seem unnecessary. For example newWord = word.strip(chars) word = newWord could be just word = word.strip(chars) > 5) Ideally, abbreviations that end in a period, such as U.N., e.g., i.e., > viz. op. cit., Mr. (Am. E.), etc., should not be stripped of their final > periods (whereas other words that end a sentence SHOULD be stripped). I > tried making and using a Python list of these, but it was too tough to > write the code to use it. Any ideas? You should be able to do this with regular expressions or searching in the word. You want to test for a word that ends with a period but doesn't include any periods. Somenthing like if word.endswith('.') and '.' not in word[:-1]: word = word[:-1] Other notes: Use re.split() to do all the splits at once. Something like L = re.split(r'\s+|--|/', textAsString) #remove empty elements in L while "" in L: L.remove("") The above iterates L twice for each empty word! The remove() calls are expensive too because the remaining elements of L must be shifted down. Do the whole thing in one pass over L with L = [ w for w in L if w ] You only need to remove empty elements once, when the rest of the processing is done. for e in saveRemovedForLaterL: L.append(e) could be L.extend(e) From enas_khalil at yahoo.com Tue Oct 11 14:28:00 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Tue, 11 Oct 2005 05:28:00 -0700 (PDT) Subject: [Tutor] Where is the error Message-ID: <20051011122801.686.qmail@web30511.mail.mud.yahoo.com> hello, when i run the following code to Read and tokenize data from a tagged text as follows : from nltk.corpus import brown from nltk.tagger import TaggedTokenizer from nltk.tokenizer import * tagged_txt_str=open('corpus.txt' ).read() tagged_txt_token=Token(TEXT=tagged_txt_str) TaggedTokenizer.tokenize(tagged_txt_token) print tagged_txt_token i got the following error : Traceback (most recent call last): File "C:\My Documents\TAGGING.PY", line 3, in -toplevel- from nltk.tagger import TaggedTokenizer ImportError: cannot import name TaggedTokenizer could anyone help me thanks in advance enas --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051011/5c05ad31/attachment.htm From kent37 at tds.net Tue Oct 11 14:50:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Oct 2005 08:50:35 -0400 Subject: [Tutor] Where is the error In-Reply-To: <20051011122801.686.qmail@web30511.mail.mud.yahoo.com> References: <20051011122801.686.qmail@web30511.mail.mud.yahoo.com> Message-ID: <434BB51B.3070400@tds.net> What version of NLTK are you using? From a look at the API docs, nltk.tagger.TaggedTokenizer seems to have been removed in v1.4. Kent enas khalil wrote: > hello, > > > when i run the following code to Read and tokenize data from a > tagged text as follows : > > > from nltk.corpus import brown > from nltk.tagger import TaggedTokenizer > from nltk.tokenizer import * > tagged_txt_str=open('corpus.txt' ).read() > tagged_txt_token=Token(TEXT=tagged_txt_str) > TaggedTokenizer.tokenize(tagged_txt_token) > print tagged_txt_token > > > > > i got the following error : > Traceback (most recent call last): > File "C:\My Documents\TAGGING.PY", line 3, in -toplevel- > from nltk.tagger import TaggedTokenizer > ImportError: cannot import name TaggedTokenizer > > > > > > > > could anyone help me > > thanks in advance > > enas > > ------------------------------------------------------------------------ > Yahoo! Music Unlimited - Access over 1 million songs. Try it free. > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From cpu.crazy at gmail.com Tue Oct 11 15:45:17 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 11 Oct 2005 07:45:17 -0600 Subject: [Tutor] AttributeError: 'str' object has no attribute, 'geturl' In-Reply-To: References: Message-ID: <434BC1ED.9000200@gmail.com> > You are welcome. This time I would like to help you but the code is incomplete > (import error for Image) and I have never used urllib2 so I don't really know what to > do. > Again, try to debug it with pdb. Place "import pdb; pdb.set_trace()" where you want > the break point and see what's going on. > > Javier Hi, I'm embarased to say that I was trying to download an image that doesn't exist (I had the url wrong). Thanks for hte tip on pdb, Joe From alberto.troiano at gmail.com Tue Oct 11 16:48:57 2005 From: alberto.troiano at gmail.com (Alberto Troiano) Date: Tue, 11 Oct 2005 10:48:57 -0400 Subject: [Tutor] Where is the error In-Reply-To: <20051011122801.686.qmail@web30511.mail.mud.yahoo.com> Message-ID: Hi from nltk.tagger import TaggedTokenizer I'm not familiar with this module but looking at the error it looks like the TaggedTokenizer module maybe misspelled or does not exists or the same with tagger Maybe an upcase letter or something like that Check your library for the correct name... If it's correct then I'm screwed *grin*. Perhaps other tutor Best Regards, Alberto _____ De: tutor-bounces at python.org [mailto:tutor-bounces at python.org] En nombre de enas khalil Enviado el: Martes, 11 de Octubre de 2005 08:28 Para: python-list at python.org; tutor at python.org Asunto: [Tutor] Where is the error hello, when i run the following code to Read and tokenize data from a tagged text as follows : from nltk.corpus import brown from nltk.tagger import TaggedTokenizer from nltk.tokenizer import * tagged_txt_str=open('corpus.txt' ).read() tagged_txt_token=Token(TEXT=tagged_txt_str) TaggedTokenizer.tokenize(tagged_txt_token) print tagged_txt_token i got the following error : Traceback (most recent call last): File "C:\My Documents\TAGGING.PY", line 3, in -toplevel- from nltk.tagger import TaggedTokenizer ImportError: cannot import name TaggedTokenizer could anyone help me thanks in advance enas _____ Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051011/e328342f/attachment.htm From rdm at rcblue.com Tue Oct 11 18:06:49 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 11 Oct 2005 09:06:49 -0700 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <434B92DD.9000402@tds.net> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> <434B92DD.9000402@tds.net> Message-ID: <6.2.1.2.2.20051011084520.06ed1ae0@rcblue.com> Kent Johnson wrote at 03:24 10/11/2005: >Dick Moores wrote: > > (Execution took about 30 sec. with my computer.) > >That's way too long How long would you expect? I've already made some changes but haven't seen the time change much. > > > > Specifically, I'm hoping for comments on or help with: > > 2) I've tried to put in remarks that will help most anyone to understand > > what the code is doing. Have I succeeded? > >Yes, i think so Good. > > 3) No modularization. Couldn't see a reason to do so. Is there one or > two? > > Specifically, what sections should become modules, if any? > >As Danny says, breaking it up into functions makes it easier to >understand and test OK. > > 4) Variable names. I gave up on making them self-explanatory. Instead, I > > put in some remarks near the top of the script (lines 6-10) that I hope > > do the job. Do they? In the code, does the "L to newL to L to newL to L" > > kind of thing remain puzzling? > >Some of your variables seem unnecessary. For example > newWord = word.strip(chars) > word = newWord >could be just > word = word.strip(chars) Yes, I'll have to get that kind of thing straightened out. In my mind, first of all. > > 5) Ideally, abbreviations that end in a period, such as U.N., e.g., > i.e., > > viz. op. cit., Mr. (Am. E.), etc., should not be stripped of their final > > periods (whereas other words that end a sentence SHOULD be stripped). I > > tried making and using a Python list of these, but it was too tough to > > write the code to use it. Any ideas? > >You should be able to do this with regular expressions or searching in >the word. You want to test for a word that ends with a period but >doesn't include any periods. Something like >if word.endswith('.') and '.' not in word[:-1]: > word = word[:-1] Nice! That takes care of U.N., e.g., i.e., but not viz., op. cit., or Mr. >Other notes: >Use re.split() to do all the splits at once. Something like > L = re.split(r'\s+|--|/', textAsString) Don't understand this yet. I'll work on it. >#remove empty elements in L >while "" in L: > L.remove("") >The above iterates L twice for each empty word! I don't get the twice. Could you spell it out, please? >The remove() calls are expensive too because the remaining elements of L >must be shifted down. Do the whole thing in one pass over L with > L = [ w for w in L if w ] >You only need to remove empty elements once, when the rest of the >processing is done. Got it. But using this doesn't seem to make much difference in the time. Also, I'm puzzled that whether or not psyco is employed makes no difference in the time. Can you explain why? >for e in saveRemovedForLaterL: > L.append(e) >could be >L.extend(e) Are you recommending L.extend(e), or is it just another way to do it? Thanks very much for your help, Kent. Dick From kent37 at tds.net Tue Oct 11 18:36:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Oct 2005 12:36:59 -0400 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051011084520.06ed1ae0@rcblue.com> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> <434B92DD.9000402@tds.net> <6.2.1.2.2.20051011084520.06ed1ae0@rcblue.com> Message-ID: <434BEA2B.3050204@tds.net> Dick Moores wrote: > Kent Johnson wrote at 03:24 10/11/2005: > >>Dick Moores wrote: >> >>>(Execution took about 30 sec. with my computer.) >> >>That's way too long > > > How long would you expect? I've already made some changes but haven't > seen the time change much. A couple of seconds at most, unless you are running it on some dog computer. It's just not that much text and you should be able to process it in a couple of passes at most. What changes have you made? Several changes already posted should have a noticable effect, I think. What is your current code? >>>5) Ideally, abbreviations that end in a period, such as U.N., e.g., >> >>i.e., >> >>>viz. op. cit., Mr. (Am. E.), etc., should not be stripped of their final >>>periods (whereas other words that end a sentence SHOULD be stripped). I >>>tried making and using a Python list of these, but it was too tough to >>>write the code to use it. Any ideas? >> >>You should be able to do this with regular expressions or searching in >>the word. You want to test for a word that ends with a period but >>doesn't include any periods. Something like >>if word.endswith('.') and '.' not in word[:-1]: >> word = word[:-1] > > > Nice! That takes care of U.N., e.g., i.e., but not viz., op. cit., or Mr. Ah, right. I don't know how you could handle that except with a dictionary. At least they will only appear in the word list once, without the trailing period. >>Other notes: >>Use re.split() to do all the splits at once. Something like >> L = re.split(r'\s+|--|/', textAsString) > > > Don't understand this yet. I'll work on it. OK, it's a regular expression that will match either \s+ one or more white space e.g. space, tab, newline -- a hyphen / a slash re.split() then splits the string on each match. > > >>#remove empty elements in L >>while "" in L: >> L.remove("") >>The above iterates L twice for each empty word! > > > I don't get the twice. Could you spell it out, please? the test /"" in L/ searches the list for an empty string - that's one L.remove("") searches the list again for the empty string, then removes it > > >>The remove() calls are expensive too because the remaining elements of L >>must be shifted down. Do the whole thing in one pass over L with >> L = [ w for w in L if w ] >>You only need to remove empty elements once, when the rest of the >>processing is done. > > > Got it. But using this doesn't seem to make much difference in the time. > > Also, I'm puzzled that whether or not psyco is employed makes no > difference in the time. Can you explain why? My guess is it's because you have so many O(n^2) elements in the code. You have to get your algorithm to be O(n). > > >>for e in saveRemovedForLaterL: >> L.append(e) >>could be >>L.extend(e) > > > Are you recommending L.extend(e), or is it just another way to do it? Recommending. Look for ways to eliminate loops. If you can't eliminate them, move them into C code in the runtime, which is what this one does. > > Thanks very much for your help, Kent. No problem! Kent > > Dick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Tue Oct 11 19:37:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Oct 2005 13:37:44 -0400 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <434BEA2B.3050204@tds.net> References: <6.2.1.2.2.20051010112926.084abe70@rcblue.com> <434B92DD.9000402@tds.net> <6.2.1.2.2.20051011084520.06ed1ae0@rcblue.com> <434BEA2B.3050204@tds.net> Message-ID: <434BF868.2080400@tds.net> Kent Johnson wrote: > Dick Moores wrote: > >> Kent Johnson wrote at 03:24 10/11/2005: >> >>> Dick Moores wrote: >>> >>>> (Execution took about 30 sec. with my computer.) >>> >>> >>> That's way too long >> >> >> >> How long would you expect? I've already made some changes but haven't >> seen the time change much. > > > A couple of seconds at most, unless you are running it on some dog > computer. It's just not that much text and you should be able to process > it in a couple of passes at most. OK I couldn't resist. I took your program and ran it on my computer - took about 38 seconds and got the same results as you. Then I made the changes I outlined, and a few other similar ones, and got it down to 34 secs. Finally I made the change suggested by John Fouhy - to accumulate the counts in a dict - and the time went down to 0.23 seconds. >> Also, I'm puzzled that whether or not psyco is employed makes no >> difference in the time. Can you explain why? > > > My guess is it's because you have so many O(n^2) elements in the code. > You have to get your algorithm to be O(n). In particular this code: for word in L: k = L.count(word) if (k,word) not in F: F.append((k,word)) L.count() has to scan through the entire list (L) looking for a match with each word. So for each word, you are making 26140 string compares. The total number of compares is 26140*26140 or 683,299,600. That's a lot! Then, for each word, you scan F for a match. Now you are doing tuple compares. The number of compares will increase as the length of F, but overall it will be about 26140*3700/2 or 48,359,000 compares. Compare this to the dictionary version which just iterates L once, doing a dictionary lookup and write for each word. The reason psyco doesn't make much difference is because all the time is spent in list.count() which is already C code. Kent From dyoo at hkn.eecs.berkeley.edu Tue Oct 11 20:54:54 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 11 Oct 2005 11:54:54 -0700 (PDT) Subject: [Tutor] code improvement for beginner ? (fwd) Message-ID: ---------- Forwarded message ---------- Date: Tue, 11 Oct 2005 20:55:24 +0200 From: lmac To: Danny Yoo Subject: Re:code improvement for beginner ? Danny Yoo wrote: > >>>The point of this restructuring is to allow you to add more image >>>types without too much pain, since there's no more hardcoded array >>>indexing against r1. It also simplifies to calls to imgreg from: >>> >>> if imgreg(r1[0],a) == 1: >>> continue >>> if imgreg(r1[1],a) == 1: >>> continue >>> imgreg(r1[2],a) >>> >>>to the simpler: >>> >>> imgreg(a) >> >>Yes. Thats good. > > > > Check your code: pageimgs() is calling imgreg three times. > > > > >>The problem with downloading the images is this: >> >>------------- >>http://images.nfl.com/images/globalnav-shadow-gray.gif >>Traceback (most recent call last): >> File "/home/internet/bin/nflgrab.py", line 167, in ? >> urllib.urlretrieve(img,img[f:]) >> File "/usr/lib/python2.3/urllib.py", line 83, in urlretrieve >> return _urlopener.retrieve(url, filename, reporthook, data) >> File "/usr/lib/python2.3/urllib.py", line 216, in retrieve >> tfp = open(filename, 'wb') >>IOError: [Errno 13] Permission denied: '/globalnav-shadow-gray.gif' > > > One bug is that Python is trying to write those image files to the root > directory. Your operating system's file system is saying that it won't > allow you to write files to that location. > > urllib.urlretrieve saves those files with the path given in the second > parameter: > > urllib.urlretrieve(img, img[f:]) > ^^^^^^^ > > You may want to change this so that it stores those files in a particular > directory. Something like: > > urllib.urlretrieve(img, os.path.join("/tmp", > img[f+1:])) > > may work better. The main idea is that you should explicitly control > where the files are being downloaded to. > > > Another bug: you will probably still run into problems because 'img' must > be a URL, and each 'img' is instead a line that contains a URL. The > difference is between having a string like: > > http://python.org. > > and: > > This line contains a url to the python web site: http://python.org. > > and images, as far as I can tell, is storing a list of the lines, not the > image urls. So you may want to make appropriate changes to imgreg() so > that it maintains a list of image urls. > > Ok. Version 3. Images are now downloaded Thank you. This was a double-bug ;-) I added a second argument for an optional target-directory. And of course added a line about your help. Thanks. From rdm at rcblue.com Tue Oct 11 21:10:59 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 11 Oct 2005 12:10:59 -0700 Subject: [Tutor] Please look at my wordFrequency.py Message-ID: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> Kent Johnson wrote at 10:37 10/11/2005: >Kent Johnson wrote: > > Dick Moores wrote: > > > >> Kent Johnson wrote at 03:24 10/11/2005: > >> > >>> Dick Moores wrote: > >>> > >>>> (Execution took about 30 sec. with my computer.) > >>> > >>> > >>> That's way too long > >> > >> > >> > >> How long would you expect? I've already made some changes but haven't > >> seen the time change much. > > > > > > A couple of seconds at most, unless you are running it on some dog > > computer. It's just not that much text and you should be able to process > > it in a couple of passes at most. > >OK I couldn't resist. I took your program and ran it on my computer - >took about 38 seconds and got the same results as you. Then I made the >changes I outlined, and a few other similar ones, and got it down to 34 secs. Yes, that's about the difference I was seeing. Thanks for taking the trouble. I went from 30 to 27. With no regex use (don't understand it yet). > Finally I made the change suggested by John Fouhy - to accumulate the > counts in a dict - and the time went down to 0.23 seconds. WOW! I didn't implement John's change because I didn't understand it. Haven't dealt with dictionaries yet. > >> Also, I'm puzzled that whether or not psyco is employed makes no > >> difference in the time. Can you explain why? > > > > > > My guess is it's because you have so many O(n^2) elements in the code. > > You have to get your algorithm to be O(n). OK, I finally bit the bullet, googled O(n^2), and read about Big O notation at and I think I've now got at least the basic idea. >In particular this code: >for word in L: > k = L.count(word) > if (k,word) not in F: > F.append((k,word)) > >L.count() has to scan through the entire list (L) looking for a match >with each word. So for each word, you are making 26140 string compares. >The total number of compares is 26140*26140 or 683,299,600. That's a lot! >Then, for each word, you scan F for a match. Now you are doing tuple >compares. The number of compares will increase as the length of F, but >overall it will be about 26140*3700/2 or 48,359,000 compares. Kent, you're beginning to get thru to me. Thanks for the details and the numbers. >Compare this to the dictionary version which just iterates L once, doing >a dictionary lookup and write for each word. > >The reason psyco doesn't make much difference is because all the time is >spent in list.count() which is already C code. Ah. But how can I know what is in C code and what isn't? For example, in a previous post you say that L.extend(e) is in C, and imply that L.append(e) isn't, and that therefore L.extend(e) should be used. Well, back to Hetlands' Beginning Python. Dick From kent37 at tds.net Tue Oct 11 21:22:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Oct 2005 15:22:52 -0400 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> Message-ID: <434C110C.206@tds.net> Dick Moores wrote: > Kent Johnson wrote at 10:37 10/11/2005: >>The reason psyco doesn't make much difference is because all the time is >>spent in list.count() which is already C code. > > > Ah. But how can I know what is in C code and what isn't? For example, in > a previous post you say that L.extend(e) is in C, and imply that > L.append(e) isn't, and that therefore L.extend(e) should be used. In general, if you wrote it, it's in Python. If it is built-in - either as part of the Python syntax or pretty much anything in chapter 2 of the Python Library Reference - it's in C. If it is in the standard lib (anything you import) you have to look at the lib module to see how it is implemented - some are in Python, some are in C. Both extend() and append() are part of the built-in type 'list' so they are in C. The difference is that to use append() you have to put a loop around it, the loop is in your Python code. If you use extend() the loop is implicit (in extend()) and implemented as part of extend(). Kent From grouch at gmail.com Tue Oct 11 22:06:04 2005 From: grouch at gmail.com (Andrew P) Date: Tue, 11 Oct 2005 15:06:04 -0500 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> Message-ID: Just want to add a little something here, because reading over this thread, I think there may have been some confusion: Kent wrote: for e in saveRemovedForLaterL: L.append(e) could be L.extend(e) I think he might have meant: for e in saveRemovedForLaterL: L.append(e) could be L.extend(saveRemovedForLaterL) The difference between these is that one is explicitly looping with Python, accessing each element of the first list one at a time, appending it to the other one at a time. Whereas if you call extend() instead, it will be doing that looping for you with the extend() method, written in C, and very quickly indeed. I would worry less about what is written in C vs what is built-in, and does implicit looping for you. Any time you can avoid stepping over a list one element at a time, is usually the faster way. >>> lst = [1,2,3,4] >>> lst2 = [5,6,7,8] >>> lst.extend(lst2) >>> print lst [1, 2, 3, 4, 5, 6, 7, 8] Compare this to: >>> lst = [1,2,3,4] >>> lst2 = [5,6,7,8] >>> for num in lst2: ... lst.append(num) >>> print lst [1, 2, 3, 4, 5, 6, 7, 8] FWIW, append is generally used to generate a list from something calculated on the fly: >>> lst = [] >>> for i in range(10): ... lst.append(i) ... >>> print lst [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > Ah. But how can I know what is in C code and what isn't? For example, in > a previous post you say that L.extend(e) is in C, and imply that > L.append(e) isn't, and that therefore L.extend(e) should be used. > > Well, back to Hetlands' Beginning Python. > > Dick > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051011/2f1e118c/attachment.html From kent37 at tds.net Wed Oct 12 00:00:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Oct 2005 18:00:13 -0400 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> Message-ID: <434C35ED.9020503@tds.net> Andrew P wrote: > Just want to add a little something here, because reading over this > thread, I think there may have been some confusion: > > Kent wrote: > > for e in saveRemovedForLaterL: > L.append(e) > could be > L.extend(e) > > I think he might have meant: > > for e in saveRemovedForLaterL: > L.append(e) > could be > L.extend(saveRemovedForLaterL) Right you are, thanks for the catch! Kent > > The difference between these is that one is explicitly looping with > Python, accessing each element of the first list one at a time, > appending it to the other one at a time. Whereas if you call extend() > instead, it will be doing that looping for you with the extend() method, > written in C, and very quickly indeed. I would worry less about what is > written in C vs what is built-in, and does implicit looping for you. > Any time you can avoid stepping over a list one element at a time, is > usually the faster way. > > >>> lst = [1,2,3,4] > >>> lst2 = [5,6,7,8] > >>> lst.extend(lst2) > >>> print lst > [1, 2, 3, 4, 5, 6, 7, 8] > > Compare this to: > > >>> lst = [1,2,3,4] > >>> lst2 = [5,6,7,8] > >>> for num in lst2: > ... lst.append(num) > >>> print lst > [1, 2, 3, 4, 5, 6, 7, 8] > > > FWIW, append is generally used to generate a list from something > calculated on the fly: > > >>> lst = [] > >>> for i in range(10): > ... lst.append(i) > ... > >>> print lst > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > > > Ah. But how can I know what is in C code and what isn't? For example, in > a previous post you say that L.extend(e) is in C, and imply that > L.append(e) isn't, and that therefore L.extend(e) should be used. > > Well, back to Hetlands' Beginning Python. > > Dick > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From me at scottoertel.info Wed Oct 12 01:19:22 2005 From: me at scottoertel.info (Scott Oertel) Date: Wed, 12 Oct 2005 02:19:22 +0300 Subject: [Tutor] code improvement for beginner ? In-Reply-To: <434AC60D.1050209@gmx.net> References: <434AC60D.1050209@gmx.net> Message-ID: <434C487A.9040401@scottoertel.info> lmac wrote: > --------------- > >The problem with downloading the images is this: > >------------- >http://images.nfl.com/images/globalnav-shadow-gray.gif >Traceback (most recent call last): > File "/home/internet/bin/nflgrab.py", line 167, in ? > urllib.urlretrieve(img,img[f:]) > File "/usr/lib/python2.3/urllib.py", line 83, in urlretrieve > return _urlopener.retrieve(url, filename, reporthook, data) > File "/usr/lib/python2.3/urllib.py", line 216, in retrieve > tfp = open(filename, 'wb') >IOError: [Errno 13] Permission denied: '/globalnav-shadow-gray.gif' >------------- > >Is there any solution to know if i can download the image ? > >Thanks. > > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > > I used this in my previous program while having problems writing files. from sys import argv from os.path import dirname, join try: tfp = open(join(dirname(argv[0]), filename), 'wb') except IOError: print "Unable to write file, pick another directory" this will save it into the directory that your program resides in. you might want to check out this current lib doc, http://www.python.org/doc/current/lib/os-file-dir.html it has a bunch of objects of the os module that are good for testing if a directory is writable From rdm at rcblue.com Wed Oct 12 10:46:16 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 12 Oct 2005 01:46:16 -0700 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <5e58f2e40510111509x3c0eee28n@mail.gmail.com> References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> <5e58f2e40510111509x3c0eee28n@mail.gmail.com> Message-ID: <6.2.1.2.2.20051012004506.02c1d5b0@rcblue.com> John Fouhy wrote at 15:09 10/11/2005: >On 12/10/05, Dick Moores wrote: > >Hi Dick, > >Glad you're making progress :-) > > > Yes, that's about the difference I was seeing. Thanks for taking the > > trouble. I went from 30 to 27. With no regex use (don't understand it > yet). > >Regular expressions are a power tool of text processing. They are a >bit tricky to learn, but once you've got the hang of them you'll find >they can save you a lot of effort. I'm not sure of a good tutorial, >but if you look through the archives of this list, there's been a lot >of discussion of them in the past :-) Yes, but I think I need to go at something complex systematically. In my bookcase I have the 1st edition of Friedl's _Mastering Regular Expressions_ O'Reilly, 1997. Because there is now a 2nd edition (2002) I'd been ignoring what I have, but in the Python 2.4 Python Library Reference section 4.2 re -- Regular expression operations I find: " See Also:Mastering Regular Expressions Book on regular expressions by Jeffrey Friedl, published by O'Reilly. The second edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail. " So I'd like to ask if there is agreement about the value of this book, and if the 1st is really better that the 2nd ed. for regex in Python. In Python Library Reference 4.2.1 Regular Expression Syntax there is this: "A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the Regular Expression HOWTO, accessible from http://www.python.org/doc/howto/." So I thought I'd start with that. What do you think? I'm not a complete regex beginner, but I've forgotten most of what I once knew. A long time ago (12 years) I had a well-equipped dial-up shell (tcsh) account with helpful users (Netcom) and enjoyed learning something of the power of grep, etc. The rest of what you wrote below is very clear and enlightening, and just right for my level. Are you a teacher? Ever thought about writing a Python book? > > WOW! I didn't implement John's change because I didn't understand it. > > Haven't dealt with dictionaries yet. > >Sorry about that. > >I think, basically, your project is in two parts: a "tokenization" >part and a "counting" part. > >By tokenization, I mean the act of splitting up your input text into >words (or "tokens"). This is the bit where there's no obvious right >way, and you will probably need some ad-hoc code. > >Once you've done that, you move to the counting step: You have a list >of words, and you want to count occurrences of each word. > >Think about how you would do such a task by hand with pen and paper. >One approach you could take is to find the first word, then look >through the document counting how many times the first word occurs. >Then move to the second word, and look through the document again. >You will end up looking through the entire document many times. > >But then you might think to yourself --- "When I count the first word, >I have to _look at_ every other word in the document. Why can't I >count them at the same time?" So you grab a piece of paper, write the >words along the top, and underneath each word you keep a tally. You >look through your document, and for each word, you increase the >corresponding tally. When you're done, you have a count of every >word, and you've only gone through your document once. #My code for word in L: k = L.count(word) if (k,word) not in F: F.append((k,word)) I wrote this quickly and it worked correctly--I was even proud of myself; I didn't think about how it did what it did--that it would repeatedly and unnecessarily look at each element of L and do too much with F as well (as Kent pointed out). Take L.count(word). I had this vague notion that it would take a quick look at all of L at once and come up with a count without actually counting, the way I can see a group of starlings in my back yard and know there are 4 without actually counting them. However, 5 or more I count. But computers are magical, and not limited to 4, was my non-thinking thinking. >This is the basic idea of the dictionary-based approach. A dictionary >is an efficient data structure for keeping these tallies. In Big-O >notation, it is O(1). Any python tutorial can tell you more about >dictionaries. > >Hope this helps :-) > > > Ah. But how can I know what is in C code and what isn't? For example, in > > a previous post you say that L.extend(e) is in C, and imply that > > L.append(e) isn't, and that therefore L.extend(e) should be used. > >The first rule about optimization is --- don't. Unless you're really >sure that you need to. > >I think a good general strategy is: > - If there is a builtin function that does what you want, use it. >This does require you to be familiar with the standard library. The >most important sections are probably the sections on strings, lists, >and dictionaries. > - Know where loops occur. For example, if you say something like "x >in A" where A is a list, that may require checking every element of A. > Then think about which loops are necessary, and which could be >avoided or combined with others. Thank you, John. Dick From enas_khalil at yahoo.com Wed Oct 12 12:01:33 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Wed, 12 Oct 2005 03:01:33 -0700 (PDT) Subject: [Tutor] another error in tagging program In-Reply-To: Message-ID: <20051012100134.2963.qmail@web30512.mail.mud.yahoo.com> hello all i have run the following code : # the taggerI interface from nltk.tagger import * from nltk.tokenizer import WhitespaceTokenizer from nltk.tokenizer import * from nltk.token import * # Using UnigramTagger ##Before aUnigramTagger can be used to tag data ,it must be trained on training corpus, # it uses this corpus to determine which tags are most common for each word . UnigramTaggers # are trained using the train method which takes a tagged corpus: # tag2.txt is a tagged trainning corpus tagged_txt_str=open('tag2.txt').read() tagged_txt_token=Token(TEXT=tagged_txt_str) WhitespaceTokenizer().tokenize(tagged_txt_token) #TaggedTokenizer().tokenize(tagged_txt_token) #Tagger().tokenize(tagged_txt_token) tagger=UnigramTagger() tagger.train(tagged_txt_token) and got the following error : Traceback (most recent call last): File "F:\MSC first Chapters\error correct.py", line 19, in -toplevel- tagger.train(tagged_txt_token) File "C:\Python24\Lib\site-packages\nltk\tagger\__init__.py", line 332, in train tag = subtok[TAG] KeyError: 'TAG' >>> please help thanks enas --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/a458f43c/attachment.html From alan.gauld at freenet.co.uk Wed Oct 12 15:00:18 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 14:00:18 +0100 Subject: [Tutor] Please look at my wordFrequency.py References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com><5e58f2e40510111509x3c0eee28n@mail.gmail.com> <6.2.1.2.2.20051012004506.02c1d5b0@rcblue.com> Message-ID: <005101c5cf2c$e60ba280$0a01a8c0@xp> > See Also:Mastering Regular Expressions Book on regular expressions by > Jeffrey Friedl, published by O'Reilly. The second edition of the book no > longer covers Python at all, but the first edition covered writing good > regular expression patterns in great detail. " > > So I'd like to ask if there is agreement about the value of this book, This is the bible of regular expressions, without peer. > and if the 1st is really better that the 2nd ed. for regex in Python. DEbateable, the second covers some more modern additions to the RE catalog but misses Python out. The first inclyudes Python but misses the atest/greatest. Either edition is invaluable, you only need one so if you have the first don't worry about getting the second IMHO. > further information and a gentler presentation, consult the Regular > Expression HOWTO, accessible from > http://www.python.org/doc/howto/." If you want an even gentler intro - really an intro to the intro - look at the RE page on my tutorial. It covers the very basic concepts. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Wed Oct 12 16:12:06 2005 From: wescpy at gmail.com (w chun) Date: Wed, 12 Oct 2005 07:12:06 -0700 Subject: [Tutor] another error in tagging program In-Reply-To: <20051012100134.2963.qmail@web30512.mail.mud.yahoo.com> References: <20051012100134.2963.qmail@web30512.mail.mud.yahoo.com> Message-ID: <78b3a9580510120712t70ab3b6m5e74ab2f0adb09ec@mail.gmail.com> On 10/12/05, enas khalil wrote: > > and got the following error : > Traceback (most recent call last): > File "F:\MSC first Chapters\error correct.py", line 19, in -toplevel- > tagger.train(tagged_txt_token) > File > "C:\Python24\Lib\site-packages\nltk\tagger\__init__.py", > line 332, in train > tag = subtok[TAG] > KeyError: 'TAG' > >>> > please help > thanks > enas this error is due to TAG = 'TAG' and this key not being in your subtok dictionary. what are you trying to accomplish in your application? it looks like you are following a lesson plan of a course in natural language processing. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From john.ertl at fnmoc.navy.mil Wed Oct 12 16:27:37 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed, 12 Oct 2005 07:27:37 -0700 Subject: [Tutor] launching and monitor from make Message-ID: All, I have a very simple python program that reads one file and overwrites anouther text file. This workes great from the command line and it has error checking but just outputs messages and the like to the screen. The CM team here would like to have the script run each week as part of the automated rebuilds. The suggestion was to make the execution of the scritp part of the bigger programs make file. How would I handel errors when the program is run from a makefile? I hate make so I have not done a lot of playing with what make can do in this respect but can python get an error message to make? Thanks, John Ertl From cpu.crazy at gmail.com Wed Oct 12 17:07:43 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 12 Oct 2005 09:07:43 -0600 Subject: [Tutor] slide show won't display the images in right order Message-ID: <434D26BF.6050808@gmail.com> Hi, Here's my directory listing as a list: ['ga041001.gif', 'ga041002.gif', 'ga041003.gif', 'ga041004.gif', 'ga041005.gif', 'ga041006.gif', 'ga041007.gif', 'ga041008.gif', 'ga041009.gif', 'ga041010.gif', 'ga041011.gif', 'ga000619.gif', 'ga050101.gif', 'ga050102.gif', 'ga050103.gif', 'ga050104.gif', 'ga050105.gif', 'ga050106.gif', 'ga050107.gif', 'ga050108.gif', 'ga050109.gif', 'ga050111.gif', 'ga050112.gif', 'ga050113.gif', 'ga050801.gif', 'ga050114.gif', 'ga050802.gif', 'ga050115.gif', 'ga050803.gif', 'ga050116.gif', 'ga050804.gif', 'ga050117.gif', 'ga050805.gif', 'ga050118.gif', 'ga050806.gif', 'ga050119.gif', 'ga050807.gif', 'ga050121.gif', 'ga050122.gif', 'ga050123.gif', 'ga050124.gif', 'ga050125.gif', 'ga780825.gif', 'ga780826.gif', 'ga780827.gif', 'ga780828.gif', 'ga780829.gif', 'ga780830.gif'] When I use: files = os.listdir() x = 0 direction = 1 while True: ShowImg(files[x]) # An image display function x += -1 it doesn't display the images in the right order! It will skip from ga050123.gif and go to ga050120.gif! Is there any way to counter this? Thanks, Joe PS> This is a console version of the Tkinter version I want to make (where I posted earlier). Console is just way easier! :-) From john.ertl at fnmoc.navy.mil Wed Oct 12 17:33:33 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed, 12 Oct 2005 08:33:33 -0700 Subject: [Tutor] launching and monitor from make Message-ID: Ewald, That easy...If you know. Thanks for the example and the help. Now lets see if I can modify the make file without upsetting the make god. Thanks again. John Ertl -----Original Message----- From: Ewald Ertl [mailto:ewald.ertl at hartter.com] Sent: Wednesday, October 12, 2005 7:40 AM To: Ertl, John Subject: Re: [Tutor] launching and monitor from make Hi John Ertl, John wrote: > All, > > I have a very simple python program that reads one file and overwrites > anouther text file. This workes great from the command line and it has > error checking but just outputs messages and the like to the screen. > > The CM team here would like to have the script run each week as part of the > automated rebuilds. The suggestion was to make the execution of the scritp > part of the bigger programs make file. How would I handel errors when the > program is run from a makefile? I hate make so I have not done a lot of > playing with what make can do in this respect but can python get an error > message to make? I think your Python-Script is an executeable "Shell"-Script with "#!/usr/bin/env python ... " So you can just insert your script in the makefile When the exit-Code of the script is 0, than make assumes that everything is ok, otherwise an error occured. Here's a short example with "ls" Here the mkfile want's to list the file "hugo" which does not exist mkfile: all: ls -l hugo -------------- #gmake -f mkfile ls -l hugo hugo: Datei oder Verzeichnis nicht gefunden gmake: *** [all] Error 2 Here the mkfile itself is listed with ls mkfile: all: ls -l mkfile ---------- #gmake -f mkfile ls -l mkfile -rw-rw-r-- 1 ewer entw 19 Okt 12 16:35 mkfile HTH Ewald Ertl From digitalsuicide at gmail.com Wed Oct 12 17:22:23 2005 From: digitalsuicide at gmail.com (dataw0lf) Date: Wed, 12 Oct 2005 09:22:23 -0600 Subject: [Tutor] slide show won't display the images in right order In-Reply-To: <434D26BF.6050808@gmail.com> References: <434D26BF.6050808@gmail.com> Message-ID: <434D2A2F.2000400@gmail.com> Joseph Quigley wrote: > When I use: > files = os.listdir() > x = 0 > direction = 1 > while True: > ShowImg(files[x]) # An image display function > x += -1 > > it doesn't display the images in the right order! It will skip from > ga050123.gif and go to ga050120.gif! Why not do something like this? : files = os.listdir() for file in files: ShowImg(file) I'm also curious as to what context the 'direction' variable was being used in. Cheers. -- Joshua Simpson -- dataw0lf.org Lead Network Administrator/Engineer Aero-Graphics Inc. jsimpson at aero-graphics.com From rdm at rcblue.com Wed Oct 12 17:35:57 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 12 Oct 2005 08:35:57 -0700 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <005101c5cf2c$e60ba280$0a01a8c0@xp> References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> <5e58f2e40510111509x3c0eee28n@mail.gmail.com> <6.2.1.2.2.20051012004506.02c1d5b0@rcblue.com> <005101c5cf2c$e60ba280$0a01a8c0@xp> Message-ID: <6.2.1.2.2.20051012082616.04920eb0@rcblue.com> Alan Gauld wrote at 06:00 10/12/2005: > > See Also:Mastering Regular Expressions Book on regular expressions by > > Jeffrey Friedl, published by O'Reilly. The second edition of the book no > > longer covers Python at all, but the first edition covered writing good > > regular expression patterns in great detail. " > > > > So I'd like to ask if there is agreement about the value of this book, > >This is the bible of regular expressions, without peer. > > > and if the 1st is really better that the 2nd ed. for regex in Python. > >DEbateable, the second covers some more modern additions to the RE catalog >but misses Python out. The first inclyudes Python but misses the >atest/greatest. >Either edition is invaluable, you only need one so if you have the first >don't >worry about getting the second IMHO. Thanks for the advice. > > further information and a gentler presentation, consult the Regular > > Expression HOWTO, accessible from > > http://www.python.org/doc/howto/." > >If you want an even gentler intro - really an intro to the intro - look at >the >RE page on my tutorial. It covers the very basic concepts. Looks great! http://www.freenetpages.co.uk/hp/alan.gauld The regex HOWTO, above, mentions, in section 3.3, a tool that comes with Python 2.4 for practicing/testing regex. Tools/scripts/redemo.py . Can you recommend this? And how about Kodos? () Dick From kent37 at tds.net Wed Oct 12 17:37:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 11:37:43 -0400 Subject: [Tutor] slide show won't display the images in right order In-Reply-To: <434D26BF.6050808@gmail.com> References: <434D26BF.6050808@gmail.com> Message-ID: <434D2DC7.7000400@tds.net> Joseph Quigley wrote: > Hi, > Here's my directory listing as a list: > ['ga041001.gif', 'ga041002.gif', 'ga041003.gif', 'ga041004.gif', > 'ga041005.gif', 'ga041006.gif', 'ga041007.gif', 'ga041008.gif', > 'ga041009.gif', 'ga041010.gif', 'ga041011.gif', 'ga000619.gif', > 'ga050101.gif', 'ga050102.gif', 'ga050103.gif', 'ga050104.gif', > 'ga050105.gif', 'ga050106.gif', 'ga050107.gif', 'ga050108.gif', > 'ga050109.gif', 'ga050111.gif', 'ga050112.gif', 'ga050113.gif', > 'ga050801.gif', 'ga050114.gif', 'ga050802.gif', 'ga050115.gif', > 'ga050803.gif', 'ga050116.gif', 'ga050804.gif', 'ga050117.gif', > 'ga050805.gif', 'ga050118.gif', 'ga050806.gif', 'ga050119.gif', > 'ga050807.gif', 'ga050121.gif', 'ga050122.gif', 'ga050123.gif', > 'ga050124.gif', 'ga050125.gif', 'ga780825.gif', 'ga780826.gif', > 'ga780827.gif', 'ga780828.gif', 'ga780829.gif', 'ga780830.gif'] > > When I use: > files = os.listdir() > x = 0 > direction = 1 > while True: > ShowImg(files[x]) # An image display function > x += -1 > > it doesn't display the images in the right order! It will skip from > ga050123.gif and go to ga050120.gif! > > Is there any way to counter this? os.listdir() doesn't guarantee any particular order for the results. How about sorting the list? files = os.listdir(...) files.sort() ...etc Kent > Thanks, > Joe > > PS> This is a console version of the Tkinter version I want to make > (where I posted earlier). Console is just way easier! :-) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Wed Oct 12 18:05:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 12:05:20 -0400 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <6.2.1.2.2.20051012082616.04920eb0@rcblue.com> References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> <5e58f2e40510111509x3c0eee28n@mail.gmail.com> <6.2.1.2.2.20051012004506.02c1d5b0@rcblue.com> <005101c5cf2c$e60ba280$0a01a8c0@xp> <6.2.1.2.2.20051012082616.04920eb0@rcblue.com> Message-ID: <434D3440.5000907@tds.net> Dick Moores wrote: > The regex HOWTO, above, mentions, in section 3.3, a tool that comes with > Python 2.4 for practicing/testing regex. Tools/scripts/redemo.py . Can > you recommend this? And how about Kodos? () Yes, it's very handy. Try it! Kodos is similar. I think there are versions for just about every Python GUI toolkit but they all have more or less the same features. Kodos requires PyQT, redemo.py uses Tkinter. Kent From stever at insightbb.com Wed Oct 12 18:41:16 2005 From: stever at insightbb.com (Steve Robb) Date: Wed, 12 Oct 2005 11:41:16 -0500 Subject: [Tutor] Problem with Winpdb. Message-ID: <434D3CAC.1080803@insightbb.com> Can anyone point me to what the problem may be with running Winpdb? I am running Win98, unfortunately, Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7. I have python 2.4, Python 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] on win32. I have Winpdb, WINPDB_VERSION = "WINPDB_1_0_4". I have Crypto, print Crypto.__version__ 2.0.1. I have wxPython, print wxPython.__version__ 2.6.1.0. I have thread, Directory of C:\Python24\Lib\site-packages\pythonwin\pywin\mfc THREAD PY 541 09-14-05 11:53a thread.py THREAD PYC 1,140 09-14-05 11:53a thread.pyc THREAD PYO 1,140 09-14-05 11:53a thread.pyo I seem to be able to execute _rpdb2.py in a MS-DOS command window by using the following, ..\python _rpdb2.py, while in the \python24\scripts directory. However, when I try, ..\python _winpdb.py, from the same directory, I get the following traceback. Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Python24\Scripts\_winpdb.py", line 31, in ? winpdb.main() File "C:\Python24\Lib\site-packages\winpdb.py", line 3269, in main return rpdb2.main(StartClient) File "C:\Python24\Lib\site-packages\rpdb2.py", line 6844, in main StartClient_func('', fAttach, fchdir, pwd, fAllowUnencrypted, fRemote, host) File "C:\Python24\Lib\site-packages\winpdb.py", line 3259, in StartClient app = CWinpdbApp(sm, fchdir, command_line, fAttach, fAllowUnencrypted) File "C:\Python24\Lib\site-packages\winpdb.py", line 1526, in __init__ wx.App.__init__(self, redirect = False) File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", line 7473, in __init__ self._BootstrapApp() File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", line 7125, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "C:\Python24\Lib\site-packages\winpdb.py", line 1531, in OnInit self.m_settings.load_settings() File "C:\Python24\Lib\site-packages\winpdb.py", line 632, in load_settings path = self.calc_path() File "C:\Python24\Lib\site-packages\winpdb.py", line 607, in calc_path app_data = os.environ['APPDATA'] File "C:\PYTHON24\lib\os.py", line 422, in __getitem__ return self.data[key.upper()] KeyError: 'APPDATA' Thanks in advance for any help, Steve From alan.gauld at freenet.co.uk Wed Oct 12 19:00:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 18:00:30 +0100 Subject: [Tutor] launching and monitor from make References: Message-ID: <007701c5cf4e$742c5bb0$0a01a8c0@xp> > The CM team here would like to have the script run each week as part of > the > automated rebuilds. The suggestion was to make the execution of the > scritp > part of the bigger programs make file. How would I handel errors when the > program is run from a makefile? I hate make so I have not done a lot of > playing with what make can do in this respect but can python get an error > message to make? You can write the errors to stderr instead of stdout. You can also exit with an error code using sys.exit(). make should detect the non standard error code because it uses standard shell processing.. Alan G From alan.gauld at freenet.co.uk Wed Oct 12 19:02:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 18:02:42 +0100 Subject: [Tutor] slide show won't display the images in right order References: <434D26BF.6050808@gmail.com> Message-ID: <007b01c5cf4e$c29831c0$0a01a8c0@xp> > When I use: > files = os.listdir() Have you tried printing 'files'? Are they in order there? > it doesn't display the images in the right order! It will skip from > ga050123.gif and go to ga050120.gif! I suspect listdir doesn't use name order. You probably need to do a sort() on the files list. hth, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Oct 12 19:04:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 18:04:38 +0100 Subject: [Tutor] Please look at my wordFrequency.py References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com><5e58f2e40510111509x3c0eee28n@mail.gmail.com><6.2.1.2.2.20051012004506.02c1d5b0@rcblue.com><005101c5cf2c$e60ba280$0a01a8c0@xp> <6.2.1.2.2.20051012082616.04920eb0@rcblue.com> Message-ID: <008301c5cf4f$079be370$0a01a8c0@xp> > The regex HOWTO, above, mentions, in section 3.3, a tool that comes with > Python 2.4 for practicing/testing regex. Tools/scripts/redemo.py . Can you > recommend this? And how about Kodos? () Yes I can recommend it, its a great tool for trying REs out Alan G. From john.ertl at fnmoc.navy.mil Wed Oct 12 19:14:43 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed, 12 Oct 2005 10:14:43 -0700 Subject: [Tutor] launching and monitor from make Message-ID: Alan, Thanks, just as you and Ewald said it works great. Almost too easy...I have this feeling something will turn around a bite me once it goes to ops. Thanks again John Ertl -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: Wednesday, October 12, 2005 10:01 AM To: Ertl, John; tutor at python.org Subject: Re: [Tutor] launching and monitor from make > The CM team here would like to have the script run each week as part of > the > automated rebuilds. The suggestion was to make the execution of the > scritp > part of the bigger programs make file. How would I handel errors when the > program is run from a makefile? I hate make so I have not done a lot of > playing with what make can do in this respect but can python get an error > message to make? You can write the errors to stderr instead of stdout. You can also exit with an error code using sys.exit(). make should detect the non standard error code because it uses standard shell processing.. Alan G From jeffpeery at yahoo.com Wed Oct 12 19:42:21 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 12 Oct 2005 10:42:21 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <20051012174222.96457.qmail@web30503.mail.mud.yahoo.com> hello, I am trying to find the source code for FFT. I found the FFT.py module athough I cannot find the actual code that runs the FFT. Is it in a compiled form or can I view its source? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/b8431456/attachment.htm From kent37 at tds.net Wed Oct 12 19:55:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 13:55:24 -0400 Subject: [Tutor] (no subject) In-Reply-To: <20051012174222.96457.qmail@web30503.mail.mud.yahoo.com> References: <20051012174222.96457.qmail@web30503.mail.mud.yahoo.com> Message-ID: <434D4E0C.3010005@tds.net> Jeff Peery wrote: > hello, I am trying to find the source code for FFT. I found the FFT.py > module athough I cannot find the actual code that runs the FFT. Is it in > a compiled form or can I view its source? Which FFT (where did you get fft.py)? you asked this same question in August, here is what I said then: http://aspn.activestate.com/ASPN/Mail/Message/2765231 Kent From rdm at rcblue.com Wed Oct 12 20:00:39 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 12 Oct 2005 11:00:39 -0700 Subject: [Tutor] Please look at my wordFrequency.py In-Reply-To: <008301c5cf4f$079be370$0a01a8c0@xp> References: <6.2.1.2.2.20051011121035.07a75af0@rcblue.com> <5e58f2e40510111509x3c0eee28n@mail.gmail.com> <6.2.1.2.2.20051012004506.02c1d5b0@rcblue.com> <005101c5cf2c$e60ba280$0a01a8c0@xp> <6.2.1.2.2.20051012082616.04920eb0@rcblue.com> <008301c5cf4f$079be370$0a01a8c0@xp> Message-ID: <6.2.1.2.2.20051012105755.08e72480@rcblue.com> Alan Gauld wrote at 10:04 10/12/2005: > > The regex HOWTO, above, mentions, in section 3.3, a tool that comes with > > Python 2.4 for practicing/testing regex. Tools/scripts/redemo.py . > Can you > > recommend this? And how about Kodos? () > >Yes I can recommend it, its a great tool for trying REs out > >Alan G. Sorry, I assume you mean redemo.py? Do you know Kodos? Thanks, Dick From marc_buehler at yahoo.com Wed Oct 12 20:10:28 2005 From: marc_buehler at yahoo.com (Marc Buehler) Date: Wed, 12 Oct 2005 11:10:28 -0700 (PDT) Subject: [Tutor] how to extract number of files from directory Message-ID: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> hi. i'm new to Python ... i would like to extract the number of JPG files from the current directory and use that number as a parameter in my python script. i tried: a = os.system('ls *JPG | wc -l') when i do: print a i get '0'. what am i missing? marc --------------------------------------------------------------------------------------- The apocalyptic vision of a criminally insane charismatic cult leader http://www.marcbuehler.net ---------------------------------------------------------------------------------------- __________________________________ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ From falcon3166 at hotmail.com Wed Oct 12 20:11:37 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 12 Oct 2005 12:11:37 -0600 Subject: [Tutor] Can anyone teach me...? Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/17640946/attachment.html From kent37 at tds.net Wed Oct 12 20:29:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 14:29:15 -0400 Subject: [Tutor] how to extract number of files from directory In-Reply-To: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> References: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> Message-ID: <434D55FB.9070208@tds.net> Marc Buehler wrote: > i would like to extract the number of JPG files > from the current directory and use that number > as a parameter in my python script. > i tried: > a = os.system('ls *JPG | wc -l') > when i do: > print a > i get '0'. > > what am i missing? os.system() returns the exit code of the program, not the output. You can run an external program and capture the output, but generally you should look for a solution within Python before resorting to external programs. In this case, try import glob a = len(glob.glob('*.JPG')) Kent From john.ertl at fnmoc.navy.mil Wed Oct 12 20:46:47 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed, 12 Oct 2005 11:46:47 -0700 Subject: [Tutor] how to extract number of files from directory Message-ID: Marc, You can do most system type stuff in Python and it makes it much easier. import glob jpgList = glob.glob("*.jpg") # the glob allows you to use wild cards in the search jpgCount = len(jpgList) This gives you a list of all files that end in .jpg. You can then do a len(jpgList) to get the number of files John -----Original Message----- From: Marc Buehler [mailto:marc_buehler at yahoo.com] Sent: Wednesday, October 12, 2005 11:10 AM To: tutor at python.org Subject: [Tutor] how to extract number of files from directory hi. i'm new to Python ... i would like to extract the number of JPG files from the current directory and use that number as a parameter in my python script. i tried: a = os.system('ls *JPG | wc -l') when i do: print a i get '0'. what am i missing? marc ---------------------------------------------------------------------------- ----------- The apocalyptic vision of a criminally insane charismatic cult leader http://www.marcbuehler.net ---------------------------------------------------------------------------- ------------ __________________________________ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ewalker at micron.com Wed Oct 12 20:48:49 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 12 Oct 2005 12:48:49 -0600 Subject: [Tutor] how to extract number of files from directory In-Reply-To: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> References: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> Message-ID: <200510121248.49826.ewalker@micron.com> I think os.system returns status of commands Try this: w = os.popen('ls -l | wc -l').readlines() Python Newbie... On Wednesday 12 October 2005 12:10 pm, Marc Buehler wrote: > hi. > > i'm new to Python ... > > i would like to extract the number of JPG files > from the current directory and use that number > as a parameter in my python script. > i tried: > a = os.system('ls *JPG | wc -l') > when i do: > print a > i get '0'. > > what am i missing? > > marc > > --------------------------------------------------------------------------- >------------ The apocalyptic vision of a criminally insane charismatic cult > leader > > http://www.marcbuehler.net > --------------------------------------------------------------------------- >------------- > > > > __________________________________ > Yahoo! Music Unlimited > Access over 1 million songs. Try it free. > http://music.yahoo.com/unlimited/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From jeffpeery at yahoo.com Wed Oct 12 20:55:46 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 12 Oct 2005 11:55:46 -0700 (PDT) Subject: [Tutor] comiling python to microchip? Message-ID: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> is it possible to take python code and compile it for use in a microprocessor? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/6e709aa3/attachment.htm From wescpy at gmail.com Wed Oct 12 21:24:45 2005 From: wescpy at gmail.com (w chun) Date: Wed, 12 Oct 2005 12:24:45 -0700 Subject: [Tutor] how to extract number of files from directory In-Reply-To: References: Message-ID: <78b3a9580510121224t43b9add2x1a58be53f9f41e03@mail.gmail.com> On 10/12/05, Ertl, John wrote: > > You can do most system type stuff in Python and it makes it much easier. > import glob > jpgList = glob.glob("*.jpg") # the glob allows you to use wild cards in > the > search > jpgCount = len(jpgList) > This gives you a list of all files that end in .jpg. You can then do a > len(jpgList) to get the number of files > John > glob seems to be a good idea, but is there a way to do it case-insensitively, i.e., .jpg and .JPG? it may be slower than glob, but i'm finding myself thinking more like... len([i for i in os.listdir('tmp') if i.lower().endswith('.jpg')]) now, anyone with a solution for .jpg, .JPG, .jpeg, *and* .JPEG? -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/23ecec61/attachment.html From kent37 at tds.net Wed Oct 12 21:37:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 15:37:59 -0400 Subject: [Tutor] how to extract number of files from directory In-Reply-To: <78b3a9580510121224t43b9add2x1a58be53f9f41e03@mail.gmail.com> References: <78b3a9580510121224t43b9add2x1a58be53f9f41e03@mail.gmail.com> Message-ID: <434D6617.7070302@tds.net> w chun wrote: > glob seems to be a good idea, but is there a way to do it > case-insensitively, i.e., .jpg and .JPG? > > it may be slower than glob, but i'm finding myself thinking more like... > > len([i for i in os.listdir('tmp') if i.lower().endswith('.jpg')]) > > now, anyone with a solution for .jpg, .JPG, .jpeg, *and* .JPEG? glob.glob('*.[jJ][pP][eE]?[gG]') ?? or maybe (not sure this is legal; I'm pretty sure it's ugly :-) len([i for i in os.listdir('tmp') for suffix in ['.jpg', '.jpeg'] if i.lower().endswith(suffix)]) Kent > > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2006,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Wed Oct 12 22:01:48 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 21:01:48 +0100 Subject: [Tutor] how to extract number of files from directory References: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> Message-ID: <00b301c5cf67$c7f328f0$0a01a8c0@xp> > a = os.system('ls *JPG | wc -l') > when i do: > print a > i get '0'. os.system only returns the exitcode of the command not the output. Look at the new Subprocess module and its Popen class. It can look intimidating at first but read the examples and you should find it easy enough. Altrernatively try the commands module although subprocess is intended to replace it... However you might find it easier to use the python os tools like listdir to do the job directly. a = len(os.listdir(mydir, '*JPG') Should be about right... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Oct 12 22:06:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 21:06:09 +0100 Subject: [Tutor] Can anyone teach me...? References: Message-ID: <00b601c5cf68$63081670$0a01a8c0@xp> Hello again Nathan, > When I said that I might go to Visual Basic in an earlier message, > someone replied by saying that I should ask here how to do it in Python. > Well, I'm asking now: Can anyone teach me how to make a simple > program that uses a GUI? Take a look at the GUI section of my tutorial and then look at the case study topic which turns a command-line program into a GUI. Then go and read the specialist TKinter or wxPython documentation and tutorials. You might also like projects like PythonCard which provide basic graphical GUI building tools. However I have to be honest and say that building GUIs in VB (or Borland's Delphi/Kylix) is a lot easier than in Python IMHO. I use Delphi for most of my real-world heavy duty GUI work. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Oct 12 22:17:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 16:17:30 -0400 Subject: [Tutor] how to extract number of files from directory In-Reply-To: <00b301c5cf67$c7f328f0$0a01a8c0@xp> References: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> <00b301c5cf67$c7f328f0$0a01a8c0@xp> Message-ID: <434D6F5A.4050607@tds.net> Alan Gauld wrote: > a = len(os.listdir(mydir, '*JPG') > > Should be about right... No, os.listdir() only takes one argument, the directory. See the solutions with glob.glob(). Kent From murtog at gmail.com Wed Oct 12 22:26:06 2005 From: murtog at gmail.com (Murtog) Date: Wed, 12 Oct 2005 20:26:06 +0000 Subject: [Tutor] slide show won't display the images in right order In-Reply-To: <007b01c5cf4e$c29831c0$0a01a8c0@xp> References: <434D26BF.6050808@gmail.com> <007b01c5cf4e$c29831c0$0a01a8c0@xp> Message-ID: The correct code looks like this: files = os.listdir() files.sort() x = 0 direction = 1 while True: ShowImg(files[x]) # An image display function x += -1 -- Cheers, Murtog -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/3d02ac5a/attachment.htm From ml.cyresse at gmail.com Wed Oct 12 14:17:17 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 13 Oct 2005 01:17:17 +1300 Subject: [Tutor] __slots__ Message-ID: If you've been wondering about how useful this is... Well, all I can say is, don't use them unless you need them, they're a lot of hassle. I created two versions of the same object, same attribute values, one with slots, one without. With slots, it pickled to a string of 163 characters. Without, 341.That's 178 bytes saved, rough approximation. So, if I create 5000 objects, I've saved somewhere around 900Kb of RAM. At 500,000 objects I'd be saving roughly 86Mb of RAM, assuming that a pickled object corresponds to one in memory. Or, 86Mb of HD space. Of course, having to learn what __getstate__ was in order to pickle the slotted instance wasn't much fun. Remember, premature optimisation is bad... This was a smaller object, so it'll be interesting to see what economy an object with 70ish attributes makes. FWIW, I'm doing the exact opposite of XP, and building to handle 300,000 to 600,000 objects... Regards, Liam Clarke From alan.gauld at freenet.co.uk Wed Oct 12 23:46:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 22:46:05 +0100 Subject: [Tutor] comiling python to microchip? References: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> Message-ID: <00d001c5cf76$59618120$0a01a8c0@xp> From: "Jeff Peery" > is it possible to take python code and compile it for use in a > microprocessor? > In the same way that Sun have been threatening to build a chip that has Java as its machine code then it would be possible to build a chip that ran Python bytecode but it would be a huge investment. Its certainly not possible woth current Python to generate code that can run outside of an operating system on a microchip. ON the otherhand if that chop is running even a basic operating system that supports a C compiler then it should be possible to build the Python interpreter for the chip/OS combo and use python that way. In other words, no, you can't currently get a completely standalone machine code program from Python code at present. It would be feasible to port Python to most micro chip OSs such as CP/M, PSOS, QXL(?) etc and its possible that some such port has already been done but I don't know of it. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Oct 12 23:47:52 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 22:47:52 +0100 Subject: [Tutor] how to extract number of files from directory References: <78b3a9580510121224t43b9add2x1a58be53f9f41e03@mail.gmail.com> Message-ID: <00d601c5cf76$991073d0$0a01a8c0@xp> > glob seems to be a good idea, ... Yep, I got my glob and listdir mixed up earlier... > it may be slower than glob, but i'm finding myself thinking more like... > len([i for i in os.listdir('tmp') if i.lower().endswith('.jpg')]) > > now, anyone with a solution for .jpg, .JPG, .jpeg, *and* .JPEG? Sounds like a job for a regex? Alan G. From alan.gauld at freenet.co.uk Wed Oct 12 23:49:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 22:49:56 +0100 Subject: [Tutor] how to extract number of files from directory References: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com><00b301c5cf67$c7f328f0$0a01a8c0@xp> <434D6F5A.4050607@tds.net> Message-ID: <00e401c5cf76$e2d90090$0a01a8c0@xp> >> a = len(os.listdir(mydir, '*JPG') >> >> Should be about right... > > No, os.listdir() only takes one argument, the directory. See the solutions > with glob.glob(). Oops! Quite right, my mistake. (As is the missing right paren!) Alan g. From ml.cyresse at gmail.com Wed Oct 12 11:45:52 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 12 Oct 2005 22:45:52 +1300 Subject: [Tutor] Struct headspinner Message-ID: Hi all, Erm, can someone please aid me? I'm using Windows XP, haven't tested this code on Linux yet, but, well watch this... '<' indicates little-endian, @ indicates native. i is an integer, q is a long. >>> struct.calcsize('<3i') 12 >>> struct.calcsize('@3i') 12 >>> struct.calcsize('<3iq') 20 >>> struct.calcsize('@3iq') 24 >>> struct.calcsize('@4iq') 24 Is this a feature I don't understand? Is a long preceded by 3 integers really 12 bytes long? Surely Microsoft wouldn't do that? Regards, Liam Clarke From alan.gauld at freenet.co.uk Wed Oct 12 23:53:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Oct 2005 22:53:38 +0100 Subject: [Tutor] __slots__ References: Message-ID: <00e801c5cf77$67284f40$0a01a8c0@xp> > an object with 70ish attributes makes. FWIW, I'm doing the exact > opposite of XP, and building to handle 300,000 to 600,000 objects... As a matter of interest why do you need so many in RAM at once? Its very unusual to require that many and there are techniques to minimise the space by using 'phantom' objects and only pulling in the data as needed (so called 'late evaluation'). If you tell us more about the problem context we might be able to help make the solution simpler. Alan G. From rabidpoobear at gmail.com Wed Oct 12 20:27:45 2005 From: rabidpoobear at gmail.com (luke p) Date: Wed, 12 Oct 2005 13:27:45 -0500 Subject: [Tutor] Can anyone teach me...? In-Reply-To: References: Message-ID: nathan, there are a few GUI options available to you. the one that is bundled with the python installation is TKInter. that's an "i" not an "L". you can also use the python interface for WxWindows, I forget what it's called. anyway, TKInter looks fairly nice, some say it doesn't have the windows "feel" to it as much as WxWindows but who really cares because it's pretty easy to learn etc. There's a tutorial somewher eon the web written by some New Mexico thing I'm not sure but I have to run to class so I can't look it up. anyway, Give google a workout and learn as much as you can on your own. I don't think you should ask any questions that you could solve yourself, or you may aggravate the list. so try as much as you can and then if you get stuck ask someone. Go for TKInter I think you'll like it. Alan Gauld might have a tutorial for TKInter, you could check that out too. good luck. On 10/12/05, Nathan Pinno wrote: > > Hey all, > > When I said that I might go to Visual Basic in an earlier message, someone > replied by saying that I should ask here how to do it in Python. Well, I'm > asking now: Can anyone teach me how to make a simple program that uses a > GUI? > > Thanks, > > Nathan Pinno > Crew, McDonalds Restaurant and fan extraordinare of the Oilers. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/1d0a74fe/attachment.html From tim.peters at gmail.com Thu Oct 13 00:08:42 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 12 Oct 2005 18:08:42 -0400 Subject: [Tutor] Struct headspinner In-Reply-To: References: Message-ID: <1f7befae0510121508v2d3b8139u3457f8f66434043f@mail.gmail.com> [Liam Clarke] > Erm, can someone please aid me? I'm using Windows XP, haven't tested > this code on Linux yet, but, well watch this... > > '<' indicates little-endian, @ indicates native. i is an integer, Yes x 3. > q is a long. No. q in native mode is C "long long" on Linux, or "_int64" on Windows. It's an 8-byte integer in standard modes.. "i" is a 4-byte integer in standard modes, same as C "int" in native modes. "l" is the format code for long, but none of your examples use that. > >>> struct.calcsize('<3i') > 12 3 std integers x 4 bytes each = 12. > >>> struct.calcsize('@3i') > 12 Same thing. > >>> struct.calcsize('<3iq') > 20 12 + 1 8-byte standard int = 20. > >>> struct.calcsize('@3iq') > 24 _int64 is 8-byte aligned on Windows, so that's 12 bytes + 4 bytes padding + 8 bytes = 24 bytes. > >>> struct.calcsize('@4iq') > 24 Same thing; the additional native i fills the padding in the preceding example. > Is this a feature I don't understand? Sorry, I don't know what you're asking. What specifically surprises you here? > Is a long preceded by 3 integers really 12 bytes long? No (and nothing above suggests that it is, either ...). > Surely Microsoft wouldn't do that? And they didn't ;-) From adam.jtm30 at gmail.com Thu Oct 13 00:11:07 2005 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 13 Oct 2005 00:11:07 +0200 Subject: [Tutor] comiling python to microchip? In-Reply-To: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> References: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> Message-ID: On 12/10/05, Jeff Peery wrote: > > is it possible to take python code and compile it for use in a > microprocessor? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Building on what Alan said this may be of some use uClinuxit's an embedded linux operating system for microcontrollers. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/43656074/attachment.htm From kent37 at tds.net Thu Oct 13 00:19:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 18:19:17 -0400 Subject: [Tutor] comiling python to microchip? In-Reply-To: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> References: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> Message-ID: <434D8BE5.106@tds.net> Jeff Peery wrote: > is it possible to take python code and compile it for use in a > microprocessor? I don't think you can compile python code but python itself has been ported to many tiny architectures. Take a look at http://www.python.org/download/download_other.html if you don't see what you want there then ask on comp.lang.python and be specific about your target environment. Kent From kent37 at tds.net Thu Oct 13 00:22:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 18:22:46 -0400 Subject: [Tutor] __slots__ In-Reply-To: References: Message-ID: <434D8CB6.2070308@tds.net> Liam Clarke wrote: > Well, all I can say is, don't use them unless you need them, they're a > lot of hassle. I think the conventional advice is something like, if you don't understand why using slots is a bad idea, you have no business using them :-) > I created two versions of the same object, same attribute values, one > with slots, one without. > > With slots, it pickled to a string of 163 characters. Without, > 341.That's 178 bytes saved, rough approximation. So, if I create 5000 > objects, I've saved somewhere around 900Kb of RAM. Does the size of the pickle correlate to the size of the runtime object? I don't know... Kent > > At 500,000 objects I'd be saving roughly 86Mb of RAM, assuming that a > pickled object corresponds to one in memory. Or, 86Mb of HD space. > > Of course, having to learn what __getstate__ was in order to pickle > the slotted instance wasn't much fun. Remember, premature optimisation > is bad... > > This was a smaller object, so it'll be interesting to see what economy > an object with 70ish attributes makes. FWIW, I'm doing the exact > opposite of XP, and building to handle 300,000 to 600,000 objects... > > Regards, > > Liam Clarke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Thu Oct 13 00:23:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Oct 2005 15:23:57 -0700 (PDT) Subject: [Tutor] Struct headspinner In-Reply-To: Message-ID: On Wed, 12 Oct 2005, Liam Clarke wrote: > Erm, can someone please aid me? I'm using Windows XP, haven't tested > this code on Linux yet, but, well watch this... > > '<' indicates little-endian, @ indicates native. i is an integer, q is a long. > > >>> struct.calcsize('<3i') > 12 > >>> struct.calcsize('@3i') > 12 > >>> struct.calcsize('<3iq') > 20 > >>> struct.calcsize('@3iq') > 24 > >>> struct.calcsize('@4iq') > 24 > > Is this a feature I don't understand? Is a long preceded by 3 integers > really 12 bytes long? Surely Microsoft wouldn't do that? Hi Liam, What you're seeing really has little to do with Microsoft: it has to do with the "alignment" of data structures against your computer's hardware and the underlying C compiler for your system. Most computer architectures will try to make sure that integers and words in memory are always "aligned" on some predefined boundary. It's easier on the decoder hardware if it know exactly where those primitive data types can start. This is mentioned in the comment in the 'struct' documentation: """By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).""" If the bytes that represent an integer are out of frame, then the hardware might be slower about decoding the values in a good case, and might just not be able to decode them at all in a bad case. *grin* 'struct' will introduce "padding" bytes to make sure things are framed up nicely. And we can see this padding in action: a single integer takes up four bytes: ###### >>> struct.calcsize("i") 4 ###### but if we preceed that with a single byte character: ###### >>> struct.calcsize("ci") 8 ###### rather than see that this takes five bytes, we see that it takes eight! The 'struct' module has transparently added three "padding" bytes to make sure the integer aligns in a way that's compatible with the underlying computer hardware. Order matters. Here's another example of an integer followed by a character: ###### >>> struct.calcsize("ic") 5 ###### Nothing follows that character, so no padding is necessary. But again, if we put an integer after that, then we see padding in action: ####### >>> struct.calcsize("ici") 12 >>> struct.calcsize("icci") 12 >>> struct.calcsize("iccci") 12 >>> struct.calcsize("icccci") 12 ####### All of this is meant to guarantee that the second integer is on a memory location that can be efficiently destructured by the computer hardware. Does this make sense? Please feel free to ask more questions on this; it's a bit of a low-level topic. From carroll at tjc.com Thu Oct 13 00:27:09 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed, 12 Oct 2005 15:27:09 -0700 (PDT) Subject: [Tutor] Can anyone teach me...? In-Reply-To: <00b601c5cf68$63081670$0a01a8c0@xp> Message-ID: On Wed, 12 Oct 2005, Alan Gauld wrote: > However I have to be honest and say that building GUIs in VB ... is a > lot easier than in Python IMHO. I have to say, I agree with that. I just started using VB a month ago (for a course I'm taking, all projects need to be in VB), and it's really a pleasure setting up a GUI. But, man, VB as a language and library set is horrible; and pointlessly horrible, in many cases. (I remain astonished by VB's lack of min/max functions, not to mention the lack of inverse cosine and inverse sine functions. I've only been using it for a month, but I'll bet I could find more if I used it more often. VB's slogan should be "Batteries Excluded"!) The best of both worlds, to me, would be the ability to use a VB-like GUI and the Python language and libraries. You would be able to do some pretty powerful work in just minutes. Right now, I find creating a Tkinter app to be pretty tedious work. From wescpy at gmail.com Thu Oct 13 00:36:45 2005 From: wescpy at gmail.com (w chun) Date: Wed, 12 Oct 2005 15:36:45 -0700 Subject: [Tutor] Can anyone teach me...? In-Reply-To: References: <00b601c5cf68$63081670$0a01a8c0@xp> Message-ID: <78b3a9580510121536tde34da4n7c1efa8db063fc98@mail.gmail.com> On 10/12/05, Terry Carroll wrote: > > On Wed, 12 Oct 2005, Alan Gauld wrote: > > > However I have to be honest and say that building GUIs in VB ... is a > > lot easier than in Python IMHO. > > But, man, VB as a language and library set is horrible; and pointlessly > horrible, in many cases. > > The best of both worlds, to me, would be the ability to use a VB-like GUI > and the Python language and libraries. You would be able to do some > pretty powerful work in just minutes. Right now, I find creating a > Tkinter app to be pretty tedious work. > i haven't personally, but i heard that using Glade with GTK+ and Boa with wxWindows really simplify GUI development. anyone with experience here? --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/b749de86/attachment.html From zathras at thwackety.com Thu Oct 13 01:39:08 2005 From: zathras at thwackety.com (Michael Sparks) Date: Thu, 13 Oct 2005 00:39:08 +0100 Subject: [Tutor] comiling python to microchip? In-Reply-To: <434D8BE5.106@tds.net> References: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> <434D8BE5.106@tds.net> Message-ID: <200510130039.09607.zathras@thwackety.com> On Wednesday 12 October 2005 23:19, Kent Johnson wrote: > I don't think you can compile python code Pypy can compile a restricted subset of python... More accurately it translates the restricted subset to C and then *that* can be compiled. Some code can get quite dramatic speed improvements - though interpreted pypy itself (or translated) is still *a lot* slower than regular C-Python). Pypy isn't ready (last time I looked) for general consumption yet, and certainly not for beginners :) Michael. From zathras at thwackety.com Thu Oct 13 01:58:20 2005 From: zathras at thwackety.com (Michael Sparks) Date: Thu, 13 Oct 2005 00:58:20 +0100 Subject: [Tutor] how to extract number of files from directory In-Reply-To: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> References: <20051012181028.19688.qmail@web33008.mail.mud.yahoo.com> Message-ID: <200510130058.20807.zathras@thwackety.com> On Wednesday 12 October 2005 19:10, Marc Buehler wrote: > i would like to extract the number of JPG files > from the current directory and use that number I've looked through the thread, and the following strikes me as simpler than the suggestions so far. path = "." # Current directory, unix at least. extns = ["jpg", "jpeg"] # add in any others you like :-) piccies = [ f for f in os.listdir(path) if f.split(".")[-1].lower() in extns ] num_files = len(piccies) What does this do? os.listdir(path) -- gives you a list of files in that directory. The condition: f.split(".")[-1].lower() in extns Selects which filenames get put in the resulting list files. This expression says "split the filename on dots '.' ", take the last thing after the last dot, and make it lower. Finally check to see if that extension is in the list of required extensions. I suppose if you prefer a more verbose version of the same thing: path = "." # Current directory, unix at least. extns = ["jpg", "jpeg"] # add in any others you like :-) piccies = [] for filename in os.listdir(path): extension = f.split(".")[-1] if extension.lower() in extns: piccies.append(filename) num_files = len(piccies) Regards, Michael. From ismaelgf at adinet.com.uy Thu Oct 13 01:59:05 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed, 12 Oct 2005 21:59:05 -0200 Subject: [Tutor] Can anyone teach me...? In-Reply-To: <00b601c5cf68$63081670$0a01a8c0@xp> References: <00b601c5cf68$63081670$0a01a8c0@xp> Message-ID: <434DA349.2090300@adinet.com.uy> Alan Gauld wrote: >However I have to be honest and say that building GUIs in VB >(or Borland's Delphi/Kylix) is a lot easier than in Python IMHO. >I use Delphi for most of my real-world heavy duty GUI work. > > Have you tried Boa Constructor? It is quite similar to Delphi. It builds wxPython. Ismael From kent37 at tds.net Thu Oct 13 02:08:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Oct 2005 20:08:00 -0400 Subject: [Tutor] comiling python to microchip? In-Reply-To: <200510130039.09607.zathras@thwackety.com> References: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> <434D8BE5.106@tds.net> <200510130039.09607.zathras@thwackety.com> Message-ID: <434DA560.50501@tds.net> Michael Sparks wrote: > On Wednesday 12 October 2005 23:19, Kent Johnson wrote: > >>I don't think you can compile python code > > > Pypy can compile a restricted subset of python... There is also Shed Skin - "an experimental Python-to-C++ compiler. It can convert many Python programs into optimized C++ code" http://shed-skin.blogspot.com/ Kent From amonroe at columbus.rr.com Thu Oct 13 02:28:34 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 12 Oct 2005 20:28:34 -0400 Subject: [Tutor] comiling python to microchip? In-Reply-To: <00d001c5cf76$59618120$0a01a8c0@xp> References: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> <00d001c5cf76$59618120$0a01a8c0@xp> Message-ID: <117-2117982388.20051012202834@columbus.rr.com> > From: "Jeff Peery" >> is it possible to take python code and compile it for use in a >> microprocessor? >> > In the same way that Sun have been threatening to build a chip that has Java > as its machine code then it would be possible to build a chip that ran > Python > bytecode but it would be a huge investment. > Its certainly not possible woth current Python to generate code that can run > outside of an operating system on a microchip. ON the otherhand if that > chop is running even a basic operating system that supports a C compiler > then it should be possible to build the Python interpreter for the chip/OS > combo and use python that way. > In other words, no, you can't currently get a completely standalone > machine code program from Python code at present. It would be > feasible to port Python to most micro chip OSs such as CP/M, > PSOS, QXL(?) etc and its possible that some such port has already > been done but I don't know of it. Something I noticed while playing with the dis module is that the python virtual machine appeared to use the same opcode for adding both integers and strings, for instance. It would be tricky, or slow, to translate this into other languages, I bet. Alan From andrade1 at umbc.edu Thu Oct 13 03:04:46 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Wed, 12 Oct 2005 21:04:46 -0400 (EDT) Subject: [Tutor] help with elif statements Message-ID: <1582.172.158.159.142.1129165486.squirrel@172.158.159.142> hello below is my code and everytime I input a value of 16 or more it keeps returning sophomore. could anyone help me figure out what to change so that it won't return sophmore for things greater than or equal to 16? def getcredits(num): if num < 7: return 'Freshman' elif num >= 7: return 'Sophomore' elif num <16: return 'Sophomore' elif num >= 16: return 'Junior' elif num < 26: return 'Junior' else: return 'Senior' def main(): g = input('Enter number of credits:') print 'Your standing is %s' % (getcredits(int(g))) main() From john at fouhy.net Thu Oct 13 03:15:35 2005 From: john at fouhy.net (John Fouhy) Date: Thu, 13 Oct 2005 14:15:35 +1300 Subject: [Tutor] help with elif statements In-Reply-To: <1582.172.158.159.142.1129165486.squirrel@172.158.159.142> References: <1582.172.158.159.142.1129165486.squirrel@172.158.159.142> Message-ID: <5e58f2e40510121815r2cfbb522n@mail.gmail.com> On 13/10/05, andrade1 at umbc.edu wrote: > below is my code and everytime I input a value of 16 or more it keeps > returning sophomore. could anyone help me figure out what to change so > that it won't return sophmore for things greater than or equal to 16? Which is the first branch of your IF statement to be true if you enter, say 18? -- John. From Hans.Dushanthakumar at navman.com Thu Oct 13 03:27:29 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Thu, 13 Oct 2005 14:27:29 +1300 Subject: [Tutor] help with elif statements Message-ID: <5667508E43F1B740BCFA57FF46E353000200E903@nav-akl-exch-c.newton.navman.com> U might wanna change the code to something along the lines of def getcredits(num): if num < 7: return 'Freshman' elif num >= 7 and num <16 return 'Sophomore' elif num >= 16 and num < 26: return 'Junior' Etc... Or even def getcredits(num): if num < 7: return 'Freshman' elif num <16 return 'Sophomore' elif num < 26: return 'Junior' ... -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of andrade1 at umbc.edu Sent: Thursday, 13 October 2005 2:05 p.m. To: tutor at python.org Subject: [Tutor] help with elif statements hello below is my code and everytime I input a value of 16 or more it keeps returning sophomore. could anyone help me figure out what to change so that it won't return sophmore for things greater than or equal to 16? def getcredits(num): if num < 7: return 'Freshman' elif num >= 7: return 'Sophomore' elif num <16: return 'Sophomore' elif num >= 16: return 'Junior' elif num < 26: return 'Junior' else: return 'Senior' def main(): g = input('Enter number of credits:') print 'Your standing is %s' % (getcredits(int(g))) main() _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Oct 13 04:04:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Oct 2005 19:04:31 -0700 (PDT) Subject: [Tutor] help with elif statements In-Reply-To: <1582.172.158.159.142.1129165486.squirrel@172.158.159.142> Message-ID: On Wed, 12 Oct 2005 andrade1 at umbc.edu wrote: > below is my code and everytime I input a value of 16 or more it keeps > returning sophomore. could anyone help me figure out what to change so > that it won't return sophmore for things greater than or equal to 16? If we have the following: ### Pseudocode if A: [bodyA] elif B: [bodyB] elif C: [bodyC] else: [bodyD] ############### only of those bodies will be entered, regardless if more than one condition is true. That is, we'll enter the body of the first condition that ends up true, and ignore the rest. We call this an "exclusive" branching point for this reason. If it helps, the above pseudocode could also be rewritten as the following (although it would not be idiomatic): if A: [bodyA] else: if B: [bodyB] else: if C: [bodyC] else: [bodyD] From arcege at gmail.com Wed Oct 12 16:59:51 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Wed, 12 Oct 2005 10:59:51 -0400 Subject: [Tutor] launching and monitor from make In-Reply-To: References: Message-ID: <7e5ba9220510120759m4e89edb3pcc74b96e53aa6b7d@mail.gmail.com> On 10/12/05, Ertl, John wrote: > > I have a very simple python program that reads one file and overwrites > anouther text file. This workes great from the command line and it has > error checking but just outputs messages and the like to the screen. > > The CM team here would like to have the script run each week as part of > the > automated rebuilds. The suggestion was to make the execution of the scritp > part of the bigger programs make file. How would I handel errors when the > program is run from a makefile? I hate make so I have not done a lot of > playing with what make can do in this respect but can python get an error > message to make? > In general, you want error messages to go to sys.stderr and you want to return an error code other than zero. Send messages to stderr: print >>sys.stderr, message Return error code raise SystemExit(1) At this point, make will respond to errors correctly. You can use make's -k option to ignore them, but the error messages still go the same place as other programs. HTH, -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051012/7296fd68/attachment.htm From bgailer at alum.rpi.edu Thu Oct 13 07:14:47 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 12 Oct 2005 22:14:47 -0700 Subject: [Tutor] help with elif statements In-Reply-To: <1582.172.158.159.142.1129165486.squirrel@172.158.159.142> References: <1582.172.158.159.142.1129165486.squirrel@172.158.159.142> Message-ID: <6.1.2.0.0.20051012220732.03498078@mail.mric.net> At 06:04 PM 10/12/2005, andrade1 at umbc.edu wrote: >hello > >below is my code and everytime I input a value of 16 or more it keeps >returning sophomore. could anyone help me figure out what to change so >that it won't return sophmore for things greater than or equal to 16? > >def getcredits(num): > if num < 7: > return 'Freshman' > elif num >= 7: > return 'Sophomore' > elif num <16: > return 'Sophomore' > elif num >= 16: > return 'Junior' > elif num < 26: > return 'Junior' > else: > return 'Senior' I have a preference for separating data and control structure. So I would: def getcredits(num): rank = ((7, 'Freshman'), (16, 'Sophomore'), (26, 'Junior'), (999, 'Senior') for limit, class in rank: if num < limit: return class >def main(): > g = input('Enter number of credits:') > print 'Your standing is %s' % (getcredits(int(g))) > >main() > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From raduzator at volny.cz Thu Oct 13 08:10:07 2005 From: raduzator at volny.cz (Raduz) Date: Thu, 13 Oct 2005 08:10:07 +0200 Subject: [Tutor] Can anyone teach me...? In-Reply-To: References: Message-ID: <200510130810.07892.raduzator@volny.cz> On Thursday 13 of October 2005 00:27, Terry Carroll wrote: > > The best of both worlds, to me, would be the ability to use a VB-like GUI > and the Python language and libraries. You would be able to do some > pretty powerful work in just minutes. Right now, I find creating a > Tkinter app to be pretty tedious work. > Try the Qt then. It works under Linux and Windows, has Python bindings via PyQt, it's signal/slot system is really great, and designing the GUI with Qt Designer is a breeze. -- Raduz From ajikoe at gmail.com Thu Oct 13 08:41:15 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 13 Oct 2005 08:41:15 +0200 Subject: [Tutor] how to speed up this code? Message-ID: I have code like this: def f(x,y): return math.sin(x*y) + 8 * x def main(): n = 2000 a = zeros((n,n), Float) xcoor = arange(0,1,1/float(n)) ycoor = arange(0,1,1/float(n)) for i in range(n): for j in range(n): a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x print a[1000,1000] pass if __name__ == '__main__': main() I try to make this run faster even using psyco, but I found this still slow, I tried using java and found it around 13x faster... public class s1 { /** * @param args */ public static int n = 2000; public static double[][] a = new double[n][n]; public static double [] xcoor = new double[n]; public static double [] ycoor = new double[n]; public static void main(String[] args) { // TODO Auto-generated method stub for (int i=0; i Hi all, Can Python be used to do PLC (programmable logic controller) programming? I'm not sure because Python needs some platform to run on? Thanks, Johan From wescpy at gmail.com Thu Oct 13 09:02:23 2005 From: wescpy at gmail.com (w chun) Date: Thu, 13 Oct 2005 00:02:23 -0700 Subject: [Tutor] how to speed up this code? In-Reply-To: References: Message-ID: <78b3a9580510130002j7c3a6a01u22b3d3bafe9a16b0@mail.gmail.com> On 10/12/05, Pujo Aji wrote: > I have code like this: > > def f(x,y): > return math.sin(x*y) + 8 * x > > def main(): > n = 2000 > a = zeros((n,n), Float) > xcoor = arange(0,1,1/float(n)) > ycoor = arange(0,1,1/float(n)) > > for i in range(n): > for j in range(n): > a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x > > print a[1000,1000] > > if __name__ == '__main__': > main() > > I try to make this run faster even using psyco, but I found this still > slow, I tried using java and found it around 13x faster... > > Can anybody help? > > pujo are zeros() and arange() from NumPy or SciPy? i'll assume so, so they're pretty fast already. on 1st glance, i would recommend using a while loop instead of range(), which creates a data structure (list of 2000 elements) twice: i = 0 while i < n: j = 0 while j < n: a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x j += 1 i += 1 there are probably other improvements that can be made. i also took out your 'pass' stmt. :-) HTH, --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ml.cyresse at gmail.com Thu Oct 13 09:21:44 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 13 Oct 2005 20:21:44 +1300 Subject: [Tutor] __slots__ In-Reply-To: <00e801c5cf77$67284f40$0a01a8c0@xp> References: <00e801c5cf77$67284f40$0a01a8c0@xp> Message-ID: On 10/13/05, Alan Gauld wrote: > > an object with 70ish attributes makes. FWIW, I'm doing the exact > > opposite of XP, and building to handle 300,000 to 600,000 objects... > > As a matter of interest why do you need so many in RAM at once? > Its very unusual to require that many and there are techniques to > minimise the space by using 'phantom' objects and only pulling in > the data as needed (so called 'late evaluation'). > > If you tell us more about the problem context we might be able to > help make the solution simpler. > > Alan G. > Hi Alan, First off, may I say, don't do mathematics when tired. I've revised my estimates. Problem is a certain file. http://ipodlinux.org/ITunesDB I'm creating an object for each header (for want of a better word.) A song is described by an object with several children objects, each one has certain attributes. Until I figure out a way to refactor this, I'm working on layers of abstraction. database object (contains controls, songs, podcasts, playlists etc) ^ ^ ^ composite objects (each object is composite of several base objects) ^^^^^^ base objects (objects derived from binary data) ^^^^^^^^^^ iTunesDB I've got 400ish songs, and 40 playlists which equals about 5200 headers, and hence header objects. So, a 60Gb iPod can store .... err, 15,000 songs (assuming that an average mp3 is around 4Mb). So then I did some wild guessing, and assuming that the ratio of songs to playlists remained roughly the same, then I'll make another assumption that the ratio of song & playlists to headers would also remain the same, so playlists :songs : headers is around 1 : 10 : 130. Each song is comprised of around minimum 3, can be 8/9 headers, each playlist is comprised of roughly 2n objects per song listing, and a certain amount associated with the playlist. (This is really rough). So, 15,000 songs equates to 1500 playlists (including smart playlists) , and 180,000 objects/headers. Now, I've thought about doing this various ways, but creating a coherent and usable data structure while keeping the structure of the binary file easily recreatable is what I'm after. So, in doing so, I end up with a whole lot of objects, but it's a whole lot of objects I can easily use. I'll stick the code up on the web shortliesh, I'm refactoring the file reading at the mo, as I initially wrote it only to read. Regards, Liam Clarke PS Can you recommend a decent place for a hobbyist to learn about late evaluation etc? From ml.cyresse at gmail.com Thu Oct 13 09:26:20 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 13 Oct 2005 20:26:20 +1300 Subject: [Tutor] PLC programming with Python? In-Reply-To: <434E0500.1080602@accesstel.co.za> References: <434E0500.1080602@accesstel.co.za> Message-ID: On 10/13/05, Johan Geldenhuys wrote: > Hi all, > Can Python be used to do PLC (programmable logic controller) > programming? I'm not sure because Python needs some platform to run on? > > Thanks, > > Johan > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > To some extent. Check out http://pyastra.sourceforge.net/ - it's a Python to ASM translator, which supports the PIC chips from Microchip. Regards, Liam Clarke From ml.cyresse at gmail.com Thu Oct 13 09:30:41 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 13 Oct 2005 20:30:41 +1300 Subject: [Tutor] Struct headspinner In-Reply-To: References: Message-ID: > > """By default, C numbers are represented in the machine's native format > and byte order, and properly aligned by skipping pad bytes if necessary > (according to the rules used by the C compiler).""" > > > Does this make sense? Please feel free to ask more questions on this; > it's a bit of a low-level topic. > Thanks Danny, it does indeed make sense. I'd assumed that was long as everything aligned to a multiple of 4, it was OK, based on the padding I've been working with in the data. And, I had read the above quote from the docs, but hadn't properly extrapolated it. A bit like man pages, sometimes you've gotta follow the logical consequences through. Once again, thanks, this is pretty low level stuff; I think I need to learn C, it would help. Regards, Liam Clarke From franz.steinhaeusler at gmx.at Thu Oct 13 09:27:55 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhäusler) Date: Thu, 13 Oct 2005 09:27:55 +0200 Subject: [Tutor] Problem with Winpdb. References: <434D3CAC.1080803@insightbb.com> Message-ID: On Wed, 12 Oct 2005 11:41:16 -0500, Steve Robb wrote: >Can anyone point me to what the problem may be with running Winpdb? >[snip] Hello Steve, I think, best would be to post this into: http://sourceforge.net/projects/winpdb/ bug tracker. -- Franz Steinhaeusler From ajikoe at gmail.com Thu Oct 13 09:35:01 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 13 Oct 2005 09:35:01 +0200 Subject: [Tutor] how to speed up this code? In-Reply-To: <78b3a9580510130002j7c3a6a01u22b3d3bafe9a16b0@mail.gmail.com> References: <78b3a9580510130002j7c3a6a01u22b3d3bafe9a16b0@mail.gmail.com> Message-ID: hello chun, I use Numeric. using 'while' instead of for, has the same effect. still slow pujo On 10/13/05, w chun wrote: > > On 10/12/05, Pujo Aji wrote: > > I have code like this: > > > > def f(x,y): > > return math.sin(x*y) + 8 * x > > > > def main(): > > n = 2000 > > a = zeros((n,n), Float) > > xcoor = arange(0,1,1/float(n)) > > ycoor = arange(0,1,1/float(n)) > > > > for i in range(n): > > for j in range(n): > > a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x > > > > print a[1000,1000] > > > > if __name__ == '__main__': > > main() > > > > I try to make this run faster even using psyco, but I found this still > > slow, I tried using java and found it around 13x faster... > > > > Can anybody help? > > > > pujo > > > are zeros() and arange() from NumPy or SciPy? i'll assume so, so > they're pretty fast already. on 1st glance, i would recommend using a > while loop instead of range(), which creates a data structure (list of > 2000 elements) twice: > > i = 0 > while i < n: > j = 0 > while j < n: > a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x > j += 1 > i += 1 > > there are probably other improvements that can be made. i also took > out your 'pass' stmt. :-) > > HTH, > --wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2006,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/eb8f9439/attachment.htm From me at scottoertel.info Thu Oct 13 09:38:21 2005 From: me at scottoertel.info (Scott Oertel) Date: Thu, 13 Oct 2005 10:38:21 +0300 Subject: [Tutor] Can anyone teach me...? In-Reply-To: References: Message-ID: <434E0EED.9090405@scottoertel.info> luke p wrote: > nathan, > there are a few GUI options available to you. > the one that is bundled with the python installation is TKInter. > that's an "i" not an "L". > you can also use the python interface for WxWindows, I forget what > it's called. > anyway, > TKInter looks fairly nice, some say it doesn't have the windows "feel" > to it as much as WxWindows > but who really cares because it's pretty easy to learn etc. > There's a tutorial somewher eon the web written by some New Mexico > thing I'm not sure > but I have to run to class so I can't look it up. > anyway, > Give google a workout and learn as much as you can on your own. > I don't think you should ask any questions that you could solve yourself, > or you may aggravate the list. > so try as much as you can and then if you get stuck ask someone. > Go for TKInter I think you'll like it. > Alan Gauld might have a tutorial for TKInter, you could check that out > too. > good luck. > > > On 10/12/05, *Nathan Pinno* > wrote: > > Hey all, > > When I said that I might go to Visual Basic in an earlier message, > someone replied by saying that I should ask here how to do it in > Python. Well, I'm asking now: Can anyone teach me how to make a > simple program that uses a GUI? > > Thanks, > > Nathan Pinno > Crew, McDonalds Restaurant and fan extraordinare of the Oilers. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > I've tried ALL the available options for creating GUI's with python, or so I believe I have :) right now I am finding that using PythonCard is the best solution for me, it's still a little bit rough around the edges but it make working with wxPython really simple, and things I cannot accomplish with PythonCard I can go back to using wxPython instead. Boa constructor always crashes on me in linux, on windows it's nice, but I make one small change in the code and boaconstructor will freak out and not be able to read anything. that's just my experience. -- scott oertel gawr.com :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/4783c775/attachment.html From grouch at gmail.com Thu Oct 13 10:02:35 2005 From: grouch at gmail.com (Andrew P) Date: Thu, 13 Oct 2005 03:02:35 -0500 Subject: [Tutor] how to speed up this code? In-Reply-To: References: Message-ID: It's way past my bedtime, but any use of numpy/numarray that involves two nested for loops to step over each element is the wrong solution :) You need to figure out how to get rid of that inner for. That is what is slowing you down. Compare these two ways to multiply a 1000 element array by 100. The first one steps over the elements one at a time, multiplying each one in turn. The second multiplies the entire array at once. Which boils down to looping over 2000 rows, instead of 4,000,000 elements :) If I was more awake, I'd try to figure out how you can do that. But this should give you an idea of what arrays are useful for, and how to approach the problem. >>> def time_loop(num): ... a = arange(1000) ... b = zeros(1000) ... t = time.clock() ... for i in range(num): ... for i in range(len(a)): ... b[i] = a[i] * 100.0 ... print time.clock() - t ... >>> time_loop(100000) 59.7517100637 >>> def time_numeric(num): ... a = arange(1000) ... b = zeros(1000) ... t = time.clock() ... for i in range(num): ... b = a*100 ... print time.clock() - t ... >>> time_numeric(100000) 1.44588097091 On 10/13/05, Pujo Aji wrote: > > I have code like this: > def f(x,y): > return math.sin(x*y) + 8 * x > > def main(): > n = 2000 > a = zeros((n,n), Float) > xcoor = arange(0,1,1/float(n)) > ycoor = arange(0,1,1/float(n)) > > for i in range(n): > for j in range(n): > a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x > > print a[1000,1000] > pass > > if __name__ == '__main__': > main() > > I try to make this run faster even using psyco, but I found this still > slow, I tried using java and found it around 13x faster... > > public class s1 { > > /** > * @param args > */ > public static int n = 2000; > public static double[][] a = new double[n][n]; > public static double [] xcoor = new double[n]; > public static double [] ycoor = new double[n]; > > public static void main(String[] args) { > // TODO Auto-generated method stub > for (int i=0; i xcoor[i] = i/(float)(n); > ycoor[i] = i/(float)n; > } > > for (int i=0; i for (int j=0; j a[i][j] = f(xcoor[i], ycoor[j]); > } > } > > System.out.println(a[1000][1000]); > > } > public static double f(double x, double y){ > return Math.sin(x*y) + 8*x; > } > > } > > Can anybody help? > > pujo > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/778485ab/attachment-0001.htm From ajikoe at gmail.com Thu Oct 13 10:24:14 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 13 Oct 2005 10:24:14 +0200 Subject: [Tutor] how to speed up this code? In-Reply-To: References: Message-ID: Hello Andrew, Thanks for the info. I wonder if everytime we have to solve loop inside loop which use big array will force us to think another algorithm like matrix model. Since this model is suitable with Numeric.py I think looping style sometimes easier to describe our problem. pujo On 10/13/05, Andrew P wrote: > > It's way past my bedtime, but any use of numpy/numarray that involves two > nested for loops to step over each element is the wrong solution :) You need > to figure out how to get rid of that inner for. That is what is slowing you > down. > > Compare these two ways to multiply a 1000 element array by 100. The first > one steps over the elements one at a time, multiplying each one in turn. The > second multiplies the entire array at once. Which boils down to looping over > 2000 rows, instead of 4,000,000 elements :) > > If I was more awake, I'd try to figure out how you can do that. But this > should give you an idea of what arrays are useful for, and how to approach > the problem. > > >>> def time_loop(num): > ... a = arange(1000) > ... b = zeros(1000) > ... t = time.clock() > ... for i in range(num): > ... for i in range(len(a)): > ... b[i] = a[i] * 100.0 > ... print time.clock() - t > ... > >>> time_loop(100000) > 59.7517100637 > > > >>> def time_numeric(num): > ... a = arange(1000) > ... b = zeros(1000) > ... t = time.clock() > ... for i in range(num): > ... b = a*100 > ... print time.clock() - t > ... > >>> time_numeric(100000) > 1.44588097091 > > > > On 10/13/05, Pujo Aji wrote: > > > I have code like this: > > def f(x,y): > > return math.sin(x*y) + 8 * x > > > > def main(): > > n = 2000 > > a = zeros((n,n), Float) > > xcoor = arange(0,1,1/float(n)) > > ycoor = arange(0,1,1/float(n)) > > > > for i in range(n): > > for j in range(n): > > a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x > > > > print a[1000,1000] > > pass > > > > if __name__ == '__main__': > > main() > > > > I try to make this run faster even using psyco, but I found this still > > slow, I tried using java and found it around 13x faster... > > > > public class s1 { > > > > /** > > * @param args > > */ > > public static int n = 2000; > > public static double[][] a = new double[n][n]; > > public static double [] xcoor = new double[n]; > > public static double [] ycoor = new double[n]; > > > > public static void main(String[] args) { > > // TODO Auto-generated method stub > > for (int i=0; i > xcoor[i] = i/(float)(n); > > ycoor[i] = i/(float)n; > > } > > > > for (int i=0; i > for (int j=0; j > a[i][j] = f(xcoor[i], ycoor[j]); > > } > > } > > > > System.out.println(a[1000][1000]); > > > > } > > public static double f(double x, double y){ > > return Math.sin(x*y) + 8*x; > > } > > > > } > > > > Can anybody help? > > > > pujo > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/f8ae61d6/attachment.html From alan.gauld at freenet.co.uk Thu Oct 13 10:38:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Oct 2005 09:38:56 +0100 Subject: [Tutor] Can anyone teach me...? References: <00b601c5cf68$63081670$0a01a8c0@xp> <434DA349.2090300@adinet.com.uy> Message-ID: <012801c5cfd1$8ced8ce0$0a01a8c0@xp> >>I use Delphi for most of my real-world heavy duty GUI work. >> > Have you tried Boa Constructor? It is quite similar to Delphi. It builds > wxPython. I tried it a couple of years ago but couldn't get it to work! Even if I had it didn't offer many of the features of VB/Delphi such as live database table views and close integration with the underlying objects, it simply built a GUI with hooks for the event handlers. A big step up from manually assembling TKInter in terms of simplicity but the gain wasn't that much in real speed terms. It would be interesting to see how BOa and Glade have come on the last couple of years.... Alan G. From alan.gauld at freenet.co.uk Thu Oct 13 10:49:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Oct 2005 09:49:21 +0100 Subject: [Tutor] help with elif statements References: <1582.172.158.159.142.1129165486.squirrel@172.158.159.142> Message-ID: <013201c5cfd3$01d82a00$0a01a8c0@xp> > below is my code and everytime I input a value of 16 or more it keeps > returning sophomore. could anyone help me figure out what to change so > that it won't return sophmore for things greater than or equal to 16? This is one of the gotchas of if/elif chains and I discuss it in my branching topic in the tutorial. Basically you have to sequence the tests to that you gradually filter out the ones you want. > def getcredits(num): > if num < 7: > return 'Freshman' > elif num >= 7: > return 'Sophomore' return exits the construct so you will always exit here or on the line above, you need to move this test to the bottom. I'd suggest a sequence like: > if num < 7: > elif num <16: > elif num < 26: > elif num >= 16: > elif num >= 7: > else: > return 'Senior' But mixing test types makes it really hard to do reliably. Its better to combine tests like this: if num < 7: retiurn 'Freshman' elif 7 <= num < 16: return 'Sophomore' elif 16 <= num < 26: return 'Junior' else: return 'Senior' Which I think is what you are tring to do? If thats too confusing you can use an explicit and test: if num < 7: ... elif (num >= 7) and (num <16): ... etc... The above is simply a shorthand way of writing the combined tests. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Oct 13 11:13:47 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Oct 2005 10:13:47 +0100 Subject: [Tutor] __slots__ References: <00e801c5cf77$67284f40$0a01a8c0@xp> Message-ID: <017c01c5cfd6$6b3dcb50$0a01a8c0@xp> > > As a matter of interest why do you need so many in RAM at once? > > I'm creating an object for each header (for want of a better word.) A > song is described by an object with several children objects, each one > has certain attributes. OK, But you only need the song object group to manipulate the song right? Normally you only manipulate one song at a time, so instantiate the song objects only as you need them and delete when done. > database object (contains controls, songs, podcasts, playlists etc) > composite objects (each object is composite of several base objects) > base objects (objects derived from binary data) Thats all OK so far. > (This is really rough). So, 15,000 songs equates to 1500 playlists > (including smart playlists) , and 180,000 objects/headers. Yes, but why do you need them all in memory at the same time? The only case I'd see that being necessary was if you were trying to do a bulk update of a single attribute across all songs? (And even then you could batch it internally)) > Now, I've thought about doing this various ways, but creating a > coherent and usable data structure while keeping the structure of the > binary file easily recreatable is what I'm after. Can't you read the data from the binary file as needed? For example build a table of object ids versus file locations and then use seek() to go to an object and load it from file on demand? > So, in doing so, I end up with a whole lot of objects, but it's a > whole lot of objects I can easily use. Easy to use but hoggingmemory. If you make the init method read the file then instantiating on demand becomes pretty easy too. > PS Can you recommend a decent place for a hobbyist to learn about late > evaluation etc? Its just the kind of stuff described above. Instead of ac tually holding the objects hold a reference to the class and the id(a tuple?), then when you actually need the object instantiate it and let the constructor fetch the data on demand. That way you only need the top level objects in RAM - the current playlist or song selection say... HTH, Alan G. From kent37 at tds.net Thu Oct 13 11:51:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Oct 2005 05:51:04 -0400 Subject: [Tutor] Problem with Winpdb. In-Reply-To: <434D3CAC.1080803@insightbb.com> References: <434D3CAC.1080803@insightbb.com> Message-ID: <434E2E08.5080409@tds.net> Steve Robb wrote: > Can anyone point me to what the problem may be with running Winpdb? > > I am running Win98, unfortunately > > However, when I try, > ..\python _winpdb.py, from the same directory, I get the following > traceback. > > Traceback (most recent call last): > File "C:\Python24\Lib\site-packages\winpdb.py", line 607, in calc_path > app_data = os.environ['APPDATA'] > File "C:\PYTHON24\lib\os.py", line 422, in __getitem__ > return self.data[key.upper()] > KeyError: 'APPDATA' winpdb seems to be looking for an environment variable (APPDATA) that is not supported on Win 98. As a workaround you could replace line 606 in C:\Python24\Lib\site-packages\winpdb.py which says if os.name == 'nt': with if os.name == 'nt' and os.environ.has_key('APPDATA'): This will make winpdb create its settings file in the current directory with the name winpdb_settings.cfg. Reporting this as a bug on SourceForge is also a good idea. Kent From mhansen at cso.atmel.com Thu Oct 13 15:44:46 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 13 Oct 2005 07:44:46 -0600 Subject: [Tutor] __slots__ In-Reply-To: References: Message-ID: <434E64CE.7070208@cso.atmel.com> > Subject: > Re: [Tutor] __slots__ > From: > Kent Johnson > Date: > Wed, 12 Oct 2005 18:22:46 -0400 > > CC: > Python Tutor Mailing List > > > Liam Clarke wrote: > >> Well, all I can say is, don't use them unless you need them, they're a >> lot of hassle. > > > I think the conventional advice is something like, if you don't > understand why using slots is a bad idea, you have no business using > them :-) > Can you tell us the pros and cons of using slots? Although I haven't used them yet, they seem like a way to lock down a class so you don't accidentally add new attributes to that class. (emp.name vs emp.nmae) Might be handy when working on a team too. Although something like Pychecker would most likely catch those accidents. I dunno. Mike From cpu.crazy at gmail.com Thu Oct 13 16:03:47 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Thu, 13 Oct 2005 08:03:47 -0600 Subject: [Tutor] slide show won't display the images in right order In-Reply-To: <434D2A2F.2000400@gmail.com> References: <434D26BF.6050808@gmail.com> <434D2A2F.2000400@gmail.com> Message-ID: <434E6943.8050906@gmail.com> Hi, Thank you all for your help. I must say that the python mailing list is the most helpfull of any place I've ever asked for help on. A close second comes linuxquestions.org. Somehow sort() got passed me in the Python Documentation and sort() has fixed all my problems. EDIT> Sort still didn't work but I found another fault: the direction variable. I took it out and had x += 1 and x += -1 to view the pictures ShowImg(files[x]) (x is the location of the image in the list 0, 4, 100, etc). It works great now. Hey, if you are a Garfield fan or you just want to see the source code, you can download the whole kaboodle (it's cross platform) from: http://www.jqsoftware.com/software/Gacor/gacor-096.py (Released under the GNU GPL) Joe From kent37 at tds.net Thu Oct 13 16:30:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Oct 2005 10:30:22 -0400 Subject: [Tutor] __slots__ In-Reply-To: <434E64CE.7070208@cso.atmel.com> References: <434E64CE.7070208@cso.atmel.com> Message-ID: <434E6F7E.1040009@tds.net> Mike Hansen wrote: >>From: >>Kent Johnson >>I think the conventional advice is something like, if you don't >>understand why using slots is a bad idea, you have no business using >>them :-) >> > Can you tell us the pros and cons of using slots? I think I am in the group of people who have no business using __slots__ ;-) What I gather from discussions on comp.lang.python is that really the only good reason for using __slots__ is for the memory optimization when you have huge numbers of objects instantiated. There are quite a few gotchas in the docs and more discussed in c.l.p. Search c.l.p for __slots__ to find discussion... Kent > Although I haven't used them > yet, they seem like a way to lock down a class so you don't accidentally add new > attributes to that class. (emp.name vs emp.nmae) Might be handy when working on > a team too. Although something like Pychecker would most likely catch those > accidents. I dunno. > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From stever at insightbb.com Thu Oct 13 16:32:32 2005 From: stever at insightbb.com (Steve Robb) Date: Thu, 13 Oct 2005 09:32:32 -0500 Subject: [Tutor] Problem with Winpdb. Message-ID: <434E7000.5050200@insightbb.com> Message: 5 Date: Thu, 13 Oct 2005 05:51:04 -0400 From: Kent Johnson Subject: Re: [Tutor] Problem with Winpdb. Cc: tutor at python.org Message-ID: <434E2E08.5080409 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Steve Robb wrote: >> Can anyone point me to what the problem may be with running Winpdb? >> >> I am running Win98, unfortunately >> >> However, when I try, >> ..\python _winpdb.py, from the same directory, I get the following >> traceback. >> >> Traceback (most recent call last): >> File "C:\Python24\Lib\site-packages\winpdb.py", line 607, in calc_path >> app_data = os.environ['APPDATA'] >> File "C:\PYTHON24\lib\os.py", line 422, in __getitem__ >> return self.data[key.upper()] >> KeyError: 'APPDATA' > > winpdb seems to be looking for an environment variable (APPDATA) that is not supported on Win 98. As a workaround you could replace line 606 in C:\Python24\Lib\site-packages\winpdb.py which says if os.name == 'nt': with if os.name == 'nt' and os.environ.has_key('APPDATA'): This will make winpdb create its settings file in the current directory with the name winpdb_settings.cfg. Reporting this as a bug on SourceForge is also a good idea. Kent Thanks Kent, Worked like a chanp! Thanks so much for the help. I will report the "bug" to SourceForge once they send me an account login. Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/4355773d/attachment.htm From zathras at thwackety.com Thu Oct 13 16:33:57 2005 From: zathras at thwackety.com (Michael Sparks) Date: Thu, 13 Oct 2005 15:33:57 +0100 Subject: [Tutor] comiling python to microchip? In-Reply-To: <434DA560.50501@tds.net> References: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> <200510130039.09607.zathras@thwackety.com> <434DA560.50501@tds.net> Message-ID: <200510131533.57397.zathras@thwackety.com> On Thursday 13 October 2005 01:08, Kent Johnson wrote: > Michael Sparks wrote: > > On Wednesday 12 October 2005 23:19, Kent Johnson wrote: > >>I don't think you can compile python code > > > > Pypy can compile a restricted subset of python... > > There is also Shed Skin - "an experimental Python-to-C++ compiler. It can > convert many Python programs into optimized C++ code" > http://shed-skin.blogspot.com/ Shed skin doesn't support exceptions yet though, which is a fairly major omission unfortunately. Pypy by comparison does, and can compile modules for import into python. Shed skin unfortunately doesn't do the latter. However, personally I think shed skin is pretty stellar - the C++ code it generates is (a lot) more readable than a lot of C++ code I've seen generated by people :-) Indeed. shed skin might be an interesting way for python programmers to learn C++ ;-) (I know, wrong list :) Definitely worth keeping an eye on though :) Regards, Michael. From kent37 at tds.net Thu Oct 13 17:40:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Oct 2005 11:40:53 -0400 Subject: [Tutor] slide show won't display the images in right order In-Reply-To: <434E6943.8050906@gmail.com> References: <434D26BF.6050808@gmail.com> <434D2A2F.2000400@gmail.com> <434E6943.8050906@gmail.com> Message-ID: <434E8005.5070004@tds.net> Joseph Quigley wrote: > Hey, if you are a Garfield fan or you just want to see the source code, > you can download the whole kaboodle (it's cross platform) from: > http://www.jqsoftware.com/software/Gacor/gacor-096.py I hope you like some comments... IMO the use of the Data class as a global options store is pretty ugly. I would make the data be instance variables and either pass around an instance of Data as needed, or put all the users of the data into the class as well so they can reference the parameters as self.f etc. This code if os.path.exists('C:\Documents and Settings'): imgDir = "C:\\Documents and Settings\\%s\\.gacor\\" % user if os.path.exists('D:\Documents and Settings'): imgDir = "D:\\Documents and Settings\\%s\\.gacor\\" % user if os.path.exists('E:\Documents and Settings'): imgDir = "E:\\Documents and Settings\\%s\\.gacor\\" % user etc. could be for drive in 'CDEFGHIJK': if os.path.exists('%s:\Documents and Settings' % drive): imgDir = "%s:\\Documents and Settings\\%s\\.gacor\\" % (drive, user) Do you know you are testing all the drives always? You might want use elif or put a continue in the loop above. You don't have to convert a string to a list to pull out substrings, you can get slices from a string directly. For example date = list(files[x]) Data.year = date[2] + date[3] Data.month = date[4] + date[5] Data.day = date[6] + date[7] could be date = files[x] Data.year = date[2:4] Data.month = date[4:6] Data.day = date[6:8] a similar change would clean up getother() a bit. In this code try: files.remove('license.txt') except ValueError: print why do you print here? Maybe because you don't know about pass? pass is an empty statement for when you need a block but you don't want it to do anything, e.g. try: files.remove('license.txt') except ValueError: pass You can catch multiple exceptions in one except: try: m_m = raw_input("\n\nType 'h' for help\nMain Menu> ") except (KeyboardInterrupt, TypeError): sys.exit() Kent From mrosenstihl at macnews.de Thu Oct 13 18:56:57 2005 From: mrosenstihl at macnews.de (Markus Rosenstihl) Date: Thu, 13 Oct 2005 18:56:57 +0200 Subject: [Tutor] Clean up loop and search in a list Message-ID: Hi, I wrote a program (see below) to analyse my phone bill, which is shared by three others and I don't know if there is a way to make lines like this nicer: if len(filter(re_name.search, line)) > 0 and len(filter(re_misc.search, line)) == 0 Is there for example a way to search the whole list and give back all the line numbers containing a string? Regards, Markus phone={ "Markus":"1234561",\ "Eckhard":"1234562",\ "Robert":"1234563",\ "Lei":"1234564" } for name in phone.keys(): # loop through the list for all names euro=0 # set at each run to 0 i=0 # Line number # compile REs re_name = re.compile(phone[name]) re_month=re.compile("Monatliche") re_misc=re.compile("Sonstige") for line in rechnung: if len(filter(re_month.search, line)) == 0: # skip the monthly costs # if "Monatliche" in line: if len(filter(re_name.search, line)) > 0 and len(filter(re_misc.search, line)) == 0: # if phone[name] in line: euro += float(rechnung[i][10].replace( ',' , '.')) if len(filter(re_misc.search, line)) > 0: # misc services if i not in misc_list: # add misc fees only once misc_list.append(i) misc += float(rechnung[i][10].replace( ',' , '.')) elif len(filter(re_month.search, line)) > 0: if i not in monthly_list: # add monthly occuring fees only once monthly_list.append(i) monthly += float(rechnung[i][10].replace( ',' , '.')) # replace commata with dots then add to the sum i=i+1 per_user = ( euro + ( monthly + misc )/ divider )*1.16 total += per_user print name,": ", per_user -- If everything seems to be going well, you obviously don't know what the hell is going on From levity at gmail.com Thu Oct 13 19:30:00 2005 From: levity at gmail.com (lawrence wang) Date: Thu, 13 Oct 2005 13:30:00 -0400 Subject: [Tutor] Getting info about processes via pid Message-ID: <22e13a220510131030s6f5dc6acl71bebd04291ff7aa@mail.gmail.com> So I have a list of pids, and I want to check whether the pids still refer to live processes or not. Currently I'm doing that thus: pids = ['4550\n', ...] procs = os.popen("ps ax|grep %s|awk '{ print $1 }'" % keyword).readlines() and comparing the two lists. I'm wondering, though, if there's a way to do this that's less dependent on external programs. I thought os.waitpid() might work, but on *nix I can only call it for child processes. Lawrence Wang From kent37 at tds.net Thu Oct 13 19:43:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Oct 2005 13:43:49 -0400 Subject: [Tutor] Clean up loop and search in a list In-Reply-To: References: Message-ID: <434E9CD5.4020106@tds.net> Markus Rosenstihl wrote: > Hi, > I wrote a program (see below) to analyse my phone bill, which is shared > by three others and I don't know if there is a way to make lines like > this nicer: > if len(filter(re_name.search, line)) > 0 and len(filter(re_misc.search, > line)) == 0 if len(filter(re_name.search, line)) > 0: could be written if re_name.search(line): or even, since the re is just fixed text, if phone[name] in line: > > Is there for example a way to search the whole list and give back all > the line numbers containing a string? [ i for i, line in enumerate(rechnung) if "Monatliche" in line ] Kent > > Regards, > Markus > > > > phone={ "Markus":"1234561",\ > "Eckhard":"1234562",\ > "Robert":"1234563",\ > "Lei":"1234564" > } > > > > for name in phone.keys(): # loop through the list for all names > euro=0 # set at each run to 0 > i=0 # Line number > > # compile REs > re_name = re.compile(phone[name]) > re_month=re.compile("Monatliche") > re_misc=re.compile("Sonstige") > > for line in rechnung: > if len(filter(re_month.search, line)) == 0: # skip the monthly > costs > # if "Monatliche" in line: > if len(filter(re_name.search, line)) > 0 and > len(filter(re_misc.search, line)) == 0: > # if phone[name] in line: > euro += float(rechnung[i][10].replace( ',' , '.')) > if len(filter(re_misc.search, line)) > 0: # misc services > if i not in misc_list: # add misc fees only once > misc_list.append(i) > misc += float(rechnung[i][10].replace( ',' , '.')) > elif len(filter(re_month.search, line)) > 0: > if i not in monthly_list: # add monthly occuring fees only once > monthly_list.append(i) > monthly += float(rechnung[i][10].replace( ',' , '.')) # replace > commata with dots then add to the sum > i=i+1 > per_user = ( euro + ( monthly + misc )/ divider )*1.16 > total += per_user > print name,": ", per_user > > > > -- > If everything seems to be going well, > you obviously don't know what the hell is going on > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alexiy3 at rambler.ru Thu Oct 13 11:07:54 2005 From: alexiy3 at rambler.ru (Olexiy Kharchyshyn) Date: Thu, 13 Oct 2005 12:07:54 +0300 Subject: [Tutor] how to create GUI for Python progs Message-ID: I'm really confused on the issue how to create windows, forms, etc. in Python & can't find any manual for that. Could you possibly advise me smth useful? -- Best regards, Olexiy Kharchyshyn ------------------------ alexiy3 at rambler.ru From Michael.Dwyer at ca.com Thu Oct 13 20:09:24 2005 From: Michael.Dwyer at ca.com (Dwyer, Michael) Date: Thu, 13 Oct 2005 14:09:24 -0400 Subject: [Tutor] Getting info about processes via pid Message-ID: <14C9501B97C2124FA40E1475829A56820A95AE30@usilms22.ca.com> Hi Lawrence, In a UNIX environment the method used to determine if a process is running is to issue a "kill -0 pid". If the process is running the return value will be zero (0) and -1 with errno set to ESRCH - No process or process group can be found corresponding to that specified by pid. THANX(MKD). -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of lawrence wang Sent: Thursday, October 13, 2005 10:30 AM To: tutor at python.org Subject: [Tutor] Getting info about processes via pid So I have a list of pids, and I want to check whether the pids still refer to live processes or not. Currently I'm doing that thus: pids = ['4550\n', ...] procs = os.popen("ps ax|grep %s|awk '{ print $1 }'" % keyword).readlines() and comparing the two lists. I'm wondering, though, if there's a way to do this that's less dependent on external programs. I thought os.waitpid() might work, but on *nix I can only call it for child processes. Lawrence Wang _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From nick at javacat.f2s.com Thu Oct 13 20:26:43 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu, 13 Oct 2005 19:26:43 +0100 Subject: [Tutor] how to create GUI for Python progs In-Reply-To: Message-ID: Hi Olexiy, > I'm really confused on the issue how to create windows, forms, etc. in > Python & can't find any manual for that. > Could you possibly advise me smth useful? > -- > Best regards, > > Olexiy Kharchyshyn this has come up quite a bit recently on the list. I would recommend that you go here http://pythoncard.sourceforge.net/index.html to get PythonCard and then go here http://pythoncard.sourceforge.net/walkthrough1.html to read the docs. It will take all of 10 minutes to be able to create a decent GUI. Hth, Nick . From enas_khalil at yahoo.com Thu Oct 13 20:29:29 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Thu, 13 Oct 2005 11:29:29 -0700 (PDT) Subject: [Tutor] IOError: brown is not installed In-Reply-To: Message-ID: <20051013182929.30858.qmail@web30514.mail.mud.yahoo.com> hello , when i run this code for unigramtagger : from nltk.tagger import * from nltk.corpus import brown # Tokenize ten texts from the Brown Corpus train_tokens = [] for item in brown.items()[:10]: train_tokens.append(brown.read(item)) # Initialise and train a unigram tagger mytagger = UnigramTagger(SUBTOKENS='WORDS') for tok in train_tokens: mytagger.train(tok) #Once a UnigramTagger has been trained, the tag() method can be used to tag new text: text_token = Token(TEXT="John saw the book on the table") WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(text_token) mytagger.tag(text_token) print text_token i got the following : Traceback (most recent call last): File "F:\MSC first Chapters\unigramgtag1.py", line 5, in -toplevel- for item in brown.items()[:10]: File "C:\Python24\Lib\site-packages\nltk\corpus\__init__.py", line 589, in items self._initialize() File "C:\Python24\Lib\site-packages\nltk\corpus\__init__.py", line 518, in _initialize raise IOError('%s is not installed' % self._name) IOError: brown is not installed although i have extracted the brown folder and put it in the NLTK path what should i do thanks in advance --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/7bfd2e50/attachment.html From wescpy at gmail.com Thu Oct 13 20:45:09 2005 From: wescpy at gmail.com (w chun) Date: Thu, 13 Oct 2005 11:45:09 -0700 Subject: [Tutor] how to create GUI for Python progs In-Reply-To: References: Message-ID: <78b3a9580510131145o731c7e88mc76b3f2f8d64ca60@mail.gmail.com> On 10/13/05, Nick Lunt wrote: > > > I'm really confused on the issue how to create windows, forms, etc. in > > Python & can't find any manual for that. > > Could you possibly advise me smth useful? > > > this has come up quite a bit recently on the list. > I would recommend that you go here > http://pythoncard.sourceforge.net/index.html to get PythonCard and then go > here http://pythoncard.sourceforge.net/walkthrough1.html to read the docs. > It will take all of 10 minutes to be able to create a decent GUI. pythoncard is a great way to start GUI programming. you can also try Python's default GUI Tkinter (short for Python's Tk interface) if you haven't downloaded anything other than Python yet. a good tutorial is here: http://www.ferg.org/thinking_in_tkinter/ good luck! --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/782f587f/attachment.htm From mrosenstihl at macnews.de Thu Oct 13 20:49:46 2005 From: mrosenstihl at macnews.de (Markus Rosenstihl) Date: Thu, 13 Oct 2005 20:49:46 +0200 Subject: [Tutor] Clean up loop and search in a list In-Reply-To: <434E9CD5.4020106@tds.net> References: <434E9CD5.4020106@tds.net> Message-ID: <1e80780259d38c343f8eda474150a8f0@macnews.de> Thank you for the fast reply Am 13.10.2005 um 19:43 schrieb Kent Johnson: > if len(filter(re_name.search, line)) > 0: > could be written > if re_name.search(line): this is not working because I am parsing a line in a list (i think): Traceback (most recent call last): File "telekom2.py", line 42, in ? if re_month.search(line): TypeError: expected string or buffer > or even, since the re is just fixed text, > if phone[name] in line: this won't match anything, the number is only a part of a string... I read the file in with read_file = csv.reader(open(sys.argv[1], 'r'), delimiter="\t") The input file is something like this (6 lines) "Sonstige Leistungen des Konzerns Deutsche Telekom" "Inkasso" "T-Online International AG" "Ohne Anschluss" "---" "---" "T-Online dsl flat max Monatliche Grundgeb?hr" "19112" "---" "25,8100" "25,81" "16" "Monatliche Betr?ge vom 01.09.2005 bis 30.09.2005" "ISDN" "Deutsche Telekom AG" "Rufnummer" "1234561" "---" "T-ISDN xxl sunday (monatlicherGrundpreis)" "19487" "---" "26,9600" "26,96" "16" "Monatliche Betr?ge vom 01.09.2005 bis 30.09.2005" "T-DSL" "Deutsche Telekom AG" "Rufnummer" "1234561" "---" "Monatlicher Grundpreis FastPath f?r T-DSL" "63215" "---" "0,8500" "0,85" "16" "Verbindungen Deutsche Telekom vom 17.08.2005 bis 17.08.2005" "ISDN" "Deutsche Telekom AG" "Rufnummer" "012341234561" "2" "Verbindungen zum Service 0190x" "03288" "21" "0,0533" "1,12" "16" "Verbindungen Deutsche Telekom vom 17.08.2005 bis 14.09.2005" "ISDN" "Deutsche Telekom AG" "Rufnummer" "012341234561" "23" "Verbindungen zu T-Mobile AktivPlus xxl sunday" "19483" "190" "0,1719" "32,66" "16" "Verbindungen Deutsche Telekom vom 17.08.2005 bis 14.09.2005" "ISDN" "Deutsche Telekom AG" "Rufnummer" "012341234561" "2" "Deutschlandverb. AktivPlus xxlsunday Mo-Fr Hauptzeit" "19477" "11" "0,0396" "0,44" "16" > >> >> Is there for example a way to search the whole list and give back all >> the line numbers containing a string? > [ i for i, line in enumerate(rechnung) if "Monatliche" in line ] hm, it doesn't match: >>> import csv >>> rechnung=list(csv.reader(open('2005_08_Rechnung.dat', 'r'), delimiter="\t")) >>> [ i for i, line in enumerate(rechnung) if "Monatliche" in line ] [] This matches all lines, not only the ones which have "Moantliche": >>> [ i for i, line in enumerate(rechnung) if re_month.search in line ] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40] > > Kent >> >> Regards, >> Markus >> >> >> >> phone={ "Markus":"1234561",\ >> "Eckhard":"1234562",\ >> "Robert":"1234563",\ >> "Lei":"1234564" >> } >> >> >> >> for name in phone.keys(): # loop through the list for all names >> euro=0 # set at each run to 0 >> i=0 # Line number >> >> # compile REs >> re_name = re.compile(phone[name]) >> re_month=re.compile("Monatliche") >> re_misc=re.compile("Sonstige") >> >> for line in rechnung: >> if len(filter(re_month.search, line)) == 0: # skip the monthly >> costs >> # if "Monatliche" in line: >> if len(filter(re_name.search, line)) > 0 and >> len(filter(re_misc.search, line)) == 0: >> # if phone[name] in line: >> euro += float(rechnung[i][10].replace( ',' , '.')) >> if len(filter(re_misc.search, line)) > 0: # misc services >> if i not in misc_list: # add misc fees only once >> misc_list.append(i) >> misc += float(rechnung[i][10].replace( ',' , '.')) >> elif len(filter(re_month.search, line)) > 0: >> if i not in monthly_list: # add monthly occuring fees only once >> monthly_list.append(i) >> monthly += float(rechnung[i][10].replace( ',' , '.')) # replace >> commata with dots then add to the sum >> i=i+1 >> per_user = ( euro + ( monthly + misc )/ divider )*1.16 >> total += per_user >> print name,": ", per_user >> >> >> >> -- >> If everything seems to be going well, >> you obviously don't know what the hell is going on >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nitinchandra1 at gmail.com Thu Oct 13 21:49:10 2005 From: nitinchandra1 at gmail.com (nitin chandra) Date: Fri, 14 Oct 2005 01:19:10 +0530 Subject: [Tutor] hand-holding for web development Message-ID: <965122bf0510131249had88b1fmf6124787e206a410@mail.gmail.com> Hi!... i am new to Python and i want to develop a website with forms; data submitted through forms will be stored in PostgreSQL. I am working on derivant of FC3, OpenLX. I have Apache 2.0.54 version installed, which is pre-configured with mod_python. how do i load and view my .py/.html web page (file) on the browser. i need the initial hand holding/guidance of how to start, configure , and develop modules. thank in advance. Nitin Chandra -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051014/2725ec2c/attachment.html From rdm at rcblue.com Thu Oct 13 21:51:59 2005 From: rdm at rcblue.com (Dick Moores) Date: Thu, 13 Oct 2005 12:51:59 -0700 Subject: [Tutor] redemo.py and r'python\.org' Message-ID: <6.2.1.2.2.20051013122827.0513de70@rcblue.com> I've begun to try out redemo.py to test and learn regular expressions. It doesn't seem to accept Python's raw strings as raw strings, e.g., r'python\.org' for matching python.org and nothing else. Am I correct, or is there something I don't understand here? BTW redemo.py can be found in Python 2.4 in Tools\Scripts. BTW2 The new book, _Beginning Python: From Novice to Professional_, by Magnus Lie Hetland, has 16 pages on the re module, pp. 235-251. (A question about quoting in a Tutor post: in my 1st paragraph above, how could I have indicated that I am quoting both r'python\.org' and python.org without using quotation marks to do so, so as to not confuse the regex? I think I remember someone recently using angled brackets. So how about and ? Is there a convention about this?) Thanks, Dick Moores From bill at celestial.net Thu Oct 13 22:43:16 2005 From: bill at celestial.net (Bill Campbell) Date: Thu, 13 Oct 2005 13:43:16 -0700 Subject: [Tutor] python ncurses vs OS X Tiger's xterms. Message-ID: <20051013204316.GA65306@alexis.mi.celestial.com> I'm having an ``interesting'' problem running interactive python ncurses applications in xterms under Mac OS X where the numeric keypad is forced into application mode and the numlock key has no effect. We're using curses with accounting and data entry applications for efficient keyboard entry, which isn't efficient if one can't enter numeric data from the keypad. The Apple terminal program will work with the keypad entering numbers (but the function keys don't work with it :-). Is there any way with the python ncurses modules to force the xterm keypad into numeric mode? I haven't found anything in the terminfo documentation or in the xterm X-11 Resources that control this. FWIW, the same python applications work fine when running under XFree86 or Xorg X-servers on Linux or FreeBSD systems. It's only a problem under Apple's X11, at least on Tiger and Panther which are the only machines I have in-house for testing. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ The very powerful and the very stupid have one thing in common. Instead of altering their views to fit the facts, they alter the facts to fit their views ... which can be very uncomfortable if you happen to be one of the facts that needs altering. -- Doctor Who, "Face of Evil" From alan.gauld at freenet.co.uk Thu Oct 13 23:09:19 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Oct 2005 22:09:19 +0100 Subject: [Tutor] redemo.py and r'python\.org' References: <6.2.1.2.2.20051013122827.0513de70@rcblue.com> Message-ID: <01d001c5d03a$60a4c9a0$0a01a8c0@xp> Hi Dick, > I've begun to try out redemo.py to test and learn regular expressions. It > doesn't seem to accept Python's raw strings as raw strings, e.g., > r'python\.org' for matching python.org and nothing else. Am I correct, > or is there something I don't understand here? I might be getting confused but are you trying to use the raw string as your regex? I don't think you can do that, the re module will consider the regex as a raw string. In other words if you want to match pyhon.org just use 'python\.org' with no 'r' in front. Does that help or have I misunderstood the problem? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Thu Oct 13 23:25:01 2005 From: rdm at rcblue.com (Dick Moores) Date: Thu, 13 Oct 2005 14:25:01 -0700 Subject: [Tutor] redemo.py and r'python\.org' In-Reply-To: <01d001c5d03a$60a4c9a0$0a01a8c0@xp> References: <6.2.1.2.2.20051013122827.0513de70@rcblue.com> <01d001c5d03a$60a4c9a0$0a01a8c0@xp> Message-ID: <6.2.1.2.2.20051013142321.07e63ce0@rcblue.com> Alan Gauld wrote at 14:09 10/13/2005: >Hi Dick, > > > I've begun to try out redemo.py to test and learn regular > expressions. It > > doesn't seem to accept Python's raw strings as raw strings, e.g., > > r'python\.org' for matching python.org and nothing else. Am I > correct, > > or is there something I don't understand here? > >I might be getting confused but are you trying to use the raw string >as your regex? I don't think you can do that, the re module will consider >the regex as a raw string. > >In other words if you want to match pyhon.org just use 'python\.org' >with no 'r' in front. > >Does that help or have I misunderstood the problem? You understood my confusion. Thank you! Dick From kent37 at tds.net Thu Oct 13 23:36:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Oct 2005 17:36:54 -0400 Subject: [Tutor] redemo.py and r'python\.org' In-Reply-To: <6.2.1.2.2.20051013122827.0513de70@rcblue.com> References: <6.2.1.2.2.20051013122827.0513de70@rcblue.com> Message-ID: <434ED376.3090000@tds.net> Dick Moores wrote: > I've begun to try out redemo.py to test and learn regular expressions. It > doesn't seem to accept Python's raw strings as raw strings, e.g., > r'python\.org' for matching python.org and nothing else. Am I correct, > or is there something I don't understand here? In redemo you just type the actual regex string, no quotes or r prefix. So if you type into the top text box python\.org and in the middle text box python.org then you will get a match. In your program then you have to type the regex as a string literal so you would type r'python\.org' > > BTW redemo.py can be found in Python 2.4 in Tools\Scripts. > > BTW2 The new book, _Beginning Python: From Novice to Professional_, by > Magnus Lie Hetland, has 16 pages on the re module, pp. 235-251. > > (A question about quoting in a Tutor post: in my 1st paragraph above, how > could I have indicated that I am quoting both > > r'python\.org' and python.org > > without using quotation marks to do so, so as to not confuse the regex? I > think I remember someone recently using angled brackets. So how about > and ? Is there a convention about this?) I found it clear the way you typed it. In my response I set the strings off with newlines and an indent. Angle brackets would probably work fine too. IOW I don't think there is really a convention. Kent > > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From marc_buehler at yahoo.com Thu Oct 13 23:42:01 2005 From: marc_buehler at yahoo.com (Marc Buehler) Date: Thu, 13 Oct 2005 14:42:01 -0700 (PDT) Subject: [Tutor] how to alter list content Message-ID: <20051013214201.37127.qmail@web33009.mail.mud.yahoo.com> hi. i create a list of all JPG files with: >>> list = glob.glob('*.JPG') the content of 'list' is now: >>> print list ['DSC00001.JPG', 'DSC00002.JPG', 'DSC00003.JPG'] but what i want is this type of list: ['DSC00001', 'DSC00002', 'DSC00003'] i.e. the names w/o the file extension. what's the easiest way of doing this? marc --------------------------------------------------------------------------------------- The apocalyptic vision of a criminally insane charismatic cult leader http://www.marcbuehler.net ---------------------------------------------------------------------------------------- __________________________________ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ From nick at javacat.f2s.com Thu Oct 13 23:48:20 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu, 13 Oct 2005 22:48:20 +0100 Subject: [Tutor] how to alter list content In-Reply-To: <20051013214201.37127.qmail@web33009.mail.mud.yahoo.com> Message-ID: Hi marc, > > i create a list of all JPG files with: > >>> list = glob.glob('*.JPG') > the content of 'list' is now: > >>> print list > ['DSC00001.JPG', 'DSC00002.JPG', 'DSC00003.JPG'] > > but what i want is this type of list: > ['DSC00001', 'DSC00002', 'DSC00003'] > i.e. the names w/o the file extension. > > what's the easiest way of doing this? > > marc You need the split() method. ie >> l = ['DSC00001.JPG', 'DSC00002.JPG', 'DSC00003.JPG'] >> print [i.split('.')[0] for i in l] Hth, Nick . From bretthoerner at gmail.com Thu Oct 13 23:50:54 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: Thu, 13 Oct 2005 16:50:54 -0500 Subject: [Tutor] how to alter list content In-Reply-To: <20051013214201.37127.qmail@web33009.mail.mud.yahoo.com> References: <20051013214201.37127.qmail@web33009.mail.mud.yahoo.com> Message-ID: > i create a list of all JPG files with: > >>> list = glob.glob('*.JPG') > the content of 'list' is now: > >>> print list > ['DSC00001.JPG', 'DSC00002.JPG', 'DSC00003.JPG'] > > but what i want is this type of list: > ['DSC00001', 'DSC00002', 'DSC00003'] I would make use of os.path.splitext, which returns a tuple, where [0] is the path and filename, and [1] is the extension. In [1]: import os In [2]: mylist = ['DSC00001.JPG', 'DSC00002.JPG', 'DSC00003.JPG'] In [3]: newlist = list() In [4]: for x in mylist: ....: newlist.append(os.path.splitext(x)[0]) In [5]: newlist Out[6]: ['DSC00001', 'DSC00002', 'DSC00003'] Also, don't assign things to list, list() is a buildin function in Python, you don't want to say list = x, because then you can't get to the buitin list(). Brett From andrade1 at umbc.edu Fri Oct 14 00:58:58 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Thu, 13 Oct 2005 18:58:58 -0400 (EDT) Subject: [Tutor] if-elif-else statements Message-ID: <1477.172.170.91.105.1129244338.squirrel@172.170.91.105> Hello I am having trouble getting my program to calculate the correct total if the speed limit is over 90mph. For example when i enter 100 for the clocked speed and 50 for the actual speed it returns 300 when I should receive 500. It also seems to be skipping over the else statement of if the person is not speeding they would be doing the legal speed limit. Any help would be greatly appreciated. def main(): actual = input("Please enter the legal speed limit: ") clocked = input("Please enter the clocked speed limit: ") speedlimit = clocked - actual fine = 50 + 5*speedlimit total = 200 + fine amount = fine if speedlimit < 90: print "The total amount due is", amount elif speedlimit >= 90: print "The total amount due is", total else: print "The speed was legal." main() From ewalker at micron.com Fri Oct 14 01:05:11 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 13 Oct 2005 17:05:11 -0600 Subject: [Tutor] if-elif-else statements In-Reply-To: <1477.172.170.91.105.1129244338.squirrel@172.170.91.105> References: <1477.172.170.91.105.1129244338.squirrel@172.170.91.105> Message-ID: <200510131705.11282.ewalker@micron.com> Is amount suppose to equal total instead of fine? On Thursday 13 October 2005 04:58 pm, andrade1 at umbc.edu wrote: > def main(): > ? ? actual = input("Please enter the legal speed limit: ") > ? ? clocked = input("Please enter the clocked speed limit: ") > ? ? speedlimit = clocked - actual > > ? ? fine = 50 + 5*speedlimit > ? ? total = 200 + fine > ? ? amount = fine > > ? ? if speedlimit < 90: > ? ? ? ? print "The total amount due is", amount > > ? ? elif speedlimit >= 90: > ? ? ? ? print "The total amount due is", total > > ? ? else: > ? ? ? ? print "The speed was legal." > > > main() From marc_buehler at yahoo.com Fri Oct 14 01:09:54 2005 From: marc_buehler at yahoo.com (Marc Buehler) Date: Thu, 13 Oct 2005 16:09:54 -0700 (PDT) Subject: [Tutor] passing variable to python script Message-ID: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> hi. i want to pass an argument (a number) to a python script when running it: > python script.py i want to be able to use within script.py as a parameter. how do i set this up? marc --------------------------------------------------------------------------------------- The apocalyptic vision of a criminally insane charismatic cult leader http://www.marcbuehler.net ---------------------------------------------------------------------------------------- __________________________________ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ From andrade1 at umbc.edu Fri Oct 14 01:13:39 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Thu, 13 Oct 2005 19:13:39 -0400 (EDT) Subject: [Tutor] if-elif-else statements In-Reply-To: <200510131705.11282.ewalker@micron.com> References: <1477.172.170.91.105.1129244338.squirrel@172.170.91.105> <200510131705.11282.ewalker@micron.com> Message-ID: <1589.172.170.91.105.1129245219.squirrel@172.170.91.105> amount is supposed to equal fine because there are a couple of different fines. there is a fine for going over 90mph that includes a penalty and then there is a fine for just going over the speed limit as long as it is under 90. > Is amount suppose to equal total instead of fine? > > > > On Thursday 13 October 2005 04:58 pm, andrade1 at umbc.edu wrote: >> def main(): >> ? ? actual = input("Please enter the legal speed limit: ") >> ? ? clocked = input("Please enter the clocked speed limit: ") >> ? ? speedlimit = clocked - actual >> >> ? ? fine = 50 + 5*speedlimit >> ? ? total = 200 + fine >> ? ? amount = fine >> >> ? ? if speedlimit < 90: >> ? ? ? ? print "The total amount due is", amount >> >> ? ? elif speedlimit >= 90: >> ? ? ? ? print "The total amount due is", total >> >> ? ? else: >> ? ? ? ? print "The speed was legal." >> >> >> main() > > > From ewalker at micron.com Fri Oct 14 01:18:41 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 13 Oct 2005 17:18:41 -0600 Subject: [Tutor] passing variable to python script In-Reply-To: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> References: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> Message-ID: <200510131718.41939.ewalker@micron.com> z = raw_input("Please Enter? :\n") On Thursday 13 October 2005 05:09 pm, Marc Buehler wrote: > hi. > > i want to pass an argument (a number) to a python > > script when running it: > > python script.py > > i want to be able to use within script.py > as a parameter. > > how do i set this up? > > marc > > > --------------------------------------------------------------------------- >------------ The apocalyptic vision of a criminally insane charismatic cult > leader > > http://www.marcbuehler.net > --------------------------------------------------------------------------- >------------- > > > > __________________________________ > Yahoo! Music Unlimited > Access over 1 million songs. Try it free. > http://music.yahoo.com/unlimited/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From john at fouhy.net Fri Oct 14 01:19:09 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 14 Oct 2005 12:19:09 +1300 Subject: [Tutor] passing variable to python script In-Reply-To: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> References: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> Message-ID: <5e58f2e40510131619v700644dm@mail.gmail.com> On 14/10/05, Marc Buehler wrote: > hi. > > i want to pass an argument (a number) to a python > script when running it: > > python script.py Have a look at sys.argv! #### testargs.py #### import sys print sys.argv #### C:\temp>python testargv.py 1 2 foo ['testargv.py', '1', '2', 'foo'] If you want to do anything vaguely complicated, have a look at the getopt and optparse modules. -- John. From bgailer at alum.rpi.edu Fri Oct 14 01:28:50 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 13 Oct 2005 16:28:50 -0700 Subject: [Tutor] passing variable to python script In-Reply-To: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> References: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> Message-ID: <6.1.2.0.0.20051013162411.035222e8@mail.mric.net> At 04:09 PM 10/13/2005, Marc Buehler wrote: >hi. > >i want to pass an argument (a number) to a python >script when running it: > > python script.py > >i want to be able to use within script.py >as a parameter. > >how do i set this up? In the sys module there is a property argv. The docs say: "The list of command line arguments passed to a Python script. argv[0] is the script name" import sys if len(argv) < 2: print "Usage: script.py " sys.exit(0) try: numeric_arg = int(argv[1]) except: print '1st argument must be numeric." sys.exit(0) From jason.massey at gmail.com Fri Oct 14 02:06:48 2005 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 13 Oct 2005 19:06:48 -0500 Subject: [Tutor] if-elif-else statements In-Reply-To: <1589.172.170.91.105.1129245219.squirrel@172.170.91.105> References: <1477.172.170.91.105.1129244338.squirrel@172.170.91.105> <200510131705.11282.ewalker@micron.com> <1589.172.170.91.105.1129245219.squirrel@172.170.91.105> Message-ID: <7e3eab2c0510131706s343e2cbfkd18ef1987e5f4f3@mail.gmail.com> More than anything, I think clearer variable names will help here. Something like: def main(): ... speed_limit = 60 ... clocked = int(raw_input("Clocked speed:")) ... miles_over = clocked - speed_limit ... fine = 50 + 5 * miles_over ... if miles_over >= 30: ... print "Fine is: %i" % (fine+200) ... elif miles_over > 0: ... print "Fine is: %i" % (fine) ... else: ... print "No fine" From akbarpasha at gmail.com Fri Oct 14 02:07:25 2005 From: akbarpasha at gmail.com (Akbar Pasha) Date: Thu, 13 Oct 2005 17:07:25 -0700 Subject: [Tutor] if-elif-else statements In-Reply-To: <1589.172.170.91.105.1129245219.squirrel@172.170.91.105> References: <1477.172.170.91.105.1129244338.squirrel@172.170.91.105> <200510131705.11282.ewalker@micron.com> <1589.172.170.91.105.1129245219.squirrel@172.170.91.105> Message-ID: <4ba0f6830510131707x2693548dtb6a1141ecb567582@mail.gmail.com> I think you should check the if conditions with "clocked" not speedlimit which is the differential. ::akbar On 10/13/05, andrade1 at umbc.edu wrote: > > amount is supposed to equal fine because there are a couple of different > fines. there is a fine for going over 90mph that includes a penalty and > then > there is a fine for just going over the speed limit as long as it is under > 90. > > > > Is amount suppose to equal total instead of fine? > > > > > > > > On Thursday 13 October 2005 04:58 pm, andrade1 at umbc.edu wrote: > >> def main(): > >> actual = input("Please enter the legal speed limit: ") > >> clocked = input("Please enter the clocked speed limit: ") > >> speedlimit = clocked - actual > >> > >> fine = 50 + 5*speedlimit > >> total = 200 + fine > >> amount = fine > >> > >> if speedlimit < 90: > >> print "The total amount due is", amount > >> > >> elif speedlimit >= 90: > >> print "The total amount due is", total > >> > >> else: > >> print "The speed was legal." > >> > >> > >> main() > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/ddb13ff0/attachment.html From Barry.Carroll at psc.com Fri Oct 14 02:31:42 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 13 Oct 2005 17:31:42 -0700 Subject: [Tutor] if-elif-else statements Message-ID: Greetings: I have two comments to make. First, I recommend renaming your variables to be more clear. For example: ##### speedlimit = input("Please enter the legal speed limit: ") clockedspeed = input("Please enter the clocked speed limit: ") excessspeed = clockedspeed - speedlimit ##### Next, you really have two questions to answer, the second of which depends upon the first: 1. Was the person speeding? 2. If so, was the person exceeding 90? I recommend handling this with nested if statements and calculating the fine only if the person was actually speeding, like this: ##### if excessspeed > 0: fine = 50 + 5 * excessspeed if clockedspeed >= 90: fine += 200 print "The total amount due is", fine else: print "The speed was legal." ##### This should give you the results you want. BGC ------------------------------ >Date: Thu, 13 Oct 2005 19:13:39 -0400 (EDT) >From: andrade1 at umbc.edu >Subject: Re: [Tutor] if-elif-else statements >To: ewalker at micron.com >Cc: tutor at python.org >Message-ID: <1589.172.170.91.105.1129245219.squirrel at 172.170.91.105> >Content-Type: text/plain;charset=iso-8859-1 > >amount is supposed to equal fine because there are a couple of different >fines. there is a fine for going over 90mph that includes a penalty and >then >there is a fine for just going over the speed limit as long as it is under >90. > > >> Is amount suppose to equal total instead of fine? >> >> >> >> On Thursday 13 October 2005 04:58 pm, andrade1 at umbc.edu wrote: >>> def main(): >>> ? ? actual = input("Please enter the legal speed limit: ") >>> ? ? clocked = input("Please enter the clocked speed limit: ") >>> ? ? speedlimit = clocked - actual >>> >>> ? ? fine = 50 + 5*speedlimit >>> ? ? total = 200 + fine >>> ? ? amount = fine >>> >>> ? ? if speedlimit < 90: >>> ? ? ? ? print "The total amount due is", amount >>> >>> ? ? elif speedlimit >= 90: >>> ? ? ? ? print "The total amount due is", total >>> >>> ? ? else: >>> ? ? ? ? print "The speed was legal." >>> >>> >>> main() >> >> >> From dyoo at hkn.eecs.berkeley.edu Fri Oct 14 02:41:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 13 Oct 2005 17:41:35 -0700 (PDT) Subject: [Tutor] if-elif-else statements In-Reply-To: <1589.172.170.91.105.1129245219.squirrel@172.170.91.105> Message-ID: On Thu, 13 Oct 2005 andrade1 at umbc.edu wrote: > amount is supposed to equal fine because there are a couple of different > fines. there is a fine for going over 90mph that includes a penalty and > then there is a fine for just going over the speed limit as long as it > is under 90. Hi Andradel, Because this is homework, we can not really give you specific reasons why your program isn't working: we can only give you indirect strategies and advice. Has your teacher talked about using and writing functions yet? It looks like you have a single main() function to do all the work, and since it's monolithic, it's hard to test effectively. It would be very useful if you had a separate 'get_fine()' function that took the legal and clocked speed limit values, and returned the fine from those values. If you had such a function, then you'd be able to more easily test it with hardcoded values, like: ###### assert get_fine(100, 50) == 500 ###### so you don't have to continue retyping your input every time you make a change to your program. In fact, I'd recommend temporarily disabling user input for the moment, at least until you get a get_fine() function that passes simple tests. Otherwise, what's the point of asking the user for input, if it always returns a weird answer? If you have questions about this "test-first" approach, feel free to ask about it on the list, and I'm sure folks on the list can give a few examples that demonstrate the technique. Also, consider simplifying the problem statement: it looks like you're trying to handle too much at once, with the end result that none of it is really working right. It's easier to take a program that is running correctly and then adding more things to it, than to take a program that isn't working, and trying to make it correct. Concretely: can you write a get_fine() function that doesn't care about the >90mph penalty first? As it stands, your program will give very strange results even if there is no speeding going on --- why should the police owe the speeder money? From kent37 at tds.net Fri Oct 14 03:44:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Oct 2005 21:44:29 -0400 Subject: [Tutor] Clean up loop and search in a list In-Reply-To: <1e80780259d38c343f8eda474150a8f0@macnews.de> References: <434E9CD5.4020106@tds.net> <1e80780259d38c343f8eda474150a8f0@macnews.de> Message-ID: <434F0D7D.70907@tds.net> Markus Rosenstihl wrote: > Thank you for the fast reply > > Am 13.10.2005 um 19:43 schrieb Kent Johnson: > > > >> if len(filter(re_name.search, line)) > 0: >>could be written >> if re_name.search(line): > > > this is not working because I am parsing a line in a list (i think): Ah, sorry, I misunderstood - line is a list of strings, not a single string. Can the name really appear in any field? Or could you use if re_name.search(line[4]) # (or whatever the correct field number) >>or even, since the re is just fixed text, >> if phone[name] in line: This should be if phone[name] in line[4] >>>Is there for example a way to search the whole list and give back all >>>the line numbers containing a string? >> >> [ i for i, line in enumerate(rechnung) if "Monatliche" in line ] Try [ i for i, line in enumerate(rechnung) if "Monatliche" in line[0] ] Kent From wescpy at gmail.com Fri Oct 14 04:07:30 2005 From: wescpy at gmail.com (w chun) Date: Thu, 13 Oct 2005 19:07:30 -0700 Subject: [Tutor] how to alter list content In-Reply-To: References: <20051013214201.37127.qmail@web33009.mail.mud.yahoo.com> Message-ID: <78b3a9580510131907r7ca05d6ercad200a6971d653d@mail.gmail.com> combining the best of both worlds of nick using a faster list comp and brett using os.path.splitext(): >>> files = ['DSC00001.JPG', 'DSC00002.JPG', 'DSC00003.JPG'] >>> newFiles = [os.path.splitext(f)[0] for f in files] >>> print newFiles ['DSC00001', 'DSC00002', 'DSC00003'] cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051013/c6c9bc64/attachment.html From rdm at rcblue.com Fri Oct 14 04:04:31 2005 From: rdm at rcblue.com (Dick Moores) Date: Thu, 13 Oct 2005 19:04:31 -0700 Subject: [Tutor] redemo.py and r'python\.org' In-Reply-To: <434ED376.3090000@tds.net> References: <6.2.1.2.2.20051013122827.0513de70@rcblue.com> <434ED376.3090000@tds.net> Message-ID: <6.2.1.2.2.20051013185615.06d82670@rcblue.com> Kent Johnson wrote at 14:36 10/13/2005: >Dick Moores wrote: > > I've begun to try out redemo.py to test and learn regular > expressions. It > > doesn't seem to accept Python's raw strings as raw strings, e.g., > > r'python\.org' for matching python.org and nothing else. Am I > correct, > > or is there something I don't understand here? > >In redemo you just type the actual regex string, no quotes or r prefix. >So if you type into the top text box > python\.org >and in the middle text box > python.org >then you will get a match. > >In your program then you have to type the regex as a string literal so >you would type > r'python\.org' > > > (A question about quoting in a Tutor post: in my 1st paragraph above, > how > > could I have indicated that I am quoting both > > > > r'python\.org' and python.org > > > > without using quotation marks to do so, so as to not confuse the > regex? I > > think I remember someone recently using angled brackets. So how about > > and ? Is there a convention about this?) > >I found it clear the way you typed it. In my response I set the strings >off with newlines and an indent. Angle brackets would probably work fine >too. IOW I don't think there is really a convention. If they're OK, I'll go with angle brackets unless they would be ambiguous. BTW in redemo.py, what do the checkboxes VERBOSE, LOCALE, and DOTALL mean? (I understand IGNORECASE and MULTILINE.) Thanks, Dick From kent37 at tds.net Fri Oct 14 04:21:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Oct 2005 22:21:30 -0400 Subject: [Tutor] redemo.py and r'python\.org' In-Reply-To: <6.2.1.2.2.20051013185615.06d82670@rcblue.com> References: <6.2.1.2.2.20051013122827.0513de70@rcblue.com> <434ED376.3090000@tds.net> <6.2.1.2.2.20051013185615.06d82670@rcblue.com> Message-ID: <434F162A.7060809@tds.net> Dick Moores wrote: > BTW in redemo.py, what do the checkboxes VERBOSE, LOCALE, and DOTALL > mean? (I understand IGNORECASE and MULTILINE.) http://docs.python.org/lib/node115.html Kent From alan.gauld at freenet.co.uk Fri Oct 14 05:36:03 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 14 Oct 2005 04:36:03 +0100 Subject: [Tutor] python ncurses vs OS X Tiger's xterms. References: <20051013204316.GA65306@alexis.mi.celestial.com> Message-ID: <01e501c5d070$6756bf20$0a01a8c0@xp> Bill this is a guess but try setting the terminal type to vt220 or vt330 or similar rather than xterm. Does that make any difference? curses uses the termcap database to determine how int interacts with the keyboard so changing the terminal type to somethingwell defined might make a difference? But it is a stab in the dark... Alan G. ----- Original Message ----- From: "Bill Campbell" To: "Tutor" Sent: Thursday, October 13, 2005 9:43 PM Subject: [Tutor] python ncurses vs OS X Tiger's xterms. > I'm having an ``interesting'' problem running interactive python ncurses > applications in xterms under Mac OS X where the numeric keypad is forced > into application mode and the numlock key has no effect. We're using > curses with accounting and data entry applications for efficient keyboard > entry, which isn't efficient if one can't enter numeric data from the > keypad. > > The Apple terminal program will work with the keypad entering numbers (but > the function keys don't work with it :-). > > Is there any way with the python ncurses modules to force the xterm keypad > into numeric mode? I haven't found anything in the terminfo documentation > or in the xterm X-11 Resources that control this. > > FWIW, the same python applications work fine when running under XFree86 or > Xorg X-servers on Linux or FreeBSD systems. It's only a problem under > Apple's X11, at least on Tiger and Panther which are the only machines I > have in-house for testing. > > Bill > -- > INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC > UUCP: camco!bill PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) > 236-1676 > URL: http://www.celestial.com/ > > The very powerful and the very stupid have one thing in common. > Instead of altering their views to fit the facts, they alter the facts > to fit their views ... which can be very uncomfortable if you happen to > be one of the facts that needs altering. > -- Doctor Who, "Face of Evil" > > From alan.gauld at freenet.co.uk Fri Oct 14 05:41:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 14 Oct 2005 04:41:02 +0100 Subject: [Tutor] passing variable to python script References: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> Message-ID: <01f901c5d071$19993500$0a01a8c0@xp> > i want to pass an argument (a number) to a python > script when running it: >> python script.py > > i want to be able to use within script.py > as a parameter. > > how do i set this up? This is covered in the 'talking to the user' topic in my tutorial. The short answer is use sys.argv Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From shogan at mafoi.com Fri Oct 14 07:07:28 2005 From: shogan at mafoi.com (Anthoni Shogan) Date: Fri, 14 Oct 2005 10:37:28 +0530 Subject: [Tutor] First post Message-ID: <434F3D10.1050402@mafoi.com> Hello people, this is my first post as a test.. -- Anthoni Shogan Fame is a vapor; popularity an accident; the only earthly certainty is oblivion. -- Mark Twain From andrade1 at umbc.edu Fri Oct 14 07:11:05 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Fri, 14 Oct 2005 01:11:05 -0400 (EDT) Subject: [Tutor] if-else statements Message-ID: <4460.172.152.74.182.1129266665.squirrel@172.152.74.182> Hello I'm having some trouble with my if, else statements. For some reason, the months that have 31 days work fine, but the months that have 28/30 do not work. Am I doing something wrong? it is supposed to take a date as an input like 9/31/1991 and then say that the date is not valid because september only has 30 days. import string def main(): # get the day month and year month, day, year = input("Please enter the mm, dd, yyyy: ") date1 = "%d/%d/%d" % (month,day,year) months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if day <= months[1]: d = "valid" else: n = "not valid" if day <= months[2]: d = "valid" else: d = "not valid" if day <= months[3]: d = "valid" else: d = "not valid" if day <= months[4]: d = "valid" else: n = "not valid" if day <= months[5]: d = "valid" else: d = "not valid" if day <= months[6]: d = "valid" else: d = "not valid" if day <= months[7]: d = "valid" else: d = "not valid" if day <= months[8]: d = "valid" else: d = "not valid" if day <= months[9]: d = "valid" else: d = "not valid" if day <= months[10]: d = "valid" else: d = "not valid" if day <= months[11]: d = "valid" else: d = "not valid" if day <= months[12]: d = "valid" else: d = "not valid" print "The date you entered", date1, "is", d +"." main() From nitinchandra1 at gmail.com Fri Oct 14 09:07:00 2005 From: nitinchandra1 at gmail.com (nitin chandra) Date: Fri, 14 Oct 2005 12:37:00 +0530 Subject: [Tutor] guidance for web site development Message-ID: <965122bf0510140007i4b876d5cg9eba1ed43591c8e0@mail.gmail.com> Hi!... i am new to Python and i want to develop a website with forms; data submitted through forms will be stored in PostgreSQL. I am working on deriviant of FC3, OpenLX. I have Apache 2.0.54 version installed, which is pre-configured with mod_python. how do i load and view my .py/.html web page (file) on the browser. i need the initial hand holding/guidance of how to start, configure , and develop modules. thanks in advance. Nitin Chandra From shogan at mafoi.com Fri Oct 14 09:27:12 2005 From: shogan at mafoi.com (Anthoni Shogan) Date: Fri, 14 Oct 2005 12:57:12 +0530 Subject: [Tutor] guidance for web site development In-Reply-To: <965122bf0510140007i4b876d5cg9eba1ed43591c8e0@mail.gmail.com> References: <965122bf0510140007i4b876d5cg9eba1ed43591c8e0@mail.gmail.com> Message-ID: <434F5DD0.1020500@mafoi.com> nitin chandra wrote: > Hi!... >i am new to Python and i want to develop a website with forms; data >submitted through forms will be stored in PostgreSQL. >I am working on deriviant of FC3, OpenLX. >I have Apache 2.0.54 version installed, which is pre-configured with mod_python. >how do i load and view my .py/.html web page (file) on the browser. >i need the initial hand holding/guidance of how to start, configure , >and develop modules. > >thanks in advance. > >Nitin Chandra >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Take a look at TurboGears, it sounds promising. -- Anthoni Shogan Fame is a vapor; popularity an accident; the only earthly certainty is oblivion. -- Mark Twain From andreengels at gmail.com Fri Oct 14 09:42:43 2005 From: andreengels at gmail.com (Andre Engels) Date: Fri, 14 Oct 2005 09:42:43 +0200 Subject: [Tutor] if-else statements In-Reply-To: <6faf39c90510140042v7dd74f6dv@mail.gmail.com> References: <4460.172.152.74.182.1129266665.squirrel@172.152.74.182> <6faf39c90510140042v7dd74f6dv@mail.gmail.com> Message-ID: <6faf39c90510140042m610fdc7w@mail.gmail.com> 2005/10/14, andrade1 at umbc.edu : > Hello > > I'm having some trouble with my if, else statements. For some reason, the > months that have 31 days work fine, but the months that have 28/30 do not > work. Am I doing something wrong? it is supposed to take a date as an > input like 9/31/1991 and then say that the date is not valid because > september only has 30 days. First hint: Where is 'month' used in your program? The answer is: nowhere. It should be used. Why? Second hint: Currently, the program checks each date first for validity with respect to January, then throws the outcome away to do the same with February, etcetera upto December. Thus, the final outcome says whether the date is correct in December, not whether it is correct in the given month. (actual code below) > import string > > def main(): > # get the day month and year > month, day, year = input("Please enter the mm, dd, yyyy: ") > date1 = "%d/%d/%d" % (month,day,year) > > months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] > > if day <= months[1]: > d = "valid" > else: > n = "not valid" > > if day <= months[2]: > d = "valid" > else: > d = "not valid" > > if day <= months[3]: > d = "valid" > else: > d = "not valid" > > if day <= months[4]: > d = "valid" > else: > n = "not valid" > > if day <= months[5]: > d = "valid" > else: > d = "not valid" > > if day <= months[6]: > d = "valid" > else: > d = "not valid" > > if day <= months[7]: > d = "valid" > else: > d = "not valid" > > if day <= months[8]: > d = "valid" > else: > d = "not valid" > > if day <= months[9]: > d = "valid" > else: > d = "not valid" > > if day <= months[10]: > d = "valid" > else: > d = "not valid" > > if day <= months[11]: > d = "valid" > else: > d = "not valid" > > if day <= months[12]: > d = "valid" > else: > d = "not valid" > > print "The date you entered", date1, "is", d +"." > > main() Correct and shortened code: Instead of the whole line "if day <= months[1]"... series of if-then-else statements, use only one statement, namely: if day <= months[month]: d = "valid" else: d = "not valid" -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From johan at accesstel.co.za Fri Oct 14 10:25:19 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 14 Oct 2005 10:25:19 +0200 Subject: [Tutor] guidance for web site development In-Reply-To: <965122bf0510140007i4b876d5cg9eba1ed43591c8e0@mail.gmail.com> References: <965122bf0510140007i4b876d5cg9eba1ed43591c8e0@mail.gmail.com> Message-ID: <434F6B6F.30008@accesstel.co.za> I am also looking for a good tutorial on this subject. Have you tried http://www.modpython.org/ ? I think that the mod_python mailing list will be a better place to ask. I'm going to. Johan nitin chandra wrote: > Hi!... >i am new to Python and i want to develop a website with forms; data >submitted through forms will be stored in PostgreSQL. >I am working on deriviant of FC3, OpenLX. >I have Apache 2.0.54 version installed, which is pre-configured with mod_python. >how do i load and view my .py/.html web page (file) on the browser. >i need the initial hand holding/guidance of how to start, configure , >and develop modules. > >thanks in advance. > >Nitin Chandra >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From paul1brian at gmail.com Fri Oct 14 11:05:24 2005 From: paul1brian at gmail.com (paul brian) Date: Fri, 14 Oct 2005 10:05:24 +0100 Subject: [Tutor] Fwd: if-else statements In-Reply-To: References: <4460.172.152.74.182.1129266665.squirrel@172.152.74.182> <6faf39c90510140042v7dd74f6dv@mail.gmail.com> <6faf39c90510140042m610fdc7w@mail.gmail.com> Message-ID: My apologies - I keep failing to reply-all. ---------- Forwarded message ---------- From: paul brian Date: Oct 14, 2005 10:04 AM Subject: Re: [Tutor] if-else statements To: Andre Engels I would also suggest you look at either datetime module or the mx.DateTime modules (from egenix). They are both very good and contain plenty of error checking for just such things, aas well as nicely overriding operators like + (so you can add 2 weeks to a date easily). >>> import datetime We can try an invlaid date and trap the error (using try: Except: statements) >>> datetime.date(2005,02,30) Traceback (most recent call last): File "", line 1, in ? ValueError: day is out of range for month A valid date >>> d = datetime.date(2005,02,27) And shown in a easy to read format >>> d.strftime("%A %B %d %Y") 'Sunday February 27 2005' cheers On 10/14/05, Andre Engels wrote: > 2005/10/14, andrade1 at umbc.edu : > > Hello > > > > I'm having some trouble with my if, else statements. For some reason, the > > months that have 31 days work fine, but the months that have 28/30 do not > > work. Am I doing something wrong? it is supposed to take a date as an > > input like 9/31/1991 and then say that the date is not valid because > > september only has 30 days. > > First hint: > Where is 'month' used in your program? The answer is: nowhere. It > should be used. Why? > > Second hint: > Currently, the program checks each date first for validity with > respect to January, then throws the outcome away to do the same with > February, etcetera upto December. Thus, the final outcome says whether > the date is correct in December, not whether it is correct in the > given month. > > (actual code below) > > > import string > > > > def main(): > > # get the day month and year > > month, day, year = input("Please enter the mm, dd, yyyy: ") > > date1 = "%d/%d/%d" % (month,day,year) > > > > months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] > > > > if day <= months[1]: > > d = "valid" > > else: > > n = "not valid" > > > > if day <= months[2]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[3]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[4]: > > d = "valid" > > else: > > n = "not valid" > > > > if day <= months[5]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[6]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[7]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[8]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[9]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[10]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[11]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[12]: > > d = "valid" > > else: > > d = "not valid" > > > > print "The date you entered", date1, "is", d +"." > > > > main() > > Correct and shortened code: > > Instead of the whole line "if day <= months[1]"... series of > if-then-else statements, use only one statement, namely: > > if day <= months[month]: > d = "valid" > else: > d = "not valid" > > -- > Andre Engels, andreengels at gmail.com > ICQ: 6260644 -- Skype: a_engels > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From paul1brian at gmail.com Fri Oct 14 11:15:04 2005 From: paul1brian at gmail.com (paul brian) Date: Fri, 14 Oct 2005 10:15:04 +0100 Subject: [Tutor] passing variable to python script In-Reply-To: <01f901c5d071$19993500$0a01a8c0@xp> References: <20051013230954.86018.qmail@web33002.mail.mud.yahoo.com> <01f901c5d071$19993500$0a01a8c0@xp> Message-ID: There are several approaches ranging from the simple but limited to rather advanced. raw_input is the simplest but it is to be deprecated, and more importantly it limits you to entering commands after the script is running. automation becomes harder $ myscript Those args are put into a list called sys.argv where sys.argv[0] is the name of the script you ran and any subsequent ones are sys.argv[1] {2] etc etc However my favourite is optparse module, which allows you to set up what options you like (for example $ myscript -q --outfile=/home/foo.txt) and will carefully check their validity, provide defaults, convert to floats etc where needed, and there is a cool easygui addon. On guido's Artima weblog there is a good article on using special main cases - it is pretty "deep" so do not worry if you cannot put it all to use - at least you know where you can get to. The above $ myscript is the best way to call a script, because you can run it from the command line automatically, manually, and if you use the convention of wrapping the script in a main() function, then putting this at the bottom of the file if __name__ == '__main__': main() (ie you have a function addTwoNumbers(a,b), and main takes args[1] and args[2] and passes them to addTwoNumbers) Then main() will only be run when the script is called from the command line, meaning the same code can be import'ed and addTwoNumbers can be called from any other python program. HTH On 10/14/05, Alan Gauld wrote: > > i want to pass an argument (a number) to a python > > script when running it: > >> python script.py > > > > i want to be able to use within script.py > > as a parameter. > > > > how do i set this up? > > This is covered in the 'talking to the user' topic in my tutorial. > > The short answer is use sys.argv > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From paul1brian at gmail.com Fri Oct 14 11:23:38 2005 From: paul1brian at gmail.com (paul brian) Date: Fri, 14 Oct 2005 10:23:38 +0100 Subject: [Tutor] how to create GUI for Python progs In-Reply-To: References: Message-ID: It seems to depend on what you want easygui ----------- Very simple, very easy to set up, but is NOT event driven (ie the program uses it much like it would use raw_input but with drop boxes. All other guis are event driven - that is the gui has the main loop, and when it detects (a button click) it fires off a request to the rest of the program to do something. The main frameworks (ie they provide widgets like buttons so you do not have to write your own button code) pyQT ------- Extrememly well suported and mature, Has a good drag and drop developer. Is free for Linux / open source use. Commercially is a bit more confused. tkinter -------- The default python Gui but it might be changing - see frederick Lundh's IDE for what can be done in it. WxPython ------------- Simialr to pyQt, widgets bigger than tkinter Wrappers around the above frameworks for ease PythonCard --------------- As recommended above. There are a plethora of gui interfaces (http://wiki.python.org/moin/GuiProgramming) Almost as many as web frameworks ! I suggest starting with easygui if you just want pop up dialogs, otherwise take a day or two to get to grips with QT. with a drag and drop editor it is surprisingly good. There is a tutorial by a B Rempt somewhere on line. On 10/13/05, Olexiy Kharchyshyn wrote: > > I'm really confused on the issue how to create windows, forms, etc. in > Python & can't find any manual for that. > Could you possibly advise me smth useful? > -- > Best regards, > > Olexiy Kharchyshyn > ------------------------ > alexiy3 at rambler.ru > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From kent37 at tds.net Fri Oct 14 12:04:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Oct 2005 06:04:14 -0400 Subject: [Tutor] redemo.py and r'python\.org' In-Reply-To: <6.2.1.2.2.20051013201442.02b10a10@rcblue.com> References: <6.2.1.2.2.20051013122827.0513de70@rcblue.com> <434ED376.3090000@tds.net> <6.2.1.2.2.20051013185615.06d82670@rcblue.com> <434F162A.7060809@tds.net> <6.2.1.2.2.20051013201442.02b10a10@rcblue.com> Message-ID: <434F829E.5070308@tds.net> Dick Moores wrote: > Kent Johnson wrote at 19:21 10/13/2005: > >> > BTW in redemo.py, what do the checkboxes VERBOSE, LOCALE, and DOTALL >> > mean? (I understand IGNORECASE and MULTILINE.) >> >> http://docs.python.org/lib/node115.html > > > OK, but that didn't help with LOCALE. From > http://en.wikipedia.org/wiki/Locale > LOCALE seems to be something I don't need to worry about for a while. LOCALE Make \w, \W, \b, \B, \s and \S dependent on the current locale. Locale is a setting that affects some operations that differ in different cultures, for example whether a . or , is used as a decimal separator and what the money symbol is. You can access locale settings with the locale module. The list of word and space characters can differ by locale. This affects the meaning of the \ escapes noted above. Even setting the locale to 'en' (from the default 'C' locale) changes the default letters: >>> import string, locale >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> locale.setlocale(locale.LC_ALL, 'en') 'English_United States.1252' >>> string.letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\x83\x8a\x8c\x8e\x9a\x9c\x9e\x9f\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\ xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf 6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' >>> Kent From ml.cyresse at gmail.com Fri Oct 14 14:23:04 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 15 Oct 2005 01:23:04 +1300 Subject: [Tutor] __slots__ In-Reply-To: <017c01c5cfd6$6b3dcb50$0a01a8c0@xp> References: <00e801c5cf77$67284f40$0a01a8c0@xp> <017c01c5cfd6$6b3dcb50$0a01a8c0@xp> Message-ID: > Can't you read the data from the binary file as needed? > For example build a table of object ids versus file locations > and then use seek() to go to an object and load it from file > on demand? > > > So, in doing so, I end up with a whole lot of objects, but it's a > > whole lot of objects I can easily use. > > Easy to use but hoggingmemory. If you make the init method > read the file then instantiating on demand becomes pretty easy too. Haha, that's pretty danged funny. I just spent ages ripping out all my file reads on instantiation, so that when a new object was created, it didn't care where the data came from.... but I'm happy with my decision to let a function do it for now. I might just clarify my intent. It's just a library to facilitate movement of music on/off an iPod without loading up iTunes, or ml_ipod for Winamp or similar. So to do that, I've created objects that are just subclassed lists like so - (they're actually subclasses of a subclass of list, so I've just c & p ed the inherited bits). class MHLP(list): """ Type: Playlist list Tuple format: [0] header_id (4 char string) [1] header_length (int) [2] number_of_playlists (int) <--(Includes special 'library' playlist which is hidden) Note: Library playlist must be first child. """ def __init__(self, data): self.extend(data) self._setRankAttr() def _setRankAttr(self): self.isMaster = True self.isSlave = True self.slaves = [] self.masters = ['mhsd'] def addSlave(self, slave): self.slaves.append(slave) def writeMe(self, f): hexed = struct.pack(self.pattern, self.pData) f.write(hexed) if self.isMaster: for slave in self.slaves: slave.writeMe(f) The setrank part is my way of preserving the hierachy of the file. It parses the database, and returns a list of objects, which is then iterated over to set the relationships, via this function - def setRelationships(headerList): masterStack = [] for dataObject in headerList: if dataObject.isSlave: while not masterStack[-1][0] in dataObject.masters: masterStack.pop() masterStack[-1].addSlave(dataObject) if dataObject.isMaster: masterStack.append(dataObject) What happens when a user adds a song to the iPod via this is that the ID3 tags are read, the song is copied across, and the various MHIT & MHOD objects created, and appropriate references inserted in the correct object's slaves list. A Song object is also created just unifying the methods necessary to add/remove/edit the song's details; and making available the useful data contained in the fiddlier rawer objects without exposing the messy internals. A song header is 66 items long, and about 30 of them have unknown function at this point. When a song is added, a reference to it (an integer, not a Python reference) needs to be added in about 5/6 objects, plus child counts need to be updated; hence why holding all the info in memory seemed to be the simplest solution (for me to develop). I'm writing for the 80% of cases where at most there'll be 60,000 objects, usually 12,000, and as not overly many people have USB 2.0, multiple read/writes to the iPod are something I wish to minimise. Writing to a local drive isn't something I want to rely on either, as hopefully, I'll be able to get this running directly from the iPod via a Linux install. Linux can read NTFS but not write it, I believe. I'm pie in the sky dreaming at the moment, I have to finish adding struct patterns for the rest of the weird objects. > Its just the kind of stuff described above. Instead of ac tually > holding the objects hold a reference to the class and the id(a tuple?), > then when you actually need the object instantiate it and let the > constructor fetch the data on demand. That way you only need the > top level objects in RAM - the current playlist or song selection say.. I must admit, I'm also not too sure about how to maintain the correct order in a simple manner using that late evaluation stuff; especially with adding new objects. I was thinking of perhaps a whole bunch of nested lists, but I don't tend to do well with nested lists. :/ I suspect I'm getting distracted by premature optimisation, I've been playing with MPLab's simulator, and trying to write tight ASM is getting to me. :) Thank you for your advice. Regards, Liam Clarke From 3dbernard at gmail.com Fri Oct 14 15:44:30 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 14 Oct 2005 09:44:30 -0400 Subject: [Tutor] "Decompile" pyc file Message-ID: <61d0e2b40510140644l6b3e684bme55ea74e2ceac61d@mail.gmail.com> Hello, Is there a way to "decompile" a pyc file? I have a big problem where the py file was lost, but the pyc file is instact. I would need to extract the source code from the pyc file. Thanks for any suggestion Beranrd From kent37 at tds.net Fri Oct 14 16:01:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Oct 2005 10:01:37 -0400 Subject: [Tutor] "Decompile" pyc file In-Reply-To: <61d0e2b40510140644l6b3e684bme55ea74e2ceac61d@mail.gmail.com> References: <61d0e2b40510140644l6b3e684bme55ea74e2ceac61d@mail.gmail.com> Message-ID: <434FBA41.4070103@tds.net> Bernard Lebel wrote: > Hello, > > Is there a way to "decompile" a pyc file? I have a big problem where > the py file was lost, but the pyc file is instact. I would need to > extract the source code from the pyc file. Google 'python decompiler' try http://www.freshports.org/devel/decompyle/ or the commercial service at http://www.crazy-compilers.com/decompyle/ Kent From andy.dani at lycos.com Fri Oct 14 19:51:44 2005 From: andy.dani at lycos.com (Andy Dani) Date: Fri, 14 Oct 2005 12:51:44 -0500 Subject: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path Message-ID: <20051014175144.B5CC8CA071@ws7-4.us4.outblaze.com> Python 2.3.2 came with the linux distribution which is located in /usr/lib. Installed 2.4.1 in /usr/local/Python-2.4.1 updated /etc/profile path so IDLE or "python" would point to the latest version (2.4.1). PATH="$PATH:/usr/local/Python-2.4.1/:." export PATH But it is still pointing to the old one unless I go /use/local/Python-2.4.1/python. I want to be able to launch and run python 2.4.1, from the user account so I do not need to be "root" every time. One more question, what is the significance of "import readline" in pythonrc.py file? Any harm if I comment that line out? this line gives a problem when I launch the 2.4.1 from /usr/loca/Python-2.4.1 directory. Thanks - -- _______________________________________________ Search for businesses by name, location, or phone number. -Lycos Yellow Pages http://r.lycos.com/r/yp_emailfooter/http://yellowpages.lycos.com/default.asp?SRC=lycos10 From dyoo at hkn.eecs.berkeley.edu Fri Oct 14 20:06:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 14 Oct 2005 11:06:24 -0700 (PDT) Subject: [Tutor] First post In-Reply-To: <434F3D10.1050402@mafoi.com> Message-ID: On Fri, 14 Oct 2005, Anthoni Shogan wrote: > this is my first post as a test.. Hi Anthoni, Ok, we see you. In general, it's usually not a good idea to write test messages on these kinds of mailing lists: it adds to the "noise" in the channel. Anyway, do you have a question about learning Python? Good luck! From dyoo at hkn.eecs.berkeley.edu Fri Oct 14 20:22:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 14 Oct 2005 11:22:09 -0700 (PDT) Subject: [Tutor] if-else statements In-Reply-To: <4460.172.152.74.182.1129266665.squirrel@172.152.74.182> Message-ID: > I'm having some trouble with my if, else statements. Ok, let's pause for a moment: it seems like you're having problems with more fundamental problems than just simple if/else statements. In the past questions you've written: http://mail.python.org/pipermail/tutor/2005-October/041863.html http://mail.python.org/pipermail/tutor/2005-October/042250.html you haven't really responded back in a way that helps us understand why you're getting stuck. Let's have some give and take here. Is there something you're not understanding from the other people's replies? If so, ask! Otherwise, it really does sound like you're just pushing your homework on us. The jist of your questions right seem to be "This program doesn't work: help me fix it." This is not really interesting to us. We really want to help you get unstuck, but we don't want to do your homework. > For some reason, the months that have 31 days work fine, but the months > that have 28/30 do not work. How do you know that? Show us why you think there's a problem in the program. We have our own opinions, of course, but it'll be very helpful if you try explaining how you're thinking this through. Why do you think that the program is buggy? From bill at celestial.net Fri Oct 14 20:30:08 2005 From: bill at celestial.net (Bill Campbell) Date: Fri, 14 Oct 2005 11:30:08 -0700 Subject: [Tutor] python ncurses vs OS X Tiger's xterms. In-Reply-To: <01e501c5d070$6756bf20$0a01a8c0@xp> References: <20051013204316.GA65306@alexis.mi.celestial.com> <01e501c5d070$6756bf20$0a01a8c0@xp> Message-ID: <20051014183008.GA77867@alexis.mi.celestial.com> On Fri, Oct 14, 2005, Alan Gauld wrote: >Bill this is a guess but try setting the terminal type to vt220 >or vt330 or similar rather than xterm. Does that make any difference? I haven't tried fiddling the terminal type, and would prefer not to unless it's the last resort. >curses uses the termcap database to determine how int interacts with >the keyboard so changing the terminal type to somethingwell defined >might make a difference? The ncurses libraries support termcap, but I think that all current versions of curses use terminfo which has many more options under ncurses than the original AT&T versions had. I suspect that the problem is more related to keyboard mappings in the Apple X11 implementation than it does with the terminfo and terminal type settings as the same applications work fine from Linux desktops. I've looked into xmodmap, and the X Resources that xterms support, but it would be much nicer if there is something I can handle in my python ncurses routines than if I have to dig into the keyboard mapping stuff. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``It's not what you pay a man but what he costs you that counts.'' Will Rogers From dyoo at hkn.eecs.berkeley.edu Fri Oct 14 20:33:18 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 14 Oct 2005 11:33:18 -0700 (PDT) Subject: [Tutor] if-else statements In-Reply-To: Message-ID: > > For some reason, the months that have 31 days work fine, but the > > months that have 28/30 do not work. > > How do you know that? > > Show us why you think there's a problem in the program. We have our own > opinions, of course, but it'll be very helpful if you try explaining how > you're thinking this through. Why do you think that the program is > buggy? As one more hint: try simplifying your problem. Can you change the program to handle just January, and see if it can handle January dates well? Next, can you modify your working program to handle both January and February? Does it work on January and February dates correctly? Next, can you modify your program to handle January, February, and March? Once you figure that out, then it should be a little easier to scale the program to all the months, and you should be able to better build on a program that you can progressively test. What we're trying to show you are general techniques for solving hard problems. See: http://www.math.utah.edu/~alfeld/math/polya.html From norman at littletank.org Fri Oct 14 20:50:34 2005 From: norman at littletank.org (Norman Silverstone) Date: Fri, 14 Oct 2005 19:50:34 +0100 Subject: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path In-Reply-To: <20051014175144.B5CC8CA071@ws7-4.us4.outblaze.com> References: <20051014175144.B5CC8CA071@ws7-4.us4.outblaze.com> Message-ID: <1129315834.2907.8.camel@localhost.localdomain> > I want to be able to launch and run python 2.4.1, from the user account so I do not need to be "root" every time. I use Ubuntu Linux and Python 2.4.1 comes with it. All I need to do is to open a terminal and type python and press enter. What's the problem? Norman From nick at javacat.f2s.com Fri Oct 14 21:12:33 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri, 14 Oct 2005 20:12:33 +0100 Subject: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path In-Reply-To: <20051014175144.B5CC8CA071@ws7-4.us4.outblaze.com> Message-ID: Hi Andy, > Behalf Of Andy Dani > > Python 2.3.2 came with the linux distribution which is located in > /usr/lib. > > Installed 2.4.1 in /usr/local/Python-2.4.1 > > updated /etc/profile path so IDLE or "python" would point to the > latest version (2.4.1). > > PATH="$PATH:/usr/local/Python-2.4.1/:." > export PATH > > But it is still pointing to the old one unless I go > /use/local/Python-2.4.1/python. > > I want to be able to launch and run python 2.4.1, from the user > account so I do not need to be "root" every time. The default install of python on Mandrake probably install the python executable in /usr/bin/python. /usr/bin/ is in your PATH, so if you put PATH=$PATH:/usr/local/Python-2.4.1 in /etc/profile it will still pick up the default python install. Try typing 'which python' at the command line and see what it picks up. Chances are it will be /usr/bin/python. You could solve this by either putting PATH=/path/to/my/wanted/python/dir:$PATH in /etc/profile (or ~/.bash_profile) or by putting an alias in ~/.bashrc, such as 'alias python='path/to/my/wanted/python/dir/python'. What I must stress is that you do not overwrite your default python installation, leave it as it is, otherwise many of mandrakes GUI tools will no work. I hope that helps, feel free to ask more questions about this as I have had to overcome the same issue on RHEL serveral times. Hth, Nick . From hugonz-lists at h-lab.net Fri Oct 14 21:14:43 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 14 Oct 2005 13:14:43 -0600 Subject: [Tutor] comiling python to microchip? In-Reply-To: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> References: <20051012185546.24744.qmail@web30501.mail.mud.yahoo.com> Message-ID: <435003A3.2080408@h-lab.net> If you mean a small one like a microcontroller (ARM, AVR, Dragonball, 68x000) then no. If you're using, say, embedded Linux on ARM, then it probably works, here's a link: http://www.vanille.de/projects/python.spy Hope it helps, Hugo Jeff Peery wrote: > is it possible to take python code and compile it for use in a > microprocessor? > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From nephish at xit.net Fri Oct 14 21:23:02 2005 From: nephish at xit.net (nephish) Date: Fri, 14 Oct 2005 14:23:02 -0500 Subject: [Tutor] question about pychart Message-ID: <1129317782.4480.6.camel@localhost.localdomain> Hey there, i have a simple app that plots some numbers sent by a field sensor with respect to time. i am trying to do this in pychart, but the problem is, when the numbers come in, they do so at almost random times. y shows the value sent by the sensor x plots the time that the value came in. what happens is that the plots are spaced evenly throughout the x axis. so it always looks like an even amount of time when most often, it isn't i need a way to make it plot out the x so that when a lot of values come in at close to the same time, it looks more like that on the graph. i looked at the docs where the examples show that this can be done, the example uses a log style to the plot. it looks like this. http://home.gna.org/pychart/examples/scattertest.png mostly the graph on the right my chart shows just a plot of x=datetime y=value, someone have an idea about how i can get more realistic looking values? thanks shawn From luke.jordan at gmail.com Fri Oct 14 21:35:45 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Fri, 14 Oct 2005 14:35:45 -0500 Subject: [Tutor] dictionaries in classes Message-ID: Hi, Another stumped beginner here. I'm trying to have functions to create, edit and store dictionaries within a class. What I can't figure out is how to retain the edits after making them. I think it has something to do with namespace. Ideally I'd like to pickle class instances and be able to access each instance's unique dictionaries through a classInst.dict arrangement. I don't know why I can't figure out how to make the dictionary an attribute of the class, or if that's even possible. Does the dict have to be a separate pickled file? I've tried setting the dict in these namespaces: class N: dict = {} class N: def func(self): dict = {} but neither of these is working for me. If I make the dict global, then all class instances could edit it, which is not what I'm shooting for either. I'm out of ideas, and I sense that there is something basic that I either don't know or am overlooking. Thanks in advance. Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051014/2129b6f8/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Oct 14 22:01:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 14 Oct 2005 13:01:19 -0700 (PDT) Subject: [Tutor] dictionaries in classes In-Reply-To: Message-ID: On Fri, 14 Oct 2005, Luke Jordan wrote: > I'm trying to have functions to create, edit and store dictionaries > within a class. Here's a small example of a class: ###### class Person: def __init__(self, name): self.name = name ###### Let's try pickling an instance of it: ###### >>> p = Person("Luke") >>> pickle.dumps(p) "(i__main__\nPerson\np0\n(dp1\nS'name'\np2\nS'Luke'\np3\nsb." ###### Given a string like that, let's see if we can unpickle it back to an object instance: ###### >>> p2 = pickle.loads("(i__main__\nPerson\np0\n(dp1\nS'name'\np2\nS'Luke'\np3\nsb.") >>> p2 <__main__.Person instance at 0x4048d8cc> >>> p2.name 'Luke' ###### > I don't know why I can't figure out how to make the dictionary an > attribute of the class, or if that's even possible. You may want to make it an attribute of the class instance, and not necessarily one of the class itself. A class attribute is shared among all instances, and that's probably not what you want. The example above shows how to initialize an attribute of a class instance, and that's probably what you've been missing. If you have more questions, please feel free to ask! From alan.gauld at freenet.co.uk Sat Oct 15 00:14:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 14 Oct 2005 23:14:27 +0100 Subject: [Tutor] python ncurses vs OS X Tiger's xterms. References: <20051013204316.GA65306@alexis.mi.celestial.com><01e501c5d070$6756bf20$0a01a8c0@xp> <20051014183008.GA77867@alexis.mi.celestial.com> Message-ID: <026f01c5d10c$a4e17960$0a01a8c0@xp> > On Fri, Oct 14, 2005, Alan Gauld wrote: >>Bill this is a guess but try setting the terminal type to vt220 >>or vt330 or similar rather than xterm. Does that make any difference? > > I haven't tried fiddling the terminal type, and would prefer not > to unless it's the last resort. The reason I suggested oit is that its one of the things thats platform dependant and so setting a standard terminal setting on all platforms might show up the differences. In particular the Apple Terminal program versus xterm, but even an xterm can be defined difeerently on different Unix flavours. This is one reason I have a line in my profile/cshrc files to force term type to v220, it just makes life more consistent... > The ncurses libraries support termcap, but I think that all > current versions of curses use terminfo which has many more termcap or terminfo the point was that the beghaviour is not really in curses but in the terminal definitions stored in those databases. Of course curses tries hard to hide those differences but ultimately is only as capable as the capabilities that have been defined. > I suspect that the problem is more related to keyboard mappings > in the Apple X11 implementation than it does with the terminfo > and terminal type settings as the same applications work fine As a matter of interest what does trhe apple Terminal and xterm claim the terninal type to be? (I should just go downstairs and boot my iBook! :-) > there is something I can handle in my python ncurses routines > than if I have to dig into the keyboard mapping stuff. Absolutely and curses is supposede to do that, but when debugging curses(*) I've found it useful top know exactly what terminal curses thinks its playing with. (*)And I mean curses I've never used ncurses in anger... Alan G. From wescpy at gmail.com Sat Oct 15 00:31:46 2005 From: wescpy at gmail.com (w chun) Date: Fri, 14 Oct 2005 15:31:46 -0700 Subject: [Tutor] dictionaries in classes In-Reply-To: References: Message-ID: <78b3a9580510141531i3818bc3dx338318caf4e452d@mail.gmail.com> > > On Fri, 14 Oct 2005, Luke Jordan wrote: > > > I'm trying to have functions to create, edit and store dictionaries > > within a class. i 2nd danny's motion: make your dictionary an instance attribute (unique to that instance) rather than a class attribute (shared amongst all instances), and 2ndly, don't use 'dict' because that is a built-in (factory) function: class N: def __init__(self): self.myDict = {} n = N() ... then pickle 'n' as danny has described. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051014/7fde67d9/attachment.html From marc_buehler at yahoo.com Sat Oct 15 00:50:07 2005 From: marc_buehler at yahoo.com (Marc Buehler) Date: Fri, 14 Oct 2005 15:50:07 -0700 (PDT) Subject: [Tutor] extract plain english words from html Message-ID: <20051014225007.39955.qmail@web33007.mail.mud.yahoo.com> hi. i have a ton of html files from which i want to extract the plain english words, and then write those words into a single text file. example: <... all kinds html tags ...> this is text from the above, i want to extract the string 'this is text' and write it out to a text file. note that all of the html files have the same format, i.e. the text is always surrounded by the same html tags. also, i am sorting through thousands of html files, so whatever i do needs to be fast. any ideas? marc --------------------------------------------------------------------------------------- The apocalyptic vision of a criminally insane charismatic cult leader http://www.marcbuehler.net ---------------------------------------------------------------------------------------- __________________________________ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ From dyoo at hkn.eecs.berkeley.edu Sat Oct 15 01:51:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 14 Oct 2005 16:51:57 -0700 (PDT) Subject: [Tutor] extract plain english words from html In-Reply-To: <20051014225007.39955.qmail@web33007.mail.mud.yahoo.com> Message-ID: On Fri, 14 Oct 2005, Marc Buehler wrote: > i have a ton of html files from which i want to extract the plain > english words, and then write those words into a single text file. Hi Marc, The BeautifulSoup parser should be able to do what you want: http://www.crummy.com/software/BeautifulSoup/ For example: ###### >>> from BeautifulSoup import BeautifulSoup >>> import urllib >>> import re >>> soup = BeautifulSoup(urllib.urlopen('http://python.org/index.html')) >>> for chunk in soup.fetch('a'): ... print chunk.fetchText(re.compile('.+')) ... [] ['Search'] ['Download'] ['Documentation'] ['Help'] ['Developers'] ['Community'] ['SIGs'] ['What is Python?'] ['Python FAQs'] ['Python 2.4'] ['(docs)'] ['Python 2.3'] ['(docs)'] ['Python 2.2'] ['(docs)'] ['MacPython'] ['Jython'] ... [lots of output here] ###### And this allows us to quickly get all the hyperlinked text off the Python.org web site. It's not perfect, but it can deal surprisingly well with ugly HTML. Hope this helps! From bgailer at alum.rpi.edu Sat Oct 15 02:06:48 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 14 Oct 2005 17:06:48 -0700 Subject: [Tutor] extract plain english words from html In-Reply-To: <20051014225007.39955.qmail@web33007.mail.mud.yahoo.com> References: <20051014225007.39955.qmail@web33007.mail.mud.yahoo.com> Message-ID: <6.1.2.0.0.20051014170348.028e1ef8@mail.mric.net> At 03:50 PM 10/14/2005, Marc Buehler wrote: >hi. > >i have a ton of html files from which i want to >extract the plain english words, and then write >those words into a single text file. http://www.crummy.com/software/BeautifulSoup/ will read the html, let you step from tag to tag and extract the text. Almost no effort on your part. [snip] From samrobertsmith at gmail.com Sat Oct 15 02:50:04 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 14 Oct 2005 17:50:04 -0700 Subject: [Tutor] output question Message-ID: <1d987df30510141750s6128ad24g23e297d8ef60ec55@mail.gmail.com> After I run the following python code, I expect to have the printing such as: The year is 2005 However, I got something like: The year is 2005 Fri Oct 14 17:43:31 2005 Fri Oct 14 17:43:31 2005 The year is 2005 What is the reason? The code follows: import time import now class today(now.now): def __init__(self, y = 1970): now.now.__init__(self) def update(self,tt): if len(tt) < 9 : raise TypeError if tt[0] < 1970 or tt[0] > 2038: raise OverflowError self.t = time.mktime(tt) self(self.t) if __name__ == "__main__": n = today() print "The year is", n.year From kent37 at tds.net Sat Oct 15 02:54:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Oct 2005 20:54:51 -0400 Subject: [Tutor] extract plain english words from html In-Reply-To: <20051014225007.39955.qmail@web33007.mail.mud.yahoo.com> References: <20051014225007.39955.qmail@web33007.mail.mud.yahoo.com> Message-ID: <4350535B.2040603@tds.net> Marc Buehler wrote: > hi. > > i have a ton of html files from which i want to > extract the plain english words, and then write > those words into a single text file. If you just want the text from a single tag in the document then BeautifulSoup will work well, as Danny and Bob suggest. If you have many tags containing text and you want all the text, you might like StripOGram http://www.zope.org/Members/chrisw/StripOGram or this succinct example from Python Cookbook 2nd edition: from sgmllib import SGMLParser class XMLJustText(SGMLParser): def handle_data(self, data): print data XMLJustText().feed(open('text.xml').read()) Kent > > example: > > > <... all kinds html tags ...> > > this is text > > > from the above, i want to extract the string > 'this is text' and write it out to a text file. > note that all of the html files have the same > format, i.e. the text is always surrounded by the same > html tags. > also, i am sorting through thousands of > html files, so whatever i do needs to be > fast. > > any ideas? > > marc > > > --------------------------------------------------------------------------------------- > The apocalyptic vision of a criminally insane charismatic cult leader > > http://www.marcbuehler.net > ---------------------------------------------------------------------------------------- > > > > __________________________________ > Yahoo! Music Unlimited > Access over 1 million songs. Try it free. > http://music.yahoo.com/unlimited/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sat Oct 15 03:00:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Oct 2005 21:00:30 -0400 Subject: [Tutor] output question In-Reply-To: <1d987df30510141750s6128ad24g23e297d8ef60ec55@mail.gmail.com> References: <1d987df30510141750s6128ad24g23e297d8ef60ec55@mail.gmail.com> Message-ID: <435054AE.2070900@tds.net> Shi Mu wrote: > After I run the following python code, I expect to have the printing such as: > The year is 2005 > > However, I got something like: > The year is 2005 > Fri Oct 14 17:43:31 2005 > Fri Oct 14 17:43:31 2005 > The year is 2005 > > What is the reason? Maybe coming from module 'now'? What is that? Kent > > The code follows: > > import time > import now > > class today(now.now): > def __init__(self, y = 1970): > now.now.__init__(self) > def update(self,tt): > if len(tt) < 9 : > raise TypeError > if tt[0] < 1970 or tt[0] > 2038: > raise OverflowError > self.t = time.mktime(tt) > self(self.t) > > if __name__ == "__main__": > n = today() > print "The year is", n.year > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From samrobertsmith at gmail.com Sat Oct 15 03:10:42 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 14 Oct 2005 18:10:42 -0700 Subject: [Tutor] output question In-Reply-To: <435054AE.2070900@tds.net> References: <1d987df30510141750s6128ad24g23e297d8ef60ec55@mail.gmail.com> <435054AE.2070900@tds.net> Message-ID: <1d987df30510141810p5df52eb0y832ed50e1ea5ec48@mail.gmail.com> I found the code for class "now". I got confused by two things: First, how did the former code I posted know to import tis module of "Now"; Second. what does "\" mean following "self.year," Thanks a lot! class now: def __init__(self): self.t = time.time() self.storetime() def storetime(self): self.year, \ self.month, \ self.day, \ self.hour, \ self.minute, \ self.second, \ self.dow, \ self.doy, \ self.dst = time.localtime(self.t) def __str__(self): return time.ctime(self.t) def __repr__(self): return time.ctime(self.t) def __call__(self,t=-1.0): if t < 0.0: self.t = time.time() else: self.t = t self.storetime() On 10/14/05, Kent Johnson wrote: > Shi Mu wrote: > > After I run the following python code, I expect to have the printing such as: > > The year is 2005 > > > > However, I got something like: > > The year is 2005 > > Fri Oct 14 17:43:31 2005 > > Fri Oct 14 17:43:31 2005 > > The year is 2005 > > > > What is the reason? > > Maybe coming from module 'now'? What is that? > > Kent > > > > > The code follows: > > > > import time > > import now > > > > class today(now.now): > > def __init__(self, y = 1970): > > now.now.__init__(self) > > def update(self,tt): > > if len(tt) < 9 : > > raise TypeError > > if tt[0] < 1970 or tt[0] > 2038: > > raise OverflowError > > self.t = time.mktime(tt) > > self(self.t) > > > > if __name__ == "__main__": > > n = today() > > print "The year is", n.year > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From wescpy at gmail.com Sat Oct 15 03:33:06 2005 From: wescpy at gmail.com (w chun) Date: Fri, 14 Oct 2005 18:33:06 -0700 Subject: [Tutor] output question In-Reply-To: <1d987df30510141810p5df52eb0y832ed50e1ea5ec48@mail.gmail.com> References: <1d987df30510141750s6128ad24g23e297d8ef60ec55@mail.gmail.com> <435054AE.2070900@tds.net> <1d987df30510141810p5df52eb0y832ed50e1ea5ec48@mail.gmail.com> Message-ID: <78b3a9580510141833q26c9f7bag2aee0b3657d7bf02@mail.gmail.com> On 10/14/05, Shi Mu wrote: > > I found the code for class "now". I got confused by two things: > First, how did the former code I posted know to import tis module of > "Now"; > Second. what does "\" mean following "self.year," > Thanks a lot! > > class now: > > def __str__(self): > return time.ctime(self.t) > def __repr__(self): > return time.ctime(self.t) > you mean you didn't write the "former code?" why are you asking for help with code that you did not write? your output is caused by the 2 now methods above. the '\' is the continuation character in Python. are you learning Python on your own? -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051014/a3ca1fd7/attachment.html From kent37 at tds.net Sat Oct 15 03:40:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Oct 2005 21:40:12 -0400 Subject: [Tutor] output question In-Reply-To: <1d987df30510141810p5df52eb0y832ed50e1ea5ec48@mail.gmail.com> References: <1d987df30510141750s6128ad24g23e297d8ef60ec55@mail.gmail.com> <435054AE.2070900@tds.net> <1d987df30510141810p5df52eb0y832ed50e1ea5ec48@mail.gmail.com> Message-ID: <43505DFC.2000708@tds.net> Shi Mu wrote: > I found the code for class "now". I got confused by two things: > First, how did the former code I posted know to import tis module of "Now"; You told it to with the statement import now This statement tells Python to look in the directories in its path for a file called now.py and load it, assigning the resulting module object to the name 'now'. > Second. what does "\" mean following "self.year," It is a line continuation character - it means the text of the line continues on the next line. Is there anything else in now.py? Any print statements? When I run the code you have posted so far I just get one line of output. Kent > Thanks a lot! > > class now: > def __init__(self): > self.t = time.time() > self.storetime() > def storetime(self): > self.year, \ > self.month, \ > self.day, \ > self.hour, \ > self.minute, \ > self.second, \ > self.dow, \ > self.doy, \ > self.dst = time.localtime(self.t) > def __str__(self): > return time.ctime(self.t) > def __repr__(self): > return time.ctime(self.t) > def __call__(self,t=-1.0): > if t < 0.0: > self.t = time.time() > else: > self.t = t > self.storetime() > > > On 10/14/05, Kent Johnson wrote: > >>Shi Mu wrote: >> >>>After I run the following python code, I expect to have the printing such as: >>>The year is 2005 >>> >>>However, I got something like: >>>The year is 2005 >>>Fri Oct 14 17:43:31 2005 >>>Fri Oct 14 17:43:31 2005 >>>The year is 2005 >>> >>>What is the reason? >> >>Maybe coming from module 'now'? What is that? >> >>Kent >> >> >>>The code follows: >>> >>>import time >>>import now >>> >>>class today(now.now): >>> def __init__(self, y = 1970): >>> now.now.__init__(self) >>> def update(self,tt): >>> if len(tt) < 9 : >>> raise TypeError >>> if tt[0] < 1970 or tt[0] > 2038: >>> raise OverflowError >>> self.t = time.mktime(tt) >>> self(self.t) >>> >>>if __name__ == "__main__": >>> n = today() >>> print "The year is", n.year >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From grouch at gmail.com Sat Oct 15 05:23:58 2005 From: grouch at gmail.com (Andrew P) Date: Fri, 14 Oct 2005 22:23:58 -0500 Subject: [Tutor] extract plain english words from html In-Reply-To: <20051014225007.39955.qmail@web33007.mail.mud.yahoo.com> References: <20051014225007.39955.qmail@web33007.mail.mud.yahoo.com> Message-ID: You could try: http://www.aminus.org/rbre/python/cleanhtml.py YMMV, as the kids say. But I did choose this over BeautifulSoup or Strip-o-gram to do this particular thing. I don't remember -why- I chose it, but there you go. Easy enough to test all three :) Oh, and if you just want a whole page prettily formatted: lynx -dump page.html > file.txt is often the easiest way. Good luck, Andrew On 10/14/05, Marc Buehler wrote: > hi. > > i have a ton of html files from which i want to > extract the plain english words, and then write > those words into a single text file. > > example: > > > <... all kinds html tags ...> > > this is text > > > from the above, i want to extract the string > 'this is text' and write it out to a text file. > note that all of the html files have the same > format, i.e. the text is always surrounded by the same > html tags. > also, i am sorting through thousands of > html files, so whatever i do needs to be > fast. > > any ideas? > > marc > > > --------------------------------------------------------------------------------------- > The apocalyptic vision of a criminally insane charismatic cult leader > > http://www.marcbuehler.net > ---------------------------------------------------------------------------------------- > > > > __________________________________ > Yahoo! Music Unlimited > Access over 1 million songs. Try it free. > http://music.yahoo.com/unlimited/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From grouch at gmail.com Sat Oct 15 07:38:14 2005 From: grouch at gmail.com (Andrew P) Date: Sat, 15 Oct 2005 00:38:14 -0500 Subject: [Tutor] if-else statements In-Reply-To: References: <4460.172.152.74.182.1129266665.squirrel@172.152.74.182> Message-ID: Well, on the bright side, at least Python is being taught in schools. My younger sister is a CS major just starting her programming courses, and it's Java/C++ all the way. I am becoming convinced that lines of code are not only related to the number of bugs and development speed, but learning speed as well. Too much time tripping over syntax and you miss the important bits. On 10/14/05, Danny Yoo wrote: > Otherwise, it really does sound like you're just pushing your homework on > us. The jist of your questions right seem to be "This program doesn't > work: help me fix it." This is not really interesting to us. We really > want to help you get unstuck, but we don't want to do your homework. > From dyoo at hkn.eecs.berkeley.edu Sat Oct 15 10:20:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 15 Oct 2005 01:20:17 -0700 (PDT) Subject: [Tutor] if-else statements In-Reply-To: Message-ID: On Sat, 15 Oct 2005, Andrew P wrote: > Well, on the bright side, at least Python is being taught in schools. [Warning: I get totally off-topic, opinionated, and cranky in the following rant. My apologies in advance!] Hi Andrew, But I get worried, though, that much teaching uses fragile techniques that don't really scale well. I've disliked the order in which some Python tutorials approach language features --- in particular, functions seem to be given short shrift at times. I think the concept of functions really need to come as soon as possible: to me, they're essential core material, and functions need to be introduced as a way to control program complexity and allow for testing. As an example of a Python tutorial that ignores functions altogether is Richard Baldwin's Python Programming Tutorial: http://www.dickbaldwin.com/tocpyth.htm His tutorial doesn't even approach the idea of breaking down hard problems into small ones: it just jumps right into language features, without really providing the connective glue that puts it all together. I hate being mean to him, but I really think that the particular tutorial there is just poor, and its failure is a reflection on the misguided focus on iterating through all the features and idiocyncracies of Python. I think those kinds of tutorials usually just end up convincing beginners that programming is just a matter of tricks and silly details. For simliar reasons, I really don't think the official Python Tutorial belongs on the top of the Non Programmers page at http://wiki.python.org/moin/BeginnersGuide/NonProgrammers: I truly think beginners would scream in horror at it if they really tried to learn to program from it. *grin* My point is that because something is being taught in Python isn't a guarantee that good teaching is going to happen automatically. In fact, because Python's so featureful, I think it can be dangerously tempting for a teacher or tutor to focus on Python-specific language features too much. For folks who know the fundamentals of programming already, that's fine --- they want to be productive --- but for a real beginner who is trying to figure out this crazy programming stuff, that kind of focus can be damaging. I really wish that someone would take a similar approach in writing a beginner Python tutorial that focuses on functions almost immediately, even before control flow. Something like: http://www.htdp.org/2003-09-26/Book/ for Python would be nice to see... Anyway, sorry for ranting; I just get heated up when I see programs that don't use functions at all. *grin* From skylark at fastmail.fm Sat Oct 15 12:31:47 2005 From: skylark at fastmail.fm (Dave Shea) Date: Sat, 15 Oct 2005 23:31:47 +1300 Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) Message-ID: <001e01c5d173$af6b0d80$9c0cf6d2@default> Hi, I'm very new to Python. Today I downloaded the python-2.4.2.msi file from www.python.org I had previously installed the up-to-date Windows installer as instructed. Python installed without a complaint. However, when I fire up IDLE, there is an hour glass shown for a couple of seconds, then nothing else happens. When I fire up Python (command line) no problem, the DOS box opens and Python starts. I've tried re-starting, using Explorer instead of the Start menu, all the usual voodoo but still the IDLE refuses to start. I'm sure that I'm missing something simple here, but cannot see what it is. I've tried uninstalling, giving the registry a good going over with Nortons and re-installing all to no avail. Python works very well in command line mode but the IDLE does not seem to want to start. Any thoughts? I had thought that this entry in the FAQ might be a clue but the Microsoft Knowledge Base article it refers to does not appear to exist (any more ?). Then again, it may be nothing to do with my actual IDLE problem. http://www.python.org/doc/faq/windows.html#id15 I look forward to receiving any help Cheers. Dave Shea Wellington New Zealand From alan.gauld at freenet.co.uk Sat Oct 15 13:03:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 15 Oct 2005 12:03:54 +0100 Subject: [Tutor] Programming tutors WAS: if-else statements References: Message-ID: <02bc01c5d178$22307950$0a01a8c0@xp> > [Warning: I get totally off-topic, opinionated, and cranky in the > following rant. My apologies in advance!] Well since you've gone off topic so will I ;-) > But I get worried, though, that much teaching uses fragile techniques that > don't really scale well. I've disliked the order in which some Python > tutorials approach language features --- in particular, functions seem to > be given short shrift at times. There are lots of ways to teach a language and there are ways to teach programming. And the two things are different. That is the reaon that I deliberately don;t teach Python specific idioms in my tutor prefering to show a more general approach. I treat functions as one of the 4 basic building blocks and introduce them in my third topic 'What is Programing' but... > I really wish that someone would take a similar approach in writing a > beginner Python tutorial that focuses on functions almost immediately, > even before control flow. Something like: > > http://www.htdp.org/2003-09-26/Book/ > The problem with this approach for Python is that it requires a language with tail end recursion which allows you to use recursive function calls as the control structure. Python blows up too easily to do that so a more conventional approach is necessary - trying to explain a recursion limit error in the early stages of learning to program would just be too hard IMHO anyway! But I do agree that teaching the basic structures and princuiples is far more important than documenting all of the various options and Python specific idioms in the language - that simply teaches Python not programming. One of my pet peeves with new graduates joining our company is that they expect to get sent on a training course just because a project uses a new (to them) programming language. In most cases a day(*) with a book will be enough to become productive if you understand the basics. (*) If the language introduces a new paradigm then a course is appropriate - but to teach the paradigm(OOP, Functional programming, Predicate logic etc). Moving from Pascal to C to VB to Python or Perl or Ruby etc doesn't count! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Oct 15 13:10:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 15 Oct 2005 12:10:42 +0100 Subject: [Tutor] if-else statements References: <4460.172.152.74.182.1129266665.squirrel@172.152.74.182> Message-ID: <02c001c5d179$15c02890$0a01a8c0@xp> > and it's Java/C++ all the way. I am becoming convinced that lines of > code are not only related to the number of bugs and development speed, > but learning speed as well. Too much time tripping over syntax and > you miss the important bits. It depends. I learned to program in Pascal and a more fussy language syntractically you can't find.butt that fussy syntax really reinforced in my mind concepts such as Strong Typing, and the difference between function and procedure, argument and parameter, passing by value or reference, etc. But in C++ many of the syntactic errors encounteredcare unrelated to good practice and the fix is not to "do it right" but to apply a horrble hack like a type cast! In other words the compiler encourages bad habits not good ones. But that is a reflection on the design of the languages, neither C++ nor Java were designed for teaching, Pascal was. The former assume an experienced, understanding practitioner. Pascal assumes a beginner to the extent that experienced programmers find it frustratingly binding and inflexibvle. One of the really clever features of Python is that it can fulfill both roles well because it encourages good practice while supporting the features needed for the real world too. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wolfgang.braun at gmx.de Sat Oct 15 14:24:42 2005 From: wolfgang.braun at gmx.de (Wolfgang Braun) Date: Sat, 15 Oct 2005 14:24:42 +0200 Subject: [Tutor] os.listdir blocks threads? Message-ID: <4350F50A.1090009@gmx.de> Hello List, I try to read large directories off network shares (samba3,NT) with os.listdir(). The listdir() takes up to 5 minutes and blocks the rest of the program (gui refreshes, ...) The idea now is to put the listdir call into a separate thread so the program can go on doing stuff (see below). Unfortunately, as soon as I start a rdir instance the whole python process locks up and waits for the os.listdir to return. Plan b was to popen('/bin/ls -1 '%dir) in the rdir thread which works better but is a bit kludgy (needs to work on NT, too) and the program cannot be shudown cleanly unless the rdir thread has finished. Obviously I'm doing something wrong? What would be the Right Way to handle this situation? Thanks, Wolfgang # --- skeleton listdir in a thread class rdir(threading.Thread): def __init__(self,dir,glob=None): super(rdir,self).__init__() self.dir=dir self.content=() def start(self): self.setDaemon(True) super(dircache,self).start() def run(self): self.content=os.listdir(self.dir) # alternatively os.popen(' /bin/ls -1U '%dir) # stuff to keep run() from returning From kent37 at tds.net Sat Oct 15 14:48:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Oct 2005 08:48:31 -0400 Subject: [Tutor] if-else statements In-Reply-To: References: Message-ID: <4350FA9F.30205@tds.net> Danny Yoo wrote: > [Warning: I get totally off-topic, opinionated, and cranky in the > following rant. My apologies in advance!] > > Hi Andrew, > > But I get worried, though, that much teaching uses fragile techniques that > don't really scale well. I've disliked the order in which some Python > tutorials approach language features --- in particular, functions seem to > be given short shrift at times. > > I think the concept of functions really need to come as soon as possible: > to me, they're essential core material, and functions need to be > introduced as a way to control program complexity and allow for testing. > > I really wish that someone would take a similar approach in writing a > beginner Python tutorial that focuses on functions almost immediately, > even before control flow. You might like John Zelle's book - he teaches functions before control flow and puts a fair emphasis on using functions to eliminate duplication and improve program structure. "Python Programming: An Introduction to Computer Science" http://www.fbeedle.com/99-6.html Kent From pierre.barbier at cirad.fr Sat Oct 15 15:07:29 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Sat, 15 Oct 2005 15:07:29 +0200 Subject: [Tutor] os.listdir blocks threads? In-Reply-To: <4350F50A.1090009@gmx.de> References: <4350F50A.1090009@gmx.de> Message-ID: <4350FF11.5010001@cirad.fr> Hello, first, I believe listdir is implemented so as to block other threads because underlying C functions are *not* thread safe ! So if you try reading two directories in two different threads you may end up with really strange things happening ! For your process problem, if you want to have full control of the process while abstracting the pipe things, you may want to use the popen2 module and, more precisely, the Popen3 or Popen4 objects that will give you access to the PID. However, be aware that functions involving PID are always OS-dependant. So you may want to abstract it a bit to call UNIX, Windows or OS-X functions depending on the current plateform. Pierre Wolfgang Braun a ?crit : > Hello List, > > > I try to read large directories off network shares (samba3,NT) with > os.listdir(). The listdir() takes up to 5 minutes and blocks the rest of > the program (gui refreshes, ...) > > The idea now is to put the listdir call into a separate thread so the > program can go on doing stuff (see below). > > Unfortunately, as soon as I start a rdir instance the whole python > process locks up and waits for the os.listdir to return. > > Plan b was to popen('/bin/ls -1 '%dir) in the rdir thread which works > better but is a bit kludgy (needs to work on NT, too) and the program > cannot be shudown cleanly unless the rdir thread has finished. > > > Obviously I'm doing something wrong? What would be the Right Way to > handle this situation? > > > Thanks, > Wolfgang > > > # --- skeleton listdir in a thread > > class rdir(threading.Thread): > def __init__(self,dir,glob=None): > super(rdir,self).__init__() > self.dir=dir > self.content=() > > def start(self): > self.setDaemon(True) > super(dircache,self).start() > > def run(self): > self.content=os.listdir(self.dir) > # alternatively os.popen(' /bin/ls -1U '%dir) > # stuff to keep run() from returning > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From andy.dani at lycos.com Sat Oct 15 17:22:35 2005 From: andy.dani at lycos.com (Andy Dani) Date: Sat, 15 Oct 2005 10:22:35 -0500 Subject: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path Message-ID: <20051015152235.36A0FCA071@ws7-4.us4.outblaze.com> Thanks Nick, Any idea about the second question? When I python from /usr/loca/Python-2.4.1/bin, it does launch the interpreter but with an traceback error saying there is some conflict with "import readline" line on pythonrc.py file located somewhere in /etc/ directory. Is there any harm If I comment the it out (import readline)? Thanks - Andy ----- Original Message ----- From: "Nick Lunt" To: "Andy Dani" , tutor at python.org Subject: RE: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path Date: Fri, 14 Oct 2005 20:12:33 +0100 > > Hi Andy, > > > > Behalf Of Andy Dani > > > > Python 2.3.2 came with the linux distribution which is located in > > /usr/lib. > > > > Installed 2.4.1 in /usr/local/Python-2.4.1 > > > > updated /etc/profile path so IDLE or "python" would point to the > > latest version (2.4.1). > > > > PATH="$PATH:/usr/local/Python-2.4.1/:." > > export PATH > > > > But it is still pointing to the old one unless I go > > /use/local/Python-2.4.1/python. > > > > I want to be able to launch and run python 2.4.1, from the user > > account so I do not need to be "root" every time. > > The default install of python on Mandrake probably install the python > executable in /usr/bin/python. > /usr/bin/ is in your PATH, so if you put PATH=$PATH:/usr/local/Python-2.4.1 > in /etc/profile it will still pick up the default python install. > > Try typing 'which python' at the command line and see what it picks up. > Chances are it will be /usr/bin/python. > > You could solve this by either putting > PATH=/path/to/my/wanted/python/dir:$PATH in /etc/profile (or > ~/.bash_profile) or by putting an alias in ~/.bashrc, such as 'alias > python='path/to/my/wanted/python/dir/python'. > > What I must stress is that you do not overwrite your default python > installation, leave it as it is, otherwise many of mandrakes GUI tools will > no work. > > I hope that helps, feel free to ask more questions about this as I have had > to overcome the same issue on RHEL serveral times. > > Hth, > Nick . Thank You Andy andy.dani at lycos.com (647) 222 9073 ============================= He is able who thinks he is able -Buddha -- _______________________________________________ Search for businesses by name, location, or phone number. -Lycos Yellow Pages http://r.lycos.com/r/yp_emailfooter/http://yellowpages.lycos.com/default.asp?SRC=lycos10 From kent37 at tds.net Sat Oct 15 17:37:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Oct 2005 11:37:13 -0400 Subject: [Tutor] slide show won't display the images in right, order In-Reply-To: <43504FE5.4020109@gmail.com> References: <43504FE5.4020109@gmail.com> Message-ID: <43512229.7090801@tds.net> Joseph Quigley wrote: > This suggestion: > > date = files[x] > Data.year = date[2:4] > Data.month = date[4:6] > Data.day = date[6:8] > > > Doesn't work because DspImage needs a concatenated string. (you'll see > a 07/28/['5'] instead of the current 07/28/05. Did you try it? Presuming your file names look something like this: >>> date = 'xx051015.jpg' Taking a slice of a string gives another string: >>> date[2:4] '05' Which is exactly the same as turning the string into a list (of strings) and concatenating: >>> datel=list(date) >>> datel[2] + datel[3] '05' Kent PS Please reply on list so everyone can benefit From damien.gouteux at gmail.com Sat Oct 15 20:28:02 2005 From: damien.gouteux at gmail.com (Damien Gouteux) Date: Sat, 15 Oct 2005 20:28:02 +0200 Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) In-Reply-To: <001e01c5d173$af6b0d80$9c0cf6d2@default> References: <001e01c5d173$af6b0d80$9c0cf6d2@default> Message-ID: <43514A32.4010007@gmail.com> Try to right-click on a python file and click 'Edit with IDLE'. IDLE doesn't work without a file in argument. I hope it will help you. Damien G. Dave Shea wrote: >Hi, > >I'm very new to Python. Today I downloaded the python-2.4.2.msi file from >www.python.org > >I had previously installed the up-to-date Windows installer as instructed. > >Python installed without a complaint. However, when I fire up IDLE, there is >an hour glass shown for a couple of seconds, then nothing else happens. When >I fire up Python (command line) no problem, the DOS box opens and Python >starts. I've tried re-starting, using Explorer instead of the Start menu, >all the usual voodoo but still the IDLE refuses to start. > >I'm sure that I'm missing something simple here, but cannot see what it is. >I've tried uninstalling, giving the registry a good going over with Nortons >and re-installing all to no avail. Python works very well in command line >mode but the IDLE does not seem to want to start. > >Any thoughts? > >I had thought that this entry in the FAQ might be a clue but the Microsoft >Knowledge Base article it refers to does not appear to exist (any more ?). >Then again, it may be nothing to do with my actual IDLE problem. >http://www.python.org/doc/faq/windows.html#id15 > >I look forward to receiving any help > >Cheers. > >Dave Shea >Wellington >New Zealand > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From adam.jtm30 at gmail.com Sat Oct 15 21:13:25 2005 From: adam.jtm30 at gmail.com (Adam) Date: Sat, 15 Oct 2005 20:13:25 +0100 Subject: [Tutor] Any good Glade and python tutorials? Message-ID: I'm making a Twisted app that needs a client side GUI and GTK seems like the best way to go about this. Can anybody point me in the direction of any decent tutorials on how to use Glade with python and pyGTK. Thanks. Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051015/28c3353f/attachment.html From zamb at saudi.net.sa Sat Oct 15 21:37:04 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Sat, 15 Oct 2005 22:37:04 +0300 Subject: [Tutor] Any good Glade and python tutorials? In-Reply-To: References: Message-ID: <1129405024.2378.1.camel@localhost.localdomain> On Sat, 2005-10-15 at 20:13 +0100, Adam wrote: > I'm making a Twisted app that needs a client side GUI and GTK seems > like the best way to go about this. Can anybody point me in the > direction of any decent tutorials on how to use Glade with python and > pyGTK. > Thanks. > Adam. http://primates.ximian.com/~sandino/python-glade/ Take care. Ziyad. From nick at javacat.f2s.com Sat Oct 15 21:39:58 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Sat, 15 Oct 2005 20:39:58 +0100 Subject: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path In-Reply-To: <20051015152235.36A0FCA071@ws7-4.us4.outblaze.com> References: <20051015152235.36A0FCA071@ws7-4.us4.outblaze.com> Message-ID: <43515B0E.9090700@javacat.f2s.com> Hi Andy, Andy Dani wrote: >Thanks Nick, > >Any idea about the second question? When I python from /usr/loca/Python-2.4.1/bin, it does launch the interpreter but with an traceback error saying there is some conflict with "import readline" line on pythonrc.py file located somewhere in /etc/ directory. Is there any harm If I comment the it out (import readline)? > >Thanks - Andy > > Im sorry I have no idea what problem your having with "import readline", I have never come across that error. However, Im certain that one of the python tutors will be able to help you out. Good Luck, Nick . From alan.gauld at freenet.co.uk Sun Oct 16 00:12:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 15 Oct 2005 23:12:09 +0100 Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) References: <001e01c5d173$af6b0d80$9c0cf6d2@default> Message-ID: <02d301c5d1d5$7cf46d80$0a01a8c0@xp> > Python installed without a complaint. However, when I fire up IDLE, there > is > an hour glass shown for a couple of seconds, then nothing else happens. Personally, since you are on Windows, I'd try using Pythonwin instead. In most respects its a better tool that IDLE but only works on Windows. Its part of the winall package that you need to download separately to Python, but you'll need it if you want to do anything windows specific anyway! > mode but the IDLE does not seem to want to start. As a matter of interest what happens when you type this at the command prompt: >>> from Tkinter import * >>> top = Tk() >>> Label(top,text='Hello world').pack() >>> top.mainloop() It should display the label in a small window which you can close using the usual windows control widget. If that works it means Tkinter(upon which IDLE is built) is working OK If not it might be worth a reinstall to try and get Tkinter working. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Sun Oct 16 01:14:33 2005 From: wescpy at gmail.com (w chun) Date: Sat, 15 Oct 2005 16:14:33 -0700 Subject: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path In-Reply-To: <20051015152235.36A0FCA071@ws7-4.us4.outblaze.com> References: <20051015152235.36A0FCA071@ws7-4.us4.outblaze.com> Message-ID: <78b3a9580510151614i21320d21i1db540f59b2b929b@mail.gmail.com> On 10/15/05, Andy Dani wrote: >When I python from /usr/loca/Python-2.4.1/bin, it does launch the interpreter but with an traceback error saying there is some conflict with "import readline" line on pythonrc.py file located somewhere in /etc/ directory. Is there any harm If I comment the it out (import readline)? andy, did you build 2.4.1 yourself and install it in /usr/local? it's possible that when you compiled it, you did not have the readline library installed -- Python by default looks for it and tries to build Python with it. you may have to download the readline code, build it 1st, then rebuild Python. the readline page is http://cnswww.cns.cwru.edu/~chet/readline/rltop.html i would say commenting out the import line is not a good idea. an import stmt like the one in question usually means that a module will be doing something with it, i.e., readline.XXX(). if you take it out, you'll likely get an error that reads something like, "NameError: global name 'readline' not found." hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dyoo at hkn.eecs.berkeley.edu Sun Oct 16 02:02:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 15 Oct 2005 17:02:09 -0700 (PDT) Subject: [Tutor] Focus on the functions [Was Re: if-else statements] In-Reply-To: <4350FA9F.30205@tds.net> Message-ID: On Sat, 15 Oct 2005, Kent Johnson wrote: > > I really wish that someone would take a similar approach in writing a > > beginner Python tutorial that focuses on functions almost immediately, > > even before control flow. > > You might like John Zelle's book - he teaches functions before control > flow and puts a fair emphasis on using functions to eliminate > duplication and improve program structure. > > "Python Programming: An Introduction to Computer Science" > http://www.fbeedle.com/99-6.html Hi Kent, Thanks for the book reference; it's nice that some portions of the book are available in PDF format. I apologize to the list again for the noisy contentless ranting I made yesterday, so I'll try making it up by doing concrete demos of a function-focused approach. This will critique Zelle's Chapter Two and Chapter Five, and see what things would look like if under a function regime. The 'convert.py' program on Chapter 2 is of the form: ###### # convert.py # A program to convert Celsius tmps to Fahrenheit # by: Susan Computewell def main(): celsius = input("What is the Celsius temperature? ") fahrenheit = (9.0 / 5.0) * celsius + 32 print "The temperature is", fahrenheit, "degrees Fahrenheit" main() ###### It would have been nicer to strip out the input/output stuff altogether, and just straight into showing a to_fahrenheit() function: ####### def to_fahrenheit(celsius): """A function to convert celsius tmps to Fahrenheit.""" return (9.0 / 5.0) * celsius + 32 ####### This function can then be used from the interactive interpreter, because the interactive interpreter prompt itself serves as a good place to do program interaction: ###### >>> to_fahrenheit(0) 32.0 >>> to_fahrenheit(100) 212.0 ###### If we're going to take advantage of any Python-specific feature, it might as well be the interactive interpreter prompt. One of Python's greatest strengths is that it has a good interactive interpreter prompt that we can use for casual experimentation. My feeling is that 'input()' and 'print' isn't really useful until we get to the point of writing programs that other people are meant to use. Until then, the interactive interpreter is sufficient as our 'user interface' to the program. As another example, something like the average program: ###### def main(): print "This program computes the average of two exam scores" score1, score2 = input("Enter two scores separated by commas") average = (score1 + score2) / 2.0 print "The average of the scores is:", average main() ###### could be reduced to a small function: ###### def average(score1, score2): """Computes the average of two exam scores.""" return (score1 + score2) / 2.0 ###### Another obvious example where an earlier introduction of functions would have helped would be the example on Chapter 5 on drawing two "eyes": ###### leftEye = Circle(Point(80, 50), 5) leftEye.setFill('yellow') leftEye.setOutline('red') rightEye = Circle(Point(100, 50), 5) rightEye.setFill('yellow') rightEye.setOutline('red') ###### The approach advocated by the book was to know that certain objects could be cloned() through the graphics API: ###### leftEye = Circle(Point(80, 50), 5) leftEye.setFill('yellow') leftEye.setOutline('red') rightEye = leftEye.clone() rightEye.move(20, 0) ###### But to me, this is a "trick" in the sense that it's teaching a technique that doesn't apply to situations in general --- if we didn't have clone(), what would we have done then? A more useful approach would have been to use functions: ###### def Eye(centerx, centery): """Builds a new eye at the point given by (centerx, centery).""" eye = Circle(Point(centerx, centery), 5) eye.setFill('yellow') eye.setOutline('red') return eye leftEye = Eye(80, 50) rightEye = Eye(100, 50) ###### An Eye() definition allows us to go crazy with Mr. Potatohead without having to think so much about the individual atomic steps we have to do to build an eye each time. If we want a triclops, then building another eye is just a matter of calling Eye() with a different center, just as building a Circle is a matter of providing a Point and a size. I do see that after functions are introduced that things start to pick up. But I really do think that writing functions should have come up in Chapter One or Two, and not as late in the game as Chapter Six. That's what I don't get. Anyway, hope this helps! From norman at littletank.org Sun Oct 16 17:11:00 2005 From: norman at littletank.org (Norman Silverstone) Date: Sun, 16 Oct 2005 16:11:00 +0100 Subject: [Tutor] Focus on the functions [Was Re: if-else statements] In-Reply-To: References: Message-ID: <1129475460.378.26.camel@localhost.localdomain> > I apologize to the list again for the noisy contentless ranting I made > yesterday, so I'll try making it up by doing concrete demos of a > function-focused approach. This will critique Zelle's Chapter Two and > Chapter Five, and see what things would look like if under a function > regime. > < snip> I am an elderly person somewhat physically handicapped with some experience programming in basic and pascal, many years ago. In order to keep myself mentally active I decided to have a look once again at programming and chose python as a good language to start with. So, I had a look at 'Dive into Python', bought a couple of books, 'Python Programming for the Absolute Beginner' and 'Learn to program Using Python'. All was well to start with until I came to the section on functions. I am finding it very difficult to grasp the reasoning behind the use of functions and how and when to use them. I keep trying to see if any of the snippets of programs that I have already come across are transferable into functions without a great deal of success. The problem appears to be that, and here I agree with the writer, functions are introduced as something on their own, well after manipulating strings, lists, dictionaries, tuples, loops etc are dealt with. Having studied the examples given here, I am beginning to get some understanding of what is going on. If only I could find many more examples like these, in simple English, I would be a very happy student. > Anyway, hope this helps! It certainly helps me. Norman From bgailer at alum.rpi.edu Sun Oct 16 18:14:31 2005 From: bgailer at alum.rpi.edu (bob) Date: Sun, 16 Oct 2005 09:14:31 -0700 Subject: [Tutor] Focus on the functions [Was Re: if-else statements] In-Reply-To: <1129475460.378.26.camel@localhost.localdomain> References: <1129475460.378.26.camel@localhost.localdomain> Message-ID: <6.1.2.0.0.20051016090056.035209e8@mail.mric.net> At 08:11 AM 10/16/2005, Norman Silverstone wrote: >I am an elderly person somewhat physically handicapped with some >experience programming in basic and pascal, many years ago. In order to >keep myself mentally active I decided to have a look once again at >programming and chose python as a good language to start with. So, I had >a look at 'Dive into Python', bought a couple of books, 'Python >Programming for the Absolute Beginner' and 'Learn to program Using >Python'. > >All was well to start with until I came to the section on functions. I >am finding it very difficult to grasp the reasoning behind the use of >functions and how and when to use them. 1) did you ever use GOSUB in Basic or procedure or function in Pascal? If so, same thing here. 2) functions: a) as a way to set aside pieces of code `that might otherwise obscure an algorithm. For example if I have a complex calculation to do inside some loop it may make the program easier to read to put the calculation in a function and call the function from w/in the loop. b) the classical use of functions is to package code that might be called from more than one place rather than writing the same code twice. c) in Python (different than Basic or Pascal) functions are objects that can be passed around, allowing for things like dictionaries that choose which function to use based on some input or condition. d) in classes functions become methods, a way to evoke a behavior of an object. [snip] From adam.jtm30 at gmail.com Sun Oct 16 22:51:37 2005 From: adam.jtm30 at gmail.com (Adam) Date: Sun, 16 Oct 2005 21:51:37 +0100 Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) In-Reply-To: <000201c5d22d$fabed9a0$e709f6d2@default> References: <001e01c5d173$af6b0d80$9c0cf6d2@default> <000201c5d22d$fabed9a0$e709f6d2@default> Message-ID: On 16/10/05, Dave Shea wrote: > > Hi Adam, > > Thanks for your reponse. I tried your suggestion of starting IDLE via the > command line. > > Using the command and parameter line that install created behind the > Python > (IDLE) icon on my Start menu: > > C:\WINDOWS\DESKTOP>"C:\Program Files\Python24\pythonw.exe" "C:\Program > Files\Python24\Lib\idlelib\idle.pyw" > > C:\WINDOWS\DESKTOP> > > Nothing appears to happen except a pause between hitting and > getting > the DOS prompt back to me. > > I tried this again, but this timechanges the called program to be > python.exe > rather than the original pythonw.exe > > C:\WINDOWS\DESKTOP>"C:\Program Files\Python24\python.exe" "C:\Program > Files\Python24\Lib\idlelib\idle.pyw" > Traceback (most recent call last): > File "C:\Program Files\Python24\Lib\idlelib\idle.pyw", line 6, in ? > import PyShell > File "C:\PROGRAM FILES\PYTHON24\lib\idlelib\PyShell.py", line 9, in ? > import socket > File "C:\PROGRAM FILES\PYTHON24\lib\socket.py", line 45, in ? > import _socket > ImportError: DLL load failed: One of the library files needed to run this > application cannot be found. > > I'm not sure if the errors that have been reported above are simply > because > it makes no sense to call idle.pyw as a parameter to python.exe or whether > these errors give some clues to the actual problem I am experiencing > sinply > getting IDLE going. > > Now, here I'm talking out of my league, but I ran a test on Tkinter as > suggested on one of the support pages > (http://mail.python.org/pipermail/python-list/2000-January/020199.html) > as: > >>> import Tkinter > >>> Tkinter._test() > > and this caused the little test dialog box to appear so I assume that > Tkinter is installed correctly. > > Any further thoughts? > > Cheers, > > Dave. > ----- Original Message ----- > From: "Adam" > To: "Dave Shea" > Sent: Sunday, October 16, 2005 1:34 AM > Subject: Re: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) > > > Try opening IDLE from the command line and see what, if any errors it > gives > you. > python idlelib\idle.py > from your python directory should work. > > On 15/10/05, Dave Shea wrote: > > > > Hi, > > > > I'm very new to Python. Today I downloaded the python-2.4.2.msi file > from > > www.python.org > > > > I had previously installed the up-to-date Windows installer as > instructed. > > > > Python installed without a complaint. However, when I fire up IDLE, > there > > is > > an hour glass shown for a couple of seconds, then nothing else happens. > > When > > I fire up Python (command line) no problem, the DOS box opens and Python > > starts. I've tried re-starting, using Explorer instead of the Start > menu, > > all the usual voodoo but still the IDLE refuses to start. > > > > I'm sure that I'm missing something simple here, but cannot see what it > > is. > > I've tried uninstalling, giving the registry a good going over with > > Nortons > > and re-installing all to no avail. Python works very well in command > line > > mode but the IDLE does not seem to want to start. > > > > Any thoughts? > > > > I had thought that this entry in the FAQ might be a clue but the > Microsoft > > Knowledge Base article it refers to does not appear to exist (any more > ?). > > Then again, it may be nothing to do with my actual IDLE problem. > > http://www.python.org/doc/faq/windows.html#id15 > > > > I look forward to receiving any help > > > > Cheers. > > > > Dave Shea > > Wellington > > New Zealand > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > Try "C:\Program Files\Python24\python.exe" "C:\Program Files\Python24\Lib\idlelib\idle.py" instead of the idle.pyw and tell me what happens. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051016/b661b69d/attachment.htm From ajikoe at gmail.com Sun Oct 16 23:15:03 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Sun, 16 Oct 2005 23:15:03 +0200 Subject: [Tutor] Focus on the functions [Was Re: if-else statements] In-Reply-To: <1129475460.378.26.camel@localhost.localdomain> References: <1129475460.378.26.camel@localhost.localdomain> Message-ID: Dear Norman, You can reuse function, this make your code more easy to handle. Suppose you have code to calculate area of rectangle, but this time you like to calculate 3 times: width = 3; length = 2 print 'area', width * length width = 1; length =32 print 'area', width * length width = 31; length = 22 print 'area', width * length it is better if you have function func_area def func_area(width,length): return func_area(width,length) then your code becomes: width = 3; length = 2 print 'area', func_area(width,length) width = 1; length =32 print 'area', func_area(width,length) width = 31; length = 22 print 'area', func_area(width ,length) And something happened that a new area formulation of rectangle is = width * length * length (of course this is wrong, it is only an example that your formula or code sometime needs to be changed), so instead of writing all of this formulation one by one which prone to error, you can change only your defined function func_area. def func_area(width,length): return width * length * length And you get the right result. The key here is that you can change your code easily. The next day you create a code in another module for example new_module.py then you would like to use your func_area which in old_module.py, then you can just import and use it. in your new_module.py you can type: import old_module print 'area of rectangle according old module is : ', old_module.func_area(11,22) The key here is that you can reuse your function when you need it in other module. Hope this help you understand a little bit the function of a function Cheers, pujo Cheers, pujo On 10/16/05, Norman Silverstone wrote: > > > > I apologize to the list again for the noisy contentless ranting I made > > yesterday, so I'll try making it up by doing concrete demos of a > > function-focused approach. This will critique Zelle's Chapter Two and > > Chapter Five, and see what things would look like if under a function > > regime. > > > < snip> > > I am an elderly person somewhat physically handicapped with some > experience programming in basic and pascal, many years ago. In order to > keep myself mentally active I decided to have a look once again at > programming and chose python as a good language to start with. So, I had > a look at 'Dive into Python', bought a couple of books, 'Python > Programming for the Absolute Beginner' and 'Learn to program Using > Python'. > > All was well to start with until I came to the section on functions. I > am finding it very difficult to grasp the reasoning behind the use of > functions and how and when to use them. I keep trying to see if any of > the snippets of programs that I have already come across are > transferable into functions without a great deal of success. The problem > appears to be that, and here I agree with the writer, functions are > introduced as something on their own, well after manipulating strings, > lists, dictionaries, tuples, loops etc are dealt with. > > Having studied the examples given here, I am beginning to get some > understanding of what is going on. If only I could find many more > examples like these, in simple English, I would be a very happy student. > > > Anyway, hope this helps! > > It certainly helps me. > > Norman > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051016/f115270d/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Oct 17 05:32:46 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 16 Oct 2005 20:32:46 -0700 (PDT) Subject: [Tutor] Focus on the functions [Was Re: if-else statements] In-Reply-To: <1129475460.378.26.camel@localhost.localdomain> Message-ID: > Having studied the examples given here, I am beginning to get some > understanding of what is going on. If only I could find many more > examples like these, in simple English, I would be a very happy student. [Note: this is a fairly long post. Didn't know how to do the subject justice without really doing some work. *grin*] Hi Norman, I'm a concrete-examples sort of person, so I'll take an example from another tutorial and see if I can talk about functions in that context. Ah, good, there's an 'area.py' example in Josh Cogliati's "Non-programmers Tutorial For Python" that looks ripe. It's near the bottom of: http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html Let's tear it apar... er, I mean, let's do some constructive criticism. *grin* For starters, here's what it looks like (with some small edits): ################################################################# def hello(): print 'Hello!' def area(width,height): return width*height def print_welcome(name): print 'Welcome,',name name = raw_input('Your Name: ') hello() print_welcome(name) print print 'To find the area of a rectangle,' print 'Enter the width and height below.' print w = input('Width: ') while w <= 0: print 'Must be a positive number' w = input('Width: ') h = input('Height: ') while h <= 0: print 'Must be a positive number' h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h) ################################################################# In this example, the area program uses functions to try to give names to particular concepts. The hello() function tries to capture the idea of saying hello, and print_welcome() is a function that tries to give a personal welcome to the user. We also see an area function that takes a width and height, and returns the area of a triangle of those dimensions. There are many possible ways of capturing related concepts together in functions. For example, we might think that the personal greeting stuff with hello() and print_welcome() should really be considered bundled together as a single concept. We might do something like this: ###### def print_personal_hello(): name = raw_input('Your Name: ') hello() print_welcome(name) ###### And if we make this function, then we can change our program to use this new function: ###### print_personal_hello() print print 'To find the area of a rectangle,' print 'Enter the width and height below.' print w = input('Width: ') while w <= 0: print 'Must be a positive number' w = input('Width: ') h = input('Height: ') while h <= 0: print 'Must be a positive number' h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h) ###### If we take a revised look at this program, we might also think that the initial instruction print statements should be boxed too as a print_instructions() function: ###### def print_instructions(): print print 'To find the area of a rectangle,' print 'Enter the width and height below.' print ###### Again, we're writing a function so that we can express the idea that those print statements belong together. Because I personally think they're related conceptually, I'm expressing that idea by boxing them with a function. Let's see what the program looks like now with those two new functions: ###### print_personal_hello() print_instructions() w = input('Width: ') while w <= 0: print 'Must be a positive number' w = input('Width: ') h = input('Height: ') while h <= 0: print 'Must be a positive number' h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h) ###### I think you can guess what I'm looking at next. To an experienced eye, cut-and-pasted code is really ugly and a prime target for functions, so we're going to go after that next. This particular part of the program tries to input positive integers for width and height. Let's look at the width-grabbing code: ###### w = input('Width: ') while w <= 0: print 'Must be a positive number' w = input('Width: ') ###### This block of code is trying to get a positive number. We can do an initial revision of this code by doing this: ###### def read_width(): w = input('Width: ') while w <= 0: print 'Must be a positive number' w = input('Width: ') return w ###### If we look at this a little closer, though, we can still see duplication: that 'Width:' string is repeated twice, and also repeated in the name of the function as read_width. So perhaps it might be useful to make the function a little more general by making it take the dimension as a parameter. Let's take read_width() and turn it into read_dimension(): ####### def read_dimension(dim): d = input(dim + ': ') while d <= 0: print 'Must be a positive number' d = input(dim + ': ') return d def read_width(): return read_dimension('Width') ####### We know that process of reading the height is going to look really similar to read_width(), so let's express that too: ###### def read_height(): return read_dimension('Height') ###### What does the program look like now? Since we've been doing so much transformation, let's make this self-contained and repeat the function definitions too, just so we remember what in the world we've been doing. *grin* ################################################################### def hello(): print 'Hello!' def print_welcome(name): print 'Welcome,',name def print_personal_hello(): name = raw_input('Your Name: ') hello() print_welcome(name) def print_instructions(): print print 'To find the area of a rectangle,' print 'Enter the width and height below.' print def area(width,height): return width*height def read_dimension(dim): d = input(dim + ': ') while d <= 0: print 'Must be a positive number' d = input(dim + ': ') return d def read_width(): return read_dimension('Width') def read_height(): return read_dimension('Height') print_personal_hello() print_instructions() w = read_width() h = read_height() print 'Width =',w,' Height =',h,' so Area =',area(w,h) ################################################################### Let's stop turning things into functions at this point, and review. The program has expanded a bit! Some of the functions we've written are actually a little useless, so if we were to go further, we might consider undoing some of the "useless" functions by inlining, and that should reduce the overall lines of the file. (Of course, what we'd consider to be "useless" is subjective. I think the hello() and print_welcome() functions could be inlined into print_personal_hello().) But even with that expansion, we can now read the motions of our program as the following steps: print_personal_hello() print_instructions() w = read_width() h = read_height() print 'Width =',w,' Height =',h,' so Area =',area(w,h) We've turned the main program from a bunch of disconnected print statements and while loops into fairly straightforward "straight-line" code. (That last statement looks funny, so I'd personally turn that into a function called "print_final_report" or something, just to be consistent.) In all of this, although we've done some major movement of code around, we have not added anything in terms of what the program will do. All the function refactoring we've been doing should still preserve the original program's behavior. We write our programs with functions, then, not for our computer's benefit, but for our human readers. I hope this made some sort of sense. If you have questions, please feel free to ask! From dyoo at hkn.eecs.berkeley.edu Mon Oct 17 06:17:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 16 Oct 2005 21:17:39 -0700 (PDT) Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) In-Reply-To: <001e01c5d173$af6b0d80$9c0cf6d2@default> Message-ID: On Sat, 15 Oct 2005, Dave Shea wrote: > Python installed without a complaint. However, when I fire up IDLE, > there is an hour glass shown for a couple of seconds, then nothing else > happens. When I fire up Python (command line) no problem, the DOS box > opens and Python starts. I've tried re-starting, using Explorer instead > of the Start menu, all the usual voodoo but still the IDLE refuses to > start. Hi Dave, According to: http://python.org/2.4.2/bugs.html IDLE might not work well if Python has been installed into Program Files. Do you know if you've done this? If so, try reinstalling and just leave the installation path at the defaults (Python should install under "C:\PYTHON24", I think.) IDLE has unfortunately been a bit problematic in the Python 2.4 release, so if you continue to run into issues, I'd second Alan's suggestion about trying Pythonwin instead. Good luck! From norman at littletank.org Mon Oct 17 11:59:19 2005 From: norman at littletank.org (Norman Silverstone) Date: Mon, 17 Oct 2005 10:59:19 +0100 Subject: [Tutor] functions Message-ID: <1129543159.7813.5.camel@localhost.localdomain> I am greatly impressed by the most useful instruction I have received since I raised my need for help on this subject. The more I read the more things fall into place. My grateful thanks to one and all and please keep the good stuff flowing. Norman From Thomas.Beale at manchester.ac.uk Mon Oct 17 14:46:37 2005 From: Thomas.Beale at manchester.ac.uk (Tom Beale) Date: Mon, 17 Oct 2005 13:46:37 +0100 Subject: [Tutor] extentions and osX Message-ID: <9C645830-B158-4297-BCC3-D9E02D4B8692@manchester.ac.uk> I have a problem with a c++ extension into a python program. I am trying to run a program written by someone else. It has been written and tested on linux/intel but I don't have access to a linux machine at the moment, so I am attempting to run it on osX (G4). When the program runs I get a segmentation fault. This happens when it reaches the line import _contributionForPixel which has previously been created by setup.py which is as follows: #!/usr/bin/env python # To use: # python setup.py install # import os, sys, string, re from glob import glob import distutils #try: import distutils from distutils.command.install import install from distutils.core import setup, Extension # except: # raise SystemExit, "Distutils problem, see Numeric README." headers = glob (os.path.join ("Include","*.h") ) header = headers + glob (os.path.join ("Include/Numeric","*.h") ) # The version is set in Lib/numeric_version.py setup (name = "extension", description = " Extension to Python", ext_modules = [Extension('_contributionForPixel', ['contribution.cc', 'contribution_wrap.cxx' ] , include_dirs = ['./'] ), ] ) Can someone point me in the right direction? Is it likely there is a problem with the original contribution.cc file (even though setup python build) runs fine, or is there some problem with the way it is linked. I am using python 2.4.1 on osX 10.4 Thanks Tom. From hugonz-lists at h-lab.net Mon Oct 17 20:12:11 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 17 Oct 2005 12:12:11 -0600 Subject: [Tutor] os.listdir blocks threads? In-Reply-To: <4350F50A.1090009@gmx.de> References: <4350F50A.1090009@gmx.de> Message-ID: <4353E97B.5060303@h-lab.net> Hi, I wrote a quick module for spawning a subprocess and run the function, just as an excercise, after I read your post... It will spawn a subprocess, then pass the serialized return values to the parent. So, if you want to do: lala = os.listdir(".") you do lala = fmg(os.listdir, ".") This will not block, but it will run only on UNIX/Linux, unless there is a version of python that includes support for cygwin, which has fork() for Win32. The module is below: ################################################################### """ fmg.py As all threads will block on a call to some os functions, this implements a function for doing thread-safe syscalls/C library functions using a child process. Availability: UNIX """ import os import cPickle def fork_me_gently(myfunct, *myargs): """fork_me_gently(callable, arguments) -> retval Make an arbitrary function pseudo thread-safe by running it in a child process. Return what the passed callable returns.""" #prepare a pipe for child-parent communication r_end, w_end = os.pipe() pid = os.fork() if pid == 0: #child retval = myfunct(*myargs) #Serialize list for sending to pipe #dump() needs a file object, not a fd w_end_fo = os.fdopen(w_end, 'w') cPickle.dump(retval, w_end_fo) w_end_fo.close() # DIE, CHILD! raise SystemExit else: #parent # load() needs a file object r_end_fo = os.fdopen(r_end) retval = cPickle.load(r_end_fo) #clean up after yourself before continuing os.waitpid(pid, 0) return(retval) fmg = fork_me_gently if __name__ == "__main__": #temp = ts_listdir(".") temp = fmg(os.listdir, ".") for i in temp: print i Wolfgang Braun wrote: > Hello List, > > > I try to read large directories off network shares (samba3,NT) with > os.listdir(). The listdir() takes up to 5 minutes and blocks the rest of > the program (gui refreshes, ...) > > The idea now is to put the listdir call into a separate thread so the > program can go on doing stuff (see below). > > Unfortunately, as soon as I start a rdir instance the whole python > process locks up and waits for the os.listdir to return. > > Plan b was to popen('/bin/ls -1 '%dir) in the rdir thread which works > better but is a bit kludgy (needs to work on NT, too) and the program > cannot be shudown cleanly unless the rdir thread has finished. > > > Obviously I'm doing something wrong? What would be the Right Way to > handle this situation? > > > Thanks, > Wolfgang > > > # --- skeleton listdir in a thread > > class rdir(threading.Thread): > def __init__(self,dir,glob=None): > super(rdir,self).__init__() > self.dir=dir > self.content=() > > def start(self): > self.setDaemon(True) > super(dircache,self).start() > > def run(self): > self.content=os.listdir(self.dir) > # alternatively os.popen(' /bin/ls -1U '%dir) > # stuff to keep run() from returning > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From luke.jordan at gmail.com Mon Oct 17 20:18:39 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Mon, 17 Oct 2005 13:18:39 -0500 Subject: [Tutor] Assign to vars by iteration Message-ID: I've got a bunch of pickled class instances, and I'm trying to load them as variables using a function. The class has a self.name attribute, and I've got a list of self.name for all the instances pickled separately. When I would like to attach the names of each instance to the corresponding class instance (using self.name def loadClassInst(): classInstFile = "filepath" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051017/382de065/attachment.html From luke.jordan at gmail.com Mon Oct 17 20:19:10 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Mon, 17 Oct 2005 13:19:10 -0500 Subject: [Tutor] Please excuse the previous message sent in error Message-ID: Sincerely, Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051017/e164e31a/attachment.htm From wescpy at gmail.com Mon Oct 17 20:50:37 2005 From: wescpy at gmail.com (w chun) Date: Mon, 17 Oct 2005 11:50:37 -0700 Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) In-Reply-To: References: <001e01c5d173$af6b0d80$9c0cf6d2@default> Message-ID: <78b3a9580510171150s42ef7d52vddabb9547a8a134a@mail.gmail.com> On 10/16/05, Danny Yoo wrote: > > On Sat, 15 Oct 2005, Dave Shea wrote: > > > Python installed without a complaint. However, when I fire up IDLE, > > there is an hour glass shown for a couple of seconds, then nothing else > > happens. When I fire up Python (command line) no problem, the DOS box > > opens and Python starts. I've tried re-starting, using Explorer instead > > of the Start menu, all the usual voodoo but still the IDLE refuses to > > start. > > Hi Dave, > > According to: > > http://python.org/2.4.2/bugs.html > > IDLE might not work well if Python has been installed into Program Files. > > Do you know if you've done this? If so, try reinstalling and just leave > the installation path at the defaults (Python should install under > "C:\PYTHON24", I think.) yep, danny is right. there always seems to be problems when there is a DOS (C:\PROGRA~1) vs Win32 (C:\Program Files) filenaming issue. i ran into this in previous versions of Python, and have never installed it anywhere else other than C:\Python2x ever again. if it still doesn't work, then i too, would recommend downloading the latest copy of win32all and PythonWin. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051017/555244d4/attachment.html From python at jayloden.com Mon Oct 17 21:13:35 2005 From: python at jayloden.com (Jay Loden) Date: Mon, 17 Oct 2005 15:13:35 -0400 Subject: [Tutor] hand-holding for web development In-Reply-To: <965122bf0510131249had88b1fmf6124787e206a410@mail.gmail.com> References: <965122bf0510131249had88b1fmf6124787e206a410@mail.gmail.com> Message-ID: <200510171513.36008.python@jayloden.com> You need an Apache config section to tell it what to use mod_python on and how. For example, in httpd.conf or a separate file in your conf.d directory for apache: AddHandler mod_python .py PythonHandler test PythonDebug On tells Apache to use mod_python on all .py files in my /var/www/html directory (which is also the document root on my server). Once that's loaded you should be able to run whatever your python code through a handler. For example, saving this as test.py: # #mod_python super basic test script # from mod_python import apache def handler(req): req.content_type = "text/html" req_file = basename(req.uri) if req.header_only: return apache.OK else: req.write("mod_python is working") return apache.OK # end of script This should print "mod_python is working" to the browser if you visit http://yoursite.com/test.py Remember that you need to restart/reload apache after any config change. The basic gist is that any .py file you load in the /var/www/html runs the script "test.py" (PythonHandler test) and executes the "handler()" function within the script. NOTE: this can be very non-intuitive, becuase running http://yoursite.com/test.py has exactly the same result as http;//yoursite.com/foo.py - because they're both simply running the handler script, test.py, for ALL .py files in the directory. That means that your PythonHandler script needs to dispatch other scripts or load special pages in order to get different code to run. Also note that there are some pre-written Handler scripts that come with mod_python that can often do most of your work for you. You'll probably want a good tutorial on using mod_python to make sense of all this, because it's not really intuitive and it works differently than traditional cgi programming. Take a look at: http://modpython.org/live/current/doc-html/ to get you started, it's a lot more detailed and will probably answer your questions better. -Jay On Thursday 13 October 2005 3:49 pm, nitin chandra wrote: > Hi!... > i am new to Python and i want to develop a website with forms; data > submitted through forms will be stored in PostgreSQL. > I am working on derivant of FC3, OpenLX. > I have Apache 2.0.54 version installed, which is pre-configured with > mod_python. > how do i load and view my .py/.html web page (file) on the browser. > i need the initial hand holding/guidance of how to start, configure , and > develop modules. > thank in advance. > Nitin Chandra From dyoo at hkn.eecs.berkeley.edu Mon Oct 17 22:49:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 17 Oct 2005 13:49:57 -0700 (PDT) Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) (fwd) Message-ID: [Keeping tutor in CC] ---------- Forwarded message ---------- Date: Mon, 17 Oct 2005 22:03:22 +1300 From: Dave Shea To: Danny Yoo Subject: Re: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) Hi Danny, Thanks for your note. I tried your original suggestion of using the C:\Python24 as the home directory but to no avail. So now I am a bit stuck on your and Alan's next suggestion which is to use PythonWin. I downloaded: http://optusnet.dl.sourceforge.net/sourceforge/pywin32/pywin32-204.win32-py2 .4.exe and it installed fine. However, it is listed as "Python for Windows extensions" so I assume that installing this whilst still having Pythin24 installed was the way to go. The installer seemed to be OK about this but when I went to start PythonWin I could not actually find anything to start. I think I may be missing something here. Is PythonWin a separate installation of Python with an IDE/GUI ? Or is PythonWin simply something to sit over the top of a (any) Python installation. I'm a bit lost, as you may tell so any help would be greatly accepted. Many thanks. Dave Shea Wellington New Zealand. ----- Original Message ----- From: "Danny Yoo" To: "Dave Shea" Cc: Sent: Monday, October 17, 2005 5:17 PM Subject: Re: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) > > > On Sat, 15 Oct 2005, Dave Shea wrote: > > > Python installed without a complaint. However, when I fire up IDLE, > > there is an hour glass shown for a couple of seconds, then nothing else > > happens. When I fire up Python (command line) no problem, the DOS box > > opens and Python starts. I've tried re-starting, using Explorer instead > > of the Start menu, all the usual voodoo but still the IDLE refuses to > > start. > > Hi Dave, > > According to: > > http://python.org/2.4.2/bugs.html > > IDLE might not work well if Python has been installed into Program Files. > > Do you know if you've done this? If so, try reinstalling and just leave > the installation path at the defaults (Python should install under > "C:\PYTHON24", I think.) > > IDLE has unfortunately been a bit problematic in the Python 2.4 release, > so if you continue to run into issues, I'd second Alan's suggestion about > trying Pythonwin instead. > > > Good luck! > > From wescpy at gmail.com Mon Oct 17 23:11:08 2005 From: wescpy at gmail.com (w chun) Date: Mon, 17 Oct 2005 14:11:08 -0700 Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) (fwd) In-Reply-To: References: Message-ID: <78b3a9580510171411v43a8ec21nc52616160ca24c83@mail.gmail.com> dave, you should be able to start PythonWin in one of 2 ways: 1) Start menu -> Programs -> Python 2.4 -> PythonWin or 2) C:\Python24\Lib\site-packages\pythonwin\Pythonwin.exe hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051017/44ef677f/attachment.htm From paul1brian at gmail.com Mon Oct 17 23:11:31 2005 From: paul1brian at gmail.com (paul brian) Date: Mon, 17 Oct 2005 22:11:31 +0100 Subject: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) (fwd) In-Reply-To: References: Message-ID: I would suggest that you use "add Remove Programs" in the control panel and remove the python and win32 installations that you have installed Then visit www.activestate.com and download the package for activePython (http://activestate.com/Products/Download/Download.plex?id=ActivePython) You may need to download the latest MSI (MS installer) files from microsoft as Win95 does not understand them Activestate has a nice installer and you would be up and running then. cheers On 10/17/05, Danny Yoo wrote: > [Keeping tutor in CC] > > ---------- Forwarded message ---------- > Date: Mon, 17 Oct 2005 22:03:22 +1300 > From: Dave Shea > To: Danny Yoo > Subject: Re: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) > > Hi Danny, > > Thanks for your note. I tried your original suggestion of using the > C:\Python24 as the home directory but to no avail. So now I am a bit stuck > on your and Alan's next suggestion which is to use PythonWin. > > I downloaded: > http://optusnet.dl.sourceforge.net/sourceforge/pywin32/pywin32-204.win32-py2 > .4.exe > > and it installed fine. > > However, it is listed as "Python for Windows extensions" so I assume that > installing this whilst still having Pythin24 installed was the way to go. > The installer seemed to be OK about this but when I went to start PythonWin > I could not actually find anything to start. I think I may be missing > something here. Is PythonWin a separate installation of Python with an > IDE/GUI ? Or is PythonWin simply something to sit over the top of a (any) > Python installation. > > I'm a bit lost, as you may tell so any help would be greatly accepted. > > Many thanks. > > Dave Shea > Wellington > New Zealand. > ----- Original Message ----- > From: "Danny Yoo" > To: "Dave Shea" > Cc: > Sent: Monday, October 17, 2005 5:17 PM > Subject: Re: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) > > > > > > > > On Sat, 15 Oct 2005, Dave Shea wrote: > > > > > Python installed without a complaint. However, when I fire up IDLE, > > > there is an hour glass shown for a couple of seconds, then nothing else > > > happens. When I fire up Python (command line) no problem, the DOS box > > > opens and Python starts. I've tried re-starting, using Explorer instead > > > of the Start menu, all the usual voodoo but still the IDLE refuses to > > > start. > > > > Hi Dave, > > > > According to: > > > > http://python.org/2.4.2/bugs.html > > > > IDLE might not work well if Python has been installed into Program Files. > > > > Do you know if you've done this? If so, try reinstalling and just leave > > the installation path at the defaults (Python should install under > > "C:\PYTHON24", I think.) > > > > IDLE has unfortunately been a bit problematic in the Python 2.4 release, > > so if you continue to run into issues, I'd second Alan's suggestion about > > trying Pythonwin instead. > > > > > > Good luck! > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From vincent.gulinao at gmail.com Tue Oct 18 07:10:49 2005 From: vincent.gulinao at gmail.com (Vincent Gulinao) Date: Tue, 18 Oct 2005 13:10:49 +0800 Subject: [Tutor] multiple assignment Message-ID: I was fascinated when I learned that I can do this in Python: (str1, str2, str3, rest) = str.split(" ", 3) Later that I realize that str could contain values of less than 4 strings, in which case it would complain something like -- ValueError: unpack list of wrong size. Now I don't want to spoil the fun. In essence, I'd like to capture the first 3 words in a string. If str is less than 3 words then any or all of the containers could have a None value. TIA. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051018/c02245dd/attachment.html From john at fouhy.net Tue Oct 18 07:28:43 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 18 Oct 2005 18:28:43 +1300 Subject: [Tutor] multiple assignment In-Reply-To: References: Message-ID: <5e58f2e40510172228m3e43d302q@mail.gmail.com> On 18/10/05, Vincent Gulinao wrote: > I was fascinated when I learned that I can do this in Python: > > (str1, str2, str3, rest) = str.split(" ", 3) > [...] > In essence, I'd like to capture the first 3 words in a string. If str is > less than 3 words then any or all of the containers could have a None value. I'm not aware of any simple syntax... You could do something with itertools. eg: >>> from itertools import islice, chain, repeat >>> lst = [1, 2, 3] >>> a, b, c, d, e, f, g = islice(chain(lst, repeat(None)), 7) >>> print a, b, c, d, e, f, g 1 2 3 None None None None >>> a, b, c, d = islice(chain(lst, repeat(None)), 4) >>> print a, b, c, d 1 2 3 None >>> a, b = islice(chain(lst, repeat(None)), 2) >>> print a, b 1 2 Not quite as elegant as the simple case, but it's the best I can think of right now... -- John. From kent37 at tds.net Tue Oct 18 12:25:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Oct 2005 06:25:41 -0400 Subject: [Tutor] multiple assignment In-Reply-To: References: Message-ID: <4354CDA5.7090101@tds.net> Vincent Gulinao wrote: > I was fascinated when I learned that I can do this in Python: > > (str1, str2, str3, rest) = str.split(" ", 3) > > Later that I realize that str could contain values of less than 4 > strings, in which case it would complain something like -- ValueError: > unpack list of wrong size. > > Now I don't want to spoil the fun. > > In essence, I'd like to capture the first 3 words in a string. If str is > less than 3 words then any or all of the containers could have a None value. AFAIK there is no pretty solution but this works: str1, str2, str3 = (s.split(" ", 3) + [None]*3)[:3] Kent From kent37 at tds.net Tue Oct 18 13:55:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Oct 2005 07:55:58 -0400 Subject: [Tutor] multiple assignment In-Reply-To: References: <4354CDA5.7090101@tds.net> Message-ID: <4354E2CE.2050807@tds.net> Vincent Gulinao wrote: > Haha. Cool. > > I think it's better than... > > if str.find(" "): > str1, str2, str3 = str.split(" ", 3) > else: > str1, str2, str3, rest = str, None, None, None Less buggy, too - your version will fail if str="1 2" or "1 2 3 4" BTW don't use str as the name of a string, it is already the name of the string *type*. In general you should avoid using the names of built-ins for variable names. Kent PS Please reply on list so others can benefit > > On 10/18/05, *Kent Johnson* > wrote: > AFAIK there is no pretty solution but this works: > str1, str2, str3 = (s.split(" ", 3) + [None]*3)[:3] From rdm at rcblue.com Tue Oct 18 22:00:12 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 18 Oct 2005 13:00:12 -0700 Subject: [Tutor] "a cute recipe for getting the help command text" Message-ID: <6.2.1.2.2.20051018125057.04f6da00@rcblue.com> Found this in comp.lang.python. The Google link is ================================= import subprocess as subp p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, stdout=subp.PIPE, stderr=subp.STDOUT) flag = "(@@@@@@}" print >>p.stdin, "PROMPT", flag print >>p.stdin, "HELP" print >>p.stdin, "EXIT" text = p.stdout.read() p.wait() helptext = text[text.index(flag + 'HELP') + len(flag) + 4 : text.index(flag + 'EXIT')] words = [line.split(None, 1)[0] for line in helptext.split('\n') if line.strip()] commands = [word for word in words if word.isupper()] dest = open('cmd_help.txt', 'wb') p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, stdout=dest, stderr=subp.STDOUT) print >>p.stdin, "PROMPT (@@@@@@@@)" print >>p.stdin, "HELP" for command in commands: print >>p.stdin, "HELP", command print >>p.stdin, "EXIT" p.wait() dest.close() =================end of script============= When I run this I get no text, but just a series of cmd.exe windows entitled HELP . How do I get any text? Thanks, Dick Moores From nitinchandra1 at gmail.com Tue Oct 18 22:23:24 2005 From: nitinchandra1 at gmail.com (nitin chandra) Date: Wed, 19 Oct 2005 01:53:24 +0530 Subject: [Tutor] hand-holding for web development In-Reply-To: <200510171513.36008.python@jayloden.com> References: <965122bf0510131249had88b1fmf6124787e206a410@mail.gmail.com> <200510171513.36008.python@jayloden.com> Message-ID: <965122bf0510181323k7ede8385mc7673e4a75c85305@mail.gmail.com> Thanks Jay On 10/18/05, Jay Loden wrote: > You need an Apache config section to tell it what to use mod_python on and > how. For example, in httpd.conf or a separate file in your conf.d directory i guess the can be added only in one of the conf file. Which one should i add in? > for apache: > > > AddHandler mod_python .py > PythonHandler test > PythonDebug On > > > tells Apache to use mod_python on all .py files in my /var/www/html directory > (which is also the document root on my server). > > Once that's loaded you should be able to run whatever your python code through > a handler. For example, saving this as test.py: > > # > #mod_python super basic test script > # > from mod_python import apache > > def handler(req): > req.content_type = "text/html" > req_file = basename(req.uri) > if req.header_only: > return apache.OK > > else: > req.write("mod_python is working") > return apache.OK > > # end of script > > This should print "mod_python is working" to the browser if you visit > http://yoursite.com/test.py > > Remember that you need to restart/reload apache after any config change. The > basic gist is that any .py file you load in the /var/www/html runs the script > "test.py" (PythonHandler test) and executes the "handler()" function within > the script. NOTE: this can be very non-intuitive, becuase running > http://yoursite.com/test.py has exactly the same result as > http;//yoursite.com/foo.py - because they're both simply running the handler > script, test.py, for ALL .py files in the directory. That means that your > PythonHandler script needs to dispatch other scripts or load special pages in > order to get different code to run. Also note that there are some pre-written > Handler scripts that come with mod_python that can often do most of your work > for you. > > You'll probably want a good tutorial on using mod_python to make sense of all > this, because it's not really intuitive and it works differently than > traditional cgi programming. Take a look at: > http://modpython.org/live/current/doc-html/ > to get you started, it's a lot more detailed and will probably answer your > questions better. Thaks you. could you please guide how to interface Django with mod_python, for effectively using in web site development? > > -Jay Thanks You Nitin From kent37 at tds.net Tue Oct 18 22:23:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Oct 2005 16:23:35 -0400 Subject: [Tutor] "a cute recipe for getting the help command text" In-Reply-To: <6.2.1.2.2.20051018125057.04f6da00@rcblue.com> References: <6.2.1.2.2.20051018125057.04f6da00@rcblue.com> Message-ID: <435559C7.2040504@tds.net> It makes a file called cmd_help.txt in the current directory. Did you look for that? The file contains the result of asking for help on every command. Kind of cool! Kent Dick Moores wrote: > Found this in comp.lang.python. The Google link is > > > ================================= > import subprocess as subp > > p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, > stdout=subp.PIPE, stderr=subp.STDOUT) > flag = "(@@@@@@}" > print >>p.stdin, "PROMPT", flag > print >>p.stdin, "HELP" > print >>p.stdin, "EXIT" > text = p.stdout.read() > p.wait() > helptext = text[text.index(flag + 'HELP') + len(flag) + 4 : > text.index(flag + 'EXIT')] > words = [line.split(None, 1)[0] > for line in helptext.split('\n') > if line.strip()] > commands = [word for word in words if word.isupper()] > > dest = open('cmd_help.txt', 'wb') > p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, > stdout=dest, stderr=subp.STDOUT) > print >>p.stdin, "PROMPT (@@@@@@@@)" > print >>p.stdin, "HELP" > for command in commands: > print >>p.stdin, "HELP", command > print >>p.stdin, "EXIT" > p.wait() > dest.close() > =================end of script============= > > When I run this I get no text, but just a series of cmd.exe windows > entitled HELP . How do I get any text? > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From randy at psg.com Tue Oct 18 22:30:58 2005 From: randy at psg.com (Randy Bush) Date: Tue, 18 Oct 2005 10:30:58 -1000 Subject: [Tutor] string.split() into a list Message-ID: <17237.23426.216564.787457@roam.psg.com> and stupid question of the morning (for me) i want to string.split() into a sequence, a la l = [] l = myString.split('|') but, of course it whines about too many values. what is the common way to do this? randy From jason.massey at gmail.com Tue Oct 18 22:34:17 2005 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 18 Oct 2005 15:34:17 -0500 Subject: [Tutor] string.split() into a list In-Reply-To: <17237.23426.216564.787457@roam.psg.com> References: <17237.23426.216564.787457@roam.psg.com> Message-ID: <7e3eab2c0510181334p4fe2356bu94728002cec7ef7f@mail.gmail.com> Works fine for me: >>> l = [] >>>a='1|2|3|4' >>> l=a.split('|') >>>l ['1', '2', '3', '4'] On 10/18/05, Randy Bush wrote: > and stupid question of the morning (for me) > > i want to string.split() into a sequence, a la > > l = [] > l = myString.split('|') > > but, of course it whines about too many values. what is the > common way to do this? > > randy > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Tue Oct 18 22:36:49 2005 From: rdm at rcblue.com (Dick Moores) Date: Tue, 18 Oct 2005 13:36:49 -0700 Subject: [Tutor] "a cute recipe for getting the help command text" Message-ID: <6.2.1.2.2.20051018133642.060a88c0@rcblue.com> Ah, the line dest = open('cmd_help.txt', 'wb') Thanks, Kent. Yes, I've got it. Dick Kent Johnson wrote at 13:23 10/18/2005: >It makes a file called cmd_help.txt in the current directory. Did you >look for that? The file contains the result of asking for help on every >command. Kind of cool! > >Kent > >Dick Moores wrote: > > Found this in comp.lang.python. The Google link is > > > > > > > ================================= > > import subprocess as subp > > > > p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, > > stdout=subp.PIPE, stderr=subp.STDOUT) > > flag = "(@@@@@@}" > > print >>p.stdin, "PROMPT", flag > > print >>p.stdin, "HELP" > > print >>p.stdin, "EXIT" > > text = p.stdout.read() > > p.wait() > > helptext = text[text.index(flag + 'HELP') + len(flag) + 4 : > > text.index(flag + 'EXIT')] > > words = [line.split(None, 1)[0] > > for line in helptext.split('\n') > > if line.strip()] > > commands = [word for word in words if word.isupper()] > > > > dest = open('cmd_help.txt', 'wb') > > p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, > > stdout=dest, stderr=subp.STDOUT) > > print >>p.stdin, "PROMPT (@@@@@@@@)" > > print >>p.stdin, "HELP" > > for command in commands: > > print >>p.stdin, "HELP", command > > print >>p.stdin, "EXIT" > > p.wait() > > dest.close() > > =================end of script============= > > > > When I run this I get no text, but just a series of cmd.exe windows > > entitled HELP . How do I get any text? > > > > Thanks, > > > > Dick Moores > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From randy at psg.com Tue Oct 18 22:51:09 2005 From: randy at psg.com (Randy Bush) Date: Tue, 18 Oct 2005 10:51:09 -1000 Subject: [Tutor] string.split() into a list References: <17237.23426.216564.787457@roam.psg.com> <7e3eab2c0510181334p4fe2356bu94728002cec7ef7f@mail.gmail.com> Message-ID: <17237.24637.196277.956121@roam.psg.com> > >>> l = [] > >>>a='1|2|3|4' > >>> l=a.split('|') > >>>l > ['1', '2', '3', '4'] >> and stupid question of the morning (for me) >> >> i want to string.split() into a sequence, a la >> >> l = [] >> l = myString.split('|') >> >> but, of course it whines about too many values. what is the >> common way to do this? maybe it's that i am actually doing l = [] a, l = string.split('|') ? From jason.massey at gmail.com Tue Oct 18 23:25:33 2005 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 18 Oct 2005 16:25:33 -0500 Subject: [Tutor] string.split() into a list In-Reply-To: <17237.24637.196277.956121@roam.psg.com> References: <17237.23426.216564.787457@roam.psg.com> <7e3eab2c0510181334p4fe2356bu94728002cec7ef7f@mail.gmail.com> <17237.24637.196277.956121@roam.psg.com> Message-ID: <7e3eab2c0510181425h52a3d64avf8757b034a95954f@mail.gmail.com> well that would definitely cause your error. The string.split sends the list to a, but after that it's looking for something to assign to l and there's nothing leftover from the command for it to assign. On 10/18/05, Randy Bush wrote: > > >>> l = [] > > >>>a='1|2|3|4' > > >>> l=a.split('|') > > >>>l > > ['1', '2', '3', '4'] > >> and stupid question of the morning (for me) > >> > >> i want to string.split() into a sequence, a la > >> > >> l = [] > >> l = myString.split('|') > >> > >> but, of course it whines about too many values. what is the > >> common way to do this? > > maybe it's that i am actually doing > > l = [] > a, l = string.split('|') > > ? > > From randy at psg.com Tue Oct 18 23:32:54 2005 From: randy at psg.com (Randy Bush) Date: Tue, 18 Oct 2005 11:32:54 -1000 Subject: [Tutor] string.split() into a list References: <17237.23426.216564.787457@roam.psg.com> <7e3eab2c0510181334p4fe2356bu94728002cec7ef7f@mail.gmail.com> <17237.24637.196277.956121@roam.psg.com> <7e3eab2c0510181425h52a3d64avf8757b034a95954f@mail.gmail.com> Message-ID: <17237.27142.725065.208618@roam.psg.com> > The string.split sends the list to a, but after that it's looking for > something to assign to l and there's nothing leftover from the command > for it to assign. nope, it does not send the list to a >>> l = [] >>> s = 'a|b' >>> t, l = s.split('|') >>> t 'a' >>> l 'b' i believe the problem is really that the lhs is of the form ( a, [b] ) but i see no simple intuitive way to unpack into that > > > On 10/18/05, Randy Bush wrote: > > > >>> l = [] > > > >>>a='1|2|3|4' > > > >>> l=a.split('|') > > > >>>l > > > ['1', '2', '3', '4'] > > >> and stupid question of the morning (for me) > > >> > > >> i want to string.split() into a sequence, a la > > >> > > >> l = [] > > >> l = myString.split('|') > > >> > > >> but, of course it whines about too many values. what is the > > >> common way to do this? > > > > maybe it's that i am actually doing > > > > l = [] > > a, l = string.split('|') > > > > ? > > > > From kent37 at tds.net Tue Oct 18 23:35:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Oct 2005 17:35:48 -0400 Subject: [Tutor] string.split() into a list In-Reply-To: <17237.24637.196277.956121@roam.psg.com> References: <17237.23426.216564.787457@roam.psg.com> <7e3eab2c0510181334p4fe2356bu94728002cec7ef7f@mail.gmail.com> <17237.24637.196277.956121@roam.psg.com> Message-ID: <43556AB4.2030709@tds.net> Randy Bush wrote: > maybe it's that i am actually doing > > l = [] > a, l = string.split('|') How about >>> s='1|2|3|4' >>> l=s.split('|') >>> a, l = l[0], l[1:] >>> a '1' >>> l ['2', '3', '4'] ? Kent > > ? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dstotijn at gmail.com Tue Oct 18 23:35:14 2005 From: dstotijn at gmail.com (David Stotijn) Date: Tue, 18 Oct 2005 23:35:14 +0200 Subject: [Tutor] Python books: buying advice needed Message-ID: <40cda6f40510181435q6181be19r@mail.gmail.com> Hi, I'm planning on buying a book to help me learn Python. Some of the books I'm considering are a few years old and based on an older version of Python (e.g. 2.3). Is it wise to buy a book based on an older version? Are the principles and methods used in those books outdated by now? Ideally, the book I'm looking for has some "best practice" guidelines and alot of example code. Do you have any tips? Thanks in advance! David -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051018/6ba5f3eb/attachment.html From g.tagliaretti at gmail.com Wed Oct 19 00:43:46 2005 From: g.tagliaretti at gmail.com (Gian Mario Tagliaretti) Date: Wed, 19 Oct 2005 00:43:46 +0200 Subject: [Tutor] Python books: buying advice needed In-Reply-To: <40cda6f40510181435q6181be19r@mail.gmail.com> References: <40cda6f40510181435q6181be19r@mail.gmail.com> Message-ID: <35bf41160510181543xbedcaa8q@mail.gmail.com> 2005/10/18, David Stotijn : > I'm planning on buying a book to help me learn Python. Some of the books > I'm considering are a few years old and based on an older version of Python > (e.g. 2.3). Python 2.3 is not so old... :) > Is it wise to buy a book based on an older version? Are the principles and > methods used in those books outdated by now? Most of the books covers 2.3 ATM I guess > Ideally, the book I'm looking for has some "best practice" guidelines and > alot of example code. > > Do you have any tips? I found very useful the book of Magnus Lie Hatland "Practical Python" in my opinion very well done, I've heard anyway that he is going to publish a new revision. cheers -- Gian Mario Tagliaretti PyGTK GUI programming http://www.parafernalia.org/pygtk/ From challman at gmail.com Wed Oct 19 00:55:56 2005 From: challman at gmail.com (Chris Hallman) Date: Tue, 18 Oct 2005 18:55:56 -0400 Subject: [Tutor] script question In-Reply-To: <433D09EA.6020701@tds.net> References: <9f68812f05092604563052918f@mail.gmail.com> <43387C41.20307@tds.net> <4338A883.7020001@tds.net> <9f68812f05092805343e834cb8@mail.gmail.com> <433D09EA.6020701@tds.net> Message-ID: <9f68812f0510181555x56f20ca8yaccee087540f8402@mail.gmail.com> Here is my latest revision, which works very well. # This Python script was written to forward interface down messages # to ESM1. If the incoming arguements match the interface file # (c:\utils\interface.ini) then the message is forwarded. # # Author: tcdh # Date: 09/22/05 # Modified: 10/04/05 changed os.system to use raw("r") strings. Used % and join method to join # the sys.argv's. replaced list generating lines with one line of code. # import ConfigParser, sys, os section = sys.argv[1] interface = sys.argv[3] ini=ConfigParser.ConfigParser() ini.read("c:\utils\interfaces.ini") interface_list=ini.items(section) for i in interface_list: if i[1] == interface: os.system(r"d:\tnd\bin\delkeep.exe -all -n l17aesm1 %s" % (" ".join(sys.argv[1:3]),)+ "*") os.system(r"d:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward red held %s" % (" ".join(sys.argv[1:5]),)) break Again, thank you all for your input. I greatly appreciated it!!!! Let me know if you have any further suggestions. On 9/30/05, Kent Johnson wrote: > > Chris Hallman wrote: > > > > Thanks for all the input!!! I really appreciate it. I need to post a > > correction to my script. What I sent was an early version. I made a few > > minor modifications: > > You don't seem to have incorporated any of the suggestions that you have > received! > > I doubt that a 4000-line ini file will be any problem at all. > > Kent > > > > > import ConfigParser, string, sys, os > > section = sys.argv[1] > > interface = sys.argv[3] > > INI=ConfigParser.ConfigParser() > > INI.read("c:\utils\interfaces.ini") > > interface_entries=[p for p in INI.options > > (section)] > > interface_list=[INI.get(section, pw) for pw in interface_entries] > > for i in interface_list: > > if i == interface: > > os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red > held " + > > sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4]) > > > > > > I've researched what you all have suggested and I may need to switch to > > reading the ini file line by line or using a different file parser. The > > ini file is only 100 lines long now, but will likely grow to 500 line > > and maybe to 4000 lines. To give you a better background of what I'm > > doing with this script, it's running on a network management system that > > receives traps. After some processing of the raw trap, messages get sent > > to this script for further processing. These messages are for interface > > down traps from routers and switches in our network. I use this script > > to mitigate the number of interface down messages on our console. I need > > to do this because we do not need to know when every port has gone down > > (i.e. user ports). This script searches the ini file for a device name > > match. Once it has found a match and if the interface matches as well, I > > need to message forwarded to the console (the Windows command). If no > > matching device or interface is found, then the script can just exit. > > > > > > On 9/26/05, *Kent Johnson* > > wrote: > > > > Kent Johnson wrote: > > > *TEST FIRST* Don't optimize until you know it is too slow and you > > > have a test case that you can time to see if your 'optimizations' are > > > making it faster. > > > > Pardon my shouting :-) > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051018/b96651cb/attachment.htm From challman at gmail.com Wed Oct 19 00:57:41 2005 From: challman at gmail.com (Chris Hallman) Date: Tue, 18 Oct 2005 18:57:41 -0400 Subject: [Tutor] script to change device configuration Message-ID: <9f68812f0510181557x18c6d37cy99b3364b9a43c294@mail.gmail.com> I created a script that parses a directory, strips the ".txt" extension off the file, telnet & log on to the device (the filename is the device name), opens the associated ".txt" file, sends all the commands containted in the file to the device and then executes some commands to save the changes. I'm not very experienced with programming, writing Python, using functions, OOP, etc., therefore I'd like to know if there is a better way to do this: # # This scripts obtains a directory listing, strips the extensions and telnets to the # device (which is the filename in the directory). Then it writes the commands in the # file to the device, saves config and writes it back to SYSMAN. It can be run using: # python send_file4.py # # Note: "os" is imported for future functionality. # # by: TCDH # on: 10/17/05 # revised: 10/18/05 TCDH - Added logic to check for offline devices and sign-on failures. # import telnetlib, re, os, string dirpath = (r"c:\temp\sun") dirlist = os.listdir(dirpath) wpath = (r"c:\temp\py\send_file4.out") output = file(wpath, "w") for i in dirlist: try: tn = telnetlib.Telnet(i.rstrip(".txt")) tn.read_until("Username: ") except: output.write(i.rstrip(".txt") + ": not responding.\n") continue tn.write("cworks\n") (index, match, read) = tn.expect(["Password: "], 5) if not match: output.write(i.rstrip(".txt") + ": sign-on failure.\n") continue tn.write("\n") tn.write("conf t\n") rpath = (dirpath + "\\" + i) input = file(rpath, "r") for lines in file(rpath): tn.write(input.readline()) tn.write("end\n") # exit config mode tn.write("wr\n") # save config tn.read_until("#") tn.write("wr net\n") #write config to TFTP tn.read_until("]? ") tn.write("172.16.250.22\n") # TFTP server address tn.read_until("]? ") tn.write("\n") tn.read_until("[confirm]") tn.write("\n") tn.read_until("#") tn.write("exit\n") # end session This script needs to be able to log which device is offline and if there was a sign-on problem. For the first exception (device offline), I had to use try-except because tn.expect wouldn't work. However, I had to use tn.expecton the second exception (sign-on problem) because try-except wouldn't work there. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051018/ea2d0bcc/attachment.html From randy at psg.com Wed Oct 19 01:10:15 2005 From: randy at psg.com (Randy Bush) Date: Tue, 18 Oct 2005 13:10:15 -1000 Subject: [Tutor] string.split() into a list References: <17237.23426.216564.787457@roam.psg.com> <7e3eab2c0510181334p4fe2356bu94728002cec7ef7f@mail.gmail.com> <17237.24637.196277.956121@roam.psg.com> <43556AB4.2030709@tds.net> Message-ID: <17237.32983.148018.27090@roam.psg.com> > How about > >>> s='1|2|3|4' > >>> l=s.split('|') > >>> a, l = l[0], l[1:] > >>> a > '1' > >>> l > ['2', '3', '4'] looks kinda readable. thanks randy From dyoo at hkn.eecs.berkeley.edu Wed Oct 19 01:13:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 18 Oct 2005 16:13:34 -0700 (PDT) Subject: [Tutor] string.split() into a list In-Reply-To: <43556AB4.2030709@tds.net> Message-ID: On Tue, 18 Oct 2005, Kent Johnson wrote: > > l = [] > > a, l = string.split('|') > > How about > >>> s='1|2|3|4' > >>> l=s.split('|') > >>> a, l = l[0], l[1:] > >>> a > '1' > >>> l > ['2', '3', '4'] > ? Hi Randy, I think you're expecting Perl behavior. The Perl idiom for partially destructuring an array looks something like this: ### Perl ######################################################## my @rest; my $firstElement; ($firstElement, @rest) = split(/:/, "hello:world:this:is:a:test"); ################################################################# But we don't have a direct analog to this in Python, since there's no real distinction between "scalar" and "array" values in the Python language. In your original code: l = [] a, l = string.split('|') assigning 'l' to an empty list has no effect: it doesn't freeze the type of 'l' so that it can only be a list. For example: ###### >>> thing = [] >>> thing = 42 >>> thing = "blah" ###### show that we can easily redirect the name 'thing' to different kinds of values. List values in Python aren't any more special than other things. If you come from a Perl background, the non-existance of array-vs-scalar context issues is something you might need to keep in mind. The closest we can probably get is with Kent's example, where the 'rest' are explicitely bundled together by using list slicing. Would something like this be fine for you? ### Python ####################################################### def splitFirstAndRest(delimiter, text): pieces = text.split(delimiter) return pieces[0], pieces[1:] first, rest = splitFirstAndRest(':', "hello:world:this:is:a:test") ################################################################## Best of wishes! From randy at psg.com Wed Oct 19 01:30:05 2005 From: randy at psg.com (Randy Bush) Date: Tue, 18 Oct 2005 13:30:05 -1000 Subject: [Tutor] string.split() into a list References: <43556AB4.2030709@tds.net> Message-ID: <17237.34173.722991.691432@roam.psg.com> >> >>> s='1|2|3|4' >> >>> l=s.split('|') >> >>> a, l = l[0], l[1:] >> >>> a >> '1' >> >>> l >> ['2', '3', '4'] i went with the above, or more specifically aList = line[:-1].split('|') netName, asList = aList[0], aList[1:] not gorgeous, but readable and my instinct for pinning a type is from modula and other wirthwhile bondage and discipline languages. and, yes, i see it does not carry. thanks. randy From kent37 at tds.net Wed Oct 19 04:17:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Oct 2005 22:17:32 -0400 Subject: [Tutor] Python books: buying advice needed In-Reply-To: <40cda6f40510181435q6181be19r@mail.gmail.com> References: <40cda6f40510181435q6181be19r@mail.gmail.com> Message-ID: <4355ACBC.9090608@tds.net> David Stotijn wrote: > Hi, > > I'm planning on buying a book to help me learn Python. Some of the books > I'm considering are a few years old and based on an older version of > Python (e.g. 2.3). > Is it wise to buy a book based on an older version? Are the principles > and methods used in those books outdated by now? 2.3 is not that old. The basics of Python change slowly, especially the beginner-level stuff. The later versions introduce refinements, convenience features and new, advanced stuff; they don't generally break much or change the overall 'feel' of Python. I don't know if there are any books out yet that cover 2.4. > Ideally, the book I'm looking for has some "best practice" guidelines > and alot of example code. > > Do you have any tips? I like _Learning Python_ Kent From kent37 at tds.net Wed Oct 19 04:42:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Oct 2005 22:42:29 -0400 Subject: [Tutor] script to change device configuration In-Reply-To: <9f68812f0510181557x18c6d37cy99b3364b9a43c294@mail.gmail.com> References: <9f68812f0510181557x18c6d37cy99b3364b9a43c294@mail.gmail.com> Message-ID: <4355B295.5040708@tds.net> Chris Hallman wrote: I'm not very experienced with programming, writing > Python, using functions, OOP, etc., therefore I'd like to know if there > is a better way to do this: It looks pretty good to me. A few suggestions below. > import telnetlib, re, os, string > > dirpath = (r"c:\temp\sun") The parens here and for wpath are not needed. > dirlist = os.listdir(dirpath) > wpath = (r"c:\temp\py\send_file4.out") > output = file(wpath, "w") > for i in dirlist: i is not a very descriptive name. You might want to check that i ends with '.txt' device = i.rstrip('.txt') might be handy too. > try: > tn = telnetlib.Telnet(i.rstrip(".txt")) > tn.read_until("Username: ") > except: > output.write(i.rstrip(".txt") + ": not responding.\n") > continue > tn.write("cworks\n") > (index, match, read) = tn.expect(["Password: "], 5) > if not match: > output.write(i.rstrip(".txt") + ": sign-on failure.\n") > continue > tn.write("\n") > tn.write("conf t\n") > rpath = (dirpath + "\\" + i) Use os.path.join(dirpath, i) > input = file(rpath, "r") You don't use input > for lines in file(rpath): > tn.write(input.readline()) > tn.write("end\n") # exit config mode > tn.write("wr\n") # save config > tn.read_until("#") > tn.write("wr net\n") #write config to TFTP > tn.read_until("]? ") > tn.write("172.16.250.22\n") # TFTP server address > tn.read_until("]? ") > tn.write("\n") > tn.read_until("[confirm]") > tn.write("\n") > tn.read_until("#") > tn.write("exit\n") # end session The above is pretty repetitive. How about something like finishCmds = [ ("#", "wr net\n"), #write config to TFTP ("]? ", "172.16.250.22\n"), # TFTP server address ("]? ", "\n"), ("[confirm]", "\n"), ("#", "exit\n"), # end session ] for prompt, response in finishCmds: tn.read_until(prompt) tn.write(response) Kent From tegmine at gmail.com Wed Oct 19 08:52:48 2005 From: tegmine at gmail.com (Luis N) Date: Tue, 18 Oct 2005 23:52:48 -0700 Subject: [Tutor] Any good Glade and python tutorials? In-Reply-To: References: Message-ID: <77bfa81a0510182352qa6e4b26q42f2fc28cedc2f33@mail.gmail.com> You might want to search for how it fits together with twisted's reactor http://www.google.com/search?q=twisted+glade+reactor Luis. On 10/15/05, Adam wrote: > I'm making a Twisted app that needs a client side GUI and GTK seems like the > best way to go about this. Can anybody point me in the direction of any > decent tutorials on how to use Glade with python and pyGTK. > Thanks. > Adam. > From meesters at uni-mainz.de Wed Oct 19 09:45:07 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Wed, 19 Oct 2005 09:45:07 +0200 Subject: [Tutor] regular expression matching a dot? Message-ID: <62b9617312def89628c31ef88d131978@uni-mainz.de> Hi I've got the problem that I need to find a certain group of file names within a lot of different file names. Those I want to match with a regular expression are a bit peculiar since they all look like: 07SS.INF , 10SE.INF, 13SS.INF, 02BS.INF, 05SS.INF. Unfortunately there are similar file names that shouldn't be matched, like: 01BE.INF, 02BS.INF Any other extension than 'INF' should also be skipped. (There are names like 07SS.E00, wich I don't want to see matched.) So I tried the following pattern (using re): \d+[SS|SE]\.INF - as there should be at least one digit, the group 'SE' or 'SS' followed by a dot and the extension 'INF'. Well, this doesn't work, no match. However, if I change the pattern to \d+[SS|SE] it somehow works and all all valid names are matched. But if there is a different extension than 'INF' it matches too - but it shouldn't. (Surrounding the dot with [] doesn't help, though I have no idea as for why.) Any ideas what I could do else? TIA Christian PS Hope that I described the problem well enough ... From kent37 at tds.net Wed Oct 19 12:08:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Oct 2005 06:08:11 -0400 Subject: [Tutor] regular expression matching a dot? In-Reply-To: <62b9617312def89628c31ef88d131978@uni-mainz.de> References: <62b9617312def89628c31ef88d131978@uni-mainz.de> Message-ID: <43561B0B.90103@tds.net> Christian Meesters wrote: > Hi > > I've got the problem that I need to find a certain group of file names > within a lot of different file names. Those I want to match with a > regular expression are a bit peculiar since they all look like: > 07SS.INF , 10SE.INF, 13SS.INF, 02BS.INF, 05SS.INF. > Unfortunately there are similar file names that shouldn't be matched, > like: > 01BE.INF, 02BS.INF > Any other extension than 'INF' should also be skipped. (There are names > like 07SS.E00, wich I don't want to see matched.) > So I tried the following pattern (using re): > \d+[SS|SE]\.INF - as there should be at least one digit, the group 'SE' > or 'SS' followed by a dot and the extension 'INF'. Use parentheses () for grouping. Brackets [] define a group of characters. Your re says to match \d+ one or more digits [SS|SE] exactly one of the characters S, |, E \.INF literal .INF Since there are TWO characters S or E, nothing matches. Change the [] to () and it works. Kent From mistobaan at gmail.com Wed Oct 19 12:11:32 2005 From: mistobaan at gmail.com (Misto .) Date: Wed, 19 Oct 2005 12:11:32 +0200 Subject: [Tutor] regular expression matching a dot? In-Reply-To: <62b9617312def89628c31ef88d131978@uni-mainz.de> References: <62b9617312def89628c31ef88d131978@uni-mainz.de> Message-ID: [ Workaround ] What about using the glob module? http://docs.python.org/lib/module-glob.html you can use something like glob.glob('./[0-9][0-9]S[E|S].INF') (Not tested) Misto From meesters at uni-mainz.de Wed Oct 19 13:10:37 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Wed, 19 Oct 2005 13:10:37 +0200 Subject: [Tutor] regular expression matching a dot? In-Reply-To: References: <62b9617312def89628c31ef88d131978@uni-mainz.de> Message-ID: <2e8d7a6524076ffdfa0f87121bb7a110@uni-mainz.de> Hi Misto, Thanks, but this is no option for me - though I use glob a lot in other cases (mostly the quick and dirty hacks). But here I'm working on a list of names - not the files directly. Besides: REs are a lot more powerful (usually ;-), e.g. I'm using \d+ since I don't now that there are always only two digits, but there need to be one. Cheers, Christian On 19 Oct 2005, at 12:11, Misto . wrote: > [ Workaround ] > What about using the glob module? > > http://docs.python.org/lib/module-glob.html > > you can use something like > glob.glob('./[0-9][0-9]S[E|S].INF') > (Not tested) > > > Misto > From meesters at uni-mainz.de Wed Oct 19 13:24:02 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Wed, 19 Oct 2005 13:24:02 +0200 Subject: [Tutor] regular expression matching a dot? In-Reply-To: References: <62b9617312def89628c31ef88d131978@uni-mainz.de> Message-ID: Actually, your answer did help to open my eyes. The expression is "\d+S[S|E]\.INF": Ouch! Thanks a lot, Christian On 19 Oct 2005, at 12:11, Misto . wrote: > [ Workaround ] > What about using the glob module? > > http://docs.python.org/lib/module-glob.html > > you can use something like > glob.glob('./[0-9][0-9]S[E|S].INF') > (Not tested) > > > Misto > From kent37 at tds.net Wed Oct 19 13:50:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Oct 2005 07:50:33 -0400 Subject: [Tutor] regular expression matching a dot? In-Reply-To: References: <62b9617312def89628c31ef88d131978@uni-mainz.de> Message-ID: <43563309.2060206@tds.net> Christian Meesters wrote: > Actually, your answer did help to open my eyes. The expression is > "\d+S[S|E]\.INF": Ouch! That will work, but what you really mean is one of these: "\d+S[SE]\.INF" "\d+S(S|E)\.INF" Your regex will match 0S|.INF Kent From samrobertsmith at gmail.com Wed Oct 19 14:22:53 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Wed, 19 Oct 2005 05:22:53 -0700 Subject: [Tutor] setting Message-ID: <1d987df30510190522l16b6cf3dh64a9823e788ae806@mail.gmail.com> I have installed Python 2.3 and I type "help()" and then "Keywords". I get a list of words. And it says that I can enter any of the words to get more help. I enter "and" and I get the following error message: "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." but I have set both the environment variable, with the path to be C:\Python23\Doc which includes python23.chm Why I still got the above error message? From meesters at uni-mainz.de Wed Oct 19 14:25:25 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Wed, 19 Oct 2005 14:25:25 +0200 Subject: [Tutor] regular expression matching a dot? In-Reply-To: <43563309.2060206@tds.net> References: <62b9617312def89628c31ef88d131978@uni-mainz.de> <43563309.2060206@tds.net> Message-ID: <79ba406ef9193f0e72ab5c4f5164d12e@uni-mainz.de> Thanks, corrected. I was happy now - and then too fast ;-). Cheers Christian On 19 Oct 2005, at 13:50, Kent Johnson wrote: > Christian Meesters wrote: >> Actually, your answer did help to open my eyes. The expression is >> "\d+S[S|E]\.INF": Ouch! > > That will work, but what you really mean is one of these: > "\d+S[SE]\.INF" > "\d+S(S|E)\.INF" > > Your regex will match 0S|.INF > > Kent > From davholla2002 at yahoo.co.uk Wed Oct 19 16:37:00 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 19 Oct 2005 15:37:00 +0100 (BST) Subject: [Tutor] python books Message-ID: <20051019143700.56909.qmail@web25906.mail.ukl.yahoo.com> The best book I found was python programming for the absolute beginner by Michael Dawson. I would strongly recommend it. The only annoying thing is that he uses a games wrapper called livewires, which he modifies from the original but keeps the same name, which does not seem very clever to me. So if you want to have one program with the original wrapper and one program with his then you have a slight problem. ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From davholla2002 at yahoo.co.uk Wed Oct 19 16:39:14 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 19 Oct 2005 15:39:14 +0100 (BST) Subject: [Tutor] python books Message-ID: <20051019143915.44902.qmail@web25907.mail.ukl.yahoo.com> The best book I found was python programming for the absolute beginner by Michael Dawson. I would strongly recommend it. The only annoying thing is that he uses a games wrapper called livewires, which he modifies from the original but keeps the same name, which does not seem very clever to me. So if you want to have one program with the original wrapper and one program with his then you have a slight problem. ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From paul1brian at gmail.com Wed Oct 19 17:13:13 2005 From: paul1brian at gmail.com (paul brian) Date: Wed, 19 Oct 2005 16:13:13 +0100 Subject: [Tutor] setting In-Reply-To: <1d987df30510190522l16b6cf3dh64a9823e788ae806@mail.gmail.com> References: <1d987df30510190522l16b6cf3dh64a9823e788ae806@mail.gmail.com> Message-ID: Did you install from the python.org download or from activestate. If you have a .chm file I am guessing activestate. For some reason the normal docs that you get with the python.org distributin (the "official" one) are only found as a chm file. I suggest you get the python.org installer and carefully install to a temp directory, and copy across the html files in Doc, or remove activestate, install python.org and then add in the win32all extensions. I would suggest the first option for sheer ease. (in fact on windows i would suggest keeping the .chm and using that, cmd.exe is quite poor in command line reading and copying so that .chm is my favourtie way of looking up documentation) HTH. On 10/19/05, Shi Mu wrote: > I have installed Python 2.3 and I type "help()" and then "Keywords". > I get a list of words. And it says that I can enter any of the words > to get more help. I enter > "and" and I get the following error message: > "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." > > but I have set both the environment variable, with the path to be > C:\Python23\Doc which includes python23.chm > Why I still got the above error message? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------- Paul Brian m. 07875 074 534 t. 0208 352 1741 From luke.jordan at gmail.com Wed Oct 19 17:23:38 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Wed, 19 Oct 2005 10:23:38 -0500 Subject: [Tutor] define vars by iteration Message-ID: I've got a bunch of pickled class instances with self.nameattributes, and I would like to assign the instances themselves to variables named whatever is stored in self.name using a function. "Can't assign to literal", right? Is there a way to do this? Thanks, Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051019/fc80793b/attachment.html From broek at cc.umanitoba.ca Wed Oct 19 17:48:36 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 19 Oct 2005 10:48:36 -0500 Subject: [Tutor] setting In-Reply-To: <1d987df30510190522l16b6cf3dh64a9823e788ae806@mail.gmail.com> References: <1d987df30510190522l16b6cf3dh64a9823e788ae806@mail.gmail.com> Message-ID: <43566AD4.2090602@cc.umanitoba.ca> Shi Mu said unto the world upon 2005-10-19 07:22: > I have installed Python 2.3 and I type "help()" and then "Keywords". > I get a list of words. And it says that I can enter any of the words > to get more help. I enter > "and" and I get the following error message: > "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." > > but I have set both the environment variable, with the path to be > C:\Python23\Doc which includes python23.chm > Why I still got the above error message? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hi Shi Mu, I solved that problem by downloading the html version of the docs from the python site, and placing them in the same dir as the .chm, setting PYTHONDOCS appropriately. Best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Wed Oct 19 19:45:00 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 19 Oct 2005 10:45:00 -0700 (PDT) Subject: [Tutor] define vars by iteration In-Reply-To: Message-ID: On Wed, 19 Oct 2005, Luke Jordan wrote: > I've got a bunch of pickled class instances with > self.nameattributes, and I would like to assign the > instances themselves to variables > named whatever is stored in self.name using a function. > "Can't assign to literal", right? Is there a way to do this? Hi Luke, It's technically possible to do this, but discouraged. The reason it's not so safe is because some of those names might collide with your own program's names, or with the builtins. So if you start having pickled instances with names like 'list' or 'open', havoc is bound to ensue. Furthermore, Python variable names have some physical restrictions that may interfere with what you're trying to do: ###### >>> 4meUshouldnthave = 42 File "", line 1 4meUshouldnthave = 42 ^ SyntaxError: invalid syntax ###### (For the gory details on what's allowed in a name "identifier", see: http://www.python.org/doc/ref/identifiers.html) A safer way to do that I think you want is to use a separate dictionary container for those instances. As a concrete example: ###### class Person: def __init__(self, name): self.name = name people_names = ['fred', 'barney', 'wilma', 'betty'] people = {} for name in people_names: people[name] = Person(name) ###### Rather than using a direct variable name to refer to the person, we can go an indirect route, and refer to the corresponding entry in the 'people' dictionary. Does this make sense? This is safer because there's no potential to munge up the toplevel, plus the 'name' keys won't have the restrictions that Python variable names have. Hope this helps! From ronin_cpim at hotmail.com Wed Oct 19 23:12:48 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Wed, 19 Oct 2005 17:12:48 -0400 Subject: [Tutor] Saving command line keyed input? Message-ID: I know that one should use IDLE or a choosen editor for any substantial Python coding! However, if one happens to have written some interesting doodlings on the regular command line interface (under Windows XP in my case), is there an easy way to save ALL input to date into a selected file? For example: >>>class work_center: def __init__(self,x_name): self.name = x_name >>>x = work_center("machine press") >>> --- What do I do to save the above work into a file named "mywork.py" Thanks. RC _________________________________________________________________ On the road to retirement? Check out MSN Life Events for advice on how to get there! http://lifeevents.msn.com/category.aspx?cid=Retirement From bgailer at alum.rpi.edu Wed Oct 19 23:24:36 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 19 Oct 2005 14:24:36 -0700 Subject: [Tutor] Saving command line keyed input? In-Reply-To: References: Message-ID: <6.1.2.0.0.20051019142209.0350b4a8@mail.mric.net> At 02:12 PM 10/19/2005, CPIM Ronin wrote: >I know that one should use IDLE or a choosen editor for any substantial >Python coding! However, if one happens to have written some interesting >doodlings on the regular command line interface (under Windows XP in my >case), is there an easy way to save ALL input to date into a selected file? The way I do it is: select the text by dragging with the mouse (a recangle), then hit Enter. This puts it on the clipboard. Then go to where you want it and paste. As I did here: Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> "hi" 'hi' >>> From jonasmg at SoftHome.net Thu Oct 20 01:16:13 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Thu, 20 Oct 2005 00:16:13 +0100 Subject: [Tutor] iteration is overwriting the previous set value Message-ID: <4356D3BD.3010303@SoftHome.net> def _pre_save(self): for field in [self.name, self.native_name]: if not field.istitle(): #print field.title() field = field.title() The change I try to do there (field = field.title()) is not being applied I changed code so that you do 'self.foo = bar' statements for each attribute instead of using a loop and see if data gets saved, and it goes ok I'm supposed that each iteration is overwriting the previous set value how solve it? using a dict? From dyoo at hkn.eecs.berkeley.edu Thu Oct 20 01:18:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 19 Oct 2005 16:18:06 -0700 (PDT) Subject: [Tutor] iteration is overwriting the previous set value In-Reply-To: <4356D3BD.3010303@SoftHome.net> Message-ID: On Thu, 20 Oct 2005, Jonas Melian wrote: > def _pre_save(self): > for field in [self.name, self.native_name]: > if not field.istitle(): > #print field.title() > field = field.title() > > The change I try to do there (field = field.title()) is not being > applied I changed code so that you do 'self.foo = bar' statements for > each attribute instead of using a loop and see if data gets saved, and > it goes ok Hi Jonas, Do you understand why it isn't working? The issue is that 'field' is just another variable name, and the assignment just redirects that particular name to some other value. So when we're doing: field = field.title() this statement has no effect on any other name, and in particular, doesn't do any mutation on 'self'. As a related matter: ###### >>> a = "42" >>> b = a >>> b = "17" ###### What do you expect 'a' to be? > I'm supposed that each iteration is overwriting the previous set value > > how solve it? using a dict? One way to do this is to use getattr() and setattr() so that we can do mutation on 'self'. Your example above should work with: ################################################### def _pre_save(self): for fieldname in ['name', 'native_name']: value = getattr(self, fieldname) if not value.istitle(): setattr(self, fieldname, value.title()) ################################################### Hope this helps! From bgailer at alum.rpi.edu Thu Oct 20 02:20:04 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 19 Oct 2005 17:20:04 -0700 Subject: [Tutor] iteration is overwriting the previous set value In-Reply-To: <4356D3BD.3010303@SoftHome.net> References: <4356D3BD.3010303@SoftHome.net> Message-ID: <6.1.2.0.0.20051019170840.0351fa18@mail.mric.net> At 04:16 PM 10/19/2005, Jonas Melian wrote: >def _pre_save(self): > for field in [self.name, self.native_name]: > if not field.istitle(): > #print field.title() > field = field.title() > >The change I try to do there (field = field.title()) is not being applied Yes it is. field (a local variable) is being replaced by field.title(). You can confirm that by putting print field after the assignment. However I guess you want the change to apply to self.name and self.native_name. Unfortunately you have a list containing the values of self.name and self.native_name. Even if you modified the list elements (which assignment to field does not do) self.name and self.native_name would not be affected. Use getattr and setattr to access and assign the attributes, which you specify by name. def _pre_save(self): for fieldname in ['name', 'native_name']: setattr(self, fieldname) = getattr(self, fieldname).title() [snip] From bgailer at alum.rpi.edu Thu Oct 20 02:56:12 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 19 Oct 2005 17:56:12 -0700 Subject: [Tutor] iteration is overwriting the previous set value Message-ID: <6.1.2.0.0.20051019175419.0351dfc0@mail.mric.net> At 04:16 PM 10/19/2005, Jonas Melian wrote: >def _pre_save(self): > for field in [self.name, self.native_name]: > if not field.istitle(): > #print field.title() > field = field.title() And FWIW there is no benefit in using "if not field.istitle():" since it calculates the title value anyway you might just as well assign it without checking. From byron at christianfreebies.com Thu Oct 20 06:12:14 2005 From: byron at christianfreebies.com (Byron) Date: Wed, 19 Oct 2005 21:12:14 -0700 Subject: [Tutor] Python books: buying advice needed In-Reply-To: <40cda6f40510181435q6181be19r@mail.gmail.com> References: <40cda6f40510181435q6181be19r@mail.gmail.com> Message-ID: <4357191E.3070300@christianfreebies.com> Hi David, The answer depends. If you are looking for free resources, I would recommend checking out: http://www.greenteapress.com However, if you are looking for a professional-grade book, then I would recommend "Python Programming for the Absolute Beginner." I, personally speaking, found this book to be an excellent resource -- I would highly recommend it. Byron --- David Stotijn wrote: > Hi, > > I'm planning on buying a book to help me learn Python. Some of the books > I'm considering are a few years old and based on an older version of > Python (e.g. 2.3). > Is it wise to buy a book based on an older version? Are the principles > and methods used in those books outdated by now? > Ideally, the book I'm looking for has some "best practice" guidelines > and alot of example code. > > Do you have any tips? > > Thanks in advance! > > David > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From byron at christianfreebies.com Thu Oct 20 06:15:27 2005 From: byron at christianfreebies.com (Byron) Date: Wed, 19 Oct 2005 21:15:27 -0700 Subject: [Tutor] python books In-Reply-To: <20051019143700.56909.qmail@web25906.mail.ukl.yahoo.com> References: <20051019143700.56909.qmail@web25906.mail.ukl.yahoo.com> Message-ID: <435719DF.4010701@christianfreebies.com> David Holland wrote: > The best book I found was python programming for the > absolute beginner by Michael Dawson. I would strongly > recommend it. Yes, I would agree 100%. Michael Dawson does an excellent job teaching Python to beginners. (Most others don't come close to his book, in my opinion.) Byron --- From wescpy at gmail.com Thu Oct 20 07:26:02 2005 From: wescpy at gmail.com (w chun) Date: Wed, 19 Oct 2005 22:26:02 -0700 Subject: [Tutor] Python books: buying advice needed In-Reply-To: <4355ACBC.9090608@tds.net> References: <40cda6f40510181435q6181be19r@mail.gmail.com> <4355ACBC.9090608@tds.net> Message-ID: <78b3a9580510192226o26ec5a03kf308786fbf035dcf@mail.gmail.com> On 10/18/05, Kent Johnson wrote: > David Stotijn wrote: > > Hi, > > > > I'm planning on buying a book to help me learn Python. Some of the books > > I'm considering are a few years old and based on an older version of > > Python (e.g. 2.3). > > Is it wise to buy a book based on an older version? Are the principles > > and methods used in those books outdated by now? > > 2.3 is not that old. The basics of Python change slowly, especially the beginner-level stuff. The later versions introduce refinements, convenience features and new, advanced stuff; they don't generally break much or change the overall 'feel' of Python. I don't know if there are any books out yet that cover 2.4. > > > Ideally, the book I'm looking for has some "best practice" guidelines > > and alot of example code. > > > > Do you have any tips? > > I like _Learning Python_ david, as others have said, for beginners, the version of Python that's used has less impact than for more advanced users. look for any book that focuses on teaching you the language rather than just being a tutorial for the features in the latest releases. if you are completely new to programming, as many are here, then the recommendation for Dawson's Python for the Absolute Beginner seems to be a very popular choice. i recently picked up the book to evaluate to use as the textbook for my intro to programming class, but haven't had a chance to really go through it yet. it seems to have surpassed the popular Learn to Program Using Python by Alan Gauld, which is slightly dated but also a good choice. there is also the How to Think like a Computer Scientist series, which aims at teaching programming to high schoolers, and is available for a number of languages: Python, Java, C++, and Logo... see http://www.ibiblio.org/obp/thinkCS Dawson's book targets games. there are other intro to programming books on my shelf with alternative targets: Python Programming by John Zelle is gearsed towards learning Computer Science as an undergraduate, and Mark Guzdial's Intro to Computing and Programming in Python has a graphics/multimedia approach. and on the side, i'd recommend Chris Fehily's Python visual quickstart guide because it has lots of pictures and serves as a good reference for a beginner. books such as Learning Python and Core Python Programming are geared towards those who already know how to program. some have noted that Learning Python targets C programmers more than others, but Core Python doesn't assume anything other than knowing at least one other high-level language. and i *definitely* use Core Python when teaching my standard Python courses. ;-) i'd suggest taking a look through some of the titles discussed on this thread in a bookstore if possible to see what you like, and also check out the reviews on Amazon as well as Python book reviews online. hope this helps! --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Thu Oct 20 07:35:05 2005 From: wescpy at gmail.com (w chun) Date: Wed, 19 Oct 2005 22:35:05 -0700 Subject: [Tutor] Saving command line keyed input? In-Reply-To: <6.1.2.0.0.20051019142209.0350b4a8@mail.mric.net> References: <6.1.2.0.0.20051019142209.0350b4a8@mail.mric.net> Message-ID: <78b3a9580510192235j5b58d1a8o9866ec099b29b256@mail.gmail.com> On 10/19/05, bob wrote: > At 02:12 PM 10/19/2005, CPIM Ronin wrote: > >I know that one should use IDLE or a choosen editor for any substantial > >Python coding! However, if one happens to have written some interesting > >doodlings on the regular command line interface (under Windows XP in my > >case), is there an easy way to save ALL input to date into a selected file? > > The way I do it is: select the text by dragging with the mouse (a > recangle), then hit Enter. This puts it on the clipboard. Then go to where > you want it and paste. As I did here: hi ronin, another alternative you have in IDLE is to just open a source window by going to the File menu -> New Window, and doodling in there. then just click F5 (to save and) run your doodling. that way your code is already saved in a file. i do have to admit that it's not as easy as just playing in the interpreter and typing Ctrl-A and pasting that into your text editor, e-mail window, etc. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From jonasmg at SoftHome.net Thu Oct 20 09:32:48 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Thu, 20 Oct 2005 08:32:48 +0100 Subject: [Tutor] iteration is overwriting the previous set value In-Reply-To: <6.1.2.0.0.20051019170840.0351fa18@mail.mric.net> References: <4356D3BD.3010303@SoftHome.net> <6.1.2.0.0.20051019170840.0351fa18@mail.mric.net> Message-ID: <43574820.2080502@SoftHome.net> bob wrote: > At 04:16 PM 10/19/2005, Jonas Melian wrote: > >> def _pre_save(self): >> for field in [self.name, self.native_name]: >> if not field.istitle(): >> #print field.title() >> field = field.title() >> >> The change I try to do there (field = field.title()) is not being >> applied > > > Yes it is. field (a local variable) is being replaced by > field.title(). You can confirm that by putting > print field after the assignment. > > However I guess you want the change to apply to self.name and > self.native_name. > > Unfortunately you have a list containing the values of self.name and > self.native_name. Even if you modified the list elements (which > assignment to field does not do) self.name and self.native_name would > not be affected. > > Use getattr and setattr to access and assign the attributes, which you > specify by name. > > def _pre_save(self): > for fieldname in ['name', 'native_name']: > setattr(self, fieldname) = getattr(self, fieldname).title() > > [snip] > This fails: SyntaxError: can't assign to function call Danny Yoo's goes ok You've the reason: there is no benefit in using "if not field.istitle():" Thanks all From jonasmg at SoftHome.net Thu Oct 20 09:39:08 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Thu, 20 Oct 2005 08:39:08 +0100 Subject: [Tutor] iteration is overwriting the previous set value In-Reply-To: References: Message-ID: <4357499C.6040004@SoftHome.net> Your code is correct. Thanks I understood it. 'field' is a local variable inner that loop. Respect to a related matter, a should be '42' Danny Yoo wrote: >On Thu, 20 Oct 2005, Jonas Melian wrote: > > > >Hi Jonas, > > >Do you understand why it isn't working? > >The issue is that 'field' is just another variable name, and the >assignment just redirects that particular name to some other value. So >when we're doing: > > field = field.title() > >this statement has no effect on any other name, and in particular, doesn't >do any mutation on 'self'. > > >As a related matter: > >###### > > >>>>a = "42" >>>>b = a >>>>b = "17" >>>> >>>> >###### > >What do you expect 'a' to be? > > > > > >>I'm supposed that each iteration is overwriting the previous set value >> >>how solve it? using a dict? >> >> > >One way to do this is to use getattr() and setattr() so that we can do >mutation on 'self'. Your example above should work with: > >################################################### >def _pre_save(self): > for fieldname in ['name', 'native_name']: > value = getattr(self, fieldname) > if not value.istitle(): > setattr(self, fieldname, value.title()) >################################################### > > >Hope this helps! > > > > From ml.cyresse at gmail.com Thu Oct 20 10:58:20 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 20 Oct 2005 21:58:20 +1300 Subject: [Tutor] pytunes (Was __slots__, struct, etc.) Message-ID: Hi all, Well, the fruits of my labour and your assistance is now at a basic level. 'Tis called pytunes, designed to parse and make sense of the iPod's database file. I'm not satisfied with it at all, it's a bit half baked in terms of functions and classes, but I would heartily welcome your perusal and feedback, criticisms, suggestions regarding it as you see fit. I need to take a break and gain some perspective, but I'm going to keep working on this until it's usable and consistent. And, if anyone's got an iPod of any sort, please give it a go, and let me know how it goes, my little iPod mini isn't a broad test. Page is here - http://silence.decivex.net/pytunes.htm Please note, as I'm an absolute beginner with webpages and CSS, my website looks absolutely terrible in Internet Explorer, and I have no idea why, but I'm trying to fix it. (Any hints on this also gratefully received.) I'd like to thank those who've assisted me in grappling with some more unusual corners of Python, with special thanks (in no particular order) to Kent, Alan Gauld and Danny. Regards, Liam Clarke From dklose at nimr.mrc.ac.uk Thu Oct 20 11:01:51 2005 From: dklose at nimr.mrc.ac.uk (Dan Klose) Date: Thu, 20 Oct 2005 10:01:51 +0100 Subject: [Tutor] file opening and errors. Message-ID: <1129798914.2149.4.camel@yangon.mathbio.nimr> Hi, I usually use perl but fancy a bit of a change so have started playing with python. using perl to open a file or directory I usually use: open(FILE, $file) or die "Error: $!\n"; The $! is a perl variable that holds an error should the open fail, example being : "No such file or directory". With python I have use a try except block but I have no idea how I would get the same warning from python as I would from perl (the reason for the exception), I am not even sure if this is possible (I assume it must be) as google searching has been fruitless. Thanks for any help, pointers and suggestions. Dan. From wescpy at gmail.com Thu Oct 20 11:29:02 2005 From: wescpy at gmail.com (w chun) Date: Thu, 20 Oct 2005 02:29:02 -0700 Subject: [Tutor] file opening and errors. In-Reply-To: <1129798914.2149.4.camel@yangon.mathbio.nimr> References: <1129798914.2149.4.camel@yangon.mathbio.nimr> Message-ID: <78b3a9580510200229j783477b7s1c0b9274f132f925@mail.gmail.com> On 10/20/05, Dan Klose wrote: > > I usually use perl but fancy a bit of a change so have started playing > with python. congrats! :-) > using perl to open a file or directory I usually use: > open(FILE, $file) or die "Error: $!\n"; > > The $! is a perl variable that holds an error should the open fail, > example being : "No such file or directory". > > With python I have use a try except block but I have no idea how I would > get the same warning from python as I would from perl (the reason for > the exception), I am not even sure if this is possible (I assume it must > be) as google searching has been fruitless. in the body of your code, you'd have something like: try: f = open(filename, 'r') except IOError, e: print 'Error: %s' % str(e) # 'e' is a exception instance obj w/ the error string return # or sys.exit(1) or whatever you like hope this helps, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Thu Oct 20 13:48:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 07:48:54 -0400 Subject: [Tutor] Rebate on "Beginning Python" In-Reply-To: <4357191E.3070300@christianfreebies.com> References: <40cda6f40510181435q6181be19r@mail.gmail.com> <4357191E.3070300@christianfreebies.com> Message-ID: <43578426.3070105@tds.net> Apress, publisher of the book "Beginning Python: From Novice to Professional", is offering a $10 rebate if you purchase the book before October 30. See for example http://www.bookpool.com/sm/159059519X Kent From kent37 at tds.net Thu Oct 20 14:07:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 08:07:33 -0400 Subject: [Tutor] file opening and errors. In-Reply-To: <1129798914.2149.4.camel@yangon.mathbio.nimr> References: <1129798914.2149.4.camel@yangon.mathbio.nimr> Message-ID: <43578885.3050501@tds.net> Dan Klose wrote: > Hi, > > I usually use perl but fancy a bit of a change so have started playing > with python. > > using perl to open a file or directory I usually use: > > open(FILE, $file) or die "Error: $!\n"; > > The $! is a perl variable that holds an error should the open fail, > example being : "No such file or directory". If you want the error to be fatal as in the example above, my recommendation is to just use a plain open() call. If the open fails it will raise an exception which will be caught by the interpreter. The interpreter will print the text of the error and a complete stack trace which can be very useful in locating and troubleshooting the error. For example: >>> f=open('foo.txt') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'foo.txt' If you catch the exception and just print the error message you are suppressing useful information. If you want to print the error and continue processing, instead of aborting, traceback.print_exc() is handy - it prints the same information as the interpreter would. For example: >>> import traceback >>> def trapper(): ... try: ... f = open('foo.txt') ... except IOError: ... traceback.print_exc() ... print 'Still here...' ... >>> trapper() Traceback (most recent call last): File "", line 3, in trapper IOError: [Errno 2] No such file or directory: 'foo.txt' Still here... In these small examples the traceback is not that interesting, but in a larger program they can be helpful. Also it is a good habit in general not to suppress tracebacks - for file errors you may have a pretty good idea where the problem is, but other kinds of errors can be harder to track down. Kent From frankbloeink at nerdshack.com Wed Oct 19 17:31:39 2005 From: frankbloeink at nerdshack.com (Frank Bloeink) Date: Wed, 19 Oct 2005 17:31:39 +0200 Subject: [Tutor] regular expression matching a dot? In-Reply-To: <62b9617312def89628c31ef88d131978@uni-mainz.de> References: <62b9617312def89628c31ef88d131978@uni-mainz.de> Message-ID: <1129735899.9290.2.camel@speedking.dyndns.org> Hi [Christian|List] This post is not regarding your special problem (which anyway has been solved by now), but I'd like to share some general tip on working with regular expressions. There are some nice regex-debuggers out there that can help clearify what went wrong when a regex doesn't match when it should or vice versa. Kodos http://kodos.sourceforge.net/ is one of them, but there are many others that can make your life easier ; at least in terms of regex-debugging ;) Probably most of you (especially all regex-gurus) know about this already, but i thought it was worth the post as a hint for all beginners hth Frank On Wed, 2005-10-19 at 09:45 +0200, Christian Meesters wrote: > Hi > > I've got the problem that I need to find a certain group of file names > within a lot of different file names. Those I want to match with a > regular expression are a bit peculiar since they all look like: > ... > ...(regex-problem) > ... > Any ideas what I could do else? > TIA > Christian > > PS Hope that I described the problem well enough ... From kent37 at tds.net Thu Oct 20 14:52:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 08:52:25 -0400 Subject: [Tutor] regular expression matching a dot? In-Reply-To: <1129735899.9290.2.camel@speedking.dyndns.org> References: <62b9617312def89628c31ef88d131978@uni-mainz.de> <1129735899.9290.2.camel@speedking.dyndns.org> Message-ID: <43579309.40700@tds.net> Frank Bloeink wrote: > There are some nice regex-debuggers out there that can help clearify > what went wrong when a regex doesn't match when it should or vice versa. > > Kodos http://kodos.sourceforge.net/ is one of them, but there are many > others that can make your life easier ; at least in terms of > regex-debugging ;) Yes, these programs can be very helpful. There is even one that ships with Python - see C:\Python24\Tools\Scripts\redemo.py Kent From 3dbernard at gmail.com Thu Oct 20 14:58:18 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 20 Oct 2005 08:58:18 -0400 Subject: [Tutor] "Decompile" pyc file In-Reply-To: <434FBA41.4070103@tds.net> References: <61d0e2b40510140644l6b3e684bme55ea74e2ceac61d@mail.gmail.com> <434FBA41.4070103@tds.net> Message-ID: <61d0e2b40510200558x7e38ca49q224564f951e3c563@mail.gmail.com> Sorry for the late reply. Thanks a lot Kent, that was really helpful. Bernard On 10/14/05, Kent Johnson wrote: > Bernard Lebel wrote: > > Hello, > > > > Is there a way to "decompile" a pyc file? I have a big problem where > > the py file was lost, but the pyc file is instact. I would need to > > extract the source code from the pyc file. > > Google 'python decompiler' > > try http://www.freshports.org/devel/decompyle/ > or the commercial service at http://www.crazy-compilers.com/decompyle/ > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From luke.jordan at gmail.com Thu Oct 20 16:46:54 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Thu, 20 Oct 2005 09:46:54 -0500 Subject: [Tutor] define vars by iteration In-Reply-To: References: Message-ID: Danny, It does help. I'm still stuck on part of it though, maybe a little background will help. To learn more about classes I decided to make a class Map, with many instances that have directions pointing to other Map instances. Each Map has different objects you can find on it, but is still a Map, so I have to customize each one. So if the only solution involves having names that could collide with builtins, I'd like to do it that way. I recognize the potential for chaos, but none of the names that I am using will collide (crossed fingers) becuase I'm using names like "Backyard", "Kitchen" etc. So, >>> MyBackyard = Map("MyBackyard") >>> MyBackyard.setDirections() set direction for N: MyHouse set direction for S: TheStreet >>> MyBackyard.N MyHouse etc, where MyHouse and TheStreet are made, via function, into MyHouse = Map("MyHouse") and so forth. Each instance is pickled in its own file named after self.name . When I load the pickles like this classNameList = ["Yard","Kitchen","LivingRoom"] def getPickles(): for name in classNameList: filepath = "C:\Python24\"+name+".dat" openedFile = file(filepath,"r") classInstanceName = pickle.load(openedFile) classInstanceName.name = classInstanceName print classInstanceName.name, classInstanceName Yard Kitchen LivingRoom >>> LivingRoom >>> Kitchen name Kitchen not defined >>> Yard name Yard not defined Also, I have done what I'm trying to do successfully by populating a dictionary with class instances named after self.name , which, after the function runs, I can access this way >>> classDictionary["Yard"] the thing is I would like to be able to get at Yard's attributes by typing >>> Yard.anAttribute garbage cans at the prompt rather than >>> Yard = classDictionary["Yard"] >>> Yard.anAttribute garbage cans It's just that I can't pin down how to automate it, say through a loadAllMaps() func. Thanks again for your helpful advice! Luke On 10/19/05, Danny Yoo wrote: > > > > On Wed, 19 Oct 2005, Luke Jordan wrote: > > > I've got a bunch of pickled class instances with > > self.name attributes, and I would > like to assign the > > instances themselves to variables > > named whatever is stored in self.name < > http://self.name/> using a function. > > "Can't assign to literal", right? Is there a way to do this? > > Hi Luke, > > It's technically possible to do this, but discouraged. The reason it's > not so safe is because some of those names might collide with your own > program's names, or with the builtins. So if you start having pickled > instances with names like 'list' or 'open', havoc is bound to ensue. > > Furthermore, Python variable names have some physical restrictions that > may interfere with what you're trying to do: > > ###### > >>> 4meUshouldnthave = 42 > File "", line 1 > 4meUshouldnthave = 42 > ^ > SyntaxError: invalid syntax > ###### > > (For the gory details on what's allowed in a name "identifier", see: > http://www.python.org/doc/ref/identifiers.html) > > > A safer way to do that I think you want is to use a separate dictionary > container for those instances. As a concrete example: > > ###### > class Person: > def __init__(self, name): > self.name = name > > people_names = ['fred', 'barney', 'wilma', 'betty'] > people = {} > for name in people_names: > people[name] = Person(name) > ###### > > Rather than using a direct variable name to refer to the person, we can go > an indirect route, and refer to the corresponding entry in the 'people' > dictionary. Does this make sense? This is safer because there's no > potential to munge up the toplevel, plus the 'name' keys won't have the > restrictions that Python variable names have. > > > Hope this helps! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051020/60811317/attachment.html From bgailer at alum.rpi.edu Thu Oct 20 16:49:22 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 20 Oct 2005 07:49:22 -0700 Subject: [Tutor] iteration is overwriting the previous set value In-Reply-To: <43574820.2080502@SoftHome.net> References: <4356D3BD.3010303@SoftHome.net> <6.1.2.0.0.20051019170840.0351fa18@mail.mric.net> <43574820.2080502@SoftHome.net> Message-ID: <6.1.2.0.0.20051020074155.035973e0@mail.mric.net> At 12:32 AM 10/20/2005, Jonas Melian wrote: >bob wrote: > > > At 04:16 PM 10/19/2005, Jonas Melian wrote: > > > >> def _pre_save(self): > >> for field in [self.name, self.native_name]: > >> if not field.istitle(): > >> #print field.title() > >> field = field.title() > >> > >> The change I try to do there (field = field.title()) is not being > >> applied > > > > > > Yes it is. field (a local variable) is being replaced by > > field.title(). You can confirm that by putting > > print field after the assignment. > > > > However I guess you want the change to apply to self.name and > > self.native_name. > > > > Unfortunately you have a list containing the values of self.name and > > self.native_name. Even if you modified the list elements (which > > assignment to field does not do) self.name and self.native_name would > > not be affected. > > > > Use getattr and setattr to access and assign the attributes, which you > > specify by name. > > > > def _pre_save(self): > > for fieldname in ['name', 'native_name']: > > setattr(self, fieldname) = getattr(self, fieldname).title() > > > > [snip] > > >This fails: >SyntaxError: can't assign to function call Oops me bad. Did not test! setattr(self, fieldname, getattr(self, fieldname).title()) >Danny Yoo's goes ok > >You've the reason: there is no benefit in using "if not field.istitle():" Is that a question or an appreciation? If question: It takes execution time to test to see if something is already set. If the variables are already set the cost of checking them to avoid assigning then is about the same as the cost of just assigning. If the variables are not set then the cost of checking and assigning is twice the cost of just assigning. Also just assigning is less code to write and maintain. From srini_iyyer_bio at yahoo.com Thu Oct 20 18:32:02 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 20 Oct 2005 09:32:02 -0700 (PDT) Subject: [Tutor] how to do systematic searching in dictionary and printing it In-Reply-To: <6.1.2.0.0.20051020074155.035973e0@mail.mric.net> Message-ID: <20051020163202.47649.qmail@web31608.mail.mud.yahoo.com> dear group, I have two files in a text format and look this way: File a1.txt: >a1 TTAATTGGAACA >a2 AGGACAAGGATA >a3 TTAAGGAACAAA File b1.txt: >b1 TTAATTGGAACA >b2 AGGTCAAGGATA >b3 AAGGCCAATTAA I want to check if there are common elements based on ATGC sequences. a1 and b1 are identical sequences and I want to select them and print the headers (starting with > symbol). a1 '\t' b1 Here: >XXXXX is called header and the line followed by >line is sequence. In bioinformatics, this is called a FASTA format. What I am doing here is, I am matching the sequences (these are always 25 mers in this instance) and if they match, I am asking python to write the header +'\t'+ header ak = a[1::2] av = a[::2] seq_dict = dict(zip(ak,av)) ************************************** >>>seq_dict {'TTAAGGAACAAA': '>a3', 'AGGACAAGGATA': '>a2', 'TTAATTGGAACA': '>a1'} ************************************** bv = b[1::2] *************************************** >>>bv ['TTAATTGGAACA', 'AGGTCAAGGATA', 'AAGGCCAATTAA'] >>>for i in bv: if seq_dict.has_key(i): print seq_dict[i] >a1 *************************************** Here a1 is the only common element. However, I am having difficulty printing that b1 is identical to a1 how do i take b and do this search. It was easy for me to take the sequence part by doing b[1::2]. however, I want to print b1 header has same sequence as a1 a1 +'\t'+b1 Is there anyway i can do this. This is very simple and due to my brain block, I am unable to get it out. Can any one please help me out. Thanks __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From grouch at gmail.com Thu Oct 20 18:48:07 2005 From: grouch at gmail.com (Andrew P) Date: Thu, 20 Oct 2005 11:48:07 -0500 Subject: [Tutor] file opening and errors. In-Reply-To: <1129798914.2149.4.camel@yangon.mathbio.nimr> References: <1129798914.2149.4.camel@yangon.mathbio.nimr> Message-ID: It's not in direct answer to your question, but a real short answer is "Python doesn't need 'or die' here." It throws exceptions gleefully whenever it encounters an error: >>> f = open('no_such_file') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'no_such_file' >>> import os >>> os.rmdir('/squeak') Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 41] Directory not empty: '/squeak' This behavior highlights one of the philosophical differences between the languages. Another reversal of stances to keep in mind is that variables are local by default in Python, and global by default in Perl. These are also two of my absolute favorite differences. Silent errors and global variables never sat well with me. Die and my are the general use cases :) Good luck, Andrew On 10/20/05, Dan Klose wrote: > Hi, > > I usually use perl but fancy a bit of a change so have started playing > with python. > > using perl to open a file or directory I usually use: > > open(FILE, $file) or die "Error: $!\n"; > > The $! is a perl variable that holds an error should the open fail, > example being : "No such file or directory". > > With python I have use a try except block but I have no idea how I would > get the same warning from python as I would from perl (the reason for > the exception), I am not even sure if this is possible (I assume it must > be) as google searching has been fruitless. > > Thanks for any help, pointers and suggestions. > > Dan. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Oct 20 19:56:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 13:56:24 -0400 Subject: [Tutor] how to do systematic searching in dictionary and printing it In-Reply-To: <20051020163202.47649.qmail@web31608.mail.mud.yahoo.com> References: <20051020163202.47649.qmail@web31608.mail.mud.yahoo.com> Message-ID: <4357DA48.6040307@tds.net> I would do this by making a dictionary mapping sequence to header for each data set. Then make a set that contains the keys common to both data sets. Finally use the dictionaries again to look up the headers. a = '''>a1 TTAATTGGAACA >a2 AGGACAAGGATA >a3 TTAAGGAACAAA'''.split() # Make a dict mapping sequence to header for the 'a' data set ak = a[1::2] av = a[::2] a_dict = dict(zip(ak,av)) print a_dict b = '''>b1 TTAATTGGAACA >b2 AGGTCAAGGATA >b3 AAGGCCAATTAA'''.split() # Make a dict mapping sequence to header for the 'b' data set bk = b[1::2] bv = b[::2] b_dict = dict(zip(bk,bv)) print b_dict # Make a set that contains the keys common to both dicts common_keys = set(a_dict.iterkeys()) common_keys.intersection_update(b_dict.iterkeys()) print common_keys # For each common key, print the corresponding headers for common in common_keys: print '%s\t%s' % (a_dict[common], b_dict[common]) Kent Srinivas Iyyer wrote: > dear group, > > > I have two files in a text format and look this way: > > > File a1.txt: > >>a1 > > TTAATTGGAACA > >>a2 > > AGGACAAGGATA > >>a3 > > TTAAGGAACAAA > > > > File b1.txt: > >>b1 > > TTAATTGGAACA > >>b2 > > AGGTCAAGGATA > >>b3 > > AAGGCCAATTAA > > > I want to check if there are common elements based on > ATGC sequences. a1 and b1 are identical sequences and > I want to select them and print the headers (starting > with > symbol). > > a1 '\t' b1 > > > > Here: > >>XXXXX is called header and the line followed by >line > > is sequence. In bioinformatics, this is called a FASTA > format. What I am doing here is, I am matching the > sequences (these are always 25 mers in this instance) > and if they match, I am asking python to write the > header +'\t'+ header > > > ak = a[1::2] > av = a[::2] > seq_dict = dict(zip(ak,av)) > > ************************************** > >>>>seq_dict > > {'TTAAGGAACAAA': '>a3', 'AGGACAAGGATA': '>a2', > 'TTAATTGGAACA': '>a1'} > ************************************** > > > > bv = b[1::2] > > *************************************** > >>>>bv > > ['TTAATTGGAACA', 'AGGTCAAGGATA', 'AAGGCCAATTAA'] > > > >>>>for i in bv: > > if seq_dict.has_key(i): > print seq_dict[i] > > > >>a1 > > > *************************************** > > Here a1 is the only common element. > > However, I am having difficulty printing that b1 is > identical to a1 > > > how do i take b and do this search. It was easy for me > to take the sequence part by doing > > b[1::2]. however, I want to print b1 header has same > sequence as a1 > > a1 +'\t'+b1 > > Is there anyway i can do this. This is very simple and > due to my brain block, I am unable to get it out. > Can any one please help me out. > > Thanks > > > > > > __________________________________ > Yahoo! Mail - PC Magazine Editors' Choice 2005 > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Thu Oct 20 20:36:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 20 Oct 2005 11:36:33 -0700 (PDT) Subject: [Tutor] file opening and errors. In-Reply-To: <1129798914.2149.4.camel@yangon.mathbio.nimr> Message-ID: > open(FILE, $file) or die "Error: $!\n"; > > The $! is a perl variable that holds an error should the open fail, > example being : "No such file or directory". > > With python I have use a try except block but I have no idea how I would > get the same warning from python as I would from perl (the reason for > the exception), I am not even sure if this is possible (I assume it must > be) as google searching has been fruitless. Hi Dan, If we leave off an explicit exception handler, any exceptions that happen will be considered fatal, and will croak out a stack trace, similar to what Perl does with its Carp module. For example: ###### >>> open('/foobar') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: '/foobar' ###### In my own programs, I usually don't do exception handling much because I do want my programs to fail fast and with a visible stack trace --- the default error message is usually informative enough. (I'm usually the only audience for my programs, so having verbose error messages is acceptable to me. *grin*) Best of wishes to you! From hugonz-lists at h-lab.net Thu Oct 20 20:58:21 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 20 Oct 2005 12:58:21 -0600 Subject: [Tutor] regular expression matching a dot? In-Reply-To: <43579309.40700@tds.net> References: <62b9617312def89628c31ef88d131978@uni-mainz.de> <1129735899.9290.2.camel@speedking.dyndns.org> <43579309.40700@tds.net> Message-ID: <4357E8CD.6050607@h-lab.net> I personally fancy Kiki, that comes with the WxPython installer... It has very nice coloring for grouping in Regexes. Hugo Kent Johnson wrote: > Frank Bloeink wrote: > >>There are some nice regex-debuggers out there that can help clearify >>what went wrong when a regex doesn't match when it should or vice versa. >> >>Kodos http://kodos.sourceforge.net/ is one of them, but there are many >>others that can make your life easier ; at least in terms of >>regex-debugging ;) > > > Yes, these programs can be very helpful. There is even one that ships with Python - see > C:\Python24\Tools\Scripts\redemo.py > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tomas.markus at gmail.com Thu Oct 20 21:10:53 2005 From: tomas.markus at gmail.com (Tomas Markus) Date: Thu, 20 Oct 2005 21:10:53 +0200 Subject: [Tutor] file.read..... Abort Problem Message-ID: <415a96060510201210u3491c8bej@mail.gmail.com> Hello Pythoners, This is probably a very newbie question (after all I am one): I am trying to read a file with some 2500 lines and to do a scan for "not allowed" characters in there (such as accented ones and so on). The problem is that the file I am testing with has got one of those somewhere on line 2100 (the hex value of the character is 1a) and all of the file.readfunctions (read, readline, readlines) actually stop reading the file exactly at that line as if it was interpreted as an EOF. Can you, please, help? Btw: When I am past this problem I will be asking yet another question: what is the most effective way to check a file for not allowed characters or how to check it for allowed only characters (which might be i.e. ASCII only). Many, many thanks. Tom -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051020/5f149d44/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Oct 20 21:31:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 20 Oct 2005 12:31:45 -0700 (PDT) Subject: [Tutor] define vars by iteration In-Reply-To: Message-ID: > Also, I have done what I'm trying to do successfully by populating a > dictionary with class instances named after self.name , > which, after the function runs, I can access this way > >>> classDictionary["Yard"] > > the thing is I would like to be able to get at Yard's attributes by typing > >>> Yard.anAttribute > garbage cans > at the prompt rather than > >>> Yard = classDictionary["Yard"] > >>> Yard.anAttribute > garbage cans Hi Luke, One thing to note is that we can formally plunk and embed these places in some kind of World: ###################################################### class World: def __init__(self): self.places = {} def attach(self, place): """Given a place, attaches it to the world.""" self.places[place.name] = place def lookup(self, name): return self.places[name] ###################################################### If each place was aware that it was a part of a world --- that is, if we embed the World inside each place as a part of a place's state --- then things might work out. For example, we might have a north-south corridor: ################################################################## class Corridor: def __init__(self, world, name, northName, southName): self.world, self.name, self.northName, self.southName = ( world, name, northName, southName) def N(self): return self.world.lookup(self.northName) def S(self): return self.world.lookup(self.southName) ################################################################## What's a little funny about this Corridor definition is that, because a cooridor knows its in the world, it can also ask the world what place 'northName' stands for in its N() method. Here's a small test: ###### >>> world = World() >>> world.attach(Corridor(world, "Water cooler", ... north="Stairs", south="Boss Office")) >>> world.attach(Corridor(world, "Stairs", ... north="Wall", south="Water cooler")) >>> >>> >>> world.lookup("Water cooler") <__main__.Corridor instance at 0x403a7fcc> >>> world.lookup("Water cooler").name 'Water cooler' >>> world.lookup("Water cooler").N() <__main__.Corridor instance at 0x403a7f6c> >>> world.lookup("Water cooler").N().name 'Stairs' ###### Another advantage of having a central place is that saving and restoring the environment is just a matter of pickling the world. Hmmm... briny pickles... *grin* Sorry, I'm getting distracted by food. Does this make sense? Please feel free to ask more questions. From kent37 at tds.net Thu Oct 20 21:33:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 15:33:18 -0400 Subject: [Tutor] "Decompile" pyc file In-Reply-To: <61d0e2b40510200558x7e38ca49q224564f951e3c563@mail.gmail.com> References: <61d0e2b40510140644l6b3e684bme55ea74e2ceac61d@mail.gmail.com> <434FBA41.4070103@tds.net> <61d0e2b40510200558x7e38ca49q224564f951e3c563@mail.gmail.com> Message-ID: <4357F0FE.7000608@tds.net> Bernard Lebel wrote: > Sorry for the late reply. > > Thanks a lot Kent, that was really helpful. What did you end up doing? I'm interested in what worked for you... Kent > > > Bernard > > > > On 10/14/05, Kent Johnson wrote: > >>Bernard Lebel wrote: >> >>>Hello, >>> >>>Is there a way to "decompile" a pyc file? I have a big problem where >>>the py file was lost, but the pyc file is instact. I would need to >>>extract the source code from the pyc file. >> >>Google 'python decompiler' >> >>try http://www.freshports.org/devel/decompyle/ >>or the commercial service at http://www.crazy-compilers.com/decompyle/ >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Oct 20 21:33:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 15:33:36 -0400 Subject: [Tutor] file.read..... Abort Problem In-Reply-To: <415a96060510201210u3491c8bej@mail.gmail.com> References: <415a96060510201210u3491c8bej@mail.gmail.com> Message-ID: <4357F110.9050708@tds.net> Tomas Markus wrote: > Hello Pythoners, > > This is probably a very newbie question (after all I am one): > > I am trying to read a file with some 2500 lines and to do a scan for > "not allowed" characters in there (such as accented ones and so on). The > problem is that the file I am testing with has got one of those > somewhere on line 2100 (the hex value of the character is 1a) and all of > the file.read functions (read, readline, readlines) actually stop > reading the file exactly at that line as if it was interpreted as an > EOF. Can you, please, help? Are you on windows? Try opening the file in binary mode: >>> d='abc\x1adef\nghij\n' >>> d 'abc\x1adef\nghij\n' >>> open('(temp)/test.txt', 'w').write(d) >>> d1=open('(temp)/test.txt').read() >>> d1 'abc' >>> d1=open('(temp)/test.txt', 'rb').read() >>> d1 'abc\x1adef\r\nghij\r\n' > Btw: When I am past this problem I will be > asking yet another question: what is the most effective way to check a > file for not allowed characters or how to check it for allowed only > characters (which might be i.e. ASCII only). You can read the file with read() and use a regex to search for unallowed characters. Kent > > Many, many thanks. > > Tom > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Oct 20 21:37:40 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 20 Oct 2005 12:37:40 -0700 (PDT) Subject: [Tutor] file.read..... Abort Problem In-Reply-To: <415a96060510201210u3491c8bej@mail.gmail.com> Message-ID: On Thu, 20 Oct 2005, Tomas Markus wrote: > I am trying to read a file with some 2500 lines and to do a scan for "not > allowed" characters in there (such as accented ones and so on). The problem > is that the file I am testing with has got one of those somewhere on line > 2100 (the hex value of the character is 1a) and all of the > file.readfunctions (read, readline, readlines) actually stop reading > the file exactly Try opening the file in 'binary' mode first: Python assumes that files are in text format by default. When it hits an EOF character, that signals the end of the file if it's in text mode. We can tell Python to treat a file as binary when we open it. For example: f = open('/usr/share/dict/words', 'rb') Afterwards, you should be able to look into the entire file. > what is the most effective way to check a file for not allowed > characters or how to check it for allowed only characters (which might > be i.e. ASCII only). If the file is small enough to fit into memory, you might use regular expressions as a sledgehammer. See: http://www.amk.ca/python/howto/regex/ for a small tutorial on regular expressions. But unless performance is a real concern, doing a character-by-character scan shouldn't be too horrendous. Best of wishes! From kent37 at tds.net Thu Oct 20 22:21:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 16:21:25 -0400 Subject: [Tutor] file.read..... Abort Problem In-Reply-To: References: Message-ID: <4357FC45.5060901@tds.net> Danny Yoo wrote: > > On Thu, 20 Oct 2005, Tomas Markus wrote: >>what is the most effective way to check a file for not allowed >>characters or how to check it for allowed only characters (which might >>be i.e. ASCII only). > > > If the file is small enough to fit into memory, you might use regular > expressions as a sledgehammer. See: > > http://www.amk.ca/python/howto/regex/ > > for a small tutorial on regular expressions. But unless performance is a > real concern, doing a character-by-character scan shouldn't be too > horrendous. Hi Danny, I was going to ask why you think regex is a sledgehammer for this one, then I decided to try the two alternatives and found out it is actually faster to scan for individual characters than to use a regex and look for them all at once! Here is a program that scans a string for test chars, either using a single regex search or by individually searching for the test chars. The test data set doesn't include any of the test chars so it is a worst case (neither scan terminates early): # FindAny.py import re, string data = string.letters * 2500 testchars = string.digits + string.whitespace testRe = re.compile('[' + testchars + ']') def findRe(): return testRe.search(data) is not None def findScan(): for c in testchars: if c in data: return True return False and here are the results of timing calls to findRe() and findScan(): F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findRe()" 100 loops, best of 3: 2.29 msec per loop F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findScan()" 100 loops, best of 3: 2.04 msec per loop Surprised the heck out of me! When in doubt, measure! When you think you know, measure anyway, you are probably wrong! Kent From lsloan-000002 at umich.edu Thu Oct 20 22:26:43 2005 From: lsloan-000002 at umich.edu (Lance E Sloan) Date: Thu, 20 Oct 2005 16:26:43 -0400 Subject: [Tutor] is mxDateTime recommended? Message-ID: Hello, all. It's been quite some time since I've sent a message to the Python tutor list. I would like to know if mxDateTime is still the recommended module to use for date calculations. I've been using it for a few years with a set of CGIs I had written. Should I continue to use that, or is there some other "preferred" module I should use? I ask because recently the Webmasters have changed from a Solaris environment to a Linux one. I recompiled the (very) old version of mxDateTime I have and it works, but through a process of elimination, I found that it is causing a segmentation fault as my program ends. That is, it does all the date manipulation properly, but as the Python interpreter terminates (due to a sys.exit() call, implicit end of program, or an error) a segmentation fault happens. I suspect that I could correct this by building a newer version of mxDateTime, but I just wanted to be sure that's what I should do before I spend the time on it. Thanks in advance! -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From kent37 at tds.net Thu Oct 20 22:34:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 16:34:34 -0400 Subject: [Tutor] file.read..... Abort Problem In-Reply-To: <4357FC45.5060901@tds.net> References: <4357FC45.5060901@tds.net> Message-ID: <4357FF5A.20300@tds.net> Kent Johnson wrote: > Here is a program that scans a string for test chars, either using a single regex search or by individually searching for the test chars. The test data set doesn't include any of the test chars so it is a worst case (neither scan terminates early): > > # FindAny.py > import re, string > > data = string.letters * 2500 > > testchars = string.digits + string.whitespace > testRe = re.compile('[' + testchars + ']') > > def findRe(): > return testRe.search(data) is not None > > def findScan(): > for c in testchars: > if c in data: > return True > return False > > > and here are the results of timing calls to findRe() and findScan(): > > F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findRe()" > 100 loops, best of 3: 2.29 msec per loop > > F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findScan()" > 100 loops, best of 3: 2.04 msec per loop > > Surprised the heck out of me! On the other hand, if the number of chars you are searching for is large (and unicode?) the regex solution wins: # FindAny.py (new version) # From a recipe by Martin v. L?wis, who claims that this regex match is "time independent of the number of characters in the class" # http://tinyurl.com/7jqgt import re, string, sys data = string.digits * 2500 data = data.decode('ascii') uppers = [] for i in range(sys.maxunicode): c = unichr(i) if c.isupper(): uppers.append(c) uppers = u"".join(uppers) uppers_re = re.compile(u'[' + uppers + u']') def findRe(): return uppers_re.search(data) is not None def findScan(): for c in uppers: if c in data: return True return False F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findRe()" 1000 loops, best of 3: 442 usec per loop F:\Tutor>python -m timeit -s "from FindAny import findRe, findScan" "findScan()" 10 loops, best of 3: 36 msec per loop Now the search solution takes 80 times as long as the regex! I'm-a-junkie-for-timings-ly-yrs, Kent From kent37 at tds.net Thu Oct 20 22:44:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 16:44:36 -0400 Subject: [Tutor] is mxDateTime recommended? In-Reply-To: References: Message-ID: <435801B4.70703@tds.net> Lance E Sloan wrote: > Hello, all. It's been quite some time since I've sent a message to the > Python tutor list. > > I would like to know if mxDateTime is still the recommended module to use > for date calculations. I've been using it for a few years with a set of > CGIs I had written. Should I continue to use that, or is there some other > "preferred" module I should use? Since 2.3 Python includes a datetime module which has some facility for date calculations. I think mxDateTime is more sophisticated but if your needs are simple take a look at datetime. Kent > > I ask because recently the Webmasters have changed from a Solaris > environment to a Linux one. I recompiled the (very) old version of > mxDateTime I have and it works, but through a process of elimination, I > found that it is causing a segmentation fault as my program ends. That is, > it does all the date manipulation properly, but as the Python interpreter > terminates (due to a sys.exit() call, implicit end of program, or an error) > a segmentation fault happens. > > I suspect that I could correct this by building a newer version of > mxDateTime, but I just wanted to be sure that's what I should do before I > spend the time on it. > > Thanks in advance! > > -- > Lance E Sloan, Systems Research Programmer III > U-M WATS: Web Applications, Technologies, and Solutions > Full-service web and database design, development, and hosting. > http://www.itcs.umich.edu/wats/ - "Putting U on the Web" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Thu Oct 20 23:03:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 20 Oct 2005 14:03:28 -0700 (PDT) Subject: [Tutor] file.read..... Abort Problem In-Reply-To: <4357FC45.5060901@tds.net> Message-ID: > I was going to ask why you think regex is a sledgehammer for this one, Regex's are more complex because we have to then make sure that none of the testchars have any special meaning as regular expression metacharacters. If one of those test chars, for example, contained things like '-' or '\\', we'd have to know to use re.escape() to be safe about things. Once we know regex's (and have been bitten by forgetting those issues... *grin*), then these factors aren't so large. From jonasmg at SoftHome.net Thu Oct 20 23:18:37 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Thu, 20 Oct 2005 22:18:37 +0100 Subject: [Tutor] Time - sum/difference Message-ID: <435809AD.6030808@SoftHome.net> I would get the local time of a country, using UTC (Universal Time Coordinated) and DST (Daylight SavingTime) of that country. An example, utc time -02:30 and dst +1 : country_utc = datetime.time(2,30) isUTCNegative = True dst = datetime.time(1,0) Now I would the difference of both times. -02:30 + 01:00 -> -01:30 Is possible get sum/difference of time values? How? Thanks in advance From carl.badgley at gmail.com Thu Oct 20 23:09:07 2005 From: carl.badgley at gmail.com (carl.badgley@gmail.com) Date: Thu, 20 Oct 2005 17:09:07 -0400 Subject: [Tutor] greetings... Message-ID: <1cbf5cf90510201409w36248683y9a1c43d136d5f321@mail.gmail.com> Greetings to list, Tomorrow is my last day in class with Lutz. I am not only new to Python but new to programming in general, this is my first language. Looking forward to your help in the days and weeks to come. Any suggestions for self tutorial, whether on python.org or not, would be greatly appreciated. I am going to finish his Learning... book first then hack open some open code for a simple project in order to see how it works. peace Carl -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051020/6fac0225/attachment.htm From john at fouhy.net Thu Oct 20 23:38:41 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 21 Oct 2005 10:38:41 +1300 Subject: [Tutor] is mxDateTime recommended? In-Reply-To: <435801B4.70703@tds.net> References: <435801B4.70703@tds.net> Message-ID: <5e58f2e40510201438v5038926cu@mail.gmail.com> On 21/10/05, Kent Johnson wrote: > Since 2.3 Python includes a datetime module which has some facility for date > calculations. I think mxDateTime is more sophisticated but if your needs are simple take > a look at datetime. The only significant difference I've come across is that mxDateTime has a .strptime() function (for parsing a string like "10/12/2005"), and python DateTime doesn't (so you have to go via the time module). -- John. From grouch at gmail.com Thu Oct 20 23:43:40 2005 From: grouch at gmail.com (Andrew P) Date: Thu, 20 Oct 2005 16:43:40 -0500 Subject: [Tutor] Help(!) with OOP/Composition from "Learning Python" Message-ID: I've been reading about composition vs inheritance, and went back to "Learning Python" to look at something I found very confusing a year ago. Turns out I still find it very confusing :) The code at the bottom was taken from the OOP chapter, it's a solution to one of the end-of-chapter problems. Honestly, this toy program is enough to make my head spin. Am I too stupid for OOP? Here is me trying to decipher it: Starting here: x = Lunch( ) # Self-test code x.order('burritos') # If run, not imported You have to look at the method of class Lunch: def order(self, foodName): # Start a Customer order simulation. self.cust.placeOrder(foodName, self.empl) check the instance name: self.cust = Customer( ) to see what class it belongs to, jump to class Customer, look up the method being called: def placeOrder(self, foodName, employee): # Place order with Employee. self.food = employee.takeOrder(foodName) which uses employee as an argument, which was, looking back up, an instance of class Employee: class Employee: def takeOrder(self, foodName): # Return a Food, with requested name. return Food(foodName) which seems to return an instance of food? I don't really understand that, but I've already forgotten what it was I started off looking to find :) x.result( ) Which is just entirely too much for my brain to hold at once. I'm sorry if this sounds like whining, but this entire program seems as bad as trying to decipher the GOTO-crazy scribblings of a lunatic. There is no linearity, and the extra abstraction of the classes just adds another layer of complexity. Instead of functions and arguments there are methods, classes, and instances being passed about willy-nilly and no (for me) easy way to follow the path or make sense of it. Is this just an example of a technique with a constant complexity factor that looks ridiculous on a toy program, but very quickly becomes useful on larger ones? Are there tools that make reading something like this more clear? Thanks, Andrew ############# # lunch program ############# class Lunch: def __init__(self): # Make/embed Customer and Employee. self.cust = Customer( ) self.empl = Employee( ) def order(self, foodName): # Start a Customer order simulation. self.cust.placeOrder(foodName, self.empl) def result(self): # Ask the Customer about its Food. self.cust.printFood( ) class Customer: def __init__(self): # Initialize my food to None. self.food = None def placeOrder(self, foodName, employee): # Place order with Employee. self.food = employee.takeOrder(foodName) def printFood(self): # Print the name of my food. print self.food.name class Employee: def takeOrder(self, foodName): # Return a Food, with requested name. return Food(foodName) class Food: def __init__(self, name): # Store food name. self.name = name if __name__ == '__main__': x = Lunch( ) # Self-test code x.order('burritos') # If run, not imported x.result( ) x.order('pizza') x.result( ) From john at fouhy.net Fri Oct 21 00:03:57 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 21 Oct 2005 11:03:57 +1300 Subject: [Tutor] pytunes (Was __slots__, struct, etc.) In-Reply-To: References: Message-ID: <5e58f2e40510201503t2c5bd59ck@mail.gmail.com> Hmm, neat. I don't have any feedback for you on your code, but since you're working with this sort of thing, I have a puzzle for you: Suppose you have a collection of MP3 files. You want to build a random playlist, subject to the condition that tracks by the same artist are as far apart as possible. You can assume you have the track / artist data in any structure you like. How would you do this? (I have a solution, but I don't think it is optimal. In fact, I'm not sure how to actually define "optimal" here... And so I am interested in how other people would solve this problem :-) ) -- John. From TValone at DMV.CA.gov Fri Oct 21 00:20:02 2005 From: TValone at DMV.CA.gov (Valone, Toren W.) Date: Thu, 20 Oct 2005 15:20:02 -0700 Subject: [Tutor] PYBSDDB help Message-ID: <5AE0A72A4C0AD711806A000255FC47DB09CC19EA@dmv-ent-ex07.dmv-ent.root.dmv.ca.gov> I am creating my Db with this code def open_db(self): self.cadmvinfo.open(self.filename, db.DB_HASH, db.DB_CREATE,db.DB_DUP) I am putting the data with this code def store_data(self,manual_processing_code,date,file_code,license_number,vin_num ber, year_model,make,user_info,End_Usr_ac): print "storing data..." self.cadmvinfo.put("manual_processing_code",manual_processing_code) self.cadmvinfo.put("date" ,date) self.cadmvinfo.put("filecode" ,file_code) self.cadmvinfo.put("licensenumber" ,license_number) self.cadmvinfo.put("vinnumber" ,vin_number) self.cadmvinfo.put("yearmodel" ,year_model) self.cadmvinfo.put("make" ,make) self.cadmvinfo.put("userinfo" ,user_info) self.cadmvinfo.put("EndUsrac" ,End_Usr_ac) but I still cannot get it to store duplicate keys (in other words I overwrite the data over and over) I know it is something simple, but cannot put my finger on it. Help! From alan.gauld at freenet.co.uk Fri Oct 21 01:09:19 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Oct 2005 00:09:19 +0100 Subject: [Tutor] Help(!) with OOP/Composition from "Learning Python" References: Message-ID: <006101c5d5cb$4d105300$0a01a8c0@xp> > I've been reading about composition vs inheritance, and went back to > "Learning Python" to look at something I found very confusing a year > ago. Turns out I still find it very confusing :) I don;t know the example but from the snippetts you've posted it doresn't look like a particularly good example of OOD. So that won't help. However its not a terrible example either... > Am I too stupid for OOP? Definitely not but for some people OOP is not as naturally intuitive as it is to others. For some reason those with a background in math seem to find OOP less intuitive, I dunno if that applies to you though :-) WHen OOP first appeared several studies suggestedit took between 6 months to 2 years for an established non OOP programmer to fully "convert" to OOP whereas complete newbies picke it up in less than 3 months... So much of the effort comes in unlearning old habits. x = Lunch( ) # Self-test code x.order('burritos') # If run, not imported Pesonally Lunch is a strange name for a class and order() is not an operation I'd assosiate with a lunch object - eat() maybe! These are the kind of design issues I referred to above. > def order(self, foodName): # Start a Customer order simulation. > self.cust.placeOrder(foodName, self.empl) Again a weird design decision, I wouldn't expect to place an order with a customer, I'd expect that to be on the waiter object. I would expect to see a customer send a messaage to a waiter asking to place an order for a Lunch.... And the Lunch would comprise several courses/foodstuffs. Again a weird OO design IMHO. > def placeOrder(self, foodName, employee): # Place order with Employee. > self.food = employee.takeOrder(foodName) Now here we have the empoyee taking the order, that makes more sense. > x.result( ) And what exactly a Lunch object doesin response to a result message I have no idea, again a badly chosen method IMHO. > Which is just entirely too much for my brain to hold at once. Absolutely. You are not supposed to try to follow the chain of command to the bottom, you are supposed to work with theobjects as stand alone mini programs. YOu don;t think about how they work inside any more than you read the Python interpreter source code every time you call it (I assume you don't do that???!) Objects are tested independantly and thereafter we just trust them to do what they claim to do. > bad as trying to decipher the GOTO-crazy scribblings of a lunatic. Not so because at least there can be no returns from the middle of blocks etc... > There is no linearity, and the extra abstraction of the classes just > adds another layer of complexity. You are right that there is no linearity. Thats one characterisatic of an OOP programme. The structure is a directed graph of object relationships with messages passing between objects along the connecting lines. It is not a heirarchical tree structuire as found in structured programming. > Instead of functions and arguments there are methods, classes, > and instances being passed about willy-nilly There should be messages which include objects as their arguments. Its important to conceptually separate messages from methods. We send a message to an object and it responds by executing a method - which method we mauy not know(this is polymorphism!) - and we get a result back. We pass objects around so that the receiving object can call methods of that object - this is somewhat akin to passing function pointers or lambdas in more traditional languages. > no (for me) easy way to follow the path or make sense of it. You cannot easily do that without specialised debuggers such as "Look!" etc OOP works on the assumption that you debug one object at a time and rarely need to follow the code to understand whats happening. In the example given it looks like the object lattice and method names are not too intuitive. > Is this just an example of a technique with a constant complexity > factor that looks ridiculous on a toy program, but very quickly > becomes useful on larger ones? Thereis a huge amount of trith in that too. I rarely use OOP on programs of less than 50 -100 lines but beyond that size and the use of OOP really kicks in. By the time you have 10,000+ lines OOP becomes very powerful. > Are there tools that make reading something like this more clear? There are many tools but most are commercial. I mentioned the Look! debugger for C++/Java and SmallTalk. Borland and Microsoft both provide message visualisation tools too. Many OOD CASE tools provide simulation tools for testing s design prior to generating code. Don't give up hope but rather try to live in faith for a spell. Ty to find some other examples of Python OOP too, I don;t personally like the look of the Lunch example. One of the key features of a good OOP programme is that each object should have clear reponsibilities and those should be exposed as the objectsinterface. These objects look like they aren't quite sure who orders what! At risk of too much blatant self promotion try the OOP topic in my tutor. Also try reading through the Games framework (hmgui.zip) that I submitted to Useless Python (or is described in the paper book version of my tutor) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Fri Oct 21 01:10:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 20 Oct 2005 16:10:30 -0700 (PDT) Subject: [Tutor] PYBSDDB help In-Reply-To: <5AE0A72A4C0AD711806A000255FC47DB09CC19EA@dmv-ent-ex07.dmv-ent.root.dmv.ca.gov> Message-ID: Hi Toren, Ok, I see that you've asked your question on the pybsddb mailing list as well a few weeks ago, which is fine. http://lists.sourceforge.net/lists/listinfo/pybsddb-users Unfortunately, it looks like spammers have attacked that mailing list badly enough that it appears they've done severe damage to that community there We'll do what we can to help. Your call to open(): self.cadmvinfo.open(self.filename, db.DB_HASH, db.DB_CREATE,db.DB_DUP) appears to be the culprit. I see that you're trying to db.DB_CREATE and db.DB_DUP as flags. I would have expected to see something like: db.DB_CREATE | db.DB_DUP because flags are traditionally combined by using bitwise arithmetic. However, DB_DUP is not a flag that should be passed off to the open() function anyway. I suspect that your problems stem from this, since if we don't call open() with the right arguments, then pybsddb won't do what you want. Let's ignore the DB_DUP stuff for the moment. According to: http://pybsddb.sourceforge.net/bsddb3.html the method signature for open() is: open(filename, dbname=None, dbtype=DB_UNKNOWN, flags=0, mode=0660) so if we're going to provide arguments that override the defaults, we'll want to be explicit in which arguments we'ere overriding. Rather than: self.cadmvinfo.open(self.filename, db.DB_HASH, db.DB_CREATE) Try: self.cadmvinfo.open(self.filename, dbtype=db.DB_HASH, flags=db.DB_CREATE) where we explictely say which arguments go where. That way, we have no possiblity of accidently putting db.DB_HASH into the place where open() expects a database name. According to: http://pybsddb.sourceforge.net/api_c/db_open.html I don't see DB_DUP being a flag option that we pass into open(). Instead, I see it as an option to set_flags() instead: http://pybsddb.sourceforge.net/api_c/db_set_flags.html So the following will probably do what you want: self.cadmvinfo.set_flags(db.DB_DUP) self.cadmvinfo.open(self.filename, dbtype=db.DB_HASH, flags=db.DB_CREATE) This matches the usage in the test case examples in bsddb/test/test_basics.py in the pybsddb source distribution. Do you have any questions on this so far? From dyoo at hkn.eecs.berkeley.edu Fri Oct 21 01:14:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 20 Oct 2005 16:14:24 -0700 (PDT) Subject: [Tutor] file.read..... Abort Problem (fwd) Message-ID: [Keeping tutor in CC] ---------- Forwarded message ---------- Date: Thu, 20 Oct 2005 23:21:13 +0200 From: Tomas Markus To: Danny Yoo Subject: Re: [Tutor] file.read..... Abort Problem Hi All, Just to let you know my ressults (+ one tiny question :-): I did a bit of investigation and narrowed the "invalid" characters group to jus one the hex 1a. My code now looks quite small: fpath = 'c:\\pytemp\\bafir550.edi' fl = file(fpath, 'rb') print 'Checking file %s' % fpath x=0 for line in fl.readlines(): x=x+1 if "" in line: print 'Not allowed chars at line %s --- %s' % (x,line), print "The check finished on line %s which was %s" % (x,line) The only proble is tha in the if clause there actually is the hex 1a character. The code works when executed from idle but when I run it from command line, I get: File "c:\Apps\PTOOLS\payfiles\editest.py", line 7 if " ^ SyntaxError: EOL while scanning single-quoted string Is there any workaround? Thanks Tom On 20/10/05, Danny Yoo wrote: > > > > I was going to ask why you think regex is a sledgehammer for this one, > > Regex's are more complex because we have to then make sure that none of > the testchars have any special meaning as regular expression > metacharacters. If one of those test chars, for example, contained things > like '-' or '\\', we'd have to know to use re.escape() to be safe about > things. > > Once we know regex's (and have been bitten by forgetting those issues... > *grin*), then these factors aren't so large. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Oct 21 01:45:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 19:45:18 -0400 Subject: [Tutor] Time - sum/difference In-Reply-To: <435809AD.6030808@SoftHome.net> References: <435809AD.6030808@SoftHome.net> Message-ID: <43582C0E.2000209@tds.net> Jonas Melian wrote: > I would get the local time of a country, using UTC (Universal Time > Coordinated) and DST (Daylight SavingTime) of that country. > > An example, utc time -02:30 and dst +1 : > > country_utc = datetime.time(2,30) > isUTCNegative = True > dst = datetime.time(1,0) > > Now I would the difference of both times. > -02:30 + 01:00 -> -01:30 > > Is possible get sum/difference of time values? How? I'm not exactly sure what you are looking for, but you can subtract datetime.datetime instances. If you are trying to find the difference between local time and utc this is one way: >>> import datetime as dt >>> dt.datetime.now() datetime.datetime(2005, 10, 20, 19, 41, 30, 393000) >>> dt.datetime.utcnow() datetime.datetime(2005, 10, 20, 23, 41, 52, 195000) >>> dt.datetime.utcnow()-dt.datetime.now() datetime.timedelta(0, 14400) though there is a race condition here that might give you an error of a millisecond sometimes. Kent From kent37 at tds.net Fri Oct 21 02:02:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 20:02:54 -0400 Subject: [Tutor] file.read..... Abort Problem (fwd) In-Reply-To: References: Message-ID: <4358302E.7070100@tds.net> > From: Tomas Markus > Just to let you know my ressults (+ one tiny question :-): > I did a bit of investigation and narrowed the "invalid" characters group to > jus one the hex 1a. My code now looks quite small: > > fpath = 'c:\\pytemp\\bafir550.edi' > fl = file(fpath, 'rb') > print 'Checking file %s' % fpath > x=0 > for line in fl.readlines(): > x=x+1 > if "" in line: > print 'Not allowed chars at line %s --- %s' % (x,line), > print "The check finished on line %s which was %s" % (x,line) > > The only proble is tha in the if clause there actually is the hex 1a > character. You don't have to type an actual 1a character to get it into a Python string. You can use special character escapes instead. To put a hex value into a string, use the escape \x followed by the two hex digits. So your test can be if "\x1a" in line: This way there is no actual 1a character in your program, but it will still do what you want. Kent From grouch at gmail.com Fri Oct 21 02:35:35 2005 From: grouch at gmail.com (Andrew P) Date: Thu, 20 Oct 2005 19:35:35 -0500 Subject: [Tutor] Help(!) with OOP/Composition from "Learning Python" In-Reply-To: <006101c5d5cb$4d105300$0a01a8c0@xp> References: <006101c5d5cb$4d105300$0a01a8c0@xp> Message-ID: Hi Alan, thanks for taking the time to answer so thoroughly. I've responded to a few things below. But let me say right off I have gone through the OOP section in your excellent tutor. It was one of my main resources learning Python. I actually have Bertand Meyer's book here (and have written a couple small programs in Eiffel!) based on your recommendation, but I think my main confusion is stemming from composition vs inheritance, and it's effect on program readability/understandability. I went to "Learning Python" looking for that composition example trying to make things a little more concrete. On 10/20/05, Alan Gauld wrote: > However its not a terrible example either... > > > Am I too stupid for OOP? > > Definitely not but for some people OOP is not as naturally intuitive as it > is to others. For some reason those with a background in math seem > to find OOP less intuitive, I dunno if that applies to you though :-) I was referring specifically to being able to follow how the classes interacted to obtain the results. I know that objects interact dynamically at runtime, so there may only be so much I can infer, but I am trying to read code to get an idea of how to write it, and it was discouraging to be stymied by an example from "Learning Python", especially a do-nothing example.. > Absolutely. You are not supposed to try to follow the chain of command > to the bottom, you are supposed to work with theobjects as stand alone > mini programs. YOu don;t think about how they work inside any more > than you read the Python interpreter source code every time you call it > (I assume you don't do that???!) Objects are tested independantly and > thereafter we just trust them to do what they claim to do. How does this relate to composition vs inheritance? When you have multiple classes composed of multiple parts of multiple other classes, doesn't that freeze your interface decisions early on? It seems to really tightly bind classes together. I think I just need to track down a real-world example, maybe. This was probably the wrong one to choose. I just can't picture how it would even be possible to write and grow. Inheritance, subclassing, and overloading are much simpler concepts, and relatively straightforward to read, at any rate, ignoring design issues :) You can point to a class and say ok, this is inheriting that class's methods, or overloading an abstract class. Perhaps it's just the interaction between classes that is giving me a problem. > > Instead of functions and arguments there are methods, classes, > > and instances being passed about willy-nilly > > There should be messages which include objects as their arguments. > Its important to conceptually separate messages from methods. We > send a message to an object and it responds by executing a method > - which method we mauy not know(this is polymorphism!) - and we > get a result back. We pass objects around so that the receiving object > can call methods of that object - this is somewhat akin to passing > function pointers or lambdas in more traditional languages. > I should have been more clear here, as well. I was talking more specifically about the example as composition. I think I am just missing something conceptually. I've written basic classes for myself before that just bundle logic and state, and I think they were reasonable choices for objects. But really it was just a way to interact with an object procedurally, like I do every day with Python. I'm just not sure how to organize the piecemeal composition of new classes from existing ones, in any sensical way. Or for that matter, how to arrange a bundle of classes with no "leader" :) Speaking of structural programming biases. But at least I recognize that hurdle, and can see how it would be possible. > At risk of too much blatant self promotion try the OOP topic in my tutor. > Also try reading through the Games framework (hmgui.zip) that I submitted > to Useless Python (or is described in the paper book version of my tutor) > Well, that sounds like a real-world example I can look at :) Thanks again for your time, Alan. From tubaranger at gmail.com Fri Oct 21 02:52:12 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Thu, 20 Oct 2005 19:52:12 -0500 Subject: [Tutor] Dynamic Function Assignment Message-ID: <57aa55060510201752w6d2434a1teeae20c021f36592@mail.gmail.com> Hello- Suppose I have three objects... a = MyObject(id=1) b = MyObject(id=2) c = MyObject(id=3) As I read in segments from my file, I need to choose one of the above based on the segment, something like this; segment = 'A Segment to Process' for id, S in (('A',a), ('B',b), ('C',c)): if segment.upper().startswith(id): S.DoSomething(segment) That is, I want to associate an object to work with a condition on the input segment (there are dozens of segment types and very large files to process). But I'd like to clean up the "for" statement and have something like this: for id in ('A', 'B', 'C'): if segment.upper().startswith(id): ??how can I select the correct object here with a big "if" statement?? The routine works fine as is, but if I can clean up the syntax I will be able to configure the application via a database; very attractive because I can process all of the records with one fairly small (~500 line) routine. Thanks for your consideration... --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051020/3d49c075/attachment.htm From john at fouhy.net Fri Oct 21 03:02:35 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 21 Oct 2005 14:02:35 +1300 Subject: [Tutor] Dynamic Function Assignment In-Reply-To: <57aa55060510201752w6d2434a1teeae20c021f36592@mail.gmail.com> References: <57aa55060510201752w6d2434a1teeae20c021f36592@mail.gmail.com> Message-ID: <5e58f2e40510201802u7a001b7bo@mail.gmail.com> On 21/10/05, Greg Lindstrom wrote: > Suppose I have three objects... > > a = MyObject(id=1) > b = MyObject(id=2) > c = MyObject(id=3) > > segment = 'A Segment to Process' > > for id in ('A', 'B', 'C'): > if segment.upper().startswith(id): > ??how can I select the correct object here with a big "if" > statement?? Perhaps a dictionary? Something like: myObjects = { 'A':MyObject(id=1), 'B':MyObject(id=2), 'C':MyObject(id=3) } for c in ('A', 'B', 'C'): if segment.upper().startswith(c): myObjects[c].doSomething(segment) If your MyObject instances are going to be constructed in a systematic way, then you could simplify your definition of myObjects a bit more. Eg: objectData = [('A', 1), ('B', 2), ('C', 3)] # etc myObjects = dict([(c, MyObject(id=id)) for c, id in objectData]) Hope this helps! -- John. From kent37 at tds.net Fri Oct 21 04:08:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Oct 2005 22:08:28 -0400 Subject: [Tutor] Dynamic Function Assignment In-Reply-To: <5e58f2e40510201802u7a001b7bo@mail.gmail.com> References: <57aa55060510201752w6d2434a1teeae20c021f36592@mail.gmail.com> <5e58f2e40510201802u7a001b7bo@mail.gmail.com> Message-ID: <43584D9C.40606@tds.net> John Fouhy wrote: > On 21/10/05, Greg Lindstrom wrote: > >> Suppose I have three objects... >> >> a = MyObject(id=1) >> b = MyObject(id=2) >> c = MyObject(id=3) >> >> segment = 'A Segment to Process' >> >> for id in ('A', 'B', 'C'): >> if segment.upper().startswith(id): >> ??how can I select the correct object here with a big "if" >>statement?? > > Something like: > > myObjects = { 'A':MyObject(id=1), 'B':MyObject(id=2), 'C':MyObject(id=3) } > for c in ('A', 'B', 'C'): > if segment.upper().startswith(c): > myObjects[c].doSomething(segment) This can be simplified even further to something like key = segment[0].upper() myObjects[key].doSomething(segment) This will raise an exception if segment doesn't start with A, B or C. But the idea is that once you have a dictionary you can look up segment directly. To handle the exception you can use a try/except block or use a default handler. Kent From johan at accesstel.co.za Fri Oct 21 07:47:56 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 21 Oct 2005 07:47:56 +0200 Subject: [Tutor] "Decompile" pyc file In-Reply-To: <61d0e2b40510200558x7e38ca49q224564f951e3c563@mail.gmail.com> References: <61d0e2b40510140644l6b3e684bme55ea74e2ceac61d@mail.gmail.com> <434FBA41.4070103@tds.net> <61d0e2b40510200558x7e38ca49q224564f951e3c563@mail.gmail.com> Message-ID: <4358810C.4040501@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051021/bd58de69/attachment.htm From SChitti at manh.com Fri Oct 21 08:23:40 2005 From: SChitti at manh.com (Suri Chitti) Date: Fri, 21 Oct 2005 11:53:40 +0530 Subject: [Tutor] How do I recursively remove the contents of a directory?? Message-ID: If I have a directory /u01/qa/logs and the logs has a number of children directories and I want to remove everything in logs and logs itself, is there a single method or command to do that? I want to avoid recursively removing the files in each child directory and so on. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051021/0df9ff8d/attachment.htm From wescpy at gmail.com Fri Oct 21 09:02:37 2005 From: wescpy at gmail.com (w chun) Date: Fri, 21 Oct 2005 00:02:37 -0700 Subject: [Tutor] How do I recursively remove the contents of a directory?? In-Reply-To: References: Message-ID: <78b3a9580510210002o6fbb6c79rc059bcc525d6e379@mail.gmail.com> On 10/20/05, Suri Chitti wrote: > > If I have a directory /u01/qa/logs and the logs has a number of children > directories and I want to remove everything in logs and logs itself, is > there a single method or command to do that? I want to avoid recursively > removing the files in each child directory and so on. i'd try /bin/rm -rf /u01/qa/logs from the shell. if you have to do it programmatically, you can use os.system() with that cmd. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ml.cyresse at gmail.com Fri Oct 21 09:21:50 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 21 Oct 2005 20:21:50 +1300 Subject: [Tutor] Help(!) with OOP/Composition from "Learning Python" In-Reply-To: References: Message-ID: On 10/21/05, Andrew P wrote: > I've been reading about composition vs inheritance, and went back to > "Learning Python" to look at something I found very confusing a year > ago. Turns out I still find it very confusing :) > > The code at the bottom was taken from the OOP chapter, it's a solution > to one of the end-of-chapter problems. > > Honestly, this toy program is enough to make my head spin. Am I too > stupid for OOP? Here is me trying to decipher it: > > Starting here: > > x = Lunch( ) # Self-test code > x.order('burritos') # If run, not imported > > You have to look at the method of class Lunch: > > def order(self, foodName): # Start a Customer order simulation. > self.cust.placeOrder(foodName, self.empl) > > check the instance name: > > self.cust = Customer( ) > > to see what class it belongs to, jump to class Customer, look up the > method being called: > > def placeOrder(self, foodName, employee): # Place order with Employee. > self.food = employee.takeOrder(foodName) > > which uses employee as an argument, which was, looking back up, an > instance of class Employee: > > class Employee: > def takeOrder(self, foodName): # Return a Food, with requested name. > return Food(foodName) > > which seems to return an instance of food? I don't really understand > that, but I've already forgotten what it was I started off looking to > find :) > > x.result( ) > > Which is just entirely too much for my brain to hold at once. I'm > sorry if this sounds like whining, but this entire program seems as > bad as trying to decipher the GOTO-crazy scribblings of a lunatic. > There is no linearity, and the extra abstraction of the classes just > adds another layer of complexity. Instead of functions and arguments > there are methods, classes, and instances being passed about > willy-nilly and no (for me) easy way to follow the path or make sense > of it. > > Is this just an example of a technique with a constant complexity > factor that looks ridiculous on a toy program, but very quickly > becomes useful on larger ones? Are there tools that make reading > something like this more clear? > > Thanks, > > Andrew > > > ############# > # lunch program > ############# > > class Lunch: > def __init__(self): # Make/embed Customer and Employee. > self.cust = Customer( ) > self.empl = Employee( ) > def order(self, foodName): # Start a Customer order simulation. > self.cust.placeOrder(foodName, self.empl) > def result(self): # Ask the Customer about its Food. > self.cust.printFood( ) > > class Customer: > def __init__(self): # Initialize my food to None. > self.food = None > def placeOrder(self, foodName, employee): # Place order with Employee. > self.food = employee.takeOrder(foodName) > def printFood(self): # Print the name of my food. > print self.food.name > > class Employee: > def takeOrder(self, foodName): # Return a Food, with requested name. > return Food(foodName) > > class Food: > def __init__(self, name): # Store food name. > self.name = name > > if __name__ == '__main__': > x = Lunch( ) # Self-test code > x.order('burritos') # If run, not imported > x.result( ) > x.order('pizza') > x.result( ) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Andrew, You've run into one of my biggest peeves when trying to learn OO. The whole "OO models real world objects" is detrimental when the examples that are given are pointless to programming. You'll never model someone ordering pizza. Alan Gauld's tutorial has a decent guide to OO, but it still takes a bit of getting used to. That's why I like Python, it doesn't force you into a certain style of programming, as opposed to something like, say, Java, and it's somewhat ludicrous Hello World - http://java.sun.com/docs/books/tutorial/getStarted/application/ The thing is, if you can use a list method or string method, you're using OO, and when you begin learning, you don't need to know too much about objects immediately. I attempted to learn programming via my local university, which taught Java, and our first lab had us creating the classes Tap (Faucet for the norteamericanos), Mixer and Basin. While, in retrospect, I can see that it included some essential bits of Java like multiple constructors, get/sets, subclassing etc, it was just so pointless, (as was the rest of the practical stuff until the very last assignment where one built a calculator) as all you were doing was designing classes that passed unit tests. Speaking for myself, I learn best when I come across a problem that needs a particular solution. I still don't know exactly what a composite is, but my best guess is that it's just a design pattern to simplify handling multiple instances, wherein multiple instances are passed in to one instance and controlled via methods of that object. I found this "Composite: this pattern is often used to handle complex composite recursive structures." which sounds about right. I can't think of a specific example for that. But I've just used something similar to it. In the iPod's database, data regarding a song comes in several different sections, each of which needs to be manipulated in it's own right. But, to make it easier, instead of having to handle seven/eight objects at once, I created a Song object, which has methods to act on those seven/eight objects for me. For instance, to change the artist of a song, you have to change an attribute of two objects, which the Song class does for me via one method. I hope that's a correctish example, hopefully someone will correct me if it's not. All the examples of composite objects I can find tend to be ahem.. rather abstract with many a leaf and node object. I do wish you luck in your endeavour. Regards, Liam Clarke From ml.cyresse at gmail.com Fri Oct 21 09:44:25 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 21 Oct 2005 20:44:25 +1300 Subject: [Tutor] pytunes (Was __slots__, struct, etc.) In-Reply-To: <5e58f2e40510201503t2c5bd59ck@mail.gmail.com> References: <5e58f2e40510201503t2c5bd59ck@mail.gmail.com> Message-ID: Hmmm, that's interesting. Obviously, for a playlist with x songs, and n songs by a particular artist, the optimum separation between songs would be x/n. Which would be easy for one artist, but for all of them? Hmm... Let's see. First off, let's discount all the artists with only one song, they can be the space filler. Next, you'd have to work out optimal spacing for each artist's songs, and try to insert them into a list. If that slot was already taken, you'd want to look down and up the list for the next free space, choosing whichever maximised the distance. And you'd have to treat x[5] - 10 as x[96] for a list x where len(x) == 100. Err, there's got to be an algorithm for this sorta stuff, but I can't understand the big words when I google it... what's your solution? On 10/21/05, John Fouhy wrote: > Hmm, neat. I don't have any feedback for you on your code, but since > you're working with this sort of thing, I have a puzzle for you: > > Suppose you have a collection of MP3 files. You want to build a > random playlist, subject to the condition that tracks by the same > artist are as far apart as possible. You can assume you have the > track / artist data in any structure you like. How would you do this? > > (I have a solution, but I don't think it is optimal. In fact, I'm not > sure how to actually define "optimal" here... And so I am interested > in how other people would solve this problem :-) ) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From meesters at uni-mainz.de Fri Oct 21 10:03:25 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Fri, 21 Oct 2005 10:03:25 +0200 Subject: [Tutor] regular expression matching a dot? Message-ID: <09886ba0f8d1fbb52288f5a2835d38e2@uni-mainz.de> Hi Frank & Kent & Hugo, Didn't have the time to read the list yesterday ... Thanks for pointing me to the regex-debuggers. Though I don't considered myself a regex-beginner I had to learn, that now that I'm using regexes only occasionally I might need some help here and there. Cheers, Christian Frank Bloeink wrote: > Hi [Christian|List] > > This post is not regarding your special problem (which anyway has been > solved by now), but I'd like to share some general tip on working with > regular expressions. > There are some nice regex-debuggers out there that can help clearify > what went wrong when a regex doesn't match when it should or vice > versa. > > Kodos http://kodos.sourceforge.net/ is one of them, but there are many > others that can make your life easier ; at least in terms of > regex-debugging ;) > > Probably most of you (especially all regex-gurus) know about this > already, but i thought it was worth the post as a hint for all > beginners > > hth Frank From alan.gauld at freenet.co.uk Fri Oct 21 10:06:55 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Oct 2005 09:06:55 +0100 Subject: [Tutor] Dynamic Function Assignment References: <57aa55060510201752w6d2434a1teeae20c021f36592@mail.gmail.com> Message-ID: <002901c5d616$6760aa20$0a01a8c0@xp> for id in ('A', 'B', 'C'): if segment.upper().startswith(id): Think dictionary: objects = {'A': a, 'B':b, 'C':c} for id in ('A','B','C') objects[id].method() I have a section within my OOP topic that specifically talks about this in the context of a collection of bank account objects. You might find it worth skimming through. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Oct 21 10:10:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Oct 2005 09:10:21 +0100 Subject: [Tutor] How do I recursively remove the contents of a directory?? References: Message-ID: <003801c5d616$eaa602e0$0a01a8c0@xp> >If I have a directory /u01/qa/logs and the logs has a number of children > directories and I want to remove everything in logs and logs itself, is os.system('rm -rf %s ' % logpath) Sometimes its easier to use the OS directly! If you were selectively deleting files it would be different but for the sledgehammer case I'd pobably just go with rm... Alan g From jonasmg at SoftHome.net Fri Oct 21 10:24:45 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Fri, 21 Oct 2005 09:24:45 +0100 Subject: [Tutor] Time - sum/difference In-Reply-To: <43582C0E.2000209@tds.net> References: <435809AD.6030808@SoftHome.net> <43582C0E.2000209@tds.net> Message-ID: <4358A5CD.202@SoftHome.net> I wanted to sum two time values: -02:30 +01:00 -------------- -01:30 I found one solution: >>> time_local = dt.time(2,30) >>> time_str = str(time_local).split(':') Now I'll can get the first value, convert to integer and sum it. Kent Johnson wrote: >Jonas Melian wrote: > > >>I would get the local time of a country, using UTC (Universal Time >>Coordinated) and DST (Daylight SavingTime) of that country. >> >>An example, utc time -02:30 and dst +1 : >> >>country_utc = datetime.time(2,30) >>isUTCNegative = True >>dst = datetime.time(1,0) >> >>Now I would the difference of both times. >>-02:30 + 01:00 -> -01:30 >> >>Is possible get sum/difference of time values? How? >> >> > >I'm not exactly sure what you are looking for, but you can subtract datetime.datetime instances. If you are trying to find the difference between local time and utc this is one way: > > >>> import datetime as dt > >>> dt.datetime.now() >datetime.datetime(2005, 10, 20, 19, 41, 30, 393000) > >>> dt.datetime.utcnow() >datetime.datetime(2005, 10, 20, 23, 41, 52, 195000) > >>> dt.datetime.utcnow()-dt.datetime.now() >datetime.timedelta(0, 14400) > >though there is a race condition here that might give you an error of a millisecond sometimes. > >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From singletoned at gmail.com Fri Oct 21 11:02:37 2005 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 21 Oct 2005 10:02:37 +0100 Subject: [Tutor] Fwd: Saving command line keyed input? In-Reply-To: <34bb7f5b0510210202x1858783fg@mail.gmail.com> References: <34bb7f5b0510210202x1858783fg@mail.gmail.com> Message-ID: <34bb7f5b0510210202g17f6c9a5k@mail.gmail.com> A quick tip for the Windows command line. Ctrl-C, Ctrl-A etc don't work, neither does right-clicking (menu-click). However, right-clicking does work on the blue title bar. Right-click on the blue title bar and then go down to Edit and then you can Select All. Then right-click on the blue title bar again and go down to Edit and then Copy. If at any point you right click in the black part of the window or do a Ctrl key sequence, it deselects all your text. Very unintuitive, as it is completely different to every other Windows app. (I think they do it on purpose to stop people wanting to use the Command Line). Ed On 19/10/05, CPIM Ronin wrote: > I know that one should use IDLE or a choosen editor for any substantial > Python coding! However, if one happens to have written some interesting > doodlings on the regular command line interface (under Windows XP in my > case), is there an easy way to save ALL input to date into a selected file? > > For example: > >>>class work_center: > def __init__(self,x_name): > self.name = x_name > > >>>x = work_center("machine press") > >>> > > --- What do I do to save the above work into a file named "mywork.py" > > Thanks. > > RC > > _________________________________________________________________ > On the road to retirement? Check out MSN Life Events for advice on how to > get there! http://lifeevents.msn.com/category.aspx?cid=Retirement > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Oct 21 12:08:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Oct 2005 06:08:17 -0400 Subject: [Tutor] Help(!) with OOP/Composition from "Learning Python" In-Reply-To: References: Message-ID: <4358BE11.1060305@tds.net> Andrew P wrote: > I've been reading about composition vs inheritance, and went back to > "Learning Python" to look at something I found very confusing a year > ago. Turns out I still find it very confusing :) > > The code at the bottom was taken from the OOP chapter, it's a solution > to one of the end-of-chapter problems. > > Honestly, this toy program is enough to make my head spin. Am I too > stupid for OOP? Here is me trying to decipher it: You did a pretty good job! > > Which is just entirely too much for my brain to hold at once. I'm > sorry if this sounds like whining, but this entire program seems as > bad as trying to decipher the GOTO-crazy scribblings of a lunatic. > There is no linearity, and the extra abstraction of the classes just > adds another layer of complexity. Instead of functions and arguments > there are methods, classes, and instances being passed about > willy-nilly and no (for me) easy way to follow the path or make sense > of it. I agree with the other posters that this is not a very good example of OOP. It shows some of the nuts and bolts of OOP - objects containing objects, invoking methods on objects and dividing responsibility between different classes - but it doesn't use them well and the motivation is lacking. Fundamentally classes are a way to package state (variables) and behaviour (functions) into a single abstraction. Done well, the resulting class has a coherence and utility of its own. For simple examples just look at Python's built in string, list and dict classes. In each case, the class hides considerable complexity and provides a useful abstraction. You can use a list without worrying about the details of how the list items are stored, how the storage is allocated, what happens when new storage is needed, etc., etc. You have at your disposal a sort() algorithm that has been tuned for high performance by top-notch programmers over many years, and much more. You can also think of classes very pragmatically, as another tool available to organize your code, just like modules and functions. Classes add some useful capabilities to your toolkit. This essay gives some simple motivating examples of why a beginner might want to use classes: http://personalpages.tds.net/~kent37/blog/stories/15.html > > Is this just an example of a technique with a constant complexity > factor that looks ridiculous on a toy program, but very quickly > becomes useful on larger ones? Are there tools that make reading > something like this more clear? There is a very real cost to OOP that responsibility for some action can be distributed among multiple cooperating classes, so to trace through an operation you may have to follow a chain from one class to the next. When the design is well done, the benefit of useful abstractions outweighs this cost. Done poorly, you can write object-oriented spaghetti code. The key is to have a clear idea of the responsibility of each class. Stepping through the code in a debugger can be useful to understanding the flow. Kent From kent37 at tds.net Fri Oct 21 12:11:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Oct 2005 06:11:39 -0400 Subject: [Tutor] How do I recursively remove the contents of a directory?? In-Reply-To: References: Message-ID: <4358BEDB.5000902@tds.net> Suri Chitti wrote: > If I have a directory /u01/qa/logs and the logs has a number of children > directories and I want to remove everything in logs and logs itself, is > there a single method or command to do that? I want to avoid > recursively removing the files in each child directory and so on. shutil.rmtree() (which actually does recursively remove all the children) Kent From kent37 at tds.net Fri Oct 21 12:14:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Oct 2005 06:14:27 -0400 Subject: [Tutor] Fwd: Saving command line keyed input? In-Reply-To: <34bb7f5b0510210202g17f6c9a5k@mail.gmail.com> References: <34bb7f5b0510210202x1858783fg@mail.gmail.com> <34bb7f5b0510210202g17f6c9a5k@mail.gmail.com> Message-ID: <4358BF83.8010202@tds.net> Ed Singleton wrote: > A quick tip for the Windows command line. > > Ctrl-C, Ctrl-A etc don't work, neither does right-clicking > (menu-click). However, right-clicking does work on the blue title > bar. > > Right-click on the blue title bar and then go down to Edit and then > you can Select All. Then right-click on the blue title bar again and > go down to Edit and then Copy. If you turn on Quick Edit (from Properties in the right-click menu) then you can select text and right-click to copy, then right-click again to paste. Kent From gsf at panix.com Fri Oct 21 17:39:52 2005 From: gsf at panix.com (Gabriel Farrell) Date: Fri, 21 Oct 2005 11:39:52 -0400 Subject: [Tutor] greetings... In-Reply-To: <1cbf5cf90510201409w36248683y9a1c43d136d5f321@mail.gmail.com> References: <1cbf5cf90510201409w36248683y9a1c43d136d5f321@mail.gmail.com> Message-ID: <20051021153952.GA2557@panix.com> Welcome to the list, Carl. Feel free to browse the list archive at http://mail.python.org/pipermail/tutor/ or http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor to get some idea of the kinds of questions asked and answers given. You'll find a lot of suggestions for beginners among the threads there as well. There's also http://wiki.python.org/moin/BeginnersGuide, which is always a good place to start. gsf On Thu, Oct 20, 2005 at 05:09:07PM -0400, carl.badgley at gmail.com wrote: > Greetings to list, > Tomorrow is my last day in class with Lutz. I am not only new to Python but > new to programming in general, this is my first language. Looking forward to > your help in the days and weeks to come. > Any suggestions for self tutorial, whether on python.org > or not, would be greatly appreciated. I am going to > finish his Learning... > book first then hack open some open code for a simple project in order to > see how it works. > peace > Carl > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dklose at nimr.mrc.ac.uk Fri Oct 21 18:19:35 2005 From: dklose at nimr.mrc.ac.uk (Dan Klose) Date: Fri, 21 Oct 2005 17:19:35 +0100 Subject: [Tutor] perldoc - confused! Message-ID: <1129911585.2149.44.camel@yangon.mathbio.nimr> Hello Python List, When using perl I tend to use perldoc. I spent ages today trying to list all items in a directory, simple I now know (os.listdir) but I was trying to use os.walk simply because I had no idea that listdir existed. I only found listdir because I was reading about walk!!!! Is there a python version of perldoc? Thanks for any guidance Dan. From wescpy at gmail.com Fri Oct 21 18:47:59 2005 From: wescpy at gmail.com (w chun) Date: Fri, 21 Oct 2005 09:47:59 -0700 Subject: [Tutor] Fwd: Saving command line keyed input? In-Reply-To: <4358BF83.8010202@tds.net> References: <34bb7f5b0510210202x1858783fg@mail.gmail.com> <34bb7f5b0510210202g17f6c9a5k@mail.gmail.com> <4358BF83.8010202@tds.net> Message-ID: <78b3a9580510210947u5d3fdfbej6119428fbdb032e8@mail.gmail.com> On 10/21/05, Kent Johnson wrote: > Ed Singleton wrote: > > A quick tip for the Windows command line. > > > > Ctrl-C, Ctrl-A etc don't work, neither does right-clicking > > (menu-click). However, right-clicking does work on the blue title > > bar. > > If you turn on Quick Edit (from Properties in the right-click menu) then you can select text and right-click to copy, then right-click again to paste. so yes, ed and kent are right. you have to do those things if you're running Python from the DOS window. Ctrl-A, Ctrl-C, Ctrl-V work from the IDLE window and most non-DOS win32 windows.. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ligon at are.berkeley.edu Fri Oct 21 20:13:47 2005 From: ligon at are.berkeley.edu (Ethan Ligon) Date: Fri, 21 Oct 2005 11:13:47 -0700 Subject: [Tutor] self knowledge Message-ID: <20051021181347.GA1787@are.berkeley.edu> I've devised a simple class; one of the class attributes is an identifier. Thus, class Foo: def __init__(self,name): self.name=name When using the class in practice, I've found it natural to create instances of Foo so that the instance itself is called name. Thus, I find myself doing things like: >>> a=Foo('a') >>> b=Foo('b') I want the name attribute to depend only on the name of the original variable; thus >>> c=a >>> c.name 'a' is the desired behavior. But this is plainly silly--I'm supplying information on identity twice when I instantiate each instance---and gives rise to two questions. First, my immediate inclination is to try and think of a way for the object to know its own name (at the time its instantiated) without being told, perhaps via the creation of a name method for Foo. But the only ways I can think of learning this name are all incredibly awkward and kludgy. What's the best way to do this? Second, because this seems awkward, I strongly suspect that there's a pretty fundamental problem with the way I'm approaching the problem. When the name of a variable is itself information which might be useful, what's the right way convey this information? Thanks, -Ethan -- Ethan Ligon, Assoc. Professor ligon at are.berkeley.edu Dept. of Agricultural & Resource Economics University of California http://are.berkeley.edu/~ligon Berkeley, CA 94720-3310 (510)643-5411 From singingxduck at gmail.com Fri Oct 21 20:33:58 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Fri, 21 Oct 2005 14:33:58 -0400 Subject: [Tutor] : Threads? Message-ID: <43593496.1000706@gmail.com> Hello all, I've been working on a program for a week or two now that will convert all the wav files in a folder to mp3s, filling the id3 tags with the correct information as collected from gracenote.com. This part works fine. However, the actual conversion to mp3 takes between 30 and 50 seconds per song, so it's usually about 10 minutes per album. With this in mind, I thought, why not try to use threads so all the conversions happen simultaneously? That way, the whole album will take between 30 and 50 seconds. Unfortunately, I can't seem to get a working threaded version that significantly reduces the time involved . . . The unthreaded version is available at http://rafb.net/paste/results/Y1DTnW54.html, and the current, only slightly time-improved threaded version is available at http://rafb.net/paste/results/Lvsjj495.html. Any and all suggestions as to how to threadify this are welcome. I realize the code isn't as pretty as it could be, but first I want to make a threaded version that works. Once this has been accomplished, I'll finish commenting the code and making it more user-friendly to read. Thanks in advance, Orri P.S. - In order to make my code work, it is necessary to download several modules. Once the code works, I'll include above the code a comment listing all the requirements. Right now, I believe the following modules are needed: ClientForm - http://wwwsearch.sourceforge.net/ClientForm/ id3writer - http://www.comfortableshoe.co.uk/cgi-bin/blosxom.cgi/Home/Python/id3Writer.comments (click the "download link" link) id3reader - http://www.comfortableshoe.co.uk/cgi-bin/blosxom.cgi/Home/Python/id3Writer.comments (click the "Ned Batchelder's id3Reader" link) PyID3 - http://sourceforge.net/projects/pyid3 threadpool - http://chrisarndt.de/en/software/python/threadpool.html I also considered using the following, but decided not to for reasons of difficulty of use or lack of desired operations: PyID3Tag - http://superduper.net/?page=pyid3tag ID3-Py - http://id3-py.sourceforge.net/ The following non-Python program is also needed: Lame - http://lame.sourceforge.net/download/download.html -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From kent37 at tds.net Fri Oct 21 20:44:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Oct 2005 14:44:48 -0400 Subject: [Tutor] self knowledge In-Reply-To: <20051021181347.GA1787@are.berkeley.edu> References: <20051021181347.GA1787@are.berkeley.edu> Message-ID: <43593720.3040202@tds.net> Ethan Ligon wrote: > I've devised a simple class; one of the class attributes is an identifier. > > Thus, > > class Foo: > def __init__(self,name): > self.name=name > > When using the class in practice, I've found it natural to > create instances of Foo so that the instance itself is called > name. Thus, I find myself doing things like: > > >>>>a=Foo('a') >>>>b=Foo('b') Why does this matter? Why do you need the name both places? > First, my immediate inclination is to try and think of > a way for the object to know its own name (at the time > its instantiated) without being told, perhaps via the > creation of a name method for Foo. But the only ways > I can think of learning this name are all incredibly > awkward and kludgy. What's the best way to do this? The only ways to do this are awkward and kludgy - you have to inspect the stack and find out the name of the variable in the caller. Don't do it. > > Second, because this seems awkward, I strongly suspect > that there's a pretty fundamental problem with the way > I'm approaching the problem. When the name of a variable > is itself information which might be useful, what's the > right way convey this information? I think this is the third time this question has come up this week! Usually the answer is to put your data in a dictionary or list. Here is another version: http://mail.python.org/pipermail/tutor/2005-October/042371.html From kent37 at tds.net Fri Oct 21 21:03:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Oct 2005 15:03:56 -0400 Subject: [Tutor] : Threads? In-Reply-To: <43593496.1000706@gmail.com> References: <43593496.1000706@gmail.com> Message-ID: <43593B9C.9000002@tds.net> Orri Ganel wrote: > Hello all, > > I've been working on a program for a week or two now that will convert > all the wav files in a folder to mp3s, filling the id3 tags with the > correct information as collected from gracenote.com. This part works > fine. However, the actual conversion to mp3 takes between 30 and 50 > seconds per song, so it's usually about 10 minutes per album. With this > in mind, I thought, why not try to use threads so all the conversions > happen simultaneously? That way, the whole album will take between 30 > and 50 seconds. Unfortunately, I can't seem to get a working threaded > version that significantly reduces the time involved . . . The The only part you are doing in a thread is the actual conversion. This is likely to be CPU-intensive so running it in multiple threads may not help - you still have only the one CPU to run on. To the extent that you can overlap disk I/O in one conversion with processing in another you may get a win; on the other hand you could just as well have contention for the disk as you try to read and write a bunch of files at the same time. The fetch from gracenote.com seems like a better candidate for threading because there is some latency...but the total time is still probably small compared to the conversion time. Maybe if you have multiple CPUs you can get a speedup by using as many threads as CPUs...I'm not sure how os.system() behaves in this case. You may have to explicitly fork to get a new process. Hmm...come to think of it, os.system() may block other threads, I don't know...you could try subprocess.Popen() instead. Kent > unthreaded version is available at > http://rafb.net/paste/results/Y1DTnW54.html, and the current, only > slightly time-improved threaded version is available at > http://rafb.net/paste/results/Lvsjj495.html. Any and all suggestions as > to how to threadify this are welcome. I realize the code isn't as > pretty as it could be, but first I want to make a threaded version that > works. Once this has been accomplished, I'll finish commenting the code > and making it more user-friendly to read. > > Thanks in advance, > Orri > > P.S. - In order to make my code work, it is necessary to download > several modules. Once the code works, I'll include above the code a > comment listing all the requirements. Right now, I believe the following > modules are needed: > > ClientForm - http://wwwsearch.sourceforge.net/ClientForm/ > id3writer - > http://www.comfortableshoe.co.uk/cgi-bin/blosxom.cgi/Home/Python/id3Writer.comments > (click the "download link" link) > id3reader - > http://www.comfortableshoe.co.uk/cgi-bin/blosxom.cgi/Home/Python/id3Writer.comments > (click the "Ned Batchelder's id3Reader" link) > PyID3 - http://sourceforge.net/projects/pyid3 > threadpool - http://chrisarndt.de/en/software/python/threadpool.html > > I also considered using the following, but decided not to for reasons of > difficulty of use or lack of desired operations: > > PyID3Tag - http://superduper.net/?page=pyid3tag > ID3-Py - http://id3-py.sourceforge.net/ > > The following non-Python program is also needed: > > Lame - http://lame.sourceforge.net/download/download.html > From singingxduck at gmail.com Fri Oct 21 21:12:08 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Fri, 21 Oct 2005 15:12:08 -0400 Subject: [Tutor] : Threads? In-Reply-To: <43593B9C.9000002@tds.net> References: <43593496.1000706@gmail.com> <43593B9C.9000002@tds.net> Message-ID: <43593D88.3010709@gmail.com> Kent Johnson wrote: >Orri Ganel wrote: > > >>Hello all, >> >>I've been working on a program for a week or two now that will convert >>all the wav files in a folder to mp3s, filling the id3 tags with the >>correct information as collected from gracenote.com. This part works >>fine. However, the actual conversion to mp3 takes between 30 and 50 >>seconds per song, so it's usually about 10 minutes per album. With this >>in mind, I thought, why not try to use threads so all the conversions >>happen simultaneously? That way, the whole album will take between 30 >>and 50 seconds. Unfortunately, I can't seem to get a working threaded >>version that significantly reduces the time involved . . . The >> >> > >The only part you are doing in a thread is the actual conversion. This is likely to be CPU-intensive so running it in multiple threads may not help - you still have only the one CPU to run on. To the extent that you can overlap disk I/O in one conversion with processing in another you may get a win; on the other hand you could just as well have contention for the disk as you try to read and write a bunch of files at the same time. > >The fetch from gracenote.com seems like a better candidate for threading because there is some latency...but the total time is still probably small compared to the conversion time. > >Maybe if you have multiple CPUs you can get a speedup by using as many threads as CPUs...I'm not sure how os.system() behaves in this case. You may have to explicitly fork to get a new process. > >Hmm...come to think of it, os.system() may block other threads, I don't know...you could try subprocess.Popen() instead. > >Kent > Thanks for the tip. Unfortunately, I only have 1 CPU and not the slightest idea how to code for multiple CPUs in any case. Looks like I'll just hafta deal with a 10-minute time per album. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From grouch at gmail.com Fri Oct 21 21:14:00 2005 From: grouch at gmail.com (Andrew P) Date: Fri, 21 Oct 2005 14:14:00 -0500 Subject: [Tutor] Help(!) with OOP/Composition from "Learning Python" In-Reply-To: <4358BE11.1060305@tds.net> References: <4358BE11.1060305@tds.net> Message-ID: On 10/21/05, Kent Johnson wrote: >For simple examples just look at Python's built in string, list and dict >classes. -Using- OOP isn't the problem :) It's impossible to ignore it's usefulness when programming in Python. But getting from there to thinking non-procedurally is, as has been pointed out, a tiny bit difficult. My frustration/abject fear was with this particular example being very hard to decipher, and not seeing any advantages to it being laid out that way. I assumed there were some, where this kind of thing had benefits. >You can also think of classes very pragmatically, as another tool available to >organize your code, just like modules and functions. Classes add some useful >capabilities to your toolkit. This essay gives some simple motivating examples >of why a beginner might want to use classes: >http://personalpages.tds.net/~kent37/blog/stories/15.html I realize after all these reposnses that I should have mentioned that I do use classes to do exactly that. Bundle logic and data, but then call the classes I've made procedurally. It's handy, having methods attached to objects, and to be able to use any object that supports the same interface interchangeably. But I have the nagging feeling I still have it all upside down and inside out. Writing a bunch of objects that are supposed to interact in dynamic ways at runtime with nobody leading the band, and all. Maybe if I'm not writing a a library or framework I shouldn't worry so much. > >There is a very real cost to OOP that responsibility for some action can be >distributed among multiple cooperating classes, so to trace through an >operation you may have to follow a chain from one class to the next. When the >design is well done, the benefit of useful abstractions outweighs this cost. >Done poorly, you can write object-oriented spaghetti code. The key is to have a >clear idea of the responsibility of each class. > For all I know people are using IDEs that let them write unreadable code that simultaneously allows loosest coupling between classes, and most reuse of code at the expense of readability. Giant jellyfish-like automatons that are easy to maintain with appropriate tools. I'm still not sure that impression is wrong :) I do my best learning by reading good examples. I imagine most people do. There is just no substitute for understanding what somebody else has done well, tip to tail. I am just mistrustful of something so hard to puzzle out. >Stepping through the code in a debugger can be useful to understanding the flow. I've never actually used a Python debugger. Or any debugger. That was such a commonsense answer I'm embarassed I didn't try it first. Thanks again, Kent :) From kent37 at tds.net Fri Oct 21 21:44:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Oct 2005 15:44:08 -0400 Subject: [Tutor] Help(!) with OOP/Composition from "Learning Python" In-Reply-To: References: <4358BE11.1060305@tds.net> Message-ID: <43594508.7050700@tds.net> Andrew P wrote: > On 10/21/05, Kent Johnson wrote: >>You can also think of classes very pragmatically, as another tool available to >>organize your code, just like modules and functions. > > I realize after all these reposnses that I should have mentioned that I do use > classes to do exactly that. > > But I have the nagging feeling I still have it all upside down and inside out. > Writing a bunch of objects that are supposed to interact in dynamic ways at > runtime with nobody leading the band, and all. Maybe if I'm not writing a > a library or framework I shouldn't worry so much. Hmm...there are probably some programs like that...maybe a large framework like Twisted. Most of my use of classes is fairly prosaic, just a way to organize code so it makes sense. Class instances are usually related by simple containment in a loose hierarchy of some sort. > For all I know people are using IDEs that let them write unreadable code that > simultaneously allows loosest coupling between classes, and most reuse of code > at the expense of readability. Giant jellyfish-like automatons that are easy > to maintain with appropriate tools. I'm still not sure that impression is > wrong :) Well, except for the "easy to maintain with appropriate tools" you are probably right. In fact I have the misfortune of working on a system like that right now. Without appropriate tools, whatever they may be. > > I do my best learning by reading good examples. I imagine most people do. > There is just no substitute for understanding what somebody else has done well, > tip to tail. I am just mistrustful of something so hard to puzzle out. This thread has a few suggestions: http://groups.google.com/group/comp.lang.python/browse_frm/thread/da095d94c77fe2c7?q=code+examples&hl=en& Kent From dyoo at hkn.eecs.berkeley.edu Fri Oct 21 23:00:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 21 Oct 2005 14:00:06 -0700 (PDT) Subject: [Tutor] perldoc - confused! In-Reply-To: <1129911585.2149.44.camel@yangon.mathbio.nimr> Message-ID: > I spent ages today trying to list all items in a directory, simple I now > know (os.listdir) but I was trying to use os.walk simply because I had > no idea that listdir existed. I only found listdir because I was > reading about walk!!!! You should have a 'pydoc' utility. It's also possible to get help from the interactive prompt by doing 'help()'. Good luck! From keridee at jayco.net Fri Oct 21 00:41:25 2005 From: keridee at jayco.net (Jacob S.) Date: Thu, 20 Oct 2005 17:41:25 -0500 Subject: [Tutor] Can anyone teach me...? References: <00b601c5cf68$63081670$0a01a8c0@xp><434DA349.2090300@adinet.com.uy> <012801c5cfd1$8ced8ce0$0a01a8c0@xp> Message-ID: <000001c5d689$0e4c1d20$6601a8c0@JSLAPTOP> >>>I use Delphi for most of my real-world heavy duty GUI work. >>> >> Have you tried Boa Constructor? It is quite similar to Delphi. It builds >> wxPython. > > I tried it a couple of years ago but couldn't get it to work! > > Even if I had it didn't offer many of the features of VB/Delphi such > as live database table views and close integration with the underlying > objects, it simply built a GUI with hooks for the event handlers. > A big step up from manually assembling TKInter in terms of simplicity > but the gain wasn't that much in real speed terms. > > It would be interesting to see how BOa and Glade have come on > the last couple of years.... > > Alan G. I didn't like PythonCard when I tried it, because I couldn't get it to merge the rcpy(?) file into the main py file and then there was all of the import the module into its own namespace, etc. It didn't go over well with me. Next, I checked out VB, great for building GUIs, but I have to agree that the code isn't that great after a year of python. I, too, found myself trying to find things in the library that weren't there. However, I was prepared to get to know VB well. I liked the ease of GUI building and the ability to make a stand-alone exe that the Professional Edition offered. Then, I did a little research on Boa-Constructor. I have heard on the list that it is a little unstable. The reason for this is the storing of the placement inside the main code blocks. As mentioned above, PythonCard uses a rcpy file to store these values, so it doesn't need to specially parse the main code block. However, I found that if I followed the style of the generated code, I could edit it directly. Otherwise, the parser runs into an error when you try to start the designer again. That's why there is the commented notice at the top of the _init_ctrls_ (or whatever it is) function that says #Generated method - do not edit Also, I noticed that the __init__ block was not affected by control placement, and therefore not parsed when the frame designer is started. This is good. All of my class level changes occur in the __init__ block, any initial lists are sent to listboxes there, etc. If you wish to delete an event, you might or might not have to change some of the generated code depending on whether you do it properly or not. If you delete the code directly, the parser doesn't catch the ids that it generated for the now-non-existent events. I also like the ability of it to use the very versatile wxPython library. Strangely, though, it doesn't seem to incorporate all of the wx library. Does anybody know why this is/when they will fix that? (Or how to fix it now?) I found it relatively easy to merge the separate files into one file after I finished the applications I did, and it has a very similar interface to that of VB. With a little more work, it could be the all powerful VB GUI building, python coding mix that was mentioned before. Ask for code and I will send! (maniacal laughter) Oh, and if you need help learning, I'm here keridee at jayco.net and I'm sure that the members on the list will be as forgiving with you as they are with several others who ask questions that they could find on their own with enough searching. (I know some will disagree with me, that's why I provided my email address specifically if it becomes a problem.) Jacob ;-) From keridee at jayco.net Sat Oct 22 01:05:58 2005 From: keridee at jayco.net (Jacob S.) Date: Fri, 21 Oct 2005 18:05:58 -0500 Subject: [Tutor] code improvement for beginner ? References: <4348310D.7080602@gmx.net> <434ADC43.7040600@tds.net> Message-ID: <016c01c5d694$1f723750$6601a8c0@JSLAPTOP> > Text mode is the default, you have to specify the 'b' if you want binary > mode. And open() seems to accept any mode quite happily: > > >>> f=open('build.xml', 'rt') > >>> f > > >>> f.close() > >>> f=open('build.xml', 'rabcd') > >>> f > > > Kent I'll bet you'll find that open() is coded something like the following def open(filename,mode="r"): if mode = 'w': dosomething() if mode = 'wb': dosomething() if mode = 'w+': dosomething() if mode = 'rb': dosomething() ... else: dosomething() # Where this assumes you are using default mode "r" This flow control with emphasis on the else means that if the mode doesn't match anything other than "r", then return file object mode "r" Let's see, now that I'm checking whether that's true, it doesn't quite match up. A file that's opened with "r" will check to see whether the file exists or not, whereas a file opened with nonsense does not. Ahh. That's because you can write to a file opened with nonsense. So instead the function (if it were written in python and not C) would probably look like this instead. def open(filename, mode="r") if mode = "r": dosomethingread() if mode = "rb": dosomethingreadbin() if mode = "w+": dosomethingwriteupd() ... else: dosomethingwrite() # Where write is in the else clause, but read is the default value for mode Phew. This seems strange. Why don't they put write in the control flow above with a raise statement in the else clause? HTH, Jacob From alan.gauld at freenet.co.uk Sat Oct 22 01:25:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 22 Oct 2005 00:25:32 +0100 Subject: [Tutor] self knowledge References: <20051021181347.GA1787@are.berkeley.edu> Message-ID: <005801c5d696$bb60d110$0a01a8c0@xp> Hi Ethan, > When using the class in practice, I've found it natural to > create instances of Foo so that the instance itself is called > name. Thus, I find myself doing things like: > >>>> a=Foo('a') >>>> b=Foo('b') > This is very common at the interactive prompt. However its nearly always the wrong thing to do in a real world type program. For one thing how will the code elsewhere in your programme know about these new object names? You would need to find a way for every point in your code to gain awareness of all the names currently in use! In fact Python does provide ways of doing that because the mnames are hekld in system dictionaries which you can access but its extre,mekly kludgy! Much better is to create your instances in a dictionary with the key being the name. Thus in your example: >>> objects = {} # empty dictionary >>> objects['a']=Foo('a') >>> objects['b']=Foo('b') You then access the objects with objects[name].method() slightly more typing but much easier to use because you can iterate over all the objects in the dictionary with for obj in objects: obj.dosomething() Otherwise you would need to know all the object names and call each in turn or resort to "black magic" to access the Python internal dictionaries. > I want the name attribute to depend only on the name of the > original variable Now that's a different proposition. Do you want the name to depend on the prebviously created variable or the variable name to depend on the object attribute? If you want the object attribute to depend on the variable name thats very strange. What happens when you pass the object to amother namespace? Or if you save to a file or database and then restore, will it always be associated with the same variable? Can you explain why you believe that would be useful? >>>> c=a >>>> c.name > 'a' > > is the desired behavior. OK, Thats different again. That could be done as shoewn above with >>> c = objects['a'] >>> c.name > First, my immediate inclination is to try and think of > a way for the object to know its own name (at the time > its instantiated) without being told variables in python are merely references to an object, the object is not actually called by the name of the variable. Consider: a = C() # an instance of c b = a # both a and b point at the instance which is the name of the C instance? Is it a or b or neither? >>> id(a) >>> id(b) shows that the objects real identity is a number which is unrelated to either 'a' or 'b' > Second, because this seems awkward, I strongly suspect > that there's a pretty fundamental problem with the way > I'm approaching the problem. When the name of a variable > is itself information which might be useful, what's the > right way convey this information? Yes you are trying tonsolve the wrong problem. Instances created dynamically at runtime are best kept in a container (list or dictionary) and managed as a group or selected on demand. A dictionary is usually the best option. After all thats why Python uses dictionaries under the hood for its own purposes! FWIW I give an example of this problem in the OOP topic of my tutor, in the bank account example where we need to store a collection of bank accounts by account ID. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Oct 22 01:29:17 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 22 Oct 2005 00:29:17 +0100 Subject: [Tutor] : Threads? References: <43593496.1000706@gmail.com> Message-ID: <005e01c5d697$41c6f1d0$0a01a8c0@xp> > in mind, I thought, why not try to use threads so all the conversions > happen simultaneously? That way, the whole album will take between 30 > and 50 seconds. One possible problem with this is that the activity is disk IO bound. In fact using too many threads could even slow the thing down as the HD head spends all its time shunting between files. If you keep the thread count down to two or three you might get a noticable improvement but one thread per track, unless you have a lot of separate hard disk spindles to distribute the work will not help much I suspect. Alan G. From kent37 at tds.net Sat Oct 22 01:39:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Oct 2005 19:39:28 -0400 Subject: [Tutor] code improvement for beginner ? In-Reply-To: <016c01c5d694$1f723750$6601a8c0@JSLAPTOP> References: <4348310D.7080602@gmx.net> <434ADC43.7040600@tds.net> <016c01c5d694$1f723750$6601a8c0@JSLAPTOP> Message-ID: <43597C30.9070306@tds.net> Jacob S. wrote: >> Text mode is the default, you have to specify the 'b' if you want >> binary mode. And open() seems to accept any mode quite happily: >> >> >>> f=open('build.xml', 'rt') >> >>> f >> >> >>> f.close() >> >>> f=open('build.xml', 'rabcd') >> >>> f >> >> >> Kent > > > I'll bet you'll find that open() is coded something like the following > > def open(filename,mode="r"): > if mode = 'w': > dosomething() > if mode = 'wb': > dosomething() > if mode = 'w+': > dosomething() > if mode = 'rb': > dosomething() > ... > else: > dosomething() # Where this assumes you are using default mode "r" One of the cool features of Python is that you can look at the source code to answer questions like this. open() is implemented in Objects/fileobject.c. Not too surprisingly, it delegates to the underlying C implementation for the actual open call. On Windows it converts the name and mode to Unicode and calls _wfopen(); on other platforms it calls fopen(). The ANSI C standard says, The argument mode points to a string. If the string is one of the following, the file is open in the indicated mode. Otherwise, the behavior is undefined. If the string begins with one of the [below] sequences, the implementation might choose to ignore the remaining characters, or it might use them to select different kinds of a file (some of which might not conform to the properties in 7.19.2). r open text file for reading w truncate to zero length or create text file for writing a append; open or create text file for writing at end-of-file etc so it seems the implementation is free to ignore characters it doesn't understand after a valid initial sequence. Kent From lsloan at umich.edu Sat Oct 22 02:13:23 2005 From: lsloan at umich.edu (Lance E Sloan) Date: Fri, 21 Oct 2005 20:13:23 -0400 Subject: [Tutor] is mxDateTime recommended? In-Reply-To: <435801B4.70703@tds.net> References: <435801B4.70703@tds.net> Message-ID: <3EDCACCF192588508BA40292@blue-four.us.itd.umich.edu> --On Thursday, October 20, 2005 4:44 PM -0400 Kent Johnson wrote: > Since 2.3 Python includes a datetime module which has some facility for > date calculations. I think mxDateTime is more sophisticated but if your > needs are simple take a look at datetime. I think I would like to use the "datetime" module included with Python, just so I don't need to worry about an additional piece of code, the "mxDateTime" module. In my code, I set up some mxDateTime RelativeDateTime objects that will be used later: secondLockBeginsDelta = DateTime.RelativeDateTime( day = 14, hour = 23, minute = 59, months = -4 ) When I add that to another mxDateTime object, the month, hour, and minute get set to those absolute values, but the month is reduced by four. I know I won't be able to exactly the same thing with datetime. I think I could do something like this (semi-pseudocode): firstTime = datetime.now() secondTime = firstTime - timedeltaFourMonthsObject secondTime.replace( day = 14, hour = 23, minute = 59 ) The problem is that I can't figure out how to create that timedeltaFourMonthsObject. The datetime timedelta class constructor doesn't allow creating a delta with a month. Any suggestions? (I think it's a little too bad that the timedelta class represents all deltas as days and seconds. That must be why they don't support months, since months have different lengths. IMHO...) Also, how can I make a copy of a datetime object? timeA = datetime.now() timeB = timeA # copy or reference to same object? -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From kent37 at tds.net Sat Oct 22 04:40:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Oct 2005 22:40:08 -0400 Subject: [Tutor] is mxDateTime recommended? In-Reply-To: <3EDCACCF192588508BA40292@blue-four.us.itd.umich.edu> References: <435801B4.70703@tds.net> <3EDCACCF192588508BA40292@blue-four.us.itd.umich.edu> Message-ID: <4359A688.2010900@tds.net> Lance E Sloan wrote: > When I add that to another mxDateTime object, the month, hour, and > minute get set to those absolute values, but the month is reduced by > four. I know I won't be able to exactly the same thing with datetime. > I think I could do something like this (semi-pseudocode): > > firstTime = datetime.now() > secondTime = firstTime - timedeltaFourMonthsObject > secondTime.replace( day = 14, hour = 23, minute = 59 ) > > The problem is that I can't figure out how to create that > timedeltaFourMonthsObject. The datetime timedelta class constructor > doesn't allow creating a delta with a month. Any suggestions? > > (I think it's a little too bad that the timedelta class represents all > deltas as days and seconds. That must be why they don't support months, > since months have different lengths. IMHO...) This thread may help: http://groups.google.com/group/comp.lang.python/browse_frm/thread/6c751e2845932c20/08466fb5a150dd9e?hl=en#08466fb5a150dd9e > Also, how can I make a copy of a datetime object? > > timeA = datetime.now() > timeB = timeA # copy or reference to same object? Reference to the same object. one way is: import copy timeB = copy.copy(timeA) Kent From tim.peters at gmail.com Sat Oct 22 05:40:16 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 21 Oct 2005 23:40:16 -0400 Subject: [Tutor] is mxDateTime recommended? In-Reply-To: <3EDCACCF192588508BA40292@blue-four.us.itd.umich.edu> References: <435801B4.70703@tds.net> <3EDCACCF192588508BA40292@blue-four.us.itd.umich.edu> Message-ID: <1f7befae0510212040q4515ec00w37d2758d8d99f227@mail.gmail.com> [Lance E Sloan] > ... > (I think it's a little too bad that the timedelta class represents all > deltas as days and seconds. And microseconds. > That must be why they don't support months, since months have > different lengths. IMHO...) That's right. It's hard to argue about what days, seconds and microseconds mean (note that I didn't say it's impossible <0.5 wink>). Exactly what "a month" means depends on who you ask, when you ask it, and what they're doing at the time. That is, there is no answer to the question that doesn't assume some policy that, while it may help some people some of the time, would at least as often get in the way for other people. datetime tries to be like, say, integers that way: a solid base with clear semantics, but if you want square roots you're gonna have to define what the heck you mean by that and do it yourself ;-) > Also, how can I make a copy of a datetime object? It's almost certainly the case that you don't really want to, but are suffering a confusion about something else that makes you _think_ you want to. It's hard to guess what that may be unless you can explain clearly what you think "making a copy" would _accomplish_ for you. It will almost certainly turn out to be the case that it would not accomplish what you're really after, or that there's no advantage in accomplishing it. datetime objects are (again like integers) immutable: there is nothing anyone can do to _change_ the value of a datetime object. In a nutshell, that's why "making a copy" is almost certainly irrelevant. For example, if you see that d.month is 7 at some point, d.month will always be 7 thereafter, no matter what other code you may run, just so long as `d` is bound to the same datetime object for the duration. There are no operations in the language that can mutate a datetime object's value. > timeA = datetime.now() > timeB = timeA # copy or reference to same object? Same object, and it makes no difference to that answer in Python no matter what appears on the right side of the first statement. You happened to use a datetime.date in this example, but it would be the same answer if you used an integer, string, list, tuple, function, bound method object, class, array, module, file ..., any object whatsoever. No exceptions. [Kent Johnson] > import copy > timeB = copy.copy(timeA) That does happen to make a distinct physical copy today, but there's no guarantee it will always do so. In general, _any_ operation is free to return a pre-existing instance of an object of an immutable type, if it has the correct value. Again there are no exceptions to that rule. Here's an example where copy.copy() doesn't happen to make a distinct physical copy today: >>> import copy >>> two = 2 >>> another_2 = copy.copy(2) >>> two is another_2 True Again, if anyone thinks "bad consequences" may follow from this, it's almost certainly the case that they misunderstand something else about Python. There is simply no way to tell whether two immutable objects with the same _value_ are or aren't the same physical object without looking at their memory addresses, and it's extremely rare for sane Python code to give a hoot about exactly where an object happens to reside in RAM. From singingxduck at gmail.com Sat Oct 22 06:15:41 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sat, 22 Oct 2005 00:15:41 -0400 Subject: [Tutor] : Threads? In-Reply-To: <005e01c5d697$41c6f1d0$0a01a8c0@xp> References: <43593496.1000706@gmail.com> <005e01c5d697$41c6f1d0$0a01a8c0@xp> Message-ID: <3449428f0510212115v741d03aeradc93f7700434b90@mail.gmail.com> I'll try doing 3 or 4 tracks per thread, then. Thanks for the advice. > > > If you keep the thread count down to two or three you might get > a noticable improvement but one thread per track, unless you have > a lot of separate hard disk spindles to distribute the work will > not help much I suspect. > > > Alan G. > -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051022/379e7790/attachment.htm From kent37 at tds.net Sat Oct 22 14:07:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Oct 2005 08:07:26 -0400 Subject: [Tutor] is mxDateTime recommended? In-Reply-To: <3EDCACCF192588508BA40292@blue-four.us.itd.umich.edu> References: <435801B4.70703@tds.net> <3EDCACCF192588508BA40292@blue-four.us.itd.umich.edu> Message-ID: <435A2B7E.2070706@tds.net> Lance E Sloan wrote: > --On Thursday, October 20, 2005 4:44 PM -0400 Kent Johnson > wrote: > >> Since 2.3 Python includes a datetime module which has some facility for >> date calculations. I think mxDateTime is more sophisticated but if your >> needs are simple take a look at datetime. > > > I think I would like to use the "datetime" module included with Python, > just so I don't need to worry about an additional piece of code, the > "mxDateTime" module. > > In my code, I set up some mxDateTime RelativeDateTime objects that will > be used later: > > secondLockBeginsDelta = DateTime.RelativeDateTime( day = 14, hour = 23, > minute = 59, months = -4 ) You might want to look at dateutils, it can do this. It is an add-on module but it is pure Python. http://labix.org/python-dateutil >>> from datetime import *; from dateutil.relativedelta import * >>> firstTime = datetime.now() >>> offset = relativedelta(day = 14, hour = 23, minute = 59, months = -4 ) >>> firstTime+offset datetime.datetime(2005, 6, 14, 23, 59, 4, 209000) Kent From kent37 at tds.net Sat Oct 22 15:11:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Oct 2005 09:11:56 -0400 Subject: [Tutor] : Threads? In-Reply-To: <3449428f0510212115v741d03aeradc93f7700434b90@mail.gmail.com> References: <43593496.1000706@gmail.com> <005e01c5d697$41c6f1d0$0a01a8c0@xp> <3449428f0510212115v741d03aeradc93f7700434b90@mail.gmail.com> Message-ID: <435A3A9C.9060103@tds.net> Orri Ganel wrote: > I'll try doing 3 or 4 tracks per thread, then. Thanks for the advice. > > > If you keep the thread count down to two or three you might get > a noticable improvement but one thread per track, unless you have > a lot of separate hard disk spindles to distribute the work will > not help much I suspect. Alan means to use two or three threads *total*. Orri, I took another look at your program and you are not using threads correctly; the way you have it set up you are just doing one conversion at a time. Your main loop is roughly like this: for each track make a thread pool queue a request to convert the track wait for all threads to finish (but there is only one) finish converting the track Since you wait for each thread individually, the processing ends up being sequential. You should put all the processing for a track in convert_thread and structure your code like this: make a thread pool with 2-3 threads for each track queue a request to convert the track wait for all threads to finish finish up - processing that has to be done after all threads complete With this structure, you will always be running 2-3 conversions at a time; when one finishes you will start another until they are all done. You might want to print 'starting' and 'finishing' messages in convert_thread so you can see the overlap. When you get it working, experiment with the number of threads in the pool to see what number gives the best performance. ============================ I wanted to find out whether os.system() calls block other threads. It seems that they don't. (That's a good thing, it means it should work for you!) Here is a program to test this: # ThreadSystem.py import os, threading def makeCommand(n): return '''python -c "import time;print 'hello %s',time.time();time.sleep(2);print 'goodbye %s',time.time()"''' % (n, n) threading.Thread(target=os.system, args=(makeCommand(1),)).start() threading.Thread(target=os.system, args=(makeCommand(2),)).start() On my Win2K machine it consistently prints results like F:\Tutor>python threadsystem.py hello 1 1129985497.16 hello 2 1129985497.17 goodbye 1 1129985499.16 goodbye 2 1129985499.17 so the two threads are both active. Kent From sfhaley at earthlink.net Sat Oct 22 16:18:16 2005 From: sfhaley at earthlink.net (Steve Haley) Date: Sat, 22 Oct 2005 10:18:16 -0400 Subject: [Tutor] A Really Quick Question Message-ID: Folks, I am running Python 2.1 which ships with ArcView 9.1. I am going through the 2.1 tutorial and came across readlines(). Simply put it doesn't seem to be behaving as the tutorial describes. Specifically, I created a small text file as shown below: f=open("c:/python21/sfh_modules/test.txt", "w") f.write("This is the second line\n") f.write("This is the second line\n") f.close() # then closed and reopened in read mode f=open("c:/python21/sfh_modules/test.txt", "r") f.readlines(2) # Here's my problem ['This is the first line\n', 'This is the second line\n'] # please note this output The tutorial seems to be telling me that 'f.readlines(2) should read out 2 bytes plus what is needed to complete the current line. Instead, it is reading out the entire file no matter what I enter as a parameter. I know I am going to feel really dumb when I hear the explanation but please remember I'm new to this. Thanks very much, Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051022/ef337357/attachment.htm From amonroe at columbus.rr.com Sat Oct 22 16:11:30 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 22 Oct 2005 10:11:30 -0400 Subject: [Tutor] : Threads? In-Reply-To: <435A3A9C.9060103@tds.net> References: <43593496.1000706@gmail.com> <005e01c5d697$41c6f1d0$0a01a8c0@xp> <3449428f0510212115v741d03aeradc93f7700434b90@mail.gmail.com> <435A3A9C.9060103@tds.net> Message-ID: <117268939794.20051022101130@columbus.rr.com> > I wanted to find out whether os.system() calls block other threads. > It seems that they don't. (That's a good thing, it means it should > work for you!) Here is a program to test this: For threads that run longer than a few seconds, you can visibly verify this with Sysinterals Process Explorer. Super useful tool. Alan From python-tutor at toddmaynard.com Sat Oct 22 16:54:13 2005 From: python-tutor at toddmaynard.com (Todd Maynard) Date: Sat, 22 Oct 2005 10:54:13 -0400 Subject: [Tutor] A Really Quick Question In-Reply-To: References: Message-ID: <200510221054.13187.python-tutor@toddmaynard.com> Hi Steve, Here is the python documentation. Hopefully it is a *little* clearer.... http://docs.python.org/lib/bltin-file-objects.html *** readlines *** readlines( [sizehint]) Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently. *** read *** read( [size]) Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. *********************** If you want to only read X bytes at a time then read would be more appropriate. Have fun learning, --Todd On Saturday 22 October 2005 10:18, Steve Haley wrote: > Folks, > > > > I am running Python 2.1 which ships with ArcView 9.1. I am going through > the 2.1 tutorial and came across readlines(). Simply put it doesn't seem > to be behaving as the tutorial describes. Specifically, I created a small > text file as shown below: > > > > f=open("c:/python21/sfh_modules/test.txt", "w") > > f.write("This is the second line\n") > > f.write("This is the second line\n") > > f.close() # then closed and reopened in read mode > > f=open("c:/python21/sfh_modules/test.txt", "r") > > f.readlines(2) # Here's my problem > > ['This is the first line\n', 'This is the second line\n'] # please note > this output > > > > The tutorial seems to be telling me that 'f.readlines(2) should read out 2 > bytes plus what is needed to complete the current line. Instead, it is > reading out the entire file no matter what I enter as a parameter. I know > I am going to feel really dumb when I hear the explanation but please > remember I'm new to this. > > > > Thanks very much, > > Steve From kent37 at tds.net Sat Oct 22 17:57:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Oct 2005 11:57:17 -0400 Subject: [Tutor] A Really Quick Question In-Reply-To: References: Message-ID: <435A615D.50805@tds.net> Steve Haley wrote: > I am running Python 2.1 which ships with ArcView 9.1. I am going > through the 2.1 tutorial and came across readlines(). > > The tutorial seems to be telling me that ?f.readlines(2) should read out > 2 bytes plus what is needed to complete the current line. Instead, it > is reading out the entire file no matter what I enter as a parameter. I > know I am going to feel really dumb when I hear the explanation but > please remember I?m new to this. As the documentation says, the parameter to readlines() is a hint which may be rounded up to an internal buffer size. Python 2.4 seems to use a buffer size of 8192 so using sizehint < 8192 may have no effect. If you want to read a single line of the file, use readline() instead. To iterate through all the lines of a file one at a time use for line in f.xreadlines(): # process line HTH. Come back if you have more questions! Kent From singingxduck at gmail.com Sat Oct 22 18:29:14 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sat, 22 Oct 2005 12:29:14 -0400 Subject: [Tutor] : Threads? In-Reply-To: <435A3A9C.9060103@tds.net> References: <43593496.1000706@gmail.com> <005e01c5d697$41c6f1d0$0a01a8c0@xp> <3449428f0510212115v741d03aeradc93f7700434b90@mail.gmail.com> <435A3A9C.9060103@tds.net> Message-ID: <3449428f0510220929h1794512bk38dcd6be7714bc94@mail.gmail.com> I knew what he meant, but since most albums have around 12 tracks, 4 tracks per thread gives you 3 threads. In any case, thanks for the catch on the loop. I'll let you know if it makes a difference. On 10/22/05, Kent Johnson wrote: > > Alan means to use two or three threads *total*. > > Orri, I took another look at your program and you are not using threads > correctly; the way you have it set up you are just doing one conversion at a > time. Your main loop is roughly like this: > > for each track > make a thread pool > queue a request to convert the track > wait for all threads to finish (but there is only one) > finish converting the track > > Since you wait for each thread individually, the processing ends up being > sequential. > > You should put all the processing for a track in convert_thread and > structure your code like this: > > make a thread pool with 2-3 threads > for each track > queue a request to convert the track > wait for all threads to finish > finish up - processing that has to be done after all threads complete > > With this structure, you will always be running 2-3 conversions at a time; > when one finishes you will start another until they are all done. You might > want to print 'starting' and 'finishing' messages in convert_thread so you > can see the overlap. > > When you get it working, experiment with the number of threads in the pool > to see what number gives the best performance. > -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051022/526dbcdf/attachment-0001.html From keridee at jayco.net Sat Oct 22 18:48:19 2005 From: keridee at jayco.net (Jacob S.) Date: Sat, 22 Oct 2005 11:48:19 -0500 Subject: [Tutor] class and methods/functions References: <200510061120.50425.ewalker@micron.com><200510061221.43938.ewalker@micron.com> <43457178.4070807@tds.net> <200510061315.22601.ewalker@micron.com> Message-ID: <00d601c5d728$6ca7d810$be5428cf@JSLAPTOP> >> def nameCheck(self, value): >> > import re >> > tempREG = re.match('.*:.*',value) >> > return str(tempREG) != 'None' >> >> Still a syntax error here! >> > Code is working as I thought it would. What syntax error do I have? This could be written better. def nameCheck(self, value): tempREG = re.match('.*:.*',value) return tempREG != None There's no need to convert to string. None is a type that you can check against directly. Jacob From wescpy at gmail.com Sat Oct 22 23:16:35 2005 From: wescpy at gmail.com (w chun) Date: Sat, 22 Oct 2005 14:16:35 -0700 Subject: [Tutor] class and methods/functions In-Reply-To: <00d601c5d728$6ca7d810$be5428cf@JSLAPTOP> References: <200510061120.50425.ewalker@micron.com> <200510061221.43938.ewalker@micron.com> <43457178.4070807@tds.net> <200510061315.22601.ewalker@micron.com> <00d601c5d728$6ca7d810$be5428cf@JSLAPTOP> Message-ID: <78b3a9580510221416q3fb3dc8ct75a8a635edba32cc@mail.gmail.com> On 10/22/05, Jacob S. wrote: > >> def nameCheck(self, value): > >> > import re > >> > tempREG = re.match('.*:.*',value) > >> > return str(tempREG) != 'None' > > This could be written better. > > def nameCheck(self, value): > tempREG = re.match('.*:.*',value) > return tempREG != None > > There's no need to convert to string. None is a type that you can check > against directly. and even more so, a further refinement takes advantage of a single None value: return tempREG is not None this works faster than "tempREG != None" because this is an object *value* comparison (vs an object *identity* comparison). in value comparisons, the interpreter has to pull out the "value" of both objects and compare them. for identity checks, it just checks the objects themselves. this extra step saves time and improves performance. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From challman at gmail.com Sun Oct 23 00:07:25 2005 From: challman at gmail.com (Chris Hallman) Date: Sat, 22 Oct 2005 18:07:25 -0400 Subject: [Tutor] threading issues Message-ID: <9f68812f0510221507tb9ef4a6gd83adf836e695d01@mail.gmail.com> I hacked together my first script to learn threading. I'm seeing some weird output. This script will PING approximately 1,000 routers. I added a few print commands for debugging so I can see if it runs faster than a single threaded script. It blazes through the routers, however I'm seeing multiple prints (PINGs) for the same device. What is causing this? Also, I can get fc to write to the file. #!/usr/bin/env python #Let us profile code which uses threads import os, re, string, thread, threading, time from time import strftime #from threading import Thread class PingThread(threading.Thread): def run(self): pingaf = os.popen('ping -n 1 -w 3 ' + rtr) pingas = string.join(pingaf.readlines()) if ms.search(pingas): print (re.sub('\n','',rtr)) + " responded." #for debugging else: pingaf = os.popen('ping -n 2 -w 3 ' + rtr) pingas = string.join(pingaf.readlines()) if ms.search(pingas): print (re.sub('\n','',rtr)) + " responded." # for debugging else: fc=fc+1 output.write(re.sub('\n','',rtr) + " did not respond.\n") fc = 0 # failure counter ms = re.compile("Reply from") rpath = (r"c:\temp\py\network_ping_routers.txt") if os.path.exists(r"c:\temp\py\network_ping_again.txt"): rpath = (r"c:\temp\py\network_ping_again.txt") wpath = (r"c:\temp\py\network_ping.out") #os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") + "\n") output = open(wpath, "a") output.write("\n" + "\n" + "Network PING test started -" + strftime(" %H:%M:%S %x") + "\n") output.flush() for rtr in file(rpath): PingThread().start() print fc # for debugging #output.write(fc + " failures found.\n") output.write("\n" + "\n" + "Network PING test completed -" + strftime(" %H:%M:%S %x") + "\n") output.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051022/40c30694/attachment.htm From nagle.p at gmail.com Sun Oct 23 01:13:27 2005 From: nagle.p at gmail.com (Patrick Nagle) Date: Sat, 22 Oct 2005 18:13:27 -0500 Subject: [Tutor] removal Message-ID: please remove me from your tutor mailing list. Cheers -- Patrick J. Nagle _____________ Pocket Rocket FX From adam.jtm30 at gmail.com Sun Oct 23 01:27:33 2005 From: adam.jtm30 at gmail.com (Adam) Date: Sun, 23 Oct 2005 00:27:33 +0100 Subject: [Tutor] removal In-Reply-To: References: Message-ID: Do it yourself On 23/10/05, Patrick Nagle wrote: > > please remove me from your tutor mailing list. > > Cheers > > -- > Patrick J. Nagle > _____________ > Pocket Rocket FX > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051023/83c9c299/attachment.htm From kent37 at tds.net Sun Oct 23 01:30:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Oct 2005 19:30:03 -0400 Subject: [Tutor] threading issues In-Reply-To: <9f68812f0510221507tb9ef4a6gd83adf836e695d01@mail.gmail.com> References: <9f68812f0510221507tb9ef4a6gd83adf836e695d01@mail.gmail.com> Message-ID: <435ACB7B.7080305@tds.net> Chris Hallman wrote: > > I hacked together my first script to learn threading. I'm seeing some > weird output. > > This script will PING approximately 1,000 routers. I added a few print > commands for debugging so I can see if it runs faster than a single > threaded script. It blazes through the routers, however I'm seeing > multiple prints (PINGs) for the same device. What is causing this? PingThread.run() uses a global variable - rtr - to determine the router to ping. But PingThread.run() runs *asynchronously* to the main loop. It's unlikely that one thread will run for each different value that rtr takes on. It's possible, for example, that the main loop could complete before any of the PingThreads gets a chance to run, and each thread would ping the same router. The solution is to pass the router value to each thread in a constructor: class PingThread(threading.Thread): def __init__(self, rtr): threading.Thread.__init__(self) self.rtr = rtr When you create a thread pass it the rtr: PingThread(rtr).start() then in PingThread.run() you should use self.rtr instead of the global rtr. > Also, I can get fc to write to the file. Do you mean you are getting the wrong value of fc written to the file? This is likely - your main thread will probably complete, and write fc to output, before all of the pings complete. I would guess that the main thread completes before *any* of the pings complete, since running ping takes a second or two. Fixing this is a little harder. You have to wait for each thread to complete before writing the results. One way to do this would be to keep track of the threads and join them all like this: threads = [] for rtr in file(rpath): thread = PingThread() thread.start() threads.append(thread) # now wait until all threads are done for thread in threads: thread.join() # now you can write fc and it will be correct. Kent > > > > #!/usr/bin/env python > > #Let us profile code which uses threads > import os, re, string, thread, threading, time > from time import strftime > #from threading import Thread > > class PingThread(threading.Thread): > def run(self): > pingaf = os.popen('ping -n 1 -w 3 ' + rtr) > pingas = string.join(pingaf.readlines()) > if ms.search(pingas): > print (re.sub('\n','',rtr)) + " responded." #for debugging > else: > pingaf = os.popen('ping -n 2 -w 3 ' + rtr) > pingas = string.join(pingaf.readlines()) > if ms.search(pingas): > print (re.sub('\n','',rtr)) + " responded." # for > debugging > else: > fc=fc+1 > output.write(re.sub('\n','',rtr) + " did not respond.\n") > > fc = 0 # failure counter > ms = re.compile("Reply from") > rpath = (r"c:\temp\py\network_ping_routers.txt") > if os.path.exists(r"c:\temp\py\network_ping_again.txt"): > rpath = (r"c:\temp\py\network_ping_again.txt") > wpath = (r"c:\temp\py\network_ping.out") > #os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue > held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") + "\n") > output = open(wpath, "a") > output.write("\n" + "\n" + "Network PING test started -" + strftime(" > %H:%M:%S %x") + "\n") > output.flush() > > for rtr in file(rpath): > PingThread().start() > print fc # for debugging > #output.write(fc + " failures found.\n") > output.write("\n" + "\n" + "Network PING test completed -" + strftime(" > %H:%M:%S %x") + "\n") > output.close() > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From daniel at thewatkins.org.uk Sun Oct 23 01:41:51 2005 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Sun, 23 Oct 2005 00:41:51 +0100 Subject: [Tutor] Storing Dictionaries Externally Message-ID: <1130024512.21766.6.camel@amdbert.oxbridgetechnology.local> Currently, I'm writing a little project which needs to store a dictionary in an external file (so it can be accessed by another program). However, no matter how much I try, I cannot get Python to import the dictionary from the file properly. However, I know the problem. Whatever format I put the data in within the file (either as a dictionary or a list of tuples to 'dict()') Python reads it as a string, rather than a dictionary or list of tuples. My question is essentially this: How do I convert a string into a dictionary or list of tuples, assuming it's syntax is correct (ie. it is actually how a dictionary or list of tuples would look if I were defining it). Thanks in advance, Dan From kent37 at tds.net Sun Oct 23 03:18:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Oct 2005 21:18:04 -0400 Subject: [Tutor] Storing Dictionaries Externally In-Reply-To: <1130024512.21766.6.camel@amdbert.oxbridgetechnology.local> References: <1130024512.21766.6.camel@amdbert.oxbridgetechnology.local> Message-ID: <435AE4CC.4080901@tds.net> Daniel Watkins wrote: > Currently, I'm writing a little project which needs to store a > dictionary in an external file (so it can be accessed by another > program). However, no matter how much I try, I cannot get Python to > import the dictionary from the file properly. However, I know the > problem. Whatever format I put the data in within the file (either as a > dictionary or a list of tuples to 'dict()') Python reads it as a string, > rather than a dictionary or list of tuples. If you are trying to share a dict between two Python programs, the simplest way is to use the pickle module. To write a dict to a pickle is as simple as >>> import pickle >>> data = {'a':1, 'b':2} >>> f=open('data.txt', 'wb') >>> pickle.dump(data, f) >>> f.close() The output is not particularly human-readable; in this case data.txt contains (dp0 S'a' p1 I1 sS'b' p2 I2 s. but that doesn't really matter; to read it back, use pickle again: >>> f=open('data.txt', 'rb') >>> newData = pickle.load(f) >>> newData {'a': 1, 'b': 2} >>> f.close() Kent From samrobertsmith at gmail.com Sun Oct 23 05:08:39 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 22 Oct 2005 20:08:39 -0700 Subject: [Tutor] index and find Message-ID: <1d987df30510222008k2f878332vdd7531e77ce97255@mail.gmail.com> what is the difference between index and find in the module of string? for both "find" and "index", I got the position of the letter. From remailer at ka3nam.com Sun Oct 23 05:14:40 2005 From: remailer at ka3nam.com (Joe Bennett) Date: Sat, 22 Oct 2005 22:14:40 -0500 Subject: [Tutor] Boolean math question Message-ID: <435B0020.3050401@ka3nam.com> Anyone know of a good explanation of either how to perform boolean math in Python? What I am trying to do is AND two numbers together: e = 51 AND 15 00110011 00001111 ------------ 00000011 In this case the result should be e = 3... Ideas? -Joe From carroll at tjc.com Sun Oct 23 05:17:46 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat, 22 Oct 2005 20:17:46 -0700 (PDT) Subject: [Tutor] index and find In-Reply-To: <1d987df30510222008k2f878332vdd7531e77ce97255@mail.gmail.com> Message-ID: On Sat, 22 Oct 2005, Shi Mu wrote: > what is the difference between index and find in the module of string? > for both "find" and "index", I got the position of the letter. index raises a ValueError if the string isn't found: >>> s = "spam" >>> s.find('m') 3 >>> s.index('m') 3 >>> s.find('z') -1 >>> s.index('z') Traceback (most recent call last): File "", line 1, in ? ValueError: substring not found From carroll at tjc.com Sun Oct 23 05:19:25 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat, 22 Oct 2005 20:19:25 -0700 (PDT) Subject: [Tutor] Boolean math question In-Reply-To: <435B0020.3050401@ka3nam.com> Message-ID: On Sat, 22 Oct 2005, Joe Bennett wrote: > Anyone know of a good explanation of either how to perform boolean math > in Python? What I am trying to do is AND two numbers together: > > e = 51 AND 15 > > 00110011 > 00001111 > ------------ > 00000011 Use '&' rather than "AND": >>> e = 51 & 15 >>> e 3 From dyoo at hkn.eecs.berkeley.edu Sun Oct 23 05:25:40 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 22 Oct 2005 20:25:40 -0700 (PDT) Subject: [Tutor] Boolean math question In-Reply-To: Message-ID: > > Anyone know of a good explanation of either how to perform boolean > > math in Python? What I am trying to do is AND two numbers together: > > > > e = 51 AND 15 > > > > 00110011 > > 00001111 > > ------------ > > 00000011 > > Use '&' rather than "AND": > > >>> e = 51 & 15 > >>> e > 3 For reference, the bitwise boolean operators can be found here: http://www.python.org/doc/ref/bitwise.html http://www.python.org/doc/ref/shifting.html http://www.python.org/doc/ref/unary.html From nephish at xit.net Sun Oct 23 05:32:01 2005 From: nephish at xit.net (nephish) Date: Sat, 22 Oct 2005 22:32:01 -0500 Subject: [Tutor] advice on how to start with urllib Message-ID: <1130038321.3593.2.camel@bitsbam.localdomain> hey there gents, i am looking for a good place to start learning how to read a web page with python and pull out bits of information for an app i am doing for work. i have googled and looked at the docs. i looked at urllib and httplib so i think this a place to kinda start. Does anyone know of a good site with some examples or tutorials for this kind of thing ? thanks From kent37 at tds.net Sun Oct 23 13:22:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Oct 2005 07:22:37 -0400 Subject: [Tutor] index and find In-Reply-To: <1d987df30510222008k2f878332vdd7531e77ce97255@mail.gmail.com> References: <1d987df30510222008k2f878332vdd7531e77ce97255@mail.gmail.com> Message-ID: <435B727D.4070502@tds.net> Shi Mu wrote: > what is the difference between index and find in the module of string? > for both "find" and "index", I got the position of the letter. Chapter 2 of the Library Reference is a wealth of information about built-in types: http://docs.python.org/lib/builtin.html In particular this page http://docs.python.org/lib/string-methods.html which says find( sub[, start[, end]]) Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end). Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. index( sub[, start[, end]]) Like find(), but raise ValueError when the substring is not found. Kent From kent37 at tds.net Sun Oct 23 13:47:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Oct 2005 07:47:33 -0400 Subject: [Tutor] advice on how to start with urllib In-Reply-To: <1130038321.3593.2.camel@bitsbam.localdomain> References: <1130038321.3593.2.camel@bitsbam.localdomain> Message-ID: <435B7855.4020106@tds.net> nephish wrote: > hey there gents, > i am looking for a good place to start learning how to read a web page > with python and pull out bits of information for an app i am doing for > work. i have googled and looked at the docs. i looked at urllib and > httplib so i think this a place to kinda start. Does anyone know of a > good site with some examples or tutorials for this kind of thing ? Using urllib to fetch a web page can be as simple as >>> import urllib >>> data = urllib.urlopen('http://www.google.com').read() >>> data[:100] 'Google</t' To parse the HTML and get the data you want from it try Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup(data) >>> soup('title') [<title>Google] >>> for a in soup('a'): ... print a.get('href'), a.string ... /imghp?hl=en&tab=wi&ie=UTF-8 Images http://groups.google.com/grphp?hl=en&tab=wg&ie=UTF-8 Groups http://news.google.com/nwshp?hl=en&tab=wn&ie=UTF-8 News http://froogle.google.com/frghp?hl=en&tab=wf&ie=UTF-8 Froogle /lochp?hl=en&tab=wl&ie=UTF-8 Null None Null /intl/en/options/ more » /advanced_search?hl=en Advanced Search /preferences?hl=en Preferences /language_tools?hl=en Language Tools /ads/ Advertising Programs /services Business Solutions /intl/en/about.html About Google Kent From chris.arndt at web.de Sun Oct 23 14:46:54 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Sun, 23 Oct 2005 13:46:54 +0100 Subject: [Tutor] advice on how to start with urllib In-Reply-To: <1130038321.3593.2.camel@bitsbam.localdomain> References: <1130038321.3593.2.camel@bitsbam.localdomain> Message-ID: <435B863E.2050609@web.de> nephish schrieb: > hey there gents, > i am looking for a good place to start learning how to read a web page > with python and pull out bits of information for an app i am doing for > work. i have googled and looked at the docs. i looked at urllib and > httplib so i think this a place to kinda start. Does anyone know of a > good site with some examples or tutorials for this kind of thing ? The online book "Diving into Python" by Mark Pilgrim has an excellent chapter on how to download webpages and process them: http://diveintopython.org/http_web_services/index.html HTH, Chris From nephish at xit.net Sun Oct 23 15:34:34 2005 From: nephish at xit.net (nephish) Date: Sun, 23 Oct 2005 08:34:34 -0500 Subject: [Tutor] advice on how to start with urllib In-Reply-To: <435B863E.2050609@web.de> References: <1130038321.3593.2.camel@bitsbam.localdomain> <435B863E.2050609@web.de> Message-ID: <1130074474.4322.0.camel@bitsbam.localdomain> Thanks a lot, this stuff is pretty easy. i got a couple of things working here. thanks for your help sk On Sun, 2005-10-23 at 13:46 +0100, Christopher Arndt wrote: > nephish schrieb: > > hey there gents, > > i am looking for a good place to start learning how to read a web page > > with python and pull out bits of information for an app i am doing for > > work. i have googled and looked at the docs. i looked at urllib and > > httplib so i think this a place to kinda start. Does anyone know of a > > good site with some examples or tutorials for this kind of thing ? > > The online book "Diving into Python" by Mark Pilgrim has an excellent chapter > on how to download webpages and process them: > > http://diveintopython.org/http_web_services/index.html > > HTH, Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From sweetdaddysiki at hotmail.com Sun Oct 23 17:04:54 2005 From: sweetdaddysiki at hotmail.com (Trent Rigsbee) Date: Sun, 23 Oct 2005 15:04:54 +0000 Subject: [Tutor] Creating Programs (Basics?) Message-ID: Hi! I'm on Gauld's wonderful "Learning to Program" tutor. I've got to the end of the chapter on "Error Handling" and I'm trying the sample ideas for creating my own programs. My problem is getting started! Is there a "step by step" method for creating programs or some basic guidelines for this? Also, how are computer science students taught this? Thanks! From hamalnamal at gmail.com Sun Oct 23 19:53:51 2005 From: hamalnamal at gmail.com (Jason) Date: Sun, 23 Oct 2005 13:53:51 -0400 Subject: [Tutor] global and local vaiables Message-ID: i know that when you define a variable in a function it is defined as a local variable. and that when you type return variable it will set the value of that variable to a global variable and that it will then exit the function but say i wanted to define variable x as a global variable and then do something else in the function how would i do that? to be a bit more specific i have this function: 1. def sign_in(number,account,password): 2. if number.has_key(account) and number[account]==password: 3. account = account+".txt" 4. load_numbers(numbers,account) 5. display_menu() 6. return account 7. else: 8. print "Either the account name or password was wrong,\nplease remember that the account names are CASE SESITIVE" 9. print 10. welcome() and i need to return account as a global variable before display_menu() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051023/1bb9e46a/attachment.html From sfhaley at earthlink.net Sun Oct 23 23:25:21 2005 From: sfhaley at earthlink.net (Steve Haley) Date: Sun, 23 Oct 2005 17:25:21 -0400 Subject: [Tutor] Thanks for the Help on the Quick Question Message-ID: Kent and Todd, Thanks for the help on my quick question regarding readlines. That helped a lot. - Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051023/903cd74f/attachment.htm From challman at gmail.com Mon Oct 24 00:06:50 2005 From: challman at gmail.com (Chris Hallman) Date: Sun, 23 Oct 2005 18:06:50 -0400 Subject: [Tutor] threading issues In-Reply-To: <435ACB7B.7080305@tds.net> References: <9f68812f0510221507tb9ef4a6gd83adf836e695d01@mail.gmail.com> <435ACB7B.7080305@tds.net> Message-ID: <9f68812f0510231506w1e1b8955q5d9cabf8454de8a9@mail.gmail.com> I made a mistake in my first email..... I meant that I can't get fc to write to the file. Here is the error: Traceback (most recent call last): File "thread_test_ping.py", line 37, in ? output.write(fc + " failures found.\n") TypeError: unsupported operand type(s) for +: 'int' and 'str' I tried the suggestions you made, but I can't get it to work. Is this what you meant?: #!/usr/bin/env python #Let us profile code which uses threads import os, re, string, thread, threading, time from time import strftime #from threading import Thread class PingThread(threading.Thread): def __init__(self, rtr): threading.Thread.__init__(self) self.rtr = rtr PingThread(rtr).start(rtr) def run(self): pingaf = os.popen('ping -n 1 -w 3 ' + rtr) pingas = string.join(pingaf.readlines()) if ms.search(pingas): print (re.sub('\n','',rtr)) + " responded." #for debugging else: pingaf = os.popen('ping -n 2 -w 3 ' + rtr) pingas = string.join(pingaf.readlines()) if ms.search(pingas): print (re.sub('\n','',rtr)) + " responded." # for debugging else: fc=fc+1 output.write(re.sub('\n','',rtr) + " did not respond.\n") fc = 0 # failure counter ms = re.compile("Reply from") rpath = (r"c:\temp\py\network_ping_routers.txt") if os.path.exists(r"c:\temp\py\network_ping_again.txt"): rpath = (r"c:\temp\py\network_ping_again.txt") wpath = (r"c:\temp\py\network_ping.out") #os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") + "\n") output = open(wpath, "a") output.write("\n" + "\n" + "Network PING test started -" + strftime(" %H:%M:%S %x") + "\n") output.flush() threads = [] for rtr in file(rpath): thread = PingThread() thread.start() threads.append(thread) for thread in threads: thread.join() print fc # for debugging output.write(fc + " failures found.\n") output.write("\n" + "\n" + "Network PING test completed -" + strftime(" %H:%M:%S %x") + "\n") output.close() On 10/22/05, Kent Johnson wrote: > > Chris Hallman wrote: > > > > I hacked together my first script to learn threading. I'm seeing some > > weird output. > > > > This script will PING approximately 1,000 routers. I added a few print > > commands for debugging so I can see if it runs faster than a single > > threaded script. It blazes through the routers, however I'm seeing > > multiple prints (PINGs) for the same device. What is causing this? > > PingThread.run() uses a global variable - rtr - to determine the router to > ping. But PingThread.run() runs *asynchronously* to the main loop. It's > unlikely that one thread will run for each different value that rtr takes > on. It's possible, for example, that the main loop could complete before any > of the PingThreads gets a chance to run, and each thread would ping the same > router. > > The solution is to pass the router value to each thread in a constructor: > class PingThread(threading.Thread): > def __init__(self, rtr): > threading.Thread.__init__(self) > self.rtr = rtr > > When you create a thread pass it the rtr: > PingThread(rtr).start() > then in PingThread.run() you should use self.rtr instead of the global > rtr. > > > Also, I can get fc to write to the file. > > Do you mean you are getting the wrong value of fc written to the file? > This is likely - your main thread will probably complete, and write fc to > output, before all of the pings complete. I would guess that the main thread > completes before *any* of the pings complete, since running ping takes a > second or two. > > Fixing this is a little harder. You have to wait for each thread to > complete before writing the results. One way to do this would be to keep > track of the threads and join them all like this: > threads = [] > for rtr in file(rpath): > thread = PingThread() > thread.start() > threads.append(thread) > > # now wait until all threads are done > for thread in threads: > thread.join () > > # now you can write fc and it will be correct. > > Kent > > > > > > > > > #!/usr/bin/env python > > > > #Let us profile code which uses threads > > import os, re, string, thread, threading, time > > from time import strftime > > #from threading import Thread > > > > class PingThread(threading.Thread): > > def run(self): > > pingaf = os.popen('ping -n 1 -w 3 ' + rtr) > > pingas = string.join(pingaf.readlines()) > > if ms.search(pingas): > > print (re.sub('\n','',rtr)) + " responded." #for debugging > > else: > > pingaf = os.popen('ping -n 2 -w 3 ' + rtr) > > pingas = string.join(pingaf.readlines()) > > if ms.search(pingas): > > print (re.sub('\n','',rtr)) + " responded." # for > > debugging > > else: > > fc=fc+1 > > output.write(re.sub('\n','',rtr) + " did not respond.\n") > > > > fc = 0 # failure counter > > ms = re.compile("Reply from") > > rpath = (r"c:\temp\py\network_ping_routers.txt") > > if os.path.exists(r"c:\temp\py\network_ping_again.txt"): > > rpath = (r"c:\temp\py\network_ping_again.txt") > > wpath = (r"c:\temp\py\network_ping.out") > > #os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue > > held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") + > "\n") > > output = open(wpath, "a") > > output.write("\n" + "\n" + "Network PING test started -" + strftime(" > > %H:%M:%S %x") + "\n") > > output.flush() > > > > for rtr in file(rpath): > > PingThread().start() > > print fc # for debugging > > #output.write(fc + " failures found.\n") > > output.write("\n" + "\n" + "Network PING test completed -" + strftime(" > > %H:%M:%S %x") + "\n") > > output.close() > > > > > > ------------------------------------------------------------------------ > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051023/28d67ce1/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Oct 24 00:31:01 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 23 Oct 2005 15:31:01 -0700 (PDT) Subject: [Tutor] threading issues In-Reply-To: <9f68812f0510231506w1e1b8955q5d9cabf8454de8a9@mail.gmail.com> Message-ID: On Sun, 23 Oct 2005, Chris Hallman wrote: > I made a mistake in my first email..... I meant that I can't get fc to write > to the file. Here is the error: > > Traceback (most recent call last): > File "thread_test_ping.py", line 37, in ? > output.write(fc + " failures found.\n") > TypeError: unsupported operand type(s) for +: 'int' and 'str' Hi Chris, Python's string concatenation operation requires the left hand side and the right hand side to be strings. The problem above says that: fc isn't a string --- it's a number --- so it can't be directly concatenated to the string: " failures found.\n". The documentation in: http://www.python.org/doc/lib/typesseq-strings.html should help; take a look at that page, and you should be able to figure out how to format that number into the string. Alternatively, you can also use the str() function to turn things into strings to avoid the type error. If you're still getting stuck, send another email to the list, and we'll be happy to elaborate. Best of wishes! From kent37 at tds.net Mon Oct 24 00:55:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Oct 2005 18:55:54 -0400 Subject: [Tutor] threading issues In-Reply-To: <9f68812f0510231506w1e1b8955q5d9cabf8454de8a9@mail.gmail.com> References: <9f68812f0510221507tb9ef4a6gd83adf836e695d01@mail.gmail.com> <435ACB7B.7080305@tds.net> <9f68812f0510231506w1e1b8955q5d9cabf8454de8a9@mail.gmail.com> Message-ID: <435C14FA.6090006@tds.net> Chris Hallman wrote: > > I made a mistake in my first email..... I meant that I can't get fc to > write to the file. Here is the error: > > Traceback (most recent call last): > File "thread_test_ping.py", line 37, in ? > output.write(fc + " failures found.\n") > TypeError: unsupported operand type(s) for +: 'int' and 'str' This is a pretty easy error to understand. It is saying that you can't add an int and a string. Looking at your code, you are trying to add fc + " failures found.\n". fc is indeed an int. You have to change it to a string to be able to add it to another string. You can do this with the str() function. So the correct statement is output.write(str(fc) + " failures found.\n") > > I tried the suggestions you made, but I can't get it to work. Is this > what you meant?: No, not quite. > > #!/usr/bin/env python > > #Let us profile code which uses threads > import os, re, string, thread, threading, time > from time import strftime > #from threading import Thread > > class PingThread(threading.Thread): > def __init__(self, rtr): > threading.Thread.__init__(self) > self.rtr = rtr The init method initializes a PingThread. It is passed self as an argument, plus whatever parameters you pass in when you create the PingThread. You call the superclass constructor and save the value of the parameter. So far so good...but this next line is creating a PingThread, it belongs below in your loop. > PingThread(rtr).start(rtr) > > def run(self): Here you should reference self.rtr so you get the value that was stored in the call to __init__(), and similarly for each reference to rtr in the run method. > pingaf = os.popen('ping -n 1 -w 3 ' + rtr) > pingas = string.join(pingaf.readlines()) > if ms.search(pingas): > print (re.sub('\n','',rtr)) + " responded." #for debugging > else: > pingaf = os.popen('ping -n 2 -w 3 ' + rtr) > pingas = string.join(pingaf.readlines()) > if ms.search(pingas): > print (re.sub('\n','',rtr)) + " responded." # for > debugging > else: > fc=fc+1 > output.write(re.sub('\n','',rtr) + " did not respond.\n") > > fc = 0 # failure counter > ms = re.compile("Reply from") > rpath = (r"c:\temp\py\network_ping_routers.txt") > if os.path.exists(r"c:\temp\py\network_ping_again.txt"): > rpath = (r"c:\temp\py\network_ping_again.txt") > wpath = (r"c:\temp\py\network_ping.out") > #os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue > held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") + "\n") > output = open(wpath, "a") > output.write("\n" + "\n" + "Network PING test started -" + strftime(" > %H:%M:%S %x") + "\n") > output.flush() > threads = [] > for rtr in file(rpath): > thread = PingThread() Here is where you need to call PingThread(rtr) to pass the value of rtr to the constructor. > thread.start() > threads.append(thread) > for thread in threads: > thread.join() > print fc # for debugging > output.write(fc + " failures found.\n") > output.write("\n" + "\n" + "Network PING test completed -" + strftime(" > %H:%M:%S %x") + "\n") > output.close() I suspect that I am talking over your head and that maybe you are in over your head a bit here. If you don't understand the basics of classes and parameter passing you should spend some time with a tutorial that explains them, for example Alan Gauld's tutorial at http://www.freenetpages.co.uk/hp/alan.gauld/ There is a brief introduction to threading here. It even uses your problem (pinging multiple servers) as the example. http://www.wellho.net/solutions/python-python-threads-a-first-example.html Kent http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Mon Oct 24 01:24:31 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 00:24:31 +0100 Subject: [Tutor] Creating Programs (Basics?) References: Message-ID: <00f301c5d828$ec1619d0$0a01a8c0@xp> > Hi! I'm on Gauld's wonderful "Learning to Program" tutor. Aw shucks! :-) > end of the chapter on "Error Handling" and I'm trying the sample ideas for > creating my own programs. My problem is getting started! Is there a "step > by step" method for creating programs or some basic guidelines for this? A very good question. > how are computer science students taught this? Thanks! Badly in the main... Basically they get lots of projects and by the end of 3 years have kind of stumbled on a way to do it. There are some books around on how to design programs which is really what you need, but the first step is to analyse what you want to do and either 1) Use OOP: break it into objects (if that feels natural to you) and decide what part of the problems solution each object is responsible for. Then code each object in turn(starting at the lowest level) building methods for each responsibility, testing as you go at the >>> prompt [ A quote from my old OOP mentor: Objects have responsibilities, methods implement responsibilities, attributes support methods, messages invoke methods] OR 2) Use functional decomposition decide on the top level functionality and break that into sub functions. Keep breaking the functions into smaller pieces until you find one that you think you know how to write in Python. Write it. Now try writing the one above that or some of the other sub functions at the same level. Gradually fill in the gaps till you get back to the top of the tree. Either way: Use the >>> prompt extensively to experiment. Test extensively Try to keep very clear in your mind what it is you are trying to do. Do the simplest thing first (usually not involving a GUI!) Evolve gradually Test extensively HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Oct 24 01:25:50 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 00:25:50 +0100 Subject: [Tutor] global and local vaiables References: Message-ID: <00f901c5d829$1b459190$0a01a8c0@xp> > ..but say i wanted to define variable x as a global variable and then do > something else in the function how would i do that? Try reading the namespaces topic in my tutor, it should give you the answers. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Mon Oct 24 02:26:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 23 Oct 2005 17:26:56 -0700 (PDT) Subject: [Tutor] Creating Programs (Basics?) In-Reply-To: <00f301c5d828$ec1619d0$0a01a8c0@xp> Message-ID: > > end of the chapter on "Error Handling" and I'm trying the sample ideas > > for creating my own programs. My problem is getting started! Is there > > a "step by step" method for creating programs or some basic guidelines > > for this? > > There are some books around on how to design programs which is really > what you need, In fact, there's a book with that exact title. *grin* http://www.htdp.org/ That book's implementation language is a subset of Scheme, but the material there is solid. The things they talk about are really about programming in general, so the book's ideas apply to Python programming too. For example, their initial "design recipe" is very applicable for small programs: http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-5.html#node_sec_2.5 and throughout the rest of the book, they revise this pattern to follow what Alan's described as "functional decomposition". From kent37 at tds.net Mon Oct 24 03:19:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Oct 2005 21:19:51 -0400 Subject: [Tutor] global and local vaiables In-Reply-To: References: Message-ID: <435C36B7.80602@tds.net> Jason wrote: > i know that when you define a variable in a function it is defined as > a local variable. > and that when you type return variable it will set the value of that > variable to a global variable and that it will then exit the function No, the return statement doesn't set a global variable, it sets the value that is returned from the function. The caller may assign this to a global variable or some other type of variable or ignore it. For example: >>> def foo(): ... x=3 ... return x ... foo returns the value 3 but it isn't bound to any name: >>> foo() 3 >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined We can give any name we want to the returned value: >>> y=foo() >>> y 3 Still no global x: >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined We can call foo() from another function and use the return value there: >>> def bar(): ... z=foo() ... print z ... >>> bar() 3 No global x or z - they are local to the functions that use them: >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> y 3 >>> z Traceback (most recent call last): File "", line 1, in ? NameError: name 'z' is not defined > but say i wanted to define variable x as a global variable and then do > something else in the function > how would i do that? Use the global statement if you must...usually it's better to find a solution that doesn't require global variables. > > to be a bit more specific i have this function: > > 1. |def sign_in(number,account,password):| > 2. if number.has_key(account) and number[account]==password: > 3. account = account+".txt" > 4. load_numbers(numbers,account) > 5. display_menu() > 6. return account > 7. else: > 8. print "Either the account name or password was wrong,\nplease remember that the account names are CASE SESITIVE" > > 9. print > 10. welcome() > > and i need to return account as a global variable before display_menu() Why? If display_menu() is using account, why not just pass it as an argument to account? In this specific case, you are already passing account as a parameter to sign_in(). If you make account a global variable as well you will get a syntax error. Can you say a little more about what you are trying to do with the global variable? Kent -- http://www.kentsjohnson.com From samrobertsmith at gmail.com Mon Oct 24 09:06:16 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 24 Oct 2005 00:06:16 -0700 Subject: [Tutor] what does %25f mean? Message-ID: <1d987df30510240006i3d9c1cf1w4594f8c744c83429@mail.gmail.com> what does %25f mean? From samrobertsmith at gmail.com Mon Oct 24 09:13:58 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 24 Oct 2005 00:13:58 -0700 Subject: [Tutor] dictionary Message-ID: <1d987df30510240013u2d7880easb8a7081586f2fd33@mail.gmail.com> I typed: landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]} and when i checked landUse, I found it become: {'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2} why the order is changed? From ajikoe at gmail.com Mon Oct 24 09:16:05 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 24 Oct 2005 09:16:05 +0200 Subject: [Tutor] what does %25f mean? In-Reply-To: <1d987df30510240006i3d9c1cf1w4594f8c744c83429@mail.gmail.com> References: <1d987df30510240006i3d9c1cf1w4594f8c744c83429@mail.gmail.com> Message-ID: it will reserve the 25 space for your number. example: print '%25.2f' % (1.222,) It will use 25 space and 2 digit of your 1.222 result is: 1.22 cheers, pujo On 10/24/05, Shi Mu wrote: > > what does %25f mean? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/25cf02d1/attachment-0001.htm From ajikoe at gmail.com Mon Oct 24 09:18:50 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 24 Oct 2005 09:18:50 +0200 Subject: [Tutor] dictionary In-Reply-To: <1d987df30510240013u2d7880easb8a7081586f2fd33@mail.gmail.com> References: <1d987df30510240013u2d7880easb8a7081586f2fd33@mail.gmail.com> Message-ID: you work with dictionary. In dictionary you work with the key to get your value. You don't care about how python arrange the key. your key here are: 'res', 'com', 'ind', and 'other' when you want to get your value you just type: landUse['res'] this you will get 1 landUse['ind'] this you will get 3 cheers, pujo On 10/24/05, Shi Mu wrote: > > I typed: > landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]} > and when i checked landUse, I found it become: > {'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2} > why the order is changed? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/c87a9ba4/attachment.html From lists at mostrom.pp.se Mon Oct 24 09:24:42 2005 From: lists at mostrom.pp.se (Jan Erik =?UTF-8?Q?Mostr=C3=B6m?=) Date: Mon, 24 Oct 2005 09:24:42 +0200 Subject: [Tutor] dictionary In-Reply-To: <1d987df30510240013u2d7880easb8a7081586f2fd33@mail.gmail.com> Message-ID: Shi Mu 2005-10-24 09:13: > why the order is changed? By definition a dictionary has no order. jem -- Jan Erik Mostr?m, www.mostrom.pp.se From shaleh at speakeasy.net Mon Oct 24 09:26:42 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Mon, 24 Oct 2005 00:26:42 -0700 Subject: [Tutor] dictionary In-Reply-To: <1d987df30510240013u2d7880easb8a7081586f2fd33@mail.gmail.com> References: <1d987df30510240013u2d7880easb8a7081586f2fd33@mail.gmail.com> Message-ID: <435C8CB2.2050306@speakeasy.net> Shi Mu wrote: > I typed: > landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]} > and when i checked landUse, I found it become: > {'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2} > why the order is changed? the docs warn you about this. A dictionary stores its values based on the keys. Internally Python sorts the keys to make the lookup meet performance expectations. You can not expect a dictionary to return keys in the other you added them. If you want that, store the items as tuples in a list. landUse = [('res', 1), ('com', 2), ('ind', 3), ("other", [4,5,6,7])] From ldapguru at yahoo.com Mon Oct 24 10:06:00 2005 From: ldapguru at yahoo.com (Alan) Date: Mon, 24 Oct 2005 03:06:00 -0500 Subject: [Tutor] Modify to Print All Results After Sort In-Reply-To: Message-ID: <008b01c5d871$c7271ae0$2b01a8c0@server01> Dear Python's Gurus I have this nice over-my-head scripts 1. It loads two files (daifmaster.txt and sahihmaster.txt) HELP ONE Please I NEED to print these unified two sorted files as one = call it dsmaster.txt 2. It load file (Kanzmaster.txt) and sort it HELP TWO Please I need to print this sorted kanzmaster.txt and call it KSmaster.txt 3. Please Explain to me the lines def addCommand(self,command,callback,flags): self.callbacks[command]={'callback':callback,'command':command,'flags':f lags} def findCallback(self,command): #!/usr/bin/python # -*- coding: UTF-8 -*- import sys import codecs import re TYPE_MULTILINE=0x1 class ReaderBase: def __init__(self): self.callbacks={} def addCommand(self,command,callback,flags): self.callbacks[command]={'callback':callback,'command':command,'flags':f lags} def findCallback(self,command): try: return self.callbacks[command[0]] except KeyError: return None def processFile(self,path): #f=open(path, 'r') f = codecs.open(path, encoding='CP1256', mode='r') val='' citem=None for line in f.readlines(): parts=line.split('|') if citem!=None: if citem['flags']&TYPE_MULTILINE: val+=parts[0] for part in parts[1:]: if citem!=None: citem['callback'](citem['command'],val.strip()) lineparts=part.split(' ',1) cmd=lineparts[0] if(len(lineparts)>1): val=lineparts[1] else: val='' if len(cmd)>0: citem=self.findCallback(cmd) else: citem=None if citem!=None: citem['callback'](citem['command'],val.strip()) f.close() entryCount=0 class HadithEntry: def __init__(self): self.keys=[] self.values=[] def addValue(self,key,val): for i in range(len(self.keys)): if self.keys[i]==key: self.values[i]=val return self.keys.append(key) self.values.append(val) def write(self,f=sys.stdout): global entryCount entryCount=entryCount+1 for i in range(len(self.keys)): if not self.keys[i].endswith('-tmp'): f.write(('|'+self.keys[i]+str(entryCount)+' '+self.values[i]+'\n').encode('utf-8')) def getValue(self,key): for i in range(len(self.keys)): if self.keys[i]==key: return self.values[i] return '' hadithItems=[] sortByH_regex_punct = re.compile(u"[ ,??.:\\\\(\\\\)?{}\n.]") def sortByH(a,b): a=a.getValue('H-tmp') b=b.getValue('H-tmp') #remove punctuation before comparison #a=re.sub(sortByH_regex_punct,'',a) #b=re.sub(sortByH_regex_punct,'',b) if(a==b): return 0 if(a>b): return 1 return -1 currentEntry=None #reads the 40k hadith entries def fill1stHadithEntries(cmd,val): global hadithItems global currentEntry #the last tag in a record is H if cmd=='H': currentEntry=HadithEntry() hadithItems.append(currentEntry) a=val a=re.sub(sortByH_regex_punct,'',a) currentEntry.addValue('H-tmp',a) if currentEntry!=None: currentEntry.addValue(cmd,val) hadith2Items=[] #reads the 15K files format def fill2stHadithEntries(cmd,val): global hadith2Items global currentEntry if cmd=='R': currentEntry=HadithEntry() if currentEntry!=None: currentEntry.addValue(cmd,val) #The last tag in a record if F if cmd=='F': a=currentEntry.getValue('H') a=re.sub(sortByH_regex_punct,'',a) currentEntry.addValue('H-tmp',a) hadith2Items.append(currentEntry) tempEntry=None tempEntryPos=0 successMerges=0 #both lists must be sorted, otherwise it will fail. def mergeHadithEntries(val): global hadithItems global tempEntry global tempEntryPos global successMerges while tempEntryPos0: tempEntryPos=tempEntryPos+1 if tempEntryPos>=len(hadithItems): return if sortByH(val,hadithItems[tempEntryPos])==0: hadithItems[tempEntryPos].addValue('R',val.getValue('R')) #print 'found entry' successMerges=successMerges+1 return #print 'entry not found', val.getValue('H') reader=ReaderBase() reader.addCommand('H',fill1stHadithEntries,TYPE_MULTILINE) reader.addCommand('R',fill1stHadithEntries,0) reader.addCommand('F',fill1stHadithEntries,0) #reader.processFile('test.txt') print "Processing KanzMaster ...." reader.processFile('../../src/cd2/KanzMaster.txt') print "loaded ",len(hadithItems),"." print "Sorting..." hadithItems.sort(sortByH) currentEntry=None reader=ReaderBase() reader.addCommand('H',fill2stHadithEntries,TYPE_MULTILINE) reader.addCommand('R',fill2stHadithEntries,0) reader.addCommand('F',fill2stHadithEntries,0) print "Processing sahihMaster ...." reader.processFile('../../src/cd2/sahihMaster.txt') currentEntry=None print "Processing daifMaster ...." reader.processFile('../../src/cd2/daifMaster.txt') #sort before merging to speed up the merge process hadith2Items.sort(sortByH) print "loaded ",len(hadith2Items),"." #Now both maps are sorted print "Merging ...." map(mergeHadithEntries,hadith2Items) #write the merged items print "writing ",len(hadithItems),"..." map(HadithEntry.write,hadithItems) print "successMerges=",successMerges Regards Alan Darwish "Knowledgeable enemy is better than an ignorant friend" --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 From samrobertsmith at gmail.com Mon Oct 24 10:52:34 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 24 Oct 2005 01:52:34 -0700 Subject: [Tutor] string Message-ID: <1d987df30510240152h6f37acb0md5ffa5a23ba73646@mail.gmail.com> what does the following sentence mean? does it mean i can not use double-quoted string? SyntaxError: EOL while scanning single-quoted string From ajikoe at gmail.com Mon Oct 24 11:02:01 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 24 Oct 2005 11:02:01 +0200 Subject: [Tutor] string In-Reply-To: <1d987df30510240152h6f37acb0md5ffa5a23ba73646@mail.gmail.com> References: <1d987df30510240152h6f37acb0md5ffa5a23ba73646@mail.gmail.com> Message-ID: please show us the code.... cheers, pujo On 10/24/05, Shi Mu wrote: > > what does the following sentence mean? does it mean i can not use > double-quoted string? > SyntaxError: EOL while scanning single-quoted string > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/820c4eee/attachment.htm From vincent.gulinao at gmail.com Mon Oct 24 11:37:04 2005 From: vincent.gulinao at gmail.com (Vincent Gulinao) Date: Mon, 24 Oct 2005 17:37:04 +0800 Subject: [Tutor] neat join Message-ID: is there any simple syntax for joining strings such that if any (or all) of the params is white space or None, it won't be included in the resulting string? e.g. str1, str2, str3 = "foo", "bar", None, if delimiter is " " would result to "foo bar"; str1, str2 = None, None would result to None. TIA. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/02a5fc46/attachment.html From kent37 at tds.net Mon Oct 24 11:55:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Oct 2005 05:55:21 -0400 Subject: [Tutor] neat join In-Reply-To: References: Message-ID: <435CAF89.30203@tds.net> Vincent Gulinao wrote: > is there any simple syntax for joining strings such that if any (or all) > of the params is white space or None, it won't be included in the > resulting string? > > e.g. str1, str2, str3 = "foo", "bar", None, if delimiter is " " would > result to "foo bar"; str1, str2 = None, None would result to None. If all your values are in a list, use a list comprehension to strip out the empty ones and join() to make a string: >>> def joinNoWs(lst): ... lst = [s for s in lst if s and s.strip() ] ... if lst: ... return ' '.join(lst) ... return None ... >>> joinNoWs( [ "foo", "bar", None ] ) 'foo bar' >>> joinNoWs( [ None, None ] ) If it's OK to return an empty string instead of None when all the inputs are empty, you can do this in one line: >>> def joinNoWs(lst): ... return ' '.join( [s for s in lst if s and s.strip()] ) ... >>> joinNoWs( [ None, None ] ) '' >>> joinNoWs( [ "foo", "bar", None ] ) 'foo bar' Kent -- http://www.kentsjohnson.com From samrobertsmith at gmail.com Mon Oct 24 12:21:09 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 24 Oct 2005 03:21:09 -0700 Subject: [Tutor] about FIND Message-ID: <1d987df30510240321y17a079ecr9e7225b55a7ae5dd@mail.gmail.com> I got confused by the following information from the help for "FIND": find(s, *args) find(s, sub [,start [,end]]) -> in what does *args mean (especially the '*')? also, in the sub, why put a comma before start? what does 'in' mean? From ldapguru at yahoo.com Mon Oct 24 12:49:45 2005 From: ldapguru at yahoo.com (Alan) Date: Mon, 24 Oct 2005 05:49:45 -0500 Subject: [Tutor] Modify to Print All Results After Sort (Alan) Or Self Inflected - When runs in MS active python the output is no good In-Reply-To: Message-ID: <000001c5d888$a83b2f10$2b01a8c0@server01> I did this and it worked 1. However will be nice to print output into filenames without me using > 2. Another problem: when run in Linux the output is OK BUT when runs in windows active python the output is no good # modify1: PRINT THE ABOVE CALL IT SORTEDkanz.TXT I commented the last lines in the script: #write the merged items #print "writing ",len(hadithItems),"..." #map(HadithEntry.write,hadithItems) I added the following # Ahmad to insert here the print the SORTEDkanz.TXT using >SORTEDkanz.TXT #write the merged items print "writing ",len(hadith2Items),"..." map(HadithEntry.write,hadith2Items) print "successMerges=",successMerges # END Ahmad to insert here the print command # modify1: PRINT THE ABOVE CALL IT SORTEDkanz.TXT # Ahmad to insert here the print command #write the merged items #print "writing ",len(hadithItems),"..." #map(HadithEntry.write,hadithItems) #print "successMerges=",successMerges # END Ahmad to insert here the print command will be nice to print SORTEDkanz.TXT, newKanzMater.txt etc --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 From samrobertsmith at gmail.com Mon Oct 24 15:01:15 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 24 Oct 2005 06:01:15 -0700 Subject: [Tutor] about \ Message-ID: <1d987df30510240601r20615631j26fc1dda455c8700@mail.gmail.com> Is there any difference if I remove the '/' from the following statement? intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\ [1,2,5,3,9,1,1,1,9,1],\ [0,0,5,1,1,1,9,7,7,7]] print intMatrix2 I removed one '\' and it still works. So what is the use of '\'? From kent37 at tds.net Mon Oct 24 16:17:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Oct 2005 10:17:43 -0400 Subject: [Tutor] about \ In-Reply-To: <1d987df30510240601r20615631j26fc1dda455c8700@mail.gmail.com> References: <1d987df30510240601r20615631j26fc1dda455c8700@mail.gmail.com> Message-ID: <435CED07.1080107@tds.net> Please don't duplicate post to python-tutor and comp.lang.python. You are getting two sets of answers to all your questions which wastes the time of those kind enough to reply. Thanks, Kent Shi Mu wrote: > Is there any difference if I remove the '/' > from the following statement? > intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\ > [1,2,5,3,9,1,1,1,9,1],\ > [0,0,5,1,1,1,9,7,7,7]] > print intMatrix2 > I removed one '\' and it still works. > So what is the use of '\'? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com From vincent.gulinao at gmail.com Mon Oct 24 16:29:43 2005 From: vincent.gulinao at gmail.com (Vincent Gulinao) Date: Mon, 24 Oct 2005 22:29:43 +0800 Subject: [Tutor] manipulating list of lists Message-ID: I have a list of lists of constant width (2 rows). I need to: 1. delete sub-lists with None element 2. sort it by any sub-list index say: [ ['c','d'], ['g',None], ['a','b',], ['e','f'] if sorted using 2nd index: [ ['a','b'], ['c','d'], ['e','f'] ] (same result for 1st index for this example) TIA. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/b21a1fe5/attachment.htm From hugonz-lists at h-lab.net Sat Oct 22 21:32:24 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sat, 22 Oct 2005 13:32:24 -0600 Subject: [Tutor] : Threads? In-Reply-To: <43593D88.3010709@gmail.com> References: <43593496.1000706@gmail.com> <43593B9C.9000002@tds.net> <43593D88.3010709@gmail.com> Message-ID: <435A93C8.1090302@h-lab.net> I have done scripts for decompressing MP3 in the past. I normally follow a fork() exec() subprocess scheme, and this helps me gain about 30% improvement. I'm not an expert, but I have read that CPU time will be better used by several processes than for just one, and while one process is waiting for disk IO and the like, another can be number crunching. I have some code, but I will have to look for it and then post it. I do: pid = os.fork() if pid == 0:#child os.system("my mp3 decompressor") raise SystemExit Doing this for all files that I have to convert, with up to, say, 5 subprocesses. Then, on the parent, os.waitpid() will be used to check when subprocesses have terminated and respawned until I run out of files.. I will post some code when I find it. Hugo Orri Ganel wrote: > Kent Johnson wrote: > > >>Orri Ganel wrote: >> >> >> >>>Hello all, >>> >>>I've been working on a program for a week or two now that will convert >>>all the wav files in a folder to mp3s, filling the id3 tags with the >>>correct information as collected from gracenote.com. This part works >>>fine. However, the actual conversion to mp3 takes between 30 and 50 >>>seconds per song, so it's usually about 10 minutes per album. With this >>>in mind, I thought, why not try to use threads so all the conversions >>>happen simultaneously? That way, the whole album will take between 30 >>>and 50 seconds. Unfortunately, I can't seem to get a working threaded >>>version that significantly reduces the time involved . . . The >>> >>> >> >>The only part you are doing in a thread is the actual conversion. This is likely to be CPU-intensive so running it in multiple threads may not help - you still have only the one CPU to run on. To the extent that you can overlap disk I/O in one conversion with processing in another you may get a win; on the other hand you could just as well have contention for the disk as you try to read and write a bunch of files at the same time. >> >>The fetch from gracenote.com seems like a better candidate for threading because there is some latency...but the total time is still probably small compared to the conversion time. >> >>Maybe if you have multiple CPUs you can get a speedup by using as many threads as CPUs...I'm not sure how os.system() behaves in this case. You may have to explicitly fork to get a new process. >> >>Hmm...come to think of it, os.system() may block other threads, I don't know...you could try subprocess.Popen() instead. >> >>Kent >> > > Thanks for the tip. Unfortunately, I only have 1 CPU and not the > slightest idea how to code for multiple CPUs in any case. Looks like > I'll just hafta deal with a 10-minute time per album. > From hugonz-lists at h-lab.net Sat Oct 22 21:38:29 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sat, 22 Oct 2005 13:38:29 -0600 Subject: [Tutor] Time - sum/difference In-Reply-To: <435809AD.6030808@SoftHome.net> References: <435809AD.6030808@SoftHome.net> Message-ID: <435A9535.4090309@h-lab.net> What I usually do is convert them all to UNIX epoch and then substact the values in seconds: >>> import time >>> early = time.time() >>> sleep(5) >>> time.sleep(5) >>> late = time.time() >>> print late - early 5.7889997959 >>> Jonas Melian wrote: > I would get the local time of a country, using UTC (Universal Time > Coordinated) and DST (Daylight SavingTime) of that country. > > An example, utc time -02:30 and dst +1 : > > country_utc = datetime.time(2,30) > isUTCNegative = True > dst = datetime.time(1,0) > > Now I would the difference of both times. > -02:30 + 01:00 -> -01:30 > > Is possible get sum/difference of time values? How? > > Thanks in advance > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Oct 24 16:58:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Oct 2005 10:58:52 -0400 Subject: [Tutor] : Threads? In-Reply-To: <435A93C8.1090302@h-lab.net> References: <43593496.1000706@gmail.com> <43593B9C.9000002@tds.net> <43593D88.3010709@gmail.com> <435A93C8.1090302@h-lab.net> Message-ID: <435CF6AC.9080608@tds.net> Hugo Gonz?lez Monteverde wrote: > I have done scripts for decompressing MP3 in the past. I normally follow > a fork() exec() subprocess scheme, and this helps me gain about 30% > improvement. I'm not an expert, but I have read that CPU time will be > better used by several processes than for just one, and while one > process is waiting for disk IO and the like, another can be number > crunching. > > I have some code, but I will have to look for it and then post it. IIUC Orri is running on Windows and fork() is not supported there. Kent From hugonz-lists at h-lab.net Mon Oct 24 16:59:01 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 24 Oct 2005 08:59:01 -0600 Subject: [Tutor] about \ In-Reply-To: <1d987df30510240601r20615631j26fc1dda455c8700@mail.gmail.com> References: <1d987df30510240601r20615631j26fc1dda455c8700@mail.gmail.com> Message-ID: <435CF6B5.4070306@h-lab.net> Hi, The '\' character is used to break lines and ask the interpreter to treat them as a single line, but Python is smart enough to allow breaking lines inside parenthesis and braces...so: NOT WORKING: >>> a, e, i, o, u = 1, 2, Traceback (most recent call last): File "", line 1, in ? ValueError: unpack tuple of wrong size >>> 3, 4, 5 File "", line 1 3, 4, 5 ^ SyntaxError: invalid syntax WORKS: >>> (a, e, i, o, u) = (1, 2, ... 3, 4, 5) >>> What's the difference? The parenthesis... the interpreter sees the open parenthesis and assumes correctly that the line is not yet finished. Hugo Shi Mu wrote: > Is there any difference if I remove the '/' > from the following statement? > intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\ > [1,2,5,3,9,1,1,1,9,1],\ > [0,0,5,1,1,1,9,7,7,7]] > print intMatrix2 > I removed one '\' and it still works. > So what is the use of '\'? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jonasmg at SoftHome.net Mon Oct 24 18:02:53 2005 From: jonasmg at SoftHome.net (Jonas Melian) Date: Mon, 24 Oct 2005 17:02:53 +0100 Subject: [Tutor] Time - sum/difference In-Reply-To: <435A9535.4090309@h-lab.net> References: <435809AD.6030808@SoftHome.net> <435A9535.4090309@h-lab.net> Message-ID: <435D05AD.30705@SoftHome.net> Anyway, I found a library for working with time zones http://pytz.sourceforge.net/ Hugo Gonz?lez Monteverde wrote: > What I usually do is convert them all to UNIX epoch and then substact > the values in seconds: > > >>> import time > >>> early = time.time() > >>> sleep(5) > >>> time.sleep(5) > >>> late = time.time() > >>> print late - early > 5.7889997959 > >>> > > > Jonas Melian wrote: > >> I would get the local time of a country, using UTC (Universal Time >> Coordinated) and DST (Daylight SavingTime) of that country. >> >> An example, utc time -02:30 and dst +1 : >> >> country_utc = datetime.time(2,30) >> isUTCNegative = True >> dst = datetime.time(1,0) >> >> Now I would the difference of both times. >> -02:30 + 01:00 -> -01:30 >> >> Is possible get sum/difference of time values? How? >> >> Thanks in advance >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From luke.jordan at gmail.com Mon Oct 24 18:04:50 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Mon, 24 Oct 2005 11:04:50 -0500 Subject: [Tutor] define vars by iteration In-Reply-To: References: Message-ID: Thanks for this insight into classes. It often takes me a few days to absorb and respond because my job limits the time I can give to programming. But thanks again for taking the time to respond in a meaningful way. I guess I could say that you changed my world when it comes to programming (sorry, low-hanging fruit :)) Luke On 10/20/05, Danny Yoo wrote: > > > > > Also, I have done what I'm trying to do successfully by populating a > > dictionary with class instances named after self.name < > http://self.name>, > > which, after the function runs, I can access this way > > >>> classDictionary["Yard"] > > > > the thing is I would like to be able to get at Yard's attributes by > typing > > >>> Yard.anAttribute > > garbage cans > > at the prompt rather than > > >>> Yard = classDictionary["Yard"] > > >>> Yard.anAttribute > > garbage cans > > > Hi Luke, > > One thing to note is that we can formally plunk and embed these places in > some kind of World: > > ###################################################### > class World: > def __init__(self): > self.places = {} > def attach(self, place): > """Given a place, attaches it to the world.""" > self.places[place.name ] = place > def lookup(self, name): > return self.places[name] > ###################################################### > > > If each place was aware that it was a part of a world --- that is, if we > embed the World inside each place as a part of a place's state --- then > things might work out. > > For example, we might have a north-south corridor: > > ################################################################## > class Corridor: > def __init__(self, world, name, northName, southName): > self.world, self.name , self.northName, self.southName = > ( > world, name, northName, southName) > def N(self): > return self.world.lookup(self.northName) > def S(self): > return self.world.lookup(self.southName) > ################################################################## > > What's a little funny about this Corridor definition is that, because a > cooridor knows its in the world, it can also ask the world what place > 'northName' stands for in its N() method. > > > Here's a small test: > > ###### > >>> world = World() > >>> world.attach(Corridor(world, "Water cooler", > ... north="Stairs", south="Boss Office")) > >>> world.attach(Corridor(world, "Stairs", > ... north="Wall", south="Water cooler")) > >>> > >>> > >>> world.lookup("Water cooler") > <__main__.Corridor instance at 0x403a7fcc> > >>> world.lookup("Water cooler").name > 'Water cooler' > >>> world.lookup("Water cooler").N() > <__main__.Corridor instance at 0x403a7f6c> > >>> world.lookup("Water cooler").N().name > 'Stairs' > ###### > > Another advantage of having a central place is that saving and restoring > the environment is just a matter of pickling the world. Hmmm... briny > pickles... *grin* Sorry, I'm getting distracted by food. > > > Does this make sense? Please feel free to ask more questions. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/6e2198ec/attachment-0001.htm From samrobertsmith at gmail.com Mon Oct 24 12:19:35 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 24 Oct 2005 03:19:35 -0700 Subject: [Tutor] help Message-ID: <1d987df30510240319x60dc1ffci9f62f5f58f4fe9f1@mail.gmail.com> I got confused by the following information from the help for "FIND": find(s, *args) find(s, sub [,start [,end]]) -> in what does *args mean (especially the '*')? also, in the sub, why put a comma before start? what does 'in' mean? From dyoo at hkn.eecs.berkeley.edu Mon Oct 24 19:08:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Oct 2005 10:08:41 -0700 (PDT) Subject: [Tutor] what does %25f mean? In-Reply-To: <1d987df30510240006i3d9c1cf1w4594f8c744c83429@mail.gmail.com> Message-ID: On Mon, 24 Oct 2005, Shi Mu wrote: > what does %25f mean? Hi Shi Mu, Without more context, I'd have to guess that this looks like a format string. Here's more information about them: http://www.python.org/doc/lib/typesseq-strings.html But can you show us where you saw this "%25f" thing though? Like bytes, words can be "interpreted" in different ways. Offhand, another alternative interpretation is as a url-escaped string: ###### >>> import urllib >>> >>> urllib.unquote('%25f') '%f' >>> >>> urllib.quote_plus('hello world, this is a percent: %') 'hello+world%2C+this+is+a+percent%3A+%25' ###### So if you can tell us where you saw '%25f', that'll help us cut down on the possible explanations that can better account for what you're seeing. Good luck! From marichar at csusb.edu Mon Oct 24 19:15:28 2005 From: marichar at csusb.edu (Matt Richardson) Date: Mon, 24 Oct 2005 10:15:28 -0700 Subject: [Tutor] problem with class overloading (maybe it's just me) Message-ID: <435D16B0.8030309@csusb.edu> Hi all, I've started the wxPython tutorials and have hit a problem already. When run from IDLE or by calling the script from the command line with matt at sprint:~/wxpy$ python helloWorld.py the script works fine, generating a small text editor. Making the file executable and including the shebang, running matt at sprint:~/wxpy$ ./helloWorld.py generates a cross-hair looking mouse pointer. Clicking the mouse generates the following error: matt at sprint:~/wxpy$ ./helloWorld.py ./helloWorld.py: line 6: syntax error near unexpected token `(' ./helloWorld.py: line 6: `class MainWindow(wx.Frame):' Which to me looks like it doesn't know what to do with wx.Frame, or some problem in extending the class. In the hello world example previous to this, there's no problem with wx.Frame and the program runs when executed from the command line. Here's the details: python 2.3.5 this one works: matt at sprint:~/wxpy$ cat hello.py #!/usr/bin/python import wx app = wx.PySimpleApp() frame = wx.Frame(None, -1, "Hello World") frame.Show(1) app.MainLoop() -------------------- this one fails: matt at sprint:~/wxpy$ cat helloWorld.py #!/usr/bin/python import wx class MainWindow(wx.Frame): """ We simply derive a new class of Frame. """ def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(200,100), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE) self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE) self.Show(True) app = wx.PySimpleApp() frame = MainWindow(None, -1, 'Small editor') app.MainLoop() I'm sure it's something simple I'm overlooking, so I'll go get a cup of coffee and see if someone with better eyes spots my error. thanks, Matt -- Matt Richardson IT Consultant College of Arts and Letters CSU San Bernardino (909)537-7598 From dyoo at hkn.eecs.berkeley.edu Mon Oct 24 19:16:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Oct 2005 10:16:05 -0700 (PDT) Subject: [Tutor] dictionary In-Reply-To: <435C8CB2.2050306@speakeasy.net> Message-ID: > > I typed: > > landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]} > > and when i checked landUse, I found it become: > > {'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2} > > why the order is changed? > > the docs warn you about this. Hi Shi, By the way, here's a post from a long long time ago that might help make it clearer what dictionaries are doing: http://mail.python.org/pipermail/tutor/2002-January/011281.html From dyoo at hkn.eecs.berkeley.edu Mon Oct 24 19:24:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Oct 2005 10:24:39 -0700 (PDT) Subject: [Tutor] problem with class overloading (maybe it's just me) In-Reply-To: <435D16B0.8030309@csusb.edu> Message-ID: > this one fails: > matt at sprint:~/wxpy$ cat helloWorld.py > > #!/usr/bin/python Hi Matt, Ah, good for showing that cat command: it gave enough hints that we can tell what's going on. Take out the leading empty space in your file; it's interfering with the magic line '#!/usr/bin/python'. The error message you're seeing isn't Python: > matt at sprint:~/wxpy$ ./helloWorld.py > ./helloWorld.py: line 6: syntax error near unexpected token `(' > ./helloWorld.py: line 6: `class MainWindow(wx.Frame):' It's actually Bourne shell trying to interpret your program as Bourne shell commands. *grin* Here's a session that verifies that those errors are symptomatic of '/bin/sh' error messages: ###### [dyoo at shoebox ~]$ cat foo.py class Foo(object): pass [dyoo at shoebox ~]$ /bin/sh foo.py foo.py: line 1: syntax error near unexpected token `(' foo.py: line 1: `class Foo(object):' ###### Hope this helps! From mi.janssen at gmail.com Mon Oct 24 19:32:44 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Mon, 24 Oct 2005 19:32:44 +0200 Subject: [Tutor] help In-Reply-To: <1d987df30510240319x60dc1ffci9f62f5f58f4fe9f1@mail.gmail.com> References: <1d987df30510240319x60dc1ffci9f62f5f58f4fe9f1@mail.gmail.com> Message-ID: <1ff2dfbf0510241032k74b2f19dpa7cb7de21f8907e9@mail.gmail.com> On 10/24/05, Shi Mu wrote: > I got confused by the following information from the help for "FIND": > find(s, *args) > find(s, sub [,start [,end]]) -> in Hello Shi Mu, this is the help for the function find in the string module, which is slightly out of date. Better you use the string method find: ### s = "" help(s.find) find(...) S.find(sub [,start [,end]]) -> int ### so the "in" is simply a typo. find returns an "int" not an "in". "*args" is the arbitrary number of arguments notation: http://docs.python.org/tut/node6.html#SECTION006730000000000000000 which might be misleading and is replaced by "..." in the string method's online help. The comma before start ist mandatory: *when* you want to give a "start" argument, you leave out the []-brackets but you need the comma: s.find('something', 1) The builtin documentation ist meant (there are such statements by Guido van Rossum in the web) as a brief mnemonic for things that are explained in more detail in the library documentation and the tutorial. regards Michael From marichar at csusb.edu Mon Oct 24 19:38:54 2005 From: marichar at csusb.edu (Matt Richardson) Date: Mon, 24 Oct 2005 10:38:54 -0700 Subject: [Tutor] problem with class overloading (maybe it's just me) In-Reply-To: References: Message-ID: <435D1C2E.20103@csusb.edu> Danny Yoo wrote: > Hope this helps! Helped a lot. Shows that syntax errors aren't always visible (like whitespace) and that I should know better than to attempt anything before having at least one cup of coffee. Thanks! Matt -- Matt Richardson IT Consultant College of Arts and Letters CSU San Bernardino (909)537-7598 From carl.badgley at gmail.com Mon Oct 24 20:05:08 2005 From: carl.badgley at gmail.com (carl.badgley@gmail.com) Date: Mon, 24 Oct 2005 11:05:08 -0700 Subject: [Tutor] py in a nut Message-ID: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> Hope this is not too off topic: I noticed that the Python in a Nutshell book is version 2.2 and a few years old. Does anyone know if there are plans to bring out a new edition anytime soon? I checked the O'reilly page and didnt find anything, also googled it. If anyone knows anything let me know. Thanks, Carl -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/2cde84e2/attachment.html From ronin_cpim at hotmail.com Mon Oct 24 20:10:01 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Mon, 24 Oct 2005 14:10:01 -0400 Subject: [Tutor] Help(!) with OOP/Composition from "Learning Python" Message-ID: >I've been reading about composition vs inheritance, and went back to >"Learning Python" to look at something I found very confusing a year >ago. Turns out I still find it very confusing :) Try this example ecology simulation by Kirby Urner: http://mail.python.org/pipermail/edu-sig/2000-April/000306.html It does have a bug or two in it, but I was able to find and fix them by myself. But the bugs are discussed here if you get stuck: http://mail.python.org/pipermail/edu-sig/2003-March/002742.html and here: http://mail.python.org/pipermail/edu-sig/2003-March/002744.html Still, simple as it is, it gave me a much more profound grasp of Python based OOP than any of Learning Python's examples. I suspect the following book might be superb for leaning OOP: Game Programming With Python (Game Development Series) (Paperback) by Sean Riley In short, study actual simulations (of which games are a major subset)! RC _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar – get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From kent37 at tds.net Mon Oct 24 20:34:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Oct 2005 14:34:04 -0400 Subject: [Tutor] py in a nut In-Reply-To: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> Message-ID: <435D291C.3070608@tds.net> carl.badgley at gmail.com wrote: > Hope this is not too off topic: > I noticed that the Python in a Nutshell book is version 2.2 and a few > years old. Does anyone know if there are plans to bring out a new > edition anytime soon? I checked the O'reilly page and didnt find > anything, also googled it. AFAIK it is still just a gleam in Alex Martelli's eye. He has recently resurfaced on comp.lang.python so maybe he will have time for some writing...we can hope! Kent From alan.gauld at freenet.co.uk Mon Oct 24 21:30:43 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 20:30:43 +0100 Subject: [Tutor] dictionary References: <1d987df30510240013u2d7880easb8a7081586f2fd33@mail.gmail.com> <435C8CB2.2050306@speakeasy.net> Message-ID: <012e01c5d8d1$6d624b50$0a01a8c0@xp> > A dictionary stores its values based on the keys. Internally Python > sorts the keys to make the lookup meet performance expectations. > > You can not expect a dictionary to return keys in the other you added > them. If you want that, store the items as tuples in a list. Or you can sort the keys and iterate over that: keys = dic.keys() keys.sort() # sorts in place! for key in keys.sort(): print key,dic[key] Alan G From alan.gauld at freenet.co.uk Mon Oct 24 21:34:04 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 20:34:04 +0100 Subject: [Tutor] string References: <1d987df30510240152h6f37acb0md5ffa5a23ba73646@mail.gmail.com> Message-ID: <013201c5d8d1$e4d7ce80$0a01a8c0@xp> > what does the following sentence mean? does it mean i can not use > double-quoted string? > SyntaxError: EOL while scanning single-quoted string No, it means you didn't correctly terminate the string with a matching quote. The error is slightly ambiguous, the word 'single' here means there is only one quote sign, it is not referring to the use of ' instead of " ... Alan G. From alan.gauld at freenet.co.uk Mon Oct 24 21:40:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 20:40:22 +0100 Subject: [Tutor] about FIND References: <1d987df30510240321y17a079ecr9e7225b55a7ae5dd@mail.gmail.com> Message-ID: <014b01c5d8d2$c66b4de0$0a01a8c0@xp> > find(s, sub [,start [,end]]) -> in > > what does *args mean (especially the '*')? *args means that a variable number of arguments can be provided. The exact nature of those being described in the next line. So: find =(s,sub) find(s,sub,start) find(s,sub,start,stop) are all valid > also, in the sub, why put a comma before start? because start is optional but if you have it there must be a comma separating it from the previous sub argument. That is the comma is required as part of the syntax. The square brackets indicate that start is optional. > what does 'in' mean? IT should be 'int' The arrow shows the return value - in this case the location as an index number. HTH< Alan G From alan.gauld at freenet.co.uk Mon Oct 24 22:01:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 21:01:34 +0100 Subject: [Tutor] about \ References: <1d987df30510240601r20615631j26fc1dda455c8700@mail.gmail.com> Message-ID: <015101c5d8d5$bca4ae70$0a01a8c0@xp> > Is there any difference if I remove the '/' You mean the '\' I assume? In this case no difference whatsoever because Python will keep on looking for the matching closing ']' > intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\ > [1,2,5,3,9,1,1,1,9,1],\ > [0,0,5,1,1,1,9,7,7,7]] > So what is the use of '\'? \ is the line continuation character. Thus if you need to wrap a line but don't want python to interpret it as two lines use a \ character: >>> print ' here is a long line of text ' + \ ... 'extended by another string' ' here is a long line of text extended by another string' Without the \ char you get an error. But if there is an open bracket or paren then Python ignores the end of line until it finds the closing paren etc. However many programmers like to put the \ char anyway just to indicate that it is a single logical line broken for readability HTH, Alan G. From alan.gauld at freenet.co.uk Mon Oct 24 22:12:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 21:12:20 +0100 Subject: [Tutor] Time - sum/difference References: <435809AD.6030808@SoftHome.net> <435A9535.4090309@h-lab.net> <435D05AD.30705@SoftHome.net> Message-ID: <016101c5d8d7$3d57a710$0a01a8c0@xp> > Anyway, I found a library for working with time zones > http://pytz.sourceforge.net/ Thanks for pointing this one out, it looks good. As someone who once commisioned a research paper on Time Zones and programming I must say this looks like one of the most complete timezone sites around. However this statement needs to be highlighted with an anecdote :-) "Note that if you perform date arithmetic on local times that cross DST boundaries, the results may be in an incorrect timezone " DST is not an agreed well defined entity. When on a skiing holiday in the tiny country of Andorra the local council decided that the snow was melting too much in the late afternoon. Their brilliantly simple solution was to bring forward DST by a week (a simple announcement on local radio and newspaper!) and the snow slopes now closed an hour earlier saving the snow from skiers turning it to slush in the late afternoon sun! I can't imagine the havoc that created for their computer systems... But tourism is king in Andorra. A salutory lesson on how fragile is our grasp on time. Alan G. From alan.gauld at freenet.co.uk Mon Oct 24 22:23:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 21:23:56 +0100 Subject: [Tutor] py in a nut References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> Message-ID: <018601c5d8d8$dc496420$0a01a8c0@xp> > I noticed that the Python in a Nutshell book is version 2.2 and a few > years > old. Does anyone know if there are plans to bring out a new edition Disclaimer: I know nothing of O'Reilly or Alex Martelli's plans! But from experience of my own book it takes a good year to 18 months to do a full re-edit and all the other pre publication chores. Given the book only came out in 2003 I'd be surprised to see an update before next year... The problem is that open source software tends to change so quickly an author can't hope to keep up. My book started out when Python v1.5.2 was the latest stable release, by the time it got published it was Python 2.0 and an alpha of 2.1 was available! I put v2.0 on the CD but the text stayed at 1.5.2 The good news is that with Python 95%+ will still be applicable because Python has a good tradition of suipporting backwards compatibility. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Mon Oct 24 23:29:54 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 25 Oct 2005 10:29:54 +1300 Subject: [Tutor] pytunes (Was __slots__, struct, etc.) In-Reply-To: References: <5e58f2e40510201503t2c5bd59ck@mail.gmail.com> Message-ID: <5e58f2e40510241429i3b05f9fas@mail.gmail.com> For all of them --- not guaranteed that you'll be able to achieve the optimum.. My solution is basically a greedy algorithm: Make a list of (artist, tracks) pairs, and sort descending by len(tracks). Then iteratively: 1. Take the next track from the first artist on the list. 2. Move that artist down to position total/len(tracks). Repeat until all tracks have been selected :-) Generally it works well, except at the end of the playlist sometimes. See attachment for my implementation. (uses mmpython, which you can find on the net) -- John. On 21/10/05, Liam Clarke wrote: > Hmmm, that's interesting. > > Obviously, for a playlist with x songs, and n songs by a particular > artist, the optimum separation between songs would be x/n. > > Which would be easy for one artist, but for all of them? > > Hmm... > > Let's see. First off, let's discount all the artists with only one > song, they can be the space filler. > > Next, you'd have to work out optimal spacing for each artist's songs, > and try to insert them into a list. If that slot was already taken, > you'd want to look down and up the list for the next free space, > choosing whichever maximised the distance. And you'd have to treat > x[5] - 10 as x[96] for a list x where len(x) == 100. > > Err, there's got to be an algorithm for this sorta stuff, but I can't > understand the big words when I google it... what's your solution? > > On 10/21/05, John Fouhy wrote: > > Hmm, neat. I don't have any feedback for you on your code, but since > > you're working with this sort of thing, I have a puzzle for you: > > > > Suppose you have a collection of MP3 files. You want to build a > > random playlist, subject to the condition that tracks by the same > > artist are as far apart as possible. You can assume you have the > > track / artist data in any structure you like. How would you do this? > > > > (I have a solution, but I don't think it is optimal. In fact, I'm not > > sure how to actually define "optimal" here... And so I am interested > > in how other people would solve this problem :-) ) > > > > -- > > John. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: randomizeMusic.py Url: http://mail.python.org/pipermail/tutor/attachments/20051025/8011a02f/randomizeMusic.asc From mdcooper at uvic.ca Mon Oct 24 23:36:25 2005 From: mdcooper at uvic.ca (mdcooper) Date: Mon, 24 Oct 2005 14:36:25 -0700 Subject: [Tutor] Tkinter Data Passing Problem Message-ID: <435E5D70@wm2.uvic.ca> Hi, I am having some trouble with tkinter. I am creating a filled set of entry boxes so that a user can adjust certain data if desired. I would prefer that the box containing these data be separate from the main GUI. The problem is that when I specify that the frame be part of root the data appears in the entry boxes (using textvariable = StringVar()) but if a second Tk() root is specified, the entry boxes appear, but there is no data. I cannot figure out why. Can someone help? Thanks, Matt def adjustGuassianData2(self, master): self.frames.append(Frame(master)) self.frames[4].grid() self.entries=[] self.text=[] Label(self.frames[4], text="Frequencies").grid(row=0, column=0) Label(self.frames[4], text="Intensities").grid(row=0, column=1) Label(self.frames[4], text="New Intensities").grid(row=0, column=2) for r in range(len(self.frequencies)): self.text.append([[],[],[]]) self.text[r][0]=StringVar() self.text[r][1]=StringVar() self.text[r][2]=StringVar() self.text[r][0].set("%3.2f" % (self.frequencies[r])) self.text[r][1].set("%3.2f" % (self.IR_intensities[r])) self.text[r][2].set("%3.2f" % (self.IR_intensities[r])) self.entries.append([Entry(self.frames[4],textvariable=self.text[r][0]), Entry(self.frames[4],textvariable=self.text[r][1]), Label(self.frames[4], textvariable=self.text[r][2])]) self.entries[r][0].grid(row=r+1, column=0) self.entries[r][1].grid(row=r+1, column=1) self.entries[r][2].grid(row=r+1, column=2) b = Button(self.frames[4], text="UPDATE!", command=self.updateEntries) b.grid(row=r+2,column=0,columnspan=3) From john at fouhy.net Mon Oct 24 23:44:29 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 25 Oct 2005 10:44:29 +1300 Subject: [Tutor] Tkinter Data Passing Problem In-Reply-To: <435E5D70@wm2.uvic.ca> References: <435E5D70@wm2.uvic.ca> Message-ID: <5e58f2e40510241444r66e9a44k@mail.gmail.com> On 25/10/05, mdcooper wrote: > The problem is that when I specify that the frame be part of root the data > appears in the entry boxes (using textvariable = StringVar()) but if a second > Tk() root is specified, the entry boxes appear, but there is no data. I cannot > figure out why. > > Can someone help? I'm not sure if I understand exactly --- but it is generally an error to make two root windows. If you want to have additional windows on your screen, look into the Toplevel() class. -- John. From edhotchkiss at gmail.com Mon Oct 24 23:56:01 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Mon, 24 Oct 2005 17:56:01 -0400 Subject: [Tutor] testing for modules? Message-ID: i have a generic script that is using several modules on windows and linux boxes. i need to have the scripts test if a module is installed, and then if not - then to install the module. can anyone give me a headsup on how to test for a module, returning something to indicate whether or not it is installed, then after that executing file to install the module.? just somewhere to start would be helpful! thanks in advance. -- edward hotchkiss -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/e9a4be3c/attachment.htm From alan.gauld at freenet.co.uk Tue Oct 25 00:14:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 24 Oct 2005 23:14:46 +0100 Subject: [Tutor] Tkinter Data Passing Problem References: <435E5D70@wm2.uvic.ca> Message-ID: <01b901c5d8e8$57ecdbc0$0a01a8c0@xp> > The problem is that when I specify that the frame be part of root the data > appears in the entry boxes (using textvariable = StringVar()) but if a > second > Tk() root is specified, the entry boxes appear, but there is no data. I > cannot > figure out why. Create your new dialog as a child of TopLevel instead of Tk() Alan G From kent37 at tds.net Tue Oct 25 00:35:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Oct 2005 18:35:05 -0400 Subject: [Tutor] testing for modules? In-Reply-To: References: Message-ID: <435D6199.2010408@tds.net> Ed Hotchkiss wrote: > i have a generic script that is using several modules on windows and > linux boxes. i need to have the scripts test if a module is installed, > and then if not - then to install the module. can anyone give me a > headsup on how to test for a module, returning something to indicate > whether or not it is installed, then after that executing file to > install the module.? just somewhere to start would be helpful! thanks in > advance. I don't know a generic way to install a module but the testing part is easy - just try to import it: try: import mymodule except ImportError: # install mymodule In general you need to download and unzip a module, then run 'python setup.py install'. Kent -- http://www.kentsjohnson.com From billburns at pennswoods.net Tue Oct 25 00:41:31 2005 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 24 Oct 2005 18:41:31 -0400 Subject: [Tutor] testing for modules? In-Reply-To: References: Message-ID: <435D631B.4000703@pennswoods.net> Ed Hotchkiss wrote: > i have a generic script that is using several modules on windows and > linux boxes. i need to have the scripts test if a module is installed, > and then if not - then to install the module. can anyone give me a > headsup on how to test for a module, returning something to indicate > whether or not it is installed, then after that executing file to > install the module.? just somewhere to start would be helpful! thanks in > advance. Hi Ed, You can at do this to test if a module is installed: try: import SomeModule except ImportError: print 'SomeModule is not installed!' I'm not sure about the part regarding the module installation. I guess you would replace the print statement above with some code to install the module. HTH, Bill From singingxduck at gmail.com Tue Oct 25 02:42:42 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Mon, 24 Oct 2005 20:42:42 -0400 Subject: [Tutor] : Threads? In-Reply-To: <435CF6AC.9080608@tds.net> References: <43593496.1000706@gmail.com> <43593B9C.9000002@tds.net> <43593D88.3010709@gmail.com> <435A93C8.1090302@h-lab.net> <435CF6AC.9080608@tds.net> Message-ID: <3449428f0510241742j3b22ae5bkf62133a9309c9d79@mail.gmail.com> Not sure what IIUC stands for, but I am, indeed, running windows. XP Home Edition, in fact, with Python 2.4.2 final On 10/24/05, Kent Johnson wrote: > > Hugo Gonz?lez Monteverde wrote: > > I have done scripts for decompressing MP3 in the past. I normally follow > > a fork() exec() subprocess scheme, and this helps me gain about 30% > > improvement. I'm not an expert, but I have read that CPU time will be > > better used by several processes than for just one, and while one > > process is waiting for disk IO and the like, another can be number > > crunching. > > > > I have some code, but I will have to look for it and then post it. > > IIUC Orri is running on Windows and fork() is not supported there. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051024/8ea1bddb/attachment.htm From kent37 at tds.net Tue Oct 25 03:06:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Oct 2005 21:06:53 -0400 Subject: [Tutor] : Threads? In-Reply-To: <3449428f0510241742j3b22ae5bkf62133a9309c9d79@mail.gmail.com> References: <43593496.1000706@gmail.com> <43593B9C.9000002@tds.net> <43593D88.3010709@gmail.com> <435A93C8.1090302@h-lab.net> <435CF6AC.9080608@tds.net> <3449428f0510241742j3b22ae5bkf62133a9309c9d79@mail.gmail.com> Message-ID: <435D852D.7050302@tds.net> Orri Ganel wrote: > Not sure what IIUC stands for, but I am, indeed, running windows. XP > Home Edition, in fact, with Python 2.4.2 final If I Understand Correctly http://www.acronymfinder.com/ is helpful here. Kent From python at jayloden.com Tue Oct 25 03:11:41 2005 From: python at jayloden.com (Jay Loden) Date: Mon, 24 Oct 2005 21:11:41 -0400 Subject: [Tutor] hand-holding for web development In-Reply-To: <965122bf0510181323k7ede8385mc7673e4a75c85305@mail.gmail.com> References: <965122bf0510131249had88b1fmf6124787e206a410@mail.gmail.com> <200510171513.36008.python@jayloden.com> <965122bf0510181323k7ede8385mc7673e4a75c85305@mail.gmail.com> Message-ID: <200510242111.41645.python@jayloden.com> Sorry, didn't see your reply until now... the directory section can go either in your main apache config file (in my case, /etc/httpd/conf/httpd.conf ) OR in a separate file in the conf.d directory. In my case, I have a python.conf file in /etc/httpd/conf.d/ that contains the following: LoadModule python_module modules/mod_python.so AddHandler mod_python .htm PythonHandler parse # PythonDebug On As for Django, I don't even know what that is, let alone how to interface to it, so you'd have to look elsewhere for help on that. I imagine there's someplace online you can get Django help such a specific mailing list. -Jay On Tuesday 18 October 2005 04:23 pm, nitin chandra wrote: > Thanks Jay > > i guess the can be added only in one of the conf > file. Which one should i add in? > > Thaks you. could you please guide how to interface Django with > mod_python, for effectively using in web site development? > From broek at cc.umanitoba.ca Tue Oct 25 04:46:47 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 24 Oct 2005 21:46:47 -0500 Subject: [Tutor] manipulating list of lists In-Reply-To: References: Message-ID: <435D9C97.5010501@cc.umanitoba.ca> Vincent Gulinao said unto the world upon 2005-10-24 09:29: > I have a list of lists of constant width (2 rows). I need to: > 1. delete sub-lists with None element > 2. sort it by any sub-list index > > say: [ ['c','d'], ['g',None], ['a','b',], ['e','f'] > if sorted using 2nd index: [ ['a','b'], ['c','d'], ['e','f'] ] (same result > for 1st index for this example) > > TIA. Hi Vincent, I'm no guru, so watch this space for better suggestions ;-) I changed your example to one where the sort order is different for sort by the first and second items of the nested lists. I'd use a list comprehension to remove the items with a None value: >>> orig_list = [ ['c','b'], ['g',None], ['a','g',], ['e','f'], ['d', None]] >>> noneless = [[x, y] for [x, y] in orig_list if not (x is None or y is None)] >>> noneless [['c', 'b'], ['a', 'g'], ['e', 'f']] Or: >>> noneless = [[x, y] for [x, y] in orig_list if not None in [x, y]] >>> noneless [['c', 'b'], ['a', 'g'], ['e', 'f']] To sort by the second item, try >>> def sort_by_second(sequence): decorated = [(x[1], x) for x in sequence] decorated.sort() return [x[1] for x in decorated] (google for DSU, Decorate Sort Undecorate for more info) >>> sort_by_second(noneless) [['c', 'b'], ['e', 'f'], ['a', 'g']] HTH. There's no explanation here (I'm feeling lazy); post again if you need some help sorting this out. Best, Brian vdB From john at fouhy.net Tue Oct 25 05:12:48 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 25 Oct 2005 16:12:48 +1300 Subject: [Tutor] manipulating list of lists In-Reply-To: <435D9C97.5010501@cc.umanitoba.ca> References: <435D9C97.5010501@cc.umanitoba.ca> Message-ID: <5e58f2e40510242012v1c4966a1t@mail.gmail.com> On 25/10/05, Brian van den Broek wrote: > To sort by the second item, try > > >>> def sort_by_second(sequence): > decorated = [(x[1], x) for x in sequence] > decorated.sort() > return [x[1] for x in decorated] With python2.4, you can use the key= argument to sort. eg: >>> arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)] >>> arr.sort(key=lambda x: x[1]) >>> arr [('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)] -- John. From john at fouhy.net Tue Oct 25 05:18:14 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 25 Oct 2005 16:18:14 +1300 Subject: [Tutor] manipulating list of lists In-Reply-To: <435D9C97.5010501@cc.umanitoba.ca> References: <435D9C97.5010501@cc.umanitoba.ca> Message-ID: <5e58f2e40510242018y2a92accm@mail.gmail.com> On 25/10/05, Brian van den Broek wrote: > To sort by the second item, try > > >>> def sort_by_second(sequence): > decorated = [(x[1], x) for x in sequence] > decorated.sort() > return [x[1] for x in decorated] With python2.4, you can use the key= argument to sort. eg: >>> arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)] >>> arr.sort(key=lambda x: x[1]) >>> arr [('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)] -- John. From broek at cc.umanitoba.ca Tue Oct 25 05:46:20 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 24 Oct 2005 22:46:20 -0500 Subject: [Tutor] manipulating list of lists In-Reply-To: <5e58f2e40510242018y2a92accm@mail.gmail.com> References: <435D9C97.5010501@cc.umanitoba.ca> <5e58f2e40510242018y2a92accm@mail.gmail.com> Message-ID: <435DAA8C.4060207@cc.umanitoba.ca> John Fouhy said unto the world upon 2005-10-24 22:18: > On 25/10/05, Brian van den Broek wrote: > >>To sort by the second item, try >> >> >>> def sort_by_second(sequence): >> decorated = [(x[1], x) for x in sequence] >> decorated.sort() >> return [x[1] for x in decorated] > > > With python2.4, you can use the key= argument to sort. > > eg: > >>>>arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)] >>>>arr.sort(key=lambda x: x[1]) >>>>arr > > [('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)] And that would be the better suggestion I predicted :-) I also should have pointed out that I wrote >>> noneless = [[x, y] for [x, y] in orig_list if not (x is None or y is None)] to be fully explicit. Better in real code (I think) would be >>> noneless = [x for x in orig_list if not None in x] >>> noneless [['c', 'b'], ['a', 'g'], ['e', 'f']] >>> Best, Brian vdB From samrobertsmith at gmail.com Tue Oct 25 06:26:26 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 24 Oct 2005 21:26:26 -0700 Subject: [Tutor] Matrix Message-ID: <1d987df30510242126p331f2cfat1420f13c1c726ed1@mail.gmail.com> I can not understand the use of "cell in row" for two times in the code: # convert the matrix to a 1D list matrix = [[13,2,3,4,5],[0,10,6,0,0],[7,0,0,0,9]] items = [cell for row in matrix for cell in row] print items From francis.moore at rawflow.com Tue Oct 25 10:33:57 2005 From: francis.moore at rawflow.com (Frank Moore) Date: Tue, 25 Oct 2005 09:33:57 +0100 Subject: [Tutor] py in a nut In-Reply-To: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> Message-ID: <435DEDF5.1050001@rawflow.com> carl.badgley at gmail.com wrote: > Hope this is not too off topic: > I noticed that the Python in a Nutshell book is version 2.2 and a few > years old. Does anyone know if there are plans to bring out a new > edition anytime soon? I checked the O'reilly page and didnt find > anything, also googled it. > If anyone knows anything let me know. > Thanks, > Carl > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > Carl, I mailed O'Reilly in June of this year to ask about any Python books on the horizon. I particularly wanted to know if an 'Advanced Python' book was on the cards. Something that included subjects like Descriptors, Generators, Iterators, Metaclasses, Decorators, Design patterns, etc. And this was the response I got from them: We do have a couple of Python books in the works. Twisted: A Developer's Notebook - should be released in October. Programming Python, 3E which should be released in December. Python in a Nutshell, 2nd Edition - scheduled to be released in March of next year. So there is no Advanced Python book on the horizon, which is a shame. But as you can see, Python in a Nutshell 2nd edition is due out next March. Cheers, F. From shitizb at yahoo.com Tue Oct 25 10:48:33 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue, 25 Oct 2005 01:48:33 -0700 (PDT) Subject: [Tutor] testing for modules? In-Reply-To: Message-ID: <20051025084833.17774.qmail@web53805.mail.yahoo.com> try: import except: import --- Ed Hotchkiss wrote: > i have a generic script that is using several > modules on windows and linux > boxes. i need to have the scripts test if a module > is installed, and then if > not - then to install the module. can anyone give me > a headsup on how to > test for a module, returning something to indicate > whether or not it is > installed, then after that executing file to install > the module.? just > somewhere to start would be helpful! thanks in > advance. > > -- > edward hotchkiss > > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Tue Oct 25 11:58:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Oct 2005 05:58:34 -0400 Subject: [Tutor] manipulating list of lists In-Reply-To: <5e58f2e40510242018y2a92accm@mail.gmail.com> References: <435D9C97.5010501@cc.umanitoba.ca> <5e58f2e40510242018y2a92accm@mail.gmail.com> Message-ID: <435E01CA.6030402@tds.net> John Fouhy wrote: > On 25/10/05, Brian van den Broek wrote: > >>To sort by the second item, try >> >> >>> def sort_by_second(sequence): >> decorated = [(x[1], x) for x in sequence] >> decorated.sort() >> return [x[1] for x in decorated] > > > With python2.4, you can use the key= argument to sort. > > eg: > >>>>arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)] >>>>arr.sort(key=lambda x: x[1]) and you can use operator.itemgetter() instead of a lambda - it is intended for this usage: >>> import operator >>> arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)] >>> arr.sort(key=operator.itemgetter(1)) >>> arr [('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)] Kent -- http://www.kentsjohnson.com From kent37 at tds.net Tue Oct 25 12:04:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Oct 2005 06:04:51 -0400 Subject: [Tutor] py in a nut In-Reply-To: <435DEDF5.1050001@rawflow.com> References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> <435DEDF5.1050001@rawflow.com> Message-ID: <435E0343.5080603@tds.net> Frank Moore wrote: > I mailed O'Reilly in June of this year to ask about any Python books on > the horizon. > I particularly wanted to know if an 'Advanced Python' book was on the > cards. > Something that included subjects like Descriptors, Generators, > Iterators, Metaclasses, Decorators, Design patterns, etc. Have you looked at Python Cookbook 2E? Chapter 19 is "Iterators and Generators". Chapter 20 is "Descriptors, Decorators and Metaclasses". > And this was the response I got from them: > > > We do have a couple of Python books in the works. > > Twisted: A Developer's Notebook - should be released in October. This one is available: http://www.oreilly.com/catalog/twistedadn/ Kent -- http://www.kentsjohnson.com From francis.moore at rawflow.com Tue Oct 25 13:52:38 2005 From: francis.moore at rawflow.com (Frank Moore) Date: Tue, 25 Oct 2005 12:52:38 +0100 Subject: [Tutor] testing for modules? In-Reply-To: <20051025084833.17774.qmail@web53805.mail.yahoo.com> References: <20051025084833.17774.qmail@web53805.mail.yahoo.com> Message-ID: <435E1C86.20003@rawflow.com> Shitiz Bansal wrote: >try: > import >except: > > import > > >--- Ed Hotchkiss wrote: > > > Explicit is always better than implicit... try: import except ImportError: # Only catch import errors import Cheers, F. From francis.moore at rawflow.com Tue Oct 25 14:05:49 2005 From: francis.moore at rawflow.com (Frank Moore) Date: Tue, 25 Oct 2005 13:05:49 +0100 Subject: [Tutor] py in a nut In-Reply-To: <435E0343.5080603@tds.net> References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> <435DEDF5.1050001@rawflow.com> <435E0343.5080603@tds.net> Message-ID: <435E1F9D.9070709@rawflow.com> Kent Johnson wrote: >Have you looked at Python Cookbook 2E? Chapter 19 is "Iterators and Generators". Chapter 20 is "Descriptors, Decorators and Metaclasses". > > I have. But I'd rather have a complete book on these subjects ;-) I'm sure someone will write one in the end. Hopefully Alex Martelli will. He currently runs a course on these subjects. The reason I wrote to O'Reilly originally was because the 2nd Edition of the 'Advanced Perl Programming' book had just come out and I noticed how perl had so many books (almost 40) written about it but Python only had 9. An advanced Python book seemed to be the one that was so obviously missing. >This one is available: >http://www.oreilly.com/catalog/twistedadn/ > > I'm still waiting for O'Reilly to publish the Table of Contents so I can see what's in it. As everyone else has noted, the cover is definitely one of their best. Cheers, F. From damien.gouteux at gmail.com Tue Oct 25 16:01:08 2005 From: damien.gouteux at gmail.com (Damien Gouteux) Date: Tue, 25 Oct 2005 16:01:08 +0200 Subject: [Tutor] py in a nut In-Reply-To: <435E1F9D.9070709@rawflow.com> References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> <435DEDF5.1050001@rawflow.com> <435E0343.5080603@tds.net> <435E1F9D.9070709@rawflow.com> Message-ID: <435E3AA4.4090206@gmail.com> In french, 'Python pr?cis & concis', from O'Reilly is now out : from Mark Lutz, it covers python 2.4 (and decorators). I assume there is a english edition of this book. Frank Moore wrote: >Kent Johnson wrote: > > > >>Have you looked at Python Cookbook 2E? Chapter 19 is "Iterators and Generators". Chapter 20 is "Descriptors, Decorators and Metaclasses". >> >> >> >> >I have. But I'd rather have a complete book on these subjects ;-) >I'm sure someone will write one in the end. Hopefully Alex Martelli >will. He currently runs a course on these subjects. > >The reason I wrote to O'Reilly originally was because the 2nd Edition of >the 'Advanced Perl Programming' book had just come out and I noticed how >perl had so many books (almost 40) written about it but Python only had >9. An advanced Python book seemed to be the one that was so obviously >missing. > > > >>This one is available: >>http://www.oreilly.com/catalog/twistedadn/ >> >> >> >> >I'm still waiting for O'Reilly to publish the Table of Contents so I can >see what's in it. >As everyone else has noted, the cover is definitely one of their best. > >Cheers, >F. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/8c749bb0/attachment.htm From francis.moore at rawflow.com Tue Oct 25 16:16:11 2005 From: francis.moore at rawflow.com (Frank Moore) Date: Tue, 25 Oct 2005 15:16:11 +0100 Subject: [Tutor] py in a nut In-Reply-To: <435E3AA4.4090206@gmail.com> References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> <435DEDF5.1050001@rawflow.com> <435E0343.5080603@tds.net> <435E1F9D.9070709@rawflow.com> <435E3AA4.4090206@gmail.com> Message-ID: <435E3E2B.9070809@rawflow.com> Damien Gouteux wrote: > In french, 'Python pr?cis & concis', from O'Reilly is now out : from > Mark Lutz, it covers python 2.4 (and decorators). > I assume there is a english edition of this book. Yes, that's the Python Pocket Reference. It does have 1 (small) page on decorators, but nothing on metaclasses, descriptors etc... The Pocket Reference is useful as a reminder on how something works syntactically, but it's probably not the best place to find an in-depth explanation on how something works in the first place. Cheers, F. From kent37 at tds.net Tue Oct 25 16:23:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Oct 2005 10:23:58 -0400 Subject: [Tutor] py in a nut In-Reply-To: <435E3AA4.4090206@gmail.com> References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> <435DEDF5.1050001@rawflow.com> <435E0343.5080603@tds.net> <435E1F9D.9070709@rawflow.com> <435E3AA4.4090206@gmail.com> Message-ID: <435E3FFE.2000905@tds.net> Damien Gouteux wrote: > In french, 'Python pr?cis & concis', from O'Reilly is now out : from > Mark Lutz, it covers python 2.4 (and decorators). > I assume there is a english edition of this book. Probably Python Pocket Reference, Third Edition http://www.oreilly.com/catalog/pythonpr3/ Kent From edhotchkiss at gmail.com Tue Oct 25 18:00:24 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Tue, 25 Oct 2005 12:00:24 -0400 Subject: [Tutor] identify python interpreters platform? Message-ID: how can i use the os module (or something else?) to determine what platform the interpreter is running on? -- edward hotchkiss -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/8a7b8145/attachment.html From kent37 at tds.net Tue Oct 25 18:16:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Oct 2005 12:16:04 -0400 Subject: [Tutor] identify python interpreters platform? In-Reply-To: References: Message-ID: <435E5A44.7020700@tds.net> Ed Hotchkiss wrote: > > how can i use the os module (or something else?) to determine what > platform the interpreter is running on? Try sys.platform Kent -- http://www.kentsjohnson.com From edhotchkiss at gmail.com Tue Oct 25 18:24:25 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Tue, 25 Oct 2005 12:24:25 -0400 Subject: [Tutor] identify python interpreters platform? In-Reply-To: <435E5A44.7020700@tds.net> References: <435E5A44.7020700@tds.net> Message-ID: Well, on windows XP it returns "nt" for os.name and for sys.platform it returns win32. how can i determine win2k, xp, 9x, etc etc ... -edward -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/c3a7059e/attachment.html From kent37 at tds.net Tue Oct 25 18:46:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Oct 2005 12:46:02 -0400 Subject: [Tutor] identify python interpreters platform? In-Reply-To: References: <435E5A44.7020700@tds.net> Message-ID: <435E614A.1070201@tds.net> Ed Hotchkiss wrote: > Well, on windows XP it returns "nt" for os.name and for > sys.platform it returns win32. how can i determine win2k, xp, 9x, etc > etc ... I don't know...maybe something in os.environ? From edhotchkiss at gmail.com Tue Oct 25 18:52:40 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Tue, 25 Oct 2005 12:52:40 -0400 Subject: [Tutor] identify python interpreters platform? In-Reply-To: <435E614A.1070201@tds.net> References: <435E5A44.7020700@tds.net> <435E614A.1070201@tds.net> Message-ID: print os.environ("OS") - i need to run it on diff platforms that i dont have with me now, but i think it should work fine, otherwise ill get a workaround then post it to the list. thanks -edward -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/84857ef5/attachment.htm From edhotchkiss at gmail.com Tue Oct 25 22:17:16 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Tue, 25 Oct 2005 16:17:16 -0400 Subject: [Tutor] python myspace module? Message-ID: looking to write a myspace wrapper/module. what is the best way (hopefully using the stdlib not an outside module) to connect to a website and (if possible, otherwise ill have to code it?) access forms with GET POST blah blah blah ... thanks! -- edward hotchkiss -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/1bf37ada/attachment.html From alan.gauld at freenet.co.uk Tue Oct 25 22:41:12 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 25 Oct 2005 21:41:12 +0100 Subject: [Tutor] py in a nut References: <1cbf5cf90510241105h7e0375f4pa699ac09c6f46d96@mail.gmail.com> <435DEDF5.1050001@rawflow.com> Message-ID: <01f201c5d9a4$704c26f0$0a01a8c0@xp> > Programming Python, 3E which should be released in December. > > So there is no Advanced Python book on the horizon, which is a shame. > But as you can see, Python in a Nutshell 2nd edition is due out next > March. If PP continues the trend of the 2nd edition it could well be the book you want. The first ed was a beginners book, the second covered a lot of the more advanced topics and I would not be surprised if the 3rd ed dropped any pretense at being an intro - Learning Python fills that role. But I know nothing... :-) Alan G. From dyoo at hkn.eecs.berkeley.edu Tue Oct 25 23:24:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 25 Oct 2005 14:24:53 -0700 (PDT) Subject: [Tutor] python myspace module? In-Reply-To: Message-ID: On Tue, 25 Oct 2005, Ed Hotchkiss wrote: > looking to write a myspace wrapper/module. what is the best way > (hopefully using the stdlib not an outside module) to connect to a > website and (if possible, otherwise ill have to code it?) access forms > with GET POST blah blah blah ... Hi Ed, We do have some rudimentary access by using libraries like urllib and urllib2. Let's look at urllib for the moment: http://www.python.org/doc/lib/module-urllib.html By default, it send GET queries, but if we pass in a data argument to its open() function, it can perform a POST. So for really quick-and-dirty stuff, urllib can do the trick. For anything more sophisticated, we may want to look at some tools like mechanize: http://wwwsearch.sourceforge.net/mechanize/ which can help provide the illusion of a stateful session with a web server. Best of wishes! From edhotchkiss at gmail.com Wed Oct 26 00:30:05 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Tue, 25 Oct 2005 18:30:05 -0400 Subject: [Tutor] downloading remote files Message-ID: is there a method in the stdlib of downloading a remote file via HTTP? or do i need sockets ... -- edward hotchkiss -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/41c464d5/attachment.htm From kent37 at tds.net Wed Oct 26 00:39:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Oct 2005 18:39:29 -0400 Subject: [Tutor] downloading remote files In-Reply-To: References: Message-ID: <435EB421.7070300@tds.net> Ed Hotchkiss wrote: > is there a method in the stdlib of downloading a remote file via HTTP? > or do i need sockets ... for simple needs, you can use urllib: import urllib data = urllib.urlopen('http://www.google.com').read() For more control, see urllib2. As suggested recently, Dive into Python has a good chapter on this which gives you several reasons why the above one-liner is a bad idea :-) http://diveintopython.org/http_web_services/index.html Kent From broek at cc.umanitoba.ca Wed Oct 26 03:44:40 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 25 Oct 2005 20:44:40 -0500 Subject: [Tutor] identify python interpreters platform? In-Reply-To: <435E614A.1070201@tds.net> References: <435E5A44.7020700@tds.net> <435E614A.1070201@tds.net> Message-ID: <435EDF88.10704@cc.umanitoba.ca> Kent Johnson said unto the world upon 2005-10-25 11:46: > Ed Hotchkiss wrote: > >> Well, on windows XP it returns "nt" for os.name >> and for sys.platform it returns win32. how can i determine win2k, >> xp, 9x, etc etc ... > > > I don't know...maybe something in os.environ? > >>> sys.getwindowsversion() (5, 1, 2600, 2, 'Service Pack 2') >>> help(sys.getwindowsversion) Help on built-in function getwindowsversion in module sys: getwindowsversion(...) getwindowsversion() Return information about the running version of Windows. The result is a tuple of (major, minor, build, platform, text) All elements are numbers, except text which is a string. Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP >>> The chm help also says: > This function wraps the Win32 GetVersionEx() function; see the > Microsoft documentation for more information about these fields. > > Availability: Windows. New in version 2.3. > From nephish at xit.net Wed Oct 26 04:10:59 2005 From: nephish at xit.net (nephish) Date: Tue, 25 Oct 2005 21:10:59 -0500 Subject: [Tutor] python myspace module? In-Reply-To: References: Message-ID: <1130292659.11657.3.camel@bitsbam.localdomain> Hey there Ed, if you pull this off, let us know. i have wanted to do this very thing, but just don't have the time. sk On Tue, 2005-10-25 at 14:24 -0700, Danny Yoo wrote: > > On Tue, 25 Oct 2005, Ed Hotchkiss wrote: > > > looking to write a myspace wrapper/module. what is the best way > > (hopefully using the stdlib not an outside module) to connect to a > > website and (if possible, otherwise ill have to code it?) access forms > > with GET POST blah blah blah ... > > Hi Ed, > > We do have some rudimentary access by using libraries like urllib and > urllib2. Let's look at urllib for the moment: > > http://www.python.org/doc/lib/module-urllib.html > > By default, it send GET queries, but if we pass in a data argument to its > open() function, it can perform a POST. So for really quick-and-dirty > stuff, urllib can do the trick. > > > For anything more sophisticated, we may want to look at some tools like > mechanize: > > http://wwwsearch.sourceforge.net/mechanize/ > > which can help provide the illusion of a stateful session with a web > server. > > > Best of wishes! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From challman at gmail.com Wed Oct 26 04:17:28 2005 From: challman at gmail.com (Chris Hallman) Date: Tue, 25 Oct 2005 22:17:28 -0400 Subject: [Tutor] threading issues In-Reply-To: <435C14FA.6090006@tds.net> References: <9f68812f0510221507tb9ef4a6gd83adf836e695d01@mail.gmail.com> <435ACB7B.7080305@tds.net> <9f68812f0510231506w1e1b8955q5d9cabf8454de8a9@mail.gmail.com> <435C14FA.6090006@tds.net> Message-ID: <9f68812f0510251917m282d8ccdqf5a3f2f78d91c965@mail.gmail.com> You're right. I'm inexperienced with classes and threading. The example you gave (www.wellho.net ) was the same example I used as the basis for my script however I wasn't able to get it to work. I couldn't figure out what the -q parameter is (it's not a valid parameter on the *nix I have access to) and when I gave it an IP address range with reachable and unreachable hosts, it reported them all as alive therefore this example script isn't a good example. I was able to Google for more examples. I was finally able to get my script to not show duplicate PINGs. I also realized that my script was not PINGing all the hosts in the input file. Here is my latest version: import os, re, string, sys, threading, time from threading import Thread from time import strftime ms = re.compile("Reply") rpath = (r"c:\utils\network_ping_devices.txt") if os.path.exists(r"c:\utils\network_ping_again.txt"): rpath = (r"c:\utils\network_ping_again.txt") wpath = (r"c:\logs\network_ping.out") tpath = (r"c:\temp\ping.txt") if os.path.exists(tpath): os.remove(tpath) temp = open(tpath, "w") output = open(wpath, "a") output.write("\n" + "Network PING test started -" + strftime(" %H:%M:%S %x") + "\n") output.flush() class PingIT(threading.Thread): def __init__(self,rtr): Thread.__init__(self) self.rtr = rtr def run(self): pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr) pingas = string.join(pingaf.readlines()) if ms.search(pingas): # print (re.sub('\n','',self.rtr)) + " responded." #for debugging return else: pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr) pingas = string.join(pingaf.readlines()) if ms.search(pingas): # print (re.sub('\n','',self.rtr)) + " responded." # for debugging return else: temp.write(re.sub('\n','',self.rtr) + " did not respond.\n") pinglist = [] for rtr in file(rpath): current = PingIT(rtr) pinglist.append(current) current.start() for pingle in pinglist: pingle.join() temp.close() temp = open(tpath, "r") lines = [] for line in temp: lines.append(line.rstrip()) lines.sort() for line in lines: print >>output, line output.write("Network PING test completed -" + strftime(" %H:%M:%S %x") + "\n") output.flush() output.close() All the hosts in the input file are sorted alphabetically but my results were output out of order?! (possibly due to latency in PING responses or some latency in the thread joining; not sure of either). I had to do the crude temp output file so that I could sort the results, but it works!! On 10/23/05, Kent Johnson wrote: > > Chris Hallman wrote: > > > > I made a mistake in my first email..... I meant that I can't get fc to > > write to the file. Here is the error: > > > > Traceback (most recent call last): > > File "thread_test_ping.py", line 37, in ? > > output.write(fc + " failures found.\n") > > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > This is a pretty easy error to understand. It is saying that you can't add > an int and a string. Looking at your code, you are trying to add fc + " > failures found.\n". fc is indeed an int. You have to change it to a string > to be able to add it to another string. You can do this with the str() > function. So the correct statement is > output.write(str(fc) + " failures found.\n") > > > > > I tried the suggestions you made, but I can't get it to work. Is this > > what you meant?: > > No, not quite. > > > > #!/usr/bin/env python > > > > #Let us profile code which uses threads > > import os, re, string, thread, threading, time > > from time import strftime > > #from threading import Thread > > > > class PingThread(threading.Thread): > > def __init__(self, rtr): > > threading.Thread.__init__(self) > > self.rtr = rtr > > The init method initializes a PingThread. It is passed self as an > argument, plus whatever parameters you pass in when you create the > PingThread. You call the superclass constructor and save the value of the > parameter. So far so good...but this next line is creating a PingThread, it > belongs below in your loop. > > > PingThread(rtr).start(rtr) > > > > def run(self): > > Here you should reference self.rtr so you get the value that was stored in > the call to __init__(), and similarly for each reference to rtr in the run > method. > > > pingaf = os.popen('ping -n 1 -w 3 ' + rtr) > > pingas = string.join(pingaf.readlines()) > > if ms.search(pingas): > > print (re.sub('\n','',rtr)) + " responded." #for debugging > > else: > > pingaf = os.popen('ping -n 2 -w 3 ' + rtr) > > pingas = string.join(pingaf.readlines()) > > if ms.search(pingas): > > print (re.sub('\n','',rtr)) + " responded." # for > > debugging > > else: > > fc=fc+1 > > output.write(re.sub('\n','',rtr) + " did not respond.\n") > > > > fc = 0 # failure counter > > ms = re.compile("Reply from") > > rpath = (r"c:\temp\py\network_ping_routers.txt") > > if os.path.exists(r"c:\temp\py\network_ping_again.txt"): > > rpath = (r"c:\temp\py\network_ping_again.txt") > > wpath = (r"c:\temp\py\network_ping.out") > > #os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue > > held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") + > "\n") > > output = open(wpath, "a") > > output.write("\n" + "\n" + "Network PING test started -" + strftime(" > > %H:%M:%S %x") + "\n") > > output.flush() > > threads = [] > > for rtr in file(rpath): > > thread = PingThread() > Here is where you need to call PingThread(rtr) to pass the value of rtr to > the constructor. > > > thread.start() > > threads.append(thread) > > for thread in threads: > > thread.join() > > print fc # for debugging > > output.write(fc + " failures found.\n") > > output.write("\n" + "\n" + "Network PING test completed -" + strftime(" > > %H:%M:%S %x") + "\n") > > output.close() > > I suspect that I am talking over your head and that maybe you are in over > your head a bit here. If you don't understand the basics of classes and > parameter passing you should spend some time with a tutorial that explains > them, for example Alan Gauld's tutorial at > http://www.freenetpages.co.uk/hp/alan.gauld/ > > There is a brief introduction to threading here. It even uses your problem > (pinging multiple servers) as the example. > http://www.wellho.net/solutions/python-python-threads-a-first-example.html > > Kent > http://www.kentsjohnson.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/b655478b/attachment-0001.htm From NEberle at lucasarts.com Wed Oct 26 07:53:58 2005 From: NEberle at lucasarts.com (Nick Eberle) Date: Tue, 25 Oct 2005 22:53:58 -0700 Subject: [Tutor] new user question about while loops Message-ID: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8E@lec-mail1.lucasarts.alllucas.com> Sorry for potential double post, error with first send ---------------------------------------------------------------------- Hello all, I had a new question about python. I am pretty much in tutorial learning stages, but attempting to create sample programs not in my book to learn how to construct scripts. I understand the format of while loops, but is it possible to use the random.randrange function in them? My goal, create a program that flips a coin 100 times, at the end it says the number of times it flipped heads and flipped tails. My dilemia, how do I get this to work with a while loop? I tried intially assigning heads=0 tails=1 then I figured I could just do a while loop and then use the random function each time. At the end it could count the number of times the random generated a 0 or a 1. However I can't seem to construct it in a way that makes or works. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/204c8178/attachment.html From bgailer at alum.rpi.edu Wed Oct 26 07:58:49 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 25 Oct 2005 22:58:49 -0700 Subject: [Tutor] new user question about while loops In-Reply-To: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8E@lec-mail1.lucasar ts.alllucas.com> References: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8E@lec-mail1.lucasarts.alllucas.com> Message-ID: <6.1.2.0.0.20051025225756.033e43f8@mail.mric.net> At 10:53 PM 10/25/2005, Nick Eberle wrote: >Content-class: urn:content-classes:message >Content-Type: multipart/alternative; > boundary="----_=_NextPart_001_01C5D9F1.A836CF4F" > >Sorry for potential double post, error with first send >---------------------------------------------------------------------- >Hello all, > >I had a new question about python. I am pretty much in tutorial learning >stages, but attempting to create sample programs not in my book to learn >how to construct scripts. > >I understand the format of while loops, but is it possible to use the >random.randrange function in them? > >My goal, create a program that flips a coin 100 times, at the end it says >the number of times it flipped heads and flipped tails. > >My dilemia, how do I get this to work with a while loop? I tried intially >assigning > >heads=0 >tails=1 > >then I figured I could just do a while loop and then use the random >function each time. At the end it could count the number of times the >random generated a 0 or a 1. > >However I can't seem to construct it in a way that makes or works. Show us your code, as flawed as it might be. Then we can advise you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/d1304fff/attachment.htm From NEberle at lucasarts.com Wed Oct 26 08:04:08 2005 From: NEberle at lucasarts.com (Nick Eberle) Date: Tue, 25 Oct 2005 23:04:08 -0700 Subject: [Tutor] new user question about while loops Message-ID: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8F@lec-mail1.lucasarts.alllucas.com> print "This is a coin flip game" print "\n100 flips will be made and it will show the amount of times heads or tails came up" import random #assigning variables to track the amount of times heads or tails comes up heads=0 tails=1 flip=100 while flip < 100: flip -= 1 random.randrange(2) if flip < 100: break print "\nThe amount of times tails came up was" , tails , "The amount of times heads came up was" , heads raw_input() ________________________________ From: bob [mailto:bgailer at alum.rpi.edu] Sent: Tue 10/25/2005 10:58 PM To: Nick Eberle; tutor at python.org Subject: Re: [Tutor] new user question about while loops At 10:53 PM 10/25/2005, Nick Eberle wrote: Content-class: urn:content-classes:message Content-Type: multipart/alternative; boundary="----_=_NextPart_001_01C5D9F1.A836CF4F" Sorry for potential double post, error with first send ---------------------------------------------------------------------- Hello all, I had a new question about python. I am pretty much in tutorial learning stages, but attempting to create sample programs not in my book to learn how to construct scripts. I understand the format of while loops, but is it possible to use the random.randrange function in them? My goal, create a program that flips a coin 100 times, at the end it says the number of times it flipped heads and flipped tails. My dilemia, how do I get this to work with a while loop? I tried intially assigning heads=0 tails=1 then I figured I could just do a while loop and then use the random function each time. At the end it could count the number of times the random generated a 0 or a 1. However I can't seem to construct it in a way that makes or works. Show us your code, as flawed as it might be. Then we can advise you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051025/5ae2157e/attachment.html From norman at littletank.org Wed Oct 26 09:29:46 2005 From: norman at littletank.org (Norman Silverstone) Date: Wed, 26 Oct 2005 08:29:46 +0100 Subject: [Tutor] new user question about while loops In-Reply-To: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8E@lec-mail1.lucasarts.alllucas.com> References: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8E@lec-mail1.lucasarts.alllucas.com> Message-ID: <1130311786.14539.5.camel@localhost.localdomain> > I understand the format of while loops, but is it possible to use the > random.randrange function in them? > > My goal, create a program that flips a coin 100 times, at the end it > says the number of times it flipped heads and flipped tails. I am also trying to learn python and came across this very exercise. The answer to your question is yes and, if you like I will post my attempt at the code. Just for fun, I also got the process to repeat itself 10 times and report the results. It was fun doing it and very encouraging when it worked. Norman From johan at accesstel.co.za Wed Oct 26 09:42:04 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 26 Oct 2005 09:42:04 +0200 Subject: [Tutor] new user question about while loops In-Reply-To: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8F@lec-mail1.lucasarts.alllucas.com> References: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8F@lec-mail1.lucasarts.alllucas.com> Message-ID: <435F334C.3060807@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051026/d54559fe/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Oct 26 10:07:01 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 26 Oct 2005 01:07:01 -0700 (PDT) Subject: [Tutor] new user question about while loops In-Reply-To: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8E@lec-mail1.lucasarts.alllucas.com> Message-ID: On Tue, 25 Oct 2005, Nick Eberle wrote: > My goal, create a program that flips a coin 100 times, at the end it > says the number of times it flipped heads and flipped tails. Hi Nick, Do you might if we simplify the problem slightly? Say that you're only flipping the coin two times. Can you write code to say how many times it flips heads and tails? Once you get that working, then modify that program to do it for three coins, then four. The idea is to try really small cases first, just so you get a better sense of the problem. From your initial code, it looks like you might be getting stuck on another concept besides loops, so let's see if we can get that cleared up first. Please feel free to ask questions. Good luck! From dyoo at hkn.eecs.berkeley.edu Wed Oct 26 10:12:01 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 26 Oct 2005 01:12:01 -0700 (PDT) Subject: [Tutor] new user question about while loops In-Reply-To: Message-ID: > > My goal, create a program that flips a coin 100 times, at the end it > > says the number of times it flipped heads and flipped tails. > > Do you might if we simplify the problem slightly? Say that you're only > flipping the coin two times. Can you write code to say how many times > it flips heads and tails? Once you get that working, then modify that > program to do it for three coins, then four. Duh: I forgot to add: can you try to do the above without loops? Since there's so little coin flipping going on, the code to do this shouldn't be too long to write, even without loops. (... although it will get longer for each additional coin we flip. When we want to scale our solution to more coins, then that's where loops can come into play.) From ajikoe at gmail.com Wed Oct 26 10:28:47 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 26 Oct 2005 10:28:47 +0200 Subject: [Tutor] new user question about while loops In-Reply-To: References: Message-ID: Hello, I'm not so sure about your problem, but probably this code can help.... sumHead, sumTail = 0,0 listHeadTime = [] listTailTime = [] for i in range(100): time_start = time.clock() coin = random.randint(0,1) # 0 head, 1 tail time_stop = time.clock() time_duration = time_stop - time_start if coin == 0: sumHead += 1 listHeadTime.append(time_duration) else: sumTail += 1 listTailTime.append(time_duration) print sumHead, sumTail print listHeadTime print listTailTime Cheers, pujo On 10/26/05, Danny Yoo wrote: > > > > > > My goal, create a program that flips a coin 100 times, at the end it > > > says the number of times it flipped heads and flipped tails. > > > > Do you might if we simplify the problem slightly? Say that you're only > > flipping the coin two times. Can you write code to say how many times > > it flips heads and tails? Once you get that working, then modify that > > program to do it for three coins, then four. > > Duh: I forgot to add: can you try to do the above without loops? Since > there's so little coin flipping going on, the code to do this shouldn't be > too long to write, even without loops. > > (... although it will get longer for each additional coin we flip. When > we want to scale our solution to more coins, then that's where loops can > come into play.) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051026/86030612/attachment.htm From alan.gauld at freenet.co.uk Wed Oct 26 10:53:08 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 26 Oct 2005 09:53:08 +0100 Subject: [Tutor] new user question about while loops References: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8F@lec-mail1.lucasarts.alllucas.com> Message-ID: <026f01c5da0a$b06a6ce0$0a01a8c0@xp> As Danny says, try breaking the problem into chunks and solving each bit separately. I'll provide a few comments on your code in the meantime but try the "evolving soluition" approach too. #assigning variables to track the amount of times heads or tails comes up heads=0 tails=1 AG> Why not make both zero, after all there have been no flips so far! flip=100 while flip < 100: AG> flip is never less than 100 because you set it to 100! AG> Thus you never enter the loop... flip -= 1 random.randrange(2) if flip < 100: break AG> And if you did after the first time through you make flip equal 99 AG> so that it will always exit the loop(break) here so it would only run once! AG> Try getting a while loop to run 100 times printing out the loop test value. AG> Or better stuill, since you know how many times you want the lopp to AG> run use a for loop instead: AG> for loop in range(100): AG> # loop code here print "\nThe amount of times tails came up was" , tails , "The amount of times heads came up was" , heads AG> But the only values you assign to head/tails are the initial 1 and 0. AG> Try Danny;'s suggestion of flipping the coin twice... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Oct 26 11:59:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Oct 2005 05:59:14 -0400 Subject: [Tutor] threading issues In-Reply-To: <9f68812f0510251917m282d8ccdqf5a3f2f78d91c965@mail.gmail.com> References: <9f68812f0510221507tb9ef4a6gd83adf836e695d01@mail.gmail.com> <435ACB7B.7080305@tds.net> <9f68812f0510231506w1e1b8955q5d9cabf8454de8a9@mail.gmail.com> <435C14FA.6090006@tds.net> <9f68812f0510251917m282d8ccdqf5a3f2f78d91c965@mail.gmail.com> Message-ID: <435F5372.4040706@tds.net> Chris Hallman wrote: > I was finally able to get my script to not show duplicate PINGs. I also > realized that my script was not PINGing all the hosts in the input file. Congratulations on getting it to work! See below for a few notes. > Here is my latest version: > > > import os, re, string, sys, threading, time > from threading import Thread > from time import strftime > > ms = re.compile("Reply") You don't need a regular expression for this, you could use the simpler if "Reply" in pingas > rpath = (r"c:\utils\network_ping_devices.txt") > > if os.path.exists(r"c:\utils\network_ping_again.txt"): > rpath = (r"c:\utils\network_ping_again.txt") > wpath = (r"c:\logs\network_ping.out") > tpath = (r"c:\temp\ping.txt") > if os.path.exists(tpath): > os.remove(tpath) > temp = open(tpath, "w") > output = open(wpath, "a") > output.write("\n" + "Network PING test started -" + strftime(" %H:%M:%S > %x") + "\n") > output.flush() > > class PingIT(threading.Thread): > def __init__(self,rtr): > Thread.__init__(self) > self.rtr = rtr > > def run(self): > pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr) > pingas = string.join(pingaf.readlines()) > if ms.search(pingas): > # print (re.sub('\n','',self.rtr)) + " responded." #for > debugging > return > else: > pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr) > pingas = string.join(pingaf.readlines()) > if ms.search(pingas): > # print (re.sub('\n','',self.rtr)) + " responded." # > for debugging You don't need a regex for simple string replacements, either - you can use self.rtr.replace('\n', '') In this case the \n is at the end of the string - it is included in the lines you read from the file - so you could also use self.rtr.strip(). But even better would be to strip the '\n' from rtr when you read it from the file below, then you wouldn't have to deal with it everywhere else. > return > else: > temp.write(re.sub('\n','',self.rtr) + " did not respond.\n") Instead of writing the results to a file you could accumulate them in a list and sort the list. Make a global failed = [] before you start any threads, then use failed.append(re.sub('\n','',self.rtr) + " did not respond.") > > pinglist = [] > for rtr in file(rpath): Here you should say rtr = rtr.strip() to get rid of that annoying trailing newline > current = PingIT(rtr) Yes, that's exactly right - you pass the value of rtr as a parameter to the thread so it doesn't matter that the global value changes. > pinglist.append(current) > current.start() > > for pingle in pinglist: > pingle.join() > > temp.close() > temp = open(tpath, "r") > lines = [] > for line in temp: > lines.append(line.rstrip()) > lines.sort() The sort should be outside the loop, you only have to sort once. If you use the failed list as I suggest above, here you just need failed.sort() then for line in failed: > for line in lines: > print >>output, line > > output.write("Network PING test completed -" + strftime(" %H:%M:%S %x") > + "\n") > output.flush() > output.close() > > > All the hosts in the input file are sorted alphabetically but my results > were output out of order?! (possibly due to latency in PING responses or > some latency in the thread joining; not sure of either). I had to do the > crude temp output file so that I could sort the results, but it works!! Using threads introduces some indeterminance into the program. You can't be sure that the threads will run in the order that you start them, or that they will run to completion without interruption. And since the ping itself can take different amounts of time that affects the order in which they complete also. Kent -- http://www.kentsjohnson.com From norman at littletank.org Wed Oct 26 12:19:14 2005 From: norman at littletank.org (Norman Silverstone) Date: Wed, 26 Oct 2005 11:19:14 +0100 Subject: [Tutor] new user question about while loops In-Reply-To: <435F334C.3060807@accesstel.co.za> References: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8F@lec-mail1.lucasarts.alllucas.com> <435F334C.3060807@accesstel.co.za> Message-ID: <1130321954.12098.6.camel@localhost.localdomain> This may not be up to the standard of the more experienced programmer but here is my effort. An added bit is the ability to go on using the code until you are fed up. #To check the computers odds and evens import random anothergo = "y" while(anothergo != "n"): oddsevens = random.randrange(2) odd = 0 even = 0 tries = 0 while(tries != 100): oddevens = random.randrange(2) if (oddevens == 0): even += 1 else: odd += 1 tries += 1 print "In %d tries there were %d odds and %d evens" % (tries, odd, even) anothergo = raw_input("Have another go y/n - ") Hope you like it. Norman From johan at accesstel.co.za Wed Oct 26 14:00:13 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 26 Oct 2005 14:00:13 +0200 Subject: [Tutor] os command Message-ID: <435F6FCD.4090704@accesstel.co.za> I have script that calls a system command that I want to run for 5 minutes. """ import os cmd = 'tcpdump -n -i eth0' os.system(cmd) """ I can start a timer after the cmd is issued, but I don't know how to send a control signal to stop the command after I issued it. This is normally from the shell ^c. This cmd my run in more than one thread on different interfaces and I don't whant all of then stopped at once. I think the best way is to make a thread for each interface where the cmd can be issued and stopped without the danger of stopping he wrong thread. Can anybody help? Thanks Johan From kent37 at tds.net Wed Oct 26 14:19:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Oct 2005 08:19:40 -0400 Subject: [Tutor] os command In-Reply-To: <435F6FCD.4090704@accesstel.co.za> References: <435F6FCD.4090704@accesstel.co.za> Message-ID: <435F745C.6020104@tds.net> Johan Geldenhuys wrote: > I have script that calls a system command that I want to run for 5 minutes. > """ > import os > cmd = 'tcpdump -n -i eth0' > os.system(cmd) > """ > > I can start a timer after the cmd is issued, but I don't know how to > send a control signal to stop the command after I issued it. This is > normally from the shell ^c. This is problematic. In general there is no clean way to kill a thread in Python. The usual approach is to set a flag which the thread checks but this won't work for you. A recent thread in comp.lang.python has some discussion and suggestions but it is inconclusive: http://groups.google.com/group/comp.lang.python/browse_frm/thread/94281f5a797489b1/ebca44930a016f74?q=os.system+thread&rnum=5&hl=en#ebca44930a016f74 Kent -- http://www.kentsjohnson.com From johan at accesstel.co.za Wed Oct 26 15:49:13 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 26 Oct 2005 15:49:13 +0200 Subject: [Tutor] os command In-Reply-To: <435F745C.6020104@tds.net> References: <435F6FCD.4090704@accesstel.co.za> <435F745C.6020104@tds.net> Message-ID: <435F8959.8020903@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051026/6713bd92/attachment.htm From vanzwieten at science-and-technology.nl Wed Oct 26 15:55:50 2005 From: vanzwieten at science-and-technology.nl (Joris van Zwieten) Date: Wed, 26 Oct 2005 15:55:50 +0200 (CEST) Subject: [Tutor] packages,modules, and module attributes Message-ID: <34977.217.77.152.33.1130334950.squirrel@control.prolocation.net> Hi all, I've a question, essentially about the import statement. Suppose I have two python files, a.py and b.py: a.py ---- flag = True def getFlag(): return flag b.py ---- from a import * now, in the interpreter: >>> import b >>> b.flag True >>> b.flag=False >>> b.flag False >>> b.getFlag() True this is probably related to namespaces? I find it very confusing, because after the import, b _does_ have an attribute called 'flag' (try dir(b)), which has the value that was assigned to it in a.py. (i.e. the second statement in the interpreter does not inject a new variable 'flag' into b.) however, modifications to 'flag' are not 'seen' by functions defined in a.py, called from b (i.e. b.getFlag()). could someone explain what is happening here? thanks, Joris van Zwieten From srini_iyyer_bio at yahoo.com Wed Oct 26 17:11:06 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 26 Oct 2005 08:11:06 -0700 (PDT) Subject: [Tutor] Glossory of terms in Python In-Reply-To: <34977.217.77.152.33.1130334950.squirrel@control.prolocation.net> Message-ID: <20051026151106.89504.qmail@web31602.mail.mud.yahoo.com> Dear python experts, I am a novice python learner and aspiring to become decent python programmer. I am reading 'Learning Python' by Mark Lutz et al. and it is one of the good books that I find in addition to Alan Gauld's book 'Learn to Program Using Python'. While reading these books step-by-step and progressing ahead, I feel that some of the terms are highly volatile. In simple terms, while reading about lambda functions after reading a lot of stuff before, I am unable to clearly define what is an expression and what is a statement. Although, I know the difference and what exactly they mean inherently in my mind, I am unable to comprehend and move ahead. This reamins a stumblick block. What I feel is that to overcome this stumbling block, I need a glossory of terms at the end of the book that defines the critical terms that are very easy to programmer paralance such as : a. Statement - A statement is .......... . For eg. xxxxxx is called a statment b. Expression - An expression is something ........ . For example, def f(x): xxx return y is an expression. c. Jump table: A jump table is a table where ...... d. Attribute : An attribute is a variable that is used as an input to a function. For eg. def Xabl(a): here a is an attribute. Such a glossory of terms would be a great gift from python experts. This would help novice and learning programmers who never talked the terms of computing language in daily english. Whenever we come across these terms I would refer to this glossory and refresh my brain time to time. I would love to paste this glossory on my wall and gawk at them daily. What is your opinion ? Thanks Srini --- Joris van Zwieten wrote: > Hi all, > > I've a question, essentially about the import > statement. Suppose I have > two python files, a.py and b.py: > > a.py > ---- > flag = True > > def getFlag(): > return flag > > b.py > ---- > from a import * > > now, in the interpreter: > > >>> import b > >>> b.flag > True > >>> b.flag=False > >>> b.flag > False > >>> b.getFlag() > True > > this is probably related to namespaces? I find it > very confusing, because > after the import, b _does_ have an attribute called > 'flag' (try dir(b)), > which has the value that was assigned to it in a.py. > (i.e. the second > statement in the interpreter does not inject a new > variable 'flag' into > b.) however, modifications to 'flag' are not 'seen' > by functions defined > in a.py, called from b (i.e. b.getFlag()). > could someone explain what is happening here? > thanks, > > > Joris van Zwieten > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Yahoo! FareChase: Search multiple travel sites in one click. http://farechase.yahoo.com From bgailer at alum.rpi.edu Wed Oct 26 17:16:48 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 26 Oct 2005 08:16:48 -0700 Subject: [Tutor] new user question about while loops In-Reply-To: <026f01c5da0a$b06a6ce0$0a01a8c0@xp> References: <3E2726BAB3A69E4BB7FD1C4D4C689A9D0436BE8F@lec-mail1.lucasarts.alllucas.com> <026f01c5da0a$b06a6ce0$0a01a8c0@xp> Message-ID: <6.1.2.0.0.20051026080036.03480e98@mail.mric.net> Thank you for posting your code. That really helps us see where you are and therefore how to help. I encourage you to "desk check" your code: pretend you are the computer: write down the values of variables and expressions as things change. Evaluate each statement to see what it does. Example: heads tails flip flip < 100 while flip < 100: 0 1 100 False loop not entered program ends. I hope you understand why the loop is not entered. If not please (re)read an explanation of while. Noticing that you would alter the loop condition. To do that you need to ask "When do I want the loop to end?" Let's say you changed it to: while flip <= 100. Now your "desk check" would look like: heads tails flip flip <= 100 while flip <= 100: 0 1 100 True loop entered 99 random.randrange(2) has no effect since nothing is done with the value returned flip < 100 break True leaves the loop print "\nThe amount of times tails came up was" , tails , "The amount of times heads came up was" , heads results in: The amount of times tails came up was 1 The amount of times heads came up was 0 I hope this helps. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051026/8d41473e/attachment.html From NEberle at lucasarts.com Wed Oct 26 17:23:35 2005 From: NEberle at lucasarts.com (Nick Eberle) Date: Wed, 26 Oct 2005 08:23:35 -0700 Subject: [Tutor] new user question about while loops Message-ID: <3E2726BAB3A69E4BB7FD1C4D4C689A9D04B46FA8@lec-mail1.lucasarts.alllucas.com> Ahh makes much more sense, thanks for all the help! I'll go back and rework it, keeping in mind trying to solve each piece separately. Thanks again all. -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: Wednesday, October 26, 2005 1:53 AM To: Nick Eberle; bob; tutor at python.org Subject: Re: [Tutor] new user question about while loops As Danny says, try breaking the problem into chunks and solving each bit separately. I'll provide a few comments on your code in the meantime but try the "evolving soluition" approach too. #assigning variables to track the amount of times heads or tails comes up heads=0 tails=1 AG> Why not make both zero, after all there have been no flips so far! flip=100 while flip < 100: AG> flip is never less than 100 because you set it to 100! AG> Thus you never enter the loop... flip -= 1 random.randrange(2) if flip < 100: break AG> And if you did after the first time through you make flip equal 99 AG> so that it will always exit the loop(break) here so it would only run once! AG> Try getting a while loop to run 100 times printing out the loop test value. AG> Or better stuill, since you know how many times you want the lopp to AG> run use a for loop instead: AG> for loop in range(100): AG> # loop code here print "\nThe amount of times tails came up was" , tails , "The amount of times heads came up was" , heads AG> But the only values you assign to head/tails are the initial 1 and 0. AG> Try Danny;'s suggestion of flipping the coin twice... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From norman at littletank.org Wed Oct 26 18:21:03 2005 From: norman at littletank.org (Norman Silverstone) Date: Wed, 26 Oct 2005 17:21:03 +0100 Subject: [Tutor] new user question about while loops In-Reply-To: <3E2726BAB3A69E4BB7FD1C4D4C689A9D04B46FA8@lec-mail1.lucasarts.alllucas.com> References: <3E2726BAB3A69E4BB7FD1C4D4C689A9D04B46FA8@lec-mail1.lucasarts.alllucas.com> Message-ID: <1130343663.12098.12.camel@localhost.localdomain> Yes I am going through the Michael Dawson book. Also, I am working from the Alan Gauld book to reinforce my attempts at learning python. Norman From alan.gauld at freenet.co.uk Wed Oct 26 19:32:47 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 26 Oct 2005 18:32:47 +0100 Subject: [Tutor] packages,modules, and module attributes References: <34977.217.77.152.33.1130334950.squirrel@control.prolocation.net> Message-ID: <02a601c5da53$48496f00$0a01a8c0@xp> > I've a question, essentially about the import statement. Suppose I have > two python files, a.py and b.py: OK, I'll have a go although I'm only 90% sure I've got it right... > a.py > ---- > flag = True > > def getFlag(): > return flag > > b.py > ---- > from a import * This imports the names from a. Thus b now has a name flag that points to TRue and a name getFlag that points to the function in a. > now, in the interpreter: > >>>> import b >>>> b.flag > True >>>> b.flag=False >>>> b.flag > False This first reads the value imported from a then creates a new name in b that overwrites the imported value and sets it to False. >>>> b.getFlag() > True This calls the function in a which returns the value from a which is still set to True. > this is probably related to namespaces? I find it very confusing, It is to do with namespaces and shows why two bad practices you have used are indeed bad practices! :-) First if you had used import a in b instead of from a import * All would have worked as you expected because you would have been forced to specify b.a.flag etc. Secondly relying on a global variable in the function getFlag meant that when you imported getFLag the function object remained in a and accessed the variable flag in a. If you had passed the name of the flag to getFlag as a parameter then it would have worked as expected - although only returning the value you already had! (But if Flag were a more complex object it would then make sense!) So as usual the advice "do not use from X import *" holds. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From edhotchkiss at gmail.com Wed Oct 26 19:44:10 2005 From: edhotchkiss at gmail.com (Ed Hotchkiss) Date: Wed, 26 Oct 2005 13:44:10 -0400 Subject: [Tutor] urllib2 & form submit Message-ID: i am trying to write a class to log into myspace. either i am doing something wrong, or... myspace is requiring that i accept a cookie, or create a session? however i am new to urllib and urllib2. heres my code: correctly formatted code is at: http://www.jeah.net/~marla/myspace.py #!/bin/env python # ----------- import sgmllib import urllib import urllib2 import urlparse # ----------- class myspace: # login to one myspace account def login(self, user, password): the_url = " http://viewmorepics.myspace.com/index.cfm?fuseaction=login.process" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = { 'User-Agent' : user_agent } values = { 'email' : user, 'password' : password } data = urllib.urlencode(values) req = urllib2.Request(the_url, data) try: handle = urllib2.urlopen(req) except IOError: print 'Something went wrong' else: x = handle.read() temp = open("edspage.html", "w") temp.write(x) temp.close() # add friend based on users URL def addFriend(self, friendURL): return 1 # delete friend based on users URL def deleteFriend(self, friendURL): return 1 # post a friends bulletin def postBulletin(self, bulletin): return 1 # read all bulletins into a tuple named 'bulletins' def readBulletins(self): bulletins = {} # a photo to your profile def addPhoto(self, photoLocation): return 1 # delete a photo from your profile def deletePhoto(self, photoID): return 1 # return a tuple of people that match your browsing criteria def browse(self, sex, ageBegin, ageEnd, gayBiStraight, zipCode, zipRange): return 1 # stick someones myspace page into an html file def grabUserPageHTML(self, xURL, outputFile): req = urllib2.Request(xURL) handle = urllib2.urlopen(req) thepage = handle.read() temp = open(outputFile, "w") temp.write(thepage) temp.close() def logout(self): return 1 # ----------- # example of class usage me = myspace() me.login("xxx at gmail.com", "password here") #me.grabUserPageHTML("http://www.myspace.com/blahuser/","blah.html") #me.logout() # ----------- EOF the form uses POST method. the action for the form is the_url. what am i doing wrong? all that the script does, is to refer me to another login page. is it detecting somehow that i am a script and not a users browser? any help would be appreciate, lost in the water here. -- edward hotchkiss -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051026/0166ff2c/attachment.htm From alan.gauld at freenet.co.uk Wed Oct 26 19:50:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 26 Oct 2005 18:50:54 +0100 Subject: [Tutor] Glossory of terms in Python References: <20051026151106.89504.qmail@web31602.mail.mud.yahoo.com> Message-ID: <02aa01c5da55$d00019b0$0a01a8c0@xp> > While reading these books step-by-step and progressing > ahead, I feel that some of the terms are highly > volatile. In simple terms, while reading about lambda > functions after reading a lot of stuff before, I am > unable to clearly define what is an expression and > what is a statement. Good catch. One of the things I tried very hard to do was define all these computer terms as I used them. But obviously I missed a few! An expression is anything that can go on the right hand side of an assignment. ie it can be evaluated. A statement is a little more tricky since it varies slightly from language to language. Basically its any single line that can be typed into the Python >>> prompt without raising an error (including multiple lines where the \ character or unmatched brackets are used!) Statements may be expressions or include expressions. Thus var = E is a statement containing the expression E someFunction() is both a statement and an expression! if E1 >- E2: print 42 is a statement that utilised two expressions E1 and E2 to form a third expression (E1 >=E2) the result of which determines the outcome of the statement. Thats not a rigorous definition, for that you should read the language reference in the documentation. But hoppefully goves a flavour of the meanings. > Although, I know the difference and what exactly they > mean inherently in my mind, I am unable to comprehend > and move ahead. This reamins a stumblick block. > a. Statement - A statement is .......... . For eg. > xxxxxx is called a statment > b. Expression - An expression is something ........ . > For example, def f(x): xxx return y is an expression. actually in that example only y is an expression, the rest are statements! > c. Jump table: A jump table is a table where ...... I don't cover jump tables in my tutor but if I did I'd certainly define it :-) > d. Attribute : An attribute is a variable that is used > as an input to a function. For eg. def Xabl(a): here a > is an attribute. Nope a is a parameter. The value passed in when you call XAbl() is an argument. An attribute is an internal field of an object, usially a data field but sometimes methods are called attributes too. > Such a glossory of terms would be a great gift from > python experts. Actually it would be good for programmers in geneal. The best I can think of is the Wikipedia. For example on the difference between statements and expressions see: http://en.wikipedia.org/wiki/Statement_%28programming%29 It certainly dscribes all the terms you have listed so far... > This would help novice and learning and programmers > who never talked the terms of computing language in > daily english. It sounds like a great idea and would encourage you to start one straight way. Tell the usenet community and you will instantly receive lots of 'feedback'. Don't take any of it personally but use it to improve your site. You should fairly quickly become the owner of a frequently visited and useful internet resource. I mean it, just do it and you will have contributed. You might even become an "internet hero" :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From hugonz-lists at h-lab.net Thu Oct 27 00:07:38 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 26 Oct 2005 16:07:38 -0600 Subject: [Tutor] os command In-Reply-To: <435F6FCD.4090704@accesstel.co.za> References: <435F6FCD.4090704@accesstel.co.za> Message-ID: <435FFE2A.8040105@h-lab.net> Hi, os.system will return the errorval of the application. You need to 1) get the pid of the child process 2) kill it using os.kill(os.SIGTERM) 3) reap the killed process This is all in unix/linux, of course. what I do (untested, please check order of args and correct usage of exec): pid = os.fork() if pid == 0: #child process os.execvp("tcpdump", "tcpdump", "-n", "-i", "eth0") else: #parent time.sleep(5) os.kill(pid, os.SIGTERM) os.waitpid(pid, 0) #wait for process to end Johan Geldenhuys wrote: > I have script that calls a system command that I want to run for 5 minutes. > """ > import os > cmd = 'tcpdump -n -i eth0' > os.system(cmd) > """ > > I can start a timer after the cmd is issued, but I don't know how to > send a control signal to stop the command after I issued it. This is > normally from the shell ^c. > > This cmd my run in more than one thread on different interfaces and I > don't whant all of then stopped at once. I think the best way is to make > a thread for each interface where the cmd can be issued and stopped > without the danger of stopping he wrong thread. > > Can anybody help? > > Thanks > > Johan > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Oct 27 00:52:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Oct 2005 18:52:04 -0400 Subject: [Tutor] urllib2 & form submit In-Reply-To: References: Message-ID: <43600894.4030002@tds.net> Ed Hotchkiss wrote: > i am trying to write a class to log into myspace. either i am doing > something wrong, or... myspace is requiring that i accept a cookie, or > create a session? however i am new to urllib and urllib2. It's very likely that myspace is returning a cookie from the login, this is a common way to handle login sessions. You have to install an HTTPCookieProcessor into urllib2. In your setup code before you call urllib2.urlopen(), put these two lines: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) Now when you use urllib2.urlopen() it will save any cookies returned by the server, and send them in future requests. There is an article on cookies at www.voidspace.org.uk. The site seems to be down now but the Google cache version is here: http://64.233.161.104/search?q=cache:24L65pecYJ0J:www.voidspace.org.uk/python/articles/cookielib.shtml+httpcookieprocessor&hl=en&client=firefox-a The article is overly complicated because it shows how to use an older cookie library as well as urllib2. You can just focus on the urllib2 part. Kent > > heres my code: > correctly formatted code is at: http://www.jeah.net/~marla/myspace.py > > #!/bin/env python > > # ----------- > > import sgmllib > import urllib > import urllib2 > import urlparse > > # ----------- > > class myspace: > > # login to one myspace account > def login(self, user, password): > the_url = > "http://viewmorepics.myspace.com/index.cfm?fuseaction=login.process" > user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > headers = { 'User-Agent' : user_agent } > values = { 'email' : user, > 'password' : password } > data = urllib.urlencode(values) > req = urllib2.Request(the_url, data) > try: > handle = urllib2.urlopen (req) > except IOError: > print 'Something went wrong' > else: > x = handle.read() > temp = open("edspage.html", "w") > temp.write(x) > temp.close() > > # add friend based on users URL > def addFriend(self, friendURL): > return 1 > > # delete friend based on users URL > def deleteFriend(self, friendURL): > return 1 > > # post a friends bulletin > def postBulletin(self, bulletin): > return 1 > > # read all bulletins into a tuple named 'bulletins' > def readBulletins(self): > bulletins = {} > > # a photo to your profile > def addPhoto(self, photoLocation): > return 1 > > # delete a photo from your profile > def deletePhoto(self, photoID): > return 1 > > # return a tuple of people that match your browsing criteria > def browse(self, sex, ageBegin, ageEnd, gayBiStraight, zipCode, zipRange): > return 1 > > # stick someones myspace page into an html file > def grabUserPageHTML(self, xURL, outputFile): > req = urllib2.Request(xURL) > handle = urllib2.urlopen(req) > thepage = handle.read() > temp = open(outputFile, "w") > temp.write (thepage) > temp.close() > > def logout(self): > return 1 > > # ----------- > > # example of class usage > > me = myspace() > me.login("xxx at gmail.com ", "password here") > #me.grabUserPageHTML("http://www.myspace.com/blahuser/","blah.html > ") > #me.logout() > > # ----------- > EOF > > > the form uses POST method. the action for the form is the_url. what am i > doing wrong? all that the script does, is to refer me to another login > page. is it detecting somehow that i am a script and not a users > browser? any help would be appreciate, lost in the water here. > > -- > edward hotchkiss > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://www.kentsjohnson.com From ukc802591034 at btconnect.com Thu Oct 27 00:53:03 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Wed, 26 Oct 2005 23:53:03 +0100 Subject: [Tutor] Matrix References: <1d987df30510242126p331f2cfat1420f13c1c726ed1@mail.gmail.com> Message-ID: This doesn't seem to have been answered... "Shi Mu" wrote in message news:1d987df30510242126p331f2cfat1420f13c1c726ed1 at mail.gmail.com... >I can not understand the use of "cell in row" for two times in the code: > > # convert the matrix to a 1D list > matrix = [[13,2,3,4,5],[0,10,6,0,0],[7,0,0,0,9]] > items = [cell for row in matrix for cell in row] > print items Lets expand the list comprehension: matrix = [[13,2,3,4,5],[0,10,6,0,0],[7,0,0,0,9]] items = [] for row in matrix: for cell in row: items.append(cell) print items Does that explain whats going on? Its just nesting another for loop. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From missive at hotmail.com Thu Oct 27 01:06:03 2005 From: missive at hotmail.com (Lee Harr) Date: Thu, 27 Oct 2005 03:36:03 +0430 Subject: [Tutor] Python as Application Message-ID: >My son is learning something about using a spreadsheet - extremely >useful and I support it 100%. That he thinks what he is learning is >Excel is absolutely unforgivable, in terms of my understanding of >ethical norms that once prevailed in an institute of higher education. > I guess it depends on whether that is what he was taught or if he was ever taught about alternatives. If this is an advanced class and was billed as "learn all the details about Excel" that's fine. If this is an introductory course I believe it should really start off with ... Excel is a spreadsheet. There are many spreadsheet applications available. All spreadsheets share these common traits .... >We understand that all the functionality he will ever need from Excel is >available for free in other spreadsheet software. > Probably. Anything beyond the common spreadsheet functions is almost certainly better done another way. >Do I care that he is within an institution that has lost its bearings on >fundamental matters of academic ethics. > Of course. More frightening to me than the ubiquitous use of MS Office is the omnipresence of windows. Every time a student sits down in front of KDE in our lab and says "Where is the internet?" I can only cringe. Microsoft may not own the internet, but that is not what we are teaching. I seriously get about 10% of users who are unable to see any other browser as performing the same function as internet explorer. If "what is a spreadsheet?" is pretty scary. "What is a browser?" is downright terrifying. >Do I care that I am made to feel that this point of view is somehow >radical on a educational forum that is an offshoot of an open source >software community. > Hmm... more like "preaching to the choir" isn't it? _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From rob at customdatasoft.com Thu Oct 27 01:11:35 2005 From: rob at customdatasoft.com (Rob Dowell) Date: Wed, 26 Oct 2005 18:11:35 -0500 Subject: [Tutor] Tkinter problem (.create_image) Message-ID: <43600D27.2090408@customdatasoft.com> I am having a problem with Tkinter. The goal is a program that will copy images from one folder to another then delete them from the source dir after it is verified that they made it to the target dir. I have the base functionality figured out (comments on that are welcome of course). Now I want to have a gui that shows a small thumbnail of the image as it is copied. Right now everything works fine except that the gui only shows the last picture that is copied. Here is the code: from Tkinter import * import PIL.Image as image import PIL.ImageTk as imagetk import ConfigParser import os import time import shutil class MyApp: def __init__(self, parent): self.myParent = parent self.myContainer1 = Frame(parent) self.myContainer1.pack() self.button1 = Button(self.myContainer1) self.button1.configure(text="Copy Pics") self.button1.pack() self.button1.bind("", self.button1Click) self.tv1 = StringVar() self.tv1.set("Ready to copy.") self.label1 = Label(self.myContainer1) self.label1.configure(textvariable = self.tv1) self.label1.pack() self.canvas1 = Canvas(self.myContainer1) self.canvas1.configure(width=200, height=200, bg='yellow') self.canvas1.pack() def button1Click(self, event): files = {} print "Here" #Import config information from the ini file configfile = "./GetPics.ini" config = ConfigParser.ConfigParser() config.read(configfile) sourcedirloc = config.get("GetPics", "sourcedir") targetdirloc = config.get("GetPics", "targetdir") deleteold = config.get("GetPics", "deleteold") enddict = {'1':'st', '2':'nd', '3':'rd', '4':'th', '5':'th', '6':'th', '7':'th', '8':'th', '9':'th', '0':'th'} #OPen the source dir and get a list of the files making the new name and path as you go sourcefiles = os.listdir(sourcedirloc) files = {} for file in sourcefiles: filepath = sourcedirloc + "/" + file if files.has_key(filepath): #The file is duplicated? pass else: files[filepath] = {} files[filepath]['originalname'] = file files[filepath]['modtuple'] = time.localtime(os.stat(filepath).st_mtime) files[filepath]['size'] = os.stat(filepath).st_size files[filepath]['monthdir'] = targetdirloc + "/" + time.strftime('%Y-%m', time.localtime(os.stat(filepath).st_mtime)) files[filepath]['daydir'] = files[filepath]['monthdir'] + "/" + time.strftime('%d', time.localtime(os.stat(filepath).st_mtime)) + enddict[time.strftime('%d', time.localtime(os.stat(filepath).st_mtime))[len(time.strftime('%d', time.localtime(os.stat(filepath).st_mtime)))-1]] files[filepath]['newname'] = files[filepath]['daydir'] + "/" + time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(os.stat(filepath).st_mtime)) + os.path.splitext(file)[1] #Now check to see if a file with this name already exists and increment the name if it does n = 1 while os.path.isfile(files[filepath]['newname']): files[filepath]['newname'] = os.path.splitext(files[filepath]['newname'])[0] + "-" + str(n) + os.path.splitext(files[filepath]['newname'])[1] n += 1 #Copy all of the file to the target dir for file in files.keys(): #Check for the dir and create it if needed: if not os.path.isdir(files[file]['monthdir']): self.tv1.set("Creating (monthdir) " + files[file]['monthdir']) os.mkdir(files[file]['monthdir']) if not os.path.isdir(files[file]['daydir']): self.tv1.set("Creating (daydir) " + files[file]['daydir']) os.mkdir(files[file]['daydir']) #copy the file self.tv1.set("Copying " + file + " to " + files[file]['newname']) # DISPLAY THE THUMBNAIL self.DisplayImage(file) shutil.copy2(file, files[file]['newname']) #Go back and remove the sorce files checking that the target file exists first for file in files.keys(): if os.stat(files[file]['newname']).st_size == files[file]['size'] and deleteold.lower() == "true": print deleteold.lower() self.tv1.set("Deleting " + file) os.remove(file) else: self.tv1.set("There was an error with " + file) self.tv1.set("Copy done. " + str(len(files)) + " files were copied.") def DisplayImage(self, file): im = image.open(file) origx, origy = im.size if origx > origy: ratio = 100./origx else: ratio = 100./origy size = (int(ratio*origx), int(ratio*origy)) out = im.resize(size) self.pic1 = imagetk.PhotoImage(out) self.canvas1.create_image(0, 0, image = self.pic1, anchor = NW) - 1 # run it ... root = Tk() myapp = MyApp(root) root.mainloop() Thanks in advance for any help. From m.haft at abdn.ac.uk Thu Oct 27 02:01:22 2005 From: m.haft at abdn.ac.uk (Mike Haft) Date: Thu, 27 Oct 2005 01:01:22 +0100 (BST) Subject: [Tutor] File IO help Message-ID: <1562.87.242.128.120.1130371282.squirrel@www.abdn.ac.uk> Hello all, I'm new to python but so far I have to say its a really good language I've been having some trouble with File IO can anyone help? I've got the basics but my problem is that I have many files (one for each year of the last 100 years or so) that look like this: MONTH RAIN AVTEMP RAD EVAP **************************************** 1 12.4 12.0 * 10 2 13.9 30.0 * 11 3 etc until month 12 So far all I know how to do in Python looks something like this: def readInFile(inputName): input = open(inputName, "r") result = [] for line in input: if line[:1] == "1": fields = line.split() data = fields[1] + fields[2] + fields[7] result.append(data) input.close() return result Thats basically all I've been able to do but I need to write script that opens a file, reads the relevent data, stores that data and then closes the file and moves on to the next file repeating the action until all the files have been read. Then it needs to write a file with all the data it has collected but in a different format. If anyone can help I'd be really grateful. I hope I'm not asking too much of the list but I haven't found anything that says READ THIS BEFORE POSTING! on it to tell me otherwise. Thanks in advance Mike Haft From kent37 at tds.net Thu Oct 27 02:18:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Oct 2005 20:18:13 -0400 Subject: [Tutor] Tkinter problem (.create_image) In-Reply-To: <43600D27.2090408@customdatasoft.com> References: <43600D27.2090408@customdatasoft.com> Message-ID: <43601CC5.4010102@tds.net> Rob Dowell wrote: > I am having a problem with Tkinter. The goal is a program that will copy > images from one folder to another then delete them from the source dir > after it is verified that they made it to the target dir. I have the > base functionality figured out (comments on that are welcome of course). > Now I want to have a gui that shows a small thumbnail of the image as it > is copied. Right now everything works fine except that the gui only > shows the last picture that is copied. Here is the code: You have to give the GUI a chance to update by calling self.myParent.update_idletasks() after you set the new picture. You tell the GUI to show the picture but you never give a chance to do the actual work of drawing to the screen. Kent From nephish at xit.net Thu Oct 27 04:53:06 2005 From: nephish at xit.net (nephish) Date: Thu, 27 Oct 2005 02:53:06 +0000 Subject: [Tutor] question about try & except Message-ID: <1130381586.13560.2.camel@bitsbam.localdomain> Hey there, i am writing some (for me) pretty complicated stuff for work that really needs to work. i have looked at exception handling in the Learning Python book. and i am using some try / except statements. the problem is, that even though my script does not crash, i dont know the exact error. is there a parameter that will allow me to use try and except but that will also pring out the traceback statements that python usually does to the terminal? thanks From cpu.crazy at gmail.com Wed Oct 26 23:09:54 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 26 Oct 2005 15:09:54 -0600 Subject: [Tutor] Module Thread Message-ID: <435FF0A2.8060701@gmail.com> I'm back to my IRC client. I accidentally found the thread module in the Python 2.3 documentation while looking at the time module. What I can't get ideas or hints from the documentation is: What will i do to receive and send at the same time via console? or: Should I forget the idea of a console and start learning GUI which will do this for me. and lastly: Should I have a program that handles all the sending and receiving and puts it into a file and have to sub programs one that will write to the file that the main program will read and send and one that just reads the file which is received data. I'm interested in python disto threads rather than other modules. From hugonz-lists at h-lab.net Thu Oct 27 05:27:17 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 26 Oct 2005 21:27:17 -0600 Subject: [Tutor] question about try & except In-Reply-To: <1130381586.13560.2.camel@bitsbam.localdomain> References: <1130381586.13560.2.camel@bitsbam.localdomain> Message-ID: <43604915.7000004@h-lab.net> Yes, You can catch an error object along with the exception, as in: try: fileo = open("nofile") except IOError, e: print "Alas...", e As you see, the error object has a string representation equal wo what normally the python interpreter prints... >>> Alas... [Errno 2] No such file or directory: 'nofile' >>> Hope it helps. It took me originally a long time to know this trick, as it's kinda buried in the docs. Hugo nephish wrote: > Hey there, > i am writing some (for me) pretty complicated stuff for work that > really needs to work. > i have looked at exception handling in the Learning Python book. > and i am using some try / except statements. > the problem is, that even though my script does not crash, i dont know > the exact error. > is there a parameter that will allow me to use try and except but that > will also pring out the traceback statements that python usually does to > the terminal? > > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nephish at xit.net Thu Oct 27 06:15:18 2005 From: nephish at xit.net (nephish) Date: Wed, 26 Oct 2005 23:15:18 -0500 Subject: [Tutor] question about try & except In-Reply-To: <43604915.7000004@h-lab.net> References: <1130381586.13560.2.camel@bitsbam.localdomain> <43604915.7000004@h-lab.net> Message-ID: <1130386518.13709.1.camel@bitsbam.localdomain> Thanks Hugo, Now that i know where to look.... appreciate your help. -sk On Wed, 2005-10-26 at 21:27 -0600, Hugo Gonz?lez Monteverde wrote: > Yes, > > You can catch an error object along with the exception, as in: > > try: > fileo = open("nofile") > except IOError, e: > print "Alas...", e > > As you see, the error object has a string representation equal wo what > normally the python interpreter prints... > > >>> > Alas... [Errno 2] No such file or directory: 'nofile' > >>> > > > Hope it helps. It took me originally a long time to know this trick, as > it's kinda buried in the docs. > > Hugo > > > nephish wrote: > > Hey there, > > i am writing some (for me) pretty complicated stuff for work that > > really needs to work. > > i have looked at exception handling in the Learning Python book. > > and i am using some try / except statements. > > the problem is, that even though my script does not crash, i dont know > > the exact error. > > is there a parameter that will allow me to use try and except but that > > will also pring out the traceback statements that python usually does to > > the terminal? > > > > thanks > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > From tvbare at socket.net Thu Oct 27 06:32:26 2005 From: tvbare at socket.net (->Terry<-) Date: Wed, 26 Oct 2005 23:32:26 -0500 (CDT) Subject: [Tutor] Question about an re Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 os - Slackware py - 2.4.1 I'm trying to grab the value 10 in Visibility: 10 mile(s):0 but sometimes the value looks like Visibility: 1/2 mile(s):0 My not working regex looks like re.compile(': \d+|: \d/\d') If I'm understanding right, this should match either or, but it doesn't work for the fractional reading. Can someone steer me in the right direction and explain what I'm doing wrong? Thanks much, - -- Terry ,-~~-.___. Terry Randall / | ' \ < ) 0 Linux Counter Project User# 98233 \_/, ,-----' ==== // / \-'~; /~~~(0) / __/~| / | If only Snoopy had Slackware... =( ______| (________| "He is your friend, your partner, your defender, your dog. You are his life, his love, his leader. He will be yours, faithful and true, to the last beat of his heart. You owe it to him to be worthy of such devotion." -- Unknown (Best viewed with a mono-spaced font.) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFDYFhdQvSnsfFzkV0RAoPyAJ4jfwjWJ1eoqDatB6Hmg07XbUMGLQCeP/eQ ognaRmmfxNlDW249jRqYE2g= =Txx/ -----END PGP SIGNATURE----- From wescpy at gmail.com Thu Oct 27 06:32:52 2005 From: wescpy at gmail.com (w chun) Date: Wed, 26 Oct 2005 21:32:52 -0700 Subject: [Tutor] question about try & except In-Reply-To: <1130381586.13560.2.camel@bitsbam.localdomain> References: <1130381586.13560.2.camel@bitsbam.localdomain> Message-ID: <78b3a9580510262132q4a07d14cu38b798cfcceba32c@mail.gmail.com> > i am writing some (for me) pretty complicated stuff for work that > really needs to work. > i have looked at exception handling... > and i am using some try / except statements. > the problem is, that even though my script does not crash, i dont know > the exact error. > is there a parameter that will allow me to use try and except but that > will also pring out the traceback statements that python usually does to > the terminal? exception handling is one of the greatest strengths of Python and other high-level languages with this feature. it allows the programmer to anticipate potential problems and perhaps be able to accept and process them at runtime. let's say you have a code block called BLOCK. newbies to Python would typically do something like this to ensure that errors don't happen: try: BLOCK except: pass however, this is not the case. if errors *do* happen, they are thrown away, thus serves no one any good, not the programmer nor the user. the best solution is to catch specific exceptions and handle each case. (sure, and having just one handler for multiple exceptions is also okay.). one example is hugo's where he catches an IOError exception and uses the exception instance 'e' to get more info out of it. now if you *don't* know what exceptions may happen, you can do something similar. it's almost a combination of the above two handlers: try: BLOCK except Exception, e: print 'Caught exception without a specific handler:", e this will at least tell you what exception happens in BLOCK, so that you can modify it to be something like: try: BLOCK except References: <1130381586.13560.2.camel@bitsbam.localdomain> <78b3a9580510262132q4a07d14cu38b798cfcceba32c@mail.gmail.com> Message-ID: <1130387971.13825.0.camel@bitsbam.localdomain> Yeah, cool. i am just starting this part. i am glad i started with python. thanks for the help sk On Wed, 2005-10-26 at 21:32 -0700, w chun wrote: > > i am writing some (for me) pretty complicated stuff for work that > > really needs to work. > > i have looked at exception handling... > > and i am using some try / except statements. > > the problem is, that even though my script does not crash, i dont know > > the exact error. > > is there a parameter that will allow me to use try and except but that > > will also pring out the traceback statements that python usually does to > > the terminal? > > > exception handling is one of the greatest strengths of Python and > other high-level languages with this feature. it allows the > programmer to anticipate potential problems and perhaps be able to > accept and process them at runtime. > > let's say you have a code block called BLOCK. newbies to Python would > typically do something like this to ensure that errors don't happen: > > try: > BLOCK > except: > pass > > however, this is not the case. if errors *do* happen, they are thrown > away, thus serves no one any good, not the programmer nor the user. > > the best solution is to catch specific exceptions and handle each > case. (sure, and having just one handler for multiple exceptions is > also okay.). one example is hugo's where he catches an IOError > exception and uses the exception instance 'e' to get more info out of > it. > > now if you *don't* know what exceptions may happen, you can do > something similar. it's almost a combination of the above two > handlers: > > try: > BLOCK > except Exception, e: > print 'Caught exception without a specific handler:", e > > this will at least tell you what exception happens in BLOCK, so that > you can modify it to be something like: > > try: > BLOCK > except # handle YourSpecificException code > except Exception, e: > print 'Caught exception without a specfic handler:', e > > once you know the range of exceptions that may happen in BLOCK and > have written handlers for them, you can dispense with the general > catch-all. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2006,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com From matthew.williams at cancer.org.uk Thu Oct 27 09:05:51 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Thu, 27 Oct 2005 08:05:51 +0100 Subject: [Tutor] General programming questions Message-ID: <1130396751.2674.7.camel@localhost.localdomain> Dear List, I've got a few general programming (not really specific to python, although you're all so helpful, I thought I'd ask here). I understand some of these are a bit long, so if you could just point me to some resources, I'd be very grateful. 1: I need to create objects that have variable levels of behaviour (controlled perhaps by a .config file). I can do the file reading, etc. - but how do I implement the behaviour, apart from just re-writing all the functions for each config level? 2: I need to implement polmorphism in some methods (and a constructor). At the moment, I have something like: def __init__ (self, a, b, c): if type(a) == type("a") then..... elif type(a) == type(["a"]) then.... I'm sure there must be a better way to do this (both the polymorphism and the type testing) - but I don't know how to do it. Thanks a lot, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7384 899570 From alan.gauld at freenet.co.uk Thu Oct 27 10:06:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 27 Oct 2005 09:06:27 +0100 Subject: [Tutor] question about try & except References: <1130381586.13560.2.camel@bitsbam.localdomain> Message-ID: <007401c5dacd$5c27a4e0$0a01a8c0@xp> > and i am using some try / except statements. > the problem is, that even though my script does not crash, i dont know > the exact error. IT sounds like your try/except is masking the error. Its usually a good idea to NOT Use try/except when developing your code, then go back and put it in when the basics are working. That way Pythons own exception handling will catch the error, force a break and print the stacktrace whoich helps identify the problem. > is there a parameter that will allow me to use try and except but that > will also pring out the traceback statements that python usually does to > the terminal? One technique is to simply call raise within each exception block, then comment out the raise lines when you no longer need them. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From singletoned at gmail.com Thu Oct 27 10:29:02 2005 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 27 Oct 2005 09:29:02 +0100 Subject: [Tutor] Question about an re In-Reply-To: References: Message-ID: <34bb7f5b0510270129va59747bh@mail.gmail.com> OR tests for the truth of the first thing then the truth of the second. The first part of your OR is always true, so it doesn't test the second. What you really want to do is look for a digit and then look for more digits or a slash and some more digits. So: : \d(\d+|/\d+) but this is easier by just allowing an optional slash in the digits: : \d+/?\d* ie 1 or more digits followed by 0 or 1 slashes followed by 0 or more digits. http://www.regular-expressions.info/ is a brilliant tutorial on regexs and http://www.weitz.de/regex-coach/ is a great program for testing them out before you put them in your code. Hope this helps Ed On 27/10/05, ->Terry<- wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > os - Slackware > py - 2.4.1 > > I'm trying to grab the value 10 in > > Visibility: 10 mile(s):0 > > but sometimes the value looks like > > Visibility: 1/2 mile(s):0 > > My not working regex looks like > > re.compile(': \d+|: \d/\d') > > If I'm understanding right, this should match either or, > but it doesn't work for the fractional reading. > > Can someone steer me in the right direction and explain > what I'm doing wrong? > > Thanks much, > - -- > Terry > > ,-~~-.___. Terry Randall > / | ' \ > < ) 0 Linux Counter Project User# 98233 > \_/, ,-----' > ==== // > / \-'~; /~~~(0) > / __/~| / | If only Snoopy had Slackware... > =( ______| (________| > > "He is your friend, your partner, your defender, your dog. > You are his life, his love, his leader. He will be yours, > faithful and true, to the last beat of his heart. You owe > it to him to be worthy of such devotion." -- Unknown > > (Best viewed with a mono-spaced font.) > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.7 (GNU/Linux) > > iD8DBQFDYFhdQvSnsfFzkV0RAoPyAJ4jfwjWJ1eoqDatB6Hmg07XbUMGLQCeP/eQ > ognaRmmfxNlDW249jRqYE2g= > =Txx/ > -----END PGP SIGNATURE----- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Oct 27 11:47:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Oct 2005 05:47:40 -0400 Subject: [Tutor] question about try & except In-Reply-To: <1130381586.13560.2.camel@bitsbam.localdomain> References: <1130381586.13560.2.camel@bitsbam.localdomain> Message-ID: <4360A23C.1020400@tds.net> nephish wrote: > Hey there, > i am writing some (for me) pretty complicated stuff for work that > really needs to work. > i have looked at exception handling in the Learning Python book. > and i am using some try / except statements. > the problem is, that even though my script does not crash, i dont know > the exact error. > is there a parameter that will allow me to use try and except but that > will also pring out the traceback statements that python usually does to > the terminal? If you put traceback.print_exc() in your exception handler it will print out the exception string and the full stack trace. This is very handy when you have unexpected exceptions as it will let you know where the problem occurs. For example: try: open('foo.txt') except IOError: import traceback traceback.print_exc() Kent -- http://www.kentsjohnson.com From kent37 at tds.net Thu Oct 27 12:04:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Oct 2005 06:04:32 -0400 Subject: [Tutor] Module Thread In-Reply-To: <435FF0A2.8060701@gmail.com> References: <435FF0A2.8060701@gmail.com> Message-ID: <4360A630.7090503@tds.net> Joseph Quigley wrote: > I'm back to my IRC client. I accidentally found the thread module in the > Python 2.3 documentation while looking at the time module. Wow, threads are in the air this month! You should use the threading module, not thread. threading is higher-level and more capable. Take a look at the recent list archives for some hints. > > What I can't get ideas or hints from the documentation is: > What will i do to receive and send at the same time via console? You will need two threads, the main application thread and one you start. One thread will listen for user input at the console, the other will listen for remote input from a socket. > > or: > Should I forget the idea of a console and start learning GUI which will > do this for me. > > and lastly: > Should I have a program that handles all the sending and receiving and > puts it into a file and have to sub programs one that will write to the > file that the main program will read and send and one that just reads > the file which is received data. No, I don't think that will help. Kent -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Thu Oct 27 12:36:35 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 27 Oct 2005 11:36:35 +0100 Subject: [Tutor] General programming questions References: <1130396751.2674.7.camel@localhost.localdomain> Message-ID: <009101c5dae2$4f34eda0$0a01a8c0@xp> > 1: I need to create objects that have variable levels of behaviour > (controlled perhaps by a .config file). I can do the file reading, etc. > - but how do I implement the behaviour, apart from just re-writing all > the functions for each config level? Usually by having multiple subclasses and instantiating the right kind of object based on the config file valuyes - perhaps using a factory object to do the config reading and instantiating. ie You have a singleton factory object that takes a config file as its constructor. It then interprets the config file and instantiates the appropriate subclasses of your entity. This is probably the easiest form of meta class programming. > 2: I need to implement polmorphism in some methods (and a constructor). > At the moment, I have something like: > > def __init__ (self, a, b, c): > if type(a) == type("a") > then..... > elif type(a) == type(["a"]) > then.... Thats pretty much the code I'm suggesting would be in the factory class method that processes the config file. The then... part translates to a constructor call for each type of subclass. > I'm sure there must be a better way to do this (both the polymorphism > and the type testing) - but I don't know how to do it. Multiple constructors is not easily done in Python because the parameters to init are untyped. (You can fake it a little with default argument values) Thats why I tend to go for a factory object which does the dynamic decision making and leaves the init methods of the individual subclasses clean - ie easier to reuse. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Thu Oct 27 12:41:07 2005 From: wescpy at gmail.com (w chun) Date: Thu, 27 Oct 2005 03:41:07 -0700 Subject: [Tutor] Module Thread In-Reply-To: <435FF0A2.8060701@gmail.com> References: <435FF0A2.8060701@gmail.com> Message-ID: <78b3a9580510270341m7391475cl579646ebe88b0172@mail.gmail.com> On 10/26/05, Joseph Quigley wrote: > I'm back to my IRC client. I accidentally found the thread module... > What will i do to receive and send at the same time via console? > > or: > Should I forget the idea of a console and start learning GUI which will > do this for me. if you want to do it from the ground up, then take Kent's suggestion and use threading, not thread. it's much higher-level and has all the good primitives you need. if you want to just worry about the server and client bits, yet still stay rather low-level, then take a look at SocketServer. You will use the ThreadingMixIn with the appropriate connection-type server: if your server is based on establishing and maintaining a connection for the IRC-chat, then use the TCPServer. if you just want to pass individual msgs back-n-forth, then use the UDPServer. The ThreadingMixIn allows for the asynchronous behavior (send and receive at the same time) that you desire. note that both client and server behave in a very similar way -- both will be able to send and recv msgs at the same time. if you're using UDP, then they may almost be the exact same class (except that the server will likely be talking to multiple clients) while for TCP, one has to establish a port binding and sits-n-waits for cxns (server) while the other initiates cxns (client). my suggestion *is* to do the console version 1st, then find your favorite GUI and just "attach" them to your then-completed client-server classes. also has Kent has suggested, drop your last idea. ;-) hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Thu Oct 27 12:49:26 2005 From: wescpy at gmail.com (w chun) Date: Thu, 27 Oct 2005 03:49:26 -0700 Subject: [Tutor] General programming questions In-Reply-To: <1130396751.2674.7.camel@localhost.localdomain> References: <1130396751.2674.7.camel@localhost.localdomain> Message-ID: <78b3a9580510270349q3384fe8bh1a78bd6407ac7435@mail.gmail.com> On 10/27/05, Matt Williams wrote: > At the moment, I have something like: > > def __init__ (self, a, b, c): > if type(a) == type("a") > then..... > elif type(a) == type(["a"]) > then.... > > I'm sure there must be a better way to do this (both the polymorphism > and the type testing) - but I don't know how to do it. i'd follow alan's advice with regards to the multiple subclasses and using a factory object to evaluate and instantiate the appropriate class instance. as far as the code above, the 1st improvement is to change "type(a) == type(...)" to "type(a) is type(...)" since your evaluations will work faster (because there is one less comparison to make -- the type objects are all the same, so why also check their *values* are the same too?); and finally, even faster is "isinstance(a, ...)". hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Thu Oct 27 12:54:43 2005 From: wescpy at gmail.com (w chun) Date: Thu, 27 Oct 2005 03:54:43 -0700 Subject: [Tutor] question about try & except In-Reply-To: <1130387971.13825.0.camel@bitsbam.localdomain> References: <1130381586.13560.2.camel@bitsbam.localdomain> <78b3a9580510262132q4a07d14cu38b798cfcceba32c@mail.gmail.com> <1130387971.13825.0.camel@bitsbam.localdomain> Message-ID: <78b3a9580510270354p545938bbi3b07e1c31105afa2@mail.gmail.com> On 10/26/05, nephish wrote: > Yeah, cool. i am just starting this part. > i am glad i started with python. > thanks for the help if your app is willing to tolerate errors/crashes, then i would take alan's advice and just letting the errors happen, as opposed to being so careful with (and integrating Kent's suggestion for the full traceback with): try: BLOCK except Exception, e: print e, traceback.print_exc() # take some other evasive yet safe maneuver i only use the above when integrating into large systems (that aren't supposed to crash, that need some cleanup, and/or that need to take other action). otherwise for simple scripts, i just let the darn thing crash out and add in the handler for those errors. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Thu Oct 27 13:50:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Oct 2005 07:50:23 -0400 Subject: [Tutor] question about try & except In-Reply-To: <78b3a9580510270354p545938bbi3b07e1c31105afa2@mail.gmail.com> References: <1130381586.13560.2.camel@bitsbam.localdomain> <78b3a9580510262132q4a07d14cu38b798cfcceba32c@mail.gmail.com> <1130387971.13825.0.camel@bitsbam.localdomain> <78b3a9580510270354p545938bbi3b07e1c31105afa2@mail.gmail.com> Message-ID: <4360BEFF.6080700@tds.net> w chun wrote: > if your app is willing to tolerate errors/crashes, then i would take > alan's advice and just letting the errors happen, as opposed to being > so careful with (and integrating Kent's suggestion for the full > traceback with): > > try: > BLOCK > except Exception, e: > print e, traceback.print_exc() > # take some other evasive yet safe maneuver No, not quite. print_exc() does its own output and returns None, so it shouldn't be part of the print statement. And print_exc() prints e as part of its output, so 'print e' is redundant. All you need in the except block is traceback.print_exc() and whatever additional handling you want to do. Normally it's not a good idea to catch generic Exception - you usually can be more focused than that - but at a high level in an application it can be useful to catch everything. For example you may be processing a list of files in a loop and you don't want an error in one file to abort the loop. So you put a try / except at the top level of the loop to catch and log errors, then continue with the next file. Kent From singletoned at gmail.com Thu Oct 27 15:01:47 2005 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 27 Oct 2005 14:01:47 +0100 Subject: [Tutor] Passing Functions or Code as Parameters Message-ID: <34bb7f5b0510270601u756d2f0aq@mail.gmail.com> How can I pass a block of code to a function for it to perform within itself? For example, I wrote a small function that recurses through a directory structure but keeps a track of the depth: from path import path def traverse(directory, depth=0): thedir = path(directory) for item in thedir.files(): ## Do stuff relative to the depth for item in thedir.dirs(): traverse(item,depth+1) What I want to do is something like: from path import path def traverse(directory, depth=0, things_to_do()): thedir = path(directory) for item in thedir.files(): things_to_do(depth) for item in thedir.dirs(): traverse(item,depth+1) Is this possible? Thanks Ed From kent37 at tds.net Thu Oct 27 15:28:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Oct 2005 09:28:56 -0400 Subject: [Tutor] Passing Functions or Code as Parameters In-Reply-To: <34bb7f5b0510270601u756d2f0aq@mail.gmail.com> References: <34bb7f5b0510270601u756d2f0aq@mail.gmail.com> Message-ID: <4360D618.40806@tds.net> Ed Singleton wrote: > How can I pass a block of code to a function for it to perform within itself? > > For example, I wrote a small function that recurses through a > directory structure but keeps a track of the depth: > > What I want to do is something like: > > from path import path > > def traverse(directory, depth=0, things_to_do()): > thedir = path(directory) > for item in thedir.files(): > things_to_do(depth) > for item in thedir.dirs(): > traverse(item,depth+1) > > Is this possible? Easy, actually! You almost have it. Functions are 'first-class objects' in Python. What that means is that a function is an object as much as a list or an integer. When you define a function, you are actually binding the function object to the name you use in the def. For example: >>> def printer(x): ... print x ... >>> printer The name 'printer' is now bound to a function object. Functions can be bound to other names or passed as parameters to functions (or stored in lists, or...). Here is a function that takes a function as a parameter and calls the passed-in function several times: >>> def test(fn): ... for x in [1, 2, 10]: ... fn(x) To call this function with the printer function as a parameter is just like any other function call: >>> test(printer) 1 2 10 So in your case, just remove the excess parens in your function definition. (You have to reorder the params since keyword params have to follow non-keyword params): def traverse(directory, things_to_do, depth=0): Then define your things_to_do function (which can be called whatever you want) as a function of one argument: def do_something(depth): print depth and call traverse passing this as an argument: traverse(myDir, do_something) You also have to change the recursive call to traverse(), you must pass the things_to_do parameter: for item in thedir.dirs(): traverse(item,things_to_do,depth+1) By the way this is a very powerful capability of Python. Your usage is a good example of customizing the behaviour of a function by passing another function as a parameter. You can also build lists or dicts of dispatch functions, wrap functions to modify their behaviour, etc... Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Thu Oct 27 16:05:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 27 Oct 2005 07:05:10 -0700 (PDT) Subject: [Tutor] new user question about while loops In-Reply-To: <026f01c5da0a$b06a6ce0$0a01a8c0@xp> Message-ID: > #assigning variables to track the amount of times heads or tails comes up > heads=0 > tails=1 > > AG> Why not make both zero, after all there have been no flips so far! Hi Alan, There is confusion here about the role of these variables. Despite what the comment says, I assume that 'heads' and 'tails' here are not meant to count how many times we see heads or tails. Instead, the code instead seems to say that 0 is an encoding for a coin flip for heads, and 1 is an encoding for a coin flip for tails. It's intrinsically tied to the call to the coin flip itself: random.randrange(2) One possible place of confusion, here, is that the program still talks in the vocabulary of numbers, where it really should be talking in the vocabulary of coin faces. Rather than random.randrange(), it is more appropriate to use random.choice(), random.choice([heads, tails]) to explicitely show that we're making a choice among the possible alternatives of: heads or tails. The fact that these values are really integers underneath the surface shouldn't show up in the coin flipping, and that's why using randrange() is probably not optimal from a human readability's standpoint here. (If efficiency is a concern, we probably would optimize this to use random.randrange() after all. But if we do so, we should be aware that we sacrificing the abstraction for performance's sake.) A problem with encoding something as a number is that it's becomes very easy to make inadvertant "puns". 0 could stand for a false value, or heads, or zero coin flips so far, or ... etc. In summary, when we go back to that code comment: > #assigning variables to track the amount of times heads or tails comes up > heads=0 > tails=1 I think the comment is troublesome because it appears to make a bad pun. I don't think the intent of heads or tails is to count, but rather to describe the encoding of the concept of a head or tail flip. Hope this helps! From johan at accesstel.co.za Thu Oct 27 16:29:59 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 27 Oct 2005 16:29:59 +0200 Subject: [Tutor] os.system sending of break signals Message-ID: <4360E467.1090500@accesstel.co.za> Hi all, I send a command to os.system(cmd) and want to send a break signal in the same way. Is this possible? The break signal is ctrl c (^c). I tried this, but it didn't work: os.system('\x03') I think Hex 03 is the signal for ctrl c. Thanks, From srini_iyyer_bio at yahoo.com Thu Oct 27 17:59:31 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 27 Oct 2005 08:59:31 -0700 (PDT) Subject: [Tutor] Weird iteration using zip() In-Reply-To: <4360E467.1090500@accesstel.co.za> Message-ID: <20051027155931.3761.qmail@web31610.mail.mud.yahoo.com> Hi all: Here is a simple code: >>> a = ['a','b','c','d','e'] >>> b = [1,2,3,4,5] >>> abdict = dict(zip(a,b)) >>> abdict {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} Why is this weird iteration going on" Why not: >>> abdict {'a':1,'b':2,'c':3,'d':4,'e':5} Is there any hidden logic in the code that is making abidct to have a , c, b, e, d sequence? Any explanation..? thanks Sr __________________________________ Start your day with Yahoo! - Make it your home page! http://www.yahoo.com/r/hs From kent37 at tds.net Thu Oct 27 18:19:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Oct 2005 12:19:27 -0400 Subject: [Tutor] Weird iteration using zip() In-Reply-To: <20051027155931.3761.qmail@web31610.mail.mud.yahoo.com> References: <20051027155931.3761.qmail@web31610.mail.mud.yahoo.com> Message-ID: <4360FE0F.9090807@tds.net> Srinivas Iyyer wrote: > Hi all: > > Here is a simple code: > > >>>>a = ['a','b','c','d','e'] >>>>b = [1,2,3,4,5] >>>>abdict = dict(zip(a,b)) >>>>abdict > > {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} > > > Why is this weird iteration going on" The order of keys in a dict is effectively indeterminate. It does not reflect the order in which the entries are added to the dict and may change over time as entries are added and deleted. This is a side-effect of the way dicts are implemented (as hash tables). Kent From kent37 at tds.net Thu Oct 27 18:33:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Oct 2005 12:33:48 -0400 Subject: [Tutor] Passing Functions or Code as Parameters In-Reply-To: <34bb7f5b0510270917r7c338a73y@mail.gmail.com> References: <34bb7f5b0510270601u756d2f0aq@mail.gmail.com> <4360D618.40806@tds.net> <34bb7f5b0510270917r7c338a73y@mail.gmail.com> Message-ID: <4361016C.2000609@tds.net> Ed Singleton wrote: > Wow, thanks again, Kent. > > If my understanding of functions in Python is correct, then the > do_something() function won't have access to the variables inside > traverse. Is this right? Yes, that's right. Python is lexically scoped which means you have access to variables in the enclosing scopes in the actual program text, not the scope of the callers. > I know I could pass them as parameters: > > def traverse(directory, things_to_do, depth=0): > thedir = path(directory) > for item in thedir.files(): > things_to_do(depth, item) > for item in thedir.dirs(): > traverse(item, things_to_do, depth+1) > > But what if I don't know in advance what parameters I want to pass? You don't have very many possibilities here, maybe just pass them all? You could pass locals() to things_to_do() - locals() returns a dictionary containing all the current local variables. Then things_to_do() would take a single argument and extract the variables it wants. Why do you need this much flexibility? I would just pass thedir, item and depth to things_to_do(). > Can I pass a block of code that will be executed within the function's > scope? Yes, you can define a function within traverse() and pass that function to things_to_do(), but I don't know how that will help. Kent PS Please reply on list so others can participate. From hugonz-lists at h-lab.net Thu Oct 27 19:42:25 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 27 Oct 2005 11:42:25 -0600 Subject: [Tutor] os.system sending of break signals In-Reply-To: <4360E467.1090500@accesstel.co.za> References: <4360E467.1090500@accesstel.co.za> Message-ID: <43611181.7050309@h-lab.net> Even if you could send a break signal, it would go to a new shell that os.system() invokes... Perhaps you know or can get the ID of the process you want to signal, a ctrl-c in a shell is equivalent to a SIGINT sent using os.kill() Please anyone in the list correct me if there is something I missed or misunderstand. Hugo Johan Geldenhuys wrote: > Hi all, > I send a command to os.system(cmd) and want to send a break signal in > the same way. Is this possible? The break signal is ctrl c (^c). > I tried this, but it didn't work: os.system('\x03') I think Hex 03 is > the signal for ctrl c. > > Thanks, > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From m.haft at abdn.ac.uk Thu Oct 27 21:18:42 2005 From: m.haft at abdn.ac.uk (Mike Haft) Date: Thu, 27 Oct 2005 20:18:42 +0100 (BST) Subject: [Tutor] File IO Help again Message-ID: <2906.84.43.113.85.1130440722.squirrel@www.abdn.ac.uk> Apologies for not making things clearer last time. My specific problems are: why can I not get the readline() or readlines() functions to work, I'm told they are not defined whenever I try. Also the following: if line[:1] == "1": collects data from month 1, 10, 11, and 12. How do I make the readfile function I defined count through 1 to 12 and retreive the fields I need? Can I just use a for loop type of construction and substitute an x variable where there is curently a [:1] and a "x" i.e.: if line[:y] == x: If not why not? What must I do. Other questions coming soon. Sorry for the vague post earlier, multitasking isn't my specialty, especially without coffee. Thanks Mike >From the previous post: ----------------------- The data in each file looks liek: MONTH RAIN AVTEMP RAD EVAP **************************************** 1 12.4 12.0 * 10 2 13.9 30.0 * 11 3 etc until month 12 So far all I know how to do in Python looks something like this: def readInFile(inputName): input = open(inputName, "r") result = [] for line in input: if line[:1] == "1": fields = line.split() data = fields[1] + fields[2] + fields[7] result.append(data) input.close() return result From dyoo at hkn.eecs.berkeley.edu Thu Oct 27 21:57:12 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 27 Oct 2005 12:57:12 -0700 (PDT) Subject: [Tutor] File IO Help again In-Reply-To: <2906.84.43.113.85.1130440722.squirrel@www.abdn.ac.uk> Message-ID: On Thu, 27 Oct 2005, Mike Haft wrote: > why can I not get the readline() or readlines() functions to work, I'm > told they are not defined whenever I try. Don't paraphrase. *grin* Show us what you did in terms of the code that you ran. Also, include the literal error message and its traceback. This is important because we need to make sure we can reproduce whatever problem you're running into. > Can I just use a for loop type of construction and substitute an x > variable where there is curently a [:1] and a "x" i.e.: > > if line[:y] == x: Yes, although you might be able to simplify this; doing a loop here seems like too much work. Depending on how your lines are structured, it might even be possible to do something like: pieces = line.split() if len(pieces) > 0 and pieces[0] == x: ... >From the data you've shown us: > MONTH RAIN AVTEMP RAD EVAP > **************************************** > 1 12.4 12.0 * 10 > 2 13.9 30.0 * 11 it seems that using a split to break the line into columns should help simplify the problem. From bgailer at alum.rpi.edu Thu Oct 27 22:20:58 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 27 Oct 2005 13:20:58 -0700 Subject: [Tutor] File IO Help again In-Reply-To: <2906.84.43.113.85.1130440722.squirrel@www.abdn.ac.uk> References: <2906.84.43.113.85.1130440722.squirrel@www.abdn.ac.uk> Message-ID: <6.1.2.0.0.20051027131622.036019b0@mail.mric.net> At 12:18 PM 10/27/2005, Mike Haft wrote: >Apologies for not making things clearer last time. > >My specific problems are: > >why can I not get the readline() or readlines() functions to work, I'm >told they are not defined whenever I try. Mike * Oh * Mike ... and all others ... Please Post The Code and the Traceback. Otherwise We Cannot Help You. As Much As We Want to be We are Not MindReaders. >Also the following: > >if line[:1] == "1": > >collects data from month 1, 10, 11, and 12. How do I make the readfile >function I defined count through 1 to 12 and retreive the fields I need? This does not compute for me. I have no idea what you want! >Can I just use a for loop type of construction and substitute an x >variable where there is curently a [:1] and a "x" i.e.: > >if line[:y] == x: > >If not why not? What must I do. [snip] From adam.jtm30 at gmail.com Thu Oct 27 22:42:31 2005 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 27 Oct 2005 21:42:31 +0100 Subject: [Tutor] File IO Help again In-Reply-To: <6.1.2.0.0.20051027131622.036019b0@mail.mric.net> References: <2906.84.43.113.85.1130440722.squirrel@www.abdn.ac.uk> <6.1.2.0.0.20051027131622.036019b0@mail.mric.net> Message-ID: >if line[:1] == "1": This line won't work because you're getting the first 2 characters from the line and seeing if it's equal to a string of length one. For example in your test file if you put this line, 1 12.4 12.0 * 10 , through that bit of code it would see if "1 " == "1", which it isn't. As Danny suggested a split should make it easier. eg: >>> s = "1 12.4 12.0 * 10" >>> s.split() ['1', '12.4', '12.0', '*', '10'] >>> then you could use if s[0] == "1": -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051027/b8ea44e9/attachment.html From cpu.crazy at gmail.com Thu Oct 27 17:35:27 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Thu, 27 Oct 2005 09:35:27 -0600 Subject: [Tutor] Module Thread In-Reply-To: <78b3a9580510270341m7391475cl579646ebe88b0172@mail.gmail.com> References: <435FF0A2.8060701@gmail.com> <78b3a9580510270341m7391475cl579646ebe88b0172@mail.gmail.com> Message-ID: <4360F3BF.60903@gmail.com> Hi, thanks for the info. I'd like o know if you guys know of any good documentation on the threading module. Or if you could give me a quick intro to it. Or am I asking too much? If so I'll try to work it out on my own for a little. From tvbare at socket.net Thu Oct 27 23:44:50 2005 From: tvbare at socket.net (->Terry<-) Date: Thu, 27 Oct 2005 16:44:50 -0500 (CDT) Subject: [Tutor] Question about an re In-Reply-To: <34bb7f5b0510270129va59747bh@mail.gmail.com> References: <34bb7f5b0510270129va59747bh@mail.gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Today (Oct 27, 2005) at 9:29am, Ed Singleton spoke these wise words: - ->OR tests for the truth of the first thing then the truth of the second. - -> - ->The first part of your OR is always true, so it doesn't test the second. - -> - ->What you really want to do is look for a digit and then look for more - ->digits or a slash and some more digits. - -> - ->So: - -> - ->: \d(\d+|/\d+) - -> - ->but this is easier by just allowing an optional slash in the digits: - -> - ->: \d+/?\d* - -> - ->ie 1 or more digits followed by 0 or 1 slashes followed by 0 or more digits. - -> - ->http://www.regular-expressions.info/ is a brilliant tutorial on regexs - ->and http://www.weitz.de/regex-coach/ is a great program for testing - ->them out before you put them in your code. - -> - ->Hope this helps - -> - ->Ed - -> - ->On 27/10/05, ->Terry<- wrote: - ->> -----BEGIN PGP SIGNED MESSAGE----- - ->> Hash: SHA1 - ->> - ->> - ->> os - Slackware - ->> py - 2.4.1 - ->> - ->> I'm trying to grab the value 10 in - ->> - ->> Visibility: 10 mile(s):0 - ->> - ->> but sometimes the value looks like - ->> - ->> Visibility: 1/2 mile(s):0 - ->> - ->> My not working regex looks like - ->> - ->> re.compile(': \d+|: \d/\d') - ->> - ->> If I'm understanding right, this should match either or, - ->> but it doesn't work for the fractional reading. Ok, I get it now. Thanks for the help and the links Ed. Works like a charm and I changed it to also grab another variation I found thanks to your help. Visibility: less than 1/4 mile(s):1 Thanks again, - -- Terry ,-~~-.___. Terry Randall / | ' \ < ) 0 Linux Counter Project User# 98233 \_/, ,-----' ==== // / \-'~; /~~~(0) / __/~| / | If only Snoopy had Slackware... =( ______| (________| "He is your friend, your partner, your defender, your dog. You are his life, his love, his leader. He will be yours, faithful and true, to the last beat of his heart. You owe it to him to be worthy of such devotion." -- Unknown (Best viewed with a mono-spaced font.) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFDYUpVQvSnsfFzkV0RAvckAJ4xrve8QaTnMUa+UO9lDjxIv+A48ACdFhcF yu6FTTtTkZiGD7GrVi98SGg= =B5Pl -----END PGP SIGNATURE----- From alan.gauld at freenet.co.uk Fri Oct 28 00:15:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 27 Oct 2005 23:15:51 +0100 Subject: [Tutor] os.system sending of break signals References: <4360E467.1090500@accesstel.co.za> Message-ID: <00d501c5db43$fe24bf00$0a01a8c0@xp> > I send a command to os.system(cmd) and want to send a break signal in > the same way. Is this possible? The break signal is ctrl c (^c). > I tried this, but it didn't work: os.system('\x03') I think Hex 03 is > the signal for ctrl c. Its not possible with os.system because os.system runs the called program to completion in a separate process. You would need to mess about with threads and process ids to do it that way. However if you use popen() (or maybe popen2()? )you should be able to send a Ctrl-C character to the process. However whether that actually terminates it will depend on the OS, the process and whether Ctrl-C is being caught anywhere. But at least there's a chance of it working! HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Oct 28 00:17:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 27 Oct 2005 23:17:58 +0100 Subject: [Tutor] Weird iteration using zip() References: <20051027155931.3761.qmail@web31610.mail.mud.yahoo.com> Message-ID: <00d901c5db44$49639810$0a01a8c0@xp> >>>> a = ['a','b','c','d','e'] >>>> b = [1,2,3,4,5] >>>> abdict = dict(zip(a,b)) >>>> abdict > {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} > > > Why is this weird iteration going on" Dictionaries store their values in the most efficient way for key lookup they do not store them in order. In fact the order can even change over the life of the dictionary. Think of a dictionary being like a tree rather than a list. This is also why accessing data from a dictionary is often faster than from a list. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From amonroe at columbus.rr.com Fri Oct 28 00:24:15 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 27 Oct 2005 18:24:15 -0400 Subject: [Tutor] os.system sending of break signals In-Reply-To: <00d501c5db43$fe24bf00$0a01a8c0@xp> References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> Message-ID: <172730505261.20051027182415@columbus.rr.com> >> I send a command to os.system(cmd) and want to send a break signal in >> the same way. Is this possible? The break signal is ctrl c (^c). >> I tried this, but it didn't work: os.system('\x03') I think Hex 03 is >> the signal for ctrl c. > Its not possible with os.system because os.system runs the called > program to completion in a separate process. You would need to > mess about with threads and process ids to do it that way. However > if you use popen() (or maybe popen2()? )you should be able to send > a Ctrl-C character to the process. However whether that actually > terminates it will depend on the OS, the process and whether > Ctrl-C is being caught anywhere. But at least there's a chance > of it working! Python has a "signal" module in the standard library. Will that work? Alan From ronin_cpim at hotmail.com Fri Oct 28 01:33:46 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Thu, 27 Oct 2005 19:33:46 -0400 Subject: [Tutor] IDLE error msgs and line continuations? In-Reply-To: Message-ID: When using IDLE, after hitting F5 to save and run, if an error occurs, it merely flashes at the code location of the error. While I usually figure out what is wrong, why don't I get the detailed text error messages that the command line gives? Also, I'm getting most error messages when I try line continuation for clarity: if (condition 123 and condition 456): I distinctly remember Python allowing the above. Thanks. RC _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From falcon3166 at hotmail.com Fri Oct 28 04:07:34 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 27 Oct 2005 20:07:34 -0600 Subject: [Tutor] Can anyone help me? Message-ID: Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how to, please? Thanks, Nathan Pinno For great sites go to: http://falcon3166.tripod.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051027/65fa2d42/attachment.htm From kent37 at tds.net Fri Oct 28 04:20:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Oct 2005 22:20:40 -0400 Subject: [Tutor] Module Thread In-Reply-To: <4360F3BF.60903@gmail.com> References: <435FF0A2.8060701@gmail.com> <78b3a9580510270341m7391475cl579646ebe88b0172@mail.gmail.com> <4360F3BF.60903@gmail.com> Message-ID: <43618AF8.5080801@tds.net> Joseph Quigley wrote: > Hi, thanks for the info. > I'd like o know if you guys know of any good documentation on the > threading module. Or if you could give me a quick intro to it. Or am I > asking too much? If so I'll try to work it out on my own for a little. In truth I am worn out on thread questions right now, there have been a lot of them this month and they are hard to answer. You can look at the list archives. Here are a couple of older threads with some good tips and pointers: http://mail.python.org/pipermail/tutor/2004-November/033247.html http://mail.python.org/pipermail/tutor/2005-August/040831.html This topic is ripe for a good how-to doc. Kent From amonroe at columbus.rr.com Fri Oct 28 04:23:09 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 27 Oct 2005 22:23:09 -0400 Subject: [Tutor] Can anyone help me? In-Reply-To: References: Message-ID: <155744839041.20051027222309@columbus.rr.com> > Hey all, > I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how > to, please? Create (empty for now) list to hold your final numbers. Have a for-loop that runs 6 times using range(6) Inside the loop, just pick a random number and append it to your final number list. Alan From jason.massey at gmail.com Fri Oct 28 05:06:18 2005 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 27 Oct 2005 22:06:18 -0500 Subject: [Tutor] IDLE error msgs and line continuations? In-Reply-To: References: Message-ID: <7e3eab2c0510272006x66090ce4gff02623b2662a5d0@mail.gmail.com> All you need is the line continuation character, '\': if (condition 123 and \ condition 456) : On 10/27/05, CPIM Ronin wrote: > When using IDLE, after hitting F5 to save and run, if an error occurs, it > merely flashes at the code location of the error. While I usually figure out > what is wrong, why don't I get the detailed text error messages that the > command line gives? > > Also, I'm getting most error messages when I try line continuation for > clarity: > > if (condition 123 and > condition 456): > > I distinctly remember Python allowing the above. > > Thanks. > > RC > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today - it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at alum.rpi.edu Fri Oct 28 06:30:50 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 27 Oct 2005 21:30:50 -0700 Subject: [Tutor] File IO Help again In-Reply-To: References: <2906.84.43.113.85.1130440722.squirrel@www.abdn.ac.uk> <6.1.2.0.0.20051027131622.036019b0@mail.mric.net> Message-ID: <6.1.2.0.0.20051027212843.0277bfe8@mail.mric.net> At 01:42 PM 10/27/2005, Adam wrote: > >if line[:1] == "1": > >This line won't work because you're getting the first 2 characters from >the line Oh? Did you test that? When I do that I get 1 character. Why? Because slicing goes UP TO the 2nd argument. >>> 'abc'[:1] 'a' From bgailer at alum.rpi.edu Fri Oct 28 06:35:07 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 27 Oct 2005 21:35:07 -0700 Subject: [Tutor] Can anyone help me? In-Reply-To: References: Message-ID: <6.1.2.0.0.20051027213152.02780158@mail.mric.net> At 07:07 PM 10/27/2005, Nathan Pinno wrote: >Hey all, >I am trying to create a program that draws 6 numbers between 1 and 49 at >random for creating lottery tickets. I want to have a better chance when I >play. Define "better chance". Lottery odds are how many tickets you buy relative to how many tickets everyone else has bought. No program will improve or degrade your odds. The only way you can reduce your odds is to buy more than one ticket with the same numbers. Keep in mind that a lottery is as truly random as one can get (assuming no rigging). There is no memory of past outcomes involved nor of better guessing techniques. From bgailer at alum.rpi.edu Fri Oct 28 06:36:33 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 27 Oct 2005 21:36:33 -0700 Subject: [Tutor] Plea for Meaningful Subject Lines (was: Can anyone help me?) In-Reply-To: References: Message-ID: <6.1.2.0.0.20051027213514.035bb740@mail.mric.net> Please in future provide meaningful subject lines. It makes it a lot easier to track the threads. From bgailer at alum.rpi.edu Fri Oct 28 06:39:30 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 27 Oct 2005 21:39:30 -0700 Subject: [Tutor] IDLE error msgs and line continuations? In-Reply-To: <7e3eab2c0510272006x66090ce4gff02623b2662a5d0@mail.gmail.co m> References: <7e3eab2c0510272006x66090ce4gff02623b2662a5d0@mail.gmail.com> Message-ID: <6.1.2.0.0.20051027213745.03699d20@mail.mric.net> At 08:06 PM 10/27/2005, Jason Massey wrote: >All you need is the line continuation character, '\': > >if (condition 123 and \ > condition 456) : Did you test that (or even read it)? That is a syntax error line continuation or not! Also recall that the parentheses obviate the need for the \. From falcon3166 at hotmail.com Fri Oct 28 06:42:06 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 27 Oct 2005 22:42:06 -0600 Subject: [Tutor] Can anyone help me? In-Reply-To: <6.1.2.0.0.20051027213152.02780158@mail.mric.net> Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051027/8bb5bd9f/attachment.htm From johanmeskenscs3 at chromaticspaceandworld.com Fri Oct 28 06:50:14 2005 From: johanmeskenscs3 at chromaticspaceandworld.com (Johan Meskens CS3 jmcs3) Date: Fri, 28 Oct 2005 06:50:14 +0200 Subject: [Tutor] equivalent of 'last' in perl Message-ID: <4361AE06.3090406@chromaticspaceandworld.com> hi is that if flag == 1: break ? thanks jmcs3 From andrade1 at umbc.edu Fri Oct 28 07:22:50 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Fri, 28 Oct 2005 01:22:50 -0400 (EDT) Subject: [Tutor] syracuse sequence (collatz or hailstone) Message-ID: <3833.172.168.38.88.1130476970.squirrel@172.168.38.88> Hello I am trying to create a program that will calculate the syracuse sequence which is also known as collatz or hailstone. the number that is input by the user may be either even or odd. the number goes through a series of functions which are x/2 if the number is even and 3x+1 if the number is odd. it keeps doing so until the number reaches 1. An example would be if the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence for the value that they started with. My code currently just prints a 1 and none of the numbers that would have preceded it. any ideas on how I could get the program to not do this would be greatly appreciated. def main(): try: x = input("Please enter a starting value: ") while x != 1: if x%2 == 0: x = x/2 else: x = x*3+1 except ValueError, excObj: msg = str(excobj) if msg == "math domain error": print "No negatives or decimals." else: print "Something went wrong." print "The Syracuse sequence of your starting value is:", x main() From johan at accesstel.co.za Fri Oct 28 09:00:39 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 28 Oct 2005 09:00:39 +0200 Subject: [Tutor] os.system sending of break signals In-Reply-To: <00d501c5db43$fe24bf00$0a01a8c0@xp> References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> Message-ID: <4361CC97.3020500@accesstel.co.za> So far: I tried >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt') You will see that I send the output from the command to a file, because I want to test how stop the command before it reaches 100 pings. If I don't write the output to the file 'cap2.txt' and succeeds in closing 'f', all the data returned to 'f' will be lost. If i use: >>>f.close() Then 'f' is not closed and the commands until 100 packets has been send. So, I am still looking for a way to stop the command before it terminates by itself. I will not be able to get the process ID in all he cases to kill it that way. Then I tried : >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap3.txt') >>> f (', mode 'w' at 0x40389530>, ', mode 'r' at 0x404a69f8>) >>> f[0].close() >>> f[1].close() >>> f (', mode 'w' at 0x40389530>, ', mode 'r' at 0x404a69f8>) This as you can see closes the fd's but the command is not terminated, because I can see my filesize is growing. Any other Ideas or what am I doing wrong? TIA, Alan Gauld wrote: >> I send a command to os.system(cmd) and want to send a break signal in >> the same way. Is this possible? The break signal is ctrl c (^c). >> I tried this, but it didn't work: os.system('\x03') I think Hex 03 is >> the signal for ctrl c. > > > Its not possible with os.system because os.system runs the called > program to completion in a separate process. You would need to mess > about with threads and process ids to do it that way. However if you > use popen() (or maybe popen2()? )you should be able to send a Ctrl-C > character to the process. However whether that actually terminates it > will depend on the OS, the process and whether Ctrl-C is being caught > anywhere. But at least there's a chance of it working! > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > From alan.gauld at freenet.co.uk Fri Oct 28 10:00:01 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 09:00:01 +0100 Subject: [Tutor] os.system sending of break signals References: <4360E467.1090500@accesstel.co.za><00d501c5db43$fe24bf00$0a01a8c0@xp> <172730505261.20051027182415@columbus.rr.com> Message-ID: <010201c5db95$99709730$0a01a8c0@xp> > Python has a "signal" module in the standard library. Will that work? Yes potentially, but you still need to mess about with process ids etc to find which process to send the signal... And you would have to do the two things in separate threads since system() blocks your main program. Alan g From alan.gauld at freenet.co.uk Fri Oct 28 10:01:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 09:01:21 +0100 Subject: [Tutor] Can anyone help me? References: Message-ID: <010801c5db95$c9095810$0a01a8c0@xp> Nathan, look at the functions in the random module. randrange() would be one potential candidate. Alan G ----- Original Message ----- From: "Nathan Pinno" To: Sent: Friday, October 28, 2005 3:07 AM Subject: [Tutor] Can anyone help me? Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how to, please? Thanks, Nathan Pinno For great sites go to: http://falcon3166.tripod.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty From alan.gauld at freenet.co.uk Fri Oct 28 10:07:36 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 09:07:36 +0100 Subject: [Tutor] os.system sending of break signals References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> <4361CC97.3020500@accesstel.co.za> Message-ID: <011601c5db96$a89a0290$0a01a8c0@xp> > >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt') > > You will see that I send the output from the command to a file, because > I want to test how stop the command before it reaches 100 pings. > If I don't write the output to the file 'cap2.txt' and succeeds in > closing 'f', all the data returned to 'f' will be lost. You can read the output of popen into your program with f.read(), but that will read all of the output after the program has run. However I think you can readline() too to catch it line by line. You can also write() data to f thus allowing you to send your Ctrl-C.(You may need popen2 or even popen3 to do the simultaneous read//write bit. #Or better still use the new subprocess module in v2.4) Does that do what you need? Alan G From johan at accesstel.co.za Fri Oct 28 10:21:46 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 28 Oct 2005 10:21:46 +0200 Subject: [Tutor] os.system sending of break signals In-Reply-To: <011601c5db96$a89a0290$0a01a8c0@xp> References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> <4361CC97.3020500@accesstel.co.za> <011601c5db96$a89a0290$0a01a8c0@xp> Message-ID: <4361DF9A.3080106@accesstel.co.za> If I use popen2, I need to write to one of the tuple parts. >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt') >>> f[0].write('\x03') Thank command works, but 'f[1]' is in read-only mode and I can't write to it. My command in the background is still not terminated. BTW I use Linux as OS. So, it doesn't work. Alan Gauld wrote: >> >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt') >> >> You will see that I send the output from the command to a file, >> because I want to test how stop the command before it reaches 100 pings. >> If I don't write the output to the file 'cap2.txt' and succeeds in >> closing 'f', all the data returned to 'f' will be lost. > > > You can read the output of popen into your program with > f.read(), but that will read all of the output after the program has > run. However I think you can readline() too to catch it line by line. > You can also write() data to f thus allowing you to send your > Ctrl-C.(You may need popen2 or even popen3 to do the simultaneous > read//write bit. #Or better still use the new subprocess module in v2.4) > > Does that do what you need? > > Alan G > From singletoned at gmail.com Fri Oct 28 10:29:53 2005 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 28 Oct 2005 09:29:53 +0100 Subject: [Tutor] OT - Re: Can anyone help me? Message-ID: <34bb7f5b0510280129v4fd096c1m@mail.gmail.com> You can actually increase your chance of winning in the English lottery. If two many tickets win a prize in one draw, the lowest prize (?10 for three numbers) is not paid out. Also the jackpot is shared between all the winning tickets (6 numbers) some sets of numbers like 1,2,3,4,5,6 are chosen by over 20,000 people a week. You would share the jackpot with 20,000 other people. Picking random numbers makes you less likely to chose the same numbers as everyone else. Incidently, the odds of winning the jackpot are 1 in 14 million (roughly). I've seen the jackpot go up to ?25million which makes it theoretically a good bet. Ed On 28/10/05, bob wrote: > At 07:07 PM 10/27/2005, Nathan Pinno wrote: > >Hey all, > >I am trying to create a program that draws 6 numbers between 1 and 49 at > >random for creating lottery tickets. I want to have a better chance when I > >play. > > Define "better chance". Lottery odds are how many tickets you buy relative > to how many tickets everyone else has bought. No program will improve or > degrade your odds. The only way you can reduce your odds is to buy more > than one ticket with the same numbers. > > Keep in mind that a lottery is as truly random as one can get (assuming no > rigging). There is no memory of past outcomes involved nor of better > guessing techniques. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Fri Oct 28 11:14:14 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 10:14:14 +0100 Subject: [Tutor] os.system sending of break signals References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> <4361CC97.3020500@accesstel.co.za> <011601c5db96$a89a0290$0a01a8c0@xp> <4361DF9A.3080106@accesstel.co.za> Message-ID: <011a01c5db9f$f7aa18d0$0a01a8c0@xp> > >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt') > >>> f[0].write('\x03') > > Thank command works, but 'f[1]' is in read-only mode and I can't write > to it. > My command in the background is still not terminated. Thats almost certainly because ping never reads its input. In that case you'll need to send a kill signal to the process and to do that you need to find the process ID. I'm not sure if popen() provides access to the PID but if not you could either search for it (this might be too slow) or just drop down to use fork rather than popen, as fork will return the PID. Alan G. From johan at accesstel.co.za Fri Oct 28 11:57:02 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 28 Oct 2005 11:57:02 +0200 Subject: [Tutor] os.system sending of break signals In-Reply-To: <011a01c5db9f$f7aa18d0$0a01a8c0@xp> References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> <4361CC97.3020500@accesstel.co.za> <011601c5db96$a89a0290$0a01a8c0@xp> <4361DF9A.3080106@accesstel.co.za> <011a01c5db9f$f7aa18d0$0a01a8c0@xp> Message-ID: <4361F5EE.2050308@accesstel.co.za> With what can I try and see what the PID is when using popen() or popen2() ? One thing that I noticed now is that when using popen() and the sys.exit(). The command is completed before my Python shell is terminated and if I use popen2(), sys.exit() works immediately but the ping command runs still as a process untill completed. Alan Gauld wrote: >> >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt') >> >>> f[0].write('\x03') >> >> Thank command works, but 'f[1]' is in read-only mode and I can't >> write to it. >> My command in the background is still not terminated. > > > Thats almost certainly because ping never reads its input. > In that case you'll need to send a kill signal to the process and > to do that you need to find the process ID. I'm not sure if popen() > provides access to the PID but if not you could either search for it > (this might be too slow) or just drop down to use fork rather than > popen, as fork will return the PID. > > > Alan G. > From johan at accesstel.co.za Fri Oct 28 11:59:09 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 28 Oct 2005 11:59:09 +0200 Subject: [Tutor] OT - Re: Can anyone help me? In-Reply-To: <34bb7f5b0510280129v4fd096c1m@mail.gmail.com> References: <34bb7f5b0510280129v4fd096c1m@mail.gmail.com> Message-ID: <4361F66D.1080003@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/251b19e6/attachment.htm From kent37 at tds.net Fri Oct 28 11:59:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 05:59:38 -0400 Subject: [Tutor] Passing Functions or Code as Parameters In-Reply-To: <34bb7f5b0510280150m36eff409u@mail.gmail.com> References: <34bb7f5b0510270601u756d2f0aq@mail.gmail.com> <4360D618.40806@tds.net> <34bb7f5b0510270917r7c338a73y@mail.gmail.com> <4361016C.2000609@tds.net> <34bb7f5b0510280150m36eff409u@mail.gmail.com> Message-ID: <4361F68A.7020900@tds.net> Ed Singleton wrote: > On 27/10/05, Kent Johnson wrote: > >>Ed Singleton wrote: >>>Can I pass a block of code that will be executed within the function's >>>scope? >> >>Yes, you can define a function within traverse() and pass that function to things_to_do(), but I don't know how that will help. > > > I was thinking more of something I think I read in Ruby where you can > pass a block of code to a function and it will perform the block of > code at each iteration, and you can operate within the scope of the > function. (I think they were actually called blocks or something). Ruby has code blocks which are passed to a function. They are widely used in Ruby. The closest equivalent in Python 2.4 is to pass a function to the other function. This has much the same capabilities as Ruby blocks but not as natural a syntax. There is a proposal to add a similar capability to Python but it has not been finalized - see PEP 343: http://www.python.org/peps/pep-0343.html Kent -- http://www.kentsjohnson.com From kent37 at tds.net Fri Oct 28 12:02:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 06:02:29 -0400 Subject: [Tutor] syracuse sequence (collatz or hailstone) In-Reply-To: <3833.172.168.38.88.1130476970.squirrel@172.168.38.88> References: <3833.172.168.38.88.1130476970.squirrel@172.168.38.88> Message-ID: <4361F735.4020107@tds.net> andrade1 at umbc.edu wrote: > Hello > > I am trying to create a program that will calculate the syracuse sequence > which is also known as collatz or hailstone. the number that is input by > the user may be either even or odd. the number goes through a series of > functions which are x/2 if the number is even and 3x+1 if the number is > odd. it keeps doing so until the number reaches 1. An example would be if > the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence > for the value that they started with. My code currently just prints a 1 > and none of the numbers that would have preceded it. any ideas on how I > could get the program to not do this would be greatly appreciated. > > > def main(): > try: > x = input("Please enter a starting value: ") > while x != 1: > > if x%2 == 0: > x = x/2 > else: > x = x*3+1 Above you have a loop. Each time through the loop you change the value of x. You don't retain the old value of x so it is lost. The simplest thing would be to print x in the loop so each successive value is shown to the user. Kent > > except ValueError, excObj: > msg = str(excobj) > if msg == "math domain error": > print "No negatives or decimals." > else: > print "Something went wrong." > > > > print "The Syracuse sequence of your starting value is:", x > > main() > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com From johan at accesstel.co.za Fri Oct 28 12:12:07 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 28 Oct 2005 12:12:07 +0200 Subject: [Tutor] Can anyone help me? In-Reply-To: <155744839041.20051027222309@columbus.rr.com> References: <155744839041.20051027222309@columbus.rr.com> Message-ID: <4361F977.7030409@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/3739ebaa/attachment.html From johan at accesstel.co.za Fri Oct 28 12:49:34 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 28 Oct 2005 12:49:34 +0200 Subject: [Tutor] Random number generator (was: Can anyone help me?) In-Reply-To: <4361F977.7030409@accesstel.co.za> References: <155744839041.20051027222309@columbus.rr.com> <4361F977.7030409@accesstel.co.za> Message-ID: <4362023E.5000406@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/e7ca8711/attachment.html From kent37 at tds.net Fri Oct 28 13:46:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 07:46:01 -0400 Subject: [Tutor] os.system sending of break signals In-Reply-To: <4361CC97.3020500@accesstel.co.za> References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> <4361CC97.3020500@accesstel.co.za> Message-ID: <43620F79.4040508@tds.net> Johan Geldenhuys wrote: > So far: > I tried > >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt') > > You will see that I send the output from the command to a file, because > I want to test how stop the command before it reaches 100 pings. > If I don't write the output to the file 'cap2.txt' and succeeds in > closing 'f', all the data returned to 'f' will be lost. > > If i use: > >>>f.close() > Then 'f' is not closed and the commands until 100 packets has been send. > > So, I am still looking for a way to stop the command before it > terminates by itself. I will not be able to get the process ID in all he > cases to kill it that way. Trent Mick's process.py shows how to kill a process started from Python. http://starship.python.net/crew/tmick/ Kent From kent37 at tds.net Fri Oct 28 13:48:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 07:48:11 -0400 Subject: [Tutor] Random number generator In-Reply-To: <4362023E.5000406@accesstel.co.za> References: <155744839041.20051027222309@columbus.rr.com> <4361F977.7030409@accesstel.co.za> <4362023E.5000406@accesstel.co.za> Message-ID: <43620FFB.3050503@tds.net> Johan Geldenhuys wrote: > After I tested the previous code, I noticed that the odds is 1:49 that a > duplicate number can be found in the 6 digit range (and it happended) > and that 0 can also be found. Look at random.sample() for a simpler way to do this. Kent > > Here is the fix: > > import random > > def randnum(): > c = [] > for x in range(6): > s = random.randrange(0, 50) > if s not in c: > c.append(s) > else: > return > print ('Randoms: ',c) > > c = [] > > if __name__ == '__main__': > > for x in range(10): # For number of 6-digit sequences > randnum() > > AYS? > >> >> >> R. Alan Monroe wrote: >> >>>>Hey all, >>>>I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how >>>>to, please? >>>> >>>> >>> >>>Create (empty for now) list to hold your final numbers. >>>Have a for-loop that runs 6 times using range(6) >>>Inside the loop, just pick a random number and append it to your final >>>number list. >>> >>>Alan >>> >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>------------------------------------------------------------------------ >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://www.kentsjohnson.com From kent37 at tds.net Fri Oct 28 13:58:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 07:58:41 -0400 Subject: [Tutor] File IO help In-Reply-To: <1562.87.242.128.120.1130371282.squirrel@www.abdn.ac.uk> References: <1562.87.242.128.120.1130371282.squirrel@www.abdn.ac.uk> Message-ID: <43621271.3070903@tds.net> Mike Haft wrote: > Hello all, > I'm new to python but so far I have to say its a really good language > > I've been having some trouble with File IO can anyone help? I've got the > basics but my problem is that I have many files (one for each year of the > last 100 years or so) that look like this: > > MONTH RAIN AVTEMP RAD EVAP > **************************************** > 1 12.4 12.0 * 10 > 2 13.9 30.0 * 11 > 3 > > etc until month 12 > > So far all I know how to do in Python looks something like this: > > def readInFile(inputName): > input = open(inputName, "r") > result = [] > for line in input: > if line[:1] == "1": > fields = line.split() > data = fields[1] + fields[2] + fields[7] > result.append(data) > input.close() > return result As you know this program returns data for the months that start with 1. Since you really want the data for all the months, you should just take out the conditional: for line in input: fields = line.split() data = fields[1] + fields[2] + fields[7] result.append(data) Now result will have the data for all the months in order (though from your sample data there doesn't seem to be a field 7?). > > Thats basically all I've been able to do but I need to write script that > opens a file, reads the relevent data, stores that data and then closes > the file and moves on to the next file repeating the action until all the > files have been read. Then it needs to write a file with all the data it > has collected but in a different format. To do this you need a list of the files to read, and a loop that calls readInFile() for each file and stores the data somewhere. Then you need another function to write out the data to a new file. > > If anyone can help I'd be really grateful. I hope I'm not asking too much > of the list but I haven't found anything that says READ THIS BEFORE > POSTING! on it to tell me otherwise. Beginner questions are welcome. Have you read a tutorial or introductory book? It might give you some help with the basics. See this page for suggestions: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From sowden at gmail.com Fri Oct 28 14:08:28 2005 From: sowden at gmail.com (Eddie S) Date: Fri, 28 Oct 2005 13:08:28 +0100 Subject: [Tutor] Joining non strings in to string Message-ID: <3082bc030510280508o68b7ea83g@mail.gmail.com> Hi, I have a list containing numbers. I want to join this list in to a string which I can then output. The problem is I cant seem to join list of non-string items in to a string. My list looks something like: list = [5,7,20,19,49,32] I could loop through the list outputing each number individually but I am sure there is a nicer method of doing it. Cheers Eddie From ml.cyresse at gmail.com Fri Oct 28 14:39:33 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 29 Oct 2005 01:39:33 +1300 Subject: [Tutor] os.system sending of break signals In-Reply-To: <011601c5db96$a89a0290$0a01a8c0@xp> References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> <4361CC97.3020500@accesstel.co.za> <011601c5db96$a89a0290$0a01a8c0@xp> Message-ID: Alan Gauld wrote: > > You can read the output of popen into your program with > f.read(), but that will read all of the output after the program > has run. However I think you can readline() too to catch it > line by line. You can also write() data to f thus allowing you > to send your Ctrl-C.(You may need popen2 or even popen3 > to do the simultaneous read//write bit. #Or better still use > the new subprocess module in v2.4) > Quick query with os.popen, popen2,3,4. Playing with IronPython, and decided to see what I could do with os.popen() and it. With the various popens, calling read() would block, as would calling readline() when what was currently displayed was the ">>>" prompt. What would be causing this? Is it because having displayed the ">>>" IronPython is looping waiting for input? It was pure mucking about, really, but curiosity... the .NET framework has some sane access to various bits of Win32, and if it weren't for the grinding loadtime of the CLR, I'd like to use IronPython scripts to get data which normal Python could then grab as text (on account of how there's no compatiable serialisation between the two), thus forgoing having to deal with the Win32 API. Regards, Liam Clarke From ml.cyresse at gmail.com Fri Oct 28 14:42:03 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 29 Oct 2005 01:42:03 +1300 Subject: [Tutor] os.system sending of break signals In-Reply-To: <011a01c5db9f$f7aa18d0$0a01a8c0@xp> References: <4360E467.1090500@accesstel.co.za> <00d501c5db43$fe24bf00$0a01a8c0@xp> <4361CC97.3020500@accesstel.co.za> <011601c5db96$a89a0290$0a01a8c0@xp> <4361DF9A.3080106@accesstel.co.za> <011a01c5db9f$f7aa18d0$0a01a8c0@xp> Message-ID: On 10/28/05, Alan Gauld wrote: > > >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt') > > >>> f[0].write('\x03') > > > > Thank command works, but 'f[1]' is in read-only mode and I can't write > > to it. > > My command in the background is still not terminated. > > Thats almost certainly because ping never reads its input. > In that case you'll need to send a kill signal to the process and > to do that you need to find the process ID. I'm not sure if > popen() provides access to the PID but if not you could > either search for it (this might be too slow) or just drop > down to use fork rather than popen, as fork will return > the PID. Would calling PS via another popen() and using string methods to get the Pid work? I'm rather new to Linux & Python... Regards, Liam Clarke From kraus at hagen-partner.de Fri Oct 28 15:01:15 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 28 Oct 2005 15:01:15 +0200 Subject: [Tutor] Joining non strings in to string In-Reply-To: <3082bc030510280508o68b7ea83g@mail.gmail.com> References: <3082bc030510280508o68b7ea83g@mail.gmail.com> Message-ID: Eddie S wrote: > Hi, > I have a list containing numbers. I want to join this list in to a > string which I can then output. The problem is I cant seem to join > list of non-string items in to a string. > > My list looks something like: > > list = [5,7,20,19,49,32] > > I could loop through the list outputing each number individually but I > am sure there is a nicer method of doing it. > > Cheers Eddie Use List Comprenhensions, join() and str(): numlist = [5,7,20,19,49,32] ','.join([str(x) for x in numlist]) BTW: never use "list" as a name for your list http://docs.python.org/tut/node7.html#SECTION007140000000000000000 HTH, Wolfram From ml.cyresse at gmail.com Fri Oct 28 15:21:59 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 29 Oct 2005 02:21:59 +1300 Subject: [Tutor] Fwd: File IO help In-Reply-To: References: <1562.87.242.128.120.1130371282.squirrel@www.abdn.ac.uk> Message-ID: On 10/27/05, Mike Haft wrote: > Hello all, > I'm new to python but so far I have to say its a really good language > > I've been having some trouble with File IO can anyone help? I've got the > basics but my problem is that I have many files (one for each year of the > last 100 years or so) that look like this: > > MONTH RAIN AVTEMP RAD EVAP > **************************************** > 1 12.4 12.0 * 10 > 2 13.9 30.0 * 11 > 3 > > Thats basically all I've been able to do but I need to write script that > opens a file, reads the relevent data, stores that data and then closes > the file and moves on to the next file repeating the action until all the > files have been read. Then it needs to write a file with all the data it > has collected but in a different format. Hi Mike, **forward to list also... Couple of things you'll need to get familiar with, to make your life easier, are the os and os.path module. I assume you've got all your files in one directory. os.listdir(directory) will return a list of all the files/directories in that directory. If you've got other directories in there as well, you can use os.path.isdir() to check if a given path is a directory or not. As listdir returns the names, and you need the full-path for simplicity, and also because os.path.isdir() requires it, you can use os.path.join() to join the directory and filename in a platform independent way. So, for example, to find only the files in my python directory import os import os.path dirPath = "c:/python24" #Either. filePaths = [] for item in os.listdir(dirPath): fullpath = os.join(dirPath, item) if not os.path.isdir(fullpath): filepaths.append(fullpath) for item in filePaths: parsedataFunc(item) #Or names = os.listdir(dirPath) for item in names: fullpath = os.join(dirPath, item) if os.path.isdir(fullpath): continue else: parsedataFunc(item) #Or, if you really want filePaths = [os.path.join(direc, item) for item in os.listdir(direc) if not os.path.isdir(os.path.join(direc, item))] for item in filePaths: parseDataFunc(item) With regards to your data, you seem to be turning it into a string... what format are you looking to write out? If it's tab/comma delimited, check out the csv module also. I'd recommend just ignoring the header lines, so you're only dealing with the data, assuming that your column headers remain static. for line in dataFile: if line.startswith("MONTH") or line.startswith("**"): continue And that will skip that line. Hope that helps, good luck handling wx data. I just used to import it into Excel and spend several hours swearing... I hope Python treats you better. And, a question for the group, I've always found that line[:1] is a complicated way of writing line[0]... is there any time when line[:1] != line[0]? Regards, Liam Clarke From ml.cyresse at gmail.com Fri Oct 28 15:23:00 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 29 Oct 2005 02:23:00 +1300 Subject: [Tutor] File IO help In-Reply-To: References: <1562.87.242.128.120.1130371282.squirrel@www.abdn.ac.uk> Message-ID: Oops, filePaths = [os.path.join(direc, item) for item in os.listdir(direc) if not os.path.isdir(os.path.join(direc, item))] should be > filePaths = [os.path.join(dirPath, item) for item in os.listdir(dirPath) > if not os.path.isdir(os.path.join(dirPath, item))] ... From ml.cyresse at gmail.com Fri Oct 28 15:26:46 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 29 Oct 2005 02:26:46 +1300 Subject: [Tutor] File IO Help again In-Reply-To: <6.1.2.0.0.20051027212843.0277bfe8@mail.mric.net> References: <2906.84.43.113.85.1130440722.squirrel@www.abdn.ac.uk> <6.1.2.0.0.20051027131622.036019b0@mail.mric.net> <6.1.2.0.0.20051027212843.0277bfe8@mail.mric.net> Message-ID: Heh, Cut 'im some slack there Bob, I only just figured out that line[:1] == line[0]... On 10/28/05, bob wrote: > At 01:42 PM 10/27/2005, Adam wrote: > > >if line[:1] == "1": > > > >This line won't work because you're getting the first 2 characters from > >the line > > Oh? Did you test that? When I do that I get 1 character. Why? Because > slicing goes UP TO the 2nd argument. > >>> 'abc'[:1] > 'a' > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Oct 28 15:44:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 09:44:01 -0400 Subject: [Tutor] Fwd: File IO help In-Reply-To: References: <1562.87.242.128.120.1130371282.squirrel@www.abdn.ac.uk> Message-ID: <43622B21.3040607@tds.net> Liam Clarke wrote: > And, a question for the group, I've always found that line[:1] is a > complicated way of writing line[0]... is there any time when line[:1] > != line[0]? Actually I would say that the general case is for them to be different and in the special case where line is a string they are the same. line[0] means, "the first element of the sequence line" line[:1] means, "the sequence consisting of everything from the start of line up to (but not including) line[1]" If line is a list, these two meanings are different: >>> r=range(4) >>> r [0, 1, 2, 3] >>> r[0] 0 >>> r[:1] [0] In the case of a string, line[0] is actually a sequence itself - a new string. This is kind of strange, really, that an element of a sequence can be the same as a subsequence of the sequence. It is a consequence of Python not having a character type - single characters are represented as strings. Kent -- http://www.kentsjohnson.com From bgailer at alum.rpi.edu Fri Oct 28 16:16:34 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 28 Oct 2005 07:16:34 -0700 Subject: [Tutor] Can anyone help me? In-Reply-To: References: <6.1.2.0.0.20051027213152.02780158@mail.mric.net> Message-ID: <6.1.2.0.0.20051028062133.036fd578@mail.mric.net> At 09:42 PM 10/27/2005, Nathan Pinno wrote: >If I create a program that randomly draws 6 numbers, its like the lottery. >According to an article I read in Reader's Digest, if you get a Quick Pick >- which is six numbers at random - you increase your odds of winning. Odds are how many tickets you buy relative to how many tickets everyone else has bought. Has nothing to do with the mechanism for generating numbers. Any guesses you make are "random". You might as well buy fortune cookies and copy the numbers in them. Or add 1 to each number. Or .... No action on your part will ensure that you win, or give you a better shot at winning than anyone else. >I want to create a program that will imitate the Quick Pick process for >myself. So ask the lottery people what random number algorithm they use and program it for yourself. Not that doing that will make any difference. From ml.cyresse at gmail.com Fri Oct 28 16:19:38 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 29 Oct 2005 03:19:38 +1300 Subject: [Tutor] Python as Application (OT now) Message-ID: On 10/27/05, Lee Harr wrote: > >My son is learning something about using a spreadsheet - extremely > >useful and I support it 100%. That he thinks what he is learning is > >Excel is absolutely unforgivable, in terms of my understanding of > >ethical norms that once prevailed in an institute of higher education. > > I've never worked in any workplace where anything else other than Excel was used. For a majority (pick a percentage out of the air) of workplaces, Excel will be used as well. Why? Because everyone uses it. Yes, it's horribly circular, but I would like to offer the pragmatic view on this. > >We understand that all the functionality he will ever need from Excel is > >available for free in other spreadsheet software. > > Probably couldn't leave nasty scripted easter eggs in your bosse's favourite spreadsheet upon finding a new job so easily... > Probably. Anything beyond the common spreadsheet functions is almost > certainly better done another way. > For better or worse, Excel is the market leader because Lotus 1-2-3 isn't anymore, so they had to have done something right along the way. It also depends on what you'd call common spreadsheet functions. > > More frightening to me than the ubiquitous use of MS Office is the > omnipresence of windows. Every time a student sits down in front > of KDE in our lab and says "Where is the internet?" I can only cringe. As one who's recently installed Ubuntu, and played with Gnome/KDE/XFCE among others, I can't honestly see any advantage from an open source GUI environment, other than the fee. When I was learning how to use computers, the phrase "X11 Windows Server" would've left me terrified to use a GUI, lest I be incurring charges for connecting to the internet. Gnome & KDE run worse than Windows XP does on my computer, which I'm somewhat gobsmacked about still, as I can't really see why that would be so. I would blame the composite windows, but XFCE does them fine. I note that with the release of Breezy Badger, XFCE is what you get from using startx at console, which is nice. I do wonder why you cringe. Educate the user. He is expecting his usual metaphor, and it's not there. The majority of the world has it, remember, so he expects you to as well. I must apologise, but I'm detecting a slight theme of... dedication to open source from both of you gentlemen. Open source is a wonderful and lovely thing, but it has it's flaws, as does a certain corporation dominant in the market. If you look at ease-of-use for beginners, you can see why the majority of computer users, a great deal of whom have had to learn how to use them to stay viable in the job market, but really don't understand them, learn Windows & MS Office, which is usually more applicable in the job market, and then stick with what they know. As a semi-coherent bunch of metaphors, Windows does alright. 98% of Office's features aren't used by anyone, but they can get the basics done. With regard to moving to Open Office... I've worked with people who have books of 'pathways'. The Copy pathway is 'Select text > Edit > Copy' and trying to teach them about the wonders of Control + C is a dead end. These people resent any and all change. When a recent workplace of mine moved to Mozilla, there were some very unhappy people, and in the end, they relented and reinstalled IE for those who really wanted it. Don't mess with the pathways. > Microsoft may not own the internet, but that is not what we are > teaching. I seriously get about 10% of users who are unable to > see any other browser as performing the same function as > internet explorer. This is annoying, when the head of IT has made his living chanting "Outsource" and his favourite outsourcing firm says "Only if it's Microsoft." as it means I can't get a browser with tabs. > If "what is a spreadsheet?" is pretty scary. "What is a browser?" is > downright terrifying. > I get that all the time at work, as I take calls from people who are having trouble using my employer's website. Generally it's cookies/caching, which is simple, and 1 out of 20 people will say "Oh right, my cookies, yeah no worries." and hang up. The other 19.... as there's different... 'pathways' for various browsers, we ask "What browser do you use?", followed by "A browser is the programme you use to view web-pages." and then "No... that's your ISP. Can you click the Help menu... It's right up the top... No, it is there. Can you see the word File? At the other end of the list of words, it should say Help. Ok, now click on Help. Down the bottom it will say About, can you read that out? Okay, you have Internet Explorer!" This is a website used to form limited liability companies (www.companies.govt.nz), search the companies database, and is generally very useful, and a lot of people will use their minimal skill and get hopelessly out of their depth, as they've installed 4 programmes which block cookies, and don't know how to disable them. Or there's the ones who threaten to sue for discrimination due to lower fees for online services... > >Do I care that I am made to feel that this point of view is somehow > >radical on a educational forum that is an offshoot of an open source > >software community. > > > > Hmm... more like "preaching to the choir" isn't it? > I really can't see why focusing teaching on Microsoft products is considered bad, other than from an ideological point of view. Certainly, teaching Lotus 1-2-3 to the exclusion of all else would be bad, as it would contain product specific knowledge for a nearly non-existent product. Likewise, to emphasise open source products at the expense of the products which employers will expect you to know is to also do a disservice to the students in question. You can't really separate spreadsheet from Excel, or word processing from Word, in the general public's view. I can name about four of each type of programme, but 3 of those are from the days when I considered an alternative OS to be DR-DOS. I like open source, I love Python, I love Gimp, I adore Bash, and Gaim is sweet. XFCE is awesome, and made up greatly for the let-down of Gnome. I hate Microsoft's "tie in" where when I wish to build a C# assembly it tells me I need to open it in Visual Studio and save it again, but I love .NET and Monad. I hate open source documentation, and I hate the fact that Firefox's right click context menu isn't, because of open source. I have "Back, Forward, Reload, Stop" in my context menu, entirely un-necessary, I don't need them, and they're very out of context when I click on an image. And, they're here, because of the way open source works - https://bugzilla.mozilla.org/show_bug.cgi?id=136665 But, I love Firefox. Liam Clarke From bgailer at alum.rpi.edu Fri Oct 28 16:23:28 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 28 Oct 2005 07:23:28 -0700 Subject: [Tutor] equivalent of 'last' in perl In-Reply-To: <4361AE06.3090406@chromaticspaceandworld.com> References: <4361AE06.3090406@chromaticspaceandworld.com> Message-ID: <6.1.2.0.0.20051028071823.036eec58@mail.mric.net> At 09:50 PM 10/27/2005, Johan Meskens CS3 jmcs3 approximated: >what is Python's equivalent of 'last' in perl? > >if flag == 1: > break Yes. If flag is either 1 or 0 you may code it thus: if flag: break That's not the whole truth. Most types have a value that is seen as false in boolean expressions. They includes 0 '' None False [] (,) {} From jsmith at medplus.com Fri Oct 28 16:28:10 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 28 Oct 2005 10:28:10 -0400 Subject: [Tutor] Can anyone help me? Message-ID: <3B05FA2AD704244BB0CAB99D8026F5554E6130@medexch2.medplus.com> Aren't the odds just based on how many tickets you buy? The odds aren't affected by different people buying more tickets. If only one person buys a ticket in the entire lottery system, his odds of winning are the same as if two people play, and the same as if 20 million play. Jeff -----Original Message----- From: bob [mailto:bgailer at alum.rpi.edu] Sent: Friday, October 28, 2005 10:17 AM To: Nathan Pinno; Tutor at python.org Subject: Re: [Tutor] Can anyone help me? At 09:42 PM 10/27/2005, Nathan Pinno wrote: >If I create a program that randomly draws 6 numbers, its like the >lottery. >According to an article I read in Reader's Digest, if you get a Quick Pick >- which is six numbers at random - you increase your odds of winning. Odds are how many tickets you buy relative to how many tickets everyone else has bought. Has nothing to do with the mechanism for generating numbers. Any guesses you make are "random". You might as well buy fortune cookies and copy the numbers in them. Or add 1 to each number. Or .... No action on your part will ensure that you win, or give you a better shot at winning than anyone else. >I want to create a program that will imitate the Quick Pick process for >myself. So ask the lottery people what random number algorithm they use and program it for yourself. Not that doing that will make any difference. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Fri Oct 28 16:51:57 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 28 Oct 2005 07:51:57 -0700 Subject: [Tutor] Can anyone help me? In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F5554E6130@medexch2.medplus.co m> References: <3B05FA2AD704244BB0CAB99D8026F5554E6130@medexch2.medplus.com> Message-ID: <6.1.2.0.0.20051028073458.036ee2d8@mail.mric.net> At 07:28 AM 10/28/2005, Smith, Jeff wrote: >Aren't the odds just based on how many tickets you buy? The odds aren't >affected by different people buying more tickets. If only one person >buys a ticket in the entire lottery system, his odds of winning are the >same as if two people play, and the same as if 20 million play. According to the wikipedia: "In probability theory and statistics the odds in favor of an event or a proposition are the quantity p / (1-p), where p is the probability of the event or proposition." If you assign equal probability of winning to each ticket then odds are how many tickets you buy relative to how many tickets everyone else has bought. The probability of a ticket winning is 1 / m**n where m is the highest number possible and n is the number of numbers. If a lottery uses 6 numbers each in the range 1..42 then the probability of a ticket winning is 1/5489031744. All of this is mathematics. Sometimes one or more tickets win. Is that "luck"? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/3ce50143/attachment.html From falcon3166 at hotmail.com Fri Oct 28 16:52:18 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 28 Oct 2005 08:52:18 -0600 Subject: [Tutor] ***[Possible UCE]*** Can anyone help me? References: <005d01c5dbba$846c7eb0$6471a8c0@zobook> Message-ID: Thanks Martin. You have a solid point. It would be a fun programming exercise anyway...I haven't programmed in ages it seems. :) Nathan Pinno For great sites go to: http://falcon3166.tripod.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty ----- Original Message ----- From: Marcin Komorowski To: Nathan Pinno Sent: Friday, October 28, 2005 6:19 AM Subject: Re: ***[Possible UCE]*** [Tutor] Can anyone help me? Hey Nathan, I do not think Python, nor any other programming language, nor any other form of analysis can help you here. We all would want to have a better chance in winning 6/49 lottery, but the reality is that each draw in the lottery is what is called an 'independent event', which means there is no correlation between the numbers what so ever. Every pick of 6 numbers has equal probability of winning as every other set of 6 numbers. There are sites out there that do statistical analysis and claim that some numbers are more probable than other, but his is total BS. Given how many possible combination of 6 numbers out of 49 there is, the lottery has not existed long enough to provide sufficient sample set to perform any meaningful statistical analysis. What I am saying is that any increased probabilities they are reporting are only there because we have not had enough draws to show otherwise. Playing lottery might be a fun thing to do, but please, do yourself a favour and don't let yourself be fooled into thinking that there are ways of improving your chances. And even if there were, improving your chance from next-to-none to next-to-next-to-none is not worth it. Do not count on chance to help you financially - there are better ways. Cheers, Marcin ----- Original Message ----- From: Nathan Pinno To: Tutor at python.org Sent: Thursday, October 27, 2005 10:07 PM Subject: ***[Possible UCE]*** [Tutor] Can anyone help me? Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how to, please? Thanks, Nathan Pinno For great sites go to: http://falcon3166.tripod.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty ---------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/ac226ecc/attachment.htm From falcon3166 at hotmail.com Fri Oct 28 17:03:40 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 28 Oct 2005 09:03:40 -0600 Subject: [Tutor] Can anyone help me? References: <010801c5db95$c9095810$0a01a8c0@xp> Message-ID: Hey, I created it. Want to see the code? Here it is: [code] import random numbers = [] while True: q = int(raw_input("Do you want a lottery number drawing? 1 for yes, 2 for no ")) if q == 1: for i in range(6): draw = random.choice(range(1,50)) numbers.append(draw) print numbers numbers = [] elif q == 2: break else: print "Read the instructions please." [/code] Enjoy! Nathan Pinno For great sites go to: http://falcon3166.tripod.com MSN Messenger: falcon3166 at hotmail,com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty ----- Original Message ----- From: "Alan Gauld" To: "Nathan Pinno" ; Sent: Friday, October 28, 2005 2:01 AM Subject: Re: [Tutor] Can anyone help me? > Nathan, > > look at the functions in the random module. > randrange() would be one potential candidate. > > Alan G > > ----- Original Message ----- > From: "Nathan Pinno" > To: > Sent: Friday, October 28, 2005 3:07 AM > Subject: [Tutor] Can anyone help me? > > > Hey all, > I am trying to create a program that draws 6 numbers between 1 and 49 at > random for creating lottery tickets. I want to have a better chance when I > play. Can anyone help me code this or show me how to, please? > Thanks, > Nathan Pinno > For great sites go to: http://falcon3166.tripod.com > MSN Messenger: falcon3166 at hotmail,com > Yahoo! Messenger: spam_swatter31 > ICQ: 199020705 > AIM: f3mighty > From jsmith at medplus.com Fri Oct 28 17:08:22 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 28 Oct 2005 11:08:22 -0400 Subject: [Tutor] Can anyone help me? Message-ID: <3B05FA2AD704244BB0CAB99D8026F5554E6146@medexch2.medplus.com> But the odds that you will win are not impacted by the number of tickets that are sold in total...only the number you buy. When you take into account the total number of tickets sold, all you get are the odds that the lottery will be won by anyone. I'm also a little confused by that def of odds. Consider flipping a coin. The probability that it will come up heads is 1/2. That def says that the odds in favor of it coming up heads is 1. Jeff -----Original Message----- From: bob [mailto:bgailer at alum.rpi.edu] Sent: Friday, October 28, 2005 10:52 AM To: Smith, Jeff; Tutor at python.org Subject: Re: [Tutor] Can anyone help me? At 07:28 AM 10/28/2005, Smith, Jeff wrote: Aren't the odds just based on how many tickets you buy? The odds aren't affected by different people buying more tickets. If only one person buys a ticket in the entire lottery system, his odds of winning are the same as if two people play, and the same as if 20 million play. According to the wikipedia: "In probability theory and statistics the odds in favor of an event or a proposition are the quantity p / (1-p), where p is the probability of the event or proposition." If you assign equal probability of winning to each ticket then odds are how many tickets you buy relative to how many tickets everyone else has bought. The probability of a ticket winning is 1 / m**n where m is the highest number possible and n is the number of numbers. If a lottery uses 6 numbers each in the range 1..42 then the probability of a ticket winning is 1/5489031744. All of this is mathematics. Sometimes one or more tickets win. Is that "luck"? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/2f67dc81/attachment.html From andrade1 at umbc.edu Fri Oct 28 17:59:44 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Fri, 28 Oct 2005 11:59:44 -0400 (EDT) Subject: [Tutor] syracuse sequence (collatz or hailstone) Message-ID: <3209.172.168.38.88.1130515184.squirrel@172.168.38.88> hello, Could I gather all of the values from print x into a string or a range? Since, I am not familiar with lists yet. def main(): x = input("Please enter a positive starting value: ") while x != 1: if x%2 == 0: x = x/2 else: x = x*3+1 print x print "The Syracuse sequence of your starting value is:", x main() ----- Original Message ----- From: "Frank Bloeink" To: Sent: Friday, October 28, 2005 5:06 AM Subject: Re: [Tutor] syracuse sequence (collatz or hailstone) > Hey, > > your code seems almost alright to me, except that in your case it's only > printing the last number of your sequence, which obviously is not what > you want. Quick fix would be to insert a line "print x" just below else > statement: > ---snip-- > else: > x=x*3+1 > print x > ---snip > This should make clear where the error is: You are just calculating, but > not printing the sequence! > If you want to leave the output to the end of the program you could as > well gather all the calculated values in a list or similar structure and > then print the contents of the list.. > > hth Frank > > On Fri, 2005-10-28 at 01:22 -0400, andrade1 at umbc.edu wrote: > > Hello > > > > I am trying to create a program that will calculate the syracuse sequence > > which is also known as collatz or hailstone. the number that is input by > > the user may be either even or odd. the number goes through a series of > > functions which are x/2 if the number is even and 3x+1 if the number is > > odd. it keeps doing so until the number reaches 1. An example would be if > > the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence > > for the value that they started with. My code currently just prints a 1 > > and none of the numbers that would have preceded it. any ideas on how I > > could get the program to not do this would be greatly appreciated. > > > > > > def main(): > > try: > > x = input("Please enter a starting value: ") > > while x != 1: > > > > if x%2 == 0: > > x = x/2 > > else: > > x = x*3+1 > > > > except ValueError, excObj: > > msg = str(excobj) > > if msg == "math domain error": > > print "No negatives or decimals." > > else: > > print "Something went wrong." > > > > > > > > print "The Syracuse sequence of your starting value is:", x > > > > main() > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From bgailer at alum.rpi.edu Fri Oct 28 19:31:45 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 28 Oct 2005 10:31:45 -0700 Subject: [Tutor] Can anyone help me? In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F5554E6146@medexch2.medplus.co m> References: <3B05FA2AD704244BB0CAB99D8026F5554E6146@medexch2.medplus.com> Message-ID: <6.1.2.0.0.20051028085544.02799b28@mail.mric.net> At 08:08 AM 10/28/2005, Smith, Jeff wrote: >But the odds that you will win are not impacted by the number of tickets >that are sold in total...only the number you buy. When you take into >account the total number of tickets sold, all you get are the odds that >the lottery will be won by anyone. > >I'm also a little confused by that def of odds. Consider flipping a >coin. The probability that it will come up heads is 1/2. That def says >that the odds in favor of it coming up heads is 1. Ah there's the rub. Odds are not "in favor". The odds of heads is 1 and the odds of tails is 1. The odds therefore are the same. If you flip 2 coins then the odds of both being heads is 1/3, ditto both tails. Odds of being different is 1/2. > >Jeff > >-----Original Message----- >From: bob [mailto:bgailer at alum.rpi.edu] >Sent: Friday, October 28, 2005 10:52 AM >To: Smith, Jeff; Tutor at python.org >Subject: Re: [Tutor] Can anyone help me? > >At 07:28 AM 10/28/2005, Smith, Jeff wrote: >>Aren't the odds just based on how many tickets you buy? The odds aren't >>affected by different people buying more tickets. If only one person >>buys a ticket in the entire lottery system, his odds of winning are the >>same as if two people play, and the same as if 20 million play. > >According to the wikipedia: "In >probability theory and >statistics the odds in favor of >an event or a proposition are the quantity p / (1-p), where p is the >probability of the event or >proposition." If you assign equal probability of winning to each ticket >then odds are how many tickets you buy relative to how many tickets >everyone else has bought. > >The probability of a ticket winning is 1 / m**n where m is the highest >number possible and n is the number of numbers. If a lottery uses 6 >numbers each in the range 1..42 then the probability of a ticket winning >is 1/5489031744. > >All of this is mathematics. Sometimes one or more tickets win. Is that >"luck"? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/21344dcc/attachment.html From bgailer at alum.rpi.edu Fri Oct 28 19:37:41 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 28 Oct 2005 10:37:41 -0700 Subject: [Tutor] Can anyone help me? In-Reply-To: References: <010801c5db95$c9095810$0a01a8c0@xp> Message-ID: <6.1.2.0.0.20051028103324.0278cc88@mail.mric.net> At 08:03 AM 10/28/2005, Nathan Pinno wrote: >Hey, >I created it. Want to see the code? >Here it is: >[code] >import random >numbers = [] Move this inside the loop following if q == 1 and get rid of the occurrence of this statement following print numbers. Less code, easier to read, more to the point. >while True: > q = int(raw_input("Do you want a lottery number drawing? 1 for yes, 2 >for no ")) This could fail if user enters a string that does not represent an integer. Either stick it in a try: block or leave the input character. I prefer the latter as there is no advantage to treating it as a number. > if q == 1: > for i in range(6): > draw = random.choice(range(1,50)) > numbers.append(draw) > print numbers > numbers = [] > elif q == 2: > break > else: > print "Read the instructions please." >[/code] > >Enjoy! >Nathan Pinno >For great sites go to: http://falcon3166.tripod.com >MSN Messenger: falcon3166 at hotmail,com >Yahoo! Messenger: spam_swatter31 >ICQ: 199020705 >AIM: f3mighty >----- Original Message ----- >From: "Alan Gauld" >To: "Nathan Pinno" ; >Sent: Friday, October 28, 2005 2:01 AM >Subject: Re: [Tutor] Can anyone help me? > > > > Nathan, > > > > look at the functions in the random module. > > randrange() would be one potential candidate. > > > > Alan G > > > > ----- Original Message ----- > > From: "Nathan Pinno" > > To: > > Sent: Friday, October 28, 2005 3:07 AM > > Subject: [Tutor] Can anyone help me? > > > > > > Hey all, > > I am trying to create a program that draws 6 numbers between 1 and 49 at > > random for creating lottery tickets. I want to have a better chance when I > > play. Can anyone help me code this or show me how to, please? > > Thanks, > > Nathan Pinno > > For great sites go to: http://falcon3166.tripod.com > > MSN Messenger: falcon3166 at hotmail,com > > Yahoo! Messenger: spam_swatter31 > > ICQ: 199020705 > > AIM: f3mighty > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Fri Oct 28 21:07:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 20:07:28 +0100 Subject: [Tutor] os.system sending of break signals References: <4360E467.1090500@accesstel.co.za><00d501c5db43$fe24bf00$0a01a8c0@xp> <4361CC97.3020500@accesstel.co.za><011601c5db96$a89a0290$0a01a8c0@xp> <4361DF9A.3080106@accesstel.co.za><011a01c5db9f$f7aa18d0$0a01a8c0@xp> Message-ID: <016901c5dbf2$d743cac0$0a01a8c0@xp> >> to do that you need to find the process ID. I'm not sure if >> popen() provides access to the PID but if not you could >> either search for it (this might be too slow) or just drop >> down to use fork rather than popen, as fork will return >> the PID. > >Would calling PS via another popen() and using string methods to get > the Pid work? That was my initial thought but there may be better tricks available in pythons os arsenal, I need to take a peek.... Nope can't see anything obvious. The snag with using ps is that it can be easy to find duplicate processes with the same name so you need to check the user ID and start time against when the local process launched its vdersion, and its still not foolproof Personally I'd go down the fok/exec route. It works something like: pid = fork() if pid == 0: exec(myprog) else: sleep(1) os.kill(pid,SIGINT) HTH, Alan G From kent37 at tds.net Fri Oct 28 21:22:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 15:22:10 -0400 Subject: [Tutor] syracuse sequence (collatz or hailstone) In-Reply-To: <3209.172.168.38.88.1130515184.squirrel@172.168.38.88> References: <3209.172.168.38.88.1130515184.squirrel@172.168.38.88> Message-ID: <43627A62.7080402@tds.net> andrade1 at umbc.edu wrote: > hello, > > Could I gather all of the values from print x into a string or a range? > Since, I am not familiar with lists yet. Here is a simple example of gathering values into a list and making a string: >>> r=[] # Start with an empty list >>> for x in range(3): # x will be 0, 1, 2 in sequence ... r.append(str(x*x)) # Put x*x (as a string) onto r ... >>> r ['0', '1', '4'] >>> ', '.join(r) # make a single string by joining the elements of r with ', ' '0, 1, 4' Kent > > > def main(): > x = input("Please enter a positive starting value: ") > while x != 1: > if x%2 == 0: > x = x/2 > else: > x = x*3+1 > print x > print "The Syracuse sequence of your starting value is:", x > > main() > > > > > ----- Original Message ----- > From: "Frank Bloeink" > To: > Sent: Friday, October 28, 2005 5:06 AM > Subject: Re: [Tutor] syracuse sequence (collatz or hailstone) > > > >>Hey, >> >>your code seems almost alright to me, except that in your case it's only >>printing the last number of your sequence, which obviously is not what >>you want. Quick fix would be to insert a line "print x" just below else >>statement: >>---snip-- >> else: >> x=x*3+1 >> print x >>---snip >>This should make clear where the error is: You are just calculating, but >>not printing the sequence! >>If you want to leave the output to the end of the program you could as >>well gather all the calculated values in a list or similar structure and >>then print the contents of the list.. >> >>hth Frank >> >>On Fri, 2005-10-28 at 01:22 -0400, andrade1 at umbc.edu wrote: >> >>>Hello >>> >>>I am trying to create a program that will calculate the syracuse sequence >>>which is also known as collatz or hailstone. the number that is input by >>>the user may be either even or odd. the number goes through a series of >>>functions which are x/2 if the number is even and 3x+1 if the number is >>>odd. it keeps doing so until the number reaches 1. An example would be if >>>the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence >>>for the value that they started with. My code currently just prints a 1 >>>and none of the numbers that would have preceded it. any ideas on how I >>>could get the program to not do this would be greatly appreciated. >>> >>> >>>def main(): >>> try: >>> x = input("Please enter a starting value: ") >>> while x != 1: >>> >>> if x%2 == 0: >>> x = x/2 >>> else: >>> x = x*3+1 >>> >>> except ValueError, excObj: >>> msg = str(excobj) >>> if msg == "math domain error": >>> print "No negatives or decimals." >>> else: >>> print "Something went wrong." >>> >>> >>> >>> print "The Syracuse sequence of your starting value is:", x >>> >>>main() >>> >>> >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Fri Oct 28 21:17:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 20:17:22 +0100 Subject: [Tutor] Python as Application (OT now) References: Message-ID: <018901c5dbf4$39966d30$0a01a8c0@xp> > >useful and I support it 100%. That he thinks what he is learning is > >Excel is absolutely unforgivable, in terms of my understanding of > >ethical norms that once prevailed in an institute of higher education. > > > > I've never worked in any workplace where anything else other > than Excel was used. Certainly true for the majority case. However many smaller businesses (especially outside the USA) use other office packages for the simple reason that they are cheaper. For example in the UK, MS Office costs around ?350 here whereas Lotus SmartSuite and Corel Office both cost less than ?100. Ability Office although less known is also much less than ?100. And of course OpenOffice is free and a lot of high street system builders are now shipping that. And finally there is MS Works which is also common in very small businesses. At the other end of the scale many high end financial organisations use more sophisticated spreadsheets than Excel - Improv was very popular until lotus withdrew it! 20/20 is another comon contender. There are a couple of other high power Unix spreadsheets that I've seen in financial clients offices. But I agree with Liam that 99% of businesses use EXcel just because everyone else does. And because MS Office is the standard suite on high volume system builders PCs - Dell, HP, IBM, Gateway, etc. Alan G. FWIW I use Excel at work and Quattro Pro at home... From tim at johnsons-web.com Fri Oct 28 22:10:39 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 28 Oct 2005 12:10:39 -0800 Subject: [Tutor] Circular approach to a dictionary structure Message-ID: <20051028201039.GN1791@johnsons-web.com> Hello: # I have the following dictionary: next_phases = {"open":"review","review":"write","write":"open"} # a 'phase is extracted by next_phase = next_phases[self.phase Note that the value for each of the first keys is the key for the next item, and that the value for the last key is the *first* key. Is there a different way to do this? Works fine for me this way, but I'm just curious about an alternative, :-) expecially if it is better. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From m.moghimi at gmail.com Fri Oct 28 22:30:29 2005 From: m.moghimi at gmail.com (Mohammad Moghimi) Date: Sat, 29 Oct 2005 00:00:29 +0330 Subject: [Tutor] nokia 60 series Message-ID: Hi As you know nokia company lauched python for its cell phones. Do you know a good tutorial to write python programs for cellphones? -- -- Mohammad do you Python?!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051029/30e6c7f9/attachment.htm From hugonz-lists at h-lab.net Fri Oct 28 22:33:28 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 28 Oct 2005 14:33:28 -0600 Subject: [Tutor] Circular approach to a dictionary structure In-Reply-To: <20051028201039.GN1791@johnsons-web.com> References: <20051028201039.GN1791@johnsons-web.com> Message-ID: <43628B18.4050504@h-lab.net> Hi, There may be, but I do not understand what is it exactly what you are trying to do. If you're trying to implement a circular something that goes back to the first element after iterating the last one, then I'd think of a list, and using some modulus when iterating. Can you explain more of what you are trying to do? Hugo Tim Johnson wrote: > Hello: > > # I have the following dictionary: > next_phases = {"open":"review","review":"write","write":"open"} > > # a 'phase is extracted by > next_phase = next_phases[self.phase > > Note that the value for each of the first keys is the key for > the next item, and that the value for the last key is the *first* key. > > Is there a different way to do this? Works fine for me this way, but > I'm just curious about an alternative, :-) expecially if it is better. > > thanks > tim > From Barry.Carroll at psc.com Fri Oct 28 22:34:02 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 28 Oct 2005 13:34:02 -0700 Subject: [Tutor] Recursion and List Comprehensions Message-ID: Greetings: I'm trying to improve my programming and Python skills. To that end I have implemented a word jumble program as a recursive function: given a string of arbitrary length, return a list of all permutations of the string each character exactly once. In other words: permute('t') = ['t'], permute('te') = ['te', 'et'], permute('tes') = ['tes', 'tse', 'ets', 'est', 'ste', 'set'], etc. Here is my first try, the brute force method: >>>>def permute1 (word): >>>> retList=[] >>>> if len(word) == 1: >>>> # There is only one possible permutation >>>> retList.append(word) >>>> else: >>>> # Return a list of all permutations using all characters >>>> for pos in range(len(word)): >>>> # First isolate the char that goes in the first spot >>>> firstChar=word[pos] >>>> # Then assemble the rest of the word >>>> restWord=word[0:pos]+word[pos+1:len(word)] >>>> # Get the permutations of the rest of the word >>>> restList=permute1(restWord) >>>> # Now, tack the first char onto each word in the list >>>> for item in restList: >>>> newWord=firstChar+item >>>> # and add it to the output >>>> retList.append(newWord) >>>> return retList My second version combines statements to remove intermediate variables: >>>>def permute2 (word): >>>> retList=[] >>>> if len(word) == 1: >>>> # There is only one possible permutation >>>> retList.append(word) >>>> else: >>>> # Return a list of all permutations using all characters >>>> for pos in range(len(word)): >>>> # Get the permutations of the rest of the word >>>> permuteList=permute2(word[0:pos]+word[pos+1:len(word)]) >>>> # Now, tack the first char onto each word in the list >>>> # and add it to the output >>>> for item in permuteList: >>>> retList.append(word[pos]+item) >>>> return retList I'm told that I can collapse the logic further by using a list comprehension, something like: >>>>def permute3 (word): >>>> retList=[] >>>> if len(word) == 1: >>>> # There is only one possible permutation >>>> retList.append(word) >>>> else: >>>> # Return a list of all permutations using all characters >>>> retlist = [a list comprehension that calls permute3] >>>> return retList Unfortunately, I don't understand how list comprehensions work and how to implement them. Can someone point me in the right direction, please. Thanks in advance for your help. I'm learning a lot by following this list. Barry -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/f271ce1d/attachment.html From nick at javacat.f2s.com Fri Oct 28 23:16:08 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri, 28 Oct 2005 22:16:08 +0100 Subject: [Tutor] Global var problem Message-ID: <43629518.2090904@javacat.f2s.com> Hi Folks, messing about with classes I've come across something basic that I don't understand. Take this class class T: def p(self): print x if __name__ == '__main__': x = 1 t = T() t.p() This outputs 1 Now this class T: def p(self): x += 1 print x if __name__ == '__main__': x = 1 t = T() t.p() This outputs UnboundLocalError: local variable 'x' referenced before assignment So I tried this class T: def p(self): x += 1 print x if __name__ == '__main__': global x x = 1 t = T() t.p() but that gives me the same UnboundLocalError exception. This has got me confused. Why does the first example work ok, but not the second ? And in the third example I get the same error even after declaring x to be global. No doubt the answer is staring me in the face ... but I still can't see it. Cheers Nick . From tim at johnsons-web.com Fri Oct 28 23:43:45 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 28 Oct 2005 13:43:45 -0800 Subject: [Tutor] Circular approach to a dictionary structure In-Reply-To: <43628B18.4050504@h-lab.net> References: <20051028201039.GN1791@johnsons-web.com> <43628B18.4050504@h-lab.net> Message-ID: <20051028214345.GO1791@johnsons-web.com> * Hugo Gonz?lez Monteverde [051028 12:51]: > Hi, > > There may be, but I do not understand what is it exactly what you are > trying to do. > > If you're trying to implement a circular something that goes back to the > first element after iterating the last one, Yes. You are correct! tj > then I'd think of a list, > and using some modulus when iterating. > Can you explain more of what you are trying to do? > > > Hugo > > Tim Johnson wrote: > > Hello: > > > > # I have the following dictionary: > > next_phases = {"open":"review","review":"write","write":"open"} > > > > # a 'phase is extracted by > > next_phase = next_phases[self.phase > > > > Note that the value for each of the first keys is the key for > > the next item, and that the value for the last key is the *first* key. > > > > Is there a different way to do this? Works fine for me this way, but > > I'm just curious about an alternative, :-) expecially if it is better. > > > > thanks > > tim > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at freenet.co.uk Fri Oct 28 23:48:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 22:48:59 +0100 Subject: [Tutor] Circular approach to a dictionary structure References: <20051028201039.GN1791@johnsons-web.com> Message-ID: <01bb01c5dc09$67c35c80$0a01a8c0@xp> Tim, I don;t know if theres a better way but > next_phases = {"open":"review","review":"write","write":"open"} > > Note that the value for each of the first keys is the key for > the next item, and that the value for the last key is the *first* key. But I think this is pretty neat, I like it. Now I just need to find a problem that I can use it on :-) Alan G. From alan.gauld at freenet.co.uk Fri Oct 28 23:50:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 22:50:32 +0100 Subject: [Tutor] nokia 60 series References: Message-ID: <01c101c5dc09$9f1ea810$0a01a8c0@xp> > As you know nokia company lauched python for its cell phones. Wild. > Do you know a good tutorial to write python programs for cellphones? That will depend on what kindf API they offer. Unless they open up the phone with a Nokia specific library/moduile it will be hard to do much that is useful. But the concept is fun! Alan G. From alan.gauld at freenet.co.uk Sat Oct 29 00:00:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 23:00:51 +0100 Subject: [Tutor] Recursion and List Comprehensions References: Message-ID: <01d001c5dc0b$102ca740$0a01a8c0@xp> >>>>>def permute3 (word): >>>>> retList=[] >>>>> if len(word) == 1: >>>>> # There is only one possible permutation >>>>> retList.append(word) >>>>> else: >>>>> # Return a list of all permutations using all characters >>>>> retlist = [a list comprehension that calls permute3] retlist += [ word[0] + item , item for item in permute3(word[1:]) ] >>>>> return retList > Unfortunately, I don't understand how list comprehensions work and how to > implement them. Can someone point me in the right direction, please. Take a look in the functional programming topic of my tutor for an explanation of comprehensions. The code above is untested but should be close I think. It tries to produce a list of each item in the permutation list plus the same item with the first char added. However one point to consider is whether order matters. Take 'te' as your word t, te, e is what the above gives but you could argue that 'et' is also a permutation, if so, my comprehension doesn't give that. And its quite hard to generate (ie I can't think of an easy way! :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Oct 29 00:05:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Oct 2005 23:05:51 +0100 Subject: [Tutor] Global var problem References: <43629518.2090904@javacat.f2s.com> Message-ID: <01d401c5dc0b$c2985000$0a01a8c0@xp> > messing about with classes I've come across something basic that I don't > understand. As you say this has nothing to do with classes its more basic. Its about namespaces. Try reading the namespaces topic in my tutor for more info. Meanwhile lets simplify by removing the class bit def f(): print x def g(): x = x + 1 # expanded version of ++ shortcut print x x = 42 f() # prints 42 g() # gives an error The error is because you are assigning to x thus creating a local var of that name, but you are using x in the definition of x which doesn't make any kind of sense def h(): global x x += 1 print x h() # prints 43 HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Sat Oct 29 00:16:39 2005 From: wescpy at gmail.com (w chun) Date: Fri, 28 Oct 2005 15:16:39 -0700 Subject: [Tutor] Question about an re In-Reply-To: References: <34bb7f5b0510270129va59747bh@mail.gmail.com> Message-ID: <78b3a9580510281516j52e37748t517cf75991566a87@mail.gmail.com> > - ->: \d+/?\d* > - -> > - ->ie 1 or more digits followed by 0 or 1 slashes followed by 0 or more digits. this looks like it'll also accept invalid data, such as "1/" ... i think there's some more tweaking involved to get it so that if there's a '/', there is at least one digit afterwards. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From tim at johnsons-web.com Sat Oct 29 00:28:12 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 28 Oct 2005 14:28:12 -0800 Subject: [Tutor] Circular approach to a dictionary structure In-Reply-To: <01bb01c5dc09$67c35c80$0a01a8c0@xp> References: <20051028201039.GN1791@johnsons-web.com> <01bb01c5dc09$67c35c80$0a01a8c0@xp> Message-ID: <20051028222812.GP1791@johnsons-web.com> * Alan Gauld [051028 14:05]: > Tim, > > I don;t know if theres a better way but > > > next_phases = {"open":"review","review":"write","write":"open"} > > > > Note that the value for each of the first keys is the key for > > the next item, and that the value for the last key is the *first* key. > > But I think this is pretty neat, I like it. Now I just need to find a > problem that I can use it on :-) Coming from you that is gratifying! Here's how it manifests: A CGI project involving forms. Forms may be either "new" or "edit", and that "mode" is described by the first part of the virtual document path (path part 1). path part 2 is the phase: "open" => either "new" form or "edit" form filled in from database record "review" => after posting form gives review of data added or changed . "write" => third page, signaling successful write of data to database (either update or new record) and presenting another URL with "open" as path part 2. Example: http://www.mydomain.com/cgi-bin/script.py/new/open => http://www.mydomain.com/cgi-bin/script.py/new/review => http://www.mydomain.com/cgi-bin/script.py/new/write => http://www.mydomain.com/cgi-bin/script.py/new/open => tim -- Tim Johnson http://www.alaska-internet-solutions.com From project5 at redrival.net Sat Oct 29 00:14:46 2005 From: project5 at redrival.net (Andrei) Date: Sat, 29 Oct 2005 00:14:46 +0200 Subject: [Tutor] Global var problem In-Reply-To: <43629518.2090904@javacat.f2s.com> References: <43629518.2090904@javacat.f2s.com> Message-ID: Hi Nick, > messing about with classes I've come across something basic that I don't > understand. Your issue is not so much with classes as it is with namespaces. You'll hit the exact same problem with simple functions. > Take this class > > class T: > def p(self): > print x In this case, the Python reference states that if a name (x) is not found in a block (i.e. inside the p method), it will look in its surrounding scope for it. That would be the global namespace. Given the fact that you defined x as a global variable, it finds it there and it works as expected. > Now this > class T: > def p(self): > x += 1 > print x > This outputs > UnboundLocalError: local variable 'x' referenced before assignment Here is what the Python docs have to say about assignment: If the target is an identifier (name): If the name does not occur in a global statement in the current code block: the name is bound to the object in the current local namespace. In other words, when trying to assign a new value to x, it: 1. looks if x was defined as global *inside the current function/class* 2. sees that it was not defined as global -> therefore it must be local 3. tries to get the value of that local x 4. finds there is no local x -> raises exception > So I tried this > > class T: > def p(self): > x += 1 > print x > > if __name__ == '__main__': > global x > x = 1 > t = T() > t.p() > but that gives me the same UnboundLocalError exception. This second attempt is almost but not quite right: the global statement is in the wrong place. x is by definition global if defined outside a class or function, so adding "global" in front of it won't make a difference. The point is that if you try to assign a value to a global variable inside a function or class definition, you must tell Python *in that block* that you want to assign to a global variable, not a local one. >>> def p(): ... global x ... x += 1 >>> x = 5 >>> p() >>> x 6 Similar problems can occur when defining a function inside another function: >>> def a(): ... aa = 2 ... def b(): ... print aa # aa in surrounding namespace, not local to b() ... b() >>> a() 2 >>> def a(): ... aa = 2 ... def b(): ... aa += 1 # in surrounding namespace, not local to b() ... print aa ... b() >>> a() UnboundLocalError: local variable 'aa' referenced before assignment > No doubt the answer is staring me in the face ... but I still can't see it. I would recommend against using global variables this way (modifying them inside functions). It's better to use method parameters for input and the return statement to output any necessary modifications, e.g.: def p(inp): output = inp + 1 print output return output if __name__ == '__main__': x = 5 x = p(x) It would be even better with a decent function name of course :). More info available in paragraph 4.1 of the Python reference manual. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) From hugonz-lists at h-lab.net Sat Oct 29 00:19:19 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 28 Oct 2005 16:19:19 -0600 Subject: [Tutor] Global var problem In-Reply-To: <43629518.2090904@javacat.f2s.com> References: <43629518.2090904@javacat.f2s.com> Message-ID: <4362A3E7.20305@h-lab.net> Hi Nick, Global variables in Python are global for *reading*, based in the precedence order for looking into the namespace: locals, globals(module scope actually), builtins for writing, as variables are created on the fly, a local variable will be created and will mask the global one. That's why the keyword global "exists" Do: global x whenever there is a variable that you need to *modify*, and that already exists ourside the function. In your example: > Now this > class T: > def p(self): global x #this line brings x into existence for writing > x += 1 > print x > > if __name__ == '__main__': > x = 1 > t = T() > t.p() > You'll get rid of the exception and the error. Hope it helps. Hugo Nick Lunt wrote: > Hi Folks, > > messing about with classes I've come across something basic that I don't > understand. > > Take this class > > class T: > def p(self): > print x > > if __name__ == '__main__': > x = 1 > t = T() > t.p() > > This outputs 1 > > Now this > class T: > def p(self): > x += 1 > print x > > if __name__ == '__main__': > x = 1 > t = T() > t.p() > > This outputs > UnboundLocalError: local variable 'x' referenced before assignment > > So I tried this > > class T: > def p(self): > x += 1 > print x > > if __name__ == '__main__': > global x > x = 1 > t = T() > t.p() > > but that gives me the same UnboundLocalError exception. > > This has got me confused. Why does the first example work ok, but not > the second ? > And in the third example I get the same error even after declaring x to > be global. > > No doubt the answer is staring me in the face ... but I still can't see it. > > Cheers > Nick . > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From wescpy at gmail.com Sat Oct 29 00:22:03 2005 From: wescpy at gmail.com (w chun) Date: Fri, 28 Oct 2005 15:22:03 -0700 Subject: [Tutor] Global var problem In-Reply-To: <43629518.2090904@javacat.f2s.com> References: <43629518.2090904@javacat.f2s.com> Message-ID: <78b3a9580510281522k1786f348x7bff274055af0d57@mail.gmail.com> > if __name__ == '__main__': > global x > x = 1 > t = T() > t.p() as alan mentioned, it's all about namespaces. the "global x" you have in the above piece of code doesn't do anything (because you're already or still in the global [name]space). you're getting the error in your p() method because there is an assignment to x in there. when that happens, it's part of p's local namespace. during compilation, the interpreter sees this creation of a local name, but because you access it before you assign it, i.e., x = x + 1, you get that error. add your global request to p(), and you'll be fine: def p(self): global x x += 1 print x hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Sat Oct 29 00:33:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 18:33:27 -0400 Subject: [Tutor] Recursion and List Comprehensions In-Reply-To: References: Message-ID: <4362A737.8000203@tds.net> Carroll, Barry wrote: >> >>> permuteList=permute2(word[0:pos]+word[pos+1:len(word)]) >> >>> # Now, tack the first char onto each word in the list >> >>> # and add it to the output >> >>> for item in permuteList: >> >>> retList.append(word[pos]+item) This could be retList.extend([word[pos]+item for item in permuteList]) or in Python 2.4 omit the extra brackets: retList.extend(word[pos]+item for item in permuteList) The list comprehension lst = [word[pos]+item for item in permuteList] is equivalent to lst = [] for item in permuteList: lst.append(word[pos]+item) PS Don't get too crazy about eliminating intermediate variables, they can make the code more readable. Kent From kent37 at tds.net Sat Oct 29 00:34:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 18:34:30 -0400 Subject: [Tutor] Question about an re In-Reply-To: <78b3a9580510281516j52e37748t517cf75991566a87@mail.gmail.com> References: <34bb7f5b0510270129va59747bh@mail.gmail.com> <78b3a9580510281516j52e37748t517cf75991566a87@mail.gmail.com> Message-ID: <4362A776.90604@tds.net> w chun wrote: >>- ->: \d+/?\d* >>- -> >>- ->ie 1 or more digits followed by 0 or 1 slashes followed by 0 or more digits. > > > > this looks like it'll also accept invalid data, such as "1/" ... i > think there's some more tweaking involved to get it so that if there's > a '/', there is at least one digit afterwards. \d+(/\d+)? Kent From mark.brown at rogers.com Sat Oct 29 00:44:01 2005 From: mark.brown at rogers.com (Mark Brown) Date: Fri, 28 Oct 2005 18:44:01 -0400 Subject: [Tutor] Can anyone help me? In-Reply-To: References: <010801c5db95$c9095810$0a01a8c0@xp> Message-ID: <4362A9B1.5050804@rogers.com> Nathan, While testing I noticed the same number coming up more that once in a set of 6 so what I've done: import random while True: q = raw_input("Do you want a lottery number drawing? 1 for yes, 2 for no ") if q == '1': numbers = [] for i in range(6): while True: draw = random.choice(range(1,50)) if not(numbers.count(draw)): numbers.append(draw) break print numbers elif q == '2': break else: print "Read the instructions please." Mark Brown Nathan Pinno wrote: >Hey, >I created it. Want to see the code? >Here it is: >[code] >import random >numbers = [] >while True: > q = int(raw_input("Do you want a lottery number drawing? 1 for yes, 2 >for no ")) > if q == 1: > for i in range(6): > draw = random.choice(range(1,50)) > numbers.append(draw) > print numbers > numbers = [] > elif q == 2: > break > else: > print "Read the instructions please." >[/code] > >Enjoy! >Nathan Pinno >For great sites go to: http://falcon3166.tripod.com >MSN Messenger: falcon3166 at hotmail,com >Yahoo! Messenger: spam_swatter31 >ICQ: 199020705 >AIM: f3mighty >----- Original Message ----- >From: "Alan Gauld" >To: "Nathan Pinno" ; >Sent: Friday, October 28, 2005 2:01 AM >Subject: Re: [Tutor] Can anyone help me? > > > > >>Nathan, >> >>look at the functions in the random module. >>randrange() would be one potential candidate. >> >>Alan G >> >>----- Original Message ----- >>From: "Nathan Pinno" >>To: >>Sent: Friday, October 28, 2005 3:07 AM >>Subject: [Tutor] Can anyone help me? >> >> >>Hey all, >>I am trying to create a program that draws 6 numbers between 1 and 49 at >>random for creating lottery tickets. I want to have a better chance when I >>play. Can anyone help me code this or show me how to, please? >>Thanks, >>Nathan Pinno >>For great sites go to: http://falcon3166.tripod.com >>MSN Messenger: falcon3166 at hotmail,com >>Yahoo! Messenger: spam_swatter31 >>ICQ: 199020705 >>AIM: f3mighty >> >> >> >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From project5 at redrival.net Sat Oct 29 01:13:45 2005 From: project5 at redrival.net (Andrei) Date: Sat, 29 Oct 2005 01:13:45 +0200 Subject: [Tutor] Recursion and List Comprehensions In-Reply-To: References: Message-ID: Carroll, Barry wrote: > Greetings: > I'm trying to improve my programming and Python skills. To that end I > have implemented a word jumble program as a recursive function: given a > string of arbitrary length, return a list of all permutations of the > string each character exactly once. In other words: > > permute('t') = ['t'], > permute('te') = ['te', 'et'], > permute('tes') = ['tes', 'tse', 'ets', 'est', 'ste', 'set'], > etc. > I'm told that I can collapse the logic further by using a list > comprehension, something like: >> >>>def permute3 (word): >> >>> retList=[] >> >>> if len(word) == 1: >> >>> # There is only one possible permutation >> >>> retList.append(word) >> >>> else: >> >>> # Return a list of all permutations using all characters >> >>> retlist = [a list comprehension that calls permute3] >> >>> return retList > Unfortunately, I don't understand how list comprehensions work and how > to implement them. Can someone point me in the right direction, please. There's nothing magic about writing a list comprehension - they're just an inside-out way of writing a for-loop :). newlist = [] for item in mylist: newlist.append(item * 2) becomes (imagine this as an animation with bits of code from above floating down to fill in the blanks :)): newlist = [ ] newlist = [ for item in mylist] newlist = [item * 2 for item in mylist] In your case, you could start with your permute2 implementation and turn it inside out to get a list comprehension: for item in permuteList: retList.append(word[pos] + item) would become according to the example above: retList = [word[pos] + item for item in permuteList] Testing this shows that it tends to cut off a bunch of combinations, because retList is overwritten in every iteration of "for pos in range". Let's fix that by extending the list instead: retList.extend([word[pos] + item for item in permuteList]) That works. Now we replace 'permuteList' with its definition a few lines above: retList.extend([word[pos] + item for item in permute2(word[0:pos]+word[pos+1:len(word)])]) Getting ugly now. Let's see what's missing: word is an argument, item comes from the "for item in ...", but pos still needs to be defined. We get that by wrapping the "for pos in range" loop around this list comprehension: for pos in range(len(word)): dosomething(pos) becomes: [dosomething(pos) for pos in range(len(word))] Where dosomething(pos) is our earlier list comprehension. Let's fill it in: [ retList.extend( [ word[pos] + item for item in permute2(word[0:pos]+word[pos+1:len(word)]) ] ) for pos in range(len(word))] The net result: def permute3(word): retList=[] if len(word) == 1: # There is only one possible permutation retList.append(word) else: # Return a list of all permutations using all characters [ retList.extend( [ word[pos] + item for item in permute3(word[0:pos]+word[pos+1:len(word)]) ] ) for pos in range(len(word))] return retList 4 lines of perfectly readable code have become 4 lines of perfectly unreadable list comprehension. Any reader interested in understanding this will have to perform the exact opposite set of operations to go back to the original code. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) From carroll at tjc.com Sat Oct 29 01:25:29 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 28 Oct 2005 16:25:29 -0700 (PDT) Subject: [Tutor] Can anyone help me? In-Reply-To: <6.1.2.0.0.20051028062133.036fd578@mail.mric.net> Message-ID: On Fri, 28 Oct 2005, bob wrote: > At 09:42 PM 10/27/2005, Nathan Pinno wrote: > > >If I create a program that randomly draws 6 numbers, its like the lottery. > >According to an article I read in Reader's Digest, if you get a Quick Pick > >- which is six numbers at random - you increase your odds of winning. > > Odds are how many tickets you buy relative to how many tickets everyone > else has bought. Has nothing to do with the mechanism for generating > numbers. Any guesses you make are "random". My guess is that the point of the Reader's Digest article (I haven't read it, this is just my conjecture) is that a truly random (or pseudo-random) number is a better lottery play than a "favorite" number like an anniversary date, your kids' ages, etc. It's not that a random number is any more likely to hit the winning combination. But numbers that are based on dates or ages of a typical family are more likely to be played than a completely random set of numbers; and therefore, a win with a random set of numbers will likely have a smaller pool of winners with whom you'll need to split the payout. Put another way: a set of randomly selected numbers is no more or less likely to hit the lotto than a set of non-randomly selected numbers, so randomness does not affect the likelihood of there being a payout. However, the collision space for a set of randomly selected numbers is likely to be smaller than the collision space for a non-randomly selected set of numbers, which does affect the amount of a payout, in the event of a win. From project5 at redrival.net Sat Oct 29 01:32:42 2005 From: project5 at redrival.net (Andrei) Date: Sat, 29 Oct 2005 01:32:42 +0200 Subject: [Tutor] Circular approach to a dictionary structure In-Reply-To: <20051028201039.GN1791@johnsons-web.com> References: <20051028201039.GN1791@johnsons-web.com> Message-ID: Tim Johnson wrote: > Hello: > > # I have the following dictionary: > next_phases = {"open":"review","review":"write","write":"open"} > > # a 'phase is extracted by > next_phase = next_phases[self.phase > > Note that the value for each of the first keys is the key for > the next item, and that the value for the last key is the *first* key. I too would be tempted to use a list for this. Something along the lines of: phases = ['open', 'review', 'write'] nextphase = phases[((1 + phases.index(phase)) % len(phases)] This is not as friendly as the dictionary option, but I'd wrap that in a function call (or object interface). It has some advantages: - there's a single instance of every string - it's obvious that it's a sequence - it's one of the standard ways of doing circular structures - there's no chance of introducing a dead branch, breaking the circle - it's easier to add/remove things. E.g. if you'd add and an "approve" step between review and write, the list approach requires a single update, while the dictionary requires one new key-value pair and modifications in another two places in order to get it working correctly. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) From adam.jtm30 at gmail.com Sat Oct 29 02:11:22 2005 From: adam.jtm30 at gmail.com (Adam) Date: Sat, 29 Oct 2005 01:11:22 +0100 Subject: [Tutor] nokia 60 series In-Reply-To: References: Message-ID: On 28/10/05, Mohammad Moghimi wrote: > > Hi > As you know nokia company lauched python for its cell phones. Do you know > a good tutorial to write python programs for cellphones? > > -- > -- Mohammad > do you Python?!! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor You might want to have a look at this. http://www.forum.nokia.com/python -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051029/814cf9b8/attachment.htm From wildcard2005 at comcast.net Sat Oct 29 02:42:15 2005 From: wildcard2005 at comcast.net (Terry Kemmerer) Date: Fri, 28 Oct 2005 17:42:15 -0700 Subject: [Tutor] Can anyone help me? In-Reply-To: References: Message-ID: <1130546537.5606.154.camel@c-24-16-68-31.hsd1.wa.comcast.net> > > >If I create a program that randomly draws 6 numbers, its like the lottery. > > >According to an article I read in Reader's Digest, if you get a Quick Pick > > >- which is six numbers at random - you increase your odds of winning. > > > > Odds are how many tickets you buy relative to how many tickets everyone > > else has bought. Has nothing to do with the mechanism for generating > > numbers. Any guesses you make are "random". > > My guess is that the point of the Reader's Digest article (I haven't read > it, this is just my conjecture) is that a truly random (or pseudo-random) > number is a better lottery play than a "favorite" number like an > anniversary date, your kids' ages, etc. > > It's not that a random number is any more likely to hit the winning > combination. But numbers that are based on dates or ages of a typical > family are more likely to be played than a completely random set of > numbers; and therefore, a win with a random set of numbers will likely > have a smaller pool of winners with whom you'll need to split the payout. > > Put another way: a set of randomly selected numbers is no more or less > likely to hit the lotto than a set of non-randomly selected numbers, so > randomness does not affect the likelihood of there being a payout. > However, the collision space for a set of randomly selected numbers is > likely to be smaller than the collision space for a non-randomly selected > set of numbers, which does affect the amount of a payout, in the event of > a win. > If this is the case, you are working on the wrong program. A random number program, like the one used for the lotto game, will give equal opportunity to any possible number. Whereas, you are now looking to maximize your winnings, when that win finally comes, by picking numbers that humans would not be prone to pick. That means your program needs to be finding numbers that are MORE popular to humans, in order to isolate numbers that are LESS popular to humans. This is sounding more like a massive search of all data and databases on the web, looking to count occurrences of numbers that have an immediacy to the human experience, while grading out counting numbers that are more arbitrarily nuetral or even inactive in the human experience, and after that evaluation is done, simply looking at your tally list of numbers and which numbers occur less frequently. The more you are able to evaluate whether a number has great or small impact upon the human mind, the more accurate your final results..... Can you say, WEB CRAWLER? BUT!! I have good news! I got a great deal on car insurance at Geiko! And, by the way, Reader's Digest is just a tad above the National Enquirer in credibility, although they both have big readerships......which should tell you something about them. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/cc86d270/attachment.html From amonroe at columbus.rr.com Sat Oct 29 02:41:59 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri, 28 Oct 2005 20:41:59 -0400 Subject: [Tutor] Recursion and List Comprehensions In-Reply-To: References: Message-ID: <179825169110.20051028204159@columbus.rr.com> > Unfortunately, I don't understand how list comprehensions work and how to > implement them. Can someone point me in the right direction, please. Compare these two pieces of code x=[1,2,3,4] y=[] for eachnum in x: y.append(eachnum * 2) versus x=[1,2,3,4] y = [each * 2 for each in x] Try them both on your box :^) Alan From Barry.Carroll at psc.com Sat Oct 29 02:48:36 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 28 Oct 2005 17:48:36 -0700 Subject: [Tutor] Recursion and List Comprehensions Message-ID: Alan et al: After reading the topic you recommended I tried rewriting my permute function as follows: ########## def permute3 (word): if len(word) == 1: # There is only one possible permutation retList=[word] else: # Return a list of all permutations using all characters for pos in range(len(word)): # Get the permutations of the rest of the word, # tack the first char onto each word in the list # and add it to the output retList=[word[pos]+item for item in permute3(word[0:pos]+ word[pos+1:])] return retList ########## The list comprehension looks correct to my eyes. However, when I run the function I always get back a one element list. For example >>>>>>>>>> >>> permute.permute3('test') ['tset'] >>>>>>>>>> By contrast my previous version returns the correct output: >>>>>>>>>> >>> permute.permute2('test') ['test', 'tets', 'tset', 'tste', 'ttes', 'ttse', 'etst', 'etts', 'estt', 'estt', 'etts', 'etst', 'stet', 'stte', 'sett', 'sett', 'stte', 'stet', 'ttes', 'ttse', 'tets', 'test', 'tste', 'tset'] >>> >>>>>>>>>> Note that permute3 returns the last element of the list returned by permute2. This is true in general: permute3 always returns the last element generated by permute2. I think there is a problem with the assignment (retList= ...), but the append operator (retList+= ...) causes this error: >>>>>>>>>> >>> permute.permute3('tests') Traceback (most recent call last): File "", line 1, in ? File "permute.py", line 50, in permute3 retList+=[word[pos]+item for item in permute3(word[0:pos]+word[pos+1:len(word)])] UnboundLocalError: local variable 'retList' referenced before assignment >>>>>>>>>> Ideas, anyone? Thanks again. Barry -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: Friday, October 28, 2005 3:01 PM To: Carroll, Barry; tutor at python.org Subject: Re: [Tutor] Recursion and List Comprehensions >>>>>def permute3 (word): >>>>> retList=[] >>>>> if len(word) == 1: >>>>> # There is only one possible permutation >>>>> retList.append(word) >>>>> else: >>>>> # Return a list of all permutations using all characters >>>>> retlist = [a list comprehension that calls permute3] retlist += [ word[0] + item , item for item in permute3(word[1:]) ] >>>>> return retList > Unfortunately, I don't understand how list comprehensions work and how to > implement them. Can someone point me in the right direction, please. Take a look in the functional programming topic of my tutor for an explanation of comprehensions. The code above is untested but should be close I think. It tries to produce a list of each item in the permutation list plus the same item with the first char added. However one point to consider is whether order matters. Take 'te' as your word t, te, e is what the above gives but you could argue that 'et' is also a permutation, if so, my comprehension doesn't give that. And its quite hard to generate (ie I can't think of an easy way! :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Sat Oct 29 03:07:22 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 28 Oct 2005 19:07:22 -0600 Subject: [Tutor] Albertito and I want you to help us create a search engine. Message-ID: Hey all, Albertito and I want you all to help us create a search engine for our site. Albertito heard that Google was created in Python, is this true? I want to know if such a task is possible, and if so, who is willing to help us create the script needed for our site. Thanks, Nathan Pinno Crew, McDonalds Restaurant and fan extraordinaire of the Oilers. http://www.the-web-surfers.store.com/ P.S. If you want to take a look at what we have done so far on the site, go right ahead. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/ea86abd7/attachment.htm From tim at johnsons-web.com Sat Oct 29 03:27:33 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 28 Oct 2005 17:27:33 -0800 Subject: [Tutor] Circular approach to a dictionary structure In-Reply-To: References: <20051028201039.GN1791@johnsons-web.com> Message-ID: <20051029012733.GQ1791@johnsons-web.com> * Andrei [051028 15:57]: Andrei, I really like your approach. Will which up an object interface for it. Will have other applications, I'm sure. thanks tim > Tim Johnson wrote: > > Hello: > > > > # I have the following dictionary: > > next_phases = {"open":"review","review":"write","write":"open"} > > > > # a 'phase is extracted by > > next_phase = next_phases[self.phase > > > > Note that the value for each of the first keys is the key for > > the next item, and that the value for the last key is the *first* key. > > I too would be tempted to use a list for this. Something along the lines of: > > phases = ['open', 'review', 'write'] > > nextphase = phases[((1 + phases.index(phase)) % len(phases)] > > This is not as friendly as the dictionary option, but I'd wrap that in a > function call (or object interface). It has some advantages: > - there's a single instance of every string > - it's obvious that it's a sequence > - it's one of the standard ways of doing circular structures > - there's no chance of introducing a dead branch, breaking the circle > - it's easier to add/remove things. > E.g. if you'd add and an "approve" step between review and write, > the list approach requires a single update, while the dictionary > requires one new key-value pair and modifications in another two > places in order to get it working correctly. > > -- > Yours, > > Andrei > > ===== > Mail address in header catches spam. Real contact info: > ''.join([''.join(s) for s in zip( > "poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", > "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Sat Oct 29 03:31:09 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 28 Oct 2005 17:31:09 -0800 Subject: [Tutor] AJAX resources for Python Message-ID: <20051029013109.GR1791@johnsons-web.com> Hi All: Are AJAX resources available for python? http://en.wikipedia.org/wiki/AJAX thanks Tim -- Tim Johnson http://www.alaska-internet-solutions.com From Barry.Carroll at psc.com Sat Oct 29 03:24:00 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 28 Oct 2005 18:24:00 -0700 Subject: [Tutor] Code Readability (was: Recursion and List Comprehensions) Message-ID: Kent Johnson wrote: <> >>PS Don't get too crazy about eliminating intermediate variables, they can >>make the code more readable. >> >>Kent I agree. When writing for keeps (i.e. production code) I prefer clarity and ease of maintenance over 'elegance' or 'trickiness'. This exercise is intended, in part, to sharpen my understanding of Python idioms. If I can write highly idiomatic code that works, chances are better that I will be able to decipher it when I come across it elsewhere. Barry From Barry.Carroll at psc.com Sat Oct 29 03:35:53 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 28 Oct 2005 18:35:53 -0700 Subject: [Tutor] Recursion and List Comprehensions Message-ID: Greetings: Andrei gave me the answer I needed: <> >Let's fix that by extending the list instead: > > retList.extend([word[pos] + item for item in permuteList]) > <> The extend method solved the problem. Barry >-----Original Message----- >From: Carroll, Barry >Sent: Friday, October 28, 2005 5:49 PM >To: 'Alan Gauld'; Carroll, Barry; tutor at python.org >Subject: RE: [Tutor] Recursion and List Comprehensions > >Alan et al: > >After reading the topic you recommended I tried rewriting my permute >function as follows: > <> From Barry.Carroll at psc.com Sat Oct 29 03:44:28 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 28 Oct 2005 18:44:28 -0700 Subject: [Tutor] Recursion and List Comprehensions Message-ID: Andrei: >Date: Sat, 29 Oct 2005 01:13:45 +0200 >From: Andrei >Subject: Re: [Tutor] Recursion and List Comprehensions >To: tutor at python.org >Message-ID: >Content-Type: text/plain; charset=ISO-8859-1; format=flowed <> >There's nothing magic about writing a list comprehension - they're just >an inside-out way of writing a for-loop :). <> That was just what I needed. Your description was clear and easy to follow. >4 lines of perfectly readable code have become 4 lines of perfectly >unreadable list comprehension. Any reader interested in understanding >this will have to perform the exact opposite set of operations to go >back to the original code. <> I couldn't agree more. This was a learning exercise for me. In a real program (one that I or someone else would have to maintain a year or so from now) I would have stopped with the first version, with all the loops and intermediate variables left in. Thanks for your help. I really enjoy this list. Barry From andrade1 at umbc.edu Sat Oct 29 04:03:56 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Fri, 28 Oct 2005 22:03:56 -0400 (EDT) Subject: [Tutor] syracuse sequence (collatz or hailstone) In-Reply-To: <43627A62.7080402@tds.net> References: <3209.172.168.38.88.1130515184.squirrel@172.168.38.88> <43627A62.7080402@tds.net> Message-ID: <1635.172.142.243.213.1130551436.squirrel@172.142.243.213> would this be a possible use of a list and appending even though I recieve an error from it: def main(): x = [1] x[0] = input('enter an int to start your syracuse sequence\n') while not isinstance(x[0], int): x[0] = input('no, please enter an int to start your syracuse sequence\n') while x[-1] != 1: if ((x[-1] % 2) == 0): x.append(x[-1] / 2) else: x.append((3 * x) + 1) print len(x), x print "The Syracuse sequence of your starting value is:", x main() line 10, in main x.append((3 * x) + 1) TypeError: can only concatenate list (not "int") to list >>> > andrade1 at umbc.edu wrote: >> hello, >> >> Could I gather all of the values from print x into a string or a range? >> Since, I am not familiar with lists yet. > > Here is a simple example of gathering values into a list and making a > string: > >>> r=[] # Start with an empty list > >>> for x in range(3): # x will be 0, 1, 2 in sequence > ... r.append(str(x*x)) # Put x*x (as a string) onto r > ... > >>> r > ['0', '1', '4'] > >>> ', '.join(r) # make a single string by joining the elements of r with > ', ' > '0, 1, 4' > > Kent > >> >> >> def main(): >> x = input("Please enter a positive starting value: ") >> while x != 1: >> if x%2 == 0: >> x = x/2 >> else: >> x = x*3+1 >> print x >> print "The Syracuse sequence of your starting value is:", x >> >> main() >> >> >> >> >> ----- Original Message ----- >> From: "Frank Bloeink" >> To: >> Sent: Friday, October 28, 2005 5:06 AM >> Subject: Re: [Tutor] syracuse sequence (collatz or hailstone) >> >> >> >>>Hey, >>> >>>your code seems almost alright to me, except that in your case it's only >>>printing the last number of your sequence, which obviously is not what >>>you want. Quick fix would be to insert a line "print x" just below else >>>statement: >>>---snip-- >>> else: >>> x=x*3+1 >>> print x >>>---snip >>>This should make clear where the error is: You are just calculating, but >>>not printing the sequence! >>>If you want to leave the output to the end of the program you could as >>>well gather all the calculated values in a list or similar structure and >>>then print the contents of the list.. >>> >>>hth Frank >>> >>>On Fri, 2005-10-28 at 01:22 -0400, andrade1 at umbc.edu wrote: >>> >>>>Hello >>>> >>>>I am trying to create a program that will calculate the syracuse >>>> sequence >>>>which is also known as collatz or hailstone. the number that is input >>>> by >>>>the user may be either even or odd. the number goes through a series of >>>>functions which are x/2 if the number is even and 3x+1 if the number is >>>>odd. it keeps doing so until the number reaches 1. An example would be >>>> if >>>>the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the >>>> sequence >>>>for the value that they started with. My code currently just prints a 1 >>>>and none of the numbers that would have preceded it. any ideas on how I >>>>could get the program to not do this would be greatly appreciated. >>>> >>>> >>>>def main(): >>>> try: >>>> x = input("Please enter a starting value: ") >>>> while x != 1: >>>> >>>> if x%2 == 0: >>>> x = x/2 >>>> else: >>>> x = x*3+1 >>>> >>>> except ValueError, excObj: >>>> msg = str(excobj) >>>> if msg == "math domain error": >>>> print "No negatives or decimals." >>>> else: >>>> print "Something went wrong." >>>> >>>> >>>> >>>> print "The Syracuse sequence of your starting value is:", x >>>> >>>>main() >>>> >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor at python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > -- > http://www.kentsjohnson.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Oct 29 05:36:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Oct 2005 23:36:24 -0400 Subject: [Tutor] AJAX resources for Python In-Reply-To: <20051029013109.GR1791@johnsons-web.com> References: <20051029013109.GR1791@johnsons-web.com> Message-ID: <4362EE38.4050201@tds.net> Tim Johnson wrote: > Hi All: > > Are AJAX resources available for python? > http://en.wikipedia.org/wiki/AJAX Turbogears supports AJAX using MochiKit on the client side and JSON for the protocol. http://www.turbogears.org/ Kent -- http://www.kentsjohnson.com From ml.cyresse at gmail.com Sat Oct 29 05:47:08 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 29 Oct 2005 16:47:08 +1300 Subject: [Tutor] Albertito and I want you to help us create a search engine. In-Reply-To: References: Message-ID: Mate, if I could write a search engine, let alone anything remotely as useful as Google, I'd hopefully be working for Google. Yah, Google heavily uses Python, but the Sphinxe's being built out of sandstone blocks does not mean that I'll be able to replicate the Sphinx by learning how to build with sandstone, if you catch my drift. I recommend some http://www.allegro-c.de/formate/tlcse.htm search theory reading. And, your site isn't working at the mo. Regards, Liam Clarke On 10/29/05, Nathan Pinno wrote: > Hey all, > > Albertito and I want you all to help us create a search engine for our site. > Albertito heard that Google was created in Python, is this true? I want to > know if such a task is possible, and if so, who is willing to help us create > the script needed for our site. > > Thanks, > Nathan Pinno > Crew, McDonalds Restaurant and fan extraordinaire of the Oilers. > http://www.the-web-surfers.store.com/ > > P.S. If you want to take a look at what we have done so far on the site, go > right ahead. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From grouch at gmail.com Sat Oct 29 09:14:29 2005 From: grouch at gmail.com (Andrew P) Date: Sat, 29 Oct 2005 02:14:29 -0500 Subject: [Tutor] Code Readability (was: Recursion and List Comprehensions) In-Reply-To: References: Message-ID: Since when is elegance a dirty word? Elegance is the soul of good programming. A simple and graceful solution to the widest number of cases, efficient and easy to understand in application. Sometimes subtle, but always beautiful. In language design, software architecture, algorithms, it is the rushing light of clarity that banishes dark and smelly corners. It's side effects are many--reusable code, effortless speed, painless maintenance, reduced complexity. The dreams shared by physicists, mathematicians, and engineers, are dreams of elegance. It is heartbreaking to see a concise and useful term maligned by dense one-liners, which are seldom anything except hard to read. Simple and short ain't the same thing. And having indulged in possibly very off-topic interlude, let me point out that recognizing a donut when you see it, doesn't make you a baker. Trust me, I'm not baking donuts. And judging by the amount of Escher-like pretzels that continute to be baked in the world, we have a long ways to go before we get more than the occasional sighting or passing whiff of something sweet and round with a hole in the middle. . Take care, Andrew On 10/28/05, Carroll, Barry wrote: > Kent Johnson wrote: > > <> > > >>PS Don't get too crazy about eliminating intermediate variables, they can > >>make the code more readable. > >> > >>Kent > > I agree. When writing for keeps (i.e. production code) I prefer clarity and > ease of maintenance over 'elegance' or 'trickiness'. This exercise is > intended, in part, to sharpen my understanding of Python idioms. If I can > write highly idiomatic code that works, chances are better that I will be > able to decipher it when I come across it elsewhere. > > Barry > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Sat Oct 29 09:27:05 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 29 Oct 2005 00:27:05 -0700 Subject: [Tutor] Tkinter Message-ID: <1d987df30510290027i5a6878a1l11235cd0f9e41dc0@mail.gmail.com> When I run the following code, script kept running and I have to force it to stop. Could you check the code to give suggestions how to improve it? Thanks a lot! from Tkinter import * from Tkinter import _cnfmerge class Dialog(Widget): def __init__(self, master=None, cnf={}, **kw): cnf = _cnfmerge((cnf, kw)) self.widgetName = '__dialog__' Widget._setup(self, master, cnf) self.num = self.tk.getint( apply(self.tk.call, ('tk_dialog', self._w, cnf['title'], cnf['text'], cnf['bitmap'], cnf['default']) + cnf['strings'])) try: Widget.destroy(self) except TclError: pass def destroy(self): pass if __name__ == '__main__': q = Button(None, {'text': 'How are you', Pack: {}}) b1 = Listbox() b1.pack() c1 = Checkbutton(text="Check") c1.pack() q.mainloop() from Tkinter import * root =Tk() menu=Menu(root) root.config(menu=menu) filemenu=Menu(menu) menu.add_cascade(label="Test", menu=filemenu) filemenu.add_command(label="Just Try") filemenu.add_separator() mainloop() From ml.cyresse at gmail.com Sat Oct 29 09:40:07 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 29 Oct 2005 20:40:07 +1300 Subject: [Tutor] Tkinter In-Reply-To: <1d987df30510290027i5a6878a1l11235cd0f9e41dc0@mail.gmail.com> References: <1d987df30510290027i5a6878a1l11235cd0f9e41dc0@mail.gmail.com> Message-ID: What kind of improvement you looking for? On 10/29/05, Shi Mu wrote: > When I run the following code, > script kept running and I have to force it to stop. > Could you check the code to give suggestions how to improve it? > Thanks a lot! > > from Tkinter import * > from Tkinter import _cnfmerge > > class Dialog(Widget): > def __init__(self, master=None, cnf={}, **kw): > cnf = _cnfmerge((cnf, kw)) > self.widgetName = '__dialog__' > Widget._setup(self, master, cnf) > self.num = self.tk.getint( > apply(self.tk.call, > ('tk_dialog', self._w, > cnf['title'], cnf['text'], > cnf['bitmap'], cnf['default']) > + cnf['strings'])) > try: Widget.destroy(self) > except TclError: pass > def destroy(self): pass > > if __name__ == '__main__': > > q = Button(None, {'text': 'How are you', > Pack: {}}) > b1 = Listbox() > b1.pack() > > c1 = Checkbutton(text="Check") > c1.pack() > > q.mainloop() > > from Tkinter import * > root =Tk() > menu=Menu(root) > root.config(menu=menu) > filemenu=Menu(menu) > menu.add_cascade(label="Test", menu=filemenu) > filemenu.add_command(label="Just Try") > filemenu.add_separator() > mainloop() > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Sat Oct 29 09:55:14 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 29 Oct 2005 00:55:14 -0700 Subject: [Tutor] Tkinter In-Reply-To: References: <1d987df30510290027i5a6878a1l11235cd0f9e41dc0@mail.gmail.com> Message-ID: <1d987df30510290055q4605c3b7q529d951cdeb7ad4d@mail.gmail.com> move the bottom codes to the top and try to make the codes following if __name__ == '__main__': as few as possible. also, i want the main menu come first, and after clicking test/just try, i can go to the "how are you" interface. On 10/29/05, Liam Clarke wrote: > What kind of improvement you looking for? > > On 10/29/05, Shi Mu wrote: > > When I run the following code, > > script kept running and I have to force it to stop. > > Could you check the code to give suggestions how to improve it? > > Thanks a lot! > > > > from Tkinter import * > > from Tkinter import _cnfmerge > > > > class Dialog(Widget): > > def __init__(self, master=None, cnf={}, **kw): > > cnf = _cnfmerge((cnf, kw)) > > self.widgetName = '__dialog__' > > Widget._setup(self, master, cnf) > > self.num = self.tk.getint( > > apply(self.tk.call, > > ('tk_dialog', self._w, > > cnf['title'], cnf['text'], > > cnf['bitmap'], cnf['default']) > > + cnf['strings'])) > > try: Widget.destroy(self) > > except TclError: pass > > def destroy(self): pass > > > > if __name__ == '__main__': > > > > q = Button(None, {'text': 'How are you', > > Pack: {}}) > > b1 = Listbox() > > b1.pack() > > > > c1 = Checkbutton(text="Check") > > c1.pack() > > > > q.mainloop() > > > > from Tkinter import * > > root =Tk() > > menu=Menu(root) > > root.config(menu=menu) > > filemenu=Menu(menu) > > menu.add_cascade(label="Test", menu=filemenu) > > filemenu.add_command(label="Just Try") > > filemenu.add_separator() > > mainloop() > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From chr.eskebjerg at tiscali.dk Sat Oct 29 10:54:41 2005 From: chr.eskebjerg at tiscali.dk (Christian Eskebjerg) Date: Sat, 29 Oct 2005 10:54:41 +0200 Subject: [Tutor] threaded chat server, is this the way? Message-ID: <436338D1.2080804@tiscali.dk> Hi, Im trying to write a threaded chat server, building on examples given in the book "Python Network Programming", chapter 21. I have managed to come up with af working (so it seems) solution, see code below. My question is: What is wrong with this aproach? I put each new connection in a common dict, and when i recieve a message i loop the dict and send the message to each connection (except the sender). In the book I'm told I have to a semaphore and a queue for each connection. What would I achieve by doing this, and how would i go about it? Thanks Christian My code looks like this: -------------------------------------- # -*- coding: latin_1 -*- # original: Echo Server with Threading - Chapter 21 - echoserver.py, Python Network programming import socket, traceback, os, sys from threading import * import time host = '' # Bind to all interfaces port = 10000 def handleclient(clientsock, connectionsDic): print "New child", currentThread().getName() print "Got connection from", clientsock.getpeername() #assign a name to this connection and put it in connectionsDic name = currentThread().getName() connectionsDic[name]=clientsock buffer = "" try: while 1: input = clientsock.recv(4096) if not len(input): break buffer += input if "\n" in buffer: #todo: check that \n is actually the end of buffer data = buffer buffer ="" for connName in connectionsDic.keys(): message = "%s says: %s"%(name, data) try: if connName!=name: connectionsDic[connName].sendall(message) else: connectionsDic[connName].sendall("Your message has been passed on\n\r") except: pass finally: # Close the connection clientsock.close() del connectionsDic[name] print name, " says goodbye.." # Set up the socket. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(1) #Dict to keep track og connections connectionsDic = {} while 1: try: clientsock, clientaddr = s.accept() except KeyboardInterrupt: raise except: traceback.print_exc() continue t = Thread(target = handleclient, args = [clientsock, connectionsDic]) t.setDaemon(1) t.start() --------------------------------------- From matthew.williams at cancer.org.uk Sat Oct 29 11:31:47 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Sat, 29 Oct 2005 10:31:47 +0100 Subject: [Tutor] Nokia 60 series Message-ID: <1130578307.2746.0.camel@localhost.localdomain> There's some extra info here: http://comments.gmane.org/gmane.comp.python.announce/5658 HTH, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com From alan.gauld at freenet.co.uk Sat Oct 29 13:26:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 29 Oct 2005 12:26:11 +0100 Subject: [Tutor] Tkinter References: <1d987df30510290027i5a6878a1l11235cd0f9e41dc0@mail.gmail.com> Message-ID: <024d01c5dc7b$90ee1f60$0a01a8c0@xp> > When I run the following code, > script kept running and I have to force it to stop. Yep. Thats usually what happens when you run a GUI program. What did you expect it to do? > Could you check the code to give suggestions how to improve it? I'll add some comments but its not clear what you are trying to do. Some general points first: 1) You should only have one call to mainloop() in a Tkinter program. 2) Its bad practice to have code after the "if name==main " block. That code gets exercised as well as the if block - very confusing! Specific comments: class Dialog(Widget): def __init__(self, master=None, cnf={}, **kw): cnf = _cnfmerge((cnf, kw)) self.widgetName = '__dialog__' AG> Looks a bit weird. Names starting with underscores usually mean private AG> and __xxx___ style names are usually private to Python itself... But those are AG> merely conventions, but useful ones... Widget._setup(self, master, cnf) AG> Are you sure you don't want to call Widget.__init__ first? self.num = self.tk.getint( apply(self.tk.call, ('tk_dialog', self._w, cnf['title'], cnf['text'], cnf['bitmap'], cnf['default']) + cnf['strings'])) AG> I have no idea whats going on here! Can you explain? try: Widget.destroy(self) except TclError: pass AG> And having constructed the Widget subclass you now destroy it? AG> I'm very confused. def destroy(self): pass AG> except destroy doesn't do anything... if __name__ == '__main__': q = Button(None, {'text': 'How are you', Pack: {}}) AG> This is a very old fashioned way of configuring a Tkinter widget AG> and suggests you have been looking at a very old Tkinter tutorial. q = Button(None, text="How are you") q.pack() AG> would be more common. b1 = Listbox() b1.pack() c1 = Checkbutton(text="Check") c1.pack() q.mainloop() AG> So you set the mainlop running here and wait for events. AG> But you haven't defined any event handlers anywhere AG> let alone connected them to your widgets. The only things AG> that will work are the default window widgets from Tkinter import * AG> You've already done this up top root =Tk() menu=Menu(root) root.config(menu=menu) filemenu=Menu(menu) menu.add_cascade(label="Test", menu=filemenu) filemenu.add_command(label="Just Try") filemenu.add_separator() AG:> And this all looks a bit confused too, I'm not sure what AG> you are trying to achieve here? mainloop() AG> And you already called mainloop above, although this mainlop isn't AG> defined anyplace that I can see, its nopt attached to an object of AG> any kind... I think you need to clarify in your mind what you are trying to achieve and restructure the code to reflect that. As it is its not clear what exactly you think the code should do. Can you simplify it? Just get a basic window/menu combination set up and working, then once thats fixed fold the config stuff in later? Also I'd make sure you check out the latest Tkinter tutorial, all that configuration by dictionary stuff was deprecated about 7 years ago! HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From sowden at gmail.com Sat Oct 29 16:29:15 2005 From: sowden at gmail.com (Eddie S) Date: Sat, 29 Oct 2005 15:29:15 +0100 Subject: [Tutor] OS X 10.4 and MySQL for Python Message-ID: <3082bc030510290729m74413db8v@mail.gmail.com> I was just about to attempt to install the python mysql package (http://sourceforge.net/projects/mysql-python/). I just wanted to know if anyone has attempted this on OS X 10.4. Searching the list it is very possible on past versions of os x no one seems to have commented on the latest version though. Cheers Eddie. From nick at javacat.f2s.com Sat Oct 29 20:37:15 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Sat, 29 Oct 2005 19:37:15 +0100 Subject: [Tutor] Global var problem In-Reply-To: <01d401c5dc0b$c2985000$0a01a8c0@xp> References: <43629518.2090904@javacat.f2s.com> <01d401c5dc0b$c2985000$0a01a8c0@xp> Message-ID: <4363C15B.1070000@javacat.f2s.com> Alan Gauld wrote: >> messing about with classes I've come across something basic that I >> don't understand. > > > As you say this has nothing to do with classes its more basic. Its > about namespaces. Try reading the namespaces topic in my tutor for > more info. > > Meanwhile lets simplify by removing the class bit > > > def h(): > global x > x += 1 > print x > > h() # prints 43 Many thanks to Alan, Andrei, Hugo and Welsey for helping me to understand where I was going wrong. I thought I understood namespaces but _obviously_ not . Thanks again, Nick . From Nick.Pomponio at gtri.gatech.edu Fri Oct 28 18:32:27 2005 From: Nick.Pomponio at gtri.gatech.edu (Nick.Pomponio@gtri.gatech.edu) Date: Fri, 28 Oct 2005 12:32:27 -0400 Subject: [Tutor] Can anyone help me? Message-ID: The "odds" are determined by the number of favorable outcomes to the number of unfavorable outcomes. In the case of flipping a coin, the odds are 1/1 (sometimes written as 1:1) for heads. The _probability_ of an event (as per a "frequency" definition) is the number of favorable outcomes that cause the event to occur to the total number of outcomes (assuming a uniform distribution). For flipping a coin, the probability of heads would be 1/2. Whether or not the total number of tickets sold impacts your probability of winning depends on the way that the lottery is conducted. Here in Georgia, I believe that the winning lottery sequence is drawn from all possile sequences, not from the restricted set of those sequences from sold tickets only. In the former case, the probability of winning is dependent only on the number of tickets you purchase. In the latter case (or a similar case in which winning sequences were generated until someone won), the number of other tickets sold would affect your chances of winning. -Nick Pomponio ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Smith, Jeff Sent: Friday, October 28, 2005 11:08 AM To: bob; Tutor at python.org Subject: Re: [Tutor] Can anyone help me? But the odds that you will win are not impacted by the number of tickets that are sold in total...only the number you buy. When you take into account the total number of tickets sold, all you get are the odds that the lottery will be won by anyone. I'm also a little confused by that def of odds. Consider flipping a coin. The probability that it will come up heads is 1/2. That def says that the odds in favor of it coming up heads is 1. Jeff -----Original Message----- From: bob [mailto:bgailer at alum.rpi.edu] Sent: Friday, October 28, 2005 10:52 AM To: Smith, Jeff; Tutor at python.org Subject: Re: [Tutor] Can anyone help me? At 07:28 AM 10/28/2005, Smith, Jeff wrote: Aren't the odds just based on how many tickets you buy? The odds aren't affected by different people buying more tickets. If only one person buys a ticket in the entire lottery system, his odds of winning are the same as if two people play, and the same as if 20 million play. According to the wikipedia: "In probability theory and statistics the odds in favor of an event or a proposition are the quantity p / (1-p), where p is the probability of the event or proposition." If you assign equal probability of winning to each ticket then odds are how many tickets you buy relative to how many tickets everyone else has bought. The probability of a ticket winning is 1 / m**n where m is the highest number possible and n is the number of numbers. If a lottery uses 6 numbers each in the range 1..42 then the probability of a ticket winning is 1/5489031744. All of this is mathematics. Sometimes one or more tickets win. Is that "luck"? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051028/ad6d20bb/attachment.htm From mike.rowan at internode.on.net Sat Oct 29 03:59:15 2005 From: mike.rowan at internode.on.net (Michael Rowan) Date: Sat, 29 Oct 2005 11:29:15 +0930 Subject: [Tutor] Real newbie - python can't open spam.py Message-ID: <4362D773.1060200@internode.on.net> Hi I'm on my first day with python2.3 on Windows XP. I'm able to run python interactively. I've created a text file using NotePad, named it spam.py (as per O'REILLY Learning Python, p13) contents as folows import sys print sys.argv If I do: >python spam.py it says can't open file 'spam.py' Anyone know why? I can open the file in NotePad without problem. Thanks Mike From kent37 at tds.net Sat Oct 29 23:11:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Oct 2005 17:11:44 -0400 Subject: [Tutor] Real newbie - python can't open spam.py In-Reply-To: <4362D773.1060200@internode.on.net> References: <4362D773.1060200@internode.on.net> Message-ID: <4363E590.8090107@tds.net> Michael Rowan wrote: > Hi > > I'm on my first day with python2.3 on Windows XP. I'm able to run > python interactively. > > I've created a text file using NotePad, named it spam.py. If I do: > > >python spam.py > > it says can't open file 'spam.py' > > Anyone know why? I can open the file in NotePad without problem. Is spam.py in the current directory when you type the command? If not, cd to the directory containing spam.py. What is the exact error message you get? Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Sat Oct 29 23:15:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 29 Oct 2005 14:15:02 -0700 (PDT) Subject: [Tutor] IDLE error msgs and line continuations? In-Reply-To: Message-ID: On Thu, 27 Oct 2005, CPIM Ronin wrote: > When using IDLE, after hitting F5 to save and run, if an error occurs, > it merely flashes at the code location of the error. While I usually > figure out what is wrong, why don't I get the detailed text error > messages that the command line gives? > > Also, I'm getting most error messages when I try line continuation for > clarity: > > if (condition 123 and > condition 456): Hi RC, It might be the case that 'condition 123' is malformed. If this is true, then the problem doesn't stem from going across lines, but with the 'condition 123' and 'condition 456' stuff. Just to check: ###### >>> if (condition 123 and File "", line 1 if (condition 123 and ^ SyntaxError: invalid syntax ###### Yeah, looks like Python immediately seizes on that part and stops at the point where the SyntaxError is. It doesn't even wait for me to enter in the rest of the line. I'm not sure if this is the real error that you're seeing; you may have just used 'condition 123' simply as an example. If you have code that you can show us, we'll look at it more carefully. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Sun Oct 30 00:14:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 29 Oct 2005 15:14:49 -0700 (PDT) Subject: [Tutor] Birthday paradox (was: Re: Random number generator (was: Can anyone help me?)) In-Reply-To: <4362023E.5000406@accesstel.co.za> Message-ID: On Fri, 28 Oct 2005, Johan Geldenhuys wrote: > After I tested the previous code, I noticed that the odds is 1:49 that a > duplicate number can be found in the 6 digit range (and it happended) > and that 0 can also be found. Hi Johan, I'm not exactly sure how 1 in 49 are the odds of getting a duplication. Let's talk about this for a moment. [Warning: long post ahead.] Just to make sure: the situation is that we're rolling a fifty-sided dice six times, and we'd like to see what's the probability of having duplicates in the mix. We have 50**6 possible rolls, but there are only: 50 * 49 * 48 * 47 * 46 * 45 ways of making sure we don't hit duplicates. The probability that we don't hit any duplicates, then, is: ###### >>> (50 * 49 * 48 * 47 * 46 * 45) / (50 **6) 0L ##### Oops, forgot about integer division. *grin* Let me try that again: ###### >>> (50.0 * 49 * 48 * 47 * 46 * 45) / (50 **6) 0.73224345599999996 ###### Ok, so we have about a 73% chance of not having any duplicate numbers if we roll a 50-digit dice six times. Since we can either have no duplication or duplication, then he probability that we will have duplication is: (1 - probability of not having duplication) ###### >>> 1 - (50.0 * 49 * 48 * 47 * 46 * 45) / (50 **6) 0.26775654400000004 ###### So we have about a 27% percent chance of getting duplication when we roll a fifty sided dice six times. But that's just probability theory. Is this real? Is this truly probable? Let's test this experimentally. First, we need some way of generating a roll of dice. Here's a quick-and-dirty function to do that: ###### >>> def make_roll(n, r): ... return [random.randrange(n) for i in range(r)] ... >>> make_roll(50, 6) [11, 48, 39, 43, 30, 24] >>> make_roll(50, 6) [6, 47, 0, 34, 9, 38] ###### We can test things experimentally by writing a function to see a roll has duplication: ###### >>> def has_duplication(roll): ... d = {} ... for number in roll: ... d[number] = d.get(number, 0) + 1 ... for count in d.values(): ... if count > 1: ... return True ... return False ... >>> has_duplication([1, 2, 3]) False >>> has_duplication([1, 2, 2]) True ###### Once we have this tool, then it becomes easy to do a trial run and see, if we roll 10 times, what percentage of those are duplicates. ###### >>> count_duplicates = 0 >>> for i in range(10): ... if has_duplication(make_roll(50, 6)): ... count_duplicates = count_duplicates + 1 ... >>> count_duplicates 1 >>> 1.0 / 10 0.10000000000000001 ###### Experimentally, we're seeing 1%, but that might just be a fluke. Or maybe it's just because the trial size is much too small. *grin* Let's formalize this test as a function, just to make it easier to retry: ###### >>> def do_trial(n): ... """Returns the number of duplicates if we do a n-trial.""" ... count_duplicates = 0 ... for i in range(n): ... if has_duplication(make_roll(50, 6)): ... count_duplicates = count_duplicates + 1 ... return float(count_duplicates) / n ... >>> >>> do_trial(5) 0.40000000000000002 >>> do_trial(10) 0.29999999999999999 >>> do_trial(100) 0.27000000000000002 >>> do_trial(1000) 0.26900000000000002 >>> do_trial(10000) 0.2621 >>> do_trial(100000) 0.26676 ###### So we're experimentally getting evidence that the probability of rolling duplicates is about 26%, if we have a 50-sided dice six times. Hey, that's not bad: that's about the value we got from doing math. As we scale our expeiment higher, we start seeing the Law of Large Numbers taking place: when we use lots of trials, then our experimental results start getting very close to the one we calculated with probability theory. http://en.wikipedia.org/wiki/Law_of_large_numbers Here's a punchline: the problem we've been looking at is another disguise for the Birthday Paradox: http://en.wikipedia.org/wiki/Birthday_problem That article makes the assertion that if we have 23 people in a room, the probability that we have at least two people with the same birthday is pretty good (about 50%). We can modify do_trial() to experimentally see that! ###### >>> def do_trial(n, x, y): ... """Returns the number of duplicates if we do a n-trial.""" ... count_duplicates = 0 ... for i in range(n): ... if has_duplication(make_roll(x, y)): ... count_duplicates = count_duplicates + 1 ... return float(count_duplicates) / n ... >>> do_trial(10000, 365, 23) 0.51390000000000002 >>> do_trial(10000, 365, 1) 0.0 >>> do_trial(10000, 365, 2) 0.0023 >>> for i in range(23): ... print i, "people, probability of shared birthday:", do_trial(10000, 365, i) ... 0 people, probability of shared birthday: 0.0 1 people, probability of shared birthday: 0.0 2 people, probability of shared birthday: 0.0035 3 people, probability of shared birthday: 0.0087 4 people, probability of shared birthday: 0.0181 5 people, probability of shared birthday: 0.0273 6 people, probability of shared birthday: 0.0436 7 people, probability of shared birthday: 0.0551 8 people, probability of shared birthday: 0.0736 9 people, probability of shared birthday: 0.0932 10 people, probability of shared birthday: 0.1201 11 people, probability of shared birthday: 0.1325 12 people, probability of shared birthday: 0.1654 13 people, probability of shared birthday: 0.1967 14 people, probability of shared birthday: 0.2241 15 people, probability of shared birthday: 0.2581 16 people, probability of shared birthday: 0.281 17 people, probability of shared birthday: 0.3169 18 people, probability of shared birthday: 0.3497 19 people, probability of shared birthday: 0.3843 20 people, probability of shared birthday: 0.4171 21 people, probability of shared birthday: 0.438 22 people, probability of shared birthday: 0.4817 ###### The variable names 'x' and 'y' suck (I'll try to think of better ones next time), but I hope that it's clear what we're doing: we're making do_trial() more general so it can handle different dice rolls. And because they are parameters in our do_trial() function, we can then see what the situation loosk like as we get more and more kids in the classroom. Does this make sense? If you have any questions about this, please feel free to ask. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Oct 30 00:21:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 29 Oct 2005 15:21:30 -0700 (PDT) Subject: [Tutor] Birthday paradox (was: Re: Random number generator (was: Can anyone help me?)) In-Reply-To: Message-ID: > ###### > >>> count_duplicates = 0 > >>> for i in range(10): > ... if has_duplication(make_roll(50, 6)): > ... count_duplicates = count_duplicates + 1 > ... > >>> count_duplicates > 1 > >>> 1.0 / 10 > 0.10000000000000001 > ###### > > > Experimentally, we're seeing 1%, but that might just be a fluke. Or maybe > it's just because the trial size is much too small. *grin* Gaaa. I can't add or subtract. I meant: Experimentally, we're seeing 10%, but that might just be a fluke. Or maybe it's just because the trial size is much too small. > >>> def do_trial(n): > ... """Returns the number of duplicates if we do a n-trial.""" > ... count_duplicates = 0 > ... for i in range(n): > ... if has_duplication(make_roll(50, 6)): > ... count_duplicates = count_duplicates + 1 > ... return float(count_duplicates) / n The comment is wrong. It should be: """Returns the probability of duplicates if we do an n-trial.""" > The variable names 'x' and 'y' suck (I'll try to think of better ones next > time), but I hope that it's clear what we're doing: we're making > do_trial() more general so it can handle different dice rolls. And > because they are parameters in our do_trial() function, we can then see > what the situation loosk like as we get more and more kids in the ^^^^^ Looks, not loosks. Sorry about that! From missive at hotmail.com Sun Oct 30 00:39:15 2005 From: missive at hotmail.com (Lee Harr) Date: Sun, 30 Oct 2005 03:09:15 +0430 Subject: [Tutor] Python as Application (OT now) Message-ID: Sorry about misposting this here. I always mix up the tutor@ and edu-sig@ lists. I am just going to follow up two things that seem tutor related. If this seems interesting, you may want to join the edu-sig list for more... >>More frightening to me than the ubiquitous use of MS Office is the >>omnipresence of windows. Every time a student sits down in front >>of KDE in our lab and says "Where is the internet?" I can only cringe. >I do wonder why you cringe. Educate the user. He is expecting his >usual metaphor, and it's not there. The majority of the world has it, >remember, so he expects you to as well. > Certainly. I guess I should have said "I have to cringe" instead of "...only cringe". I don't just walk away and leave people wondering why it is impossible to do what they want to do. As for why ... I guess I just see internet explorer (and windows) as so limiting, that I cannot understand why this is what we are teaching. How do children reach high school without knowing what the internet is, and that it is not the blue "e"? >I've never worked in any workplace where anything else other than >Excel was used. >You can't really separate spreadsheet from Excel, or word processing >from Word, in the general public's view. Well. I've never worked anyplace where excel was used for anything other than a badly designed database. Someone must be teaching people that is what it is for. ("Formula? What is a formula?") I also get all kinds of odd documents in my lab. People have no idea what file formats are and are (understandably) upset when they cannot print out their papers. And yes, we do have a computer running windows with office, and we still get strange microsoft documents that are unopenable. Papers are generally poorly formatted. Things like using the space bar or tab key to center things. Then even when the docs do open up, the formatting is all askew. Perhaps if teachers thought more about the _abstraction_ of a word processor and the _abstraction_ of a spreadsheet, and focused on how these tools are best used -- instead of focusing on how to use the specific implementations -- we would have fewer problems, and more capable students. To me, programming is all about abstraction. Thanks for your time. (please follow up to edu-sig) _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From dyoo at hkn.eecs.berkeley.edu Sun Oct 30 00:45:20 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 29 Oct 2005 15:45:20 -0700 (PDT) Subject: [Tutor] Code Readability (was: Recursion and List Comprehensions) In-Reply-To: Message-ID: > > I agree. When writing for keeps (i.e. production code) I prefer > > clarity and ease of maintenance over 'elegance' or 'trickiness'. > > This exercise is intended, in part, to sharpen my understanding of > > Python idioms. If I can write highly idiomatic code that works, > > chances are better that I will be able to decipher it when I come > > across it elsewhere. > Since when is elegance a dirty word? It's not. But there are tradeoffs. As a concrete example, we can take a look at Bram Cohen's fairly recent request for a pure-Python suffix tree implmementation: http://www.livejournal.com/users/bramcohen/22069.html He's specifically requesting for an implementation for a data structure algorithm that is easy to maintain, and he's willing to sacrifice the elegant optimal solution! But that's because he wants to make sure he can understand the code later on. I'm not sure I agree with Bram --- the "Ukkonen" algorithm for building suffix trees isn't bad, and I can probably cook it up if I'm careful --- but I can see why he values a simple implementation. From grouch at gmail.com Sun Oct 30 02:02:04 2005 From: grouch at gmail.com (Andrew P) Date: Sat, 29 Oct 2005 20:02:04 -0500 Subject: [Tutor] Code Readability (was: Recursion and List Comprehensions) In-Reply-To: References: Message-ID: Sorry. *blush* That was some late Friday night craziness. I just looked at the code being discussed: retList=[word[pos]+item for item in permute3(word[0:pos]+word[pos+1:])] And really didn't want to anybody to confuse that with Python's idea of elegance. List comprehensions can get pretty horrible when combined with nested functions and/or slices and/or multiple implicit loops. One of the few areas where Python can get really twisted. That's a great point, Danny. For me, elegance is an admirable goal under any circumstance, but includes all the aspects I listed. Effeciency -and- understandability. Throw it under the umbrella of "graceful" :) The tools we use are far from perfect, and there are still plenty of "aha!" moments to go around. In the real world the fast and ugly usually go hand in hand. I'm an optimist, tho. Anyway, sorry to go so far off topic. Oh, and by the way, I loved 'The Psychology of Programming'. That was a really entertaining book, and thanks again for recommending it. Andrew On 10/29/05, Danny Yoo wrote: > > > > I agree. When writing for keeps (i.e. production code) I prefer > > > clarity and ease of maintenance over 'elegance' or 'trickiness'. > > > This exercise is intended, in part, to sharpen my understanding of > > > Python idioms. If I can write highly idiomatic code that works, > > > chances are better that I will be able to decipher it when I come > > > across it elsewhere. > > > Since when is elegance a dirty word? > > It's not. But there are tradeoffs. As a concrete example, we can take a > look at Bram Cohen's fairly recent request for a pure-Python suffix tree > implmementation: > > http://www.livejournal.com/users/bramcohen/22069.html > > He's specifically requesting for an implementation for a data structure > algorithm that is easy to maintain, and he's willing to sacrifice the > elegant optimal solution! But that's because he wants to make sure he can > understand > I'm not sure I agree with Bram --- the "Ukkonen" algorithm for building > suffix trees isn't bad, and I can probably cook it up if I'm careful --- > but I can see why he values a simple implementation. > > d the code later on. > From kent37 at tds.net Sun Oct 30 15:24:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Oct 2005 09:24:11 -0500 Subject: [Tutor] syracuse sequence (collatz or hailstone) In-Reply-To: <1635.172.142.243.213.1130551436.squirrel@172.142.243.213> References: <3209.172.168.38.88.1130515184.squirrel@172.168.38.88> <43627A62.7080402@tds.net> <1635.172.142.243.213.1130551436.squirrel@172.142.243.213> Message-ID: <4364D78B.9020803@tds.net> andrade1 at umbc.edu wrote: > would this be a possible use of a list and appending even though I recieve > an error from it: > > def main(): > x = [1] > x[0] = input('enter an int to start your syracuse sequence\n') > while not isinstance(x[0], int): > x[0] = input('no, please enter an int to start your syracuse > sequence\n') > while x[-1] != 1: > if ((x[-1] % 2) == 0): > x.append(x[-1] / 2) > else: > x.append((3 * x) + 1) This should be x.append((3 * x[-1]) + 1) The error is caused by the expression ((3*x) + 1). When x is a list, 3*x is a valid operation; it creates a new list with the elements of the original list repeated three times. Then you do newlist+1. For a list, + means concatenate - it puts two lists together. Since the right-hand value is not a list, you get an error. Other than that your code is OK but it would be clearer (and avoid errors like the above!) if you used separate names for the current value of x and for the list. Kent > print len(x), x > > print "The Syracuse sequence of your starting value is:", x > > main() > > line 10, in main > x.append((3 * x) + 1) > TypeError: can only concatenate list (not "int") to list > > > > >>andrade1 at umbc.edu wrote: >> >>>hello, >>> >>>Could I gather all of the values from print x into a string or a range? >>>Since, I am not familiar with lists yet. >> >>Here is a simple example of gathering values into a list and making a >>string: >> >>> r=[] # Start with an empty list >> >>> for x in range(3): # x will be 0, 1, 2 in sequence >> ... r.append(str(x*x)) # Put x*x (as a string) onto r >> ... >> >>> r >>['0', '1', '4'] >> >>> ', '.join(r) # make a single string by joining the elements of r with >>', ' >>'0, 1, 4' >> >>Kent >> >> >>> >>>def main(): >>> x = input("Please enter a positive starting value: ") >>> while x != 1: >>> if x%2 == 0: >>> x = x/2 >>> else: >>> x = x*3+1 >>> print x >>> print "The Syracuse sequence of your starting value is:", x >>> >>>main() >>> >>> >>> >>> >>>----- Original Message ----- >>>From: "Frank Bloeink" >>>To: >>>Sent: Friday, October 28, 2005 5:06 AM >>>Subject: Re: [Tutor] syracuse sequence (collatz or hailstone) >>> >>> >>> >>> >>>>Hey, >>>> >>>>your code seems almost alright to me, except that in your case it's only >>>>printing the last number of your sequence, which obviously is not what >>>>you want. Quick fix would be to insert a line "print x" just below else >>>>statement: >>>>---snip-- >>>>else: >>>> x=x*3+1 >>>>print x >>>>---snip >>>>This should make clear where the error is: You are just calculating, but >>>>not printing the sequence! >>>>If you want to leave the output to the end of the program you could as >>>>well gather all the calculated values in a list or similar structure and >>>>then print the contents of the list.. >>>> >>>>hth Frank >>>> >>>>On Fri, 2005-10-28 at 01:22 -0400, andrade1 at umbc.edu wrote: >>>> >>>> >>>>>Hello >>>>> >>>>>I am trying to create a program that will calculate the syracuse >>>>>sequence >>>>>which is also known as collatz or hailstone. the number that is input >>>>>by >>>>>the user may be either even or odd. the number goes through a series of >>>>>functions which are x/2 if the number is even and 3x+1 if the number is >>>>>odd. it keeps doing so until the number reaches 1. An example would be >>>>>if >>>>>the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the >>>>>sequence >>>>>for the value that they started with. My code currently just prints a 1 >>>>>and none of the numbers that would have preceded it. any ideas on how I >>>>>could get the program to not do this would be greatly appreciated. >>>>> >>>>> >>>>>def main(): >>>>> try: >>>>> x = input("Please enter a starting value: ") >>>>> while x != 1: >>>>> >>>>> if x%2 == 0: >>>>> x = x/2 >>>>> else: >>>>> x = x*3+1 >>>>> >>>>> except ValueError, excObj: >>>>> msg = str(excobj) >>>>> if msg == "math domain error": >>>>> print "No negatives or decimals." >>>>> else: >>>>> print "Something went wrong." >>>>> >>>>> >>>>> >>>>> print "The Syracuse sequence of your starting value is:", x >>>>> >>>>>main() >>>>> >>>>> >>>>>_______________________________________________ >>>>>Tutor maillist - Tutor at python.org >>>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >>-- >>http://www.kentsjohnson.com >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > -- http://www.kentsjohnson.com From grouch at gmail.com Sun Oct 30 15:45:52 2005 From: grouch at gmail.com (Andrew P) Date: Sun, 30 Oct 2005 08:45:52 -0600 Subject: [Tutor] AJAX resources for Python In-Reply-To: <4362EE38.4050201@tds.net> References: <20051029013109.GR1791@johnsons-web.com> <4362EE38.4050201@tds.net> Message-ID: Turbogears seconded. It's a really great collection of tools. As an alternative, you may also want to check out Nevow. From the webpage: "Nevow includes LivePage, a two-way bridge between JavaScript in a browser and Python on the server. For 0.3, LivePage has been updated to operate on Mozilla, Firefox, Windows Internet Explorer 6, and Safari on Mac OS X. Event handlers can be written in pure Python and JavaScript implementation details are hidden from the programmer, with Nevow taking care of routing data to and from the server using XmlHttpRequest." You'd use it with Twisted, but it may be the easiest solution once the initial learning curve is over. Livepage actually predates the AJAX terminology, so it's been around a while. The only major example I've seen is at http://www.jotlive.com, but it's a pretty good one. Multiple people can edit a document interactively at the same time. I tried the free account, and it was impressive. Good luck, Andrew From lists at janeden.org Sun Oct 30 17:00:37 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 30 Oct 2005 17:00:37 +0100 Subject: [Tutor] Transforming object into subclass instance Message-ID: Hi, my program uses an initial "switch" statement to create an object: valid_types = dict( pages=Show.Page, syndicated=Show.Syndicated, authors=Show.Author, author_list=Show.AuthorList, galleries=Show.Gallery, pictures=Show.Picture, slideshow=Show.SlidePicture, tex=Show.Tex, blogs=Show.Blog, blogentries=Show.BlogEntry, search=Show.Search, search_author=Show.SearchAuthor, not_found=Show.NotFound ) # ... code ommitted... page = valid_types[type]]() For a certain class, it is only during the execution of the __ini__ method that I can distinguish between two subtypes (subclasses). The subclasses define two different versions of method A. Now my question is: How can I turn an object of class X into an object of either class Y or Z while (retaining all the attributes defined so far). I know I could solve the problem by using another switch statement - but is there consistent OOP solution for this problem? Thanks, Jan -- Hanlon's Razor: Never attribute to malice that which can be adequately explained by stupidity. From alan.gauld at freenet.co.uk Sun Oct 30 17:23:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 30 Oct 2005 16:23:11 -0000 Subject: [Tutor] Python as Application (OT now) References: Message-ID: <003601c5dd6e$38911360$0a01a8c0@xp> > Papers are generally poorly formatted. Things like using the space > bar or tab key to center things. Then even when the docs do open > up, the formatting is all askew. > This is one of my pet peeves. Many so called MS Office training courses barely touch on the use of paragraph formats, very few go into them in any depth and yet they are fundamental to consistent documemnts easily produced. The whole concept of styles is missed by many users - even the IT students we employ on vacation training.... > Perhaps if teachers thought more about the _abstraction_ of a word > processor and the _abstraction_ of a spreadsheet, and focused on > how these tools are best used -- instead of focusing on how to > use the specific implementations -- we would have fewer problems, > and more capable students. Absolutely correct. The same is true of programming however. Too many programming courses teach a language rather than programming. There is no difference between a course teaching programming students Python and one teaching business students Excel IMHO. Teach the principles, illustrate with a tool (or better several tools) and you get a much more effective student. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld > > To me, programming is all about abstraction. > > > Thanks for your time. > (please follow up to edu-sig) > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > > From andrade1 at umbc.edu Sun Oct 30 17:37:42 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Sun, 30 Oct 2005 11:37:42 -0500 (EST) Subject: [Tutor] help with prime number program Message-ID: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> Hello I am trying to write a program that will figure out if a number is prime or not. Currently this is the code that I have: import math def main(): number=input("Please enter a positive whole number greater than 2: ") for value in range(2, number-math.sqrt): if number % value == 0: print number, "is not prime" exit print number, "is prime" main() my problem is that the output prints both statements whether the number is prime or not. How could I get it to only print the one statement saying that 49 is not a prime number? enter a number greater than 2: 49 49 is not prime 49 is prime From dyoo at hkn.eecs.berkeley.edu Sun Oct 30 18:45:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 30 Oct 2005 09:45:41 -0800 (PST) Subject: [Tutor] help with prime number program In-Reply-To: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> Message-ID: > I am trying to write a program that will figure out if a number is prime > or not. Currently this is the code that I have: [code cut] Hi Andrade1, As in your other previous homework programs, you seem to have some trouble with control flow. Have you considered talking with your professor or teaching assistant about this? > import math > > def main(): > number=input("Please enter a positive whole number greater than 2: ") > for value in range(2, number-math.sqrt): > if number % value == 0: > print number, "is not prime" > exit > print number, "is prime" > > main() > > my problem is that the output prints both statements whether the number > is prime or not. The block of code: ###### for value in range(2, number-math.sqrt): if number % value == 0: print number, "is not prime" exit ###### has two issues. 1. What is 'exit'? 2. What is 'number - math.sqrt'? Instead of 'exit', you may be looking for the 'return' statement instead. Good luck to you. From kent37 at tds.net Sun Oct 30 19:21:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Oct 2005 13:21:27 -0500 Subject: [Tutor] Transforming object into subclass instance In-Reply-To: References: Message-ID: <43650F27.9090006@tds.net> Jan Eden wrote: > Now my question is: How can I turn an object of class X into an > object of either class Y or Z while (retaining all the attributes > defined so far). This is easy, in fact - you can change the class of an instance by assigning to its __class__ attribute: >>> class F(object): ... def p(self): print "F" ... >>> class G(object): ... def p(self): print "G" ... >>> f=F() >>> f.p() F >>> type(f) >>> f.__class__ = G >>> f.p() G >>> type(f) > > I know I could solve the problem by using another switch statement - > but is there consistent OOP solution for this problem? I'm not sure I would call this solution OO or pretty but it does work. Kent -- http://www.kentsjohnson.com From andrade1 at umbc.edu Sun Oct 30 19:40:34 2005 From: andrade1 at umbc.edu (andrade1@umbc.edu) Date: Sun, 30 Oct 2005 13:40:34 -0500 (EST) Subject: [Tutor] help with prime number program In-Reply-To: References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> Message-ID: <2003.172.134.210.33.1130697634.squirrel@172.134.210.33> > > >> I am trying to write a program that will figure out if a number is prime >> or not. Currently this is the code that I have: > > [code cut] > > Hi Andrade1, > > As in your other previous homework programs, you seem to have some trouble > with control flow. Have you considered talking with your professor or > teaching assistant about this? > > >> import math >> >> def main(): >> number=input("Please enter a positive whole number greater than 2: >> ") >> for value in range(2, number-math.sqrt): >> if number % value == 0: >> print number, "is not prime" >> exit >> print number, "is prime" >> >> main() >> >> my problem is that the output prints both statements whether the number >> is prime or not. > > > The block of code: > > ###### > for value in range(2, number-math.sqrt): > if number % value == 0: > print number, "is not prime" > exit > ###### > > has two issues. > > 1. What is 'exit'? instead of exit I can use break so that the loop will stop executing > 2. What is 'number - math.sqrt'? for math.sqrt I could use math.sqrt(n) so that it would take the sqrt of n which is entered in by the user However for the output I am still receiving enter a number greater than 2: 49 49 is prime 49 is prime 49 is prime 49 is prime 49 is prime 49 is not prime > Instead of 'exit', you may be looking for the 'return' statement instead. > > > Good luck to you. > > From adam.jtm30 at gmail.com Mon Oct 31 00:17:59 2005 From: adam.jtm30 at gmail.com (Adam) Date: Sun, 30 Oct 2005 23:17:59 +0000 Subject: [Tutor] help with prime number program In-Reply-To: <2003.172.134.210.33.1130697634.squirrel@172.134.210.33> References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> <2003.172.134.210.33.1130697634.squirrel@172.134.210.33> Message-ID: > 1. What is 'exit'? > instead of exit I can use break so that the loop will stop executing > > > 2. What is 'number - math.sqrt'? > for math.sqrt I could use math.sqrt(n) so that it would take the sqrt of n > which is entered in by the user > > > However for the output I am still receiving > > enter a number greater than 2: 49 > 49 is prime > 49 is prime > 49 is prime > 49 is prime > 49 is prime > 49 is not prime The problem is using break just breaks from the loop and then goes into the next instruction being print number, "is prime" As Danny suggested before using return will stop the entire function rather than the just the loop. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051030/5c380157/attachment-0001.htm From scottclausen at mac.com Mon Oct 31 02:29:32 2005 From: scottclausen at mac.com (Scott Clausen) Date: Sun, 30 Oct 2005 17:29:32 -0800 Subject: [Tutor] Newbie Question - Python vs Perl Message-ID: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> As a newbie to Python I'd like to know if someone can tell me some strengths and weaknesses of this language. The reason I'm asking is a friend told me I should learn Perl over Python as it's more prevalent. I'm going to be using it on a Mac. I'd appreciate hearing any views on this topic. My own view is that it's always good to learn new things as you then have more tools to use in your daily programming. Thanks in advance. Scott From kent37 at tds.net Mon Oct 31 04:56:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Oct 2005 22:56:04 -0500 Subject: [Tutor] Newbie Question - Python vs Perl In-Reply-To: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> References: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> Message-ID: <436595D4.3020005@tds.net> Scott Clausen wrote: > As a newbie to Python I'd like to know if someone can tell me some > strengths and weaknesses of this language. The reason I'm asking is a > friend told me I should learn Perl over Python as it's more > prevalent. I'm going to be using it on a Mac. http://wiki.python.org/moin/BeginnersGuide/Overview http://www.linuxjournal.com/article/3882 You might be interested in this site that lets you compare Python and Perl code http://pleac.sourceforge.net/ -- http://www.kentsjohnson.com From grouch at gmail.com Mon Oct 31 07:44:40 2005 From: grouch at gmail.com (Andrew P) Date: Mon, 31 Oct 2005 00:44:40 -0600 Subject: [Tutor] python myspace module? In-Reply-To: References: Message-ID: Probably the most useful library from the wwwsearch page Danny pointed you to is the cookielib, which is built into Python as of 2.3 or 2.4. The most useful because you can't scrape by without it on most sites, and cookies are really no fun to handle manually Login and forms can largely be fudged, but it's really nice to have cookies handled transparently. You'll want to do something like: url = "http://www.myspace.com" cj = cookielib.CookieJar() myURLOpen = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) myURLOpen.addheaders = [('User-agent', 'Mozilla/5.0')] urlopen = myURLOpen.open urlopen(url).read() I think this came straight from the Python docs originally, where it's explained a bit more fully. But this will do two things. 1) set up a client side cookie, and magically handle all cookie magic for you, and 2) change your user agent to 'Mozilla/5.0', completing the illusion that you are a browser. Many sites don't like to see user agents like "Python-urllib/2.4" :) The rest is just understanding how forms work. I've never used a library, just POSTed/GETted the data directly to login and search sites. So I can't say how much easier it would be. Probably quite a bit. You can POST data like: urlopen("https://www.whatever.com/signin.dll",data=authPairs).close() where authPairs is something like: authPairs = urllib.urlencode({'userid':'andrew', 'password':'secret1234'}) You'll have to dig around in the html to see whether forms are using POST or GET, and what variables they are passing, etc. But that should be enough to get you started. Logged in, and able to fetch pages and fill out forms manually. Good luck, Andrew On 10/25/05, Ed Hotchkiss wrote: > looking to write a myspace wrapper/module. what is the best way (hopefully > using the stdlib not an outside module) to connect to a website and (if > possible, otherwise ill have to code it?) access forms with GET POST blah > blah blah ... > > thanks! > > -- > edward hotchkiss > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From samrobertsmith at gmail.com Mon Oct 31 09:24:24 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 31 Oct 2005 00:24:24 -0800 Subject: [Tutor] compare Message-ID: <1d987df30510310024t45381b5x5727f64979ed1a28@mail.gmail.com> What does this line 11 mean in the following code? 1 # calc.py 2 def calc(seq): 3 maximum = 0 4 max_item = [] 5 for i in seq: 6 product = (i[0]*100 + i[1]*10 + i[2]) * (i[3]*10 + i[4]) 7 if product > maximum: 8 maximum = product 9 max_item = i 10 elif product == maximum: 11 max_item += ','+i 12 return max_item, maximum 13 14 seq = [ [5,6,7,8,9], [5,6,7,9,8] ] 15 max_item, maximum = calc(seq) 16 print "Maximum at", max_item, ",product", maximum From ukc802591034 at btconnect.com Mon Oct 31 09:25:06 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Mon, 31 Oct 2005 08:25:06 -0000 Subject: [Tutor] Newbie Question - Python vs Perl References: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> Message-ID: > friend told me I should learn Perl over Python as it's more > prevalent. I'm going to be using it on a Mac. In that case you should switch to a PC because they are more prevalent. Also you should learn to program in COBOL since its the most prevalent of all computer languages. And yet most folks in the industry prefer Macs to PCs when they have a choice and most unbiased observers think COBOL sucks! Python is a lot easier to learn and work with than Perl... go figure. :-) -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From lists at janeden.org Mon Oct 31 09:42:55 2005 From: lists at janeden.org (Jan Eden) Date: Mon, 31 Oct 2005 09:42:55 +0100 Subject: [Tutor] Newbie Question - Python vs Perl In-Reply-To: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> Message-ID: Hi Scott, Scott Clausen wrote on 30.10.2005: >As a newbie to Python I'd like to know if someone can tell me some >strengths and weaknesses of this language. The reason I'm asking is >a friend told me I should learn Perl over Python as it's more >prevalent. I'm going to be using it on a Mac. > >I'd appreciate hearing any views on this topic. My own view is that >it's always good to learn new things as you then have more tools to >use in your daily programming. I started learning Python approx. 4 months ago. I had been using Perl for about 4 years at that time. (BTW, I work on a Mac, too) The motivation for trying Python came when a certain project needed an OOP overhaul. While I was able to code an OOP version of the program, the result was rather slow and ugly. This was only partly because of my own deficiencies - Perl does not really invite you to produce clean code on larger projects (IMHO). When I re-coded the very same project in Python, I achieved a much better (faster, more readable) result within weeks. Most comparisons of Perl and Python also highlight Python's cleaner syntax, I can second that (although I got used to Perl's @$% syntax after a while). Cheers, Jan -- Common sense is what tells you that the world is flat. From ml.cyresse at gmail.com Mon Oct 31 10:26:54 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 31 Oct 2005 22:26:54 +1300 Subject: [Tutor] Newbie Question - Python vs Perl In-Reply-To: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> References: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> Message-ID: On 10/31/05, Scott Clausen wrote: > As a newbie to Python I'd like to know if someone can tell me some > strengths and weaknesses of this language. The reason I'm asking is a > friend told me I should learn Perl over Python as it's more > prevalent. I'm going to be using it on a Mac. > > I'd appreciate hearing any views on this topic. My own view is that > it's always good to learn new things as you then have more tools to > use in your daily programming. > > Thanks in advance. > Hi Scott, I would say, it really depends on where you're coming from and where you're going, coding wise. If your background is primarily Linux scripting with sh, awk, grep, sed, (sed?) etc, then Perl will be a nice and natural fit. If you're starting from a clean slate, then I would recommend Python, speaking as a relative beginner who had to make that choice myself not too long ago. Python has a nice clean syntax, which means that your errors are usually errors of logic and not errors of using an @ instead of a $, or missing a }, etc. Perl has an incredibly huge library, and for a beginner, that's challenging. Python's standard library encompasses about 98% of everything I need to do, and in a year of coding in Python, I'm still not familiar with all of it, but I have a fair idea of where to find particular functionality. I tried Perl and got incredibly confused by CPAN. Python is OO from the get go. Want to subclass integers? Sure, go right ahead. Whereas, Perl tends to show it's roots in aforementioned shell scripts, and the OO side feels awkward. Also, I'll just mention a pet peeve of mine regarding Perl. It flattens lists using the simple syntax. To nest a list requires special syntax that most tutorials don't mention... The classic reasons to prefer one over the other are a) scalability, and b) maintainability. Python scales well, and is quite straightforward to maintain, although I live by the mantra that one can write Perl in any language. The catch-cry of Perl is "there's more than one way to do it." As a learner, you'll spend a lot of time asking "But which is the best way?" In Python, there's generally a straight-forward and obvious way, and it's usually the best and simplest. i.e. you can stick the items of a one list in another two ways, a for loop, and a list method. x=[1,2,3] y = [4,5,6] #either for item in y: x.append(item) #or x.extend(y) The extend() method is simpler, and faster. With regards to where you're going in the future, I don't know what the future holds for Perl, but watching the .NET framework arise, I think that Microsoft has the LAMP combination in it's sights. There's already a Python implementation for the .NET framework, it's called IronPython, (it's in alpha at the mo). To be honest, if you still wanted to go with Perl, I'd recommend you learn Ruby instead. It originated in Perl, but it's just flat out better. It's the language that experienced Perl users migrate to, as it has minimal culture shock. And, Ruby on Rails is a great framework. Ruby's standard library is quite minimal on the docs at the moment, and the 3rd party modules aren't there, yet, whereas Python has a mature community. Good luck, Liam Clarke From johan at accesstel.co.za Mon Oct 31 11:16:15 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon, 31 Oct 2005 12:16:15 +0200 Subject: [Tutor] compare In-Reply-To: <1d987df30510310024t45381b5x5727f64979ed1a28@mail.gmail.com> References: <1d987df30510310024t45381b5x5727f64979ed1a28@mail.gmail.com> Message-ID: <4365EEEF.1090204@accesstel.co.za> In your code that line is not executed. And if it was at some stage, it will give you an error. max_item is a list and you cannot put a string and a list together: "TypeError: cannot concatenate 'str' and 'list' objects". What are trying to do with this line? 'maximum = 0' and so product will be greater than maximum. It looks you are trying to append a list to seq that is already there? Maybe it's a bad guess from me, I'm no expert. Johan Shi Mu wrote: >What does this line 11 mean in the following code? > >1 # calc.py > 2 def calc(seq): > 3 maximum = 0 > 4 max_item = [] > 5 for i in seq: > 6 product = (i[0]*100 + i[1]*10 + i[2]) * (i[3]*10 + i[4]) > 7 if product > maximum: > 8 maximum = product > 9 max_item = i > 10 elif product == maximum: > 11 max_item += ','+i > 12 return max_item, maximum > 13 > 14 seq = [ [5,6,7,8,9], [5,6,7,9,8] ] > 15 max_item, maximum = calc(seq) > 16 print "Maximum at", max_item, ",product", maximum >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From norman at littletank.org Mon Oct 31 11:28:26 2005 From: norman at littletank.org (Norman Silverstone) Date: Mon, 31 Oct 2005 10:28:26 +0000 Subject: [Tutor] help with prime number program In-Reply-To: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> Message-ID: <1130754506.27431.4.camel@localhost.localdomain> > I am trying to write a program that will figure out if a number is prime > or not. Currently this is the code that I have: > > import math > > def main(): > > number=input("Please enter a positive whole number greater than 2: ") > for value in range(2, number-math.sqrt): > if number % value == 0: > print number, "is not prime" > exit > print number, "is prime" > > main() I am a beginner so, I hope what I give, makes sense. In it's simplest form what is wrong with :- n = input("Enter a number") if n % 2 != 0 and n % 3 != 0: print n, " Is a prime number" Comments please. Norman From kent37 at tds.net Mon Oct 31 12:12:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 31 Oct 2005 06:12:17 -0500 Subject: [Tutor] help with prime number program In-Reply-To: <1130754506.27431.4.camel@localhost.localdomain> References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> <1130754506.27431.4.camel@localhost.localdomain> Message-ID: <4365FC11.4050303@tds.net> Norman Silverstone wrote: > I am a beginner so, I hope what I give, makes sense. In it's simplest > form what is wrong with :- > > n = input("Enter a number") > if n % 2 != 0 and n % 3 != 0: > print n, " Is a prime number" > This only gives the correct answer if n < 25. You can't test against a fixed list of divisors, there will always be a non-prime whose divisors are not in your list. Kent -- http://www.kentsjohnson.com From ml.cyresse at gmail.com Mon Oct 31 12:18:03 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 1 Nov 2005 00:18:03 +1300 Subject: [Tutor] compare In-Reply-To: <4365EEEF.1090204@accesstel.co.za> References: <1d987df30510310024t45381b5x5727f64979ed1a28@mail.gmail.com> <4365EEEF.1090204@accesstel.co.za> Message-ID: > > > >1 # calc.py > > 2 def calc(seq): > > 3 maximum = 0 > > 4 max_item = [] > > 5 for i in seq: > > 6 product = (i[0]*100 + i[1]*10 + i[2]) * (i[3]*10 + i[4]) > > 7 if product > maximum: > > 8 maximum = product > > 9 max_item = i > > 10 elif product == maximum: > > 11 max_item += ','+i > > 12 return max_item, maximum > > 13 > > 14 seq = [ [5,6,7,8,9], [5,6,7,9,8] ] > > 15 max_item, maximum = calc(seq) > > 16 print "Maximum at", max_item, ",product", maximum Well, it runs and returns [5, 6, 7, 9, 8], 55566. Is that what you were expecting? If you can tell us what output you expected and how it deviated, it's always good, details are A Good Thing. ;-) Try feeding it seq = [ [5,6,7,8,9], [5,6,7,8,9] ] and you'll get the error Johan described, as product will equal maximum. Are you wanting the output Maximum at [ [5,6,7,8,9], [5,6,7,8,9] ] ,product 50463? As it looks like you're trying to join two lists. I think you've been bitten by some operator overloading wherein >>> [1,2,3] + [4,5,6] [1, 2, 3, 4, 5, 6] Basic rule is, you can use a + between string and string, integer/float and integer/float, list and list and tuple and tuple, and "," is a string, so it breaks it. Take it out... max_item += i #( max_item = max_item + i) At this point, max_item would equal [5,6,7,8,9] and adding i to it would produce - [5,6,7,8,9, 5,6,7,8,9]. You've got various ways to do this. max_item = [max_item] + [i] #and this is a terrible way to do it, max_item = [max_item, i] #Better. There's a problem with this however... Or, you could change line 8 and 11 to max_item.append(i) But that would give [[5,6,7,8,9]] if product != maximum the second time around, but [[5,6,7,8,9], [5,6,7,8,9]] if product did equal maximum. The problem with this - max_item = [max_item, i] is that if you entered seq = [[5,6,7,8,9], [5,6,7,8,9], [5,6,7,8,9] ] max_item would come out as [ [ [5,6,7,8,9], [5,6,7,8,9] ],[5,6,7,8,9] ]... If you are going to be handling more than two sequences, I'd recommend that you change lines 8 and 11 to max_item.append(i) and insert a line or two before your return statement on line 12, and it would all look like this - def calc(seq): maximum = 0 max_item = [] for i in seq: product = (i[0]*100 + i[1]*10 + i[2]) * (i[3]*10 + i[4]) if product > maximum: maximum = product max_item.append(i) #append is a list method, by the way elif product == maximum: max_item.append(i) #This will remove [[5,6,7,8,9]] if len(max_item) == 1: max_item = max_item[0] return max_item, maximum Do you see how that works? max_item = [max_item] + [i] would give you the same multiplying brackets problem as max_item = [max_item, i], plus it's mentally harder to debug. Especially as i is traditionally used as an integer in 'for loops' since the days of BASIC... for i in range(10): print x[i] so having [i] sitting out there by itself is confusing. Good luck. Regards, Liam Clarke From norman at littletank.org Mon Oct 31 14:41:03 2005 From: norman at littletank.org (Norman Silverstone) Date: Mon, 31 Oct 2005 13:41:03 +0000 Subject: [Tutor] help with prime number program In-Reply-To: <4365FC11.4050303@tds.net> References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> <1130754506.27431.4.camel@localhost.localdomain> <4365FC11.4050303@tds.net> Message-ID: <1130766063.7726.3.camel@localhost.localdomain> On Mon, 2005-10-31 at 06:12 -0500, Kent Johnson wrote: > Norman Silverstone wrote: > > I am a beginner so, I hope what I give, makes sense. In it's simplest > > form what is wrong with :- > > > > n = input("Enter a number") > > if n % 2 != 0 and n % 3 != 0: > > print n, " Is a prime number" > > > This only gives the correct answer if n < 25. You can't test against a fixed list of divisors, there will always be a non-prime whose divisors are not in your list. Thank you for your comment which, if I understand you correctly, implies that prime numbers greater than 25 will not be recognised. Surely, that cannot be correct. However, if it is correct, could you please demonstrate what you mean for my education. Norman From gew75 at hotmail.com Mon Oct 31 14:49:02 2005 From: gew75 at hotmail.com (Glen Wheeler) Date: Tue, 1 Nov 2005 00:49:02 +1100 Subject: [Tutor] help with prime number program References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33><1130754506.27431.4.camel@localhost.localdomain><4365FC11.4050303@tds.net> <1130766063.7726.3.camel@localhost.localdomain> Message-ID: From: "Norman Silverstone" > On Mon, 2005-10-31 at 06:12 -0500, Kent Johnson wrote: >> Norman Silverstone wrote: >> > I am a beginner so, I hope what I give, makes sense. In it's simplest >> > form what is wrong with :- >> > >> > n = input("Enter a number") >> > if n % 2 != 0 and n % 3 != 0: >> > print n, " Is a prime number" >> > >> This only gives the correct answer if n < 25. You can't test against a >> fixed list of divisors, there will always be a non-prime whose divisors >> are not in your list. > > Thank you for your comment which, if I understand you correctly, implies > that prime numbers greater than 25 will not be recognised. Surely, that > cannot be correct. However, if it is correct, could you please > demonstrate what you mean for my education. > The problem is that composite numbers over 25 will be recognised. 11 is prime, but 55 is not. Your program will tell me that 55 is prime. Similarly with 34, etc. A reasonably easy to understand prime number generator, that also operates quickly, is the classic sieve of Eratosthenes (sp). Google is your friend :). HTH, Glen From kent37 at tds.net Mon Oct 31 14:54:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 31 Oct 2005 08:54:09 -0500 Subject: [Tutor] help with prime number program In-Reply-To: <1130766063.7726.3.camel@localhost.localdomain> References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> <1130754506.27431.4.camel@localhost.localdomain> <4365FC11.4050303@tds.net> <1130766063.7726.3.camel@localhost.localdomain> Message-ID: <43662201.4020105@tds.net> Norman Silverstone wrote: > On Mon, 2005-10-31 at 06:12 -0500, Kent Johnson wrote: > >>Norman Silverstone wrote: >> >>>I am a beginner so, I hope what I give, makes sense. In it's simplest >>>form what is wrong with :- >>> >>>n = input("Enter a number") >>>if n % 2 != 0 and n % 3 != 0: >>> print n, " Is a prime number" >>> >> >>This only gives the correct answer if n < 25. You can't test against a fixed list of divisors, there will always be a non-prime whose divisors are not in your list. > > > Thank you for your comment which, if I understand you correctly, implies > that prime numbers greater than 25 will not be recognised. Surely, that > cannot be correct. However, if it is correct, could you please > demonstrate what you mean for my education. More precisely, it will give an incorrect answer for any non-prime that is not divisible by 2 or 3, for example 25. >>> def test(n): ... if n % 2 != 0 and n % 3 != 0: ... print n, 'is prime' ... >>> test(2) >>> test(3) Hmm, not looking so good for 2 and 3 either... >>> test(4) >>> test(5) 5 is prime >>> test(25) 25 is prime Not so sure about that one either! Kent -- http://www.kentsjohnson.com From norman at littletank.org Mon Oct 31 15:04:06 2005 From: norman at littletank.org (Norman Silverstone) Date: Mon, 31 Oct 2005 14:04:06 +0000 Subject: [Tutor] help with prime number program In-Reply-To: <43662201.4020105@tds.net> References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> <1130754506.27431.4.camel@localhost.localdomain> <4365FC11.4050303@tds.net> <1130766063.7726.3.camel@localhost.localdomain> <43662201.4020105@tds.net> Message-ID: <1130767446.7726.7.camel@localhost.localdomain> > > Thank you for your comment which, if I understand you correctly, implies > > that prime numbers greater than 25 will not be recognised. Surely, that > > cannot be correct. However, if it is correct, could you please > > demonstrate what you mean for my education. > > More precisely, it will give an incorrect answer for any non-prime that is not divisible by 2 or 3, for example 25. > > >>> def test(n): > ... if n % 2 != 0 and n % 3 != 0: > ... print n, 'is prime' > ... > >>> test(2) > >>> test(3) > > Hmm, not looking so good for 2 and 3 either... > >>> test(4) > >>> test(5) > 5 is prime > >>> test(25) > 25 is prime > > Not so sure about that one either! How right you and Glen are and I am not very bright!! I must think again and thanks. Norman From ARoberts at ambac.com Mon Oct 31 15:58:33 2005 From: ARoberts at ambac.com (Roberts, Alice) Date: Mon, 31 Oct 2005 09:58:33 -0500 Subject: [Tutor] (no subject) Message-ID: <30CB82E83CB76D4584C5D7CEE3A4013E07E9403B@THEARCHITECT.ambac.abklan.net> Good morning, I'm migrating from DOS scripting to Python, and need a little help. I got this sample from a Google search that brought me to effbot.org, http://effbot.org/librarybook/ftplib.htm. Also, I plugged in all my variables when I tested, but replaced with generics for this email. ie) ftp.website.com . Thank you, Alice Roberts Ambac Assurance Corp. from ftplib import FTP import sys def upload(ftp, file): ftp.storlines("STOR " + file, open(file)) ftp = ftplib.FTP('ftp.website.com') # connect to host, default port ftp.login('user', 'pwd') # user, passwd ftp.set_debuglevel(1) ftp.cwd('/temp') ftp.delete('fname.txt') upload(ftp, "fname.txt") ftp.quit() ftp.close() When I ran in debugger, calling the FTP library invokes a no SOCKS module error that the ftplib seems to be trying to access. >>> --Call-- >>> Unhandled exception while debugging... Traceback (most recent call last): File "C:\Python24\lib\ftplib.py", line 42, in ? import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket ImportError: No module named SOCKS >>> --Call-- >>> Unhandled exception while debugging... Traceback (most recent call last): File "C:\Python24\lib\socket.py", line 50, in ? import _ssl ImportError: No module named _ssl >>> --Call-- >>> Unhandled exception while debugging... Traceback (most recent call last): File "C:\Python24\lib\os.py", line 36, in _get_exports_list return list(module.__all__) AttributeError: 'module' object has no attribute '__all__' [Dbg]>>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 305, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=1) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 595, in run exec cmd in globals, locals File "c:\temp\ftp_get_hub.py", line 13, in ? ftp = ftplib.FTP("ftp.website.com") # connect to host, default port NameError: name 'ftplib' is not defined [Dbg]>>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 305, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=1) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 595, in run exec cmd in globals, locals File "c:\temp\ftp_put_hub.py", line 3, in ? import FTP ImportError: No module named FTP [Dbg]>>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 305, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=1) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 595, in run exec cmd in globals, locals File "c:\temp\ftp_put_hub.py", line 9, in ? ftp = ftplib.FTP('ftp.website.com') # connect to host, default port NameError: name 'ftplib' is not defined [Dbg]>>> -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051031/c0546fbb/attachment-0001.htm From grouch at gmail.com Mon Oct 31 17:11:02 2005 From: grouch at gmail.com (Andrew P) Date: Mon, 31 Oct 2005 10:11:02 -0600 Subject: [Tutor] Newbie Question - Python vs Perl In-Reply-To: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> References: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> Message-ID: If you are interested in learning another tool, please, start with Python. If you are interested in scripting UNIX, Perl is a fine choice. There prevalence matters, and quite a bit. But sys admins are usually very Perl-centric, and in my experience monolingual, and a bit of an insular community :) Python is more than the equal of Perl by any measure. Including system administration. But moving beyond that is also a lovely language for building applications, and everything from lightweight CGI scripts to using hefty web frameworks, of which there are plenty to choose from. Perl is a language of exceptions to the rules. Python tries very hard to be consistent, which makes it much easier to learn, and much easier to use, and much, much easier to apply the concepts you have learned to other languages. Including Perl, as a second or third language. Perl can be coerced into big jobs, but it's not very pleasant. The best you can hope to keep in your head at once is your own set of idioms, which will -not- match anybody elses, and will likely change from week to week on you anyway. And really when people tell you they can't read what they wrote the day before when they come back to it, they aren't lying! Having said that, I love Perl, because it -is- quirky and sprawling and lovable. It's pretty much the worst case scenario of everything-and-the-kitchen-sink, and really not so bad for all that, and definitely more fun for it. So if that appeals, then you'll have fun too. But Python tends to be compared to general purpose languages like Java and C++ more often. OOP heavyweights of the world. Actually, let me find that quote by Bruce Eckel, who wrote the (very) popular "Thinking in Java" and "Thinking in C++" books. Here it is: "I believe it was definitely worth moving from C to C++, and from C++ to Java. So there was progress there. For something as advanced as Python is over those languages -- and as different -- there will be some hesitation." And: "When you have the experience of really being able to be as productive as possible, then you start to get pissed off at other languages. You think, 'Gee, I've been wasting my time with these other languages.'" That second quote applies to many "language vs language" comparisons, obviously. But it's food for thought. Oh, and never underestimate the power of the interactive interpreter! Don't do it! Ever! Take care, Andrew On 10/30/05, Scott Clausen wrote: > As a newbie to Python I'd like to know if someone can tell me some > strengths and weaknesses of this language. The reason I'm asking is a > friend told me I should learn Perl over Python as it's more > prevalent. I'm going to be using it on a Mac. > > I'd appreciate hearing any views on this topic. My own view is that > it's always good to learn new things as you then have more tools to > use in your daily programming. > > Thanks in advance. > > Scott > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From grouch at gmail.com Mon Oct 31 17:28:40 2005 From: grouch at gmail.com (Andrew P) Date: Mon, 31 Oct 2005 10:28:40 -0600 Subject: [Tutor] (no subject) In-Reply-To: <30CB82E83CB76D4584C5D7CEE3A4013E07E9403B@THEARCHITECT.ambac.abklan.net> References: <30CB82E83CB76D4584C5D7CEE3A4013E07E9403B@THEARCHITECT.ambac.abklan.net> Message-ID: Before you hit the debugger, it might be a good idea to just run the script normally, either at the command line, or inside IDLE/Pythonwin. Doing so will spit out: Traceback (most recent call last): File "", line 1, in ? NameError: name 'ftplib' is not defined Because you imported with: from ftplib import FTP" you don't need to prepend the module name before you call FTP. If you do "import ftplib" instead, then it will work. Conversely, if you call with just "FTP("ftp.website.com") it will also work. It's really a personal choice which you do, but the second choice is safer, as it has no chance of polluting your module's namespace if you accidentally call something FTP. Also, I noticed when pasting into IDLE that you have mismatched quotes: ftp.login('user', 'pwd') # user, passwd Using IDLE/Pythonwin will catch problems like that. Good luck, Andrew On 10/31/05, Roberts, Alice wrote: > > > > Good morning, > > > > I'm migrating from DOS scripting to Python, and need a little help. I got > this sample from a Google search that brought me to effbot.org, > http://effbot.org/librarybook/ftplib.htm. Also, I plugged > in all my variables when I tested, but replaced with generics for this > email. ie) ftp.website.com. > > > > Thank you, > > > > Alice Roberts > > Ambac Assurance Corp. > > > > from ftplib import FTP > > import sys > > > > def upload(ftp, file): > > ftp.storlines("STOR " + file, open(file)) > > > > ftp = ftplib.FTP('ftp.website.com') # connect to host, default port > > ftp.login('user', 'pwd') # user, passwd > > ftp.set_debuglevel(1) > > ftp.cwd('/temp') > > ftp.delete('fname.txt') > > > > upload(ftp, "fname.txt") > > > > ftp.quit() > > ftp.close() > > > > When I ran in debugger, calling the FTP library invokes a no SOCKS module > error that the ftplib seems to be trying to access. > > > > >>> --Call-- > > >>> Unhandled exception while debugging... > > Traceback (most recent call last): > > File "C:\Python24\lib\ftplib.py", line 42, in ? > > import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket > > ImportError: No module named SOCKS > > >>> --Call-- > > >>> Unhandled exception while debugging... > > Traceback (most recent call last): > > File "C:\Python24\lib\socket.py", line 50, in ? > > import _ssl > > ImportError: No module named _ssl > > >>> --Call-- > > >>> Unhandled exception while debugging... > > Traceback (most recent call last): > > File "C:\Python24\lib\os.py", line 36, in _get_exports_list > > return list(module.__all__) > > AttributeError: 'module' object has no attribute '__all__' > > [Dbg]>>> Traceback (most recent call last): > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 305, in RunScript > > debugger.run(codeObject, __main__.__dict__, start_stepping=1) > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", > line 60, in run > > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", > line 595, in run > > exec cmd in globals, locals > > File "c:\temp\ftp_get_hub.py", line 13, in ? > > ftp = ftplib.FTP("ftp.website.com") # connect to host, default port > > NameError: name 'ftplib' is not defined > > [Dbg]>>> Traceback (most recent call last): > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 305, in RunScript > > debugger.run(codeObject, __main__.__dict__, start_stepping=1) > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", > line 60, in run > > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", > line 595, in run > > exec cmd in globals, locals > > File "c:\temp\ftp_put_hub.py", line 3, in ? > > import FTP > > ImportError: No module named FTP > > [Dbg]>>> Traceback (most recent call last): > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 305, in RunScript > > debugger.run(codeObject, __main__.__dict__, start_stepping=1) > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", > line 60, in run > > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", > line 595, in run > > exec cmd in globals, locals > > File "c:\temp\ftp_put_hub.py", line 9, in ? > > ftp = ftplib.FTP('ftp.website.com') # connect to host, default port > > NameError: name 'ftplib' is not defined > > [Dbg]>>> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at freenet.co.uk Mon Oct 31 18:15:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 31 Oct 2005 17:15:53 -0000 Subject: [Tutor] help with prime number program References: <1370.172.134.210.33.1130690262.squirrel@172.134.210.33> <1130754506.27431.4.camel@localhost.localdomain> Message-ID: <00f801c5de3e$bfacf910$0a01a8c0@xp> > n = input("Enter a number") > if n % 2 != 0 and n % 3 != 0: > print n, " Is a prime number" > > Comments please. According to this 25 is a prime number.... Alan G. From alan.gauld at freenet.co.uk Mon Oct 31 18:25:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 31 Oct 2005 17:25:32 -0000 Subject: [Tutor] (no subject) References: <30CB82E83CB76D4584C5D7CEE3A4013E07E9403B@THEARCHITECT.ambac.abklan.net> Message-ID: <011b01c5de40$19489eb0$0a01a8c0@xp> > When I ran in debugger, calling the FTP library invokes a no SOCKS > module error that the ftplib seems to be trying to access. Can you tell us which debugger you are using? I don't recognise what's going on here. >>> --Call-- This looks like the Python interactive prompt, but whats the --Call-- thing? Its not valid Python syntax and yet the messages below suggest that it is being processed in a semi-sane way. [Dbg]>>> Traceback (most recent call last): And I don;t recognise the square brackets [Dbg] either. Which debugger is it? Finally given the number of import errors I'd suggest there is a path problem somewhere. But without knowing which OS, which IDE and where/how you are executing this I can only guess. Alan G. From ARoberts at ambac.com Mon Oct 31 19:16:21 2005 From: ARoberts at ambac.com (Roberts, Alice) Date: Mon, 31 Oct 2005 13:16:21 -0500 Subject: [Tutor] (no subject) Message-ID: <30CB82E83CB76D4584C5D7CEE3A4013E04ED4584@THEARCHITECT.ambac.abklan.net> Hi, My os.system() isn't waiting for exit status, jumping right into next os.system(). import os DIR = 'v:/pam/batch/ambac/' CMD1 = DIR + 'Prices_Prep.cmd' CMD2 = DIR + 'positions.cmd' CMD3 = DIR + 'ftp_hub.cmd' CMD4 = DIR + 'import_prices.cmd' try: os.system(CMD1) except IOError, (errno, strerror): print " E/S(%s): %s" % (errno, strerror) #result=os.system # print result try: os.system(CMD2) except IOError, (errno, strerror): print " E/S(%s): %s" % (errno, strerror) #result=os.system # print result try: os.system(CMD3) except IOError, (errno, strerror): print " E/S(%s): %s" % (errno, strerror) #result=os.system # print result try: os.system(CMD4) except IOError, (errno, strerror): print " E/S(%s): %s" % (errno, strerror) #result=os.system # print result Any thoughts? Thanks, Alice Roberts Ambac Assurance Corp. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051031/d6a42147/attachment-0001.htm From grouch at gmail.com Mon Oct 31 19:40:06 2005 From: grouch at gmail.com (Andrew P) Date: Mon, 31 Oct 2005 12:40:06 -0600 Subject: [Tutor] (no subject) In-Reply-To: <011b01c5de40$19489eb0$0a01a8c0@xp> References: <30CB82E83CB76D4584C5D7CEE3A4013E07E9403B@THEARCHITECT.ambac.abklan.net> <011b01c5de40$19489eb0$0a01a8c0@xp> Message-ID: If I'm not mistaken, that's the Pythonwin debugger spitting messages to the interactive prompt. I just used it to step through your your games framework example :) Being the first time I'd used any Python debugger, it didn't occur to me that the look of it was non-standard. I actually got the same exceptions popping up running his code, even after fixing the problems I pointed out. I figured the debugger shows caught exceptions. I noticed it before and hadn't given it much thought, but looking at his code, there are try/except pairs in all the spots the debugger highlighted: from ftplib: try: import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket from socket import getfqdn; socket.getfqdn = getfqdn; del getfqdn except ImportError: import socket from os.py: def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_'] and socket.py: try: import _ssl from _ssl import * _have_ssl = True except ImportError: pass Thats why I suspect that this: File "c:\temp\ftp_put_hub.py", line 9, in ? ftp = ftplib.FTP('ftp.website.com') # connect to host, default port Was the only real error being thrown. On 10/31/05, Alan Gauld wrote: > > When I ran in debugger, calling the FTP library invokes a no SOCKS > > module error that the ftplib seems to be trying to access. > > Can you tell us which debugger you are using? I don't recognise what's > going on here. > > >>> --Call-- > > This looks like the Python interactive prompt, > but whats the --Call-- thing? > > Its not valid Python syntax and yet the messages below suggest > that it is being processed in a semi-sane way. > > [Dbg]>>> Traceback (most recent call last): > > And I don;t recognise the square brackets [Dbg] either. > Which debugger is it? > > Finally given the number of import errors I'd suggest there is a path > problem somewhere. But without knowing which OS, which IDE > and where/how you are executing this I can only guess. > > Alan G. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Mon Oct 31 19:56:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 31 Oct 2005 18:56:53 -0000 Subject: [Tutor] (no subject) References: <30CB82E83CB76D4584C5D7CEE3A4013E04ED4584@THEARCHITECT.ambac.abklan.net> Message-ID: <016901c5de4c$dc0a9910$0a01a8c0@xp> > My os.system() isn't waiting for exit status, jumping right into next > os.system(). Are you sure it isn't just running very quickly? The time it takes to display stuff on a screen is significant - all those phosphorescent pixels :-) os.system doesn't have to wait for that so it tends to run programs much faster than normal... Just a thought, Alan G. From ARoberts at ambac.com Mon Oct 31 20:02:20 2005 From: ARoberts at ambac.com (Roberts, Alice) Date: Mon, 31 Oct 2005 14:02:20 -0500 Subject: [Tutor] (no subject) Message-ID: <30CB82E83CB76D4584C5D7CEE3A4013E04ED4586@THEARCHITECT.ambac.abklan.net> Well, I'm looking into os.spawnl with os.P_WAIT, now. Thanks, -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: Monday, October 31, 2005 1:57 PM To: Roberts, Alice; tutor at python.org Subject: Re: [Tutor] (no subject) > My os.system() isn't waiting for exit status, jumping right into next > os.system(). Are you sure it isn't just running very quickly? The time it takes to display stuff on a screen is significant - all those phosphorescent pixels :-) os.system doesn't have to wait for that so it tends to run programs much faster than normal... Just a thought, Alan G. From tim at johnsons-web.com Mon Oct 31 21:44:48 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 31 Oct 2005 11:44:48 -0900 Subject: [Tutor] Tainted characters and CGI Message-ID: <20051031204448.GT1791@johnsons-web.com> Hello: I need to tighten my handling of CGI transmissions. I particular, I need to develop a strategy of safely dealing with "tainted" characters. I'd appreciate any pointers to documentation and resources regarding this matter, as well as comments and caveats. At this time and for the forseeable future, we will be running our CGI services on *nix systems. Thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Mon Oct 31 22:31:08 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 31 Oct 2005 12:31:08 -0900 Subject: [Tutor] Newbie Question - Python vs Perl In-Reply-To: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> References: <06D7D935-DB02-411A-BD86-47712553BC8D@mac.com> Message-ID: <20051031213108.GU1791@johnsons-web.com> * Scott Clausen [051030 16:30]: > As a newbie to Python I'd like to know if someone can tell me some > strengths and weaknesses of this language. The reason I'm asking is a > friend told me I should learn Perl over Python as it's more > prevalent. I'm going to be using it on a Mac. Prevalent? So what? Forget Perl entirely. Learn python and rebol (www.rebol.com). At the same time. That's how we trained programmers here. Rebol arguably exceeds both python and perl in terms of sheer productivity on a line for line basis, but has a very small user base and fewer modules. But the bottom line is to be multi-lingual. Here's a pretty standard coding day for me. 1)Write rebol code which parses html and generates python, perl and javascript code for deployment. 2)Write python code for the deployment (front end), database interaction, server-side data validation etc. 3)Write Javascript for client-side data validation, dynamic html etc. 4)Write elisp code to enhance productivity of my Emacs and Xemacs Editors. 5)Use vim/gvim for system wide analysis and editing. I believe the rebol is pretty straight-forward and easy to install for the mac. I use Python for most of the services used directly by customers on larger projects 'cuz it scales better (for me). and python teaches me good coding practices. IOWS, coding in python makes me a better rebol programmer too. The bottom line is don't get stuck on one programming language. I've seen new programmers go thru a fast learning curve, pick up something faster than an ol' fart like me would, but get so settled in one programming niche or another that they can't or won't change. Not good! I think python is the best way to learn *good* programming. MTCW tim > I'd appreciate hearing any views on this topic. My own view is that > it's always good to learn new things as you then have more tools to > use in your daily programming. > > Thanks in advance. > > Scott > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From xecronix at yahoo.com Mon Oct 31 22:33:05 2005 From: xecronix at yahoo.com (Ron Weidner) Date: Mon, 31 Oct 2005 13:33:05 -0800 (PST) Subject: [Tutor] Tainted characters and CGI In-Reply-To: <20051031204448.GT1791@johnsons-web.com> Message-ID: <20051031213305.53112.qmail@web60622.mail.yahoo.com> --- Tim Johnson wrote: > Hello: > I need to tighten my handling of CGI transmissions. > I particular, I need to develop a strategy of safely > dealing with "tainted" characters. Ahh... tainted characters. If by "tainted" you mean not UTF-8, there is a c tool called "iconv" that fixes "tainted" characters. I believe Python has a wrapper, but I didn't check before sending this e-mail. Good luck and please write back if you implement a working solution. -- Ronald Weidner http://www.techport80.com PHP Software developer for hire. __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From zmanji at gmail.com Mon Oct 31 23:36:35 2005 From: zmanji at gmail.com (Zameer Manji) Date: Mon, 31 Oct 2005 17:36:35 -0500 Subject: [Tutor] while/if/elif/else loops Message-ID: <43669C73.7030804@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 I'm new to programming and python. I've have recently been experimenting with while/if/elif/else loops and I've created a simple number guessing game. Now I want to create a coin tossing game, but I don't know how to structure it in python. The code I already have (but it's not working) is below. #Coin Toss Game print "This game will simulate 100 coin tosses and then tell you the number of head's and tails" import random tosses = 0 heads = 0 tails = 0 while tosses = 100<0: coin = randrange(1) tosses +=1 if coin == 0: heads +=1 print "Heads" else: tails +=1 Print "Tails" -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (MingW32) iQEVAwUBQ2accw759sZQuQ1BAQqoyQgAsmVhRidMC1/WpQms6fChX+z62DWSpmRW qiY9F7bZAYZusyNsHHDUpuTAYdI0LXxgLVmYBKDz3tKhVCbEZTn9FUwgw5A2thYy I5o82tWXZnIpgmFIN2AysAj2dCI4mSfi/IJjE5JvG+IFELWigMb9Pf6tap4HiB71 IBayql8MN1XrA2zv8fXQs35zVwxnBUSvAHZuUBLi4hDcPxY/d71X/JHqfqpf3svS ClzUlYqLhXld+39/aiRFKOXHyVCnfsEUcAXB45r110Q3K+7KegwgX4Js8qL5dA66 d74HlLMb6Cp6G5AlNdQoKDin8jlMloxeQpb60hS+HmnBwkEFukyNHA== =QMuB -----END PGP SIGNATURE----- From tim at johnsons-web.com Mon Oct 31 23:57:10 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 31 Oct 2005 13:57:10 -0900 Subject: [Tutor] Tainted characters and CGI In-Reply-To: <20051031213305.53112.qmail@web60622.mail.yahoo.com> References: <20051031204448.GT1791@johnsons-web.com> <20051031213305.53112.qmail@web60622.mail.yahoo.com> Message-ID: <20051031225710.GV1791@johnsons-web.com> * Ron Weidner [051031 12:38]: > > > --- Tim Johnson wrote: > > > Hello: > > I need to tighten my handling of CGI transmissions. > > I particular, I need to develop a strategy of safely > > dealing with "tainted" characters. > > Ahh... tainted characters. If by "tainted" you mean > not UTF-8, there is a c tool called "iconv" that fixes > "tainted" characters. I believe Python has a wrapper, > but I didn't check before sending this e-mail. Good > luck and please write back if you implement a working > solution. Now that's serendipity for ya. I wasn't thinking about none-UTF-8 characters, but that's a good thread to investigate also. Actually, google gives me a thread http://mail.python.org/pipermail/tutor/2005-August/040619.html regarding handling of characters passed from a CGI post that could be exploited by malicious hacking. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com