From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 13:20:58 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 13:24:38 2003 Subject: [Tutor] python mailing list In-Reply-To: <00d401c3b6ea$9cca6c20$6400a8c0@a0> Message-ID: On Sat, 29 Nov 2003, Az wrote: > python mailing list Hi Az, Yes, you've reached the right number. *grin* Do you have any questions about learning Python? This mailing list is dedicated to help folks learn how to program Python. If you have any questions, please feel free to bring them up. From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 13:34:20 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 13:35:44 2003 Subject: [Tutor] mouse_buttons() In-Reply-To: Message-ID: On Sun, 30 Nov 2003, Leung Cris wrote: > How do I use that function? It's from Livewires . It returns three > values, the middle , right, and left button. Depending on whether it is > clicked, it will return a 0 or 1. But how do I get it so that when I > click on the screen, it will stop? I've triedthis: > > while 1: > mouse_buttons() > if mouse_buttons() == 1 > break > > > but... it doens't work Hi Leung, What does mouse_buttons() give back to us? Is it a number, or a list, or...? I see that you're trying to guess this by seeing if it's an integer. And this is something that, with enough flailing, can be guessed with time. But we can accelerate the process. *grin* Take a closer look at: http://www.livewires.org.uk/python/pdf/G-graphics.pdf According to the documentation, mouse_buttons() is a function that returns a dictionary. So you'll need to treat the return value of mouse_buttons() as a dictionary with keys 'left', 'middle', and 'right'. If you have more questions, please feel free to ask. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 16:16:51 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 16:17:00 2003 Subject: [Tutor] program doesnt work In-Reply-To: <20031127192823.40767.qmail@web60210.mail.yahoo.com> Message-ID: On Thu, 27 Nov 2003, Udz wrote: > well, after i fixed my little mistake (thanx G.Rodriguez, I made a > stupid mistake.), i ran py2exe, and it appeared to work right, it built > the dir that it was supposed to, and compiled the .dll and .exe file. > the only problem is, the program doesnt work. The window just kinda pops > up, then disappears without doing anything. Hi Udz, Just checking up on this: what happens if you add the line: ### raw_input("Program finished: press Enter to continue...") ### at the very end of your program? I suspect that Windows is closing your program down automatically. t's a common issue for console-based programs on Windows, that your program may actually be running fine, but may simply be finishing too quickly for you to see it. Many programs try to work around this window-closing feature by forcing a prompt so that the user can see things. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 16:21:50 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 16:22:04 2003 Subject: [Tutor] Accessing the mailing list archive In-Reply-To: Message-ID: > P.S., I save all the answers I get, and you couldn't imagine (or you > probably do, but I just said so, cause it sounds nice), how helpfull is > having you answers saved somewhere, and when something is not so clear, > just open those files, and see what was doing wrong ... Hi Tadey, By the way, there's also an archive of the whole mailing list: http://mail.python.org/pipermail/tutor/ so if you ever want to browse some old threads, you can always turn to that link. Everything is saved to the archive, which is pretty useful. There's also a rudimentary list searcher here: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor and sooner or later, someone is bound to write a nicer search interface to the archive. From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 16:47:50 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 16:48:00 2003 Subject: [Tutor] special character ( =?ISO-8859-1?Q?=F1?= ) In-Reply-To: <20031129025430.1ad0605a.klappnase@freenet.de> Message-ID: On Sat, 29 Nov 2003, Michael Lange wrote: > On Fri, 28 Nov 2003 13:56:17 -0500 (EST) > clickron@webtv.net (Ron A) wrote: > > > I have python 2.2.2. Is there an easy way to type =F1 (n with tilde) o= r > > other special characters?. > > > I am afraid that I'm not an encoding expert, but I guess you have the sam= e problems > as I have with german special characters. > In this case it depends on *where* you want to print it: > In IDLE(python 2.2.3): > > >>> print '=E4' > UnicodeError: ASCII encoding error: ordinal not in range(128) Hello! It sounds like you're trying to use ISO-8859-1 encoding to display accented characters on your system. If your terminal supports it, then you can use: ftp://unicode.org/Public/MAPPINGS/ISO8859/8859-1.TXT to find out the right hexadecimal constants. For example, the tilde 'n' maps to the entry: """ 0xF1=090x00F1=09#=09LATIN SMALL LETTER N WITH TILDE """ So if your terminal display natively supports ISO-8859-1, then something like: ### print '\xf1' ### should do the trick. However, if you're using a terminal that natively supports a different encoding system, then you need to do something slightly different. Apple's Terminal application, for example, natively uses UTF8. So you might need to do something like: ### print '\xf1'.decode('iso8859-1').encode('utf8') ### to see a tilde 'n' on MacOSX's Terminal. > If you just suffer from IDLE's limitations try idlefork : > > < http://idlefork.sourceforge.net > > > It's IDLE with a few extra features; as far as I know it replaces the > "original" IDLE since python 2.3 . I believe IDLE supports Unicode now, so try the second snippet example and see if you get that tilde 'n' from there. Good luck to you! From tim at johnsons-web.com Mon Dec 1 16:00:30 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Dec 1 16:59:46 2003 Subject: [Tutor] class method: dynamic overload Message-ID: <20031201210030.GN14980@johnsons-web.com> Hi All: Is it possible in python to replace (overload) an existing class method with a new one of the same name but with different functionality? I would welcome pointers to docs and keywords. - this is just R & D, not mission critical. TIA tim -- Tim Johnson http://www.alaska-internet-solutions.com From krazie_mu_boi at hotmail.com Mon Dec 1 17:05:31 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Dec 1 17:05:37 2003 Subject: FW: Re: [Tutor] mouse_buttons() Message-ID: >From: Danny Yoo >To: Leung Cris >CC: tutor@python.org >Subject: Re: [Tutor] mouse_buttons() >Date: Mon, 1 Dec 2003 10:34:20 -0800 (PST) > > > >On Sun, 30 Nov 2003, Leung Cris wrote: > > > How do I use that function? It's from Livewires . It returns three > > values, the middle , right, and left button. Depending on whether it is > > clicked, it will return a 0 or 1. But how do I get it so that when I > > click on the screen, it will stop? I've triedthis: > > > > while 1: > > mouse_buttons() > > if mouse_buttons() == 1 > > break > > > > > > but... it doens't work > > >Hi Leung, > > >What does mouse_buttons() give back to us? Is it a number, or a list, >or...? > > >I see that you're trying to guess this by seeing if it's an integer. And >this is something that, with enough flailing, can be guessed with time. >But we can accelerate the process. *grin* > > >Take a closer look at: > > http://www.livewires.org.uk/python/pdf/G-graphics.pdf > > >According to the documentation, mouse_buttons() is a function that returns >a dictionary. So you'll need to treat the return value of mouse_buttons() >as a dictionary with keys 'left', 'middle', and 'right'. > > > >If you have more questions, please feel free to ask. Good luck to you! > I'm not really familliar with "dictionary", can someone tell me how to access one? _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 17:20:47 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 17:21:01 2003 Subject: FW: Re: [Tutor] mouse_buttons() In-Reply-To: Message-ID: > >Take a closer look at: > > > > http://www.livewires.org.uk/python/pdf/G-graphics.pdf > > > > > >According to the documentation, mouse_buttons() is a function that returns > >a dictionary. So you'll need to treat the return value of mouse_buttons() > >as a dictionary with keys 'left', 'middle', and 'right'. > > > > > > > >If you have more questions, please feel free to ask. Good luck to you! > > > > > I'm not really familliar with "dictionary", can someone tell me how to > access one? Hi Leung, Livewires has a good explanation of dictionaries: http://www.livewires.org.uk/python/pdf/D-dicts.pdf By the way, when you get the chance, take a quick glance through the other reference sheets: http://www.livewires.org.uk/python/pdfsheets.html and just note the topic names. You don't have to study each sheet closely, but just be aware of what subjects they talk about. That way, when you need more details on something, can find the right sheet to get more information. If you have more questions, please feel free to ask. Good luck to you! From krazie_mu_boi at hotmail.com Mon Dec 1 18:01:24 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Dec 1 18:01:29 2003 Subject: FW: Re: FW: Re: [Tutor] mouse_buttons() Message-ID: >From: Danny Yoo >To: Leung Cris >CC: tutor@python.org >Subject: Re: FW: Re: [Tutor] mouse_buttons() >Date: Mon, 1 Dec 2003 14:20:47 -0800 (PST) > > > > > >Take a closer look at: > > > > > > http://www.livewires.org.uk/python/pdf/G-graphics.pdf > > > > > > > > >According to the documentation, mouse_buttons() is a function that returns > > >a dictionary. So you'll need to treat the return value of mouse_buttons() > > >as a dictionary with keys 'left', 'middle', and 'right'. > > > > > > > > > > > >If you have more questions, please feel free to ask. Good luck to you! > > > > > > > > > I'm not really familliar with "dictionary", can someone tell me how to > > access one? > > >Hi Leung, > > >Livewires has a good explanation of dictionaries: > > http://www.livewires.org.uk/python/pdf/D-dicts.pdf > > > >By the way, when you get the chance, take a quick glance through the other >reference sheets: > > http://www.livewires.org.uk/python/pdfsheets.html > >and just note the topic names. You don't have to study each sheet >closely, but just be aware of what subjects they talk about. That way, >when you need more details on something, can find the right sheet to get >more information. > > >If you have more questions, please feel free to ask. Good luck to you! > I think I got it, thx! ^^ _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From krazie_mu_boi at hotmail.com Mon Dec 1 18:06:01 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Dec 1 18:06:07 2003 Subject: [Tutor] A range of numbers Message-ID: I was wondering if it is possible to set a variable or something to a RANGE of numbers. For instance , I want to have it so that when I mouse clicks in a certain region( let say, from (100,100) to (200,200)), it prints out "You Clicked!" . I'm doing this with Livewires right now. Of course, it would take forever if i try to write: if mouse_position() == (100,100) or (100,101) or (100,102) .............................. and mouse_buttons()['left'] == 1: do something that won't work... so , can anyone help? _________________________________________________________________ MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : http://photos.msn.com.hk/support/worldwide.aspx From tim at johnsons-web.com Mon Dec 1 18:21:50 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Dec 1 18:14:24 2003 Subject: [Tutor] class method: dynamic overload/++ In-Reply-To: <20031201210030.GN14980@johnsons-web.com> References: <20031201210030.GN14980@johnsons-web.com> Message-ID: <20031201232150.GQ14980@johnsons-web.com> * Tim Johnson [031201 13:25]: > Hi All: > Is it possible in python to replace (overload) > an existing class method with a new one of the same > name but with different functionality? Upon review, I could have made myself more clear. I should have asked: Is it possible to overload an existing method with another at runtime? Hopefully that's clearer ----------------------- I would welcome pointers to docs and keywords. - this is just R & D, not mission critical. TIA tim -- Tim Johnson http://www.alaska-internet-solutions.com From thinkuknowme2007 at yahoo.com Mon Dec 1 18:21:42 2003 From: thinkuknowme2007 at yahoo.com (Udz) Date: Mon Dec 1 18:21:47 2003 Subject: [Tutor] program doesnt work In-Reply-To: Message-ID: <20031201232142.96081.qmail@web60208.mail.yahoo.com> >Just checking up on this: what happens if you add the line: >### >raw_input("Program finished: press Enter to continue...") >### > > >at the very end of your program? I suspect that Windows is closing your >program down automatically. t's a common issue for console-based programs >on Windows, that your program may actually be running fine, but may simply >be finishing too quickly for you to see it. I hardly doubt that is the case, since my program requires input from the user at various points throughout execution, but i'll try it anyways. thanks!! Udz --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031201/e8218773/attachment.html From desiderata at softhome.net Tue Dec 2 01:27:10 2003 From: desiderata at softhome.net (desiderata@softhome.net) Date: Mon Dec 1 18:25:03 2003 Subject: [Tutor] Attribute error? Message-ID: <20031202062710.GA1973@Valhalla> Hi, This is my first time using python and I've got a problem appending to a file... here's my short code: ----- #!/usr/bin/python uid = raw_input("Please enter your userID: ") gid = raw_input("Please enter your gID: ") f = open("file.txt","a") f.append("\nYour userID is " + uid + " And your gID is " + gid) ----- but when I input the values while executing it, it gives me an error: ----- Traceback (most recent call last): File "./test2.py", line 6, in ? f.append("\nYour userID is " + uid + " And your gID is " + gid) AttributeError: 'file' object has no attribute 'append' ----- but I already used "a" for it to append.. I don't get it =( regards, Elijah From glingl at aon.at Mon Dec 1 18:28:27 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Dec 1 18:27:29 2003 Subject: [Tutor] class method: dynamic overload/++ In-Reply-To: <20031201232150.GQ14980@johnsons-web.com> References: <20031201210030.GN14980@johnsons-web.com> <20031201232150.GQ14980@johnsons-web.com> Message-ID: <3FCBCE9B.1070806@aon.at> Tim Johnson schrieb: >* Tim Johnson [031201 13:25]: > > >>Hi All: >> Is it possible in python to replace (overload) >>an existing class method with a new one of the same >>name but with different functionality? >> >> > > Upon review, I could have made myself more clear. > > I should have asked: > Is it possible to overload an existing method > with another at runtime? > > Hi Tim! I'm not sure if it's this, what you want to know. I just played around a little: >>> class A: def __init__(self): self.u = 1 def p(self): print self.u >>> x = A() >>> x.p() 1 >>> def q(self): print 2*self.u >>> A.p = q >>> x.p() 2 >>> Even if it doesn't help it's still funny Gregor > Hopefully that's clearer > ----------------------- > I would welcome pointers to docs and keywords. > - this is just R & D, not mission critical. > > TIA > tim > > > From glingl at aon.at Mon Dec 1 18:39:06 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Dec 1 18:38:06 2003 Subject: [Tutor] Attribute error? In-Reply-To: <20031202062710.GA1973@Valhalla> References: <20031202062710.GA1973@Valhalla> Message-ID: <3FCBD11A.3040005@aon.at> desiderata@softhome.net schrieb: >Hi, > >This is my first time using python and I've got a problem appending to a >file... here's my short code: > >----- >#!/usr/bin/python > >uid = raw_input("Please enter your userID: ") >gid = raw_input("Please enter your gID: ") >f = open("file.txt","a") > Hi desiderata ;-) ! The use of "a" in open() opens the file for appending text. Writing to the file still goes with write, as write is a method of file objects. f.write("\nYour userID is " + uid + " And your gID is " + gid) You may read about methods of file-objects here: http://www.python.org/doc/current/lib/bltin-file-objects.html HTH, Gregor >f.append("\nYour userID is " + uid + " And your gID is " + gid) >----- > >but when I input the values while executing it, it gives me an error: > >----- >Traceback (most recent call last): > File "./test2.py", line 6, in ? > f.append("\nYour userID is " + uid + " And your gID is " + gid) > AttributeError: 'file' object has no attribute 'append' >----- > >but I already used "a" for it to append.. I don't get it =( > > >regards, >Elijah > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From glingl at aon.at Mon Dec 1 18:53:35 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Dec 1 18:52:36 2003 Subject: [Tutor] A range of numbers In-Reply-To: References: Message-ID: <3FCBD47F.8090100@aon.at> Hi Leung! There is a range function in Python: >>> range(5) [0, 1, 2, 3, 4] >>> range(5,10) [5, 6, 7, 8, 9] It outputs lists of integer values. play around with it to learn how it works. (Even to call range(10,20,2), i. e. with 3 arguments, is possible) On the other han you can check if some value is in a certain range with the in - Operator: >>> y = 4 >>> y in range(5) True # 1 in older Versions of Python >>> y in range(5,10) False # or 0 so if you first extract the coordinates of your mouse-position: >>> x,y = mouse_position() then you can easily check if y is in the desired range. HTH Gregor Leung Cris schrieb: > I was wondering if it is possible to set a variable or something to a > RANGE of numbers. For instance , I want to have it so that when I > mouse clicks in a certain region( let say, from (100,100) to > (200,200)), it prints out "You Clicked!" . I'm doing this with > Livewires right now. Of course, it would take forever if i try to write: > > if mouse_position() == (100,100) or (100,101) or (100,102) > .............................. > and mouse_buttons()['left'] == 1: > do something > > that won't work... so , can anyone help? > > _________________________________________________________________ > MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : > http://photos.msn.com.hk/support/worldwide.aspx > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From glingl at aon.at Mon Dec 1 18:54:29 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Dec 1 18:53:31 2003 Subject: [Tutor] A range of numbers In-Reply-To: References: Message-ID: <3FCBD4B5.8050901@aon.at> Leung Cris schrieb: > I was wondering if it is possible to set a variable or something to a > RANGE of numbers. For instance , I want to have it so that when I > mouse clicks in a certain region( let say, from (100,100) to > (200,200)), it prints out "You Clicked!" . I'm doing this with > Livewires right now. Of course, it would take forever if i try to write: > > if mouse_position() == (100,100) or (100,101) or (100,102) > .............................. > and mouse_buttons()['left'] == 1: > do something > > that won't work... so , can anyone help? > > _________________________________________________________________ > MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : > http://photos.msn.com.hk/support/worldwide.aspx > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From krazie_mu_boi at hotmail.com Mon Dec 1 18:54:53 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Dec 1 18:54:57 2003 Subject: [Tutor] A range of numbers Message-ID: THX! >From: Gregor Lingl >To: Leung Cris >CC: tutor@python.org >Subject: Re: [Tutor] A range of numbers >Date: Tue, 02 Dec 2003 00:53:35 +0100 > >Hi Leung! > >There is a range function in Python: > > >>> range(5) >[0, 1, 2, 3, 4] > >>> range(5,10) >[5, 6, 7, 8, 9] > >It outputs lists of integer values. >play around with it to learn how it works. >(Even to call range(10,20,2), i. e. with >3 arguments, is possible) > >On the other han you can check if some value >is in a certain range with the in - Operator: > > >>> y = 4 > >>> y in range(5) >True # 1 in older Versions of Python > >>> y in range(5,10) >False # or 0 > >so if you first extract the coordinates of >your mouse-position: > > >>> x,y = mouse_position() > >then you can easily check if y is in the desired >range. > >HTH >Gregor > > > >Leung Cris schrieb: > > > I was wondering if it is possible to set a variable or something to a > > RANGE of numbers. For instance , I want to have it so that when I > > mouse clicks in a certain region( let say, from (100,100) to > > (200,200)), it prints out "You Clicked!" . I'm doing this with > > Livewires right now. Of course, it would take forever if i try to write: > > > > if mouse_position() == (100,100) or (100,101) or (100,102) > > .............................. > > and mouse_buttons()['left'] == 1: > > do something > > > > that won't work... so , can anyone help? > > > > _________________________________________________________________ > > MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : > > http://photos.msn.com.hk/support/worldwide.aspx > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From glingl at aon.at Mon Dec 1 19:02:06 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Dec 1 19:01:06 2003 Subject: [Tutor] A range of numbers In-Reply-To: <3FCBD4B5.8050901@aon.at> References: <3FCBD4B5.8050901@aon.at> Message-ID: <3FCBD67E.9010100@aon.at> VERY STRANGE!!! My reply is missing here??? It's not missing in the copy of this mail in my sent-folder. I wrote: Another way to do it would be: x,y = mouse_position() if 100 <= x <= 200 and 100 <= y <= 200 and ... : do something Gregor Gregor Lingl schrieb: >Leung Cris schrieb: > > > >>I was wondering if it is possible to set a variable or something to a >>RANGE of numbers. For instance , I want to have it so that when I >>mouse clicks in a certain region( let say, from (100,100) to >>(200,200)), it prints out "You Clicked!" . I'm doing this with >>Livewires right now. Of course, it would take forever if i try to write: >> >>if mouse_position() == (100,100) or (100,101) or (100,102) >>.............................. >>and mouse_buttons()['left'] == 1: >>do something >> >>that won't work... so , can anyone help? >> >>_________________________________________________________________ >>MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : >>http://photos.msn.com.hk/support/worldwide.aspx >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> >> > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From amonroe at columbus.rr.com Mon Dec 1 19:16:38 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Dec 1 19:07:18 2003 Subject: [Tutor] A range of numbers In-Reply-To: <3FCBD47F.8090100@aon.at> References: <3FCBD47F.8090100@aon.at> Message-ID: <81-1117350024.20031201191638@columbus.rr.com> >> I was wondering if it is possible to set a variable or something to a >> RANGE of numbers. For instance , I want to have it so that when I >> mouse clicks in a certain region( let say, from (100,100) to >> (200,200)), it prints out "You Clicked!" . I'm doing this with >> Livewires right now. Of course, it would take forever if i try to write: >> >> if mouse_position() == (100,100) or (100,101) or (100,102) >> .............................. >> and mouse_buttons()['left'] == 1: >> do something >>>> y = 4 >>>> y in range(5) > True # 1 in older Versions of Python >>>> y in range(5,10) > False # or 0 > so if you first extract the coordinates of > your mouse-position: >>>> x,y = mouse_position() > then you can easily check if y is in the desired > range. I haven't tried it, but that seems like it would be slow, because Python would have to create a list, possibly hundreds of numbers long, in RAM, every time you checked it. Unless Python caches them? The traditional way I think is to use greater than and less than. if (x>100) and (x<200) and (y>100) and (y<200): print "you clicked" Alan From krazie_mu_boi at hotmail.com Mon Dec 1 19:11:15 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Dec 1 19:11:20 2003 Subject: [Tutor] A range of numbers Message-ID: Thx, but while you are at it, can you tell me what is wrong with this code? >>>while 1: >>> (x,y) = mouse_position() >>> if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: >>> break >>> move(300,200) >>> text('You Did it!') Whever I try it, it says Unpack Sequence (or something like that ) . I knew this was because my mouse wasn't in the graphic window, meaning that mouse_position() = None ; so, i moved my mouse to the graphic window, and try the code again: FREEZES. >From: Gregor Lingl >To: Leung Cris >Subject: Re: [Tutor] A range of numbers >Date: Tue, 02 Dec 2003 00:56:56 +0100 > > >Another way to do it would be: > >x,y = mouse_position() >if 100 <= x <= 200 and 100 <= y <= 200 and ... : >do something > >Gregor > > >Leung Cris schrieb: > > > I was wondering if it is possible to set a variable or something to a > > RANGE of numbers. For instance , I want to have it so that when I > > mouse clicks in a certain region( let say, from (100,100) to > > (200,200)), it prints out "You Clicked!" . I'm doing this with > > Livewires right now. Of course, it would take forever if i try to write: > > > > if mouse_position() == (100,100) or (100,101) or (100,102) > > .............................. > > and mouse_buttons()['left'] == 1: > > do something > > > > that won't work... so , can anyone help? > > > > _________________________________________________________________ > > MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : > > http://photos.msn.com.hk/support/worldwide.aspx > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _________________________________________________________________ 在您的行動裝置上傳送接收 Hotmail 郵件,請移至: http://zh-asiasms.mobile.msn.com From darnold02 at sprynet.com Mon Dec 1 19:14:06 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Mon Dec 1 19:12:34 2003 Subject: [Tutor] A range of numbers In-Reply-To: <3FCBD47F.8090100@aon.at> References: <3FCBD47F.8090100@aon.at> Message-ID: <7155612E-245C-11D8-9F7E-000A95C4F940@sprynet.com> On Dec 1, 2003, at 5:53 PM, Gregor Lingl wrote: > Hi Leung! > > There is a range function in Python: > >>>> range(5) > [0, 1, 2, 3, 4] >>>> range(5,10) > [5, 6, 7, 8, 9] > > It outputs lists of integer values. > play around with it to learn how it works. > (Even to call range(10,20,2), i. e. with > 3 arguments, is possible) > > On the other han you can check if some value > is in a certain range with the in - Operator: > >>>> y = 4 >>>> y in range(5) > True # 1 in older Versions of Python >>>> y in range(5,10) > False # or 0 > > so if you first extract the coordinates of > your mouse-position: > >>>> x,y = mouse_position() > > then you can easily check if y is in the desired > range. > > HTH > Gregor > I never thought of doing range checking like that before. Cool. But I still prefer: x, y = mouse_position() if 100 <= x <= 200 and 100 <= y <= 200: print "You clicked!" That way, you don't generate a throwaway list, and you don't have to worry about the potential off-by-one error that can happen when using range(). Just my 2 cents, Don From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 19:38:57 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 19:39:04 2003 Subject: [Tutor] A range of numbers In-Reply-To: Message-ID: On Mon, 1 Dec 2003, Leung Cris wrote: > Thx, but while you are at it, can you tell me what is wrong with this code? > > >>>while 1: > >>> (x,y) = mouse_position() [code cut] > Whenever I try it, it says Unpack Sequence (or something like that ). Hi Leung, On which line do you get the error message? Show us the exact error message, as well as the "traceback". That'll help us trace back where the problem is occurring. I'll assume for the moment that the code breaks on: (x,y) = mouse_position() If so, then we have to double check that mouse_position() always returns a 2-tuple. According to the docs in, http://www.livewires.org.uk/python/pdf/G-graphics.pdf we may need to call mouse_begin() and mouse_end() between calls to mouse_position(). It doesn't say what happens if we don't, and I get the feeling that Bad Things may happen if we don't follow the precepts. The above advice is only based on a guess though. *grin* Show us the error message, and we'll be better equipped to tackle the problem. Good luck! From littledanehren at yahoo.com Mon Dec 1 19:57:24 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Dec 1 19:57:30 2003 Subject: [Tutor] A range of numbers In-Reply-To: <81-1117350024.20031201191638@columbus.rr.com> Message-ID: <20031202005724.60097.qmail@web41807.mail.yahoo.com> --- "R. Alan Monroe" wrote: > >> I was wondering if it is possible to set a > variable or something to a > >> RANGE of numbers. For instance , I want to have > it so that when I > >> mouse clicks in a certain region( let say, from > (100,100) to > >> (200,200)), it prints out "You Clicked!" . I'm > doing this with > >> Livewires right now. Of course, it would take > forever if i try to write: > >> > >> if mouse_position() == (100,100) or (100,101) or > (100,102) > >> .............................. > >> and mouse_buttons()['left'] == 1: > >> do something > > > >>>> y = 4 > >>>> y in range(5) > > True # 1 in older Versions of Python > >>>> y in range(5,10) > > False # or 0 > > > so if you first extract the coordinates of > > your mouse-position: > >>>> x,y = mouse_position() > > then you can easily check if y is in the desired > > range. > > I haven't tried it, but that seems like it would be > slow, because > Python would have to create a list, possibly > hundreds of numbers long, > in RAM, every time you checked it. Unless Python > caches them? > > The traditional way I think is to use greater than > and less than. > > if (x>100) and (x<200) and (y>100) and (y<200): > print "you clicked" > > Alan I think you could simplify that to if 100 References: <20031201210030.GN14980@johnsons-web.com> <20031201232150.GQ14980@johnsons-web.com> <3FCBCE9B.1070806@aon.at> Message-ID: <20031202010616.GR14980@johnsons-web.com> It's as simple as all that! Great. thanks! tim * Gregor Lingl [031201 14:40]: > > Tim Johnson schrieb: > > > Is it possible to overload an existing method > > with another at runtime? > > > > > Hi Tim! > I'm not sure if it's this, what you want to know. I just played around > a little: > > >>> class A: > def __init__(self): > self.u = 1 > def p(self): > print self.u > > > >>> x = A() > >>> x.p() > 1 > >>> def q(self): > print 2*self.u > > > >>> A.p = q > >>> x.p() > 2 > >>> > > Even if it doesn't help it's still funny -- Tim Johnson http://www.alaska-internet-solutions.com From krazie_mu_boi at hotmail.com Mon Dec 1 20:27:33 2003 From: krazie_mu_boi at hotmail.com (Cris Leung) Date: Mon Dec 1 20:27:38 2003 Subject: [Tutor] A range of numbers Message-ID: Okay, I was working on it just now, and I found out that this works: __________________________________________________________________ def func(): begin_graphics() begin_mouse() box(200,200,300,300) for i in range(100): print 'delay' while 1: x,y = mouse_position() if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: break box(100,100,400,400) end_mouse() __________________________________________________________ as long as I move my mouse to the graphics window before the "print delay" is finish. However, if I dun click within seconds after the "print 'delay'" , the thing freezes. I have also tried this: ______________________________________________ def func(): begin_graphics() begin_mouse() box(200,200,300,300) mouse_wait('down') while 1: x,y = mouse_position() if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: break box(100,100,400,400) end_mouse() __________________________________________ but I have no idea how to use mouse_wait () . I've also tried using if mouse_position() != None: blah blah blah but that freezes as well. HELP!!!!! >From: Gregor Lingl >To: tutor@python.org >Subject: Re: [Tutor] A range of numbers >Date: Tue, 02 Dec 2003 01:02:06 +0100 > >VERY STRANGE!!! > >My reply is missing here??? It's not missing in the >copy of this mail in my sent-folder. > >I wrote: > >Another way to do it would be: > >x,y = mouse_position() >if 100 <= x <= 200 and 100 <= y <= 200 and ... : >do something > >Gregor > > > > > >Gregor Lingl schrieb: > > >Leung Cris schrieb: > > > > > > > >>I was wondering if it is possible to set a variable or something to a > >>RANGE of numbers. For instance , I want to have it so that when I > >>mouse clicks in a certain region( let say, from (100,100) to > >>(200,200)), it prints out "You Clicked!" . I'm doing this with > >>Livewires right now. Of course, it would take forever if i try to write: > >> > >>if mouse_position() == (100,100) or (100,101) or (100,102) > >>.............................. > >>and mouse_buttons()['left'] == 1: > >>do something > >> > >>that won't work... so , can anyone help? > >> > >>_________________________________________________________________ > >>MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : > >>http://photos.msn.com.hk/support/worldwide.aspx > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > >> > >> > >> > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 20:37:42 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 20:37:54 2003 Subject: [Tutor] A range of numbers In-Reply-To: Message-ID: On Mon, 1 Dec 2003, Cris Leung wrote: > Okay, I was working on it just now, and I found out that this works: > __________________________________________________________________ > def func(): > begin_graphics() > begin_mouse() > box(200,200,300,300) > for i in range(100): > print 'delay' > while 1: > x,y = mouse_position() > if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: > break > box(100,100,400,400) > end_mouse() > __________________________________________________________ > > as long as I move my mouse to the graphics window before the "print > delay" is finish. However, if I dun click within seconds after the > "print 'delay'" , the thing freezes. Ah! Try moving the begin_mouse() and end_mouse() stuff around the mouse_position(). What's happening is that begin_mouse() and end_mouse() are the function that update the mouse position in the program. Without them, mouse_position() will continue to return the same thing over and over. ### def func(): begin_graphics() box(200,200,300,300) while 1: begin_mouse() x,y = mouse_position() end_mouse() if (200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1): break box(100,100,400,400) ### should fix the bug. This is not an ideal fix --- in programming lingo, this is a "busy waiting" loop that continues to ask the system what the mouse position is, even if it hasn't changed recently. So it's a bit inefficient. Still, it should be ok enough to make things work. (But to tell the truth, I don't know why the Livewires API is designed that way; it seems very error prone! I think it might simply be better to have mouse_position() automatically call begin_mouse() and end_mouse() for us. I'd have to look more closely at the Livewires API to see why they don't do that.) Good luck! From dyoo at hkn.eecs.berkeley.edu Mon Dec 1 20:43:49 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 1 20:43:54 2003 Subject: [Tutor] A range of numbers In-Reply-To: Message-ID: On Mon, 1 Dec 2003, Danny Yoo wrote: > > delay" is finish. However, if I dun click within seconds after the > > "print 'delay'" , the thing freezes. > > > Ah! > > Try moving the begin_mouse() and end_mouse() stuff around the > mouse_position(). What's happening is that begin_mouse() and > end_mouse() are the function that update the mouse position in the > program. Without them, mouse_position() will continue to return the same > thing over and over. > > > ### > def func(): > begin_graphics() > box(200,200,300,300) > while 1: > begin_mouse() > x,y = mouse_position() > end_mouse() > if (200 <= x <= 300 > and 200 <= y <= 300 > and mouse_buttons()['left'] == 1): > break > box(100,100,400,400) > ### > > should fix the bug. Doh. I meant: ### def func(): begin_graphics() box(200,200,300,300) while 1: begin_mouse() x,y = mouse_position() buttons = mouse_buttons() end_mouse() if (200 <= x <= 300 and 200 <= y <= 300 and buttons['left'] == 1): break box(100,100,400,400) ### That is, we need to wrap the begin_mouse() and end_mouse() around all mouse access. Otherwise, mouse_buttons() isn't guaranteed to give us a good value. Sorry about that! From krazie_mu_boi at hotmail.com Mon Dec 1 20:44:31 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Dec 1 20:44:35 2003 Subject: [Tutor] A range of numbers Message-ID: Livewires is ERROR-PRONE. But it's wat i have to use at school, o well. Okay , the code doesn't really work because the function mouse_position() returns not a number, but a None if the cursor isn't on the graphics screen. And becuz livewires made the function begin_graphics() open up a window but doesn't MAXIMIZE it . I'm not able to out race the computer in putting my cursor on to the graphics window. So, I think i need a code that wait for something to happen before going on to the loop. I saw the mouse_wait(how) function on the worksheet, but don't kno how to use it. >From: Danny Yoo >To: Cris Leung >CC: tutor@python.org >Subject: Re: [Tutor] A range of numbers >Date: Mon, 1 Dec 2003 17:37:42 -0800 (PST) > > > >On Mon, 1 Dec 2003, Cris Leung wrote: > > > Okay, I was working on it just now, and I found out that this works: > > __________________________________________________________________ > > def func(): > > begin_graphics() > > begin_mouse() > > box(200,200,300,300) > > for i in range(100): > > print 'delay' > > while 1: > > x,y = mouse_position() > > if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: > > break > > box(100,100,400,400) > > end_mouse() > > __________________________________________________________ > > > > as long as I move my mouse to the graphics window before the "print > > delay" is finish. However, if I dun click within seconds after the > > "print 'delay'" , the thing freezes. > > >Ah! > >Try moving the begin_mouse() and end_mouse() stuff around the >mouse_position(). What's happening is that begin_mouse() and end_mouse() >are the function that update the mouse position in the program. Without >them, mouse_position() will continue to return the same thing over and >over. > > >### >def func(): > begin_graphics() > box(200,200,300,300) > while 1: > begin_mouse() > x,y = mouse_position() > end_mouse() > if (200 <= x <= 300 > and 200 <= y <= 300 > and mouse_buttons()['left'] == 1): > break > box(100,100,400,400) >### > >should fix the bug. > > >This is not an ideal fix --- in programming lingo, this is a "busy >waiting" loop that continues to ask the system what the mouse position is, >even if it hasn't changed recently. So it's a bit inefficient. Still, it >should be ok enough to make things work. > > >(But to tell the truth, I don't know why the Livewires API is designed >that way; it seems very error prone! I think it might simply be better to >have mouse_position() automatically call begin_mouse() and end_mouse() for >us. I'd have to look more closely at the Livewires API to see why they >don't do that.) > > >Good luck! > _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From krazie_mu_boi at hotmail.com Mon Dec 1 20:46:30 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Dec 1 20:46:35 2003 Subject: [Tutor] A range of numbers Message-ID: Forgot to tell you guys, if I don't get my mouse to the graphics screen, the mouse_position() will return None instead of a (x,y) . here's the error I wud get: Traceback (most recent call last): File "", line 1, in ? func() File "", line 6, in func x,y = mouse_position() TypeError: unpack non-sequence >From: Danny Yoo >To: Cris Leung >CC: tutor@python.org >Subject: Re: [Tutor] A range of numbers >Date: Mon, 1 Dec 2003 17:43:49 -0800 (PST) > > > >On Mon, 1 Dec 2003, Danny Yoo wrote: > > > delay" is finish. However, if I dun click within seconds after the > > > "print 'delay'" , the thing freezes. > > > > > > Ah! > > > > Try moving the begin_mouse() and end_mouse() stuff around the > > mouse_position(). What's happening is that begin_mouse() and > > end_mouse() are the function that update the mouse position in the > > program. Without them, mouse_position() will continue to return the same > > thing over and over. > > > > > > ### > > def func(): > > begin_graphics() > > box(200,200,300,300) > > while 1: > > begin_mouse() > > x,y = mouse_position() > > end_mouse() > > if (200 <= x <= 300 > > and 200 <= y <= 300 > > and mouse_buttons()['left'] == 1): > > break > > box(100,100,400,400) > > ### > > > > should fix the bug. > > > >Doh. I meant: > > >### >def func(): > begin_graphics() > box(200,200,300,300) > while 1: > begin_mouse() > x,y = mouse_position() > buttons = mouse_buttons() > end_mouse() > if (200 <= x <= 300 and 200 <= y <= 300 > and buttons['left'] == 1): > break > box(100,100,400,400) >### > > >That is, we need to wrap the begin_mouse() and end_mouse() around all >mouse access. Otherwise, mouse_buttons() isn't guaranteed to give us a >good value. > > >Sorry about that! > _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From andy_osagie at hotmail.com Mon Dec 1 21:06:39 2003 From: andy_osagie at hotmail.com (Andy Osagie) Date: Mon Dec 1 21:07:44 2003 Subject: [Tutor] Printing Large Amounts of Data Message-ID: I recently decided to help my mother's business out by inputting thousands of names and addresses into a tuple with a python program I made. I then saved each entry as a cPickle object in its own file. There are about 3000 objects; each having a name, title, street, city, state, and zipcode field. Now my mom wants me to print all these names and addresses onto envelopes. I have a few ideas on how to do this but I decided it would be best if I asked you guys for your advice first, before I waste a lot of paper. Thanks in advance, -- Andy Osagie -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031201/4e8fa383/attachment.html From littledanehren at yahoo.com Mon Dec 1 21:11:52 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Dec 1 21:12:01 2003 Subject: [Tutor] A range of numbers In-Reply-To: Message-ID: <20031202021152.16009.qmail@web41805.mail.yahoo.com> --- Leung Cris wrote: > Forgot to tell you guys, if I don't get my mouse to > the graphics screen, the mouse_position() will > return None instead of a (x,y) . here's the error I > wud get: > > Traceback (most recent call last): > File "", line 1, in ? > func() > File "", line 6, in func > x,y = mouse_position() > TypeError: unpack non-sequence Then catch the error. Here's just the unpacking part of the code with the error caught: try: x, y = mouse_position() except: x, y = 0, 0 Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From krazie_mu_boi at hotmail.com Mon Dec 1 21:18:32 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Dec 1 21:18:37 2003 Subject: [Tutor] A range of numbers Message-ID: ....Dun realy get it. >From: Daniel Ehrenberg >To: pytutor >Subject: Re: [Tutor] A range of numbers >Date: Mon, 1 Dec 2003 18:11:52 -0800 (PST) > > >--- Leung Cris wrote: > > Forgot to tell you guys, if I don't get my mouse to > > the graphics screen, the mouse_position() will > > return None instead of a (x,y) . here's the error I > > wud get: > > > > Traceback (most recent call last): > > File "", line 1, in ? > > func() > > File "", line 6, in func > > x,y = mouse_position() > > TypeError: unpack non-sequence > >Then catch the error. Here's just the unpacking part >of the code with the error caught: > >try: > x, y = mouse_position() >except: > x, y = 0, 0 > >Daniel Ehrenberg > >__________________________________ >Do you Yahoo!? >Free Pop-Up Blocker - Get it now >http://companion.yahoo.com/ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ 在您的行動裝置上傳送接收 Hotmail 郵件,請移至: http://zh-asiasms.mobile.msn.com From alan.gauld at blueyonder.co.uk Mon Dec 1 23:52:59 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Dec 1 23:52:41 2003 Subject: [Tutor] Attribute error? References: <20031202062710.GA1973@Valhalla> Message-ID: <004101c3b890$28d03140$6401a8c0@xp> > uid = raw_input("Please enter your userID: ") > gid = raw_input("Please enter your gID: ") > f = open("file.txt","a") > f.append("\nYour userID is " + uid + " And your gID is " + gid) > ----- > > but when I input the values while executing it, it gives me an error: > > ----- > Traceback (most recent call last): > File "./test2.py", line 6, in ? > f.append("\nYour userID is " + uid + " And your gID is " + gid) > AttributeError: 'file' object has no attribute 'append' > ----- > > but I already used "a" for it to append.. I don't get it =( Thats right, you told Python that when you *write* to the file it should append the data o the existing file. But the file object doesn't have a method called append, you just write to it. f.writeline(".............) And you should really close the file after use - its a good habit even if Python will do it for you at the end of the program. f.close() Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From clickron at webtv.net Tue Dec 2 00:10:13 2003 From: clickron at webtv.net (Ron A) Date: Tue Dec 2 00:10:18 2003 Subject: [Tutor] special character ( =?iso-8859-1?q?=F1?= ) Message-ID: <1397-3FCC1EB5-4191@storefull-3195.bay.webtv.net> >It sounds like you're trying to use > ISO-8859-1 encoding to display > accented characters on your system. >If your terminal supports it, then you can > use: >????????ftp://unicode.org/Public/MAPPINGS >/ISO8859/8859-1.TXT >to find out the right hexadecimal > constants. For example, the tilde 'n' > maps to the entry: """ >0xF1 ? 0x00F1 # ? ? ? LATIN SMALL > LETTER N WITH TILDE """ >So if your terminal display natively >supports ISO-8859-1, then something > like: >### >print '\xf1' >### >should do the trick. Yup, that works just great. Thank you. Ron A From fredm at smartypantsco.com Tue Dec 2 00:25:31 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Tue Dec 2 00:25:05 2003 Subject: [Tutor] A range of numbers In-Reply-To: Message-ID: <5.1.0.14.0.20031202161249.033f29e0@192.168.1.1> One of the really great aspects of Python is that it is OK to make a mistake! In fact, one of Python's philosophies is captured in the Python proverb: "It's better to ask for forgiveness than for permission" This means: if you think your code will be OK most of the time, but occasionally produce an error, go ahead and do it anyway! When an error comes up, say sorry :)) The key construct here is "try ... except" try: x, y = mouse_position() This fragment says: "Try this code. I think it's OK. Don't fall over if it is wrong." But what happens if there is an error (as you reported)? Then you just tell the program what to do if you were wrong :)), such as: except: # your code for what to do if the "try" code fell over. You should be aware that the "try ... except" code is very powerful and will catch all errors in your "try" code fragment. For example if your code has a typing error, such as try: x, y = mouse_posiiton() the "try" segment will fail and you will always default into the except bit. It is therefore better to specify which error you want to ignore. You know from the code that didn't work that you get a TypeError if the mouse is off the screen, so your code should be try: x, y = mouse_position() except TypeError: # your code for what to do if the "try" code fell over. .... Hope this helps, Fred Milgrom At 06:18 PM 1/12/03 -0800, Leung Cris wrote: >....Dun realy get it. > > >>From: Daniel Ehrenberg >>To: pytutor >>Subject: Re: [Tutor] A range of numbers >>Date: Mon, 1 Dec 2003 18:11:52 -0800 (PST) >> >> >>--- Leung Cris wrote: >> > Forgot to tell you guys, if I don't get my mouse to >> > the graphics screen, the mouse_position() will >> > return None instead of a (x,y) . here's the error I >> > wud get: >> > >> > Traceback (most recent call last): >> > File "", line 1, in ? >> > func() >> > File "", line 6, in func >> > x,y = mouse_position() >> > TypeError: unpack non-sequence >> >>Then catch the error. Here's just the unpacking part >>of the code with the error caught: >> >>try: >> x, y = mouse_position() >>except: >> x, y = 0, 0 >> >>Daniel Ehrenberg >> >>__________________________________ >>Do you Yahoo!? >>Free Pop-Up Blocker - Get it now >>http://companion.yahoo.com/ >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_________________________________________________________________ >?b?z?????????m?W???e???? Hotmail ?l???A??????: >http://zh-asiasms.mobile.msn.com > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Tue Dec 2 01:59:13 2003 From: carroll at tjc.com (Terry Carroll) Date: Tue Dec 2 01:59:17 2003 Subject: [Tutor] isinstance() evil? Message-ID: I've read a couple aricle here and there that isinstance() is generally a bad idea. I have a question on that. I'm writing a small method used for debugging programs using a particular class I wrote. I want it to accept either an instance of the class, or a list of instances (or, for that matter, a list of list of instances, etc., if that's really what you want to do). I use isinstance() for this; it seems very straightforward to do this recursively: Dump(thing): if isinstance(thing, list): for element in thing: Dump(element) return [rest of Dump, for a one-element invocation, follows] Is there a preferred way to do something like this? -- Terry Carroll Santa Clara, CA carroll@tjc.com From fredm at smartypantsco.com Tue Dec 2 02:14:07 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Tue Dec 2 02:15:09 2003 Subject: [Tutor] A range of numbers In-Reply-To: Message-ID: <5.1.0.14.0.20031202174654.033f6390@192.168.1.1> Hi Leung: It's better to use "reply to all" in future, so your comments get posted to the list as well, rather than just to the one person. (I am copying this answer to the list now as well.) Looking at your code, I am not sure what you think the end_mouse() code will do, but there is a logic mistake. Look at these lines: > if 200 <= x <= 300 and 200 <= y <= 300 and > mouse_buttons()['left'] == 1: > break > end_mouse() > end_mouse() Translation: If the left button has been pressed inside the box: break <=== This means 'break out of the while loop'. No further code in the "while 1" loop will be executed, including end_mouse() (continuing with the code): On the other hand, if the mouse is not in the box or if the mouse button has not been pressed end_mouse() <=== Ignore all further mouse presses. So let's see what happens if that the program gets started: Immediately the "if" test will fail (because you can't press the cursor fast enough) All further mouse presses get ignored But you are still in the "while 1" infinite loop! Hope this helps, Fred Milgrom At 09:53 PM 1/12/03 -0800, you wrote: >I think i got the try ... except concept, but did i do something wrong >here? cuz it freezes when i try this function > >_________ >def func(): > begin_graphics() > box(200,200,300,300) > while 1: > begin_mouse() > try: > x,y = mouse_position() > except: > x,y = 0,0 > if 200 <= x <= 300 and 200 <= y <= 300 and > mouse_buttons()['left'] == 1: > break > end_mouse() > end_mouse() > box(300,200,500,500) >________________ > From magnus at thinkware.se Tue Dec 2 08:25:03 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Dec 2 08:25:12 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gaXNpbnN0YW5jZSgpIGV2aWw/?= Message-ID: > I've read a couple aricle here and there that isinstance() is generally a > bad idea. I wouldn't say that. It certainly has its uses. > I have a question on that. > > I'm writing a small method used for debugging programs using a particular > class I wrote. I want it to accept either an instance of the class, or a > list of instances (or, for that matter, a list of list of instances, etc., > if that's really what you want to do). > > I use isinstance() for this; it seems very straightforward to do this > recursively: > > Dump(thing): > > if isinstance(thing, list): > for element in thing: > Dump(element) > return I wouldn't use it in this case though. It seems to me that there is no reason to restrict this particular behaviour to lists. Why not allow other sequences, such as tuples, or maybe instances of some class you made. A simple option would be... try: for element in thing: Dump(element) except TypeError: # rest of dump... This has a few problems though. First of all, you could get some other type error that the one you get from looping over something unloopable. But that is fixable: try: for element in thing: Dump(element) except TypeError, e: if str(e) != 'iteration over non-sequence': raise # rest of dump... The second problem is that throwing exceptions is a bit costly from a performance point of view. One might also have principal objections about using the exception handling for situations that aren't really errors or exceptioonal conditions. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From op73418 at mail.telepac.pt Tue Dec 2 08:57:11 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Dec 2 08:55:25 2003 Subject: [Tutor] isinstance() evil? In-Reply-To: References: Message-ID: On Tue, 2 Dec 2003 14:25:03 +0100, you wrote: [text snipped] >I wouldn't use it in this case though. It seems to me that there is >no reason to restrict this particular behaviour to lists. Why not >allow other sequences, such as tuples, or maybe instances of some >class you made. > >A simple option would be... > > try: > for element in thing: > Dump(element) > except TypeError: > # rest of dump... > >This has a few problems though. First of all, you could get some >other type error that the one you get from looping over something >unloopable. But that is fixable: > > try: > for element in thing: > Dump(element) > except TypeError, e: > if str(e) != 'iteration over non-sequence': > raise > # rest of dump... > >The second problem is that throwing exceptions is a bit costly >from a performance point of view. One might also have principal >objections about using the exception handling for situations that >aren't really errors or exceptioonal conditions. Sometimes I use the following: #Can raise TypeError if thing is not iterable. it = iter(thing) for element in it: #Some exception(s) may be raised here. Dump(element) No masking of exceptions and avoids the use of the try/except block. With my best regards, G. Rodrigues From mhansen at cso.atmel.com Tue Dec 2 09:15:13 2003 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue Dec 2 09:12:39 2003 Subject: [Tutor] Re: IDE In-Reply-To: References: <3FC4D89B.5040400@cso.atmel.com> Message-ID: <3FCC9E71.4060000@cso.atmel.com> OOPS. My Bad. I had heard or thought I heard that development on XEMACS had stopped. Discussing EMACS with a fellow developer who is a EMACS convert, it appears that many of the features of XEMACS are now in EMACS. I didn't imply that the two were merging. Mike Abel Daniel wrote: >Mike Hansen writes: > > >>BTW, I believe that development on XEMACS has stopped, and most of the >>features that were in XEMACS are now in EMACS. >> >> >well, according to http://xemacs.org/About/XEmacsVsGNUemacs.html : > > There are currently irreconcilable differences in the views about > technical, programming, design and organizational matters between > Richard Stallman (RMS) and the XEmacs development team which provide > little hope for a merge to take place in the short-term future. > >The fact that emacs is getting features xemacs had before doesn't mean >that xemacs development stopped or that there is a merger going >on. (They might be reimplemented in emacs. Copying features isn't 'merging') > > > From op73418 at mail.telepac.pt Tue Dec 2 09:31:03 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Dec 2 09:29:18 2003 Subject: [Tutor] isinstance() evil? In-Reply-To: References: Message-ID: On Mon, 1 Dec 2003 22:59:13 -0800 (PST), you wrote: >I've read a couple aricle here and there that isinstance() is generally a >bad idea. > >I have a question on that. > >I'm writing a small method used for debugging programs using a particular >class I wrote. I want it to accept either an instance of the class, or a >list of instances (or, for that matter, a list of list of instances, etc., >if that's really what you want to do). > >I use isinstance() for this; it seems very straightforward to do this >recursively: > > Dump(thing): > > if isinstance(thing, list): > for element in thing: > Dump(element) > return > > [rest of Dump, for a one-element invocation, follows] > >Is there a preferred way to do something like this? IMHO there are two different answers to your question. Let me start by what you did not ask and answer that I think you are designing it wrongly: a thing and a sequence of things are two very different things (no pun intended) and should not be conflated. In terms of design, what this means is simply: 1. Make Dump a method of thing(s). 2. Have special purpose code to deal with a "sequence of things.". This is as simple as for thing in things: thing.Dump() where things is a "sequence" (a list, a tuple, a special-purpose iterable, etc.) of thing objects. Now, to your real question. Think of the question you are asking when using isinstance. if isinstance(thing, list): As the code in the if block shows the *only* thing you are interestred in is to know if thing is a sequence of sorts. You really do not care if it's a list. A tuple is a reasonable sequence also. So why restrict the usability of your code needlessly? Just go ahead and *assume* that the object is a sequence of things and then deal with any exceptions that may be raised: try: things = iter(things) except TypeError: raise TypeError("Object not iterable", things) for thing in things: try: dump = thing.Dump except AttributeError: raise AttributeError("Object not a thing", thing) dump() We first test if things is a "sequence" of sorts. In this case, we only want to iterate over it so we just ask: are you, things, iterable? This means exactly iter(things) To be explicit, I wrapped it in a try, except block, although it is useless because we just reraise the exception. Then for each thing in things, we ask first: do you have a Dump attribute? We do this by just grabbing the attribute as thing.Dump once again I've wrapped it in a try, except block for the sake of being explicit. Once again, it is useless in fact, since nothing more is done than raise an AttributeError exception. Once this "test" is passed we just go along and call dump = thing.Dump. It can also fail here, e.g.thing.Dump is not callable but... you get the point. One can *improve* the code a little bit. As it is, the first thing.Dump may succeed but the second (or the third, or...) can fail. We can make sure that *all* succed by the following try: things = iter(things) except TypeError: raise TypeError("Object not iterable", things) try: dumps = [thing.Dump for thing in things] except AttributeError: raise AttributeError("Object not a thing") for dump in dumps: dump() I'll leave you to ponder on this one :-) With my best regards, G. Rodrigues From op73418 at mail.telepac.pt Tue Dec 2 10:15:02 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Dec 2 10:13:21 2003 Subject: [Tutor] class method: dynamic overload/++ In-Reply-To: <20031201232150.GQ14980@johnsons-web.com> References: <20031201210030.GN14980@johnsons-web.com> <20031201232150.GQ14980@johnsons-web.com> Message-ID: On Mon, 1 Dec 2003 14:21:50 -0900, you wrote: >* Tim Johnson [031201 13:25]: >> Hi All: >> Is it possible in python to replace (overload) >> an existing class method with a new one of the same >> name but with different functionality? > > Upon review, I could have made myself more clear. > > I should have asked: > Is it possible to overload an existing method > with another at runtime? > > Hopefully that's clearer > ----------------------- > I would welcome pointers to docs and keywords. > - this is just R & D, not mission critical. > > TIA > tim > As Gregor Lingl showed, you can replace at runtime one method with another. >>> class A(object): ... def __init__(self, attrib): ... self.attrib = attrib ... def method(self): ... return self.attrib ... >>> a = A(1) >>> a.method() 1 >>> def anothermethod(self): ... return 2*self.attrib ... >>> A.method = anothermethod >>> a.method() 2 >>> What this shows is that *every* instance, even existing ones, will notice the change (class objects are mutable). Think carefully, if you are not better served by simple, yet reliable, inheritance: >>> class B(A): ... def method(self): ... return 2*self.attrib ... >>> b = B(1) >>> b.method() 2 >>> You can also replace methods in a per-instance base, e.g. >>> import new >>> help(new.instancemethod) Help on class instancemethod in module __builtin__: class instancemethod(object) | instancemethod(function, instance, class) | | Create an instance method object. | ... >>> c = A(2) >>> c.method() 4 >>> c.method = new.instancemethod(lambda self: 3*self.attrib, c, c.__class__) >>> c.__dict__["method"] of <__main__.A object at 0x010F1EF0>> >>> c.attrib 2 >>> c.method() 6 >>> a.attrib 1 >>> a.method() 2 As you can see, only the c instance has the new method, not the a instance. You can also change the *class* of an instance at run time. This can fail badly, or, even worse, lead to some disastrous results. Anyway I mention it for the sake of completion, since in this case there are no problems: >>> a.__class__ = B >>> a.__class__ >>> a.method() 2 And Python's dynamic capabilities do not end here. One can go well into metaclass programming and fashion classes at run time, modify them, etc. But at the end of the day, these are all *advanced* techniques and, unless you are trying to be clever, they are not to be used in the vast majority of cases. In other words, if you don't know wether you need them, you don't: "Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why). -- Python Guru Tim Peters" With my best regards, G. Rodrigues From krazie_mu_boi at hotmail.com Tue Dec 2 11:31:37 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Tue Dec 2 11:31:43 2003 Subject: [Tutor] A range of numbers Message-ID: Ya, that's true.... but even if i change it something like this: >>def func(): >> begin_graphics() >> box(200,200,300,300) >> begin_mouse() >> while 1: >> >> try: >> x,y = mouse_position() >> except: >> x,y = 0,0 >> if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: >> break >> end_mouse() >> box(300,200,500,500) It sill won't work. I've also tried putting time.sleep(0.05) before the while loop ends , but it ....still freezes. >From: Alfred Milgrom >To: "Leung Cris" , tutor@python.org >Subject: Re: [Tutor] A range of numbers >Date: Tue, 02 Dec 2003 18:14:07 +1100 > >Hi Leung: > >It's better to use "reply to all" in future, so your comments get >posted to the list as well, rather than just to the one person. >(I am copying this answer to the list now as well.) > >Looking at your code, I am not sure what you think the end_mouse() >code will do, but there is a logic mistake. > >Look at these lines: > >> if 200 <= x <= 300 and 200 <= y <= 300 and >>mouse_buttons()['left'] == 1: >> break >> end_mouse() >> end_mouse() > >Translation: > >If the left button has been pressed inside the box: > break <=== This means 'break out of the while >loop'. > > No further code in the "while 1" loop will be executed, >including end_mouse() > >(continuing with the code): >On the other hand, if the mouse is not in the box or if the mouse >button has not been pressed > end_mouse() <=== Ignore all further mouse presses. > >So let's see what happens if that the program gets started: > Immediately the "if" test will fail (because you can't >press the cursor fast enough) > All further mouse presses get ignored > But you are still in the "while 1" infinite loop! > >Hope this helps, >Fred Milgrom > >At 09:53 PM 1/12/03 -0800, you wrote: >>I think i got the try ... except concept, but did i do something >>wrong here? cuz it freezes when i try this function >> >>_________ >>def func(): >> begin_graphics() >> box(200,200,300,300) >> while 1: >> begin_mouse() >> try: >> x,y = mouse_position() >> except: >> x,y = 0,0 >> if 200 <= x <= 300 and 200 <= y <= 300 and >>mouse_buttons()['left'] == 1: >> break >> end_mouse() >> end_mouse() >> box(300,200,500,500) >>________________ >> > > _________________________________________________________________ 在您的行動裝置上傳送接收 Hotmail 郵件,請移至: http://zh-asiasms.mobile.msn.com From tim at johnsons-web.com Tue Dec 2 12:19:07 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Dec 2 12:11:40 2003 Subject: [Tutor] class method: dynamic overload/++ In-Reply-To: References: <20031201210030.GN14980@johnsons-web.com> <20031201232150.GQ14980@johnsons-web.com> Message-ID: <20031202171907.GT14980@johnsons-web.com> * Gon?alo Rodrigues [031202 06:30]: > > Is it possible to overload an existing method > > with another at runtime? Thanks for a wealth of good information. This is great! <.snip.> regards tim -- Tim Johnson http://www.alaska-internet-solutions.com From marichar at csusb.edu Tue Dec 2 17:20:16 2003 From: marichar at csusb.edu (Matt Richardson) Date: Tue Dec 2 17:20:34 2003 Subject: [Tutor] recursion question Message-ID: <1070403616.558.47.camel@0-3-93-b6-64-42.csusb.edu> It's been awhile since I've posted last, but I promise I've been a faithful lurker :) Actually, it's been awhile since I've had a chance to work with python, so it feels kinda good to ask a question. I've been taking a c++ class this term and found it to be not as daunting as I had once feared. The little bit of python I know went a long way in making the class easier. However, yesterday we touched on (and I mean briefly touched on) recursive functions. I've seen questions posted about it before, but the way they work is just out of grasp for me. Here's the python version of the c++ function I had to write in the lab last night: >>> def mult(m, n): if n == 0: return 0 if n == 1: return m return m + mult(m, n-1) >>> mult(5, 5) 25 Ok, maybe it's just me thinking about it too much, or not enough, but I'm just not quite getting how these work. Here's what I do know: exit cases are needed to keep infinite loops from occuring, the function is called within it's definition. So I guess what I'm asking is, does the function call within the definition of the function spawn another instance of the function? And then if necessary, that second function spawn another? in confusion, Matt -- Matt Richardson Instructional Support Technician Department of Art California State University San Bernardino marichar@csusb.edu (909)880-7727 From BranimirP at cpas.com Tue Dec 2 17:32:38 2003 From: BranimirP at cpas.com (Branimir Petrovic) Date: Tue Dec 2 17:32:39 2003 Subject: [Tutor] popen's wierdness (on Win2K) Message-ID: <33678E78A2DD4D418396703A750048D45E6969@RIKER> While attempting to get to know if and how can I run and preferably have control over stdin and stdout/sterr streams of external cmd line programs and utilities launched via Python's popen, I've stumbled on this: ###################################################################### # FileName popenTest001.py import os # I will create small DOS batch file that will do no more but wait # for user to press any key in order to print greeting: script = r'C:\hello.bat' batstuff = """echo off echo . pause echo . echo Hello %1""" batfile = open(script, 'wt') batfile.write(batstuff) batfile.close() # Prepare to give task of running the above batch to Python's popen cmdshell = r'cmd /c' param = 'World' cmd = ' '.join([cmdshell, script, param]) print 'To be popen-ed: "%s"' % cmd # Run the 'thing': instrm, outstrm = os.popen4(cmd, 't') # If very next line is commented out, 'right' CMD process will have to # be killed (via Task Manager) for script to proceed. Leave it as is, # and write method will suscessfully pass 'something' to paused invisible # DOS box (child process), all will end happily - outstrm.read will # pick up whatever was brewing in child proc. stdout. instrm.write(r' ') print outstrm.read() # will show "Hello World" echoed by hello.bat # The funny part is - why 2 CMD invisible processess over and above # existing current and visible CMD 'box' running popenTest001.py? # # For instance - should I repeat the above, but allow the 'pause' to # wait indefinitley, quck peak in Task Manager at running processes # reveals 3 CMD processess; # One belongs to DOS 'box' from where this Python script was launched, # other (with slighthly bigger memory footprint of remaining two) is the # stuck child process istself, but what the heck is the third one??? # # Killing proper process ends the stallmate situation and allows # killed process to spit it guts into parent's 'DOS box' stdout. instrm, outstrm = os.popen4(cmd, 't') print outstrm.read() # Why 3 CMD processess at this point??? ###################################################################### On a side note - is there both sane AND controllable way to run, control and effectivley use external command line stuff from Python but on Win platform? (I know that popen stuff works as advertised on *nix, heard of 'expect' module too, but switching platform is not an option in this case...:( Branimir From missive at hotmail.com Tue Dec 2 17:38:43 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Dec 2 17:38:47 2003 Subject: [Tutor] Re: Printing Large Amounts of Data Message-ID: > I recently decided to help my mother's business out by inputting = >thousands of names and addresses into a tuple with a python program I = >made. I then saved each entry as a cPickle object in its own file. There = >are about 3000 objects; each having a name, title, street, city, state, = >and zipcode field. > Now my mom wants me to print all these names and addresses onto = >envelopes. I have a few ideas on how to do this but I decided it would = >be best if I asked you guys for your advice first, before I waste a lot = >of paper. Printing labels is tricky. You could probably hack something up in python, but you are probably better off doing this in a tool that has already been created. I would recommend openoffice.org or kbarcode. Both have many predefined label forms and can pull the data from a database -- which is probably better way to store all of the addresses you have. _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From missive at hotmail.com Tue Dec 2 17:54:38 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Dec 2 17:54:41 2003 Subject: [Tutor] Re: recursion question Message-ID: >>>def mult(m, n): if n == 0: return 0 if n == 1: return m return m + mult(m, n-1) >>>mult(5, 5) 25 >So I guess what I'm asking is, does the >function call within the definition of the function spawn another >instance of the function? And then if necessary, that second function >spawn another? > You got it. Just unroll your sample call: mult(5, 5) 5 + mult(5, 4) 5 + 5 + mult(5, 3) 5 + 5 + 5 + mult(5, 2) 5 + 5 + 5 + 5 + mult(5, 1) 5 + 5 + 5 + 5 + 5 (Now, you tell me why mult(5, -2) does not work right :o) _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From littledanehren at yahoo.com Tue Dec 2 18:23:28 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Dec 2 18:23:32 2003 Subject: [Tutor] wxPython window flashes open and closed Message-ID: <20031202232328.6019.qmail@web41804.mail.yahoo.com> >> I'm trying to learn wxPython. I made a simple hello >world app but it >> just flashes open and closed. Here's the code: > >I had the same problem. You need to redirect >stdout/stderr to a file. >By default it goes to a console window, but this >disappears >immediately after the program exits. So if you've got a >fatal error >that causes your program to die before it gets >started, well, you'll >never see it. > >This message describes the problem and the solution. >Worked for me. > >http://lists.wxwindows.org/archive/wxPython-users/msg07054.html I tried that, and it said "Gdk-WARNING **: locale not supported by C library" (without the quotes). I'm using Gnome 2.2 in US English and Debian and I got the package off of apt-get, if any of that makes a difference. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From kalle at lysator.liu.se Tue Dec 2 18:35:29 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Tue Dec 2 18:35:35 2003 Subject: [Tutor] recursion question In-Reply-To: <1070403616.558.47.camel@0-3-93-b6-64-42.csusb.edu> References: <1070403616.558.47.camel@0-3-93-b6-64-42.csusb.edu> Message-ID: <20031202233529.GK29814@i92.ryd.student.liu.se> [Matt Richardson] > However, yesterday we touched on (and I mean briefly touched on) > recursive functions. I've seen questions posted about it before, > but the way they work is just out of grasp for me. Here's the > python version of the c++ function I had to write in the lab last > night: > > >>> def mult(m, n): > if n == 0: > return 0 > if n == 1: > return m > return m + mult(m, n-1) > > >>> mult(5, 5) > 25 > > Ok, maybe it's just me thinking about it too much, or not enough, > but I'm just not quite getting how these work. Here's what I do > know: exit cases are needed to keep infinite loops from occuring, > the function is called within it's definition. So I guess what I'm > asking is, does the function call within the definition of the > function spawn another instance of the function? And then if > necessary, that second function spawn another? Well, that depends on what you mean by "spawn another instance of the function". Here's what happens (at least approximately): When the interpreter encounters a def statement, it reads a function body, converts it to a function object, and binds the name of the function to the function object. In this process, nothing in the function body is evaluated. In particular, no names are looked up. When the function is called, the interpreter does some bookkeeping to remember what it was doing (it pushes stuff onto a stack) and loads the function code to be executed. When the function call inside the function is encountered, the same thing happens again. It doesn't matter if the call is to the same function or to another. For more detail than you wanted, try running dis.dis on your function. Example: >>> def f(x): ... f(x) ... >>> dis.dis(f) 2 0 LOAD_GLOBAL 0 (f) 3 LOAD_FAST 0 (x) 6 CALL_FUNCTION 1 9 POP_TOP 10 LOAD_CONST 0 (None) 13 RETURN_VALUE >>> Note that as long as I don't call f, there won't be an infinite loop. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From glingl at aon.at Tue Dec 2 18:45:34 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue Dec 2 18:44:36 2003 Subject: [Tutor] recursion question In-Reply-To: <1070403616.558.47.camel@0-3-93-b6-64-42.csusb.edu> References: <1070403616.558.47.camel@0-3-93-b6-64-42.csusb.edu> Message-ID: <3FCD241E.5050901@aon.at> Matt Richardson schrieb: >It's been awhile since I've posted last, but I promise I've been a >faithful lurker :) Actually, it's been awhile since I've had a chance >to work with python, so it feels kinda good to ask a question. > >I've been taking a c++ class this term and found it to be not as >... > > >>>>def mult(m, n): >>>> >>>> > if n == 0: > return 0 > if n == 1: > return m > return m + mult(m, n-1) > > > >>>>mult(5, 5) >>>> >>>> >25 > >Ok, maybe it's just me thinking about it too much, or not enough, but >I'm just not quite getting how these work. > Hi Matt! There is an excellent chapter (# 4) on recursion in this online-tutorial: http://www.ibiblio.org/obp/thinkCSpy/ The same also exists in a c++ version: http://www.ibiblio.org/obp/thinkCS/cpp/english/ Regards, Gregor From marichar at csusb.edu Tue Dec 2 18:58:07 2003 From: marichar at csusb.edu (Matt Richardson) Date: Tue Dec 2 19:00:56 2003 Subject: [Tutor] recursion question In-Reply-To: <3FCD241E.5050901@aon.at> References: <1070403616.558.47.camel@0-3-93-b6-64-42.csusb.edu> <3FCD241E.5050901@aon.at> Message-ID: <1070409486.558.149.camel@0-3-93-b6-64-42.csusb.edu> On Tue, 2003-12-02 at 15:45, Gregor Lingl wrote: > >Ok, maybe it's just me thinking about it too much, or not enough, but > >I'm just not quite getting how these work. > > > Hi Matt! > There is an excellent chapter (# 4) on recursion in this online-tutorial: > > http://www.ibiblio.org/obp/thinkCSpy/ > > The same also exists in a c++ version: > > http://www.ibiblio.org/obp/thinkCS/cpp/english/ > D'oh!! I hadn't read that far in yet! I'll read it tonight and see if the light that Lee Harr turned on gets any brighter :) Matt -- Matt Richardson Instructional Support Technician Department of Art California State University San Bernardino marichar@csusb.edu (909)880-7727 From marichar at csusb.edu Tue Dec 2 19:03:37 2003 From: marichar at csusb.edu (Matt Richardson) Date: Tue Dec 2 19:06:06 2003 Subject: [Tutor] Re: recursion question In-Reply-To: References: Message-ID: <1070409817.558.153.camel@0-3-93-b6-64-42.csusb.edu> On Tue, 2003-12-02 at 14:54, Lee Harr wrote: > >>>def mult(m, n): > if n == 0: > return 0 > if n == 1: > return m > return m + mult(m, n-1) > > >>>mult(5, 5) > 25 > > >So I guess what I'm asking is, does the > >function call within the definition of the function spawn another > >instance of the function? And then if necessary, that second function > >spawn another? > > > > > You got it. > > Just unroll your sample call: > > mult(5, 5) > 5 + mult(5, 4) > 5 + 5 + mult(5, 3) > 5 + 5 + 5 + mult(5, 2) > 5 + 5 + 5 + 5 + mult(5, 1) > 5 + 5 + 5 + 5 + 5 > > > (Now, you tell me why mult(5, -2) does not work right :o) > Thanks, Lee, I think the unrolling you did is making it easier for me to grok this. Ok, so to answer your question, it sets up the call as mult(5, -2) so when the function hits the final return statement it looks like return 5 + mult(5, -2-1) which sets up a bad loop. If I'm wrong, correct me before I do any more damage! Matt -- Matt Richardson Instructional Support Technician Department of Art California State University San Bernardino marichar@csusb.edu (909)880-7727 From missive at hotmail.com Tue Dec 2 19:50:41 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Dec 2 19:50:46 2003 Subject: [Tutor] Re: recursion question Message-ID: > > >>>def mult(m, n): > > if n == 0: > > return 0 > > if n == 1: > > return m > > return m + mult(m, n-1) > > > > >>>mult(5, 5) > > 25 > > > > >So I guess what I'm asking is, does the > > >function call within the definition of the function spawn another > > >instance of the function? And then if necessary, that second function > > >spawn another? > > > > > > > > > You got it. > > > > Just unroll your sample call: > > > > mult(5, 5) > > 5 + mult(5, 4) > > 5 + 5 + mult(5, 3) > > 5 + 5 + 5 + mult(5, 2) > > 5 + 5 + 5 + 5 + mult(5, 1) > > 5 + 5 + 5 + 5 + 5 > > > > > > (Now, you tell me why mult(5, -2) does not work right :o) > > >Thanks, Lee, I think the unrolling you did is making it easier for me to >grok this. Ok, so to answer your question, it sets up the call as > >mult(5, -2) > >so when the function hits the final return statement it looks like > >return 5 + mult(5, -2-1) > >which sets up a bad loop. If I'm wrong, correct me before I do any more >damage! > mult(5, -2) 5 + mult(5, -3) 5 + 5 + mult(5, -4) 5 + 5 + 5 + mult(5, -5) 5 + 5 + 5 + 5 + mult(5, -6) 5 + 5 + 5 + 5 + 5 + mult(5, -7) etc, etc, etc. Now for extra credit: Make a mult that can work with negative numbers.... _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From amonroe at columbus.rr.com Tue Dec 2 21:07:27 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Dec 2 20:59:00 2003 Subject: [Tutor] recursion question In-Reply-To: <1070403616.558.47.camel@0-3-93-b6-64-42.csusb.edu> References: <1070403616.558.47.camel@0-3-93-b6-64-42.csusb.edu> Message-ID: <144-1024240019.20031202210727@columbus.rr.com> > called within it's definition. So I guess what I'm asking is, does the > function call within the definition of the function spawn another > instance of the function? And then if necessary, that second function > spawn another? Exactly. Did you ever watch a movie, in which the characters themselves were making their own movie? It's kind of like that. If you feel daring, check out the chapter about it in _Godel, Escher, Bach_ by Hofstadter (good luck reading the whole book though, I'm about 1/3 through...) Alan From python at experiencedstudents.com Wed Dec 3 01:30:31 2003 From: python at experiencedstudents.com (Az) Date: Wed Dec 3 01:30:36 2003 Subject: [Tutor] stupid Q Message-ID: <000b01c3b966$f36a0440$6400a8c0@a0> hi all i am using python 2.2 on freebsd , the thing is i dont have GUI and use only command line interface , so how do i save a file from cli in the python's >>>> ? i did read the doc at python.org but cant find anywere the answer . the only answer i find is how to do that in IDLE sorry for taking your time for such Q ;(( From magnus at thinkware.se Wed Dec 3 10:37:41 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 3 10:37:47 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHJpbnRpbmcgTGFyZ2UgQW1vdW50cyBvZiBEYXRh?= Message-ID: > I recently decided to help my mother's business out by inputting thousands of names and addresses into a tuple with a python program I made. I then saved each entry as a cPickle object in its own file. There are about 3000 objects; each having a name, title, street, city, state, and zipcode field. So you have 3000 tiny files for that data? Why not just a text file with each entry on a row? In general, text files are more practical, since you can edit them in any editor, import them into Excel, Word etc. You could then use the mail merge function in Word to print envelopes. I'm sure the same functionality is available in OpenOffice etc if you are allergic to MS. Python 2.3 has a standard module called csv which is able to produce and parse Excel compatible delimiter separated text files. The following code puts your pickles in a text file. >>> import cPickle >>> import csv >>> import glob >>> f = file('addr.csv', 'wb') >>> w = csv.writer(f) >>> for fn in glob.glob('*.dat'): w.writerow(cPickle.load(file(fn))) >>> f.close() This assumes that '*.dat' would find your pickles. Of course, you might want to add some code to sort the entries before you put them in a file. Another option could be to put the data in a database such as SQLite or MS Access, but that might be overkill in this case (and it also requires that you know yet another product). > Now my mom wants me to print all these names and addresses onto envelopes. I have a few ideas on how to do this but I decided it would be best if I asked you guys for your advice first, before I waste a lot of paper. Well, the obvious paper saver is not to print *all* envelopes until you've debugged your code properly, but I guess you figured that one out already. ;) If you read your addresses into a list: >>> addresses = [] >>> for fn in glob.glob('*.dat'): addresses.append(cPickle.load(file(fn))) You can then loop over just a few of them: for addresss in addresses[:5]: for row in address: print row What *is* your problem? Positioning on the envelope? Formfeeding? Actually, the main problem might be to get the printer to feed envelopes without feeding them one at a time. Not all printers have a feeder that can handle envelopes. In that case it might be better to print on labels that you stick on the envelopes, but that's not really a Python issue. Well, actually it is, because it means that you have to print pages with many addresses in rows and columns instead of one address per page. The simple solution here (if you print directly on envelopes) is to print something like this: empty_rows_top = 10 empty_spaces_left = 50 for addresss in addresses[:5]: print '\n' * empty_rows_top for row in address: print empty_spaces_left, row print chr(12) # Form feed For labels you need to create some kind of grid of text. A more advanced solution for pretty printing is to use the ReportLab toolkit (www.reportlab.com) to create PDF files. Reportlab is a great toolkit, but there is a learning curve. See http://www.reportlab.com/docs/userguide.pdf Here is a tiny reportlab example: from reportlab.pdfgen import canvas def hello(c): c.drawString(100,100,"Hello World") c = canvas.Canvas("hello.pdf") hello(c) c.showPage() c.save() I guess you can see roughly how to extend that to place text right for labels etc. c.showPage() would end the current page, and further c.drawString(...) would appear on the next page. Of course, I skipped details such as paper sizes etc here, but it's all in the docs. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From kalle at lysator.liu.se Wed Dec 3 11:26:10 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Wed Dec 3 11:26:15 2003 Subject: [Tutor] stupid Q In-Reply-To: <000b01c3b966$f36a0440$6400a8c0@a0> References: <000b01c3b966$f36a0440$6400a8c0@a0> Message-ID: <20031203162610.GL29814@i92.ryd.student.liu.se> [Az] > hi all > i am using python 2.2 on freebsd, the thing is i dont have GUI and > use only command line interface, so > how do i save a file from cli in the python's > >>>> > ? > i did read the doc at python.org but cant find anywere the answer. > the only answer i find is how to do that in IDLE Well, you don't, really. Edit the file in an editor, e.g. emacs or vi. Then test the code by running "python myfile.py" in the shell. In emacs, you can use python-mode to test the code as well. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From rafael.sousa at netcabo.pt Wed Dec 3 14:02:27 2003 From: rafael.sousa at netcabo.pt (rafael.sousa) Date: Wed Dec 3 14:02:37 2003 Subject: [Tutor] Handling SIGCHLD signal to kill zombie processes Message-ID: <2305CFC39C15AA4896E06E5C91C509EF02998339@VS2.hdi.tvcabo> Hi! I need to know what to write in a function that handles the SIGCHLD signal, in order to kill zombie processes that are left running. -> In C ANSI, what I do is start by specifying what function is going to handle the signal: signal(SIGCHLD, handleSIGCHLD); and then one handler that does the trick is: void handleSIGCHLD() { int stat; /*Kills all the zombie processes*/ while(waitpid(-1, &stat, WNOHANG) > 0); } -> In Python, specifying the handler is easy: import signal signal.signal(signal.SIGCHLD, handleSIGCHLD) What I don't know how to do is an equivalent to the C function above... Can anyone help? Thanks in advance, Rafael Sousa From magnus at thinkware.se Wed Dec 3 14:02:38 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 3 14:02:46 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQSByYW5nZSBvZiBudW1iZXJz?= Message-ID: > Ya, that's true.... but even if i change it something like this: > >>def func(): > >> begin_graphics() > >> box(200,200,300,300) > >> begin_mouse() > >> while 1: > >> > >> try: > >> x,y = mouse_position() > >> except: > >> x,y = 0,0 > >> if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: > >> break > >> end_mouse() > >> box(300,200,500,500) > > It sill won't work. I've also tried putting time.sleep(0.05) before the while loop ends , but it ....still freezes. Danny Yoo already explained why that won't work. And don't forget to be more specific about catching exceptions, or you will catch other errors than you thought you did, and that will often make debugging very hard. In general you can find out a lot about your code by putting print statements here and there. A "print x,y" in the end of the while loop would probably give you a clue. By the way--the program isn't frozen, it's rather running hot! -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From karl.fast at pobox.com Wed Dec 3 14:17:41 2003 From: karl.fast at pobox.com (Karl Fast) Date: Wed Dec 3 14:18:13 2003 Subject: [Tutor] wxPython window flashes open and closed In-Reply-To: <20031202232328.6019.qmail@web41804.mail.yahoo.com>; from littledanehren@yahoo.com on Tue, Dec 02, 2003 at 03:23:28PM -0800 References: <20031202232328.6019.qmail@web41804.mail.yahoo.com> Message-ID: <20031203131741.E30394@signal.lights.com> > > > I'm trying to learn wxPython. I made a simple hello world app but it > > > just flashes open and closed. > > > > You need to redirect stdout/stderr to a file. > > > >This message describes the problem and the solution. > >http://lists.wxwindows.org/archive/wxPython-users/msg07054.html > > I tried that, and it said "Gdk-WARNING **: locale not supported by C > library" (without the quotes). I'm using Gnome 2.2 in US English and > Debian and I got the package off of apt-get If I understand, you were able redirect stdout/stderr to a file. And in that file was the error message you quoted above. So now you've got a new problem. Some issue with locale. Unfortunately, I don't know have an answer. You might try searching the wxPython list, or posting your question to it. Anybody else able to help? FYI: I did my development on W2K using the packages from wxpython.org. I tested it on my linux box using an RPM from wxpython.org. No apt-get for me. --karl From carroll at tjc.com Wed Dec 3 14:18:25 2003 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 3 14:18:31 2003 Subject: [Tutor] isinstance() evil? In-Reply-To: Message-ID: Thanks Gon?alo and Magnus! You've both given me some interesting ideas. -- Terry Carroll Santa Clara, CA carroll@tjc.com From magnus at thinkware.se Wed Dec 3 14:33:19 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 3 14:33:24 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gc3R1cGlkIFE=?= Message-ID: Az wrote: > hi all > i am using python 2.2 on freebsd , the thing is i dont have GUI and use > only command line interface , so > how do i save a file from cli in the python's As Kalle said, you should normally (whether you use an IDE or not) write your code in an editor, and save it as a file. You can save any command line session in unix though. (This has nothing to do with python.) For this, you use the unix script command. Just as with Python, you end the script session by pressing Ctrl-D. www5:~> script x.txt Script started, file is x.txt > python Python 2.2.2 (#2, Feb 10 2003, 00:03:01) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello" Hello >>> [Ctrl-D] > [Ctrl-D]Script done, file is x.txt www5:~> more x.txt [This will show the same as you see above...] Naturally, you will have to edit out the leading '>>>' and extra lines of text to be able to run your interactive python code as a program. A more normal unix/linux/bsd command line session with code editing consists of either suspending your editor to run code, or to use several (virtual) terminal sessions. Unix is a multitasking OS after all, whether you use a GUI or not. You suspend your editor with Ctrl-Z and revive it with the 'fg' command. Like this: $ vi test.py [do some code editing, and save without quitting] Ctrl-Z Suspended (signal) $ python ./test.py [Your bugs become evident...] $ fg [you're back in the editor, fix and save, don't quit] Ctrl-Z Suspended (signal) $ python ./test.py Repeat until ready... (remember to use 'fg' to get back to your editor. If you start the editor again the normal way, after you left it with Ctrl-Z, you'll end up with several editor sessions running in parallel. Of course, you should exit the editor properly when you are done. If you try to log out with suspended jobs, the OS will tell you.) With Linux, you normally have several virtual consoles, that you switch between with Alt-Fx. Then you can edit (don't forget to save) in one console and run the code in another. That way you don't need to bother with suspending the editor session to run code. If you are not by the console, you can use something like the "screen" utility. Use "man screen" to figure out how. Of course, if you use a good editor, such as vi (or better: vim), you can run your python script from within the editor. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Wed Dec 3 15:30:37 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 3 15:31:01 2003 Subject: [Tutor] A range of numbers [fixes to livewires] In-Reply-To: Message-ID: On Wed, 3 Dec 2003, Magnus Lycka wrote: > > Ya, that's true.... but even if i change it something like this: > > >>def func(): > > >> begin_graphics() > > >> box(200,200,300,300) > > >> begin_mouse() > > >> while 1: > > >> > > >> try: > > >> x,y = mouse_position() > > >> except: > > >> x,y = 0,0 > > >> if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: > > >> break > > >> end_mouse() > > >> box(300,200,500,500) > > > > It sill won't work. I've also tried putting time.sleep(0.05) before > > the while loop ends , but it ....still freezes. > > Danny Yoo already explained why that won't work. Hi Magnus, I was wrong though. *sigh* I took a closer look at the 'beginners' module, and it should continue to update the mouse_position(), because Livewires registers a callback for it. >From looking at the code, I see that mouse_position() is defined to return None if the mouse isn't on screen. Since that's not convenient for us, we can write a small wrapper around it to make things nicer: ### def my_mouse_position(): """A thin wrapper around mouse_position() that always returns a 2-tuple. If the mouse isn't on screen, returns (-1, -1).""" pos = mouse_position() if pos == None: return (-1, -1) return pos ### So we don't need to use any exception handling. The inner loop: > > >> while 1: > > >> > > >> try: > > >> x,y = mouse_position() > > >> except: > > >> x,y = 0,0 > > >> if 200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1: > > >> break is freezing because it is not giving the system a chance to update the mouse state. So we do need to call mouse_wait(). However, it looks like there may be some severe bugs in Livewires's handling of the mouse! There's definitely several typos where the Livewires code is calling the wrong Tkinter methods for fiddling with the event loop. I've made the following changes to Livewires's 'beginners.py' file to correct some bugs. For those that are familiar with 'diff', here are the changes I've made: ### [dyoo@tesuque tmp2]$ diff LiveWires-2.0/livewires/beginners.py ../LiveWires-2.0/ livewires/beginners.py 694c694 < while _mouse_b == 0: _root_window.dooneevent() --- > while _mouse_b == 0: _root_window.tk.dooneevent() 696c696 < while _mouse_b != 0: _root_window.dooneevent() --- > while _mouse_b != 0: _root_window.tk.dooneevent() 699c699 < while _mouse_b == b: _root_window.dooneevent() --- > while _mouse_b == b: _root_window.tk.dooneevent() 704c704 < _root_window.dooneevent() --- > _root_window.tk.dooneevent() 707c707 < while x == _mouse_x and y == _mouse_y: _root_window.dooneevent() --- > while x == _mouse_x and y == _mouse_y: _root_window.tk.dooneevent() 711c711 < _root_window.dooneevent() --- > _root_window.tk.dooneevent() 725c725,728 < _mouse_x, _mouse_y = None, None --- > ## (dyoo) commented out: this appears to be causing some ugly problems > ## _mouse_x, _mouse_y = None, None > > ### I've packaged up these corrections into the file: http://hkn.eecs.berkeley.edu/~dyoo/python/LiveWires-2.01.tar.gz I'm putting this up temporarily so that Leung can try it out. With this, the program: ### from livewires import * def my_mouse_position(): """A thin wrapper around mouse_position() that always returns a 2-tuple. If the mouse isn't on screen, returns (-1, -1).""" pos = mouse_position() if pos == None: return (-1, -1) return pos def func(): begin_graphics() box(200,200,300,300) begin_mouse() while 1: mouse_wait('any') x, y = my_mouse_position() print "(x, y) = ", (x,y) if (200 <= x <= 300 and 200 <= y <= 300 and mouse_buttons()['left'] == 1): break end_mouse() box(300,200,500,500) ### appears to work ok. There's still some wacky situation going on with the '' event that I haven't figured out yet, so I've commented it out of the Livewires code. Anyway, when I have the time, I'll send an email over to the Livewires folks later to see if we can fold these corrections into their code. Whew. Ok, back to work for me. *grin* Talk to you later! From marichar at csusb.edu Wed Dec 3 16:25:07 2003 From: marichar at csusb.edu (Matt Richardson) Date: Wed Dec 3 16:25:47 2003 Subject: [Tutor] Re: recursion question In-Reply-To: References: Message-ID: <1070486707.991.1.camel@0-30-65-7-62-8c.csusb.edu> On Tue, 2003-12-02 at 16:50, Lee Harr wrote: > > > >>>def mult(m, n): > > > if n == 0: > > > return 0 > > > if n == 1: > > > return m > > > return m + mult(m, n-1) > > > > > > >>>mult(5, 5) > > > 25 > > > > > > >So I guess what I'm asking is, does the > > > >function call within the definition of the function spawn another > > > >instance of the function? And then if necessary, that second function > > > >spawn another? > > > > > > > > > > > > > You got it. > > > > > > Just unroll your sample call: > > > > > > mult(5, 5) > > > 5 + mult(5, 4) > > > 5 + 5 + mult(5, 3) > > > 5 + 5 + 5 + mult(5, 2) > > > 5 + 5 + 5 + 5 + mult(5, 1) > > > 5 + 5 + 5 + 5 + 5 > > > > > > > > > (Now, you tell me why mult(5, -2) does not work right :o) > > > > >Thanks, Lee, I think the unrolling you did is making it easier for me to > >grok this. Ok, so to answer your question, it sets up the call as > > > >mult(5, -2) > > > >so when the function hits the final return statement it looks like > > > >return 5 + mult(5, -2-1) > > > >which sets up a bad loop. If I'm wrong, correct me before I do any more > >damage! > > > > mult(5, -2) > 5 + mult(5, -3) > 5 + 5 + mult(5, -4) > 5 + 5 + 5 + mult(5, -5) > 5 + 5 + 5 + 5 + mult(5, -6) > 5 + 5 + 5 + 5 + 5 + mult(5, -7) > etc, etc, etc. > > Now for extra credit: Make a mult that can work with negative numbers.... > >>> def mult(m, n): if n == 0: return 0 if n == 1: return m if n < 0: p = abs(n) result = -1 * (m + mult(m, p-1)) return result return m + mult(m, n-1) >>> mult(5, 2) 10 >>> mult(5, -2) -10 Probably not the prettiest, but I'm supposed to be working :) Matt -- Matt Richardson Instructional Support Technician Department of Art California State University San Bernardino marichar@csusb.edu (909)880-7727 From joddo at apixels.net Wed Dec 3 16:42:39 2003 From: joddo at apixels.net (Jeremy Oddo) Date: Wed Dec 3 16:35:40 2003 Subject: [Tutor] Newbie: "Global" vars across modules Message-ID: <1599.172.22.1.1.1070487759.squirrel@mail.apixels.net> I'm guessing this has come up time and time again, but I can't seem to find the information that I need. Here's my problem: I want to create a global variable that EVERY module can see. Why? Because I like to define a "debug_level" variable to print out debugging information. I want to define "debug_level", then use it throughout my main code and modules. I'm running into problems when I call an external module that I've written. Here's the basic idea: --begin gvars.py-- # Debug Level (0=NONE, 1=Normal, 2=Extended, 3=Verbose) debug_level = 2 --myFunctions.py-- def ftest(): if (debug_level = 3): print "VERBOSE DB: This is a verbose statement" return 1 --testing.py-- from gvars import * from myFunctions import * print "Current debug level is:", debug_level ftest() So, testing.py is my main file. It imports gvars.py which contains my global variable "debug_level". The testing.py file prints out "debug_level" and all is good. However, when I make the call to "ftest()" which is a function from A DIFFERENT FILE called "myFunctions.py", it doesn't see "debug_level" (even if I add the line "global debug_level"). So how can I make a "truly global" global variable? Thanks! JO From vicki at thepenguin.org Wed Dec 3 16:34:23 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Wed Dec 3 16:39:23 2003 Subject: [Tutor] Iterating with Range Message-ID: <10796.206.53.226.235.1070487263.squirrel@www.thepenguin.org> I am trying to iterate through a loop based on the length of a string. The string will be something like this: FFFFFFFFFFFFFFFFFFFFFFFF // There are 24 If the string is called parameters[2] why doesn't this work? ----------------- i=0 for i in range(len(parameters[2])): port.write(parameters[2][i]) time.sleep(.01) outfile.write("Sending "+parameters[2][i] + "to meter./n") print "Sent "+parameters[2][i] CRCval=ComputeCRC(parameters[2][i],holdval) holdval=CRCval i = i+1 ----------------- The error I get is this: Traceback (most recent call last): File "F:\wxComTool9.5.py", line 1638, in CommandCallback self.SendCommand(self.selection, self.arguments) File "F:\wxComTool9.5.py", line 145, in SendCommand self.ProcessCommand(command, parameters) File "F:\wxComTool9.5.py", line 1295, in ProcessCommand for i in range(len(parameters[2])): IndexError: list index out of range I just don't see a problem (other than the error that I keep getting! ;-) ) --vicki From missive at hotmail.com Wed Dec 3 16:47:06 2003 From: missive at hotmail.com (Lee Harr) Date: Wed Dec 3 16:49:12 2003 Subject: [Tutor] Re: recursion question Message-ID: def mult(m, n): if n == 0: return 0 if n == 1: return m if n < 0: p = abs(n) result = -1 * (m + mult(m, p-1)) return result return m + mult(m, n-1) Nice. Here's my version for comparison... def mult(m, n): if n < 0: return -mult(m, -n) elif n == 0: return 0 elif n == 1: return m else: return m + mult(m, n-1) Now all we need to do is write a docstring and some regression tests and we're all set :o) _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From ATrautman at perryjudds.com Wed Dec 3 16:41:47 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Wed Dec 3 16:57:00 2003 Subject: [Tutor] Newbie: "Global" vars across modules Message-ID: <06738462136C054B8F8872D69DA140DB01C08BB5@corp-exch-1.pjinet.com> My favorite method, from a discussion on this list is to create a module and import it into all modules that need access. I name it myappname_globals.py and it contains things like database name, debug level, and other constants that might need changing. A config file is the other option I use if there is a lot to configure. If debug level is the only reason a command line argument is safest. This is the one of the very few cases where I like FROM myappname_globals.py IMPORT *. this means that the variable names are the same in every case. Hope that helps, Alan -----Original Message----- From: Jeremy Oddo [mailto:joddo@apixels.net] Sent: Wednesday, December 03, 2003 3:43 PM To: Python Tutor Subject: [Tutor] Newbie: "Global" vars across modules I'm guessing this has come up time and time again, but I can't seem to find the information that I need. Here's my problem: I want to create a global variable that EVERY module can see. Why? Because I like to define a "debug_level" variable to print out debugging information. I want to define "debug_level", then use it throughout my main code and modules. I'm running into problems when I call an external module that I've written. Here's the basic idea: --begin gvars.py-- # Debug Level (0=NONE, 1=Normal, 2=Extended, 3=Verbose) debug_level = 2 --myFunctions.py-- def ftest(): if (debug_level = 3): print "VERBOSE DB: This is a verbose statement" return 1 --testing.py-- from gvars import * from myFunctions import * print "Current debug level is:", debug_level ftest() So, testing.py is my main file. It imports gvars.py which contains my global variable "debug_level". The testing.py file prints out "debug_level" and all is good. However, when I make the call to "ftest()" which is a function from A DIFFERENT FILE called "myFunctions.py", it doesn't see "debug_level" (even if I add the line "global debug_level"). So how can I make a "truly global" global variable? Thanks! JO _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From xxjac88xx at comcast.net Wed Dec 3 17:11:29 2003 From: xxjac88xx at comcast.net (Jacques) Date: Wed Dec 3 17:11:27 2003 Subject: [Tutor] total beginner!!! Message-ID: <001901c3b9ea$6762a630$b5422444@yourw92p4bhlzg> Hello, I am a beginner. I mean I know absolutely nothing about python. I tried to read the tutorials, but I am sad to inform that I didn't understand anything. I don't understand what a script is, what this python language really does, or what a program is. I think a program is something that can be run on a computer, but I need help on were to really start. I know some one who used to hack onto the fbi site. I am trying to learn python so maybe i could do something like that. I want to be able to gather information that is not really shown on TV. I know this is illegal, but I hope I can get some help. I am not some one planning to do something wrong. I just want to see what isn't shown. I am a curious person. So, I can keep going on reasons and talk and talk and talk, but I would like to get to the point. Does anyone know where i should start? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031203/bbd8b23a/attachment.html From zak at harlekin-maus.com Wed Dec 3 17:19:07 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Wed Dec 3 17:19:11 2003 Subject: [Tutor] Iterating with Range In-Reply-To: <10796.206.53.226.235.1070487263.squirrel@www.thepenguin.org> References: <10796.206.53.226.235.1070487263.squirrel@www.thepenguin.org> Message-ID: <2309.192.207.104.221.1070489947.squirrel@webmail.harlekin-maus.com> [SNIP] > ----------------- > i=0 > for i in range(len(parameters[2])): > port.write(parameters[2][i]) [SNIP!] > The error I get is this: > > Traceback (most recent call last): > File "F:\wxComTool9.5.py", line 1638, in CommandCallback > self.SendCommand(self.selection, self.arguments) > File "F:\wxComTool9.5.py", line 145, in SendCommand > self.ProcessCommand(command, parameters) > File "F:\wxComTool9.5.py", line 1295, in ProcessCommand > for i in range(len(parameters[2])): > IndexError: list index out of range > > I just don't see a problem (other than the error that I keep getting! ;-) > ) > > --vicki Double-check your parameters variable. It looks like it's got less than 3 elements. You may have slipped up and meant "2nd element in parameter," which would be parameter[1]. --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From xxjac88xx at comcast.net Wed Dec 3 17:21:02 2003 From: xxjac88xx at comcast.net (Jacques) Date: Wed Dec 3 17:21:00 2003 Subject: [Tutor] well i just read the first timers thing Message-ID: <003201c3b9eb$bc9ced80$b5422444@yourw92p4bhlzg> Well, I see what they are saying, but I must of thought wrong. I thought these programs were really just used to help, but since they were on the internet and so easy to get to I knew they weren't what I was looking for. But what kind of programs can you make with Python? I just need some help with finding out what Python really is IN PLAIN ENGLISH. Haha, well thank you a lot for reading this!! I hope I get an answer sooner than later. Bye -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031203/31f6668b/attachment.html From xxjac88xx at comcast.net Wed Dec 3 17:23:31 2003 From: xxjac88xx at comcast.net (Jacques) Date: Wed Dec 3 17:23:31 2003 Subject: [Tutor] oops Message-ID: <004d01c3b9ec$16b30fc0$b5422444@yourw92p4bhlzg> I meant i really thought these programs were used to Hack. Anyways, i'll be checking my email to see if anyone says anythin to me. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031203/54a7e99a/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Dec 3 17:31:21 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 3 17:31:31 2003 Subject: [Tutor] Newbie: "Global" vars across modules In-Reply-To: <06738462136C054B8F8872D69DA140DB01C08BB5@corp-exch-1.pjinet.com> Message-ID: On Wed, 3 Dec 2003, Alan Trautman wrote: > My favorite method, from a discussion on this list is to create a module > and import it into all modules that need access. I name it > myappname_globals.py and it contains things like database name, debug > level, and other constants that might need changing. A config file is > the other option I use if there is a lot to configure. If debug level is > the only reason a command line argument is safest. > > This is the one of the very few cases where I like FROM > myappname_globals.py IMPORT *. this means that the variable names are > the same in every case. Hi Alan, Be careful with 'from foo import *'. The variable names are the same here, but the values will not necessarily be the same. For example, let's say we have three files: globals.py, a.py, and b.py ### """globals.py""" X = 42 ### ### """a.py""" from globals import * def setX(): global X X = 17 ### ### """b.py""" import globals def setX(): globals.X = 17 ### The second form, in 'a.py', is error prone: it does set X to by 17 throughout the 'a' module, but that value is limited to the module. That is, the following program: ### from globals import * import a a.setX() print X ### should still print 42. If we treat our global variables as constants, this isn't a problem --- it's when we start assigning to globals that this Bad Thing can happen. 'b.py' is more in spirit with the way that global variables work, and should avoid any surprises. ### import globals import b b.setX() print globals.X ### should do what you expect. This being said: avoid global variables if you can! *grin* But are you sure you're not reinventing the wheel? The 'logging' module: http://python.org/doc/current/lib/module-logging.html already provides a way of distinguishing debugging messages based on a set of log levels (DEBUG, INFO, WARNING, ERROR and CRITICAL). With the 'logging' module, your program snippets: > --begin gvars.py-- > # Debug Level (0=NONE, 1=Normal, 2=Extended, 3=Verbose) > debug_level = 2 > > > --myFunctions.py-- > def ftest(): > if (debug_level = 3): > print "VERBOSE DB: This is a verbose statement" > return 1 can be translated as: ### --begin gvars.py-- import logging logging.getLogger().setLevel(logging.INFO) --myFunctions.py-- import logging def ftest(): logging.getLogger().debug("This is a verbose statement") return 1 ### and 'logging' is pretty full featured already, so unless you're just trying to learn how to use global variables, I'd recommend using the 'logging' module --- it's quite handy. Good luck to you! From tpc at csua.berkeley.edu Wed Dec 3 17:35:51 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Dec 3 17:35:58 2003 Subject: [Tutor] total beginner!!! In-Reply-To: <001901c3b9ea$6762a630$b5422444@yourw92p4bhlzg> Message-ID: <20031203141850.B97685-100000@localhost.name> hi Jacques, so was I up until 8 months ago, a newbie just like you, and then I read Danny Yoo's "A Quick Introduction to Python" and am now an upper low-level newbie ;-) I have not hacked into the FBI computers because I don't want to go to jail, and I want to use a computer after I get out ;-) A computer program is a series of instructions to the Central Processing Unit, like a simple: print "Hello World" will say "Hello World" to your screen. You can get started by downloading and installing Python if you are on Windows, or it comes standard with most distributions of Linux. If you want to know stuff they don't show you on television, the super 53/ References: <06738462136C054B8F8872D69DA140DB01C08BB5@corp-exch-1.pjinet.com> Message-ID: <2346.192.207.104.221.1070491535.squirrel@webmail.harlekin-maus.com> > Hi Alan, > > > Be careful with 'from foo import *'. The variable names are the same > here, but the values will not necessarily be the same. For example, let's > say we have three files: globals.py, a.py, and b.py [SNIP!] > If we treat our global variables as constants, this isn't a problem --- > it's when we start assigning to globals that this Bad Thing can happen. [SNIP!] > This being said: avoid global variables if you can! *grin* I prefer the "from globals import *" simply because it saves the typing, as long as it _only includes constants_. I use a naming convention where constants are all-caps and tend to be prefixed (all colors prefixed with 'COL_' for example). Another use I have for constants is class-wide constants. For example: class CPU: MEM_SIZE = 0xFFFF def __init__(self): self.memory = [0] * CPU.MEM_SIZE You've got to be careful with this, however. In this example, I've just restricted myself to a MEM_SIZE for ALL CPU instances! If I needed CPU's to have a variable memory size, I would instead do the following: class CPU: def __init__(self, mem_size=0xFFFF): self.mem_size = mem_size self.memory = [0] * mem_size The benefit here is that I can change each CPU's memory size. The drawback is that I have an additional 'mem_size' attribute for every CPU instance. I strayed a bit from the globals-across-modules, but class-wide constants are another alternative to globals you can try. --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From glingl at aon.at Wed Dec 3 17:48:20 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed Dec 3 17:47:25 2003 Subject: [Tutor] Re: recursion question In-Reply-To: References: Message-ID: <3FCE6834.7060405@aon.at> Lee Harr schrieb: > def mult(m, n): > if n < 0: > return -mult(m, -n) > elif n == 0: > return 0 > elif n == 1: > return m > else: > return m + mult(m, n-1) > > > Now all we need to do is write a docstring and some regression tests > and we're all set :o) Hmm... , do you think my version would also pass your regression test? >>> def mult(m, n): if n < 0: return -mult(m, -n) elif n == 0: return 0 else: return m + mult(m, n-1) Regards, Gregor > > _________________________________________________________________ > Protect your PC - get McAfee.com VirusScan Online > http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From glingl at aon.at Wed Dec 3 17:53:00 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed Dec 3 17:52:02 2003 Subject: [Tutor] total beginner!!! In-Reply-To: <20031203141850.B97685-100000@localhost.name> References: <20031203141850.B97685-100000@localhost.name> Message-ID: <3FCE694C.309@aon.at> tpc@csua.berkeley.edu schrieb: >hi Jacques, so was I up until 8 months ago, a newbie just >like you, and then I read Danny Yoo's "A Quick Introduction to Python" > > Oh! Is this a document I've missed until now? Gregor >and am now an upper low-level newbie ;-) > From xxjac88xx at comcast.net Wed Dec 3 17:55:18 2003 From: xxjac88xx at comcast.net (Jacques) Date: Wed Dec 3 17:55:18 2003 Subject: [Tutor] curious Message-ID: <000e01c3b9f0$864ed9f0$b5422444@yourw92p4bhlzg> I have a question. I was wondering if learning python will help me when I want to get a job. I want to be an electrical engineer. Will program languages help? Someone please tell me if it will help with my future. I'm only 15, and I don't do that great in school. I hate school, and have to many reasons in my mind why learning some subjects in school is ridiculous. But college and electrical engineering I am going to put 110% into it. Because i want to have a good future and be wealthy. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031203/231b97d6/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Wed Dec 3 17:57:53 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 3 17:57:58 2003 Subject: [Tutor] well i just read the first timers thing In-Reply-To: <003201c3b9eb$bc9ced80$b5422444@yourw92p4bhlzg> Message-ID: On Wed, 3 Dec 2003, Jacques wrote: > Well, I see what they are saying, but I must of thought wrong. I thought > these programs were really just used to help, but since they were on the > internet and so easy to get to I knew they weren't what I was looking > for. Hi Jacques, So you're not interested in learning how to program because the materials are too easy to find? Hmmmm. Anyway, I think there's a misunderstanding here. We're here to help folks learn how to program computers. We do not advocate cracking into other people's machines, as that really makes the victim very unhappy. There's enough misery in the world, so why contribute to it? So if you're looking for that kind of material, you will not find it here. The "hacking" that we advocate is mostly based on: http://www.catb.org/~esr/faqs/hacker-howto.html and it's understandable if you've gotten confused by the terminology. > But what kind of programs can you make with Python? The web page: http://uselesspython.com shows a bunch of programs that folks have written using Python. They're relatively short, but all of them do something interesting. People have written arcade games in Python: http://pygame.org/ And scientists are using it as well: http://www.scipy.org/ It's somewhat hard to really pinpoint one particular thing. Python is a good general purpose language, used by all sorts of people, in both work and play. > I just need some help with finding out what Python really is IN PLAIN > ENGLISH. Python is a programming language that we use to communicate ideas to a computer. If there's a plan that we can think of, we can often express it in Python so that a computer can do it. There are tutorials on the Python.org web site that explain Python in detail: http://www.python.org/topics/learn/non-prog.html Good luck to you! From ac007 at bluewin.ch Wed Dec 3 18:07:30 2003 From: ac007 at bluewin.ch (Alexandre) Date: Wed Dec 3 18:07:34 2003 Subject: [Tutor] total beginner!!! References: <001901c3b9ea$6762a630$b5422444@yourw92p4bhlzg> Message-ID: <003001c3b9f2$3a000590$2101a8c0@Azbordation> Read this realy good (and free) tutorial : http://www.ibiblio.org/obp/thinkCSpy/ If you don't understand this one, someone else might point you to some more basic documentation on computers and information technologies. As for FBI hacking... i don't know... try to ask the CIA. Good luck. Alexandre ----- Original Message ----- From: Jacques To: tutor@python.org Sent: Wednesday, December 03, 2003 11:11 PM Subject: [Tutor] total beginner!!! Hello, I am a beginner. I mean I know absolutely nothing about python. I tried to read the tutorials, but I am sad to inform that I didn't understand anything. I don't understand what a script is, what this python language really does, or what a program is. I think a program is something that can be run on a computer, but I need help on were to really start. I know some one who used to hack onto the fbi site. I am trying to learn python so maybe i could do something like that. I want to be able to gather information that is not really shown on TV. I know this is illegal, but I hope I can get some help. I am not some one planning to do something wrong. I just want to see what isn't shown. I am a curious person. So, I can keep going on reasons and talk and talk and talk, but I would like to get to the point. Does anyone know where i should start? ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031204/cfd7679e/attachment.html From arkamir at softhome.net Wed Dec 3 18:26:38 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Wed Dec 3 18:26:47 2003 Subject: [Tutor] curious In-Reply-To: References: Message-ID: <1070493998.6548.4.camel@quercus> Jacques any knowledge you can gain now will be invaluable for you in any job, and since you don't like school you probably need another way to gain your math and logic skills which is basic stuff for any engineer. Python a great place to start, and not too hard. I'm only 14 and love it. I'm just finishing my first major project, and have learned a lot of valuable skill which they do not teach at school. I go to technology high school www.techhigh.org, but even there they dont teach much usefull stuff. Mark Twain said it best when he said "don't let schooling get in the way of your education" (or something like that.) From speno at isc.upenn.edu Wed Dec 3 18:58:51 2003 From: speno at isc.upenn.edu (John P Speno) Date: Wed Dec 3 18:58:55 2003 Subject: [Tutor] Handling SIGCHLD signal to kill zombie processes In-Reply-To: <2305CFC39C15AA4896E06E5C91C509EF02998339@VS2.hdi.tvcabo> References: <2305CFC39C15AA4896E06E5C91C509EF02998339@VS2.hdi.tvcabo> Message-ID: <20031203235851.GA11871@isc.upenn.edu> On Wed, Dec 03, 2003 at 07:02:27PM -0000, rafael.sousa wrote: > > Hi! > > I need to know what to write in a function that handles the SIGCHLD signal, in order to kill zombie processes that are left running. > > -> In C ANSI, what I do is start by specifying what function is going to handle the signal: > > signal(SIGCHLD, handleSIGCHLD); > > and then one handler that does the trick is: > > void handleSIGCHLD() { > int stat; > > /*Kills all the zombie processes*/ > while(waitpid(-1, &stat, WNOHANG) > 0); > } > > -> In Python, specifying the handler is easy: > > import signal > signal.signal(signal.SIGCHLD, handleSIGCHLD) > > What I don't know how to do is an equivalent to the C function above... How much help do you need? If you are looking for python's version of waitpid, you can find it in the os module: import os def handleSIGCHLD(): os.waitpid(-1, os.WNOHANG) On some unixes, you don't have to reap children if you ignore SIGCHLD. signal.signal(signal.SIGCHLD, signal.SIG_IGN) From alan.gauld at blueyonder.co.uk Wed Dec 3 19:33:12 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 3 19:32:21 2003 Subject: [Tutor] isinstance() evil? References: Message-ID: <004c01c3b9fe$32df90d0$6401a8c0@xp> > I've read a couple aricle here and there that isinstance() is generally a > bad idea. True, but... > I'm writing a small method used for debugging programs Writing debug code is not a normal thing to do - it's why we have debuggers, so that you don't normally need to! So normal coding practice does not apply, it would not be at all unusual to use things like isinstance() in debugging code. > I use isinstance() for this; it seems very straightforward to do this > recursively: > > Dump(thing): > ... Yep, that looks pretty reasonable for dumping a recursive data structure. Alan g From alan.gauld at blueyonder.co.uk Wed Dec 3 19:39:29 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 3 19:38:38 2003 Subject: [Tutor] Newbie: "Global" vars across modules References: <1599.172.22.1.1.1070487759.squirrel@mail.apixels.net> Message-ID: <009101c3b9ff$140cad40$6401a8c0@xp> > Here's my problem: I want to create a global variable that EVERY module > can see. Why? Because I like to define a "debug_level" variable to print > out debugging information. I usually recommend setting an environment variable at the operating system for this. That way each module can read the environment variable (using os.getenv) at runtime and you can change it without modifying the code. Alan g. From alan.gauld at blueyonder.co.uk Wed Dec 3 19:42:16 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 3 19:41:25 2003 Subject: [Tutor] Iterating with Range References: <10796.206.53.226.235.1070487263.squirrel@www.thepenguin.org> Message-ID: <009801c3b9ff$774c1620$6401a8c0@xp> > I am trying to iterate through a loop based on the length of a string. The > string will be something like this: > > FFFFFFFFFFFFFFFFFFFFFFFF // There are 24 > If the string is called parameters[2] why doesn't this work? Dunno, I didn't look that closely because my first thought was: > for i in range(len(parameters[2])): > port.write(parameters[2][i]) Why not just for c in parameters[2]: port.write(c) etc... Using an index here seems unnecessarily complex. Alan G. From alan.gauld at blueyonder.co.uk Wed Dec 3 19:46:55 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 3 19:46:02 2003 Subject: [Tutor] curious References: <000e01c3b9f0$864ed9f0$b5422444@yourw92p4bhlzg> Message-ID: <00b701c3ba00$1d922830$6401a8c0@xp> > I have a question. I was wondering if learning python > will help me when I want to get a job. I want to be > an electrical engineer. Will program languages help? Yes, in fact any electrical Engineering degree will definitely include a programming course. In fact my course had a programming element every year... > I hate school, and have to many reasons in my mind why > learning some subjects in school is ridiculous. Very few subjects are ridiculous. I ebven find stuff I learned in Latin class(and I thought that was truly ridiculous!) coming in useful nowadays, some 30 years later!!! > But college and electrical engineering I am going to put > 110% into it. That's fine, but start studying your math now because the bulk of electrical engineering is math... Alan G. From joddo at apixels.net Wed Dec 3 20:23:43 2003 From: joddo at apixels.net (Jeremy Oddo) Date: Wed Dec 3 20:16:41 2003 Subject: [Tutor] Newbie: 'Global' vars across modules In-Reply-To: References: <06738462136C054B8F8872D69DA140DB01C08BB5@corp-exch-1.pjinet.com> Message-ID: <2078.172.22.1.1.1070501023.squirrel@mail.apixels.net> > But are you sure you're not reinventing the wheel? The 'logging' > module: > > http://python.org/doc/current/lib/module-logging.html > Hey, thanks Danny! I didn't see that module. Looks like it will be perfect for my needs. Thanks for all the help. Jeremy From amonroe at columbus.rr.com Wed Dec 3 20:33:08 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Dec 3 20:24:37 2003 Subject: [Tutor] total beginner!!! In-Reply-To: <001901c3b9ea$6762a630$b5422444@yourw92p4bhlzg> References: <001901c3b9ea$6762a630$b5422444@yourw92p4bhlzg> Message-ID: <167-939898903.20031203203308@columbus.rr.com> > want to see what isn't shown. I am a curious person. So, I can keep > going on reasons and talk and talk and talk, but I would like to get > to the point. Does anyone know where i should start? Google search for the TCP/IP FAQ. Have you installed Python on your box and written a "Hello world" program yet? Alan From thinkuknowme2007 at yahoo.com Wed Dec 3 20:24:38 2003 From: thinkuknowme2007 at yahoo.com (Udz) Date: Wed Dec 3 20:24:47 2003 Subject: [Tutor] program still doesnt work Message-ID: <20031204012438.68496.qmail@web60206.mail.yahoo.com> hi, i tried what you said danny, and the program still doesnt work. any suggestions? i'd appreciate any help, thanks. Udz >Just checking up on this: what happens if you add the line: > > >### >raw_input("Program finished: press Enter to continue...") >### > > >at the very end of your program? I suspect that Windows is closing your >program down automatically. t's a common issue for console-based programs >on Windows, that your program may actually be running fine, but may simply >be finishing too quickly for you to see it. > >Many programs try to work around this window-closing feature by forcing a >prompt so that the user can see things. --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031203/1ff04030/attachment.html From littledanehren at yahoo.com Wed Dec 3 21:19:14 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Dec 3 21:19:20 2003 Subject: [Tutor] curious In-Reply-To: <000e01c3b9f0$864ed9f0$b5422444@yourw92p4bhlzg> Message-ID: <20031204021915.66198.qmail@web41808.mail.yahoo.com> Jacques wrote: > I have a question. I was wondering if learning > python will help me when I want to get a job. I want > to be an electrical engineer. Will program languages > help? Someone please tell me if it will help with my > future. I'm only 15, and I don't do that great in > school. I hate school, and have to many reasons in > my mind why learning some subjects in school is > ridiculous. But college and electrical engineering I > am going to put 110% into it. Because i want to have > a good future and be wealthy. Python is a very good language to learn in general and it's increasing its marketshare in buisness, but other languages are in greater use. If you want to be an engineer, you should probably learn CAD first (my highschool has a CAD class that I'm taking, but it might be more difficult for you to get access to CAD). AutoCAD, the most popular CAD program, uses Lisp for scripting, so you may want to learn that later (but not first because Lisp is really hard). But I really don't think you should be concentrating on learning some programming language when you're not doing too well in school. If you're trying to get into a good college, they're only going to look at your GPA, not how well you can program or how smart you actually are. If you don't get good grades, you'll just be at a community college or something around that level. So you really shouldn't learn Python if your goal is to become a wealthy engineer; you should get good grades. BTW AFAICT unless you want to go into management, you can't become that wealthly being an engineer. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From mlong at datalong.com Wed Dec 3 21:36:38 2003 From: mlong at datalong.com (mlong@datalong.com) Date: Wed Dec 3 21:36:47 2003 Subject: [Tutor] curious In-Reply-To: <20031204021915.66198.qmail@web41808.mail.yahoo.com> References: <000e01c3b9f0$864ed9f0$b5422444@yourw92p4bhlzg> <20031204021915.66198.qmail@web41808.mail.yahoo.com> Message-ID: <.141.149.188.210.1070505398.squirrel@datalong.com> > become a wealthy engineer; you should get good grades. > BTW AFAICT unless you want to go into management, you > can't become that wealthly being an engineer. How wealthy you become has little to do with your chosen career path and much to do with how well you understand how money works. If you are looking to learn how to program then python is a good language to learn and you will have a hard time finding a more helpful group of people than those on this list. Good Luck! Mike From littledanehren at yahoo.com Wed Dec 3 21:44:03 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Dec 3 21:44:08 2003 Subject: [Tutor] well i just read the first timers thing In-Reply-To: <003201c3b9eb$bc9ced80$b5422444@yourw92p4bhlzg> Message-ID: <20031204024403.17399.qmail@web41803.mail.yahoo.com> Jacques wrote: > Well, I see what they are saying, but I must of > thought wrong. I thought these programs were really > just used to help, but since they were on the > internet and so easy to get to I knew they weren't > what I was looking for. But what kind of programs > can you make with Python? I just need some help with > finding out what Python really is IN PLAIN ENGLISH. > Haha, well thank you a lot for reading this!! I hope > I get an answer sooner than later. Bye Python is a dynamically typed, multi-pardigmed, interperated programming language with many advanced functional and object orientated features including metaclass hacking and... That's what you've been hearing, right? Well, Python is just a general programming language. It can do pretty much anything. I'd say that it's one of the most flexible programming languages there are. Python isn't only for websites or text processing, as PHP and Perl are, and it's code can run on all operating systems (unless you try not to), unlike C or C++. It can be used for object-oriented programming like Smalltalk or functional programming like Haskell. Python is runs directly from the source code, making it great for fast development. Probably the only thing Python isn't good at is making programming languages; that's something that C will always be the best at because of its speed. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From xxjac88xx at comcast.net Wed Dec 3 21:44:48 2003 From: xxjac88xx at comcast.net (Jacques) Date: Wed Dec 3 21:44:48 2003 Subject: [Tutor] beginner Message-ID: <008401c3ba10$96068a80$b5422444@yourw92p4bhlzg> yes i have installed python. i have written "hello world!" i am using win xp which every1 says suks, but i can figure stuff out pretty well. Like instead of, DOS its command prompt, and i know how to copy/rename files using prompt. but still i dont know anythin. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031203/1aab1188/attachment.html From xxjac88xx at comcast.net Wed Dec 3 21:49:26 2003 From: xxjac88xx at comcast.net (Jacques) Date: Wed Dec 3 21:49:24 2003 Subject: [Tutor] command prompt ?? Message-ID: <00a101c3ba11$3b74da30$b5422444@yourw92p4bhlzg> "rename c:\windows\*.pwl c:\windows\*.zzz" how come that doesn't work wit win xp and command prompt?every time i put that in i get "The syntax of the command is incorrect." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031203/425ef343/attachment.html From tpc at csua.berkeley.edu Wed Dec 3 21:51:10 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Dec 3 21:51:23 2003 Subject: [Tutor] total beginner!!! In-Reply-To: <3FCE694C.309@aon.at> Message-ID: <20031203185045.L99418-100000@localhost.name> hi Gregor, yes here is a link to the document: http://mail.python.org/pipermail/tutor/2003-April/021731.html On Wed, 3 Dec 2003, Gregor Lingl wrote: > > > tpc@csua.berkeley.edu schrieb: > > >hi Jacques, so was I up until 8 months ago, a newbie just > >like you, and then I read Danny Yoo's "A Quick Introduction to Python" > > > > > Oh! Is this a document I've missed until now? > Gregor > > >and am now an upper low-level newbie ;-) > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rmangaliag at slu.edu.ph Wed Dec 3 22:35:02 2003 From: rmangaliag at slu.edu.ph (ali) Date: Wed Dec 3 22:30:12 2003 Subject: [Tutor] python vs php5 Message-ID: <002501c3ba17$99e76a00$da19a8c0@slu.edu.ph> i've heard that php5 will include declaration of attributes which are private, public and protected... aside from that interfaces which will be implemented by a class can also be created... in line with OO principles, wouldnt these features be good if implemented in python??? From littledanehren at yahoo.com Wed Dec 3 22:31:30 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Dec 3 22:31:34 2003 Subject: [Tutor] command prompt ?? In-Reply-To: <00a101c3ba11$3b74da30$b5422444@yourw92p4bhlzg> Message-ID: <20031204033130.6456.qmail@web41805.mail.yahoo.com> Jacques wrote: > "rename c:\windows\*.pwl > c:\windows\*.zzz" > how come that doesn't work wit win xp and command > prompt?every time i put that in i get "The syntax of > the command is incorrect." This isn't really related to Python, but it's probably because the Windows XP shell was significantly downgraded from the previous version. I suggest upgrading to Morphix GNU/Linux. A python script can probably be created with the same function. Something like: import os files = [x for x in os.listdir('c:\windows\') if x.endswith('.pwl')] for some_file in files: os.rename(r'c:\windows\'+some_file, r'c:\windows\'+some_file[:-4]+'.zzz') This is untested, though. Don't blame Python for being longer for this; shell scripts are always better for simple, low-level system interaction. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From christoffer81 at mail.dk Wed Dec 3 22:34:51 2003 From: christoffer81 at mail.dk (Christoffer Thomsen) Date: Wed Dec 3 22:33:58 2003 Subject: [Tutor] list with area calculation Message-ID: <3FCEAB5B.5060507@mail.dk> I want to make a program which calculates areas. And I want to select which kid of area calculation it should be from a list, but I just can't make it work. I am not surprise if it just some stupid mistake but I can't figure it out. #This program calculates areas print print "Welcome to calculation program" print def print_options() : print "options:" print " 'p' print options" print " 's' calculates square" print " 'r' calculates rectangle" print " 'p' calculates perimeter" print " 'c' calculates circle" print " 'q' quit program" def square(width): return width**2 def rectangle(width,height): return width*height def perimeter(width,height): return (width*2)+(height*2) def circle(radius): return 3.14*radius**2 choice = "p" while choice != "q": if choice == "s": width = input("Type width:") print "Area is: ", square(width) elif choice == "r": width = input("Type width:") height = input("Type height:") print "Area is: ", rectangle(width,height) elif choice == "p": width = input("Type width:") height = input("Type height:") print "Area is: ", perimeter(width,height) elif choice == "c": radius = input("Type radius:") print "Area is: ", circle(radius) elif choice != "q": print_options() choice = raw_input("option: ") From python at experiencedstudents.com Wed Dec 3 23:14:10 2003 From: python at experiencedstudents.com (Az) Date: Wed Dec 3 23:14:16 2003 Subject: [Tutor] stupid Q References: Message-ID: <001901c3ba1d$11f40ad0$6400a8c0@a0> Thanx a lot for taking your time explaning everything guys. Magnus i use vi editor to write scripts and as you know already you can just type :sh in vi and it will take you to the shell . it's more easier for me this way than Ctr+Z and "fg" PS. sorry for my english guys, it's not my native language ----- Original Message ----- From: "Magnus Lycka" To: "Az" ; Sent: Wednesday, December 03, 2003 2:33 PM Subject: Re: [Tutor] stupid Q Az wrote: > hi all > i am using python 2.2 on freebsd , the thing is i dont have GUI and use > only command line interface , so > how do i save a file from cli in the python's As Kalle said, you should normally (whether you use an IDE or not) write your code in an editor, and save it as a file. You can save any command line session in unix though. (This has nothing to do with python.) For this, you use the unix script command. Just as with Python, you end the script session by pressing Ctrl-D. www5:~> script x.txt Script started, file is x.txt > python Python 2.2.2 (#2, Feb 10 2003, 00:03:01) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello" Hello >>> [Ctrl-D] > [Ctrl-D]Script done, file is x.txt www5:~> more x.txt [This will show the same as you see above...] Naturally, you will have to edit out the leading '>>>' and extra lines of text to be able to run your interactive python code as a program. A more normal unix/linux/bsd command line session with code editing consists of either suspending your editor to run code, or to use several (virtual) terminal sessions. Unix is a multitasking OS after all, whether you use a GUI or not. You suspend your editor with Ctrl-Z and revive it with the 'fg' command. Like this: $ vi test.py [do some code editing, and save without quitting] Ctrl-Z Suspended (signal) $ python ./test.py [Your bugs become evident...] $ fg [you're back in the editor, fix and save, don't quit] Ctrl-Z Suspended (signal) $ python ./test.py Repeat until ready... (remember to use 'fg' to get back to your editor. If you start the editor again the normal way, after you left it with Ctrl-Z, you'll end up with several editor sessions running in parallel. Of course, you should exit the editor properly when you are done. If you try to log out with suspended jobs, the OS will tell you.) With Linux, you normally have several virtual consoles, that you switch between with Alt-Fx. Then you can edit (don't forget to save) in one console and run the code in another. That way you don't need to bother with suspending the editor session to run code. If you are not by the console, you can use something like the "screen" utility. Use "man screen" to figure out how. Of course, if you use a good editor, such as vi (or better: vim), you can run your python script from within the editor. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From fredm at smartypantsco.com Wed Dec 3 23:39:19 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Wed Dec 3 23:39:07 2003 Subject: [Tutor] list with area calculation In-Reply-To: <3FCEAB5B.5060507@mail.dk> Message-ID: <5.1.0.14.0.20031204153329.03891a40@192.168.1.1> Maybe it's late where you are, but did you notice that you have two entries for the letter 'p' ? Also 'perimeter' does not return an area, so you should not use print "Area is" ... :)) At 04:34 AM 4/12/03 +0100, Christoffer Thomsen wrote: >I want to make a program which calculates areas. And I want to select >which kid of area calculation it should be from a list, but I just can't >make it work. I am not surprise if it just some stupid mistake but I can't >figure it out. > >#This program calculates areas ... From christoffer81 at mail.dk Thu Dec 4 00:19:58 2003 From: christoffer81 at mail.dk (Christoffer Thomsen) Date: Thu Dec 4 00:19:04 2003 Subject: [Tutor] list with area calculation Message-ID: <3FCEC3FE.2080104@mail.dk> Yes you are right I am too tired.. I just want to finish 1 chapter in the tutorial every day. But tnx it works now --------------------------------------------------------------------------------------- Alfred Milgrom wrote: Maybe it's late where you are, but did you notice that you have two entries for the letter 'p' ? Also 'perimeter' does not return an area, so you should not use print "Area is" ... :)) At 04:34 AM 4/12/03 +0100, Christoffer Thomsen wrote: I want to make a program which calculates areas. And I want to select which kid of area calculation it should be from a list, but I just can't make it work. I am not surprise if it just some stupid mistake but I can't figure it out. #This program calculates areas ... From krazie_mu_boi at hotmail.com Thu Dec 4 00:32:09 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Thu Dec 4 00:32:15 2003 Subject: [Tutor] Flash Objects Message-ID: For those who don't kno, I'm using Livewires. How can i make an object look like they are flashing?I was trying this code: for i in range(10): circle(50, 60, 45, colour = Colour.red, filled = 1) circle(50, 60, 30, colour = Colour.white, filled = 1) time.sleep(0.5) circle(50, 60, 45, colour = Colour.blue, filled = 1) circle(50, 60, 30, colour = Colour.white, filled = 1) time.sleep(0.5) 50 is the x point, 60 is the y point, and 45 and 30 is the radii . Time.sleep(0.5) makes python do nothing for 0.5 seconds. Well, it didn't work out as i thought it would. It simply did nothing for 10 seconds, and then show me a blue circle (with white cirlce inside). _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From carroll at tjc.com Thu Dec 4 00:56:03 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 4 00:56:08 2003 Subject: [Tutor] isinstance() evil? In-Reply-To: <004c01c3b9fe$32df90d0$6401a8c0@xp> Message-ID: On Thu, 4 Dec 2003, Alan Gauld wrote: > Writing debug code is not a normal thing to do - it's why > we have debuggers, so that you don't normally need to! Well, this is playing with Chinese characters, so I can't just use print statements. My routine basically gives me the equivalent of a print statement, only using Tkinter, so I can see the character along with the other data in a structure. In addition to debugging, it also gives a quick and dirty way to give me output for a quick one-off program. Just like in a one-off you might have: [do lots of things to calculate a value for x] print x I can do a lot of stuff to look up a certain character, and then print the character and its associated data (pinyin romanization, English equivalent, and Unicode value if it's encoded in one of the other systems like GB or Big5). My main use for this is looking up a character and its pinyin equivalent when I have an MP3 with Chinese characters in the ID3 data, or an MP3 or video file with Chinese characters in the filename. > Yep, that looks pretty reasonable for dumping a recursive data > structure. Thanks. -- Terry Carroll Santa Clara, CA carroll@tjc.com From alan.gauld at blueyonder.co.uk Thu Dec 4 03:32:17 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 4 03:31:20 2003 Subject: [Tutor] curious References: <20031204021915.66198.qmail@web41808.mail.yahoo.com> Message-ID: <00e201c3ba41$2079a730$6401a8c0@xp> > AutoCAD, the most popular CAD program, uses Lisp for > scripting, so you may want to learn that later (but > not first because Lisp is really hard). I'd disagree with that. Lisp is very easy to learn provided you've nebver programmed in any other language. The problem is it is superficially very diffrent to, say Basic or Python. (But actually its really very similar to Python once you get beyond the parentheses...) > don't think you should be concentrating on learning > some programming language when you're not doing too > well in school. If you're trying to get into a good > college, they're only going to look at your GPA, And thats a good point. > BTW AFAICT unless you want to go into management, you > can't become that wealthly being an engineer. Depending on the locality most senior managers in engineering companies started out as engineers. (Certainly true of CEOs in both continental Europe and Japan). And engineers earn a lot more than bricklayers and plumbers almost everywhere :-) But equally most engineers resemble Dilbert more than they resemble Bill Gates or Larry Ellison... Alan G. (A "poor" electrical engineer) From alan.gauld at blueyonder.co.uk Thu Dec 4 03:37:39 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 4 03:36:42 2003 Subject: [Tutor] beginner References: <008401c3ba10$96068a80$b5422444@yourw92p4bhlzg> Message-ID: <00ff01c3ba41$e07217c0$6401a8c0@xp> > yes i have installed python. i have written > "hello world!" i am using win xp which every1 > says suks, Actually although its a popular pastime to knock Microsoft, XP is by far the best operating system they have produced and is far superior to things like MacOS 9, or CP/M. In many ways its better even than early Unix or VMS. Its got lots wrong with it too, especially the "broken" Home edition, but it is without any doubt the best Windows OS available. >... DOS its command prompt, and i know how to copy/rename > files using prompt. but still i dont know anythin. You know enough to get started in Python. Have patience and a little imagination and the rest will come. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Dec 4 03:44:24 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 4 03:43:27 2003 Subject: [Tutor] command prompt ?? References: <00a101c3ba11$3b74da30$b5422444@yourw92p4bhlzg> Message-ID: <010701c3ba42$d1ac3e40$6401a8c0@xp> > C:\> "rename c:\windows\*.pwl c:\windows\*.zzz" > > how come that doesn't work wit win xp and command prompt? You are not allowed to specify a path for the second filename. DOS would treat that as a COPY not a RENAME... So your command should be: C:\> rename c:\windows\*.pwl *.zzz HTH, Alan g. From alan.gauld at blueyonder.co.uk Thu Dec 4 03:51:57 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 4 03:51:00 2003 Subject: [Tutor] list with area calculation References: <3FCEAB5B.5060507@mail.dk> Message-ID: <010e01c3ba43$dfa0fa30$6401a8c0@xp> > make it work. I am not surprise if it just some stupid mistake but I > can't figure it out. > > choice = "p" > while choice != "q": > if choice == "s": > width = input("Type width:") > print "Area is: ", square(width) > elif choice == "r": > ... code snipped ... > elif choice != "q": > print_options() > choice = raw_input("option: ") You don't tell us what's going wrong! My initial thoughts include the fact that the last elif could just be an else, but otherwise, what is the problem? Alan G. From christoffer81 at mail.dk Thu Dec 4 04:28:33 2003 From: christoffer81 at mail.dk (Christoffer Thomsen) Date: Thu Dec 4 04:27:42 2003 Subject: [Tutor] list with area calculation In-Reply-To: <010e01c3ba43$dfa0fa30$6401a8c0@xp> References: <3FCEAB5B.5060507@mail.dk> <010e01c3ba43$dfa0fa30$6401a8c0@xp> Message-ID: <3FCEFE41.7030303@mail.dk> Well as Alfred Milgrom wrote, I had 2 entries of "p" defining something different. The Perimeter text is also changed to Length instead of Area. So yes 2 stupid mistakes. Alan Gauld wrote: >>make it work. I am not surprise if it just some stupid mistake >> >> >but I > > >>can't figure it out. >> >>choice = "p" >>while choice != "q": >> if choice == "s": >> width = input("Type width:") >> print "Area is: ", square(width) >> elif choice == "r": >>... code snipped ... >> elif choice != "q": >> print_options() >> choice = raw_input("option: ") >> >> > >You don't tell us what's going wrong! >My initial thoughts include the fact that the last >elif could just be an else, but otherwise, what is the problem? > >Alan G. > > > > From python at comber.cix.co.uk Thu Dec 4 06:12:58 2003 From: python at comber.cix.co.uk (Eddie Comber) Date: Thu Dec 4 06:14:17 2003 Subject: [Tutor] Pydoc Message-ID: Is it possible to use pydoc easily as a module rather than a command line script? E. From abc-100036 at apc.edu.ph Thu Dec 4 12:00:02 2003 From: abc-100036 at apc.edu.ph (abc-100036@apc.edu.ph) Date: Thu Dec 4 12:00:18 2003 Subject: [Tutor] Raw_input Questions Message-ID: <20031204170002.0C51366FA4@cerveza.apc.edu.ph> does anybody know the syntax for a raw_input wherein the typed input won't appear in the screen or the console. I specifically want to apply the syntax for a password entry. I dont want the typed password to be seen in the screen. Example, like typing a password in the password entry during login whenever linux starts... thnx!! -- Angelo Cruz CSIT-Computer Network Engineer Asia Pacific College ________________________________________________________________________________________ This email message was delivered to you by Asia Pacific College. Scanning and Virus Filtering is delivered by RAV Antivirus. For more information, please visit our website or email the system administrators at mailto:sysadmins@apc.edu.ph. From elh at outreachnetworks.com Thu Dec 4 12:20:17 2003 From: elh at outreachnetworks.com (Eric L. Howard) Date: Thu Dec 4 12:20:22 2003 Subject: [Tutor] Raw_input Questions In-Reply-To: <20031204170002.0C51366FA4@cerveza.apc.edu.ph> References: <20031204170002.0C51366FA4@cerveza.apc.edu.ph> Message-ID: <20031204172001.GA2186@outreachnetworks.com> At a certain time, now past [Dec.04.2003-05:00:02PM -0000], abc-100036@apc.edu.ph spake thusly: > does anybody know the syntax for a raw_input wherein the typed input won't > appear in the screen or the console. > > I specifically want to apply the syntax for a password entry. I dont want > the typed password to be seen in the screen. Example, like typing a password > in the password entry during login whenever linux starts... http://www.python.org/doc/current/lib/module-getpass.html ~elh -- Eric L. Howard e l h @ o u t r e a c h n e t w o r k s . c o m ------------------------------------------------------------------------ www.OutreachNetworks.com 313.297.9900 ------------------------------------------------------------------------ JabberID: elh@jabber.org Advocate of the Theocratic Rule From dyoo at hkn.eecs.berkeley.edu Thu Dec 4 12:54:48 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 4 12:54:56 2003 Subject: [Tutor] program still doesnt work In-Reply-To: <20031204012438.68496.qmail@web60206.mail.yahoo.com> Message-ID: On Wed, 3 Dec 2003, Udz wrote: > i tried what you said danny, and the program still doesnt work. any > suggestions? i'd appreciate any help, thanks. Hi Udz, Hmmm... I have to admit, then, that I'm baffled! Something must be happening, since you've mentioned that you see a window momentarily open and close up. Do you know what happens if you just run the program normally, without trying to make it an EXE? If you don't mind, can you also post up the program you've written to the mailing list, as well as the distutils script you've written? One of us here should then be able to duplicate the problem, and then be better able to help you fix it. My apologies! From dyoo at hkn.eecs.berkeley.edu Thu Dec 4 13:05:40 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 4 13:05:44 2003 Subject: [Tutor] Flash Objects In-Reply-To: Message-ID: On Wed, 3 Dec 2003, Leung Cris wrote: > For those who don't kno, I'm using Livewires. How can i make an object > look like they are flashing?I was trying this code: > > for i in range(10): > circle(50, 60, 45, colour = Colour.red, filled = 1) > circle(50, 60, 30, colour = Colour.white, filled = 1) > time.sleep(0.5) > circle(50, 60, 45, colour = Colour.blue, filled = 1) > circle(50, 60, 30, colour = Colour.white, filled = 1) > time.sleep(0.5) > > 50 is the x point, 60 is the y point, and 45 and 30 is the radii . > Time.sleep(0.5) makes python do nothing for 0.5 seconds. Well, it didn't > work out as i thought it would. It simply did nothing for 10 seconds, > and then show me a blue circle (with white cirlce inside). Hi Leung, Ah! Livewires itself has its own sleep() routine --- try: ### for i in range(10): circle(50, 60, 45, colour = Colour.red, filled = 1) circle(50, 60, 30, colour = Colour.white, filled = 1) sleep(0.5) circle(50, 60, 45, colour = Colour.blue, filled = 1) circle(50, 60, 30, colour = Colour.white, filled = 1) sleep(0.5) ### I tried it on my end, and it looks good. The reason you haven't been seeing any flashing with your original code is because the official time.sleep() function actually puts everything in Python to sleep --- including the graphic-updating part of the system! *grin* So the Livewires folks cooked up their own version of sleep() that still allows for the graphic subsystem to keep ticking. You have a knack for running into tricky things with Livewires. *grin* Keep bringing up your questions: they are great ones! For those who are interested in the internal working of Livewires, here's what they are doing with Tkinter: ### def sleep(secs): if _root_window == None: time.sleep(secs) else: _root_window.update_idletasks() _root_window.after(int(1000*secs), _root_window.quit) _root_window.mainloop() ### From venkatbabukr at yahoo.com Thu Dec 4 13:12:24 2003 From: venkatbabukr at yahoo.com (Venkatesh Babu) Date: Thu Dec 4 13:12:29 2003 Subject: [Tutor] Generating random numbers In-Reply-To: <00ff01c3ba41$e07217c0$6401a8c0@xp> Message-ID: <20031204181224.81345.qmail@web41406.mail.yahoo.com> Hi, I have a question related to generation of random numbers based on some probability distribution In my simulation program I have to generate random numbers based on same kind of distribution, say normal distribution, but for different independent purposes: like determining number of agents in a place, determination ages of each agent. So, there are more than one normal distributions, each having its own mean and variance. In such a situation I guess we should create "Random" objects corresponding to each purpose and call normalvariate function of these objects with the corresponding mean and variance. Is the above method proper or can we do away by just calling the normalvariate function given in the random module instead of creating "Random" objects. Thank you, Venkatesh __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Thu Dec 4 13:16:35 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 4 13:16:41 2003 Subject: [Tutor] Pydoc In-Reply-To: Message-ID: On Thu, 4 Dec 2003, Eddie Comber wrote: > Is it possible to use pydoc easily as a module rather than a command > line script? Hi Eddie, It should be possible, as it's implemented as a pure Python module. Out of curiosity, how are you planning to use it as a module? Talk to you later! From dyoo at hkn.eecs.berkeley.edu Thu Dec 4 13:27:21 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 4 13:27:26 2003 Subject: [Tutor] curious In-Reply-To: <00e201c3ba41$2079a730$6401a8c0@xp> Message-ID: On Thu, 4 Dec 2003, Alan Gauld wrote: > > AutoCAD, the most popular CAD program, uses Lisp for scripting, so you > > may want to learn that later (but not first because Lisp is really > > hard). > > I'd disagree with that. Lisp is very easy to learn provided you've > nebver programmed in any other language. The problem is it is > superficially very diffrent to, say Basic or Python. (But actually its > really very similar to Python once you get beyond the parentheses...) Hi Alan, I agree --- Lisp is actually quite nice! There's one book, in particular, that's really good: http://www.cs.berkeley.edu/~bh/simply-toc.html (Of course, I'm somewhat biased, given my former academic affilation. *grin*) But seriously, if you get the chance, take a look at 'Simply Scheme': it'll open your eyes to what a beginning computer programming course really should cover. The approach in Simply Scheme is simply excellent. Talk to you later! From magnus at thinkware.se Thu Dec 4 14:04:58 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Dec 4 14:05:04 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcHl0aG9uIHZzIHBocDU=?= Message-ID: Ali wrote: > i've heard that php5 will include declaration of attributes which are > private, > public and protected... aside from that interfaces which will be > implemented by > a class can also be created... > > in line with OO principles, wouldnt these features be good if implemented > in python??? I must admit that I don't have a problem with the way Python works with variable access. The subtle cues of _x and __y is simple, and good enough for me. With... class X: def __init__(self, x): self.__private = x x = X() ..you can cheat Python and access the private variable self.__private from the outside as x._X__private, but there is no way that you will do that by mistake. If you do it as a quick hack and later fail to notice it, you have very poor code reviewing practices, and will probably fail to see lots of semantic and structural problems that are far more problematic than accessing a variable that you shouldn't. It's my impression that some languages, such as Java and C++, are designed to make it difficult for programmers to do "bad things" on purpose, and at the same times have shortcomings that repeatedly make programmers try to do these bad things to work around the stupid language. Python is rather designed to provide a flexibility that reduces the need to to "bad things", and let the programmers take responsibility for their own actions, and instead try to prevent them from making common mistakes. Thus the block structure by indenting and syntax error for "if a = 0:", while peeking at private variables is permitted and simple but made to stick out in the code. Interfaces are interesting, but the problem is to design them in such a way that we keep the flexibility of python. This is not trivial, and few python programmers would be satisfied with interfaces which was as restrictive as the typical interfaces of more static languages such as C++ and Java. This has been discussed in the Python community for at least five years, but obviously noone thought it was important enough to go ahead and make an implementation that was so good that it was accepted. There is a Python Enhancement Proposal under consideration for this. See http://www.python.org/peps/pep-0245.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tim.one at comcast.net Thu Dec 4 14:23:14 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu Dec 4 14:23:20 2003 Subject: [Tutor] Generating random numbers In-Reply-To: <20031204181224.81345.qmail@web41406.mail.yahoo.com> Message-ID: [Venkatesh Babu] > I have a question related to generation of random > numbers based on some probability distribution > > In my simulation program I have to generate random > numbers based on same kind of distribution, say normal > distribution, but for different independent purposes: > like determining number of agents in a place, > determination ages of each agent. So, there are more > than one normal distributions, each having its own > mean and variance. In such a situation I guess we > should create "Random" objects corresponding to each > purpose and call normalvariate function of these > objects with the corresponding mean and variance. > > Is the above method proper or can we do away by just > calling the normalvariate function given in the random > module instead of creating "Random" objects. Calling random.normalvariate(mu, sigma) for all purposes is fine (although calling random.gauss(mu, sigma) is faster -- gauss() was added after normalvariate(), and normalvariate() sticks around so that older programs using it can continue to get bit-for-bit identical results). The only really good reason to create your own Random objects is if you're running multiple threads, in which case having each thread use its own Random object makes it very much easier to get exactly reproducible (across distinct program runs) results. From ATrautman at perryjudds.com Thu Dec 4 14:57:36 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Thu Dec 4 14:57:40 2003 Subject: [Tutor] command prompt ?? Message-ID: <06738462136C054B8F8872D69DA140DB01C08BBF@corp-exch-1.pjinet.com> Jacques, .pwl files are windows passwords access lists. I suspect either you do not have the right permissions to rename them or windows does not allow them to be renamed. By renaming them you can force some non-managed windows systems to switch back to their default values and gain access. Your problems may come from this. Alan -----Original Message----- From: Jacques [mailto:xxjac88xx@comcast.net] Sent: Wednesday, December 03, 2003 8:49 PM To: tutor@python.org Subject: [Tutor] command prompt ?? "rename c:\windows\*.pwl c:\windows\*.zzz" how come that doesn't work wit win xp and command prompt?every time i put that in i get "The syntax of the command is incorrect." From alan.gauld at blueyonder.co.uk Thu Dec 4 15:44:56 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 4 15:43:51 2003 Subject: [Tutor] Raw_input Questions References: <20031204170002.0C51366FA4@cerveza.apc.edu.ph> Message-ID: <013f01c3baa7$7a026d30$6401a8c0@xp> > I specifically want to apply the syntax for a password entry. I dont want > the typed password to be seen in the screen. Example, like typing a password > in the password entry during login whenever linux starts... Use the password module in Python. Its called getpass or passwd or something not entirely obvious but its definitely there. Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Dec 4 16:41:15 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 4 16:41:20 2003 Subject: [Tutor] popen's wierdness (on Win2K) In-Reply-To: <33678E78A2DD4D418396703A750048D45E6969@RIKER> Message-ID: On Tue, 2 Dec 2003, Branimir Petrovic wrote: > While attempting to get to know if and how can I run and preferably have > control over stdin and stdout/sterr streams of external cmd line > programs and utilities launched via Python's popen, I've stumbled on > this: Hi Branimir, Sorry for the late reply; looks like we got a barrage of messages on the list recently! *grin* It sounds like you may be running into some flow control issues. The Python Library Documentation mentions them slightly: http://www.python.org/doc/current/lib/popen2-flow-control.html If you're wondering why Python is doing things so weirdly, be assured that it's not unique to Python. Java programmers face similar pitfalls when calling external programs: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html and I think you're just running into similar issues, only in Python form. Anyway, there's an entry in the official Python FAQ that should help: http://www.python.org/doc/faq/library.html#how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output That FAQ entry mentions that child processes won't get killed until you call wait() on them; that probably explains why you're seeing those invisible processes still. It also provides a way to workaround the wackiness in popen2, so we recommend that you try their approach first and see if it fixes things. Good luck to you! From BranimirP at cpas.com Thu Dec 4 18:34:23 2003 From: BranimirP at cpas.com (Branimir Petrovic) Date: Thu Dec 4 18:34:30 2003 Subject: [Tutor] popen's wierdness (on Win2K) Message-ID: <33678E78A2DD4D418396703A750048D45E697F@RIKER> > -----Original Message----- > From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] > > Sorry for the late reply; looks like we got a barrage of > messages on the > list recently! *grin* Hi Danny, thanks for reply, "late" does not matter, answering counts! List is busy lately, and my question was neither very straightforward, nor was it appealing. > > It sounds like you may be running into some flow control issues. The > Python Library Documentation mentions them slightly: > > http://www.python.org/doc/current/lib/popen2-flow-control.html > Python does have lots of documentation doesn't it, and not all is in one place, nor is it where ("the fresh") one would expect it to be. Had seen a lot of it, but this particular piece - I missed. Weird and interesting, sad also as it clearly indicates that popen is not a proper scratch for my itch. > > Anyway, there's an entry in the official Python FAQ that should help: > > http://www.python.org/doc/faq/library.html#how-do-i-run-a-subp rocess-with-pipes-connected-to-both-input-and-output Following this link leads right to Pexpect - exact the right thing I know I need, the "thing" I know I can not have as it does not run on Windows:(( How frustrating... And all I wanted to do is to run and control various third party applications through Python. Apparently not a trivial requirement, but quite appealing thought nevertheless. Looks like Python wrapper for sql scripts and SQL*Plus will have to be shelved until such a time I am able to switch platform. > Good luck to you! That's the fallback I've been counting on;) Thanks again Danny! Branimir From arkamir at softhome.net Thu Dec 4 18:52:22 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Thu Dec 4 18:52:27 2003 Subject: [Tutor] curious Message-ID: <1070581941.6127.8.camel@quercus> http://www.catb.org/~esr/faqs/hacker-howto.html Thats what got me started. and then this is some cool stuff. http://www.catb.org/jargon/html/index.html then get yourself a better browser most notable www.mozilla.org and go here: news://alt.2600/ From joddo at apixels.net Thu Dec 4 20:16:27 2003 From: joddo at apixels.net (Jeremy Oddo) Date: Thu Dec 4 20:09:17 2003 Subject: [Tutor] Monitor CPU Usage and User Input Message-ID: <2281.172.22.1.1.1070586987.squirrel@mail.apixels.net> First off, I really appreciate this list. Finding Python info can be a little challenging, but this list makes it easier. Thanks! OK, now for my question :) Is there a *cross-platform* routine for checking CPU usage and user input? I'd like to write an app that stays quiet until the CPU usage drops really low and there's been no human typing or mousing away. I guess it's *similar* to a screen saver. Basically, I'd like my Python app to "spring into action" when no one is using the computer. Are there any modules that may help me out with this? Thanks, Jeremy From xxjac88xx at comcast.net Thu Dec 4 20:36:14 2003 From: xxjac88xx at comcast.net (Jacques) Date: Thu Dec 4 20:36:11 2003 Subject: [Tutor] Morphix GNU/Linux/unix Message-ID: <009001c3bad0$2bd1f5d0$b5422444@yourw92p4bhlzg> i keep hearing i should run from unix or linux and i also heard about morphix. can someone give me a site i would be able to download any of these from??i would like to boot them up from a cd. If that isn't possible i would like to run them anyway i can, but still have my win xp. i am running windows xp home. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031204/c34035a7/attachment.html From thomi at imail.net.nz Thu Dec 4 21:00:04 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Thu Dec 4 21:00:15 2003 Subject: [Tutor] Morphix GNU/Linux/unix In-Reply-To: <009001c3bad0$2bd1f5d0$b5422444@yourw92p4bhlzg> References: <009001c3bad0$2bd1f5d0$b5422444@yourw92p4bhlzg> Message-ID: <200312051500.07470.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Fri, 05 Dec 2003 14:36, Jacques wrote: > i keep hearing i should run from unix or linux and i also heard about > morphix. can someone give me a site i would be able to download any of > these from??i would like to boot them up from a cd. If that isn't possible > i would like to run them anyway i can, but still have my win xp. i am > running windows xp home. every tried using google? go to www.google.com and search for "morphix". You'll find what you're looking for. - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/z+am2tSuYV7JfuERAn8cAJ4qlPpQwfmsFzgBMOOAY9JRPIjRfgCdFEJL weLHih/tvMOc59+5NFEL3Qk= =z5Yx -----END PGP SIGNATURE----- From xxjac88xx at comcast.net Thu Dec 4 21:05:35 2003 From: xxjac88xx at comcast.net (Jacques) Date: Thu Dec 4 21:05:31 2003 Subject: [Tutor] morphix Message-ID: <00c601c3bad4$4547eac0$b5422444@yourw92p4bhlzg> Morphix ISO Morphix Game Morphix HeavyGUI Morphix KDE Morphix LightGUI which should i download?^^ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031204/07ca2d8d/attachment.html From xxjac88xx at comcast.net Thu Dec 4 21:14:09 2003 From: xxjac88xx at comcast.net (Jacques) Date: Thu Dec 4 21:14:06 2003 Subject: [Tutor] morphix again... Message-ID: <00e101c3bad5$77e8c610$b5422444@yourw92p4bhlzg> http://unc.dl.sourceforge.net/sourceforge/morphix/MorphixBase-0.4-1.iso is that a good download...? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031204/e13b88cc/attachment.html From missive at hotmail.com Thu Dec 4 21:35:24 2003 From: missive at hotmail.com (Lee Harr) Date: Thu Dec 4 21:35:29 2003 Subject: [Tutor] Re: recursion question Message-ID: >>def mult(m, n): >> if n < 0: >> return -mult(m, -n) >> elif n == 0: >> return 0 >> elif n == 1: >> return m >> else: >> return m + mult(m, n-1) >> >> >>Now all we need to do is write a docstring and some regression tests >>and we're all set :o) > >Hmm... , do you think my version would also pass your regression test? > > >>> def mult(m, n): > if n < 0: > return -mult(m, -n) > elif n == 0: > return 0 > else: > return m + mult(m, n-1) > def mult(m, n): if n == 0: return 0 if n == 1: return m if n < 0: p = abs(n) result = -1 * (m + mult(m, p-1)) return result return m + mult(m, n-1) def mult2(m, n): if n < 0: return -mult(m, -n) elif n == 0: return 0 elif n == 1: return m else: return m + mult(m, n-1) def mult3(m, n): if n < 0: return -mult(m, -n) elif n == 0: return 0 else: return m + mult(m, n-1) import unittest class TestMultFunction(unittest.TestCase): def setUp(self): self.this_mult = mult def test2positive(self): for n in range(1, 10): m = 20 - n self.assertEqual(self.this_mult(m, n), m*n) def test1positive1negative(self): for n in range(1, 10): m = -20 - n self.assertEqual(self.this_mult(m, n), m*n) def test2negative(self): for n in range(1, 10): m = -20 - n self.assertEqual(self.this_mult(m, -n), m*-n) def testmzero(self): m = 0 for n in range(-10, 10): self.assertEqual(self.this_mult(m, n), m*n) def testnzero(self): n = 0 for m in range(-10, 10): self.assertEqual(self.this_mult(m, n), m*n) def testlongs(self): for m in range(-10, 10): for n in range(-5, 5): lm = long(m) ln = long(n) self.assertEqual(self.this_mult(lm, ln), lm*ln) for n in range(5, -5, -1): lm = long(m) ln = long(n) self.assertEqual(self.this_mult(lm, ln), lm*ln) # All 3 fail this one pretty miserably... # # def testfloats(self): # for m in range(-100, 100): # for n in range(-50, 50): # fm = float(m)/10 # fn = float(n)/10 # self.assertEqual(self.this_mult(fm, fn), fm*fn) # # for n in range(50, -50, -1): # fm = float(m) # fn = float(n) # self.assertEqual(self.this_mult(fm, fn), fm*fn) # And this one too... # # def testintfloat(self): # for m in range(-10, 10): # for n in range(-50, 50): # fn = float(n)/10 # self.assertEqual(self.this_mult(m, fn), m*fn) # # for n in range(50, -50, -1): # fn = float(n) # self.assertEqual(self.this_mult(m, fn), m*fn) # But this seems to be ok # def testfloatint(self): for m in range(-100, 100): for n in range(-5, 5): fm = float(m)/10 self.assertEqual(self.this_mult(fm, n), fm*n) for n in range(5, -5, -1): fm = float(m) self.assertEqual(self.this_mult(fm, n), fm*n) class TestMult2Function(TestMultFunction): def setUp(self): self.this_mult = mult2 class TestMult3Function(TestMultFunction): def setUp(self): self.this_mult = mult3 if __name__ == '__main__': # you can use this simple style #unittest.main() # or this style for more detail suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestMultFunction)) suite.addTest(unittest.makeSuite(TestMult2Function)) suite.addTest(unittest.makeSuite(TestMult3Function)) unittest.TextTestRunner(verbosity=2).run(suite) _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From christoffer81 at mail.dk Thu Dec 4 22:04:04 2003 From: christoffer81 at mail.dk (Christoffer Thomsen) Date: Thu Dec 4 22:03:08 2003 Subject: [Tutor] curious In-Reply-To: <1070581941.6127.8.camel@quercus> References: <1070581941.6127.8.camel@quercus> Message-ID: <3FCFF5A4.3030502@mail.dk> I have a question.. I have tried ie6, MozillaFirebird1.6a and Mozilla1.5, but non of them showed all the characters in http://www.catb.org/jargon/html/introduction.html I use windows 98 se, Is there someone who now what I should to? Conrad Koziol wrote: >http://www.catb.org/~esr/faqs/hacker-howto.html > >Thats what got me started. > >and then this is some cool stuff. > >http://www.catb.org/jargon/html/index.html > >then get yourself a better browser most notable > >www.mozilla.org > >and go here: > >news://alt.2600/ > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From xxjac88xx at comcast.net Thu Dec 4 22:48:45 2003 From: xxjac88xx at comcast.net (Jacques) Date: Thu Dec 4 22:48:41 2003 Subject: [Tutor] unix platform Message-ID: <000a01c3bae2$aedd2690$b5422444@yourw92p4bhlzg> Does anyone know how to get a unix platform for free? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031204/8c0c82b7/attachment.html From christoffer81 at mail.dk Thu Dec 4 23:32:02 2003 From: christoffer81 at mail.dk (Christoffer Thomsen) Date: Thu Dec 4 23:31:09 2003 Subject: [Tutor] unix platform In-Reply-To: <000a01c3bae2$aedd2690$b5422444@yourw92p4bhlzg> References: <000a01c3bae2$aedd2690$b5422444@yourw92p4bhlzg> Message-ID: <3FD00A42.6070009@mail.dk> Well you can get linux distributions, which are based on unix here: http://www.linuxiso.org/ Jacques wrote: > Does anyone know how to get a unix platform for free? > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From venkatbabukr at yahoo.com Thu Dec 4 23:54:31 2003 From: venkatbabukr at yahoo.com (Venkatesh Babu) Date: Thu Dec 4 23:54:35 2003 Subject: [Tutor] Generating random numbers In-Reply-To: Message-ID: <20031205045431.17214.qmail@web41408.mail.yahoo.com> Hi, Just wanted to clarify my point once again. So, do u mean to say that in a single thread, the following sequence of calls are OK: random.gauss(50, 5) random.gauss(50, 5) ... Some code.... random.gauss(25, 4) random.gauss(25, 4) ... Some more code.... random.gauss(50, 5) random.gauss(50, 5) Because till now I was thinking that generation of random numbers following a probability distribution should maintain some history information. Thank you, Venkatesh --- Tim Peters wrote: > [Venkatesh Babu] > > I have a question related to generation of random > > numbers based on some probability distribution > > > > In my simulation program I have to generate random > > numbers based on same kind of distribution, say > normal > > distribution, but for different independent > purposes: > > like determining number of agents in a place, > > determination ages of each agent. So, there are > more > > than one normal distributions, each having its own > > mean and variance. In such a situation I guess we > > should create "Random" objects corresponding to > each > > purpose and call normalvariate function of these > > objects with the corresponding mean and variance. > > > > Is the above method proper or can we do away by > just > > calling the normalvariate function given in the > random > > module instead of creating "Random" objects. > > Calling random.normalvariate(mu, sigma) for all > purposes is fine (although > calling random.gauss(mu, sigma) is faster -- gauss() > was added after > normalvariate(), and normalvariate() sticks around > so that older programs > using it can continue to get bit-for-bit identical > results). > > The only really good reason to create your own > Random objects is if you're > running multiple threads, in which case having each > thread use its own > Random object makes it very much easier to get > exactly reproducible (across > distinct program runs) results. > __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From tim.one at comcast.net Fri Dec 5 00:36:22 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri Dec 5 00:36:25 2003 Subject: [Tutor] Generating random numbers In-Reply-To: <20031205045431.17214.qmail@web41408.mail.yahoo.com> Message-ID: [Venkatesh Babu] > Just wanted to clarify my point once again. > > So, do u mean to say that in a single thread, the > following sequence of calls are OK: > > random.gauss(50, 5) > random.gauss(50, 5) > ... Some code.... > random.gauss(25, 4) > random.gauss(25, 4) > ... Some more code.... > random.gauss(50, 5) > random.gauss(50, 5) Yes, that's what I thought you meant, and it's fine. > Because till now I was thinking that generation of > random numbers following a probability distribution > should maintain some history information. Virtually all methods of generating random variates following a particular distribution work by applying transformations to a uniform random float in 0.0 to 1.0. For example, to generate a random float uniformly from 1 to 5, take a random float uniformly from 0 to 1, multiply it by 4, then add 1. It doesn't need any history, it only needs to be given a uniform random float in 0 to 1 to work with. You can read the code in random.py to see that almost all the methods work "like that". Some are very subtle, and require difficult correctness proofs if you *really* want to know how they work. The gauss() method used by Python is briefly but nicely described here: http://en.wikipedia.org/wiki/Box-Muller_transform That page shows how to generate random *unit* normal variates given a source of random uniform variates in 0 to 1. Dealing with arbitrary mu and sigma is a trivial transformation beyond that (after you get it, multiply the random unit normal variate by sigma, then add mu). More detail can be found here: http://www.taygeta.com/random/gaussian.html As that page says , Finding transformations like the Box-Muller is a tedious process, and in the case of empirical distributions it is not possible. From alan.gauld at blueyonder.co.uk Fri Dec 5 02:58:07 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Dec 5 02:57:54 2003 Subject: [Tutor] unix platform References: <000a01c3bae2$aedd2690$b5422444@yourw92p4bhlzg> Message-ID: <01a501c3bb05$8502f520$6401a8c0@xp> > Does anyone know how to get a unix platform for free? You can use any Linux distibution, or try OpenBSD, NetBSD or Darwin (Apple's MacOS X without the GUI.) search google... Alan G From venkatbabukr at yahoo.com Fri Dec 5 03:42:20 2003 From: venkatbabukr at yahoo.com (Venkatesh Babu) Date: Fri Dec 5 03:42:26 2003 Subject: [Tutor] Generating random numbers In-Reply-To: Message-ID: <20031205084220.66693.qmail@web41401.mail.yahoo.com> Hi, Thanks very much!!! I went thru the file random.py and those links. My doubt is cleared. -Venkatesh --- Tim Peters wrote: > [Venkatesh Babu] > > Just wanted to clarify my point once again. > > > > So, do u mean to say that in a single thread, the > > following sequence of calls are OK: > > > > random.gauss(50, 5) > > random.gauss(50, 5) > > ... Some code.... > > random.gauss(25, 4) > > random.gauss(25, 4) > > ... Some more code.... > > random.gauss(50, 5) > > random.gauss(50, 5) > > Yes, that's what I thought you meant, and it's fine. > > > Because till now I was thinking that generation of > > random numbers following a probability > distribution > > should maintain some history information. > > Virtually all methods of generating random variates > following a particular > distribution work by applying transformations to a > uniform random float in > 0.0 to 1.0. For example, to generate a random float > uniformly from 1 to 5, > take a random float uniformly from 0 to 1, multiply > it by 4, then add 1. It > doesn't need any history, it only needs to be given > a uniform random float > in 0 to 1 to work with. > > You can read the code in random.py to see that > almost all the methods work > "like that". Some are very subtle, and require > difficult correctness proofs > if you *really* want to know how they work. > > The gauss() method used by Python is briefly but > nicely described here: > > > http://en.wikipedia.org/wiki/Box-Muller_transform > > That page shows how to generate random *unit* normal > variates given a source > of random uniform variates in 0 to 1. Dealing with > arbitrary mu and sigma > is a trivial transformation beyond that (after you > get it, multiply the > random unit normal variate by sigma, then add mu). > More detail can be found > here: > > http://www.taygeta.com/random/gaussian.html > > As that page says , > > Finding transformations like the Box-Muller is a > tedious process, > and in the case of empirical distributions it is > not possible. > __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Fri Dec 5 13:16:32 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 5 13:16:45 2003 Subject: [Tutor] Pydoc [pydoc.writedoc()] In-Reply-To: Message-ID: On Fri, 5 Dec 2003, Edward Comber wrote: > I just want to automatically generate HTML docs of my own modules. > > currently > > for item in targets: > args = pydoc_path + ' -w ' + target_dir + item > cmd = py_path + ' ' + args + ' > temp.txt' > print cmd > os.system(cmd) > > does the trick but os.system() opens a DOS box for each file it's > processing. I would like to do it more smoothly. Hi Edward, As far as I know, there's yet no formal documentation on using pydoc as a module --- I think it's intended usage was as a command line utility. But we can still kludge it. *grin* pydoc provides a function called writedoc(): ### >>> import pydoc >>> pydoc.writedoc('dir') wrote dir.html ### And like the command line utility, it should write the HTML into the current directory. It might be good to bring this up on the comp.lang.python newsgroups and see people are using pydoc like this enough that it should be documented and generalized. The HTML that's emitted does look a little odd; it's full of a bunch of HTML entities like ' '. Curious! I wonder why it does that. For example: """Return an alphabetized list of names  comprising (some of) the attributes
of the given object, and of attributes  reachable from it:
""" is a small portion of what pydoc emits. By the way, here's a quicky HTML parser to make it easier to see the content in there: ### >>> html = open('dir.html').read() >>> import HTMLParser >>> class MyParser(HTMLParser.HTMLParser): ... def handle_data(self, data): ... print data, ... >>> MyParser().feed(html) Python: built-in function dir dir (...) dir([object]) - list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes. ### Hope this helps! From johnm at rte.ie Mon Dec 1 12:17:51 2003 From: johnm at rte.ie (John Moylan) Date: Fri Dec 5 19:00:33 2003 Subject: [Tutor] threads In-Reply-To: References: Message-ID: <1070299071.29989.16.camel@localhost.localdomain> I found the following somewhere on the web a while back. I don't know who to attribute it too, but it is the best starting point I found for programming threads in Python. here goes: #!/usr/bin/env python import urllib, time import threading retrieveDoc = 1 numPings = 20 numThreads = 5 url = 'http://localhost/' class ping ( threading.Thread ) : def __init__ ( self, url, numPings, retrieveDoc=1 ) : self.url = url self.numPings = numPings self.retrieveDoc = retrieveDoc threading.Thread.__init__(self) def run ( self ) : StartTime = time.time() for i in range(self.numPings): page = urllib.urlopen ( self.url ) if self.retrieveDoc: page.read() page.close() EndTime = time.time() self.TotalTime = EndTime - StartTime if __name__ == '__main__' : threadList = [] for i in range(numThreads) : thread = ping( url, numPings, retrieveDoc ) threadList.append ( thread ) StartTime = time.time() for thread in threadList : thread.start() while threading.activeCount() > 1 : print ".", time.sleep(1) EndTime = time.time() TotalTime = EndTime - StartTime print TotalPings = 0 ThreadTime = 0 for thread in threadList : TotalPings = TotalPings + thread.numPings ThreadTime = ThreadTime + thread.TotalTime PingAvg = TotalPings / TotalTime ResponseAvg = ThreadTime / TotalPings print "Threads: ", numThreads print "Pings:", TotalPings print "Total time:", TotalTime print "Pings per second:", PingAvg print "Average response time (secs):", ResponseAvg ****************************************************************************** The information in this e-mail is confidential and may be legally privileged. It is intended solely for the addressee. Access to this e-mail by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Please note that emails to, from and within RT may be subject to the Freedom of Information Act 1997 and may be liable to disclosure. ****************************************************************************** From John_Dutcher at URMC.Rochester.edu Fri Dec 5 10:56:34 2003 From: John_Dutcher at URMC.Rochester.edu (Dutcher, John) Date: Fri Dec 5 19:00:42 2003 Subject: [Tutor] using global variables with functions Message-ID: Hello Tutor, Can you comment on this issue ? Using Python 2.3.1, I carefully import 'string' along with other modules. The interpreter will NOT let me use any 'string' functions in the code, (i.e. upper(), lower(), capitalize() etc.) It indicates no 'global string' defined. In a couple other scripts I coaxed it to let me use 'string.rstrip' but ONLY by doing away with a couple user functions I had positioned at the top of the script....and handling the same code 'inline'. I hate to be locked into that mode always. I assume there is some fundamental concept that relates to using your own 'defs', and how they confuse the interpreter and prevent it from recognizing the import of 'string'. The concept of having 'masked' it away in my own code arises I guess....but I have no variables named 'string' or named any of the 'string' functions either ????? Thanks, John Dutcher From TTA at accamail.com Mon Dec 1 02:41:07 2003 From: TTA at accamail.com (tt a) Date: Fri Dec 5 19:00:51 2003 Subject: [Tutor] Interface Message-ID: Hi, Basically, i am a beginner. I was wondering if Pyton has a GUI interface like VB to develope applications rather than coding in IDLE?? Thanks, TTA accamail is a service for members and students of the Association of Chartered Certified Accountants. http://www.accaglobal.com From thinkuknowme2007 at yahoo.com Fri Dec 5 18:19:26 2003 From: thinkuknowme2007 at yahoo.com (Udz) Date: Fri Dec 5 19:01:35 2003 Subject: [Tutor] program still doesnt work In-Reply-To: Message-ID: <20031205231926.77575.qmail@web60208.mail.yahoo.com> hey, well, when i just click on the original .py file, the python command line window pops up, then an application error: The instruction at "0x77fc9e82" referenced memory at "ox2049202c". The memory could not be "written". Click on OK to terminate the program Click on CANCEL to debug the program But if i click on the .pyc fleThis is wierd, because when i first started this program, i tried clicking on that file to see what would happen, and it came up in python command line just fine. i dont know what the problem is now. As Danny Yoo asked, i'll put up my code and my distutils script. I have to warn you though, this is not an advanced prgram, it basically does nothing. A friend was asking if she could see some of the writing pieces i've written (I write a lot), and i thought i would do it in a creative way. My goal is to make a little archive in which my friends can view my pieces. the program is not nearly finished. I just made the first part of it, which was to make sure the person knew me and to make them laugh a little as well. The program will ask you some questions, and you must answer accordingly. it's sorta stupid really. first of all, follow the simple instructions at the beggining, or this program will be a pain in the ass. It will ask your name, simply for retrieval purposes (i wanted to make the prgram a little more lifelike, and one way would be to address the user personally). It will ask you "You know what?", just answer "what?" it'll ask you that again. type what again. when it types it for the third time, u can either type "what" again, or type "shut up". (u wont get it, it's an inside joke). When it asks for my name, you can type in "Udz". When it asks for my birthday, type in 09/04/89. When it asks what 2 things I do best, put in "Computers, Writing". it will ask you to confirm your name. If you want, you can change what you typed earlier at this point. Thats as far as I have gotten. I was going to stat pasting essays and poems and stuff like that in, but i decided to try the py2exe because one of my friends wanted to see how far i had gotten. so here's the code: # -*- coding: cp1252 -*- def MultiLines (): print print print print ">>>>>>>>>>>>>>>>>>>WHAT I DID WITH MY FREE TIME<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" print "Well, basicallly, I got bored, and started writing this program. Yeah, I'm a" print "dork, but hey, the only other thing to do was hw, and that would just be" print "retarded. But I warn you; you have to know me very well to be able to listen to what i have to say in this program. So Goof and Peanut Butter, you're already" print "out. Actually,most people are. Actually, besides family, only 2 people get to do" print "this...kinda sad, but oh well. This starting off dialouge was just to provide " print "information about the program. The first rule: NEVER use any quotations like" print "commas, quotes, and ESPECIALLY exclamation marks. You can use question marks" print "when appropriate, I have programmed those in. Oh yeah, and no periods either, " print "those would just be a pain in the ass to program in.Also, I'll be talking to you" print "a lot through this program, so you can expect a crapload of questions. I will ask some random questions and some important ones. If you dont know which " print "questions to answer, notice that every question that i want you to answer is on a seperate line. Oh yeah, when you're answering a question, make sure that you" print "hit Enter before replying, or you'll have to type your answer all over again." print "Don't complain afterwards, I'v given you fair warning." def understand (): name = raw_input ("OK? type 'OK' if you understand my directions, and type 'I'm an idiot' if you don't understand.") input = raw_input () if input == "OK" or input == "ok" or input == "Ok": print "Good, now I know you can read!" elif input == "I'm an idiot": print "Well, duh, if you couldn't follow those instructions, you really are an idiot. Here, read it again:" print "Well, basicallly, I got bored, and started writing this program. Yeah, I'm a" print "dork, but hey, the only other thing to do was hw, and that would just be" print "retarded. But I warn you; you have to know me very well to be able to listen to what i have to say in this program. So Goof and Peanut Butter, you're already" print "out. Actually,most people are. Actually, besides family, only 2 people get to do" print "this...kinda sad, but oh well. This starting off dialouge was just to provide " print "information about the program. The first rule: NEVER use any quotations like" print "commas, quotes, and ESPECIALLY exclamation marks. You can use question marks" print "when appropriate, I have programmed those in. Oh yeah, and no periods either, " print "those would just be a pain in the ass to program in.Also, I'll be talking to you" print "a lot through this program, so you can expect a crapload of questions. I will ask some random questions and some important ones. If you dont know which " print "questions to answer, notice that every question that i want you to answer is on a seperate line. Oh yeah, when you're answering a question, make sure that you" print "hit Enter before replying, or you'll have to type your answer all over again." print "Don't complain afterwards, I'v given you fair warning." understand () else: print "[Sigh] How stupid can you people get? You can't even read. I'll ask you again." print "Well, basicallly, I got bored, and started writing this program. Yeah, I'm a" print "dork, but hey, the only other thing to do was hw, and that would just be" print "retarded. But I warn you; you have to know me very well to be able to listen to what i have to say in this program. So Goof and Peanut Butter, you're already" print "out. Actually,most people are. Actually, besides family, only 2 people get to do" print "this...kinda sad, but oh well. This starting off dialouge was just to provide " print "information about the program. The first rule: NEVER use any quotations like" print "commas, quotes, and ESPECIALLY exclamation marks. You can use question marks" print "when appropriate, I have programmed those in. Oh yeah, and no periods either, " print "those would just be a pain in the ass to program in.Also, I'll be talking to you" print "a lot through this program, so you can expect a crapload of questions. I will ask some random questions and some important ones. If you dont know which " print "questions to answer, notice that every question that i want you to answer is on a seperate line. Oh yeah, when you're answering a question, make sure that you" print "hit Enter before replying, or you'll have to type your answer all over again." print "Don't complain afterwards, I'v given you fair warning." understand () understand () print print print print print print "STARTING PROGRAM" print name = raw_input ("Press the Enter key twice.") input = raw_input () print "Please Wait........" name = raw_input ("Enter your Name(Please Capitalize):") input = raw_input () urname = input print "Please Wait........" name = raw_input ("--------------Program Ready to Run--------------Press Enter 2 times again.") input = raw_input () def countdown (s): if s == ".................................................................................": MultiLines () else: print s countdown (s + ".") countdown (".") print "PROGRAM INITIALIZED" print print print "HAVE FUN!!!!" print print print print "Hey people, what's up? So I guess you were wondering what this thing is, cuz I" print "never told you,and you were curious, right? yeah, and I was gonna say say " print "something, but I forgot it, so oh well." def newLine(): print def UKW1 (): name = raw_input ("You know what?") input = raw_input () if input == "what?" or input == "WHAT?" or input == "What?" or input == "what" or input == "WHAT" or input == "What": print "I'm cold" else: print "That's the wrong answer!!!!" UKW1 () UKW1 () def UKW2 (): name = raw_input ("You know what?") input = raw_input () if input == "what?" or input == "WHAT?" or input == "What?" or input == "what" or input == "WHAT": print "I'm still cold" else: print "That's the wrong answer!!!!" UKW2 () UKW2 () def UKW3 (): name = raw_input ("You know what?") input = raw_input () if input == "what?" or input == "WHAT?" or input == "What?" or input == "what" or input == "WHAT": print "This is getting retarded, so i won't do it anymore." elif input == "shut up" or input == "SHUT UP" or input == "Shut up": print "OK, OK I'll shut up....geez, what a temper....you're like Captain 0" else: print "That's the wrong answer!!!!" UKW3 () UKW3 () print "Well, I guess I'm here because I have a story to tell. At least that's what" print "I think. And the only story I know is my own. But before I start, I have to make sure youre allowed to read this." def WhatMyName1 (): name = raw_input("Soooo......Whats my name?") input = raw_input () if input == "Uddit" or input == "UDDIT" or input == "uddit" or input == "Udz" or input == "UDZ" or input == "udz": print "Alright, good job, on to the next question." else: print "OH MY GOD!!! You don't even know my name, and you were trying to play this game??" print "YOU LOSE!!!!!!!" closefunction () def closefunction (): name = raw_input("This window will not close by itself, you have to hit close yourself. Sorry to all the lazy people out there") input = raw_input () if input == None: closefunction () else: closefunction () WhatMyName1 () def WhatBirthday1 (): name = raw_input ("What's my birthday? Answer in mm/dd/yy format.") input = raw_input () if input == "09/04/89" or input == "9/4/89": print "Wow, maybe you do know me. But then again, maybe not...." else: print "See, you don't know me. But i understand, you could've just screwed up typing. I'll give you one more chance....." WhatBirthday2 () def WhatBirthday2 (): name = raw_input ("What's my birthday? Answer in mm/dd/yy format.") input = raw_input () if input == "09/04/89" or input == "9/4/89": print "Wow, maybe you do know me. But then again, maybe not...." else: print "Sorry, you lost, and if you don't know me, I wouldn't try again. You'll never make it through." closefunction () WhatBirthday1 () def WhatBest1 (): name = raw_input ("OK, this is the last question. What do I do best? (answer this in categories like: Math, Writing, Computers. Not specific like: programming, poetry, prose, Algebra. You get the point) Give me 2 categories, written like this: Category1, Category2.") input = raw_input () if input == "Music, Computers" or input == "MUSIC, COMPUTERS" or input == "music, computers" or input == "Computers, Music" or input == "COMPUTERS, MUSIC" or input == "computers, music" or input == "Writing, Music" or input == "WRITING, MUSIC" or input == "writing, music" or input == "Music, Writing" or input == "MUSIC, WRITING" or input == "music, writing" or input == "Writing, Computers" or input == "WRITING, COMPUTERS" or input == "writing, computers" or input == "Computers, Writing" or input == "COMPUTERS, WRITING" or input =="computers, writing": print "Wow, you are good. If you knew that, you obviously know me well. Nice, now you can experience whatever I wanted you to." else: print "Sorry, you got that question wrong, but since it's so hard, you have infinte times to get it right. Have fun!!" WhatBest2 () def WhatBest2 (): name = raw_input ("Alright, Last question, you've got infinite tries, good luck. What do I do best? (answer this in categories like: Math, Writing, Computers. Not specific like: programming, poetry, prose, Algebra. You get the point) Give me 2 categories, written like this: Category1, Category2.") input = raw_input () if input == "Music, Computers" or input == "MUSIC, COMPUTERS" or input == "music, computers" or input == "Computers, Music" or input == "COMPUTERS, MUSIC" or input == "computers, music" or input == "Writing, Music" or input == "WRITING, MUSIC" or input == "writing, music" or input == "Music, Writing" or input == "MUSIC, WRITING" or input == "music, writing" or input == "Writing, Computers" or input == "WRITING, COMPUTERS" or input == "writing, computers" or input == "Computers, Writing" or input == "COMPUTERS, WRITING" or input =="computers, writing": print "Wow, you are good. If you knew that, you obviously know me well. Nice, now you can experience whatever I wanted you to." else: print "You got it wrong, try again, maybe you'll get it someday, and be able to play my game. If you get annoyed enough, I might just tell you :)." WhatBest2 () WhatBest1 () def ConfirmName1 (): print "Alright, now that you've gotten past that little hitch(shouldn't have taken that long, you can move on. So it's ", urname, ", right?(Yes or No)" name = raw_input () input = raw_input () if input == "Yes" or input == "yes" or input == "YES": print "Cool. You can call me Uddit or Houdat or George or Bob, but I think that's it." elif input == "No" or input == "no" or input == "NO": name = raw_input ("Oh ok, then what's your name? (Capitalize please)") input = raw_input () urrealname = input ConfirmName2 () else: print "Jesus christ, can u follow instructions? I asked you something!!" ConfirmName2 () def ConfirmName2 (): print "Alright, let's make sure we didn't screw up. It's ", urrealname, ", right?(Yes or No)" name= raw_input () input = raw_input () if input == "Yes" or input == "yes" or input == "YES": print "Cool. You can call me Uddit or Houdat or George or Bob, but I think that's it." elif input == "No" or input == "no" or input == "NO": name = raw_input ("Oh ok, then what's your name? (Capitalize please)") input = raw_input () urrealname = input ConfirmName2 () else: print "Jesus christ, can u follow instructions? I asked you something!!" ConfirmName2 () ConfirmName1 () #Here, I have to Put in the list of things to do. DONT FORGET UDZ!!!!!!!! def WhatAboutGod (): print "WHAT ABOUT GOD?" print " By ME" print "God. Its one of the most argued topics in the world at any given time, so I just thought that Id add my argument to the pool. I think that God cant really be explained. I myself have had conflicting views over the years. The idea of a God or superior being has been around since the beginning of civilization. God is tied to us, and we to him. Instead of easing into the subject or trying to sneak up on it, Ill just say it right out; I dont believe that God exists. " print "There are so many people that are willing to (and already have) argue with me on the subject. I sometimes ask people why they believe in God. Their answers are pretty much all the same. The stupidest Ive ever gotten is What do you mean, Why do you believe in God? I believe in God because God exists. Thats actually a common one. Another is, Why I believe in God? Well, its been passed down in my religion for centuries, I have to carry on the belief. Its like they dont have a free mind of their own. They are following their religion. How can you possibly follow a religion if youre not sure that you even believe in it? The main reason I dont believe in God is that there is no proof. If anyone can give me solid proof that clearly proves that God exists, Ill readily believe it myself. But the fact is, no one can provide such proof. Most people in the world just believe because they were taught to do so, or because of religious obligations. I can relate to that. When I was little, I used to believe in God. I remember it. I also remember not ever having a reason to do so. I just believed because my parents and grandparents did. I went to religious ceremonies, participated in rituals and the like, but that was only because I was following everyone else; I wasnt using my own brain to form my own conclusions and my own beliefs. " print "Of the people that do believe of their own free will, none can really provide any proof. Many will claim that they believe because they experienced a traumatic experience through which God helped them. Others say that they feel clairvoyant vibrations, and can sense/talk to God. But when I ask for proof, theres no answer. One belief I find most interesting, and even most believable, is the belief that God exists only as an impartial judge of life. Most religions did start out with this belief at first, but then it got buried under the new religions. People came forward saying that they were the messengers of God, and started a new religion. This started occurring throughout the world. But the original idea was different. God is the creator of this world, the creator of life. He created all this, and is now watching us. He doesnt answer anyones prayers, he doesnt appear at beckoning, and he only steps in to alter things when he sees fit. Of course, I dont believe this theory either, but the belief that God is just an impartial judge makes much more sense than him being an all-powerful figure whom we should all respect. Yet some people still see him as an entity that controls peoples lives and destinies. " print "I totally disagree. Its impossible to have our lives controlled by another figure. We move with our own wills. We make our own decisions. The outcome of our life isnt in the hands of a superior being that decides if were good human beings or bad. The only person that can decide what you want to be is you, not some guy sitting up in the sky. He cant make our destinies for us; we can change what we want to do at any time. Our decisions could take us anywhere. One day we could be on our way to a high-class university like Yale, the next we could be out in the street smoking pot. Its our choice, not anyone elses. To me, God is a legend, thats it. To you, he could be something much more. We all have our own beliefs, and all we can do is express them." Well, that should give you some trouble. Now here is the distutil script that i wrote: #setup-script from distutils.core import setup import py2exe setup(name = "thing", scripts = ["thing.py"], ) small and simple, what i prefer. and in command prompt, this is the command i used to use py2exe: python setup-script.py py2exe well, i think thats it. i hope some one can get back to me with this ting soon, cuz its driving me crazy. have fun all! thanks in advance, Udz --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031205/e6ddd5dc/attachment-0001.html From alan.gauld at blueyonder.co.uk Fri Dec 5 19:16:07 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Dec 5 19:15:43 2003 Subject: [Tutor] using global variables with functions References: Message-ID: <003001c3bb8e$2534e700$6401a8c0@xp> > Using Python 2.3.1, I carefully import 'string' along with other > modules. > > The interpreter will NOT let me use any 'string' functions Can you show us an example. It seems OK for me with 2.3 on XP. Maybe seeing some broken code will reveal the reason. Alan g From alan.gauld at blueyonder.co.uk Fri Dec 5 19:20:29 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Dec 5 19:20:05 2003 Subject: [Tutor] Interface References: Message-ID: <003501c3bb8e$c0f66830$6401a8c0@xp> > Basically, i am a beginner. I was wondering if Pyton has a GUI > interface like VB to develope applications rather than coding in > IDLE?? There are several GUI interface builders but the code to make it function still needs to be written in the same way as VB event handlers are. However many(most?) Python programs are not GUIs so the need for a GUI builder is less. Also the Python GUI tooklits are higher level than the VB type one, there is less dependence on physical locations and sizes so its faster (albeit more challenging!) to build GUIs without drag n drop type GUIs. Some GUI builders you may like include Glade, BlackAdder, pyCard(??), and another from ActiveState that I've forgotten! There's also an old one for Tkinter called Specpy( an adapted SpecTcl) which is not supported any more but still worked last time I tried. Alan G. From dyoo at hkn.eecs.berkeley.edu Fri Dec 5 19:22:41 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 5 19:22:46 2003 Subject: [Tutor] program still doesnt work In-Reply-To: <20031205231926.77575.qmail@web60208.mail.yahoo.com> Message-ID: On Fri, 5 Dec 2003, Udz wrote: > well, when i just click on the original .py file, the python command > line window pops up, then an application error: > > The instruction at "0x77fc9e82" referenced memory at "ox2049202c". The > memory could not be "written". > > Click on OK to terminate the program > Click on CANCEL to debug the program Hi Udz, Ok, that's the error message we needed to see. There's something seriously wrong here, as the error message is not coming from your program, but from the Python runtime itself as it is interacting with Windows. Here's the good news: your program itself is probably perfectly fine. But here's the bad news: the problem is something else, and we'll have to hunt it down. A few possibilities include an out-of-control virus checker, or a corrupt Python installation. Let's first check to see if the Python installation is healthy. Udz, can you try reinstalling Python? Uninstall the current version of Python on your syste, and try using the "ActiveState" version of Python: http://activestate.com/Products/Download/Download.plex?id=ActivePython and see if it behaves better. If you install ActivePython, you'll have to reinstall Py2exe as well. Afterwards, try out your program again and see if you get a Windows error message. These sort of issues are always frustrating, but I hope we can get them fixed fast so you can share your program. Good luck! From krazie_mu_boi at hotmail.com Fri Dec 5 20:54:04 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Fri Dec 5 20:54:09 2003 Subject: [Tutor] Executable Message-ID: How do I turn python in to something like an Executable? Right now, I' m only typing in commands... _________________________________________________________________ MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : http://photos.msn.com.hk/support/worldwide.aspx From littledanehren at yahoo.com Fri Dec 5 21:02:27 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Fri Dec 5 21:02:31 2003 Subject: [Tutor] using global variables with functions In-Reply-To: Message-ID: <20031206020227.22567.qmail@web41811.mail.yahoo.com> "Dutcher, John" wrote: > > Hello Tutor, > > Can you comment on this issue ? > > Using Python 2.3.1, I carefully import 'string' > along with other > modules. > > The interpreter will NOT let me use any 'string' > functions in the > code, > (i.e. upper(), lower(), capitalize() etc.) > > It indicates no 'global string' defined. > > In a couple other scripts I coaxed it to let me use > 'string.rstrip' > but > ONLY by doing away with a couple user functions I > had positioned > at the top of the script....and handling the same > code 'inline'. > > I hate to be locked into that mode always. I assume > there is some > fundamental concept that relates to using your own > 'defs', and how > they confuse the interpreter and prevent it from > recognizing the > import of 'string'. The concept of having 'masked' > it away in my > own code arises I guess....but I have no variables > named 'string' > or named any of the 'string' functions either ????? > > Thanks, John Dutcher The string module is obsolete, you shouldn't use it. There are instead new string methods that can be used by treating the string as an object. Here's some code to demonstrate the string functions: >>> test_string = ' thisIs a String' >>> test_string.upper() ' THISIS A STRING' >>> test_string.lower() ' this is a string' >>> test_string.join(['a', 'b', 'c']) 'a thisIs a Stringb thisIs a Stringc' >>> test_string.split(' ') ['', '', 'thisIs', 'a', 'String'] >>> test_string.strip() #does both sides 'thisIs a String' and so on. Most of the methods in the string module are still available in the string methods (except some are at different names), but the constants, such as string.printable, are not. See string.__doc__ for more details. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From littledanehren at yahoo.com Fri Dec 5 22:04:34 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Fri Dec 5 22:04:38 2003 Subject: [Tutor] python vs php5 In-Reply-To: <002501c3ba17$99e76a00$da19a8c0@slu.edu.ph> Message-ID: <20031206030434.46603.qmail@web41807.mail.yahoo.com> ali wrote: > i've heard that php5 will include declaration of > attributes which are > private, > public and protected... aside from that interfaces > which will be > implemented by > a class can also be created... > > in line with OO principles, wouldnt these features > be good if implemented > in python??? In short, those principles are contrary to Python philosophy (if you can call it that). Most Python programmers believe that we should not make artificial barriers between parts of a program. Thre is no real reason to prevent programmers from doing this type of thing; at the worst it could be considered a small error. "We're all consenting adults here" has been used to summarize this idea. There's also the issue that in other languages that support private variables and constants in order to protect programmers, the limitations of the language often make programmers want to bypass these limitations. Nevertheless, it is still possible to create readonly and private variables by defining __getattr__ and __setattr__. There is probably some library out there that can be used to do this more easily, but it is not in the standard library. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From mwagman at charter.net Fri Dec 5 22:29:41 2003 From: mwagman at charter.net (Mike Wagman) Date: Fri Dec 5 22:30:14 2003 Subject: [Tutor] Executable In-Reply-To: References: Message-ID: <1070681377.2844.1.camel@24-159-248-140.jvl.wi.charter.com> Look up Py2exe for windows platforms or cxfreeze for Linux there is one for Mac too but don't know what it is called. On Fri, 2003-12-05 at 19:54, Leung Cris wrote: > How do I turn python in to something like an Executable? Right now, I' m only typing in commands... > > _________________________________________________________________ > MSN ???????????????????????? : http://photos.msn.com.hk/support/worldwide.aspx > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From klappnase at freenet.de Fri Dec 5 22:30:04 2003 From: klappnase at freenet.de (Michael Lange) Date: Fri Dec 5 22:36:44 2003 Subject: [Tutor] Executable In-Reply-To: References: Message-ID: <20031206043004.7f345f64.klappnase@freenet.de> On Fri, 05 Dec 2003 17:54:04 -0800 "Leung Cris" wrote: > How do I turn python in to something like an Executable? Right now, I' m only typing in commands... > If you are running linux or some other unix-like OS, store your code in a file "somefile.py", make this file executable with "chmod -v 755 somefile.py" and run it with "python somefile.py" from a shell. If you put something like #!/usr/bin/python (of course this must point to your python executable) or #!/usr/bin/env python at the first line of your script you can run it like any other program without the "python" command. If you are running windows you just need to double-click somefile.py in the explorer to run it. If you store your file with the ".pyw" extension instead of ".py" you can avoid the console window pop up when running your file, if you don't like this. If you meant to get a standalone executable for windows with no python install needed, there is a tool "py2exe"; I don't know much about this, I don't even know where to get it, but surely no problem to find it with google. However it seems like it can make quite a big executable out of a tiny python script and I've heard that it is not so easy to handle. Maybe it is worth to think about if you want to distribute your programs. I hope this helped Best wishes Michael From christoffer81 at mail.dk Sat Dec 6 02:42:52 2003 From: christoffer81 at mail.dk (Christoffer Thomsen) Date: Sat Dec 6 02:42:05 2003 Subject: [Tutor] save information in program Message-ID: <3FD1887C.2010401@mail.dk> I have made a few simple programs in python, but the problem is every time I add information in any program quit and restart the information is gone. For instance a program that saves tlf. numbers. I want to know what I should to so that the information is saved, and if I should wait until I have learned some more of python before I try this. From dyoo at hkn.eecs.berkeley.edu Sat Dec 6 03:52:25 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 6 03:52:32 2003 Subject: [Tutor] first program In-Reply-To: Message-ID: On Sat, 6 Dec 2003, RoT wrote: > I have coded my first non toy application since studying python for > about 2 months now. I would love to hear any comments or suggestions > regarding my coding style, methods, or suggestions of what I may need to > learn or brush up on, or what I may be doing completely wrong > (unpythonic). > > http://www.245t.com/spamkiller/SpamKiller.py Hi Kris, I'm reading through it now; very impressive so far! I'll try giving constructive criticism. Small nitpick: 'retreive' should be 'retrieve'. But I should be wary about correcting the spelling of others. There's some danger of the kettle calling the pot black. *grin* In some places, the program uses the 'string' module. For most purposes, its use is deprecated because a lot of that functionality now lives within each string as a string method. But don't worry: it's fairly easy to fix this. For example: string.find(sub[message], word) != -1 can be translated as: sub[message].find(word) != -1 I see that you're using map() to do some string stripping. I personally like map(). *grin* Some folks may be more comfortable with list comprehensions. Concretely, an expression like: map(string.strip, [' this ', ' is ', 'a ', ' test']) can be written as: [s.strip() for s in [' this ', ' is ', 'a ', ' test']] Personally, I wouldn't change this in your program. But it's good to know about list comprehensions, just in case you see it in other people's programs. For the most part, your functions have pretty good names. I want to focus on some of the ones near the bottom as a style nitpick. ### def addadd(lst): # add address def rmadd(lst): # remove address def pradd(lst): # print addresses ### I'd bite the bullet and make the names just slightly longer, to lessen the need for the comments. ### def add_address(lst): # add address def remove_address(lst): # remove address def print_address(lst): # print addresses ### I know, I'm being nitpicky! But addadd(), rmadd(), and pradd() might be potentially confusing because they can sound a lot like "add add", "remove add", and "product add". *grin* The change-option function 'chopt()' can be simplified by using a "dispatch" table technique. Here's a quick example to demonstrate the idea: ### def add(x, y): return x + y def sub(x, y): return x - y dispatch_table = {'+' : add, '-' : sub} while 1: action = raw_input("choose action: ") if action in dispatch_table: print dispatch_table[action](1009, 2009) ### getlist() is using the 'in' operator, but on a 1-tuple: ### def getlist(): # get list of setup options lst = [] while True: x = raw_input("\n>>> ") if x in ("",): continue if x in (".",): break else: lst.append(x) return lst ### This works, but it's simpler to do the direct comparison: ### def getlist(): # get list of setup options lst = [] while True: x = raw_input("\n>>> ") if x == "": continue if x == ".": break else: lst.append(x) return lst ### Then again, you may have been experimenting with allowing different choices for ending or ignoring input. But since you only have 1-tuples in there now, it might be good to switch back to the direct comparisons. Last comment for now: the last main() method might be a bit long; you may want to decompose it as you have the rest of the program. Anyway, I hope these comments help. Good luck to you! From intatia at paradise.net.nz Sat Dec 6 04:35:57 2003 From: intatia at paradise.net.nz (Intatia) Date: Sat Dec 6 04:37:50 2003 Subject: [Tutor] Executable In-Reply-To: <20031206043004.7f345f64.klappnase@freenet.de> References: <20031206043004.7f345f64.klappnase@freenet.de> Message-ID: <3FD1A2FD.8030107@paradise.net.nz> Michael Lange wrote: > On Fri, 05 Dec 2003 17:54:04 -0800 > "Leung Cris" wrote: > > >>How do I turn python in to something like an Executable? Right now, I' m only typing in commands... >> > > > If you are running linux or some other unix-like OS, store your code in a file "somefile.py", > make this file executable with "chmod -v 755 somefile.py" and I find " chmod +x somefile.py " does the job nicely. Although I've never gotten into chmod, chown and permissions much so...:) > run it with "python somefile.py" from a shell. > If you put something like > > #!/usr/bin/python (of course this must point to your python executable) or > #!/usr/bin/env python Mine is here for some weird reason, perhaps cause I'm running mandrake?:) #! /usr/local/bin/python > > at the first line of your script you can run it like any other program without the "python" command. > > If you are running windows you just need to double-click somefile.py in the explorer to run it. > If you store your file with the ".pyw" extension instead of ".py" you can avoid the console > window pop up when running your file, if you don't like this. > > If you meant to get a standalone executable for windows with no python install needed, > there is a tool "py2exe"; I don't know much about this, I don't even know where to get it, > but surely no problem to find it with google. > However it seems like it can make quite a big executable out of a tiny python script and I've > heard that it is not so easy to handle. Maybe it is worth to think about if you > want to distribute your programs. > > I hope this helped > > Best wishes > > Michael > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at blueyonder.co.uk Sat Dec 6 04:57:20 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 6 04:56:51 2003 Subject: [Tutor] Executable References: Message-ID: <005601c3bbdf$570da900$6401a8c0@xp> > How do I turn python in to something like an Executable? Right now, > I' m only typing in commands... If you type the commands into a file ending in .py you can double click it in explorer to run it just like any other program. You can give it to other people too if they have python installed. You can also use py2exe to bundle the python interpreter with your program and make it looke like a windows exe file, this meands you can give it to folks without python installed. But py2exe is not trivial to use, as udz is currently discovering! Alan g. From alan.gauld at blueyonder.co.uk Sat Dec 6 05:00:14 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 6 04:59:42 2003 Subject: [Tutor] using global variables with functions References: <20031206020227.22567.qmail@web41811.mail.yahoo.com> Message-ID: <005b01c3bbdf$beb32b20$6401a8c0@xp> > The string module is obsolete, you shouldn't use it. Actually its not obsolete, not yet, but it is deprecated which means you should be using the string methods rather than the module. But the string module is still available and still provides features not in the string objects. > and so on. Most of the methods in the string module > are still available in the string methods (except some > are at different names), but the constants, such as > string.printable, are not. Just so, which is why there is still legitimate use for the module. Alan g From alan.gauld at blueyonder.co.uk Sat Dec 6 05:04:36 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 6 05:04:06 2003 Subject: [Tutor] save information in program References: <3FD1887C.2010401@mail.dk> Message-ID: <006801c3bbe0$5af6ad90$6401a8c0@xp> > I have made a few simple programs in python, but the problem is every > time I add information in any program quit and restart the information > is gone. For instance a program that saves tlf. numbers. > I want to know what I should to so that the information is saved, You need to write the data to a file and then when you start the program read the data back from the file. See the files topic in my tutor for a starter... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From project5 at redrival.net Sat Dec 6 07:07:46 2003 From: project5 at redrival.net (Andrei) Date: Sat Dec 6 07:10:26 2003 Subject: [Tutor] Re: first program References: Message-ID: <1m67xx4wyrxfm$.19w5bh00rij4z.dlg@40tude.net> RoT wrote on Sat, 06 Dec 2003 17:52:46 +0800: > I wasn't aware of this. I found string.find in the 2.3 library reference so I didn't think it might > be deprecated. Where are these new methods documented? Paragraph 2.2.6.1 of the Library raference (Built-in objects -> Built-in types -> Sequence types -> String methods). It's deprecated at least for the part that is duplicated by the string methods. But it still contains some constants which are in no other spot. >> The change-option function 'chopt()' can be simplified by using a >> "dispatch" table technique. Here's a quick example to demonstrate the >> idea: >> >> ### >> def add(x, y): return x + y >> def sub(x, y): return x - y >> dispatch_table = {'+' : add, >> '-' : sub} > mmm nice work, I am going to have a play with this. I was thinking there must be a cleaner way of > doing this but settled on this method to get the program up and running. One of the nice things about Python is that you can put *anything* in dictionaries, including functions :). >> Last comment for now: the last main() method might be a bit long; you may >> want to decompose it as you have the rest of the program. > > I actually tried , about half way through the program, to break it up into modules, but after a > couple of wasted hours of chasing variable errors I gave up, not wanting to have a mass of globals > everywhere. Next time I should think about modular code at the begining of the process :) He's not talking about modules I think, but about the stuff you write at the bottom, after the __name__=='__main__'. The program is at 500 lines not too long to live in a single file. It's just that it's probably better to add some more functions split that stuff up. E.g. instead of asking "We have the ability to retreive 'n' numb... etc", you could make a function StoreTextFile() and you could have function GetUserLogin which gets password and the likes, etc. It makes it easier to follow the program flow. Btw, my eye fell on "if "y" in ans:". I don't think that's a very good test, e.g. if someone writes "no neverever nononono noway", it would be interpreted as "yes", while the user would obviously expect a no. Given the hint you give (y/n), it suggests that only the first letter is used. So I think you should do: if ans.strip().lower()[0]=="y" to test for a positive response: it's case insensitive and allows the user to use spaces first. But depending on how safe you want it to be, you might prefer to test for a no, so that anything that isn't a "n" (like a typo) defaults to the safe answer "y". It's interesting that a bit lower you use if raw_input("Logout and save changes? y/n\n>>> ") == "y": to test for yes, which is a very different method. You could actually make this into a function too, and add error checking in that function to make sure the user only is allowed to type "y/yes" or "n/no". -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From missive at hotmail.com Sat Dec 6 07:17:38 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Dec 6 07:17:44 2003 Subject: [Tutor] Re: first program Message-ID: >> string.find(sub[message], word) != -1 >> >>can be translated as: >> >> sub[message].find(word) != -1 > > >I wasn't aware of this. I found string.find in the 2.3 library reference so >I didn't think it mig >be deprecated. Where are these new methods documented? > http://python.org/doc/current/lib/string-methods.html The next page about strings is nice too (c-style formatting) http://python.org/doc/current/lib/typesseq-strings.html _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From david at graniteweb.com Sat Dec 6 09:44:11 2003 From: david at graniteweb.com (David Rock) Date: Sat Dec 6 09:47:02 2003 Subject: [Tutor] Executable In-Reply-To: <3FD1A2FD.8030107@paradise.net.nz> References: <20031206043004.7f345f64.klappnase@freenet.de> <3FD1A2FD.8030107@paradise.net.nz> Message-ID: <20031206144411.GB6682@wdfs.graniteweb.com> * Intatia [2003-12-06 22:35]: > > > Michael Lange wrote: > >On Fri, 05 Dec 2003 17:54:04 -0800 > >"Leung Cris" wrote: > > > > > >run it with "python somefile.py" from a shell. > >If you put something like > > > >#!/usr/bin/python (of course this must point to your python executable) or > >#!/usr/bin/env python > > Mine is here for some weird reason, perhaps cause I'm running mandrake?:) > #! /usr/local/bin/python This is not so strange. /usr/local/bin is a common place for "user added" applications. The main point is that the first line of the file must contain the path, whatever it is. This is also not specific to python. Any interpreter that you use can do the same trick; ksh, bash, perl, awk, etc. -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031206/02d3599f/attachment.bin From littledanehren at yahoo.com Sat Dec 6 10:35:50 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 6 10:35:55 2003 Subject: [Tutor] Re: first program In-Reply-To: Message-ID: <20031206153550.7183.qmail@web41812.mail.yahoo.com> RoT wrote: > mmm, I worked through 'python for non-programmers' > and then 'Learning Python' by Mark Lutz and David > Ascher, which I now realise was updated last in > 2000. I suppose I now need to locate some sort of > changelog to study or a more up to date tutorial. > Try learning from the official PSF Python tutorial. It's pretty good for beginners (I learned from it) and it is updated for every release of Python. > mmm, without any guidance on the matter I decided to > write into functions code that was to be > reused, and code that sort of stuck out on its own. > In hindsite I could have put it all into > functions and only have 10 or 20 'main()' lines but > I was not sure this would aid the readibility, > I presumed a more structural approach with a > functional/oo approach when needed for code reuse, > would be the way to go. Are you advocating putting > as much code as possible into functions? > That would be a good solution. The main() function often performs a narrow function within the range of possible things that the script can do as a library. The less is in the main function, the easier it is to make new functionality for programs. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From project5 at redrival.net Sat Dec 6 10:48:42 2003 From: project5 at redrival.net (Andrei) Date: Sat Dec 6 10:51:23 2003 Subject: [Tutor] Re: first program References: <1m67xx4wyrxfm$.19w5bh00rij4z.dlg@40tude.net> Message-ID: <9bpi50zziows.ra70vp4es6xz$.dlg@40tude.net> RoT wrote on Sat, 06 Dec 2003 21:36:46 +0800: >> Paragraph 2.2.6.1 of the Library raference (Built-in objects -> Built-in >> types -> Sequence types -> String methods). > > mmm, I worked through 'python for non-programmers' and then 'Learning Python' by Mark Lutz and David > Ascher, which I now realise was updated last in 2000. I suppose I now need to locate some sort of > changelog to study or a more up to date tutorial. String methods were introduced in v 2.0: http://www.python.org/2.0/new-python.html Btw, you might also be interested in the Python Quick Reference (http://rgruet.free.fr/). It labels things with different colors based on the version they were introduced in and is a very useful piece of info. >>>> Last comment for now: the last main() method might be a bit long; you may > mmm, without any guidance on the matter I decided to write into functions code that was to be > reused, and code that sort of stuck out on its own. In hindsite I could have put it all into That's a very good principle of course. But you really shouldn't have code blocks of 100+ lines because it's hard to see what's going on - maintenance problem. How long code blocks can maximally be depends on all kinds of factors, but I think that the amount you can see on a single screen is a useful rule of thumb - though obviously that depends on the size of the screen, size of the font, etc :). > functions and only have 10 or 20 'main()' lines but I was not sure this would aid the readibility, > I presumed a more structural approach with a functional/oo approach when needed for code reuse, It's not very hard to see that (to quote an example I gave in my previous message) all code for getting the login info from the user is really a piece that can stand on its own quite comfortably. I'm sure if you look at your code critically you can find more such pieces. > would be the way to go. Are you advocating putting as much code as possible into functions? Yep, but obviously code inside a function should belong together, it shouldn't be in a function just so that it's not written inside the main() loop. Functions also make it easier to browse your code if you have an editor which shows an outline of your classes/methods. > The thing is, that its > hard to find nice applications this size written in python to study, from what I have found they > are either scraps of code/functions or large, overly (complex) modular frameworks using a variety > of shell/languages Have you looked at uselesspython.com? I can also point you to two of my own programs: http://project5.freezope.org/mathter/index.html/# (almost entirely procedural programming, about 1k lines) and http://project5.freezope.org/kiki/index.html/# (wxPython based, about 500 lines). I'm not claiming they're perfect - in fact Kiki contains a function close to 100 lines long - but you can learn from mistakes just as well as you can learn from perfection :). -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From krazie_mu_boi at hotmail.com Sat Dec 6 13:37:39 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Sat Dec 6 13:37:43 2003 Subject: [Tutor] save information in program Message-ID: I was about to ask the same question too! I'm trying to make a high score thingy - similar to what you are talking 'bout. >From: Christoffer Thomsen >To: tutor@python.org >Subject: [Tutor] save information in program >Date: Sat, 06 Dec 2003 08:42:52 +0100 > >I have made a few simple programs in python, but the problem is >every time I add information in any program quit and restart the >information is gone. For instance a program that saves tlf. numbers. >I want to know what I should to so that the information is saved, >and if I should wait until I have learned some more of python >before I try this. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : http://photos.msn.com.hk/support/worldwide.aspx From xxjac88xx at comcast.net Sat Dec 6 15:17:23 2003 From: xxjac88xx at comcast.net (Jacques) Date: Sat Dec 6 15:17:27 2003 Subject: [Tutor] python beginner Message-ID: <000c01c3bc35$f6506ba0$b5422444@yourw92p4bhlzg> Does anyone know of any python programming site that could guide me to learn python in about a month? I also want to be able to write a program. Anyone have an ideas for a first program? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031206/929add27/attachment.html From missive at hotmail.com Sat Dec 6 15:31:10 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Dec 6 15:32:36 2003 Subject: [Tutor] Re: python beginner Message-ID: Please send only plain text to the list. >Does anyone know of any python programming site that could guide me to >learn python in about a month? I also want to be able to write a >program. Anyone have an ideas for a first program? http://python.org/topics/learn/index.html Please send only plain text to the list. _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From littledanehren at yahoo.com Sat Dec 6 16:51:22 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 6 16:51:27 2003 Subject: [Tutor] python beginner In-Reply-To: <000c01c3bc35$f6506ba0$b5422444@yourw92p4bhlzg> Message-ID: <20031206215122.36068.qmail@web41813.mail.yahoo.com> Jacques wrote: > Does anyone know of any python programming site that > could guide me to learn python in about a month? I > also want to be able to write a program. Anyone have > an ideas for a first program? A great tutorial that I learned from is at http://www.python.org/doc/current/tut/tut.html . Many people have said that this tutorial is too hard for beginners. A popular tutorial that's easier is at http://www.freenetpages.co.uk/hp/alan.gauld/ , but I don't really like it because it jumps around between Python, Basic, and Tcl. A good program to start out with could be a program to calculate the area of shapes. You could start out with a program to calculate the area of a two-by-two square. Then you could have the user input the value for the length of a side of the square. Then you could seperate the program into a function for finding the area of a square and a main() section. Eventually, you could do more advanced things such as other shapes (with certain things using the math module), making an option input from a file and then append the output to the file, making a advancednum class to hold positive floats and calculate things such as advancednum(5).square() to find the area of a square with a length of five, fitting the whole thing with a GUI, etc. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From littledanehren at yahoo.com Sat Dec 6 16:52:14 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 6 16:52:19 2003 Subject: [Tutor] python beginner Message-ID: <20031206215214.71342.qmail@web41803.mail.yahoo.com> Jacques wrote: > Does anyone know of any python programming site that > could guide me to learn python in about a month? I > also want to be able to write a program. Anyone have > an ideas for a first program? A great tutorial that I learned from is at http://www.python.org/doc/current/tut/tut.html . Many people have said that this tutorial is too hard for beginners. A popular tutorial that's easier is at http://www.freenetpages.co.uk/hp/alan.gauld/ , but I don't really like it because it jumps around between Python, Basic, and Tcl. A good program to start out with could be a program to calculate the area of shapes. You could start out with a program to calculate the area of a two-by-two square. Then you could have the user input the value for the length of a side of the square. Then you could seperate the program into a function for finding the area of a square and a main() section. Eventually, you could do more advanced things such as other shapes (with certain things using the math module), making an option input from a file and then append the output to the file, making a advancednum class to hold positive floats and calculate things such as advancednum(5).square() to find the area of a square with a length of five, fitting the whole thing with a GUI, etc. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From xxjac88xx at comcast.net Sat Dec 6 17:11:43 2003 From: xxjac88xx at comcast.net (Jacques) Date: Sat Dec 6 17:12:26 2003 Subject: [Tutor] abs(z) Message-ID: <3FD2541F.5040003@comcast.net> >>> a=3.0+4.0j >>> a.real 3.0 >>> a.imag 4.0 >>> abs(a) # sqrt(a.real**2 + a.imag**2) 5.0 >>> i understand why a.real = 3 and why a.imag = 4 but abs(a) MAKES NO SENSE... im very good in math when i lookd at it i figured in # sqrt(a.real**2 + a.imag**2) the "**" must equal half AKA .5 but then i tried >>> a=1.5+2j >>> a.real 1.5 >>> a.imag 2.0 >>> abs(a) # sqrt(a.real**2 + a.imag**2) 2.5 2.5 makes no sense??? also what does sqrt stand for? and correct me if im wrong but comment text after hash on same physical line doesn't do anythin to the program?? >>> a=3.5+5.0j >>> a.real 3.5 >>> a.imag 5.0 >>> abs(a) # sqrt(a.real**2 + a.imag**2) 6.103277807866851 what is up with all those decimal point numbers?? it looks like anythin wit a floatin point AKA number after decimal point stays the same BUT anythin witout a decimal point number or zero is divided by 2 plus the other number # if the other number has a decimal point in it. Can someone please explain this whole thing better to me? From xxjac88xx at comcast.net Sat Dec 6 17:27:55 2003 From: xxjac88xx at comcast.net (Jacques) Date: Sat Dec 6 17:28:00 2003 Subject: [Tutor] program? Message-ID: <3FD257EB.3070802@comcast.net> I dont know if you would call this a program. Please let me know if it qualifies to be a program. I just started with python and started programming. So, please bare with me. >>> # Perimeter of a rectangle equals sum of width times two, plus sum of lenth times 2. >>> width = 8 #inches >>> length = 1 #foot >>> (width * 2) + (length * 2) 18 >>> # answer is incorrect, because inches and feet are not same unit. How would I be able to fix that? From tim.one at comcast.net Sat Dec 6 17:32:29 2003 From: tim.one at comcast.net (Tim Peters) Date: Sat Dec 6 17:32:32 2003 Subject: [Tutor] abs(z) In-Reply-To: <3FD2541F.5040003@comcast.net> Message-ID: [Jacques] > >>> a=3.0+4.0j > >>> a.real > 3.0 > >>> a.imag > 4.0 > >>> abs(a) # sqrt(a.real**2 + a.imag**2) > 5.0 > >>> > i understand why a.real = 3 and why a.imag = 4 > but abs(a) MAKES NO SENSE... abs(a_complex) is the magnitude of a_complex in polar form. IOW, if you view (a_complex.real, a_complex.imag) as a point in the plane, abs is the distance from the origin (point (0, 0)) to a_complex. > im very good in math when i lookd at it i figured in # > sqrt(a.real**2 + a.imag**2) the "**" must equal half AKA .5 > but then i tried > >>> a=1.5+2j > >>> a.real > 1.5 > >>> a.imag > 2.0 > >>> abs(a) # sqrt(a.real**2 + a.imag**2) > 2.5 > > 2.5 makes no sense??? Sure it does. 1.5**2 = 2.25, and 2**2 = 4. The sum is 6.25. The square root of 6.25 is 2.5. > also what does sqrt stand for? square root > and correct me if im wrong but comment text after hash on same > physical line doesn't do anythin to the program?? Indeed, it's the hash that *makes* the text after it a comment . You're right, it (and the hash) have no effect on what the program does. > >>> a=3.5+5.0j > >>> a.real > 3.5 > >>> a.imag > 5.0 > >>> abs(a) # sqrt(a.real**2 + a.imag**2) 6.103277807866851 > > what is up with all those decimal point numbers?? It's the square root of 37.25, to the precision of your machine's floating-point hardware. From amonroe at columbus.rr.com Sat Dec 6 17:44:44 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Dec 6 17:35:42 2003 Subject: [Tutor] program? In-Reply-To: <3FD257EB.3070802@comcast.net> References: <3FD257EB.3070802@comcast.net> Message-ID: <33-690803573.20031206174444@columbus.rr.com> > >>> # Perimeter of a rectangle equals sum of width times two, plus sum > of lenth times 2. > >>> width = 8 #inches > >>> length = 1 #foot > >>> (width * 2) + (length * 2) > 18 > >>> # answer is incorrect, because inches and feet are not same unit. > How would I be able to fix that? The easy way: length = 12 #inches The hard way: Have the user enter the length as "1f", then attempt to detect whether or not their input has an "f" at the end of it - if it does, multiply it by 12... Alan From project5 at redrival.net Sat Dec 6 19:21:58 2003 From: project5 at redrival.net (Andrei) Date: Sat Dec 6 19:24:41 2003 Subject: [Tutor] Re: program? References: <3FD257EB.3070802@comcast.net> Message-ID: <17vzhf56gj1qj$.xulvp17xmtq3.dlg@40tude.net> Jacques wrote on Sat, 06 Dec 2003 17:27:55 -0500: > I dont know if you would call this a program. Please let me know if it Any piece of code qualifies as a program. Just a file containing "pass" is a program. It's just not particularly useful. > qualifies to be a program. I just started with python and started > programming. So, please bare with me. > >>> # Perimeter of a rectangle equals sum of width times two, plus sum > of lenth times 2. > >>> width = 8 #inches > >>> length = 1 #foot > >>> (width * 2) + (length * 2) > 18 > >>> # answer is incorrect, because inches and feet are not same unit. Python doesn't know units. If you tell it to add 3 #pears to 4 #apples and give you the result in #strawberries, it will happily say 7; #something is just a comment, not a unit. You have to implement code for unit conversion on your own. > How would I be able to fix that? You could do this quite easily by just picking one standard value (e.g. the meter since using SI units internally is the only sane thing to do if you don't want to end up shooting yourself in the foot - no pun intended) and defining constants like this (I don't define them very accurately, you might want to pull more decimals in there): >>> inch = 0.025 # 1 in is about 2.5 cm >>> foot = 0.30 # 1 ft is about 30 cm This way you could convert quite easily between archaic units, where in-memory everything is stored in a standard unit: >>> width = 8*inch # just write the unit as you'd usually do, # but add "*". 8 times one inch, which is really # what "8 in" means anyway. >>> length = 1*foot >>> perimeter = 2*(width+length) # in memory stored as meters >>> print "perimeter is", perimeter/foot, "ft" # give perimeter in ft perimeter is 3.33333333333 ft >>> 8*inch/foot # convert 8 in to ft; "/" works like "convert to" 0.66666666666666674 >>> 8*foot/inch # convert 8 ft to in 95.999999999999986 >>> 9.81/inch # gravity as in/s^2 392.39999999999998 There's also at least one Python module which can work with units, but I don't remember what it's called - anyway, it would be overkill for such simple cases. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From darnold02 at sprynet.com Sat Dec 6 20:42:30 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Sat Dec 6 20:41:03 2003 Subject: [Tutor] save information in program In-Reply-To: References: Message-ID: <9ED93B3E-2856-11D8-9BDC-000A95C4F940@sprynet.com> One relatively easy way to manage persistent data is to use the 'shelve' module. It allows you create a database file that you can use just like a regular dictionary: import shelve mydata = shelve.open('/Users/donarnold/temp/mydata') if mydata.has_key('highScore'): mydata['highScore'] += 100 else: mydata['highScore'] = 0 print 'current high score is', mydata['highScore'] mydata.close() Running this a couple times shows: Don-Arnolds-Computer:~ donarnold$ python score.py current high score is 0 Don-Arnolds-Computer:~ donarnold$ python score.py current high score is 100 Don-Arnolds-Computer:~ donarnold$ python score.py current high score is 200 Don-Arnolds-Computer:~ donarnold$ python score.py current high score is 300 Don-Arnolds-Computer:~ donarnold$ python score.py current high score is 400 HTH, Don On Dec 6, 2003, at 12:37 PM, Leung Cris wrote: > I was about to ask the same question too! I'm trying to make a high > score thingy - similar to what you are talking 'bout. > > >> From: Christoffer Thomsen >> To: tutor@python.org >> Subject: [Tutor] save information in program >> Date: Sat, 06 Dec 2003 08:42:52 +0100 >> >> I have made a few simple programs in python, but the problem is every >> time I add information in any program quit and restart the >> information is gone. For instance a program that saves tlf. numbers. >> I want to know what I should to so that the information is saved, and >> if I should wait until I have learned some more of python before I >> try this. >> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > _________________________________________________________________ > MSN 眈移枑鼎蠟郔庰譟褊蔆笰K蹈荂蠟腔眈えㄛ痄祫 : > http://photos.msn.com.hk/support/worldwide.aspx > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 2073 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031206/8d0ae5e9/attachment-0001.bin From littledanehren at yahoo.com Sat Dec 6 22:46:51 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 6 22:46:55 2003 Subject: [Tutor] save information in program Message-ID: <20031207034651.56600.qmail@web41804.mail.yahoo.com> Christoffer Thomsen wrote: > I have made a few simple programs in python, but the > problem is every > time I add information in any program quit and > restart the information > is gone. For instance a program that saves tlf. > numbers. > I want to know what I should to so that the > information is saved, and > if I should wait until I have learned some more of > python before I try > this. There are two ways that information can be saved: by "pickling" data, and by putting a few simple values in a text file seperated by commas or newlines. Let's take the first one: pickling. Say you have the script below: print 'Last time, you wrote', lasttime thistime = raw_input('What will the variable be next time? ') print 'You wrote', thistime lasttime = thistime except you want it to save the data. What you do is use the cPickle module. In the following replacement script, the data is saved in data.dat. import cPickle as p try: data = file('data.dat') #opens file data.dat except IOError: lasttime = '' #defaults to '' else: lasttime = d.load(data) #loads stuff from data.dat print 'Last time, you wrote', lasttime thistime = raw_input('What will the variable be next time? ') print 'You wrote', thistime datasave = file('data.dat', 'w') d.dump(thistime, datasave) If you want to just add to an existing thing that's saved, you can make a list holding stuff instead of a string. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From christoffer81 at mail.dk Sat Dec 6 23:42:59 2003 From: christoffer81 at mail.dk (Christoffer Thomsen) Date: Sat Dec 6 23:42:21 2003 Subject: [Tutor] save information in program In-Reply-To: <20031207034651.56600.qmail@web41804.mail.yahoo.com> References: <20031207034651.56600.qmail@web41804.mail.yahoo.com> Message-ID: <3FD2AFD3.2070503@mail.dk> Tnx for all the answers. I understand it now :-) From christoffer81 at mail.dk Sat Dec 6 23:47:50 2003 From: christoffer81 at mail.dk (Christoffer Thomsen) Date: Sat Dec 6 23:47:04 2003 Subject: [Tutor] python beginner In-Reply-To: <000c01c3bc35$f6506ba0$b5422444@yourw92p4bhlzg> References: <000c01c3bc35$f6506ba0$b5422444@yourw92p4bhlzg> Message-ID: <3FD2B0F6.4080603@mail.dk> I think this one is good: http://www.python.org/topics/learn/non-prog.html Jacques wrote: > Does anyone know of any python programming site that could guide me to > learn python in about a month? I also want to be able to write a > program. Anyone have an ideas for a first program? > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From krier115 at student.liu.se Sun Dec 7 06:50:14 2003 From: krier115 at student.liu.se (Kristoffer Erlandsson) Date: Sun Dec 7 06:50:32 2003 Subject: [Tutor] Monitor CPU Usage and User Input In-Reply-To: <2281.172.22.1.1.1070586987.squirrel@mail.apixels.net> References: <2281.172.22.1.1.1070586987.squirrel@mail.apixels.net> Message-ID: <3FD313F6.5040106@student.liu.se> Jeremy Oddo wrote: > First off, I really appreciate this list. Finding Python info > can be a little challenging, but this list makes it easier. > Thanks! > > OK, now for my question :) > > Is there a *cross-platform* routine for checking CPU usage and > user input? I'd like to write an app that stays quiet until > the CPU usage drops really low and there's been no human typing > or mousing away. I guess it's *similar* to a screen saver. > Basically, I'd like my Python app to "spring into action" when > no one is using the computer. > > Are there any modules that may help me out with this? I had this very same problem a while back. The short and discouraging answer I came up with was 'no' (I even tried asking in c.l.python without success). I ended up making the app only work on systems who had /proc file systems. Checking the information in /proc/stat and calculating usage is very simple and done in a few lines of code. However it gets complicated if you are interested in doing this for systems without a /proc file system. In some operating systems you have to call some C routines and so on. The easiest way is probably to find a c program which does this monitoring and make a wrapper around that code so you can use it in your Python program. I hope this helps a bit at least! Regards, -- Kristoffer Erlandsson http://errl.info From abli at freemail.hu Sun Dec 7 13:04:54 2003 From: abli at freemail.hu (Abel Daniel) Date: Sun Dec 7 13:04:47 2003 Subject: [Tutor] Re: program? In-Reply-To: <17vzhf56gj1qj$.xulvp17xmtq3.dlg@40tude.net> (project5@redrival.net's message of "Sun, 7 Dec 2003 01:21:58 +0100") References: <3FD257EB.3070802@comcast.net> <17vzhf56gj1qj$.xulvp17xmtq3.dlg@40tude.net> Message-ID: Andrei writes: > There's also at least one Python module which can work with units, but I > don't remember what it's called - anyway, it would be overkill for such > simple cases. Unum is one: http://home.tiscali.be/be052320/Unum.html -- Abel Daniel From dyoo at hkn.eecs.berkeley.edu Sun Dec 7 13:13:46 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Dec 7 13:13:52 2003 Subject: [Tutor] program? In-Reply-To: <3FD257EB.3070802@comcast.net> Message-ID: On Sat, 6 Dec 2003, Jacques wrote: > I dont know if you would call this a program. Please let me know if it > qualifies to be a program. I just started with python and started > programming. So, please bare with me. No problem! This looks fine. > >>> # Perimeter of a rectangle equals sum of width times two, plus sum > of lenth times 2. > >>> width = 8 #inches > >>> length = 1 #foot > >>> (width * 2) + (length * 2) > 18 > >>> # answer is incorrect, because inches and feet are not same unit. > > How would I be able to fix that? The last computation: width * 2 + length * 2 assumes that 'width' and 'length' are both using the same units. If they're different, we're going to get a wacky answer. One way to fix this is to make sure you're working in the same units all the time. Can you convert the feet to inches first? Good luck! From alan.gauld at blueyonder.co.uk Sun Dec 7 18:30:04 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Dec 7 18:30:08 2003 Subject: [Tutor] Re: first program References: <1m67xx4wyrxfm$.19w5bh00rij4z.dlg@40tude.net> Message-ID: <005501c3bd1a$0ad2eaa0$6401a8c0@xp> > Ascher, which I now realise was updated last in 2000. I suppose > I now need to locate some sort of > changelog to study or a more up to date tutorial. The best and most up to date tutorial, which everyone should read regardless of other books, is the one that comes with Python! It is updated with each release so includes new features as they become available. The Python documentation guys are the great unsung heros of the Python community IMHO! Any time a new feature is introduced in Python I go to the tutorial first then the PEP... Alan G. From alan.gauld at blueyonder.co.uk Sun Dec 7 18:38:15 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Dec 7 18:38:19 2003 Subject: [Tutor] python beginner References: <20031206215122.36068.qmail@web41813.mail.yahoo.com> Message-ID: <007c01c3bd1b$2fc5e190$6401a8c0@xp> > A great tutorial that I learned from is at > http://www.python.org/doc/current/tut/tut.html . Many > people have said that this tutorial is too hard for > beginners. It is almost incomprehensible for people who have never programmed before, but it is excellent for beginners to Python. > A popular tutorial that's easier is at > http://www.freenetpages.co.uk/hp/alan.gauld/ , but I > don't really like it because it jumps around between > Python, Basic, and Tcl. Important point here. I am trying to teach programming not Python. Python is just one language that I use because, I am trying to emphasise the point that the same concepts exist in all programming languages. Don't worry about the syntax, think about the structure and concepts. Once you finish my tutor you really should go through the official Python tutor(or Tcl one, or Basic one, or C, or Java or etc etc...) If you just want to learn to program in Python Josh C's tutor is better suited. But it will leave you with some jargon and concepts etc that you won't understand later. And a half way house which tries to teach Python and programming concepts is the 'How to Think like a CS' one... All are linked fom the non prog part of the Python web site. All serve slightly different purposes. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sun Dec 7 18:46:42 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Dec 7 18:46:46 2003 Subject: [Tutor] abs(z) References: <3FD2541F.5040003@comcast.net> Message-ID: <008c01c3bd1c$5e0585a0$6401a8c0@xp> > >>> a=3.0+4.0j First you are working with "complex numbers" or "imaginary numbers" THere are used to represent(among other things) 2D vectors. The first number is the real part and represents the vector segment in one dimension and the imaginary part(with a j) represents the segment in a perpendicular plane > >>> a.real > 3.0 > >>> a.imag > 4.0 > >>> abs(a) # sqrt(a.real**2 + a.imag**2) > 5.0 So abs() gets the absolute length of the vector which, using Pythagorus' theorem, is the square root(sqrt()) of the sum of the squares(**2) of the other two sides. [ In case you are curious about what imaginary numbers are used for, they crop up a lot in engineering and scientific calculations. For example they can be used to represent the electrical current and/or voltage in a complex electronic circuit. ] > comment text after hash on same physical line doesn't > do anythin to the program?? The interpreter doesn't do anything with it, it is literally just a comment to you and other programmers to explain what's going on. HTH, Alan G. From littledanehren at yahoo.com Sun Dec 7 19:01:06 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Dec 7 19:01:10 2003 Subject: [Tutor] Python vs. Lua Message-ID: <20031208000106.15799.qmail@web41807.mail.yahoo.com> I just heard about Lua, a scripting language with a minimalistic but highly extendable procedural syntax. It has only one number type that works as ints and floats, one type called a table that basically unifies dicts and lists, easily (but not necessarily) anonymous functions, and just normal strings. Pretty much anything can be used inline if it would make sense. Even though it's procedural, it can easily be used for object orientation using functions or tables (or both), and the lack of built-in object orientation actually makes it possible for it to be used in more ways than in Python. The only bad thing I can think of about Lua is the lack of many libraries, but there are still enough libraries to do anything I'd want to do. Are there any reasons why Python is better and I shouldn't use Lua instead? I think I might be missing some major flaw in the language. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From krazie_mu_boi at hotmail.com Sun Dec 7 20:20:16 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Sun Dec 7 20:20:20 2003 Subject: [Tutor] keys_pressed() Message-ID: Okay, there's some stupid problems in livewires ' function keys_pressed(). Both the button Esc and back space appears in the function even though I have only pressed it once. How do I access the real key function without using livewires? _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From magnus at thinkware.se Sun Dec 7 21:30:30 2003 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Dec 7 21:28:10 2003 Subject: [Tutor] Python vs. Lua In-Reply-To: <20031208000106.15799.qmail@web41807.mail.yahoo.com> Message-ID: <5.2.1.1.0.20031208031217.022ea910@www.thinkware.se> At 16:01 2003-12-07 -0800, Daniel Ehrenberg wrote: >I just heard about Lua, a scripting language with a >minimalistic but highly extendable procedural syntax. >It has only one number type that works as ints and >floats, one type called a table that basically unifies >dicts and lists, easily (but not necessarily) >anonymous functions, and just normal strings. Pretty >much anything can be used inline if it would make >sense. Even though it's procedural, it can easily be >used for object orientation using functions or tables >(or both), and the lack of built-in object orientation >actually makes it possible for it to be used in more >ways than in Python. I didn't get this part. How can it be used in more ways because it lacks OO? You don't have to use OO in Python. >The only bad thing I can think of >about Lua is the lack of many libraries, but there are >still enough libraries to do anything I'd want to do. I'm pretty sure you will soon run into situations where you'll be missing some nice Python library. I know I would. This autumn I've come to appreciate difflib, zipfile and a few other libs I never used before. >Are there any reasons why Python is better and I >shouldn't use Lua instead? There is no programming language which is best in every situation. As far as I understand, the strength of Lua is that it has a small footprint. It probably works better than Python in an embedded device with little RAM. Besides that, I don't know of any real Lua sweetspot. It's not very widely used it seems. Googling for "Python programming" I get about 1.5 million hits. Googling for "Lua programming" I get 13 000 hits, less than 1%. Looking at Freshmeat, I find 1276 Python projects and 19 Lua projects. >I think I might be missing >some major flaw in the language. OO? Wealth of libraries? Broad acceptance outside Brazil? ;) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From littledanehren at yahoo.com Sun Dec 7 22:00:47 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Dec 7 22:00:51 2003 Subject: [Tutor] Python vs. Lua In-Reply-To: <5.2.1.1.0.20031208031217.022ea910@www.thinkware.se> Message-ID: <20031208030047.82871.qmail@web41803.mail.yahoo.com> Magnus Lyck wrote: > I didn't get this part. How can it be used in more > ways > because it lacks OO? You don't have to use OO in > Python. > It's more flexible than a builtin OO because it doesn't force you to do one thing in particular. For example, it is much easier to use prototypes (as in the Self programming language) in Lua than in Python. > There is no programming language which is best in > every > situation. As far as I understand, the strength of > Lua > is that it has a small footprint. It probably works > better > than Python in an embedded device with little RAM. > Besides > that, I don't know of any real Lua sweetspot. > > It's not very widely used it seems. Googling for > "Python > programming" I get about 1.5 million hits. Googling > for > "Lua programming" I get 13 000 hits, less than 1%. > Looking > at Freshmeat, I find 1276 Python projects and 19 Lua > projects. > > OO? Wealth of libraries? Broad acceptance outside > Brazil? ;) There are far more projects that use C++ than Python, yet we're using Python. I forgot to mention that that Lua programs tend to be "flatter" than Python programs, something recommended by import this. The standard Lua distribution is written in pure ANSI C (like Python) with no real dependencies (unlike Python), so it is extremely portable and compiles anywhere tested without modification. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From kalle at lysator.liu.se Sun Dec 7 23:04:05 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Sun Dec 7 23:04:11 2003 Subject: [Tutor] Python vs. Lua In-Reply-To: <20031208000106.15799.qmail@web41807.mail.yahoo.com> References: <20031208000106.15799.qmail@web41807.mail.yahoo.com> Message-ID: <20031208040405.GF12373@i92.ryd.student.liu.se> [Daniel Ehrenberg] > Are there any reasons why Python is better and I shouldn't use Lua > instead? I think you can only answer this yourself. Go ahead, learn Lua and use it. After a while, you'll see which language you prefer and maybe even why. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From tim at johnsons-web.com Sun Dec 7 23:45:03 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Sun Dec 7 23:37:07 2003 Subject: [Tutor] Python vs. Lua In-Reply-To: <20031208040405.GF12373@i92.ryd.student.liu.se> References: <20031208000106.15799.qmail@web41807.mail.yahoo.com> <20031208040405.GF12373@i92.ryd.student.liu.se> Message-ID: <20031208044503.GA8749@johnsons-web.com> * Kalle Svensson [031207 19:19]: > [Daniel Ehrenberg] > > Are there any reasons why Python is better and I shouldn't use Lua > > instead? Disclaimer: Speaking of my own experiences and viewpoint - I program about equally in python and rebol. Rebol is more productive line for line than python, perhaps a factor of 3 / 2 ? *but* Python has more resources than rebol. so I do less of 'rolling my own' Also, programming in both gives me a better perspective. Sometimes I work out a problem in python and then translate it to rebol, sometimes I work out a problem in python and translate it to rebol. And sometimes I think python developers are looking at Haskell and getting ideas.... > Student, root and saint in the Church of Emacs. Hahaha! They'll take away my vim when they pry it from my cold dead fingers! *but* I'm learning emacs .... """ same thing only different """ tim -- Tim Johnson http://www.alaska-internet-solutions.com From dyoo at hkn.eecs.berkeley.edu Mon Dec 8 03:02:38 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 8 03:02:45 2003 Subject: [Tutor] Python vs. Lua In-Reply-To: <20031208000106.15799.qmail@web41807.mail.yahoo.com> Message-ID: On Sun, 7 Dec 2003, Daniel Ehrenberg wrote: > Are there any reasons why Python is better and I shouldn't use Lua > instead? I think I might be missing some major flaw in the language. Hi Daniel, When we think about programming languages, we should avoid an XOR mentality. *grin* Why assume there's a flaw in Lua, or that one language has to be supreme over another? From what you've summarized, it sounds like a reasonable programming language. By all means try it out! It's perfectly fine to learn and use other programming languages. Other ones you may want to look at include Perl (http://www.perl.com/), OCaml (http://www.ocaml.org/), and Scheme (http://www.plt-scheme.org/). If you compare how they work with what you know about Python (http://www.python.org/), you'll be a better programmer for it. There's a lot more commonalities with these languages than there are differences. But just please promise us you won't stray off the civilized path and learn something barbaric like INTERCAL (http://catb.org/~esr/intercal/). *grin* Good luck to you! From carroll at tjc.com Mon Dec 8 03:45:28 2003 From: carroll at tjc.com (Terry Carroll) Date: Mon Dec 8 03:45:35 2003 Subject: [Tutor] iterating over a urllib.urlopen().read() object Message-ID: I was looking at a sample program from the P in a Nutshell book, which had essentially this code: f = urllib.urlopen(source_url) BUFSIZE = 8192 while True: data = f.read(BUFSIZE) if not data: break p.feed(data) I didn't like the "while True:" construct, and too smart for my own good, tried this instead: for data in f.read(BUFSIZE): p.feed(data) I'd expected this to be like "for line in file:", where "file" is an opened file. It didn't work (I think it only went through once, leaving the parts of the addressed URL past byte 8191 unread). I don't *quite* understand why. I went back to the Nutshell code, which, as expected, works. But is there a cleaner construct, more like my two-liner? There's just something unaesthetic to me about breaking out of a "while True" loop. -- Terry Carroll Santa Clara, CA carroll@tjc.com From carroll at tjc.com Mon Dec 8 03:50:34 2003 From: carroll at tjc.com (Terry Carroll) Date: Mon Dec 8 03:50:38 2003 Subject: [Tutor] program doesnt work In-Reply-To: <20031201232142.96081.qmail@web60208.mail.yahoo.com> Message-ID: On Mon, 1 Dec 2003, Udz wrote: > >at the very end of your program? I suspect that Windows is closing your > >program down automatically. t's a common issue for console-based programs > >on Windows, that your program may actually be running fine, but may simply > >be finishing too quickly for you to see it. > > I hardly doubt that is the case, since my program requires input from > the user at various points throughout execution, but i'll try it > anyways. thanks!! You may have a syntax or other error that prevents it from running correctly, and then when Python ends with an error, the console window automatically closes, as it should. I usually do all my Python development by opening a command window, and running the programs from the command prompt, to avoid this. -- Terry Carroll Santa Clara, CA carroll@tjc.com From alan.gauld at blueyonder.co.uk Mon Dec 8 04:23:48 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Dec 8 04:23:46 2003 Subject: [Tutor] Python vs. Lua References: <20031208000106.15799.qmail@web41807.mail.yahoo.com> Message-ID: <00d901c3bd6c$fcc48100$6401a8c0@xp> > Are there any reasons why Python is better and I > shouldn't use Lua instead? I think I might be missing > some major flaw in the language. All languages are good for something - otherwise they wouldn't have been written! Learning Lua as well as Python is almost certainly a good thing to do. You might even learn some new tricks with Python by doing so. As to whether you should learn Lua *instead* of Python, thats a different story. Python does several things better than Lua - including having built in support for multiple programming paradigms, and having batteries included. Its also more widely used so you have a higher chance of coming across Python elsewhere. But any "Turing complete" programming language can be used to solve any computing problem as well as any other language. The differences are in ease of doing so, performance of the final result etc. There is no universally perfect language Alan G. From alan.gauld at blueyonder.co.uk Mon Dec 8 04:31:49 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Dec 8 04:31:47 2003 Subject: [Tutor] iterating over a urllib.urlopen().read() object References: Message-ID: <00ea01c3bd6e$1b375850$6401a8c0@xp> > f = urllib.urlopen(source_url) > BUFSIZE = 8192 > > while True: > data = f.read(BUFSIZE) > if not data: break > p.feed(data) > > I didn't like the "while True:" construct, and too smart for my own good, > tried this instead: > > for data in f.read(BUFSIZE): > p.feed(data) The while loop keeps reading until nothing comes back. The for vesion reads once then loops for each item in the chunk read. They are quite different concepts. "While" is the correct loop in this case because we don't know in advance how many iterations we need to go through. Although personally I'd prefer data = f.read(BUFSIZE) while data: p.feed(data) data = f.read(BUFSIZE) But that's just me... Alan G. From magnus at thinkware.se Mon Dec 8 10:07:38 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Dec 8 10:07:44 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHl0aG9uIHZzLiBMdWE=?= Message-ID: Daniel Ehrenberg wrote: > Magnus Lyck? wrote: > > I didn't get this part. How can it be used in more ways > > because it lacks OO? You don't have to use OO in Python. > > > It's more flexible than a builtin OO because it > doesn't force you to do one thing in particular. For > example, it is much easier to use prototypes (as in > the Self programming language) in Lua than in Python. Ok, so it seems a bit like Tcl in the respect that it's more "half-cooked" and open-ended. You can make it into something different... Assuming I understood you right, I think this is a mixed blessing. I suppose it might be a good quality for an embedded macro language, where the user is expected to be able to make some specialized macros, and might not even know that he's actually programming Lua (or whatever). Then it would be a good thing to fit the syntax for the particular needs of the application. In most cases, I think Python has a very good mix of rigidity and flexibility. While it's very flexible concerning data handling, it's fairly rigid in its syntax, and that helps people read code they haven't written (or forgot what they wrote :). I think the mantra "There should be one-- and preferably only one --obvious way to do it" is one of the strengths of Python, but naturally, there is not one tool which is best at everything. > There are far more projects that use C++ than Python, > yet we're using Python. Sure (although I use C++ as well). There is far, far more substance in the Python standard library than in the C++ standard library though. Most of the C++ standard library consists of convoluted ways of doing what Python very easily does with lists, strings, tuples and dictionaries. How much code there is, and what other projects use isn't very important for me. What *I* can use from other projects is important. How much value does a module add? Python comes with most of what I need, and the few remaining gaps can be downloaded from some nearby site on the net. I think it's much easier to build a new app by glueing a few different Python modules together than to do something like that in C++, how ever many C++ libraries there are out there. Both Python and Lua can make use of C++ libraries though, by turning them into extension modules, so the wealth of C++ code is a resource for both Python and Lua. But since Python has so many more users, there is much higher likelyhood that someone else have already written a Python wrapper for that nice C or C++ library I need. For Lua I'd probably have to do it myself. Programming Python is very convenient. C, C++, Java and Visual Basic are very widely used, and everybody have heard of them, it's easy to find books, training etc. Python is in the second league, most people I talk to never heard about it, but it's still possible to find Python training in little Sweden, there are about 40 Python programming books at Amazon etc. I never met a Lua programmer in the flesh (not that I know) and the only printed Lua book I heard of is "Game Programming With Python, Lua, and Ruby", which has sales rank 1,157,473 at Amazon... These sorts of things matter if you try to convince your boss to use Python or Lua in a project. And while there might ten times more C++ than Python code freely available on the net, the amount of Python code seems to be hundreds of times larger than the amount of Lua code. It all depends on what you are trying to do. I use Python a lot for testing, for data cleaning and transformation etc, for system and database administration tasks, for web site development, business administration, document production etc. I usually run the code on Windows or Linux. I don't see that Lua would buy me anything here. Quite contrary, I would miss things like ReportLab, wxPython etc. On the other hand, if I were to write a game for a Palm handheld, I would certainly prefer Lua. > I forgot to mention that that Lua programs tend to be > "flatter" than Python programs, something recommended > by import this. The standard Lua distribution is > written in pure ANSI C (like Python) with no real > dependencies (unlike Python), so it is extremely > portable and compiles anywhere tested without > modification. I assume less dependencies also mean fewer features. If you could make good use of these features, you will miss them, if you wouldn't, you might be happier with a smaller language. Python is obviously fairly portable as well, but as I said, I think Lua would be better in e.g. embedded devices. As far as I understand the Lua core and standard library uses around 64kB of RAM, and of course, that's much, much less than Python. I imagine Lua is a much more reasonable language if you are developing applications for a mobile phone or a handheld. (But in a few years, I imagine running Python will be less of a problem, also on cheap handhelds.) Actually, I've been thinking of getting a Palm, and I guess Lua would be a good programming language for that. See http://netpage.em.com.br/mmand/plua.htm Hm... maybe I should give myself a christmas gift and learn a new language? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Mon Dec 8 12:11:44 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Dec 8 12:11:56 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcHJvZ3JhbSBkb2VzbnQgd29yaw==?= Message-ID: Terry Carroll wrote: > You may have a syntax or other error that prevents it from running > correctly, and then when Python ends with an error, the console window > automatically closes, as it should. > > I usually do all my Python development by opening a command window, and > running the programs from the command prompt, to avoid this. A way to prevent the command window from closing is to write the program roughly like this: def main(): # Your code goes here (and in the functions/classes you call). if __name__ == '__main__': try: main() except: import traceback traceback.print_exc() raw_input('\n\tPress ENTER to exit program.') -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From python at dhumketu.cjb.net Mon Dec 8 03:48:03 2003 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Mon Dec 8 12:44:02 2003 Subject: [Tutor] Re: Python script to automatically send mails (running as a cron job in cygwin/linux) In-Reply-To: <000a01c3af41$1d382660$bb07a8c0@midnapore> References: <000a01c3af41$1d382660$bb07a8c0@midnapore> Message-ID: <20031208084803.GA673@dhumketu.homeunix.net> +++ Alok Rai [20-11-03 14:04 +0530]: | Hi, | I need to write a python script which would run through a cron job in cygwin/linux. I need the script to authenticate itself and send the mail. The script needs to read my account info(host, login and password) from some encrypted file. Please provide pointers regarding this, especially how I can store my login information in a secure, encrypted format and have my script read it. | | Regards, | Alok. import md5 From thomi at thomi.imail.net.nz Sun Dec 7 21:41:42 2003 From: thomi at thomi.imail.net.nz (Thomi Richards) Date: Mon Dec 8 13:17:01 2003 Subject: [Tutor] Python vs. Lua In-Reply-To: <20031208000106.15799.qmail@web41807.mail.yahoo.com> References: <20031208000106.15799.qmail@web41807.mail.yahoo.com> Message-ID: <20031208154142.3102132e.thomi@thomi.imail.net.nz> On Sun, 7 Dec 2003 16:01:06 -0800 (PST) Daniel Ehrenberg wrote: > I just heard about Lua, a scripting language with a > minimalistic but highly extendable procedural syntax. > Are there any reasons why Python is better and I > shouldn't use Lua instead? I think I might be missing > some major flaw in the language. > While I'm a devoted python follower, I'm on a project which required a scripting language to controll AI's on a server. We were trying to decide between python and Lua. I'm sorry to say that python lost; namely because you can't easily restrict which system calls the python interpreter can make. I.e.- it can't be easily "sandboxed". I'm still using python, but I'm learning lua at the same time ;) HTH! -- Thomi Richards http://www.once.net.nz From philip at pacer.co.za Mon Dec 8 09:44:13 2003 From: philip at pacer.co.za (philip gilchrist) Date: Mon Dec 8 13:17:45 2003 Subject: [Tutor] python beginner Message-ID: <598B5E93DCDC614C9C1FE22406A0F5BE35B6@pacer-server.pacer.local> I think a problem for most wannabee programmers, is that they don't know WHAT to program. If we ask someone who has been programming for a while, the professional programmer thinks that an answer like ">>> bases = ['A', 'C', 'G', 'T'] >>> bases ['A', 'C', 'G', 'T'] >>> bases.append('U') >>> bases ['A', 'C', 'G', 'T', 'U'] >>> bases.reverse() >>> bases ['U', 'T', 'G', 'C', 'A'] >>> bases[0] 'U' >>> bases[1] 'T' >>> bases.remove('U') >>> bases ['T', 'G', 'C', 'A'] >>> bases.sort() >>> bases ['A', 'C', 'G', 'T']" is the answer that we are looking for, but in all honesty it just scares the cr*p out of us:-) Does someone have a very entry level program that does more than "hello world"? Everyone has done "hello world" and then if they are like me, can't think of anything else to do. Could one of the programmers guide us with a program that simulates a traffic light for example? (red, green and yellow lights on a framework with different timing) This would enable us beginner to begin with a clear picture of the end in mind and make it something that we are able to see results from. regards Philip Gilchrist-----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Christoffer Thomsen Sent: 07 December 2003 07:01 AM To: tutor@python.org Subject: Re: [Tutor] python beginner I think this one is good: http://www.python.org/topics/learn/non-prog.html Jacques wrote: > Does anyone know of any python programming site that could guide me to > learn python in about a month? I also want to be able to write a > program. Anyone have an ideas for a first program? > >----------------------------------------------------------------------- >- > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From rob at jam.rr.com Mon Dec 8 06:45:33 2003 From: rob at jam.rr.com (Rob Andrews) Date: Mon Dec 8 13:35:44 2003 Subject: [Tutor] python beginner In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE35B6@pacer-server.pacer.local> References: <598B5E93DCDC614C9C1FE22406A0F5BE35B6@pacer-server.pacer.local> Message-ID: <200312081245.35409.rob@jam.rr.com> Feel free to snoop around at http://uselesspython.com/ for a variety of examples. (The site's about a third of the way through renovation, BTW, so Useless Python 2.0 should be launched soon.) On Monday 08 December 2003 03:44 pm, philip gilchrist wrote: > Does someone have a very entry level program that does more than "hello > world"? Everyone has done "hello world" and then if they are like me, > can't think of anything else to do. > > Could one of the programmers guide us with a program that simulates a > traffic light for example? (red, green and yellow lights on a framework > with different timing) From dyoo at hkn.eecs.berkeley.edu Mon Dec 8 13:36:39 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 8 13:36:53 2003 Subject: [Tutor] iterating over a urllib.urlopen().read() object In-Reply-To: <00ea01c3bd6e$1b375850$6401a8c0@xp> Message-ID: On Mon, 8 Dec 2003, Alan Gauld wrote: > > f = urllib.urlopen(source_url) > > BUFSIZE = 8192 > > > > while True: > > data = f.read(BUFSIZE) > > if not data: break > > p.feed(data) > > > > I didn't like the "while True:" construct, and too smart for my own > > good, tried this instead: > > > > for data in f.read(BUFSIZE): > > p.feed(data) Hi Terry, The difference between: for line in file: ... and for data in f.read(BUFSIZE): ... is one of values on the right side of the 'for data in...'. In the first case, we take 'file', and and ask our loop to iterate across it. But in the second case, we first take the value of: f.read(BUFSIZE) And we know this is a string of maximum length BUFSIZE. Once we have that value, we ask our loop to go across it. Strings do support iteration: ### >>> for character in "hello world": ... print character, ... h e l l o w o r l d ### So the second case does go across some of the data in the file, but only a character at a time, and only at most BUFSIZE characters of it! So the problem is one of getting the right iterator to go across the whole file. It is possible to make this work with an auxillary tool. Here's a small function that may help: ### def readIter(f, blocksize=8192): """Given a file 'f', returns an iterator that returns bytes of size 'blocksize' from the file, using read().""" while True: data = f.read(blocksize) if not data: break yield data ### The above code defines an iterator for files, using Python's "generator" support. Parts of it should look vaguely familiar. *grin* Ok, so this just shifts the 'while True' stuff around into readIter(). But this relocation does help, because it lets us say this now: ### for block in readIter(f, BUFSIZE): p.feed(block) ## Hope this helps! From learning.python at dbmail.dk Mon Dec 8 14:42:08 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Mon Dec 8 14:42:39 2003 Subject: [Tutor] python beginner References: <598B5E93DCDC614C9C1FE22406A0F5BE35B6@pacer-server.pacer.local> <200312081245.35409.rob@jam.rr.com> Message-ID: <001b01c3bdc3$5e75d9c0$934c73d5@BAERBAR> Feel free to snoop around at http://uselesspython.com/ for a variety of examples. (The site's about a third of the way through renovation, BTW, so Useless Python 2.0 should be launched soon.) Thats good to know, Rob. As I was beginning to think the site had been canned: "Useless Python 2.0 is Under Development: Last edited on ... March 21, 2003" Do you have an estimate on when it'll be finished; January, Febuary, anything? But rest assured I'll be checking back from time to time. From trypticon at SAFe-mail.net Mon Dec 8 17:09:35 2003 From: trypticon at SAFe-mail.net (trypticon@SAFe-mail.net) Date: Mon Dec 8 17:09:44 2003 Subject: [Tutor] python question Message-ID: Hi, i have a simple question. here is the code: import string num_str=raw_input('Enter a number:') num_num=string.atoi(num_str) fac_list=range(1,num_num+1) print "BEFORE:", `fac_list` i=0 while i < len(fac_list): if num_num % fac_list[i]==0: del fac_list[i] i=i+1 print "AFTER:", `fac_list` there is a bug in this program. i know what the bug is(doesn't work correctly when you enter an even number), but i'm not sure how to solve it. Can anybody give me a few hints? Thanks! From ATrautman at perryjudds.com Mon Dec 8 17:28:23 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Mon Dec 8 17:28:28 2003 Subject: [Tutor] python question Message-ID: <06738462136C054B8F8872D69DA140DB01C08BCE@corp-exch-1.pjinet.com> Hi, I wasn't sure what you were trying to do so I played with your program. I now prints all factor of a number entered. You problem stemmed from the used of the delete command. When you deleted the number you still incremented the counter. There would then be nothing to compare when the loop got to the end and it would appear to skip numbers. I commented where I made the change. import string num_str=raw_input('Enter a number:') num_num=string.atoi(num_str) fac_list=range(1,num_num+1) print "BEFORE:", `fac_list` i=0 while i < len(fac_list): #print "During: ", num_num % fac_list[i], num_num, fac_list[i] if num_num % fac_list[i] <> 0: del fac_list[i] # This is the new section ensure the counter is not incremented # when an item is deleted else: i=i+1 print "AFTER:", `fac_list` -----Original Message----- From: trypticon@SAFe-mail.net [mailto:trypticon@SAFe-mail.net] Sent: Monday, December 08, 2003 4:10 PM To: tutor@python.org Subject: [Tutor] python question Hi, i have a simple question. here is the code: import string num_str=raw_input('Enter a number:') num_num=string.atoi(num_str) fac_list=range(1,num_num+1) print "BEFORE:", `fac_list` i=0 while i < len(fac_list): if num_num % fac_list[i]==0: del fac_list[i] i=i+1 print "AFTER:", `fac_list` there is a bug in this program. i know what the bug is(doesn't work correctly when you enter an even number), but i'm not sure how to solve it. Can anybody give me a few hints? Thanks! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From guillermo.fernandez at epfl.ch Mon Dec 8 17:28:37 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Mon Dec 8 17:28:48 2003 Subject: [Tutor] Writing to file Message-ID: <3FD4FB15.20508@epfl.ch> hi, I'm trying to making Octave (later will be Matlab...) and one of my programs communicate together. For that, I create a file that's similar to the one that Octave creates to save his variables (with the 'save' command). This look like this: # Created by Octave 2.1.42, Mon Dec 08 18:57:00 2003 RST # name: a # type: matrix # rows: 2 # columns: 2 1 2 3 4 I did the program and the file is correctly created. Still, while loading my file, I've got this error: octave:1> load wireless ' found in file `wireless'ier `daysmac I'm almost sure the difference between the files he creates and I create is the following: $ file wireless wireless: ASCII text, with CRLF line terminators $ file save save: ASCII text I don't really get what's those CRLF line terminators (maybe the '\r\n' of windows?) but I would apreciate to get rid of them to have standard ASCII file And as the newlines attribute of a file is not writable, I can not set it to '\n' (seems to be set to None for the moment). Hereafter is my code. Thanks, Guille """ Matlab test and plot functions. it takes information from the database and translates it to files understandable by Matlab and Octave. For any comment, criticism, or whatever, feel free to contact me: guillermo.fernandez@epfl.ch """ import begohandler # That's one library of mine that returns # lists of dictionaries and so on. import time def mat_apmaclist(aplist,data,conditions=None): result=begohandler.get_apmaclist(aplist,conditions) data.write('# name: mac\n') data.write('# type: matrix\n') data.write('# rows: '+str(len(result))+'\n') data.write('# columns: 1\n') for key in result: data.write(' '+str(len(result[key]))+'\n') def mat_macaplist(maclist,data,conditions=None): result=begohandler.get_macaplist(maclist,conditions) data.write('# name: ap\n') data.write('# type: matrix\n') data.write('# rows: '+str(len(result))+'\n') data.write('# columns: 1\n') for key in result: data.write(' '+str(len(result[key]))+'\n') def mat_daysmacstat(data,conditions=None): result=begohandler.get_daysmacstat(conditions) data.write('# name: daysmac\n') data.write('# type: matrix\n') data.write('# rows: '+str(len(result))+'\n') data.write('# columns: 2\n') for key in result: data.write(' '+str(key)+' '+str(result[key])+'\n') #--- Main function if __name__=='__main__': begohandler.do_opendb('large.db') data=file('wireless','w') data.write('# Created by BEGO, '+time.strftime('%a %m %d %H:%M:%S %Y %Z')+'\n') # mat_apmaclist(['%'],data) # mat_macaplist(['%'],data) mat_daysmacstat(data) data.close() begohandler.do_closedb() From littledanehren at yahoo.com Mon Dec 8 17:43:28 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Dec 8 17:43:35 2003 Subject: [Tutor] Writing to file In-Reply-To: <3FD4FB15.20508@epfl.ch> Message-ID: <20031208224328.21700.qmail@web41808.mail.yahoo.com> Guillermo Fernandez wrote: > hi, > > I'm trying to making Octave (later will be > Matlab...) and one of my programs > communicate together. For that, I create a file > that's similar to the one that > Octave creates to save his variables (with the > 'save' command). This look like > this: > # Created by Octave 2.1.42, Mon Dec 08 18:57:00 2003 > RST > # name: a > # type: matrix > # rows: 2 > # columns: 2 > 1 2 > 3 4 > > I did the program and the file is correctly created. > Still, while loading my > file, I've got this error: > octave:1> load wireless > ' found in file `wireless'ier `daysmac > > I'm almost sure the difference between the files he > creates and I create is the > following: > $ file wireless > wireless: ASCII text, with CRLF line terminators > $ file save > save: ASCII text > > I don't really get what's those CRLF line > terminators (maybe the '\r\n' of > windows?) but I would apreciate to get rid of them > to have standard ASCII file > And as the newlines attribute of a file is not > writable, I can not set it to > '\n' (seems to be set to None for the moment). > > Hereafter is my code. > > Thanks, > > Guille Just open the file in binary mode. This is done by putting 'b' in the string that determines the mode of the file. For example, you opened the file with mode 'w'. If you want to open it in binary mode, just use 'wb' instead. This basically makes it so that Python writes directly to the file without doing its fancy cross-platform stuff. It can also be used for reading files (in mode 'rb'). Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From sigurd at 12move.de Mon Dec 8 17:55:56 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Dec 8 17:57:06 2003 Subject: [Tutor] python question In-Reply-To: (trypticon@safe-mail.net's message of "Mon, 8 Dec 2003 17:09:35 -0500") References: Message-ID: An unnamed person wrote: > import string > num_str=raw_input('Enter a number:') > num_num=string.atoi(num_str) > fac_list=range(1,num_num+1) > print "BEFORE:", `fac_list` > i=0 > while i < len(fac_list): > if num_num % fac_list[i]==0: > del fac_list[i] > i=i+1 > print "AFTER:", `fac_list` > there is a bug in this program. i know what the bug is(doesn't work correctly > when you enter an even number), but i'm not sure how to solve it. Can anybody > give me a few hints? Thanks! First to the bug. ******************************************************************** import string num_str=raw_input('Enter a number:') num_num=string.atoi(num_str) fac_list=range(1,num_num+1) print "BEFORE:", `fac_list` i=0 while i < len(fac_list): if num_num % fac_list[i]==0: del fac_list[i] i =- 1 i=i+1 print "AFTER:", `fac_list` ******************************************************************** That would be a correct version of your programm (but not a nice one). If you delete a item you mustn't increment your index. But now to the programm. First: don't use string.atoi Second: you filter a list so use either filter() or a list comprehension. Then you programm becomes: ******************************************************************** num_num=int(raw_input('Enter a number:')) fac_list=range(1,num_num+1) print "BEFORE:", `fac_list` print "AFTER:", filter(lambda x: num_num % x != 0, fac_list) #or print "AFTER:", [x for x in fac_list if num_num % x != 0] ******************************************************************** IMO that's much more readable. Karl -- Please do *not* send copies of replies to me. I read the list From tim at johnsons-web.com Mon Dec 8 18:19:05 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Dec 8 18:11:04 2003 Subject: [Tutor] Python vs. Lua/or rebol In-Reply-To: References: Message-ID: <20031208231905.GF10695@johnsons-web.com> * Magnus Lycka [031208 06:18]: > Daniel Ehrenberg wrote: > > Magnus Lyck? wrote: > > > I didn't get this part. How can it be used in more ways > > > because it lacks OO? You don't have to use OO in Python. > > > > > It's more flexible than a builtin OO because it > > doesn't force you to do one thing in particular. For > > example, it is much easier to use prototypes (as in > > the Self programming language) in Lua than in Python. <....> > In most cases, I think Python has a very good mix of rigidity > and flexibility. While it's very flexible concerning data > handling, it's fairly rigid in its syntax, and that helps > people read code they haven't written (or forgot what they > wrote :). I think the mantra "There should be one-- and > preferably only one --obvious way to do it" is one of the > strengths of Python, but naturally, there is not one tool > which is best at everything. Magnus is making an important observation here: In my case, rebol is more flexible than python, for instance there is no immmutable language syntax for control constructs - control constructs are subroutines and you can 'roll you own'. Rebol HTML rendering via CGI is less code-intensive than HtmlGen (as an example). *But* for my own needs, python 'scales' better than rebol (or perl, IMHO, for that matter), because python is more 'disciplined' - a synonym for 'regidity'. Thus python takes a front seat in my larger projects. > > There are far more projects that use C++ than Python, > > yet we're using Python. > > Sure (although I use C++ as well). > > There is far, far more substance in the Python standard > library than in the C++ standard library though. Most of the > C++ standard library consists of convoluted ways of doing what > Python very easily does with lists, strings, tuples and > dictionaries. How much code there is, and what other projects > use isn't very important for me. What *I* can use from other > projects is important. How much value does a module add? I've been programming in C and C++ for 14 years and have done many large projects with either. No more - python is *way* more productive. I can see using C or C++ to extend python for performance or customized syntax or for mission-critical system-level stuff. With C/C++, you can get faster speed, but you spend more time coding. > Python comes with most of what I need, and the few remaining > gaps can be downloaded from some nearby site on the net. And that is what makes it tough for these up-and-coming languages like lua or rebol. Python (or perl's) resources are deeply valuable and appealing in terms of over-all productivity. I keep hammering the rebol community to put together a structured, resource-rich distribution such as python and perl offer. MTCW: pass -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at blueyonder.co.uk Mon Dec 8 18:50:48 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Dec 8 18:50:35 2003 Subject: [Tutor] Python vs. Lua References: Message-ID: <010f01c3bde6$1ada7cc0$6401a8c0@xp> > Actually, I've been thinking of getting a Palm, and I > guess Lua would be a good programming language for that. You can of course get Python for the Palm, although not sure how up to date it is... > See http://netpage.em.com.br/mmand/plua.htm Hm... maybe I > should give myself a christmas gift and learn a new language? But that's always a fun thing to do! :-) One important consideration is how easy is it to use the language using Palms graffiti. Lots of funny symbols is bad news for the programmer on a Palm... Alan G. From pieter.lust at katho.be Tue Dec 9 05:55:18 2003 From: pieter.lust at katho.be (Pieter Lust) Date: Tue Dec 9 05:54:48 2003 Subject: [Tutor] Counting matching elements in sequences Message-ID: <005d01c3be42$f736f980$ac01085a@pcpwo> Hello, Recently I wrote a function to count the matching elements in two tuples. It looked like this: def matches(s1, s2): """matches: count the number of matching elements in 2 sequences of identical length (c-style)""" matches = 0 for i in range(0, len(s1)): if s1[i] == s2[i]: matches += 1 return matches Then today I saw a post from Karl Pflaesterer, which inspired another solution: def matches2(s1, s2): """matches2: count the number of matching elements in 2 sequences of identical length (lambda)""" return len(filter(lambda t: t[0] == t[1], zip(s1, s2))) And then I tried to extend it for an arbitrary number of input sequences: def matches3(*seqlist): """matches3: count the number of matching elements in sequences of identical length (lambda)""" return len(filter(lambda t: list(t).count(t[0]) == len(t), zip(*seqlist))) To my novice eye, matches3 does look quite complex. How would a seasoned Python programmer write it? Am I missing a more obvious solution? Thanks for any comment, Pieter Lust From jboone01 at bcuc.ac.uk Tue Dec 9 06:54:12 2003 From: jboone01 at bcuc.ac.uk (Jim Boone) Date: Tue Dec 9 06:54:29 2003 Subject: [Tutor] Incrementing a line? Message-ID: <3FD5B7E4.6060102@bcuc.ac.uk> Howdy all, i hope this is the right list for my query, pythons a bit new to me, and I'm trying dto something that I can't figure out: for s in userlog.readlines(): for word in s.split(): if word == ("19(Constraint"): constraintlog.write(s + "\n") print "\n\n*****Constraint Violations exist!!*****\n\n" constraintlog.close() Is a section of code i have, it reads a log file and cranks out a log file on a certain condition, I can get it to write out the same line which is in the original log file, which is useful, but, what would be much more useful is if i could write out the line thats 10 lines after the "19(Constraint", because it's more pertinent, but of course s+10 is stupidly wrong. Any help appreciated, Thanks! -- Jim Boone -------------------------------------------- Buckinghamshire Chilterns University College R&D Manager - Information and Communication Technologies Tel: 01494 522141 ext 3569 The myth that Bill Gates has appeared like a knight in shining armor to lead all customers out of a mire of technological chaos neatly ignores the fact that it was he who, by peddling second-rate technology, led them into it in the first place, and continues to do so today. ~Douglas Adams~ From darnold02 at sprynet.com Tue Dec 9 07:14:32 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Tue Dec 9 07:13:01 2003 Subject: [Tutor] Incrementing a line? In-Reply-To: <3FD5B7E4.6060102@bcuc.ac.uk> References: <3FD5B7E4.6060102@bcuc.ac.uk> Message-ID: <3ED59C18-2A41-11D8-9BDC-000A95C4F940@sprynet.com> Untested: targetLineNum = 0 lineNum = 0 for s in userlog.readlines(): lineNum++; if lineNum == targetLineNum: print 'found violation info at line', lineNum constraintlog.write(s + '\n') targetLineNum = 0 for word in s.split(): if word == '19(Constraint': targetLineNum = lineNum + 10 constraintlog.write(s + '\n') constraintlog.close() Barring my not actually being awake yet, that might be close. HTH, Don On Dec 9, 2003, at 5:54 AM, Jim Boone wrote: > Howdy all, i hope this is the right list for my query, pythons a bit > new to me, and I'm trying dto something that I can't figure out: > > for s in userlog.readlines(): > for word in s.split(): > if word == ("19(Constraint"): > constraintlog.write(s + "\n") > print "\n\n*****Constraint Violations > exist!!*****\n\n" > constraintlog.close() > > Is a section of code i have, it reads a log file and cranks out a log > file on a certain condition, I can get it to write out the same line > which is in the original log file, which is useful, but, what would be > much more useful is if i could write out the line thats 10 lines after > the "19(Constraint", because it's more pertinent, but of course s+10 > is stupidly wrong. > > Any help appreciated, Thanks! > > -- > Jim Boone > -------------------------------------------- > Buckinghamshire Chilterns University College > R&D Manager - Information and Communication Technologies > Tel: 01494 522141 ext 3569 > > The myth that Bill Gates has appeared like a knight in shining armor > to lead all customers out of a mire of technological chaos neatly > ignores the fact that it was he who, by peddling second-rate > technology, led them into it in the first place, and continues to do > so today. > > ~Douglas Adams~ > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From project5 at redrival.net Tue Dec 9 07:25:07 2003 From: project5 at redrival.net (Andrei) Date: Tue Dec 9 07:27:47 2003 Subject: [Tutor] Re: Incrementing a line? References: <3FD5B7E4.6060102@bcuc.ac.uk> Message-ID: Jim Boone wrote on Tue, 09 Dec 2003 11:54:12 +0000: > Howdy all, i hope this is the right list for my query, pythons a bit new > to me, and I'm trying dto something that I can't figure out: > > for s in userlog.readlines(): How about (with userlog being a file open for reading): for line in userlog: #code here using line (you may use s instead of line if you like) The code Don Arnold posted should help you with the rest of your question, at least as long as you don't get more than one constraint violation every ten lines. If that may happen, you could keep a list of targetLineNums and test if lineNum is in targetLineNums in order to print "violation info at line...". Oh, "lineNum++" in that code should be "lineNum+=1" or "lineNum = lineNum + 1". -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From darnold02 at sprynet.com Tue Dec 9 07:30:31 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Tue Dec 9 07:29:05 2003 Subject: [Tutor] Incrementing a line? In-Reply-To: <3ED59C18-2A41-11D8-9BDC-000A95C4F940@sprynet.com> References: <3FD5B7E4.6060102@bcuc.ac.uk> <3ED59C18-2A41-11D8-9BDC-000A95C4F940@sprynet.com> Message-ID: <7A7E21A7-2A43-11D8-9BDC-000A95C4F940@sprynet.com> And since you only process each line once, you don't really need the "targetLineNum = 0" line. Need more coffee, Don On Dec 9, 2003, at 6:14 AM, Don Arnold wrote: > Untested: > > targetLineNum = 0 > lineNum = 0 > > for s in userlog.readlines(): > lineNum++; > if lineNum == targetLineNum: > print 'found violation info at line', lineNum > constraintlog.write(s + '\n') > targetLineNum = 0 > for word in s.split(): > if word == '19(Constraint': > targetLineNum = lineNum + 10 > constraintlog.write(s + '\n') > > constraintlog.close() > > Barring my not actually being awake yet, that might be close. > > HTH, > Don > > On Dec 9, 2003, at 5:54 AM, Jim Boone wrote: > >> Howdy all, i hope this is the right list for my query, pythons a bit >> new to me, and I'm trying dto something that I can't figure out: >> >> for s in userlog.readlines(): >> for word in s.split(): >> if word == ("19(Constraint"): >> constraintlog.write(s + "\n") >> print "\n\n*****Constraint Violations >> exist!!*****\n\n" >> constraintlog.close() >> >> Is a section of code i have, it reads a log file and cranks out a log >> file on a certain condition, I can get it to write out the same line >> which is in the original log file, which is useful, but, what would >> be much more useful is if i could write out the line thats 10 lines >> after the "19(Constraint", because it's more pertinent, but of course >> s+10 is stupidly wrong. >> >> Any help appreciated, Thanks! >> >> -- >> Jim Boone >> -------------------------------------------- >> Buckinghamshire Chilterns University College >> R&D Manager - Information and Communication Technologies >> Tel: 01494 522141 ext 3569 >> >> The myth that Bill Gates has appeared like a knight in shining armor >> to lead all customers out of a mire of technological chaos neatly >> ignores the fact that it was he who, by peddling second-rate >> technology, led them into it in the first place, and continues to do >> so today. >> >> ~Douglas Adams~ >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From darnold02 at sprynet.com Tue Dec 9 07:33:02 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Tue Dec 9 07:31:28 2003 Subject: [Tutor] Re: Incrementing a line? In-Reply-To: References: <3FD5B7E4.6060102@bcuc.ac.uk> Message-ID: Shame on me for "lineNum++". Oh well, even Danny makes silly mistakes, sometimes. Don On Dec 9, 2003, at 6:25 AM, Andrei wrote: > Jim Boone wrote on Tue, 09 Dec 2003 11:54:12 +0000: > >> Howdy all, i hope this is the right list for my query, pythons a bit >> new >> to me, and I'm trying dto something that I can't figure out: >> >> for s in userlog.readlines(): > > How about (with userlog being a file open for reading): > > for line in userlog: > #code here using line (you may use s instead of line if you like) > > The code Don Arnold posted should help you with the rest of your > question, > at least as long as you don't get more than one constraint violation > every > ten lines. If that may happen, you could keep a list of targetLineNums > and > test if lineNum is in targetLineNums in order to print "violation info > at > line...". Oh, "lineNum++" in that code should be "lineNum+=1" or > "lineNum = > lineNum + 1". > > -- > Yours, > > Andrei > > ===== > Mail address in header catches spam. Real contact info (decode with > rot13): > cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V > ernq > gur yvfg, fb gurer'f ab arrq gb PP. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jboone01 at bcuc.ac.uk Tue Dec 9 08:41:17 2003 From: jboone01 at bcuc.ac.uk (Jim Boone) Date: Tue Dec 9 08:41:33 2003 Subject: [Fwd: Re: [Tutor] Re: Incrementing a line?] Message-ID: <3FD5D0FD.3060906@bcuc.ac.uk> oops, and for the rest of the list... oh yeah, is this what this list is about then? -------- Original Message -------- Subject: Re: [Tutor] Re: Incrementing a line? Date: Tue, 09 Dec 2003 13:39:51 +0000 From: Jim Boone To: Don Arnold References: <3FD5B7E4.6060102@bcuc.ac.uk> Don Arnold wrote: > Shame on me for "lineNum++". Oh well, even Danny makes silly mistakes, > sometimes. > > Don Yeah, I'm not actually awake either, which isnt helping matters, well, the code works, once I'd pulled the deliberate mistake ;-) Oddly though it reports the wrong line number, but does throw out the correct error line, cheers for that, I'll have a tinker after more coffee, and try and figure what its doing! -- Jim Boone -------------------------------------------- Buckinghamshire Chilterns University College R&D Manager - Information and Communication Technologies Tel: 01494 522141 ext 3569 The myth that Bill Gates has appeared like a knight in shining armor to lead all customers out of a mire of technological chaos neatly ignores the fact that it was he who, by peddling second-rate technology, led them into it in the first place, and continues to do so today. ~Douglas Adams~ -- Jim Boone -------------------------------------------- Buckinghamshire Chilterns University College R&D Manager - Information and Communication Technologies Tel: 01494 522141 ext 3569 The myth that Bill Gates has appeared like a knight in shining armor to lead all customers out of a mire of technological chaos neatly ignores the fact that it was he who, by peddling second-rate technology, led them into it in the first place, and continues to do so today. ~Douglas Adams~ From SlaybaughLJ at ih.navy.mil Tue Dec 9 10:28:53 2003 From: SlaybaughLJ at ih.navy.mil (Slaybaugh Laura J IHMD) Date: Tue Dec 9 10:29:29 2003 Subject: [Tutor] ping question... Message-ID: <9718D3B1ED18D31180F000A0C99DE22305B560BE@ihmdex03.ih.navy.mil> Hello, I'm still somewhat new to python, and I'm writing a program that periodically pings several computers on my network to figure out whether they're responding. My first stab was a simple x=os.system('ping -n 1 '), unfortunately whether or not I run this line against a computer with a request timed out response, x equals 0. Which helps me not at all. I tried downloading Jeremy Hyleton's ping implementation, but was unable to unzip it (Winzip). I'm looking over the socket class now to see if it'll provide anything that could be helpful, but I was curious is anyone here had any suggestions I should look into. Thanks, Laura Slaybaugh From chris at heisel.org Tue Dec 9 11:18:22 2003 From: chris at heisel.org (Chris Heisel) Date: Tue Dec 9 11:18:45 2003 Subject: [Tutor] Document URI? In-Reply-To: <3FD313F6.5040106@student.liu.se> References: <2281.172.22.1.1.1070586987.squirrel@mail.apixels.net> <3FD313F6.5040106@student.liu.se> Message-ID: <3FD5F5CE.2070707@heisel.org> Hi, I had previously wrote a scrip that accessed a document's URI by getting os.environ['DOCUMENT_URI'] Our server admin recently upgrade to Python2.3 and now Python is saying that there is no 'DOCUMENT_URI' key. I did some googling but I couldn't find a way to access a documents URI in python... FYI, the script is called via a SSI ala: File called /foo/index.html: Previously the os.environ['DOCUMENT_URI'] would return /foo/index.html but now its saying there's no value... Thanks in advance, Chris From sigurd at 12move.de Tue Dec 9 11:24:39 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Dec 9 11:25:15 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: <005d01c3be42$f736f980$ac01085a@pcpwo> (Pieter Lust's message of "Tue, 9 Dec 2003 11:55:18 +0100") References: <005d01c3be42$f736f980$ac01085a@pcpwo> Message-ID: On 9 Dec 2003, Pieter Lust <- pieter.lust@katho.be wrote: > Recently I wrote a function to count the matching elements in two tuples. It > looked like this: > def matches(s1, s2): > """matches: count the number of matching elements in 2 sequences of > identical length (c-style)""" > matches = 0 > for i in range(0, len(s1)): > if s1[i] == s2[i]: > matches += 1 > return matches [...] > And then I tried to extend it for an arbitrary number of input sequences: > def matches3(*seqlist): > """matches3: count the number of matching elements in sequences of > identical length (lambda)""" > return len(filter(lambda t: list(t).count(t[0]) == len(t), > zip(*seqlist))) > To my novice eye, matches3 does look quite complex. How would a seasoned It is complex (and len() is expensive since you always have to traverse the whole list); furthermore you build up lists only to throw them away and use their length as value. > Python programmer write it? Am I missing a more obvious solution? I don't know if it's very obvious but I would write it a bit different. First you need a function which tells you if all elements of a sequence are equal. There are some solutions. First the straightforward one: def alleq(seq): k = seq[0] for i in seq: if i == k: pass else: return False return True Then a more compact one (which will be slower, since the sequence will always completely be traversed): def alleq(seq): return seq[0] == reduce(lambda s, t: s==t and t, seq) What's happening here? reduce() takes a function with two arguments and a sequence. It applies the function to the first two elements (not always true see later) of the sequence returns the result and applies the function to the resukt and the third element of the sequence etc. The function `lambda s, t: s==t and t' returns t if s is equal t. So if you have the sequence [1,1,2] the function compares 1 and 1 and returns 1; then it compares 1 and 2 and returns 2. Finally the result is compared to the first element of the list and the function returns True (which is equal to 1) if they are equal. Then you apply that function to all your tuples. First the straightforward way to write it (which will be in Python also the faster one I think): def match3(*seqs): match = 0 for tup in zip(*seqs): match += alleq(tup) return match Then another more functional solution with reduce again: def match3(*seqs): return reduce(lambda num_of_match, tup: num_of_match + alleq(tup), zip(*seqs), 0) Here you see the full functionality of reduce. It can take an start element as third argument. That argument is used as first value for the function and the *first* element of the sequence is used as second value for the function. That's an alternative solution (if you know a bit functional programming it will look common) but perhaps not the best with Python (sadly). Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Tue Dec 9 11:33:46 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Dec 9 11:34:42 2003 Subject: [Tutor] ping question... In-Reply-To: <9718D3B1ED18D31180F000A0C99DE22305B560BE@ihmdex03.ih.navy.mil> (Slaybaugh Laura J. IHMD's message of "Tue, 9 Dec 2003 10:28:53 -0500") References: <9718D3B1ED18D31180F000A0C99DE22305B560BE@ihmdex03.ih.navy.mil> Message-ID: Slaybaugh Laura J IHMD <- SlaybaughLJ@ih.navy.mil wrote: > My first stab was a simple x=os.system('ping -n 1 '), > unfortunately whether or not I run this line against a computer with a > request timed out response, x equals 0. Which helps me not at all. os.system does only the return value of the command you run; but you want the output of ping. So you look for os.popen() (and friends there are some popen functions). If you wanted to see the output of ping it could be: for line in os.popen(''ping -n 1 '): print line, Karl -- Please do *not* send copies of replies to me. I read the list From magnus at thinkware.se Tue Dec 9 11:40:44 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Dec 9 11:41:07 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcGluZyBxdWVzdGlvbi4uLg==?= Message-ID: Hi Laura, Slaybaugh Laura J IHMD wrote: > My first stab was a simple x=os.system('ping -n 1 '), > unfortunately whether or not I run this line against a computer with a > request timed out response, x equals 0. Which helps me not at all. Yes, the return code will be 0 for ping regardless of responses, unless you make a syntax error in your command etc. You need to get the output from the ping command into Python for analysis, rather than its return code. Maybe this interactive example can give you some hints... >>> import os >>> ip = raw_input('IP? ') IP? >>> result = os.popen('ping %s' % ip).read() >>> print result >>> print "time-out" in result True -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Dec 9 11:48:56 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Dec 9 11:49:08 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRG9jdW1lbnQgVVJJPw==?= Message-ID: Chris Heisel wrote: > Our server admin recently upgrade to Python2.3 and now Python is saying > that there is no 'DOCUMENT_URI' key. Ok, but I'm not so sure those things are related... Whatever version of Python you use, you are just reading the environment variables provided by the operating system. The operating system won't make different environment variables available to a process depending on what version of Python you use. If a change in the python installation caused a difference here, it's a difference in how Python scripts are executed, not simply a version change. Are you running the Python scripts as CGI scripts? What else changed? OS? Web server? Configuration? > Previously the os.environ['DOCUMENT_URI'] would return /foo/index.html > but now its saying there's no value... Try printing out all the os.environ items from a CGI script. I think I showed an example of how to do this here a week or two ago... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Dec 9 12:03:25 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Dec 9 12:03:35 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSW5jcmVtZW50aW5nIGEgbGluZT8=?= Message-ID: Hi Jim! Jim Boone wrote: > Howdy all, i hope this is the right list for my query, pythons a bit new > to me, and I'm trying dto something that I can't figure out: You have come to the right place! > for s in userlog.readlines(): > for word in s.split(): > if word == ("19(Constraint"): > constraintlog.write(s + "\n") > print "\n\n*****Constraint Violations exist!!*****\n\n" > constraintlog.close() > > Is a section of code i have, it reads a log file and cranks out a log > file on a certain condition, I can get it to write out the same line > which is in the original log file, which is useful, but, what would be > much more useful is if i could write out the line thats 10 lines after > the "19(Constraint", because it's more pertinent, but of course s+10 is > stupidly wrong. In recent Python versions, there is a nice thingie called "enumerate()" which will turn something like ['a', 'b', 'c'] into [(0,'a'), (1,'b'), (2,'c')] That's helpful here, right? In addition to this, you should assign the result of userlog.readlines() (which is a list object) to a variable name, so that you can access the element 10 steps further down, just as easily as the current element, right? You just change your code to something like... lines = userlog.readlines() for i, s in lines: ... if ... ... print lines[i+10] Note that this might cause an IndexError if lines don't extend that far. (You can handle that with "if len(lines) > i+10:", or with try/except.) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Dec 9 12:28:31 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Dec 9 12:28:51 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ291bnRpbmcgbWF0Y2hpbmcgZWxlbWVudHMgaW4gc2VxdWVuY2Vz?= Message-ID: Pieter Lust write: > def matches3(*seqlist): > """matches3: count the number of matching elements in sequences of > identical length (lambda)""" > return len(filter(lambda t: list(t).count(t[0]) == len(t), > zip(*seqlist))) > > To my novice eye, matches3 does look quite complex. How would a seasoned > Python programmer write it? Am I missing a more obvious solution? To me, this feels less confusing. import operator def matches4(*seqlist): allSame = 0 for elements in zip(*seqlist): allSame += reduce(operator.eq, elements) return allSame or if you prefer lambda to importing operator... def matches4(*seqlist): allSame = 0 for elements in zip(*seqlist): allSame += reduce(lambda x,y: x==y, elements) return allSame -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Dec 9 12:42:48 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Dec 9 12:43:11 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gaXRlcmF0aW5nIG92ZXIgYSB1cmxsaWIudXJsb3BlbigpLnJlYWQoKSBvYmplY3Qg?= Message-ID: Terry Carroll wrote: > > I didn't like the "while True:" construct, But "while True:" with an "if x: break" in it is such a common Python idiom that you'd better get used to it. Alan Gauld responded: > "While" is the correct loop in this case because we don't > know in advance how many iterations we need to go through. > Although personally I'd prefer > > data = f.read(BUFSIZE) > while data: > p.feed(data) > data = f.read(BUFSIZE) The disadvantage with this is obviously that it breaks the "Do It Only Once" principle. Of course, in this tiny code it doesn't matter, but in many real time situations it might be a chunk of lines, of at least a much more complicated expression, and you might end up modifying it in one place, and not in the other. :( This would all be solved if Python had a "repeat - until" kind of loop, but the problem is that nobody has ever managed to create a good looking syntax for a loop in Python with a test in the end. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From trypticon at SAFe-mail.net Tue Dec 9 14:05:32 2003 From: trypticon at SAFe-mail.net (trypticon@SAFe-mail.net) Date: Tue Dec 9 14:05:40 2003 Subject: [Tutor] strings Message-ID: Hi, i'm having a little trouble with this exercise problem. We're supposed to create a function called findchr(string,char) which will look for character char in string and return the index of the first occurrence of char, or -1 if char is not part of string. you can't use string.*find() or string.*index() functions or methods. The part where i'm having trouble is returning the index of the first occurrence of char. Any help would be appreciated. Thanks From sigurd at 12move.de Tue Dec 9 14:12:12 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Dec 9 14:16:44 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: (Magnus Lycka's message of "Tue, 9 Dec 2003 18:28:31 +0100") References: Message-ID: On 9 Dec 2003, Magnus Lycka <- magnus@thinkware.se wrote: > import operator > def matches4(*seqlist): > allSame = 0 > for elements in zip(*seqlist): > allSame += reduce(operator.eq, elements) > return allSame That won't work (I first thought of the same solution) because x == y returns True or False not x or y (with two elemenstit works, with three it breaks). > or if you prefer lambda to importing operator... > def matches4(*seqlist): > allSame = 0 > for elements in zip(*seqlist): > allSame += reduce(lambda x,y: x==y, elements) > return allSame Try the simple >>> reduce(operator.eq, [2,2,2]) False So you need a function like alleq def alleq(seq): return seq[0] == reduce(lambda s, t: s==t and t, seq) >>> alleq([2,2,2]) True >>> Karl -- Please do *not* send copies of replies to me. I read the list From pythontutor at venix.com Tue Dec 9 14:21:52 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Dec 9 14:21:57 2003 Subject: [Tutor] strings In-Reply-To: References: Message-ID: <3FD620D0.50404@venix.com> Sounds like homework... Let me just suggest a plausible definition for "index of first occurrence of character". The index is a count of the characters before the character you are trying to locate. If your character is the very first character of the string, then (from the definition) the index is 0. Hope this helps. trypticon@SAFe-mail.net wrote: > Hi, > i'm having a little trouble with this exercise problem. We're supposed to create a function called findchr(string,char) which will look for character char in string and return the index of the first occurrence of char, or -1 if char is not part of string. you can't use string.*find() or string.*index() functions or methods. The part where i'm having trouble is returning the index of the first occurrence of char. Any help would be appreciated. Thanks > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From zak at harlekin-maus.com Tue Dec 9 14:23:34 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Tue Dec 9 14:23:42 2003 Subject: [Tutor] strings In-Reply-To: References: Message-ID: <2156.192.206.201.92.1070997814.squirrel@webmail.harlekin-maus.com> > Hi, > i'm having a little trouble with this exercise problem. We're > supposed to create a function called findchr(string,char) which will > look for character char in string and return the index of the first > occurrence of char, or -1 if char is not part of string. you can't > use string.*find() or string.*index() functions or methods. The part > where i'm having trouble is returning the index of the first > occurrence of char. Any help would be appreciated. Thanks Take a peek at the for loop documentation in the Python tutorial. http://www.python.org/doc/current/tut/node6.html --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From magnus at thinkware.se Tue Dec 9 14:35:41 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Dec 9 14:35:52 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ291bnRpbmcgbWF0Y2hpbmcgZWxlbWVudHMgaW4gc2VxdWVuY2Vz?= Message-ID: Karl Pfl?sterer wrote: > That won't work (I first thought of the same solution) because x == y > returns True or False not x or y (with two elemenstit works, with three > it breaks). True! > So you need a function like alleq > > def alleq(seq): > return seq[0] == reduce(lambda s, t: s==t and t, seq) That doesn't work either! :) >>> def alleq(seq): return seq[0] == reduce(lambda s, t: s==t and t, seq) >>> alleq([0,2,0]) True Perhaps it's best to skip the "clever" lambda and reduce tricks completely! This works (I think): def alleq(seq): for item in seq[1:]: if item != seq[0]: return False return True It also works correctly with 0 or 1 elements in the sequence (assuming that we consider an empty list to have all elements equal--at least there are no differences). -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Dec 9 14:51:56 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Dec 9 14:53:31 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gc3RyaW5ncw==?= Message-ID: > i'm having a little trouble with this exercise problem. We're supposed to create a function called findchr(string,char) which will look for character char in string and return the index of the first occurrence of char, or -1 if char is not part of string. you can't use string.*find() or string.*index() functions or methods. The part where i'm having trouble is returning the index of the first occurrence of char. Any help would be appreciated. Thanks Hi there, we try not to spoil education on this list by doing peoples school work. (It's so easy to just provide an answer, but it's probably not very educational...) This exercise is really so small that it's difficult to give a hint without solving it entirely. I guess you're either just stuck, or haven't still grasped how to combine the elements of a programming language to solve a problem. A good way of solving problems is usually to solve a little piece at a time... Could you write a program that can compare two values (numbers or strings or whatever) to see if they are equal? Could you write a program that would give the right answer just in the case that your char is in the first position of the string? Could you write a program that would give the right answer just in the case that your char is in the second position of the string? Can you think of any way of generalizing such a program? If you read chapters 3 and 4 in the Python tutorial, you will certainly have all the tools you need to do this. Just take one step at a time. Good luck! http://www.python.org/doc/current/tut/node5.html http://www.python.org/doc/current/tut/node6.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From glingl at aon.at Tue Dec 9 15:13:06 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue Dec 9 15:12:09 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: References: Message-ID: <3FD62CD2.8050407@aon.at> >Perhaps it's best to skip the "clever" lambda and reduce >tricks completely! This works (I think): > >def alleq(seq): > for item in seq[1:]: > if item != seq[0]: > return False > return True > >It also works correctly with 0 or 1 elements in the >sequence (assuming that we consider an empty list to >have all elements equal--at least there are no >differences). > > What do you think about: >>> def alleq(seq): ... return seq == seq[:1]*len(seq) ... >>> alleq("") True >>> alleq((1,)) True >>> alleq([1,1]) True >>> alleq((1,2)) False >>> Gregor From dyoo at hkn.eecs.berkeley.edu Tue Dec 9 15:28:55 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 9 15:29:09 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gc3RyaW5ncw==?= In-Reply-To: Message-ID: > i'm having a little trouble with this exercise problem. We're supposed > to create a function called findchr(string,char) [some text cut] > The part where i'm having trouble is returning the index of the first > occurrence of char. Any help would be appreciated. Thanks Hi trypticon, Please don't take this the wrong way, but you do understand that that "part" that you're having trouble with is the point of the whole exercise, right? One way to get a better understanding of a problem is to try a simpler version of it. This is one of the problem-solving strategies that G. Polya talks about in his book "How to Solve It": http://www.math.utah.edu/~alfeld/math/polya.html Can you think of simpler versions of the problem? The original problem allows us to pass strings of any length, and maybe you're running into problem trying to account for this. If so, here's one way to simplify the problem: what if you're only working with strings of three characters only? Say that you're writing a version of the code called findchr3() that takes a three-character string, and a character to search for. It'd work something like this: ### >>> findchr3("abc", "a") 0 >>> findchr3("abc", "c") 2 >>> findchr3("abc", "z") -1 ### findchr3() can assume that the first argument is always a string of three characters. Would you be able to write findchr3()? If not, then that's something you may want to try doing first, before tackling the more general problem. Also, you may want to try browsing through one of the tutorials on: http://www.python.org/topics/learn/non-prog.html In particular: http://www.freenetpages.co.uk/hp/alan.gauld/ is a good tutorial to try out. If you understand the concept of "loops", you should know enough to solve your original problem. Good luck to you! From sigurd at 12move.de Tue Dec 9 15:36:12 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Dec 9 15:37:23 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: (Magnus Lycka's message of "Tue, 9 Dec 2003 20:35:41 +0100") References: Message-ID: On 9 Dec 2003, Magnus Lycka <- magnus@thinkware.se wrote: > Karl Pfl?sterer wrote: >> That won't work (I first thought of the same solution) because x == y >> returns True or False not x or y (with two elemenstit works, with three >> it breaks). > True! >> So you need a function like alleq >> def alleq(seq): >> return seq[0] == reduce(lambda s, t: s==t and t, seq) > That doesn't work either! :) Yep I noticed it later; here the equality of True and 1 and False and 0 bites. >>>> def alleq(seq): > return seq[0] == reduce(lambda s, t: s==t and t, seq) >>>> alleq([0,2,0]) > True > Perhaps it's best to skip the "clever" lambda and reduce > tricks completely! This works (I think): > def alleq(seq): > for item in seq[1:]: > if item != seq[0]: > return False > return True I came up with nearly the same one. def alleq(seq): k = seq[0] for i in seq: if i != k: return 0 return 1 Sadly reduce might break if you have zero as first element. > It also works correctly with 0 or 1 elements in the > sequence (assuming that we consider an empty list to > have all elements equal--at least there are no > differences). Right. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Tue Dec 9 15:42:09 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Dec 9 15:42:43 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: <3FD62CD2.8050407@aon.at> (Gregor Lingl's message of "Tue, 09 Dec 2003 21:13:06 +0100") References: <3FD62CD2.8050407@aon.at> Message-ID: On 9 Dec 2003, Gregor Lingl <- glingl@aon.at wrote: > What do you think about: > >>> def alleq(seq): > ... return seq == seq[:1]*len(seq) > ... Cool. But the for loop is the best one I think since you only traverse the sequence until you find a difference and since you don't have to build a second list and have to use len() on the original sequence. Karl -- Please do *not* send copies of replies to me. I read the list From glingl at aon.at Tue Dec 9 16:00:31 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue Dec 9 15:59:33 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: References: Message-ID: <3FD637EF.4070803@aon.at> >>def alleq(seq): >> for item in seq[1:]: >> if item != seq[0]: >> return False >> return True >> >> > >I came up with nearly the same one. > >def alleq(seq): > k = seq[0] > for i in seq: > if i != k: > return 0 > return 1 > > Actually, if you wanted to avoid copying seq and at the same time make the function work for empty sequences you had to write something like: def alleq(seq): if len(seq) > 0: k = seq[0] for i in seq: if i!=k: return 0 return 1 or, how would you avoid "using len on the original sequence"? Gregor From sigurd at 12move.de Tue Dec 9 16:31:40 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Dec 9 16:34:50 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: <3FD637EF.4070803@aon.at> (Gregor Lingl's message of "Tue, 09 Dec 2003 22:00:31 +0100") References: <3FD637EF.4070803@aon.at> Message-ID: On 9 Dec 2003, Gregor Lingl <- glingl@aon.at wrote: >>>def alleq(seq): >>> for item in seq[1:]: >>> if item != seq[0]: >>> return False >>> return True >>I came up with nearly the same one. >>def alleq(seq): >> k = seq[0] >> for i in seq: >> if i != k: >> return 0 >> return 1 > Actually, if you wanted to avoid copying seq and at > the same time make the function work for empty > sequences you had to write something like: > def alleq(seq): > if len(seq) > 0: > k = seq[0] > for i in seq: > if i!=k: > return 0 > return 1 or simply: def alleq(seq): if seq: k = seq[0] for i in seq: if i != k: return 0 return 1 if we define empty sequences to be equal. > or, how would you avoid > "using len on the original sequence"? see the above. Karl -- Please do *not* send copies of replies to me. I read the list From chris at heisel.org Tue Dec 9 16:54:24 2003 From: chris at heisel.org (Chris Heisel) Date: Tue Dec 9 16:54:29 2003 Subject: [Tutor] Document URI? In-Reply-To: References: Message-ID: <3FD64490.6040403@heisel.org> Thanks, I checked with the sysadmin he made some changes that broke the script but he fixed it and all is well... Thanks again, Chris Magnus Lycka wrote: > Chris Heisel wrote: > >>Our server admin recently upgrade to Python2.3 and now Python is saying >>that there is no 'DOCUMENT_URI' key. > > > Ok, but I'm not so sure those things are related... Whatever > version of Python you use, you are just reading the environment > variables provided by the operating system. The operating > system won't make different environment variables available > to a process depending on what version of Python you use. > > If a change in the python installation caused a difference here, > it's a difference in how Python scripts are executed, not simply > a version change. Are you running the Python scripts as CGI scripts? > What else changed? OS? Web server? Configuration? > > >>Previously the os.environ['DOCUMENT_URI'] would return /foo/index.html >>but now its saying there's no value... > > > Try printing out all the os.environ items from a CGI script. > I think I showed an example of how to do this here a week > or two ago... > From alan.gauld at blueyonder.co.uk Tue Dec 9 19:01:51 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Dec 9 19:01:26 2003 Subject: [Tutor] Incrementing a line? References: <3FD5B7E4.6060102@bcuc.ac.uk><3ED59C18-2A41-11D8-9BDC-000A95C4F940@sprynet.com> <7A7E21A7-2A43-11D8-9BDC-000A95C4F940@sprynet.com> Message-ID: <016201c3beb0$d08c19f0$6401a8c0@xp> > On Dec 9, 2003, at 6:14 AM, Don Arnold wrote: > > > Untested: > > > > targetLineNum = 0 > > lineNum = 0 > > > > for s in userlog.readlines(): > > lineNum++; Huh? Someones been overdoing the Java... :-) In Python that's lineNum += 1 ++ isn't available in Python - at least not in my 2.3.2 version. Alan G. From alan.gauld at blueyonder.co.uk Tue Dec 9 19:02:46 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Dec 9 19:02:17 2003 Subject: [Tutor] Re: Incrementing a line? References: <3FD5B7E4.6060102@bcuc.ac.uk> Message-ID: <016701c3beb0$f155cf00$6401a8c0@xp> > Shame on me for "lineNum++". Oh well, even Danny makes silly mistakes, > sometimes. > > Don Ah, too fast on the reply key, you already caught it... Still at least I gave the += alternative... Alan G. From absmythe at ucdavis.edu Tue Dec 9 19:03:13 2003 From: absmythe at ucdavis.edu (ashleigh smythe) Date: Tue Dec 9 19:03:19 2003 Subject: [Tutor] make code less ugly/more pythonic? Message-ID: <1071014592.2730.1041.camel@nate.ucdavis.edu> Greetings! I've written a little script to process a text file. It does exactly what I want it to do but as I'm a newbie I'm sure it's very ugly and brute force - I wondered if anyone had a moment to please take a look and tell me how to improve it? For instance I have a function that calls a function that calls a function! Is that awkard and unpythonic? Should the whole thing be in a class - how would I do that? The program simply parses a file that has 10,000 iterations of the following: Strict consensus of 1 tree: Statistics derived from consensus tree: Component information (consensus fork) = 185 (normalized = 0.964) Nelson-Platnick term information = 3855 Nelson-Platnick total information = 4040 Mickevich's consensus information = 0.183 Colless weighted consensus fork (proportion max. information) = 0.216 Schuh-Farris levels sum = 0 (normalized = 0.000) Rohlf's CI(1) = 0.989 Rohlf's -ln CI(2) = 948.111 (CI(2) = 0.00) I want to extract that Component information (consensus fork) value (185 in this instance) from each of the 10,000 "paragraphs" of data in the file and get an average of that value. Below is the code I hacked together- please don't laugh!!! :-) Thanks for any imput, Ashleigh import re import sys import string def make_int(mylist): #turns the list of consensus an_int_list=[int(n) for n in mylist] #fork values from strings to return an_int_list #integers so I can average #them. def add_up(mylist): #calls function to turn int_list=make_int(mylist) #strings into asum=0 #integers. for x in int_list: #sums up all the values asum +=x return asum def average(mylist): #takes the sum of consensus sum=add_up(mylist) #fork values and finds their length=len(mylist) #average. average_confork=sum/length return average_confork mainlist=[] #initialize the list of #consensus fork values. def search(file_to_search): infile=open(file_to_search, 'r') for line in infile: if re.search('Component', line): #searches the input file for confork=line[45:49] #line containing cons. fork, mainlist.append(confork) #removes the value and puts return mainlist #it into a list. def aveconfork(file_to_search): #this executes the whole thing thelist=search(file_to_search) #so I start the program with finalaverage=average(mainlist) #aveconfork.aveconfork return finalaverage #('file_to_search') From alan.gauld at blueyonder.co.uk Tue Dec 9 19:05:46 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Dec 9 19:05:27 2003 Subject: [Tutor] ping question... References: <9718D3B1ED18D31180F000A0C99DE22305B560BE@ihmdex03.ih.navy.mil> Message-ID: <017801c3beb1$5c6b71a0$6401a8c0@xp> > My first stab was a simple x=os.system('ping -n 1 '), > unfortunately whether or not I run this line against a computer with a > request timed out response, x equals 0. Which helps me not at all. a zero return means it worked! Try using os.popen() to read the results back. > I'm looking over the socket class now to see if it'll provide > anything that could be helpful, You can do but remember that Ping doesn't work over TCP/IP it uses a different protocol (ICMP from memory). Alan G From alan.gauld at blueyonder.co.uk Tue Dec 9 19:13:44 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Dec 9 19:13:14 2003 Subject: [Tutor] strings References: Message-ID: <019801c3beb2$795a19f0$6401a8c0@xp> > i'm having a little trouble with this exercise problem. We're supposed to create a function called findchr(string,char) which will look for character char in string and return the index of the first occurrence of char, or -1 if char is not part of string. you can't use string.*find() or string.*index() functions or methods. The part where i'm having trouble is returning the index of the first occurrence of char. Any help would be appreciated. Thanks > OK, Without actually doing the homework for you here are some hints. To find the chr you need to loop over the string. To return the index you need to keep track of where you are in the string, which means you'll need to create a local variable in your function starting at zero(the first char). Add one to that each time through the loop to keep track of the current position. When you find the chr break out of the loop and return the index counter or -1 if you gort to the end of the string without finding chr - you might need another variable to determine whether you did or not, or maybe you could use some smart branching... And that should be enough to be going on with. HTH, Alan G. From krazie_mu_boi at hotmail.com Tue Dec 9 19:50:26 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Tue Dec 9 19:50:31 2003 Subject: [Tutor] the 'or' attribute Message-ID: How do i use 'or' ? for e.g , i tried x = 1 or 2 print x it would always print 1, and never two. Why is that? _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From tpc at csua.berkeley.edu Tue Dec 9 19:58:36 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Dec 9 19:58:44 2003 Subject: [Tutor] the 'or' attribute In-Reply-To: Message-ID: <20031209165510.H42986-100000@localhost.name> hi Cris, the Python 'or' operator returns y if x is false, so: w =3D x or y print w will yield x if x is true. For Python truth value testing check out: http://www.python.org/doc/current/lib/boolean.html#l2h-102 and for more on the 'or' operator: http://www.python.org/doc/current/lib/boolean.html#l2h-102 I hope that helps you. On Tue, 9 Dec 2003, Leung Cris wrote: > How do i use 'or' ? for e.g , i tried > > x =3D 1 or 2 > print x > > it would always print 1, and never two. Why is that? > > _________________________________________________________________ > =A8=CF=A5=CE MSN Messenger=A1A=BBP=AAB=A4=CD=A6b=BDu=A4W=B2=E1=A4=D1: htt= p://messenger.microsoft.com/tc > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From littledanehren at yahoo.com Tue Dec 9 20:33:01 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Dec 9 20:33:05 2003 Subject: [Tutor] strings In-Reply-To: Message-ID: <20031210013301.8899.qmail@web41804.mail.yahoo.com> trypticon-at-SAFe-mail.net wrote: > Hi, > i'm having a little trouble with this exercise > problem. We're supposed to create a function called > findchr(string,char) which will look for character > char in string and return the index of the first > occurrence of char, or -1 if char is not part of > string. you can't use string.*find() or > string.*index() functions or methods. The part where > i'm having trouble is returning the index of the > first occurrence of char. Any help would be > appreciated. Thanks As just about everyone else on this list said, this is probably a homework assignment, so I won't give you the answer. I'll only give you a hint. Try using list comprehensions. These are fairly advanced, so I'll walk you through how to use them. >>> this_list = [5, 3, 6, 2, 5] #should be obvious >>> [x for x in this_list] #goes through each item of #this_list, calling it x, then returns x into a new list [5, 3, 6, 2, 5] >>> [x**2 for x in this_list] #gets x squared for each x in this_list [25, 9, 36, 4, 25] >>> [x for x in this_list if x!=5] #takes each x for each x in this_list, but only if it doesn't equal 5 [3, 6, 2] >>> [x for x in 'hello' if x!='l'] #strings can be treated as lists, but it still returns a list ['h', 'e', 'o'] >>> enumerate(this_list) #makes an enumerator iterator >>> [(index, object) for index, object in enumerate(this_list)] #each thing in enumerate(x) is a tuple of the index and the thing in the list [(0, 5), (1, 3), (2, 6), (3, 2), (4, 5)] >>> [index for index, object in enumerate(this_list) if object==5] #I don't want to give it away [0, 4] If you followed all of that, you can use similar techniques to solve your problem. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From krazie_mu_boi at hotmail.com Tue Dec 9 20:41:50 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Tue Dec 9 20:41:55 2003 Subject: [Tutor] the 'or' attribute Message-ID: Umm....okay , I get it. So, how can i have a variable that stores ' this number, or that number' ? >From: >To: Leung Cris >CC: >Subject: Re: [Tutor] the 'or' attribute >Date: Tue, 9 Dec 2003 16:58:36 -0800 (PST) > > >hi Cris, the Python 'or' operator returns y if x is false, >so: > >w = x or y >print w > >will yield x if x is true. For Python truth value testing check out: > >http://www.python.org/doc/current/lib/boolean.html#l2h-102 > >and for more on the 'or' operator: > >http://www.python.org/doc/current/lib/boolean.html#l2h-102 > >I hope that helps you. > > On Tue, 9 Dec 2003, Leung Cris wrote: > > > How do i use 'or' ? for e.g , i tried > > > > x = 1 or 2 > > print x > > > > it would always print 1, and never two. Why is that? > > > > _________________________________________________________________ > > 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _________________________________________________________________ 使用 MSN Messenger,與朋友在線上聊天: http://messenger.microsoft.com/tc From zak at harlekin-maus.com Tue Dec 9 20:58:12 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Tue Dec 9 20:58:19 2003 Subject: [Tutor] the 'or' attribute In-Reply-To: References: Message-ID: <4029.192.206.201.92.1071021492.squirrel@webmail.harlekin-maus.com> > Umm....okay , I get it. So, how can i have a variable that stores ' this > number, or that number' ? You have to be more specific. That's like telling the person behind the counter you want "vanilla or chocolate ice cream." That person won't be able to hand you your ice cream until you've made a definite decision. Python is standing behind the counter, and you've got to tell it which number you want. Variables can only store one value at a time. ### >>> a = 1 >>> a 1 >>> a = 2 >>> a 2 ### --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From tayi177 at hotmail.com Tue Dec 9 21:27:35 2003 From: tayi177 at hotmail.com (Tadey) Date: Tue Dec 9 21:27:20 2003 Subject: [Tutor] Fw: capturing crashing application (application running under windows environment) - now sending with right adress ... Message-ID: Hello again ... I have two questions in general about Python ... One is, I thought lots of times, about how great it would be, to have program, sort of "monitoring application", which would save crashing apllication data. I do not mean logging crashing process instructions before crash, like some memory dump, but capturing any event, and unsaved user data going on just before crash occur, only some last important sequenceses (in case of capturing whole program memory from time to time), and not like logging user input all the time. In this case (logging user input all the time) the program should be sort of logging all output and user input data from all programs during current session, so if crash would occur in any other program, for example all that was written in Wordpad before crash, would be recovered (and data from all other programs too). Or maybe even logging important changes made to program configuration (changes in registry) before crash. Of course, I am no computer nor programming expert, so I can not even imagine what kind of programming language would be the most convenient, and what kind of instructions author should use, so how code would look like, and as the most important - if this is possible at all. But I just mention it as my personal craving ... But, if Python is capable of doing something like that, please, tell me, it would become my personal goal, to write something even near that. And I would be glad for any assistance. Of course after some years or so, when I will know how to program well ... Second is kind of releated to first, since all applications I would like to monitor are running under Windows. It is about Python code to be executed in Windows without Python installed. I read here on Tutor something about making some somefile.py2exe executable, but could you tell some more about this, how it looks, how Python code must be written (or just modified) to work under Windows environment. I suppose that kind of programming is much more complicated ... Thanks for any answer, Tadey -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031210/9cf39586/attachment.html From littledanehren at yahoo.com Tue Dec 9 21:36:11 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Dec 9 21:36:16 2003 Subject: [Tutor] the 'or' attribute In-Reply-To: Message-ID: <20031210023611.42859.qmail@web41802.mail.yahoo.com> Leung Cris wrote: > Umm....okay , I get it. So, how can i have a > variable that stores ' this number, or that number' > ? That's not really how it works. Something like 'x or y' will evaluate to one value, not two. Here's an example: >>> 1 or 2 2 1 evaluated to True, so 'or' (you can kinda think of it as a function) returned 2, the second thing. To test if, for example, x is either 1 or two, you have to counterintuitively do: >>> x == 1 or x == 2 becaise otherwise, Python will just interpret x == 1 or 2 as x == 2. If you still want to make one variable hold more than one thing, there's a way, but it uses different syntax. Consider the example below: >>> 1, 2 #makes a tuple, or an immutable list (1, 2) >>> x = 1, 2 #sets x to that tuple >>> x (1, 2) >>> 1 == x #doesn't work because 1 is not the same as the tuple (1, 2) False >>> 1 in x #tests to see if 1 is a member of the tuple x True >>> 1 in 1, 2 #wrong syntax, must use parenthesis Traceback (most recent call last): File "", line 1, in ? TypeError: iterable argument required >>> 1 in (1, 2) True >>> 3 in x #tests if 3 is a member of x False >>> 3 in (1, 2) False Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From littledanehren at yahoo.com Tue Dec 9 21:36:56 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Dec 9 21:37:02 2003 Subject: [Tutor] the 'or' attribute Message-ID: <20031210023656.13990.qmail@web41810.mail.yahoo.com> Leung Cris wrote: > Umm....okay , I get it. So, how can i have a > variable that stores ' this number, or that number' > ? That's not really how it works. Something like 'x or y' will evaluate to one value, not two. Here's an example: >>> 1 or 2 2 1 evaluated to True, so 'or' (you can kinda think of it as a function) returned 2, the second thing. To test if, for example, x is either 1 or two, you have to counterintuitively do: >>> x == 1 or x == 2 becaise otherwise, Python will just interpret x == 1 or 2 as x == 2. If you still want to make one variable hold more than one thing, there's a way, but it uses different syntax. Consider the example below: >>> 1, 2 #makes a tuple, or an immutable list (1, 2) >>> x = 1, 2 #sets x to that tuple >>> x (1, 2) >>> 1 == x #doesn't work because 1 is not the same as the tuple (1, 2) False >>> 1 in x #tests to see if 1 is a member of the tuple x True >>> 1 in 1, 2 #wrong syntax, must use parenthesis Traceback (most recent call last): File "", line 1, in ? TypeError: iterable argument required >>> 1 in (1, 2) True >>> 3 in x #tests if 3 is a member of x False >>> 3 in (1, 2) False Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From littledanehren at yahoo.com Tue Dec 9 22:22:09 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Dec 9 22:22:14 2003 Subject: [Tutor] make code less ugly/more pythonic? Message-ID: <20031210032209.54934.qmail@web41802.mail.yahoo.com> ashleigh smythe wrote: > Greetings! I've written a little script to process > a text file. It > does exactly what I want it to do but as I'm a > newbie I'm sure it's very > ugly and brute force - I wondered if anyone had a > moment to please take > a look and tell me how to improve it? For instance > I have a function > that calls a function that calls a function! Is > that awkard and > unpythonic? Should the whole thing be in a class - > how would I do that? > > The program simply parses a file that has 10,000 > iterations of the > following: > > > Strict consensus of 1 tree: > > Statistics derived from consensus tree: > > Component information (consensus fork) = 185 > (normalized = 0.964) > Nelson-Platnick term information = 3855 > Nelson-Platnick total information = 4040 > Mickevich's consensus information = 0.183 > Colless weighted consensus fork (proportion > max. information) = > 0.216 > Schuh-Farris levels sum = 0 (normalized = > 0.000) > Rohlf's CI(1) = 0.989 > Rohlf's -ln CI(2) = 948.111 (CI(2) = 0.00) > > > I want to extract that Component information > (consensus fork) value (185 > in this instance) from each of the 10,000 > "paragraphs" of data in the > file and get an average of that value. > > > Below is the code I hacked together- please don't > laugh!!! :-) > > Thanks for any imput, > > Ashleigh > > import re > import sys > import string > > def make_int(mylist): #turns the > list of consensus > an_int_list=[int(n) for n in mylist] #fork > values from strings to > return an_int_list #integers > so I can average > #them. > def add_up(mylist): #calls > function to turn > int_list=make_int(mylist) #strings > into > asum=0 #integers. > for x in int_list: #sums up > all the values > asum +=x > return asum > > def average(mylist): #takes the > sum of consensus > sum=add_up(mylist) #fork > values and finds their > length=len(mylist) #average. > average_confork=sum/length > return average_confork > > mainlist=[] > #initialize the list of > #consensus > fork values. > def search(file_to_search): > infile=open(file_to_search, 'r') > for line in infile: > if re.search('Component', line): #searches > the input file for > confork=line[45:49] #line > containing cons. fork, > mainlist.append(confork) #removes > the value and puts > return mainlist #it into a > list. > > def aveconfork(file_to_search): #this > executes the whole thing > thelist=search(file_to_search) #so I > start the program with > finalaverage=average(mainlist) > #aveconfork.aveconfork > return finalaverage > #('file_to_search') Your program is good. It does what it is supposed to do. I do have a few changes to it, though. Here's my edited version: def avg_str_list(L): newlist = [int(x) for x in L] return sum(newlist) #sum adds up everything in list def find_comp_if_there(string): if string.startswith('Component'): return string[45:49] def go_through_file(filename): thisfile = file(filename) #mode 'r' implied mainlist = [] for line in thisfile: cur_comp = find_comp_if_there(line) if cur_comp: mainlist.append(cur_comp) return mainlist This uses the same underlying algorithm as your program does. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From pan at uchicago.edu Wed Dec 10 00:48:48 2003 From: pan at uchicago.edu (pan@uchicago.edu) Date: Wed Dec 10 00:48:53 2003 Subject: [Tutor] mxTextTools help: find the deepest in nest lists In-Reply-To: References: Message-ID: <1071035328.3fd6b3c0ad193@webmail-b.uchicago.edu> I am learning how to use mxTextTools. I need help with the following ... I wanna match the deepest lists in a nested list tree. For example: The [2, 2a] and [3, 3b] in : [[[1,[2, 2a]],[[3,3b],4]],6] The [a.1,b_2] and [d.3,e] in : [[a.1,b_2],[[c,[d.3,e]],f]] The [a1,a2], [d.1, d.2] and [o3,o4] in : [[[[[a1,a2],out],[d.1, d.2]],o2],[[o3,o4],o5]] How can I setup a tagtable for matching them ?? What I got so far --- after painful trial and error --- is : tagTable=((None, SubTable, ( (None, AllIn, '[', Fail), ('text',AllIn,allowed, Fail), (None,AllIn,']', MatchOk, +0) ), -1, +0 ), ) which is still very terrible: -- It only matches one set of the deepest lists (for example, only match [a1,a2] in the case 3); -- it also returns something I dont' want (for example, 'c,' in the case-2) -- it can't match entries starting with a number (for example, [2, 2a]) pan From krazie_mu_boi at hotmail.com Wed Dec 10 01:28:30 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Wed Dec 10 01:28:34 2003 Subject: [Tutor] coordinates of a circle Message-ID: Can someone tell me how the circle() in LIVEWIRES is constructed? Becuz I would like to know the coordinates of the perimeter of the circle. Thx. _________________________________________________________________ MSN 相簿提供您最簡單的方式分享並列印您的相片,請移至 : http://photos.msn.com.hk/support/worldwide.aspx From alan.gauld at blueyonder.co.uk Wed Dec 10 04:18:24 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 10 04:17:49 2003 Subject: [Tutor] Counting matching elements in sequences References: <3FD62CD2.8050407@aon.at> Message-ID: <01c901c3befe$8fee0fe0$6401a8c0@xp> > On 9 Dec 2003, Gregor Lingl <- glingl@aon.at wrote: > > > What do you think about: > > > >>> def alleq(seq): > > ... return seq == seq[:1]*len(seq) > > ... Gregor, I assume you had a reason to use seq[:1] instead of seq[0]? But I can't think of any. OK, I just did while typing this, seq[0] returns an element, seq[:1] returns a single element *list*. I'll send the mail in case anyone else was confused, (although probably not!) Alan G. From alan.gauld at blueyonder.co.uk Wed Dec 10 04:34:19 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 10 04:33:41 2003 Subject: [Tutor] the 'or' attribute References: Message-ID: <01da01c3bf00$c9639e00$6401a8c0@xp> > How do i use 'or' ? for e.g , i tried > > x = 1 or 2 > print x > > it would always print 1, and never two. Why is that? 'or' is a boolean test. It applies a boolean or to both arguments and returns the boolean result. Boolean values can only be True or False(which python often represents by non-zero or 0) Thus "x = 1 or 2" says to python: If 1 or 2 is true then store 1 in x, if neither 1 or 2 is true store zero in x. But since both 1 and 2 are greater than zero python will allways see '1 or 2' as being true. Thus x always holds 1. Taking it one step further, Python actually uses something called short-circuit evaluation of logical (boolean) or. Thus in evaluating A or B because if any one value is true the whole expression is true Python will first evaluate A and if true it returns A, only if A is false does it evaluate B and return B. So in your case, if you had written x = 2 or 1 You would find x always had value 2! We can translate the way Python evaluates an or test into a function like this: def or_test(A,B): if A: return A else: return B BTW. If you want to randomly assign either 1 or 2 to x (which seems to be what you expected 'or' to do) you would need to use a function from the random module, probably randint() x = random.randint(1,2) HTH, Alan G From jboone01 at bcuc.ac.uk Wed Dec 10 04:49:00 2003 From: jboone01 at bcuc.ac.uk (Jim Boone) Date: Wed Dec 10 04:49:15 2003 Subject: [Tutor] Incrementing a line? In-Reply-To: References: Message-ID: <3FD6EC0C.9020802@bcuc.ac.uk> Hejsan Magnus! Thanks for that I'll look into it, I've got it working at the moment with Dons snippet of code, but I'll look into these other bits, it's literally been years since I've done any coding, and while I'm aware of what can be done, I can't recollect how to do things! What you're saying makes sense, now I just have to 'own' it if you like. Looks like a good list, probably would have helped to have joined earlier before writing the bulk of my little app! Cheers, Jim Magnus Lycka wrote: >Hi Jim! > >Jim Boone wrote: > > >>Howdy all, i hope this is the right list for my query, pythons a bit new >>to me, and I'm trying dto something that I can't figure out: >> >> > >You have come to the right place! > > > >>for s in userlog.readlines(): >> for word in s.split(): >> if word == ("19(Constraint"): >> constraintlog.write(s + "\n") >> print "\n\n*****Constraint Violations exist!!*****\n\n" >> constraintlog.close() >> >>Is a section of code i have, it reads a log file and cranks out a log >>file on a certain condition, I can get it to write out the same line >>which is in the original log file, which is useful, but, what would be >>much more useful is if i could write out the line thats 10 lines after >>the "19(Constraint", because it's more pertinent, but of course s+10 is >>stupidly wrong. >> >> > >In recent Python versions, there is a nice thingie called "enumerate()" >which will turn something like ['a', 'b', 'c'] into [(0,'a'), (1,'b'), >(2,'c')] That's helpful here, right? In addition to this, you should >assign the result of userlog.readlines() (which is a list object) to a >variable name, so that you can access the element 10 steps further down, >just as easily as the current element, right? > >You just change your code to something like... > >lines = userlog.readlines() >for i, s in lines: > ... > if ... > ... > print lines[i+10] > >Note that this might cause an IndexError if lines don't extend that >far. (You can handle that with "if len(lines) > i+10:", or with >try/except.) > > > -- Jim Boone -------------------------------------------- Buckinghamshire Chilterns University College R&D Manager - Information and Communication Technologies Tel: 01494 522141 ext 3569 The myth that Bill Gates has appeared like a knight in shining armor to lead all customers out of a mire of technological chaos neatly ignores the fact that it was he who, by peddling second-rate technology, led them into it in the first place, and continues to do so today. ~Douglas Adams~ From alan.gauld at blueyonder.co.uk Wed Dec 10 04:55:59 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 10 04:55:21 2003 Subject: [Tutor] Fw: capturing crashing application (application runningunder windows environment) - now sending with right adress ... References: Message-ID: <020201c3bf03$d06a9980$6401a8c0@xp> > which would save crashing apllication data. Thats really quite difficult since you dont know in advance when a program will crash! So you don;t know when to start saving the data. One technique oftenn used on industrial mainframe programs is to save the data in a "circular list", that is a list that has a fixed number of items and when you reach the end starts from the top again, overwriting what used to be there. Even that has problems since you need to know which item was last written after the crash, so a separate item containing the position also needs to be saved. All this constant saving of data slows the system down so most programs don't do that. > It is about Python code to be executed in Windows without Python > installed. I read here on Tutor something about making some > somefile.py2exe executable, but could you tell some more about this, The Python interpreter needs to be there (along with any modules you use) to run your program. py2exe is a program that will take your Python script and bundle it along with your modules and the python interpreter into a single file and then make that file look like a normal Windows exectutable (an .exe file). So the end user gets what looks like a noral program, but actually it just runs python and your script together. The problem with this approach is that the exe file is quite big so if you give out lots of these your user winds up with multiple Pythons installed! So if you give out lots of little programs its better to get the user to install Python (maybe as part of an installation script). This is the Java approach. On the other hand, if you only want to give out 1 program py2exe might be the best way. (this is the C++ approach) Alan G. From pieter.lust at katho.be Wed Dec 10 05:23:21 2003 From: pieter.lust at katho.be (Pieter Lust) Date: Wed Dec 10 05:22:43 2003 Subject: [Tutor] Counting matching elements in sequences: thanks Message-ID: <00b801c3bf07$a7ba8140$ac01085a@pcpwo> Thank you all who replied. I learned a lot. Pieter Lust. From fitz at nexma.de Wed Dec 10 06:48:19 2003 From: fitz at nexma.de (Tom Fitz) Date: Wed Dec 10 07:03:55 2003 Subject: [Tutor] Where is Jon Whitener Message-ID: <3FD70803.7090503@nexma.de> If anyone has an e-mail address for Jon Whitener please pass this on to him. Jon, I just worked through your New Zoo. It is super and really makes things clear. You have obviously organized all the bits and pieces perfectly for reuse. Very logical. Ironically it is the only chapter on TAL in the Book that actually functions and is not loaded with errors too. You gave me a complete web site. Thanks. Tom Snell Magdeburg, Germany -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031210/8250d2ea/attachment.html From cybersamurai at terra.com.br Wed Dec 10 08:29:50 2003 From: cybersamurai at terra.com.br (Luiz Siqueira Neto) Date: Wed Dec 10 07:31:52 2003 Subject: [Tutor] reference to main module Message-ID: <3FD71FCE.2080304@terra.com.br> How can I make a reference to main module to use getattr( main, 'function') on the fly? From desiderata at softhome.net Wed Dec 10 14:53:01 2003 From: desiderata at softhome.net (desiderata@softhome.net) Date: Wed Dec 10 07:50:08 2003 Subject: [Tutor] Using Linux commands Message-ID: <20031210195301.GA3587@Valhalla> Hi, Is there a module that I could import so that I could use linux commands? the os modules seems limited because I wanted to use some commands for my script.. regards, Elijah A. From vicki.stanfield at ROCHE.COM Wed Dec 10 09:26:06 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Wed Dec 10 09:26:28 2003 Subject: [Tutor] Explanation of how to set DTR and RTS with pySerial Message-ID: I need to be able to change the DTR and RTS settings for a serial port between TRUE and FALSE. I see this on the pySerial site: setRTS(level=1) #set RTS line to specified logic level setDTR(level=1) #set DTR line to specified logic level but I can't find any other reference to setting these values. Can I assume that level 1 is TRUE and level 0 is false? Is there some reference that I am missing? --vicki -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031210/1ecd6014/attachment.html From pan at uchicago.edu Wed Dec 10 09:33:59 2003 From: pan at uchicago.edu (pan@uchicago.edu) Date: Wed Dec 10 09:34:04 2003 Subject: [Tutor] Class inheritance: is the kid calling? or the mom ?? In-Reply-To: References: Message-ID: <1071066839.3fd72ed78e9c1@webmail-b.uchicago.edu> I have a class which needs calling itself in a function: class Mom(object): def __init__(self): ... def oldfunc(self): # line [1] ... self.someAttr = Mom() Now, I make a new class out of it, added some new functions: class Kid(Mom): def __init__(self): Mom.__init__(self) ... def newfunc(self): ... Then: mom = Mom() mom.oldfunc() # this will asign a new Mom() to mom.someAttr mom.someAttr.oldfunc() # ok Now: kid = Kid() kid.newfunc() # ok kid.oldfunc() # this will asign Mom() to kid.someAttr kid.someAttr.oldfunc() # ok kid.someAttr.newfunc() # not ok ... because kid.someAttr is a Mom, # which doesn't have newfunc(). To make this works, the oldfunc() is recoded as: class Mom(object): def __init__(self): ... def oldfunc(self): # line [1] ... self.someAttr = self.copy() # line [2] (copy() is pre-defined) But this slows down the operation by ~ 10 fold. Is there anyway that a class method can know who is calling it --- the kid or the mom ? If yes, then we can do : class Mom(object): def __init__(self): ... def oldfunc(self): # line [1] ... if called_by_Mom: self.someAttr = Mom () # line [3] else: self.someAttr = Kid() # line [4] or even better, in generalized manner: class Mom(object): def __init__(self): ... def oldfunc(self): # line [1] ... self.someAttr = any_class_that_is_calling_me() # line [5] Is this possible ???? thx. pan From Christian.Wyglendowski at greenville.edu Wed Dec 10 10:04:09 2003 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Dec 10 10:04:15 2003 Subject: [Tutor] Fw: capturing crashing application (application running under windows environment) - now sending with right adress ... Message-ID: For any sort of Windows programming, you will definitely want to pick up the win32all package written by Mark Hammond. http://starship.python.net/crew/mhammond/win32/Downloads.html The win32all package gives you access to the win32 api and COM via Python, amongst other useful things. I have just started looking into WMI scripting with Python which gives you the ability to manage many aspects of a Windows 2000/XP based system, including starting and stopping processes, managing disks, etc. Here is a good link for Python specific WMI stuff. http://tgolden.sc.sabren.com/python/wmi.html The scope of your program is beyond what I can offer specific advice about though! You might try looking at the Python-Win32 archives or subscribing to that list for Windows specific help when it comes to Python. http://mail.python.org/mailman/listinfo/python-win32 Christian From pythontutor at venix.com Wed Dec 10 10:08:20 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Dec 10 10:08:26 2003 Subject: [Tutor] Class inheritance: is the kid calling? or the mom ?? In-Reply-To: <1071066839.3fd72ed78e9c1@webmail-b.uchicago.edu> References: <1071066839.3fd72ed78e9c1@webmail-b.uchicago.edu> Message-ID: <3FD736E4.8010005@venix.com> self.__class__ will return a reference to its class, Kid or Mom in this case. So you could consider writing: self.someAttr = self.__class__() self.__class__.__name__ references the name of the class, "Mom" or "Kid". The documentation index should help in finding all of the "magic" class attributes. They are marked with the double underscores. pan@uchicago.edu wrote: > I have a class which needs calling itself in a function: > > class Mom(object): > def __init__(self): > ... > def oldfunc(self): # line [1] > ... > self.someAttr = Mom() > > > Now, I make a new class out of it, added some new functions: > > class Kid(Mom): > def __init__(self): > Mom.__init__(self) > ... > def newfunc(self): > ... > > Then: > > mom = Mom() > mom.oldfunc() # this will asign a new Mom() to mom.someAttr > mom.someAttr.oldfunc() # ok > > Now: > > kid = Kid() > kid.newfunc() # ok > kid.oldfunc() # this will asign Mom() to kid.someAttr > kid.someAttr.oldfunc() # ok > > kid.someAttr.newfunc() # not ok ... because kid.someAttr is a Mom, > # which doesn't have newfunc(). > > To make this works, the oldfunc() is recoded as: > > class Mom(object): > def __init__(self): > ... > def oldfunc(self): # line [1] > ... > self.someAttr = self.copy() # line [2] (copy() is pre-defined) > > > But this slows down the operation by ~ 10 fold. > > Is there anyway that a class method can know who is calling it --- > the kid or the mom ? If yes, then we can do : > > class Mom(object): > def __init__(self): > ... > def oldfunc(self): # line [1] > ... > if called_by_Mom: > self.someAttr = Mom () # line [3] > else: > self.someAttr = Kid() # line [4] > > > or even better, in generalized manner: > > class Mom(object): > def __init__(self): > ... > def oldfunc(self): # line [1] > ... > self.someAttr = any_class_that_is_calling_me() # line [5] > > > Is this possible ???? > > thx. > > pan > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From tpc at csua.berkeley.edu Wed Dec 10 10:26:49 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Dec 10 10:26:57 2003 Subject: [Tutor] the 'or' attribute In-Reply-To: <20031210023611.42859.qmail@web41802.mail.yahoo.com> Message-ID: <20031210072244.I2463-100000@localhost.name> hi Daniel, I was looking at your reply to Cris, and I couldn't figure out how you got 'or' to return '2' when you typed in '1 or 2'. The only way to do that as far as I can see is to type '2 or 1': >>> 1 or 2 1 >>> 1 or 2 1 >>> 2 or 1 2 On Tue, 9 Dec 2003, Daniel Ehrenberg wrote: > Leung Cris wrote: > > Umm....okay , I get it. So, how can i have a > > variable that stores ' this number, or that number' > > ? > > That's not really how it works. Something like 'x or > y' will evaluate to one value, not two. Here's an > example: > >>> 1 or 2 > 2 > 1 evaluated to True, so 'or' (you can kinda think of > it as a function) returned 2, the second thing. To > test if, for example, x is either 1 or two, you have > to counterintuitively do: > >>> x == 1 or x == 2 > becaise otherwise, Python will just interpret x == 1 > or 2 as x == 2. If you still want to make one variable > hold more than one thing, there's a way, but it uses > different syntax. Consider the example below: > >>> 1, 2 #makes a tuple, or an immutable list > (1, 2) > >>> x = 1, 2 #sets x to that tuple > >>> x > (1, 2) > >>> 1 == x #doesn't work because 1 is not the same as > the tuple (1, 2) > False > >>> 1 in x #tests to see if 1 is a member of the tuple > x > True > >>> 1 in 1, 2 #wrong syntax, must use parenthesis > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iterable argument required > >>> 1 in (1, 2) > True > >>> 3 in x #tests if 3 is a member of x > False > >>> 3 in (1, 2) > False > > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From hec.villafuerte at telgua.com.gt Wed Dec 10 12:34:26 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Wed Dec 10 10:33:28 2003 Subject: [Tutor] Installing RPy in Windows Message-ID: <3FD75922.9010303@telgua.com.gt> Hi all! I'm trying to install RPy in WinXP. This are my programs' versions: RPy-0.3.1 R 1.8.0 Python 2.3 After tweaking a bit RPy's setup.py (just added RHOME = "c:/Program Files/R/rw1080") I got this strange error message (what does Visual Studio has to do with it?!) E:\to_do\rpy-0.3.1>python setup.py install running install running build running build_py creating build creating build\lib.win32-2.3 copying rpy.py -> build\lib.win32-2.3 copying io.py -> build\lib.win32-2.3 copying rpy_version.py -> build\lib.win32-2.3 running build_ext error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. Thanks for your help! From david at graniteweb.com Wed Dec 10 11:12:14 2003 From: david at graniteweb.com (David Rock) Date: Wed Dec 10 11:15:41 2003 Subject: [Tutor] Using Linux commands In-Reply-To: <20031210195301.GA3587@Valhalla> References: <20031210195301.GA3587@Valhalla> Message-ID: <20031210161214.GB28075@wdfs.graniteweb.com> * desiderata@softhome.net [2003-12-11 03:53]: > Hi, > > Is there a module that I could import so that I could use linux commands? os.system will let you run any command available on the system commands.getoutput will let you collect stdout from a system command that you run > the os modules seems limited because I wanted to use some commands for > my script.. Limited in what way? What type of commands are you trying to use and what are you using them for? -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031210/ad6c2108/attachment.bin From BranimirP at cpas.com Wed Dec 10 11:27:03 2003 From: BranimirP at cpas.com (Branimir Petrovic) Date: Wed Dec 10 11:27:09 2003 Subject: [Tutor] Is there any standard module for "pretty printing" to stdout? Message-ID: <33678E78A2DD4D418396703A750048D45E698B@RIKER> I have a need for tabular and rather fancy printing to stdout. What I dream of - would give me control over setting rules on column width, cell padding and/or truncation, justification, etc. Intention is to allow running script connect its hooks into 'tabular thingy 4 fancy printing', run it and let the 'thingy' take care of appying printing rules to the output stream as it happens (as the stream is being genereated). Rather than re-inventing the wheel, is there something in Python's standard library that is close enough for the task? If not - then which Python's standard modules would be good candidates (need to know of/good to consider) for parts an/or building blocks before I jump blindly into DIY mode? Branimir From desiderata at softhome.net Wed Dec 10 18:30:57 2003 From: desiderata at softhome.net (desiderata@softhome.net) Date: Wed Dec 10 11:28:04 2003 Subject: [Tutor] Using Linux commands In-Reply-To: <20031210125159.GA1814@eng.xevion.net> References: <20031210195301.GA3587@Valhalla> <20031210125159.GA1814@eng.xevion.net> Message-ID: <20031210233057.GA3626@Valhalla> Thanks for the reply, Hmm.. from that link you gave me I found something useful os.system() , Sorry I couldn't get the open2/popopen/execlp to work right. >>> os.system('slapadd -l ldif-file.txt') It works! Thanks a lot! Regards, Elijah On 07:51 Wed 10 Dec?, David Dorgan wrote: > Sure, check out os.popen, or os.open2[0], which means you can use input and > output with commands, rather than just execute the command > blindly and let it go to the terminal. > > David. > > [0]: http://www.python.org/doc/2.3.2/lib/os-process.html From hec.villafuerte at telgua.com.gt Wed Dec 10 14:08:04 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Wed Dec 10 12:06:48 2003 Subject: [Tutor] Re: Installing RPy in Windows In-Reply-To: <3FD75922.9010303@telgua.com.gt> References: <3FD75922.9010303@telgua.com.gt> Message-ID: <3FD76F14.1070408@telgua.com.gt> H?ctor Villafuerte D. wrote: > Hi all! > I'm trying to install RPy in WinXP. This are my programs' versions: > RPy-0.3.1 > R 1.8.0 > Python 2.3 > > After tweaking a bit RPy's setup.py (just added RHOME = "c:/Program > Files/R/rw1080") > I got this strange error message (what does Visual Studio has to do > with it?!) > > E:\to_do\rpy-0.3.1>python setup.py install > running install > running build > running build_py > creating build > creating build\lib.win32-2.3 > copying rpy.py -> build\lib.win32-2.3 > copying io.py -> build\lib.win32-2.3 > copying rpy_version.py -> build\lib.win32-2.3 > running build_ext > error: Python was built with version 6 of Visual Studio, and > extensions need to be built > with the same version of the compiler, but it isn't installed. > > Thanks for your help! > Just reporting my progress (after googling for a while): E:\to_do\rpy-0.3.1>python setup.py build --compiler=mingw32-gcc bdist_wininst running build running build_py running build_ext error: don't know how to compile C/C++ code on platform 'nt' with 'mingw32-gcc' compiler Any suggestions? Thanks again. Hector From Christian.Wyglendowski at greenville.edu Wed Dec 10 12:31:10 2003 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Dec 10 12:31:15 2003 Subject: [Tutor] the 'or' attribute Message-ID: I think this would suit your purposes: >>>import random >>>help(random.choice) Help on method choice in module random: choice(self, seq) method of random.Random instance Choose a random element from a non-empty sequence. >>>options = (1,2) >>>x = random.choice(options) x will contain 1 or 2. Christian Original Message: Message: 2 Date: Tue, 09 Dec 2003 17:41:50 -0800 From: "Leung Cris" Subject: Re: [Tutor] the 'or' attribute To: tpc@csua.berkeley.edu Cc: tutor@python.org Message-ID: Content-Type: text/plain; charset=big5; format=flowed Umm....okay , I get it. So, how can i have a variable that stores ' this number, or that number' ? From sigurd at 12move.de Wed Dec 10 13:47:18 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Dec 10 13:51:22 2003 Subject: [Tutor] make code less ugly/more pythonic? In-Reply-To: <1071014592.2730.1041.camel@nate.ucdavis.edu> (ashleigh smythe's message of "09 Dec 2003 16:03:13 -0800") References: <1071014592.2730.1041.camel@nate.ucdavis.edu> Message-ID: On 10 Dec 2003, ashleigh smythe <- absmythe@ucdavis.edu wrote: > Greetings! I've written a little script to process a text file. It Daniel wrote something about your script; there's nothing more to say so let me just show you an alternative way. [...] > The program simply parses a file that has 10,000 iterations of the > following: > Strict consensus of 1 tree: > Statistics derived from consensus tree: > Component information (consensus fork) = 185 (normalized = 0.964) > Nelson-Platnick term information = 3855 > Nelson-Platnick total information = 4040 > Mickevich's consensus information = 0.183 > Colless weighted consensus fork (proportion max. information) = > 0.216 > Schuh-Farris levels sum = 0 (normalized = 0.000) > Rohlf's CI(1) = 0.989 > Rohlf's -ln CI(2) = 948.111 (CI(2) = 0.00) > I want to extract that Component information (consensus fork) value (185 > in this instance) from each of the 10,000 "paragraphs" of data in the > file and get an average of that value. [Code] To extract the information I would like you use a regexp. Then if a match is found the number should be returned and it is added to an accumulator (you added it to a list; I see no need to do that, as you don't need the numbers if you only want to compute the average (arithmetic mean)). You just have to know how much numbers have been found. I'll show you two solutions. They are similar but the second one is nicer IMO. ******************************************************************** import sre reg = sre.compile(r'Component information \(consensus fork\) = (\d+)') fil = file_to_search def extract_number(fil, reg): acc = 0 freq = 0 f = open(fil) r = sre.compile(reg) for line in f: m = r.search(line) if m: acc += int(m.group(1)) freq += 1 f.close() return (acc, freq) summ = extract_number(fil, reg) print 'Average is %s' % (float(summ[0])/summ[1]) ******************************************************************** Now the second one; it uses a feature called generator. I'm not sure if you already know about them; you use them always if you iterate over a file. Here it's used to obtain the numbers from the file. ******************************************************************** import sre reg = sre.compile(r'Component information \(consensus fork\) = (\d+)') fil = file_to_search def extract_number(fil, reg): f = open(fil) r = sre.compile(reg) acc = 0 for line in f: m = r.search(line) if m: acc += int(m.group(1)) yield acc f.close() summ = freq = 0 for frq, num in enumerate(extract_number(fil, re)): summ = num freq = frq print 'Average is %s' % (float(summ)/(freq+1)) ******************************************************************** Karl -- Please do *not* send copies of replies to me. I read the list From magnus at thinkware.se Wed Dec 10 13:59:49 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 13:59:56 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ291bnRpbmcgbWF0Y2hpbmcgZWxlbWVudHMgaW4gc2VxdWVuY2Vz?= Message-ID: I wrote: > >def alleq(seq): > > for item in seq[1:]: > > if item != seq[0]: > > return False > > return True Gregor wrote: > What do you think about: > > >>> def alleq(seq): > ... return seq == seq[:1]*len(seq) I think that if I had come up with either one I would leave the subject and consider the problem to be solved unless there was a performance problem. If there was a performance problem, I'd use the profiler or the new timeit module to measure which is faster. With very big sequences, there might be a memory issue as well, since "seq[:1]*len(seq)" makes an extra list, but that would probably lead to a performance problem if it caused swapping etc, so the profiler would probably give the same answer as a memory measurement. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Dec 10 14:00:20 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 14:00:27 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ291bnRpbmcgbWF0Y2hpbmcgZWxlbWVudHMgaW4gc2VxdWVuY2Vz?= Message-ID: > > def alleq(seq): > > for item in seq[1:]: > > if item != seq[0]: > > return False > > return True > > I came up with nearly the same one. > > def alleq(seq): > k = seq[0] > for i in seq: > if i != k: > return 0 > return 1 The reason I didn't write it like that was to avoid the IndexError you get in "k = seq[0]" if seq is empty. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Wed Dec 10 14:03:55 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 10 14:04:05 2003 Subject: [Tutor] the 'or' attribute In-Reply-To: Message-ID: On Tue, 9 Dec 2003, Leung Cris wrote: > Umm....okay , I get it. So, how can i have a variable that stores ' this > number, or that number' ? It depends. We can store multiple values by collecting them in a "container". One example of a container is a "List": ### >>> x = ['apple', 'orange'] >>> x ['apple', 'orange'] ### With a list, we can keep both choices grouped together, and extract each one by just pointing to it with an "index": ### >>> x[0] 'apple' >>> x[1] 'orange' ### So this would be one way of storing several values in a group. The usage of "or" in Python is not the one you're familiar with in English. In Python, 'or' is not really meant to present value alternatives. Instead, 'or' is most used for "logical" (true/false) comparisons, within an 'if' or 'while' conditional statement. ^^^^^^^^^^^^^^^ ### if sun_is_shining or rain_is_falling: stay_inside() ### To see if a value is in one of several alternatives, you might be tempted to say something like this: ### if fruit == 'apple' or 'orange' or 'pineapple': ... ### But don't do this! *grin* It's not doing what you think it's doing. One way to express this idea, to check if fruit is either an apple, an orange, or a pineapple, in Python is: ### if fruit in ['apple', 'orange', 'pineapple']: ... ### Another way to say this does involve 'or', but it looks more verbose than you'd expect: ### if fruit == 'apple' or fruit == 'orange' or fruit == 'pineapple': ... ### 'or' is tricky because we use 'or' in two different senses in English. Python uses 'or' in one particular way --- in the boolean 'true/false' sense. I hope this clears up some confusion! From kalle at lysator.liu.se Wed Dec 10 14:13:59 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Wed Dec 10 14:14:04 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: References: Message-ID: <20031210191359.GI12373@i92.ryd.student.liu.se> [Magnus Lycka] > > >def alleq(seq): > > > for item in seq[1:]: > > > if item != seq[0]: > > > return False > > > return True > > Gregor wrote: > > >>> def alleq(seq): > > ... return seq == seq[:1]*len(seq) [...] > With very big sequences, there might be > a memory issue as well, since "seq[:1]*len(seq)" > makes an extra list[.] But so does "for item in seq[1:]:". I think that the cost of the extra comparison caused by removing the slice would often be smaller than the cost of copying the list. Haven't done any profiling, though. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From magnus at thinkware.se Wed Dec 10 14:22:18 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 14:22:23 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ291bnRpbmcgbWF0Y2hpbmcgZWxlbWVudHMgaW4gc2VxdWVuY2Vz?= Message-ID: Kalle Svensson wrote: > [Magnus Lycka] > > > >def alleq(seq): > > > > for item in seq[1:]: > > > > if item != seq[0]: > > > > return False > > > > return True > > > > Gregor wrote: > > > >>> def alleq(seq): > > > ... return seq == seq[:1]*len(seq) > [...] > > With very big sequences, there might be > > a memory issue as well, since "seq[:1]*len(seq)" > > makes an extra list[.] > > But so does "for item in seq[1:]:". I think that the cost of the > extra comparison caused by removing the slice would often be smaller > than the cost of copying the list. Haven't done any profiling, > though. Oops! So change it to "for item in seq:". It will mean that we compare seq[0] with seq[0], which is pointless, but I guess it will save both memory and time in almost all cases anyway. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Wed Dec 10 14:28:55 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 10 14:29:16 2003 Subject: [Tutor] mxTextTools help: find the deepest in nest lists In-Reply-To: <1071035328.3fd6b3c0ad193@webmail-b.uchicago.edu> Message-ID: On Tue, 9 Dec 2003 pan@uchicago.edu wrote: > I am learning how to use mxTextTools. I need help with > the following ... > > I wanna match the deepest lists in a nested list tree. > For example: > > The [2, 2a] and [3, 3b] in : > > [[[1,[2, 2a]],[[3,3b],4]],6] > > The [a.1,b_2] and [d.3,e] in : > > [[a.1,b_2],[[c,[d.3,e]],f]] > > The [a1,a2], [d.1, d.2] and [o3,o4] in : > > [[[[[a1,a2],out],[d.1, d.2]],o2],[[o3,o4],o5]] > > How can I setup a tagtable for matching them ?? Hi Pan, I'm not familiar enough with mxTextTools's tag table stuff. Just to make sure though: are you sure that a text-handling approach is best for this problem? Is your input a originally a data structure, or a string? One way to approach this with regular expressions might be something like this: ### >>> import re >>> def find_innermost_nodes(tree_string): ... regex = re.compile(r"""\[ ## literal open brace ... [^\[]+ ## one or more non-brace ... ## characters ... \] ## literal close brace ... """, re.VERBOSE) ... return regex.findall(tree_string) ... >>> find_innermost_nodes("[[[1,[2, 2a]],[[3,3b],4]],6]") ['[2, 2a]]', '[3,3b],4]],6]'] ### Ooops! Forgot to make the search nongreedy: ### >>> def find_innermost_nodes(tree_string): ... regex = re.compile(r"""\[ ## literal open brace ... [^\[]+? ## one or more non-brace ... ## characters, nongreedily ... \] ## literal close brace ... """, re.VERBOSE) ... return regex.findall(tree_string) ... >>> find_innermost_nodes("[[[1,[2, 2a]],[[3,3b],4]],6]") ['[2, 2a]', '[3,3b]'] ### That's better. *grin* Aren't the tag tables similar to regular expressions? That being said, I think this approach is approaching the problem in a way that doesn't generalize well. If we had some tree structure, I'd approach this with something like: ### def is_innermost_node(node): if is_leaf(node): return false return is_leaf(left(node)) and is_leaf(right(node)) def find_innermost_nodes(node): if is_leaf(node): return [] if is_innermost_node(node): return [node] return (find_innermost_nodes(left(node)) + find_innermost_nodes(right(node))) ### assuming that we have some functions for seeing if a node is a leaf (is_leaf()), and well as ways of getting the left() and right() children of a tree node. Good luck to you! From gerrit at nl.linux.org Wed Dec 10 14:37:44 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed Dec 10 14:38:39 2003 Subject: [Tutor] Is there any standard module for "pretty printing" to stdout? In-Reply-To: <33678E78A2DD4D418396703A750048D45E698B@RIKER> References: <33678E78A2DD4D418396703A750048D45E698B@RIKER> Message-ID: <20031210193744.GA5122@nl.linux.org> Branimir Petrovic wrote: > Subject: [Tutor] Is there any standard module for "pretty printing" to stdout? There is indeed - it is called: pprint, after prettyprint. It does exactly what you want: 20:37:11:232:5 >>> pprint.pprint(dict(locals())) {'PROMPT': '%(pre)s\x1b[01;40;32m%(time)s:\x1b[36m%(vers)s:\x1b[31m%(count)-2s\x1b[00m%(post)s', 'Prompt': , '__builtins__': , '__doc__': None, '__file__': '/home/gerrit/.pythonrc', '__name__': '__main__', 'datetime': , 'division': _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192), 'pprint': , 'readline': , 'rlcompleter': , 'sys': } It is documented at: http://www.python.org/dev/doc/devel/lib/module-pprint.html yours, Gerrit. -- 249. If any one hire an ox, and God strike it that it die, the man who hired it shall swear by God and be considered guiltless. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From sigurd at 12move.de Wed Dec 10 15:10:34 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Dec 10 15:11:46 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: (Magnus Lycka's message of "Wed, 10 Dec 2003 20:00:20 +0100") References: Message-ID: On 10 Dec 2003, Magnus Lycka <- magnus@thinkware.se wrote: >> > def alleq(seq): >> > for item in seq[1:]: >> > if item != seq[0]: >> > return False >> > return True >> I came up with nearly the same one. >> def alleq(seq): >> k = seq[0] >> for i in seq: >> if i != k: >> return 0 >> return 1 > The reason I didn't write it like that was to > avoid the IndexError you get in "k = seq[0]" > if seq is empty. Right. And I wanted to avoid the lookup in the sequence every cycle in the loop. But if we enclose it i a `If seq: ...' then everything is fine. Karl -- Please do *not* send copies of replies to me. I read the list From glingl at aon.at Wed Dec 10 15:18:58 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed Dec 10 15:18:02 2003 Subject: [Tutor] Counting matching elements in sequences In-Reply-To: <01c901c3befe$8fee0fe0$6401a8c0@xp> References: <3FD62CD2.8050407@aon.at> <01c901c3befe$8fee0fe0$6401a8c0@xp> Message-ID: <3FD77FB2.1010402@aon.at> Alan Gauld schrieb: >>On 9 Dec 2003, Gregor Lingl <- glingl@aon.at wrote: >> >> >> >>>What do you think about: >>> >>> >>> >>> def alleq(seq): >>>... return seq == seq[:1]*len(seq) >>>... >>> >>> > >Gregor, I assume you had a reason to use seq[:1] >instead of seq[0]? But I can't think of any. > > Hi Alan, I could have used [seq[0]] instead of seq[:1], but the latter works also if seq is empty, in which case the first would cause an error. Magnus argued about empty lists having "all equal" elements. Gregor From pan at uchicago.edu Wed Dec 10 16:41:27 2003 From: pan at uchicago.edu (pan@uchicago.edu) Date: Wed Dec 10 16:41:41 2003 Subject: [Tutor] mxTextTools help: find the deepest in nest lists In-Reply-To: References: Message-ID: <1071092487.3fd793071ba32@webmail.uchicago.edu> Hi Danny, I did try the re approach earlier, but I got an "maximum recursion" error when the list gets complicated. I guess it is not good for large nested list. So I turned to mxTextTools, which I failed to finish learning it MANY MANY times before. But this time I decided to twist my brain a lot further to see if I can finally learn how it works. I am so interested because first of all it was said to be very fast, which might be critical if I wanna make some programs to work in gene/genome analysis; and secondly, it uses the state machine concept, which is quite alian for a people like me with major in biology. I can sense it is powerful in the future application on our field, but i need to learn before I can decide how right (or wrong) I am. The tagtable concept is quite different from re. Basically it is a collection of 'states'. When parsing, the core engine reads through the target text, check if the read text match a state. Defined in each state is a decision tree, which directs which state will become the next state when matched and which when failed. The mxTextTools itself is quite a briliant work, but the documentation --- IMHO ---- doesn't mean to let someone who doesn't already know about the concept understand. So it is almost impossible to learn, especially for a beginner like me. And, so far, I can't find any tutorial detailed enough. Provided in the chapter 4 of David Mertz's 'Text processing in Python' is a much better documentation but a brief glance seems to get me an impression that the example given is too complicated for a beginner. But, this might change after I have time to go over the entire mxTextTools part back and forth several times. Anyway, thx for the help. If in the end I finally "twist my head" successfully and learn how it works, I might write a tutorial on it. pan Quoting Danny Yoo : > > > On Tue, 9 Dec 2003 pan@uchicago.edu wrote: > > > I am learning how to use mxTextTools. I need help with > > the following ... > > > > I wanna match the deepest lists in a nested list tree. > > For example: > > > > The [2, 2a] and [3, 3b] in : > > > > [[[1,[2, 2a]],[[3,3b],4]],6] > > > > The [a.1,b_2] and [d.3,e] in : > > > > [[a.1,b_2],[[c,[d.3,e]],f]] > > > > The [a1,a2], [d.1, d.2] and [o3,o4] in : > > > > [[[[[a1,a2],out],[d.1, d.2]],o2],[[o3,o4],o5]] > > > > How can I setup a tagtable for matching them ?? > > > Hi Pan, > > I'm not familiar enough with mxTextTools's tag table stuff. Just to make > sure though: are you sure that a text-handling approach is best for this > problem? Is your input a originally a data structure, or a string? > > > One way to approach this with regular expressions might be something like > this: > > ### > >>> import re > >>> def find_innermost_nodes(tree_string): > ... regex = re.compile(r"""\[ ## literal open brace > ... [^\[]+ ## one or more non-brace > ... ## characters > ... \] ## literal close brace > ... """, re.VERBOSE) > ... return regex.findall(tree_string) > ... > >>> find_innermost_nodes("[[[1,[2, 2a]],[[3,3b],4]],6]") > ['[2, 2a]]', '[3,3b],4]],6]'] > ### > > > > Ooops! Forgot to make the search nongreedy: > > ### > >>> def find_innermost_nodes(tree_string): > ... regex = re.compile(r"""\[ ## literal open brace > ... [^\[]+? ## one or more non-brace > ... ## characters, nongreedily > ... \] ## literal close brace > ... """, re.VERBOSE) > ... return regex.findall(tree_string) > ... > >>> find_innermost_nodes("[[[1,[2, 2a]],[[3,3b],4]],6]") > ['[2, 2a]', '[3,3b]'] > ### > > > That's better. *grin* Aren't the tag tables similar to regular > expressions? > > > > > That being said, I think this approach is approaching the problem in a way > that doesn't generalize well. If we had some tree structure, I'd approach > this with something like: > > ### > def is_innermost_node(node): > if is_leaf(node): return false > return is_leaf(left(node)) and is_leaf(right(node)) > > def find_innermost_nodes(node): > if is_leaf(node): > return [] > if is_innermost_node(node): > return [node] > return (find_innermost_nodes(left(node)) + > find_innermost_nodes(right(node))) > ### > > assuming that we have some functions for seeing if a node is a leaf > (is_leaf()), and well as ways of getting the left() and right() children > of a tree node. > > > Good luck to you! > From dyoo at hkn.eecs.berkeley.edu Wed Dec 10 17:41:40 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 10 17:41:46 2003 Subject: [Tutor] mxTextTools help: find the deepest in nest lists In-Reply-To: <1071092487.3fd793071ba32@webmail.uchicago.edu> Message-ID: On Wed, 10 Dec 2003 pan@uchicago.edu wrote: > I did try the re approach earlier, but I got an "maximum recursion" > error when the list gets complicated. I guess it is not good for large > nested list. Hi Pan, Ah! That problem is due to the nongreediness (?) in the regex. But Python 2.3's regex engine is supposed to have added a few special cases for nongreedy matches to avoid the recursion problem. Do you still get the maximum recursion error with 2.3? Anyway, it turns out that we can rewrite the regex to make it work without the nongreediness; it should perform a lot better for you. Try: ### def find_innermost_nodes(tree_string): regex = re.compile(r"""\[ ## literal open brace [^\[\]]+ ## one or more non-brace ## characters \] ## literal close brace """, re.VERBOSE) return regex.findall(tree_string) ### It works correctly for those cases that you've given us: ### >>> find_innermost_nodes("[[[1,[2, 2a]],[[3,3b],4]],6]") ['[2, 2a]', '[3,3b]'] >>> find_innermost_nodes("[[a.1,b_2],[[c,[d.3,e]],f]]") ['[a.1,b_2]', '[d.3,e]'] >>> find_innermost_nodes("[[[[[a1,a2],out],[d.1, d.2]],o2],[[o3,o4],o5]]") ['[a1,a2]', '[d.1, d.2]', '[o3,o4]'] ### and avoids the problems with recursion --- it should work a lot better on complex binary trees strings. What's the data format here that you're working with? The example that you've given us looks similar to the "newick" tree format, http://evolution.genetics.washington.edu/phylip/newicktree.html which is used in applications like phylogenetic trees. The traditional approach for processing these structures is to use a module to do the parsing for us, maybe something like: http://www.daimi.au.dk/~mailund/newick.html Most people do not use regular expressions to directly process structured data, but use an auxillary parser to let them take advantage of the data structure. Just as we try to discourage folks from doing HTML parsing with regular expressions alone, we're trying to discourage you from doing tree processing with regular expressions alone. *grin* Tell us more about the format, and we can look for a parser for it. > The tagtable concept is quite different from re. Basically it is a > collection of 'states'. Regular expressions are, in fact, state machines. There's a direct equivalence between the two. If you want to learn more, there's a very nice introduction in the book "Introduction to the Theory of Computation": http://www-math.mit.edu/~sipser/book.html As a concrete example, the regular expression: a+b can be represented as a finite state machine with three states and three arrows: -\ / | a V / +-----+ a +--+ b +------+ |START|------->| |-------->|FINISH| +-----+ +--+ +------+ The second arrow loops the second state to itself, and is responsible for the repetition of the '*' regex. > When parsing, the core engine reads through the target text, check if > the read text match a state. Defined in each state is a decision tree, > which directs which state will become the next state when matched and > which when failed. Hmmm... Ok, I will definitely have to read: http://www.lemburg.com/files/python/mxTextTools.html closely; I'll take a look later tonight and see why your tag table isn't working the way you expect. I'm sure mxTextTools can handle this problem, but it does seem like a very low level approach. mxTextTools allows us to manually construct the state machine table, but 're' does this for us on a larger scale, handling the states and table details for us. Talk to you later! From magnus at thinkware.se Wed Dec 10 17:41:40 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 17:41:52 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRnc6IGNhcHR1cmluZyBjcmFzaGluZyBhcHBsaWNhdGlvbiAoYXBwbGljYXRpb24gcnVubmluZyB1bmRlciB3aW5kb3dzIGVudmlyb25tZW50KSAtIG5vdyBzZW5kaW5nIHdpdGggcmlnaHQgYWRyZXNzIC4uLg==?= Message-ID: > One is, I thought lots of times, about how great it would be, to have program, sort of "monitoring application", which would save crashing apllication data. I do not mean logging crashing process instructions before crash, like some memory dump, but capturing any event, and unsaved user data going on just before crash occur, only some last important sequenceses (in case of capturing whole program memory from time to time), and not like logging user input all the time. [...] > Second is kind of releated to first, since all applications I would like to monitor are running under Windows. We could have guessed, and this is where the problem lies. The only reasonable solution to those crash problems is to give up on Microsoft and get a real operating system, and real software tools. The simple Unix editor vi has been excellent at crash recovery for decades. And the need for this isn't that the OS is unstable, or that processes kill each other, but because people were editing over unreliable connections to the computer. The price for using Windows is high, and Python can only compensate that to a limited degree. > It is about Python code to be executed in Windows without Python installed. I read here on Tutor something about making some somefile.py2exe executable, but could you tell some more about this, how it looks, how Python code must be written (or just modified) to work under Windows environment. I suppose that kind of programming is much more complicated ... Here I can provide a simpler solution! You can make an executable file that bundles python.exe with your .py-files, and the ones you need to import. There are several such tools, such as py2exe and the McMillan installer. Recently I've come to favour cx_Freeze. It works when the others fail with MemoryError. You can find it with Google. You don't write your Python code any differently--although there are some library modules that will have problems cooperating with these freezers. If I have written a program that I would normally start by running my_prog.py, I will run: FreezePython.exe --base-binary ConsoleBase.exe --install-dir . my_prog.py and I'll end up with my_prog.exe and a few .dll and pyd-files that I need, in the current directory. ConsoleBase.exe (part of cx_Freeze) and my_prog.py must be in the same directory, and FreezePython.exe needs to be in my path (unless I specify it on the command line). Not very hard, is it? Anyone who has the new "my_prog.exe" and the .dll- and pyd-files in a directory, can start the Python program by double-clicking on my_prog.exe. They don't need to install Python. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Dec 10 17:49:26 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 17:49:34 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gVXNpbmcgTGludXggY29tbWFuZHM=?= Message-ID: > >>> os.system('slapadd -l ldif-file.txt') > > It works! Thanks a lot! But that won't transfer the ouput from your command into the python script. if you do: import os file_list = os.popen('ls').readlines() you will get the result of 'ls' into the variable file_list, and can work with that in Python. If you need access to stdin and stderr as well as stdout, it gets a little more complicated, but it's certainly doable. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Dec 10 18:00:14 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 18:00:22 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSXMgdGhlcmUgYW55IHN0YW5kYXJkIG1vZHVsZSBmb3IgInByZXR0eSBwcmludGluZyIgdG8gc3Rkb3V0Pw==?= Message-ID: > I have a need for tabular and rather fancy printing to stdout. What > I dream of - would give me control over setting rules on column width, > cell padding and/or truncation, justification, etc. Intention is to > allow running script connect its hooks into 'tabular thingy 4 fancy > printing', run it and let the 'thingy' take care of appying printing > rules to the output stream as it happens (as the stream is being > genereated). You might want to have a look at the textwrap module. As I understand you, you need to write some kind of stream class that replaces sys.sdtout with your code that uses (maybe) textwrap, but that's not so difficult. I think there are examples of roughly that at the ActiveState Python Cookbook. For really pretty python based printing look at reportlab.com! -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From alan.gauld at blueyonder.co.uk Wed Dec 10 18:02:16 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 10 18:01:30 2003 Subject: [Tutor] Class inheritance: is the kid calling? or the mom ?? References: <1071066839.3fd72ed78e9c1@webmail-b.uchicago.edu> Message-ID: <025201c3bf71$a81a9570$6401a8c0@xp> > Is there anyway that a class method can know who is calling it --- > the kid or the mom ? If yes, then we can do : Yes, pass it in as an argument. Just add a caller parameter to the method: > class Mom(object): > def __init__(self): > ... > def oldfunc(self, caller): # line [1] > ... > if isinstance(caller,Mom) == type(self): > self.someAttr = Mom () # line [3] > elif isinstance(caller,Kid): > self.someAttr = Kid() # line [4] But that's bad OO design, Moms shouldn't know about Kids. Better would be to override the method in Kid: class Kid(Mom): .... def oldfunc(self,caller): if isinstance(caller,Kid): self.someAttr = Kid() else: Mom.oldfunc(self,caller) That way you can keep adding new classes without changing Mom and it's ok for Kids to know about Moms because they already do ( as part of the class declaration). Also you can now extend Kid to GrandKid in the same way: class grandKid(Kid): def oldfunc(self,caller): if isinstance(caller,GrandKid): self.someAttr = GrandKid() else: Kid.oldfunc(self,caller) Which is much easier to maintain. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Wed Dec 10 18:05:29 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 10 18:04:44 2003 Subject: [Tutor] Is there any standard module for "pretty printing" to stdout? References: <33678E78A2DD4D418396703A750048D45E698B@RIKER> Message-ID: <027301c3bf72$1b7f4b50$6401a8c0@xp> > I have a need for tabular and rather fancy printing to stdout. What > I dream of - would give me control over setting rules on column width, > cell padding and/or truncation, justification, etc. Intention is to > allow running script connect its hooks into 'tabular thingy 4 fancy > printing', run it and let the 'thingy' take care of appying printing > rules to the output stream as it happens (as the stream is being > genereated). Have you looked at the % string formatting operator. That allows setting of column width, justification etc. Alan G. From missive at hotmail.com Wed Dec 10 18:07:05 2003 From: missive at hotmail.com (Lee Harr) Date: Wed Dec 10 18:07:11 2003 Subject: [Tutor] Re: Document URI? Message-ID: >I had previously wrote a scrip that accessed a document's URI by getting >os.environ['DOCUMENT_URI'] > >Our server admin recently upgrade to Python2.3 and now Python is saying >that there is no 'DOCUMENT_URI' key. > >I did some googling but I couldn't find a way to access a documents URI >in python... > >FYI, the script is called via a SSI ala: >File called /foo/index.html: > > >Previously the os.environ['DOCUMENT_URI'] would return /foo/index.html >but now its saying there's no value... This is probably not a problem with the new python version, but with some other change that occurred during the upgrade. Where and how was that environment variable being set? It could have been in the .login or .bashrc of the user owning the web server process... Or maybe you are using a web framework that sets that variable when it receives a web request. Which web server / framework are you using? Have you tried seeing what exactly is in os.environ? It is just a dict, you should be able to print it or return it to the browser and read which values are set. _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From abc-100036 at apc.edu.ph Wed Dec 10 18:12:43 2003 From: abc-100036 at apc.edu.ph (abc-100036@apc.edu.ph) Date: Wed Dec 10 18:12:49 2003 Subject: [Tutor] Password Input Message-ID: <20031210231243.771D66507A@cerveza.apc.edu.ph> Hi, - I would like to hide the password being typed by the user in the console. What syntax should i use. - My script goes like these: uname = raw_input('Enter your username: ') pname = raw_input('Enter your password: ') - I like to hide the password the user would be typing in... ThNX!!!! -- Angelo Cruz CSIT-Computer Network Engineer Asia Pacific College ________________________________________________________________________________________ This email message was delivered to you by Asia Pacific College. Scanning and Virus Filtering is delivered by RAV Antivirus. For more information, please visit our website or email the system administrators at mailto:sysadmins@apc.edu.ph. From magnus at thinkware.se Wed Dec 10 18:43:47 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 18:43:54 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUGFzc3dvcmQgSW5wdXQ=?= Message-ID: I thought I replied to this just a few days ago! import getpass pname = getpass.getpass('Enter your password: ') > - I would like to hide the password being typed by the user in the console. > What syntax should i use. > > - My script goes like these: > > uname = raw_input('Enter your username: ') > pname = raw_input('Enter your password: ') -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Dec 10 18:49:29 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 18:49:35 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcmVmZXJlbmNlIHRvIG1haW4gbW9kdWxl?= Message-ID: Luiz Siqueira Neto wrote: > How can I make a reference to main module to use getattr( main, > 'function') on the fly? I don't think anyone quite understood your question. Can you tell us what you are trying to achieve? What do you mean by "main module"? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From BranimirP at cpas.com Wed Dec 10 21:06:28 2003 From: BranimirP at cpas.com (Branimir Petrovic) Date: Wed Dec 10 21:06:32 2003 Subject: [Tutor] Is there any standard module for "pretty printing" to stdout? Message-ID: <33678E78A2DD4D418396703A750048D45E698E@RIKER> > -----Original Message----- > From: Magnus Lycka [mailto:magnus@thinkware.se] > > You might want to have a look at the textwrap module. As I > understand you, you need to write some kind of stream class > that replaces sys.sdtout with your code that uses (maybe) > textwrap, but that's not so difficult. Textwrap module looks useful, thanks for the tip. My goal with this is to be able to replace sys.stdout with a piece of code that "knows" how to print stream or pieces of stream sent to stdout in a table-like manner. Easier of two scenarios I need to find solution for has to do with emulating table formatting capabilities of SQL*Plus. Thanks to cx_Oracle module I can connect to the database and retrieve records, but over and above getting the raw data I'd also like to be able to see query result echoed to stdout (or redirected to log file) in as close to "original" form (as would be seen from within SQL*Plus) as possible. For this I guess I'll need to construct class that can de-spool recordsets in easy to set up, easy to control and above all - in eye appealing manner. Tougher scenario for which I seek solution has to do with replacing stdout with a piece of code that behaves like stdout, but is applying formatting on fly and getting end result in nice looking table-like "printout". The trick here would lie in ability to "wire" different spots in main script to proper "cells" (columns) in the output stream, provide means for one (any) particular place in code to always write to one particular column in (whatever) current row, then provide easy and dynamic way to define table, row, and cell properties (indenting, formatting, padding, truncating, wrapping, printing column titles, defining rules for advancing to next row etc), and provide easy (logical?) way for integrating and reusing such a monster in number of planned future console based scripts. Thanks to all who responded, now I know that if I want to reach one or both of the above goals, I'll have to make custom module(s), as Python by itself does not come with such "battery" (of unstandard size AAA+3/21). Branimir From magnus at thinkware.se Wed Dec 10 15:04:03 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 10 22:47:59 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gbWFrZSBjb2RlIGxlc3MgdWdseS9tb3JlIHB5dGhvbmljPw==?= Message-ID: ashleigh smythe wrote: > Is that awkard and unpythonic? You've mainly missed a few conveniences in Python that would make your code a little more convenient. Using some more features would remove the need for some of your functions, but in general it's quite normal that functions call functions that call functions. This is a normal way of solving problems. Divide the problem in smaller problems and postpone the solution of those smaller problems by making them separate functions or classes or modules or whatever. Learning the features of the builtins and standard library takes some time, and before we do that, we are bound to reinvent the wheel... (That's why it's reccomended that you keep the library manual handy.) > Should the whole thing be in a class - how would I do that? I see no compelling reason in this case, but it would be a small change. > The program simply parses a file that has 10,000 iterations of the > following: Ok. In that case it's obviously correct to work through the file in chunks. (They could be more than one line at a time though.) If it had been convenient to read the whole file into memory, I would have used re.findall which is my favourite in the re module. :) Something like (not really tested): import re data = file(file_name).read() pat = re.compile(r'Component information \(consensus fork\) = (\d+) ') nums = [float(n) for n in pat.findall(data)] print sum(nums)/len(nums) (By using float() instead of int(), I avoid the problem of having to fix the fact that int / int => int, but other solutions would be from __future__ import division import re data = file(file_name).read() pat = re.compile(r'Component information \(consensus fork\) = (\d+) ') nums = [int(n) for n in pat.findall(data)] print sum(nums)/len(nums) or import re data = file(file_name).read() pat = re.compile(r'Component information \(consensus fork\) = (\d+) ') nums = [int(n) for n in pat.findall(data)] print sum(nums)/float(len(nums)) I don't know if there is any performance difference. But either way, this isn't really suitable with a big file. I'll return to your code, but I'll skip the re module (you don't need that for such simple needs) and simplify some other things. > def make_int(mylist): #turns the list of consensus > an_int_list=[int(n) for n in mylist] #fork values from strings to > return an_int_list #integers so I can average > #them. I'd convert each item to int (or float as suggested above) before I appended it to the list. Then this step can be skipped. > def add_up(mylist): #calls function to turn > int_list=make_int(mylist) #strings into > asum=0 #integers. > for x in int_list: #sums up all the values > asum +=x > return asum Use the sum() builtin function. > def average(mylist): #takes the sum of consensus > sum=add_up(mylist) #fork values and finds their > length=len(mylist) #average. > average_confork=sum/length > return average_confork With the advice above, this turns into: def average(mylist): return sum(mylist)/len(mylist) or possibly def average(mylist): return sum(mylist)/float(len(mylist)) That's hardly worth putting in a separate function. > mainlist=[] #initialize the list of > #consensus fork values. Global variables should be avoided!!! > def search(file_to_search): > infile=open(file_to_search, 'r') > for line in infile: > if re.search('Component', line): #searches the input file for > confork=line[45:49] #line containing cons. fork, > mainlist.append(confork) #removes the value and puts > return mainlist #it into a list. And since you return mainlist, you could have defined it inside your search function instead. > def aveconfork(file_to_search): #this executes the whole thing > thelist=search(file_to_search) #so I start the program with But you never use that return value! (You could have used "thelist" instead of "mainlist" in the next line of code.) > finalaverage=average(mainlist) <= HERE! #aveconfork.aveconfork > return finalaverage #('file_to_search') Maybe something like this would be an improvement? from __future__ import division # Get new style division: int / int => float def search(file_to_search): infile = file(file_to_search) mainlist = [] for line in infile: if 'Component' in line: confork = int(line[45:49]) mainlist.append(confork) return mainlist def aveconf(file_to_search): list_of_numbers = search(file_to_search) final_average = sum(list_of_numbers)/len(list_of_numbers) return final_average There is one thing I still don't like. The search function would be more generic if it worked with any sequence. I'd rather open the file in "aveconf". That brings us to: from __future__ import division def search(lines): mainlist = [] for line in lines: if 'Component' in line: confork = int(line[45:49]) mainlist.append(confork) return mainlist def aveconf(file_to_search): my_lines = file(file_to_search) list_of_numbers = search(my_lines) final_average = sum(list_of_numbers)/len(list_of_numbers) return final_average -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From KniftonTF at 13meu.usmc.mil Thu Dec 11 00:18:22 2003 From: KniftonTF at 13meu.usmc.mil (Knifton Cpl Timothy F) Date: Thu Dec 11 00:20:26 2003 Subject: [Tutor] Programming Classes Message-ID: <7CF258B9D970404D87A49BA5A76703A449BD73@lha5mubd01.peleliu.usmc.mil> Does anyone know of a really good web site to read up on python classes and how they work? Thanks. Tim From rmangaliag at slu.edu.ph Thu Dec 11 02:18:59 2003 From: rmangaliag at slu.edu.ph (ali) Date: Thu Dec 11 02:14:04 2003 Subject: [Tutor] about pythonwin Message-ID: <00a201c3bfb7$0cbdedc0$da19a8c0@slu.edu.ph> of all the ide's available, i like pythonwin the most... because of it's simplicity... unfortunately it runs only in windows... :)... has anyone tried to run it successfully in linux (wine)??? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031211/d8e52785/attachment.html From rmangaliag at slu.edu.ph Thu Dec 11 02:19:48 2003 From: rmangaliag at slu.edu.ph (ali) Date: Thu Dec 11 02:14:51 2003 Subject: [Tutor] creating text files Message-ID: <00ab01c3bfb7$28edcf60$da19a8c0@slu.edu.ph> am a newbie and was wondering how to create a new text file in python... tnx... ali -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031211/55b62d18/attachment.html From glingl at aon.at Thu Dec 11 02:39:26 2003 From: glingl at aon.at (Gregor Lingl) Date: Thu Dec 11 02:38:27 2003 Subject: [Tutor] a list comp In-Reply-To: References: Message-ID: <3FD81F2E.4020606@aon.at> RoT schrieb: >Hi list, >why is this valid: > >def merge_list(): > newlist = [] > [newlist.append(index) for index in del_list if index not in keep_list] > return newlist > >and this is not: > >def merge_list(): > newlist = [] > return [newlist.append(index) for index in del_list if index not in keep_list] > >shouldn't the list comp' be evaluated and then returned? > Hi RoT! You're right! And it does! But your second version has two different misunderstandings: (1) the append method for lists invariably returns the None object, so your list comprehension collects as many None-s as you expected indices to be therein. It doesn't return the altered list, it only alters it! (2) however even if it returned the (now extended) newlist, the list comp consisted of a list of growing list, each one one element longer than the previous one and this also would not be what you expected. Right? Basically you can observe this here: >>> newlist = [] >>> print newlist.append(3) None >>> newlist [3] >>> print newlist.append(5) None >>> newlist [3, 5] >>> newlist = [] >>> print [newlist.append(x) for x in 1,3,5] [None, None, None] >>> newlist [1, 3, 5] >>> What you wanted is, I assume, to collect the indices themselves. Using the fact, that the list comprehension itself constructs a new list, it goes simply like this: >>> del_list = range(0,10,2) >>> keep_list = range(0,10,3) >>> del_list [0, 2, 4, 6, 8] >>> keep_list [0, 3, 6, 9] >>> [index for index in del_list if index not in keep_list] [2, 4, 8] >>> HTH, Gregor > > From exnihilo at myrealbox.com Thu Dec 11 05:11:31 2003 From: exnihilo at myrealbox.com (nihilo) Date: Thu Dec 11 05:11:40 2003 Subject: [Tutor] python photo gallery software??? Message-ID: <3FD842D3.8050104@myrealbox.com> hi, Can anybody recommend software for organizing, creating thumbnails, providing web access to (etc...) a photo gallery, written in Python, or have you heard of such a thing? There are plenty of software out there for doing this sort of thing, but I haven't found anything in python -- just php and perl, usually with mysql. It's only for personal use, so it doesn't have to be heavy duty, but i'd like it to be in python so that i can easily modify it for my own use. thanks -n. From clay at shirky.com Thu Dec 11 06:47:23 2003 From: clay at shirky.com (Clay Shirky) Date: Thu Dec 11 06:47:29 2003 Subject: [Tutor] Re: a list comp In-Reply-To: Message-ID: > mmm, ok I sort of get it, though its not exactly intuitive though is it. I > mean, even though newlist.append(x) returns None, the list comp 'does' > evaluate to a new list doesn't it It doesn't evaluate to a new list, it produces a series of discrete results that can be captured as a list. A better way to understand Gregor's description -- "the list comprehension itself constructs a new list" -- is that it produces the expected elements, in the expected order, but deciding to assign those elements to a list variable (or print them etc) is up to you. -clay From darnold02 at sprynet.com Thu Dec 11 07:04:34 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Thu Dec 11 07:03:24 2003 Subject: [Tutor] Re: a list comp In-Reply-To: References: Message-ID: <2F9D4662-2BD2-11D8-9BDC-000A95C4F940@sprynet.com> I'm going to beg to differ on that one. A list comprehension most definitely creates and returns a list: >>> [i for i in range(10)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Without the brackets, it isn't even valid python: >>> i for i in range(10) File "", line 1 i for i in range(10) ^ SyntaxError: invalid syntax Maybe you're thinking of a generator? Don On Dec 11, 2003, at 5:47 AM, Clay Shirky wrote: >> mmm, ok I sort of get it, though its not exactly intuitive though is >> it. I >> mean, even though newlist.append(x) returns None, the list comp 'does' >> evaluate to a new list doesn't it > > It doesn't evaluate to a new list, it produces a series of discrete > results > that can be captured as a list. > > A better way to understand Gregor's description -- "the list > comprehension > itself constructs a new list" -- is that it produces the expected > elements, > in the expected order, but deciding to assign those elements to a list > variable (or print them etc) is up to you. > > -clay > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cybersamurai at terra.com.br Thu Dec 11 08:25:40 2003 From: cybersamurai at terra.com.br (Luiz Siqueira Neto) Date: Thu Dec 11 07:27:44 2003 Subject: [Tutor] reference to main module In-Reply-To: References: Message-ID: <3FD87054.4070009@terra.com.br> I discovery the answer, take a look: import sys main = sys.modules['__main__'] # now I can call some function on the fly # Ex: def test(): print 'yessss' def testStart(funct): getattrib(funct)() # Example using it testStart('test') -------------------------------------------------------------------- This make me create a lot of functions by demand and use polimorphism to call some function using some parameter ------------------ Now you can understand :) -------------------- >>> If you know another way please tell me. <<< Magnus Lycka wrote: >Luiz Siqueira Neto wrote: > > >>How can I make a reference to main module to use getattr( main, >>'function') on the fly? >> >> > >I don't think anyone quite understood your question. >Can you tell us what you are trying to achieve? > >What do you mean by "main module"? > > > From Janssen at rz.uni-frankfurt.de Thu Dec 11 07:45:43 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Dec 11 07:45:58 2003 Subject: [Tutor] creating text files In-Reply-To: <00ab01c3bfb7$28edcf60$da19a8c0@slu.edu.ph> References: <00ab01c3bfb7$28edcf60$da19a8c0@slu.edu.ph> Message-ID: On Thu, 11 Dec 2003, ali wrote: > am a newbie and was wondering how to create a new text file in python... Hello Ali, you need to open a new file and then write to it: file_object = open("file-name", "w") # "w" means open in write mode file_object.write("Write some text\n") # "\n" is a newline file_object.close() # after work is done close the file Best is to compare the Tutorial: http://www.python.org/doc/current/tut/tut.html for details. Section 7.2 . Make some tests with the mode argument (like "w", "a", "r") and with read, readlines and writelines methods of file objects. Under Windows you might want to use modes like "wb" (check the tutorial for this). Michael From magnus at thinkware.se Thu Dec 11 09:26:35 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Dec 11 09:26:41 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcmVmZXJlbmNlIHRvIG1haW4gbW9kdWxl?= Message-ID: Luiz Siqueira Neto wrote: > I discovery the answer, take a look: > > import sys > > main = sys.modules['__main__'] > > # now I can call some function on the fly > # Ex: > > def test(): > print 'yessss' > > def testStart(funct): > getattrib(funct)() > > # Example using it > > testStart('test') Here I get "NameError: global name 'getattrib' is not defined" If you are in the same scope, you can do: >>> def x(): print 'Hello' >>> vars()['x']() Hello If your idea is to access code in the main module from a submodule imported directly or indirectly by __main__, I advice against it. Creating mutual dependencies between modules like that is a bad practice, and a programmer of one module does not expect that an *imported* module expects to find certain functions, or calls code, in the *importing* module. If the submodule need something from the main module, the main module should pass it in as a parameter in a call, or possibly set a variable in the submodule. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From michael.grabietz at img-online.de Thu Dec 11 10:13:35 2003 From: michael.grabietz at img-online.de (Michael Grabietz) Date: Thu Dec 11 10:14:59 2003 Subject: [Tutor] Detecting different list elements and counting them Message-ID: <3FD8899F.8010801@img-online.de> Hi, I have a list like the following: my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ] It would be nice to have the information which elements are in the list and how many times these elements appear in the list. A dictionary as the result like the following would be fine. my_dict = {'ABC':3, 'E':1, 'HJ':2} Thank you for any ideas or hints. Michael From python at comber.cix.co.uk Thu Dec 11 10:22:05 2003 From: python at comber.cix.co.uk (Eddie Comber) Date: Thu Dec 11 10:54:35 2003 Subject: [Tutor] do_it() Message-ID: I see that often when people write OO code they have a main() something like: obj = myObject(param, param, param) obj.do_it() #or obj.action() etc Are there any commanding advantages to making this sort of functionality into an object? The above example is easier written and used as: myfunc(param, param, param) I ask because I have just written a MAKE utility, and having started off as an object I really don't know what the advantages are above a simple function. Best, Eddie. From project5 at redrival.net Thu Dec 11 11:14:44 2003 From: project5 at redrival.net (Andrei) Date: Thu Dec 11 11:17:24 2003 Subject: [Tutor] Re: python photo gallery software??? References: <3FD842D3.8050104@myrealbox.com> Message-ID: <1n26pjudx2odi.195lqo9c5ppud$.dlg@40tude.net> nihilo wrote on Thu, 11 Dec 2003 02:11:31 -0800: > hi, > > Can anybody recommend software for organizing, creating thumbnails, > providing web access to (etc...) a photo gallery, written in Python, or > have you heard of such a thing? There are plenty of software out there Cornice (http://web.tiscali.it/agriggio/cornice.html) is an image viewer. I don't know if it creates thumbnails and webpages, but if it doesn't, you could probably extend it. If that's not good enough, a quick search on the Vaults of Parnassus for "thumbnail" also reveals three results: http://py.vaults.ca/apyllo.py?find=thumbnail&findtype=ts&o=d&od=d&b=a Have a look at them, there's bound to be something in there which suits your needs :). -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From python at comber.cix.co.uk Thu Dec 11 11:38:59 2003 From: python at comber.cix.co.uk (Eddie Comber) Date: Thu Dec 11 11:42:49 2003 Subject: [Tutor] Detecting different list elements and counting them In-Reply-To: Message-ID: Bugger. This works.. my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ] my_dict = {} for item in my_list: if my_dict.has_key(item): my_dict[item] = my_dict[item] + 1 else: my_dict[item] = 1 print my_dict -----Original Message----- From: Edward Comber [mailto:comber@cix.co.uk] Sent: 11 December 2003 16:00 To: Michael Grabietz; tutor@python.org Subject: RE: [Tutor] Detecting different list elements and counting them I would imagine something like my_dict = {} for item in my_list: if my_dict.haskey(item): my_dict[item] = my_dict[item] + 1 else: my_dict[item] = 0 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Michael Grabietz Sent: 11 December 2003 15:14 To: tutor@python.org Subject: [Tutor] Detecting different list elements and counting them Hi, I have a list like the following: my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ] It would be nice to have the information which elements are in the list and how many times these elements appear in the list. A dictionary as the result like the following would be fine. my_dict = {'ABC':3, 'E':1, 'HJ':2} Thank you for any ideas or hints. Michael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Thu Dec 11 11:46:25 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 11 11:45:26 2003 Subject: [Tutor] a list comp References: Message-ID: <005901c3c006$511c1ec0$6401a8c0@xp> > def merge_list(): > newlist = [] > [newlist.append(index) for index in del_list if index not in keep_list] What this does is build a list of return codes from [].append() Probably all Nones. But as a side effect it populates newlist > return newlist So this works... > and this is not: > > def merge_list(): > newlist = [] > return [newlist.append(index) for index in del_list if index not in keep_list] This returns the list of return values - not very useful. Try this: def merge_list(del_list, keep_list): return [index for index in del_list if index not in keep_list] The comprehension creates a list you don't need to initialise one separately. Also its good to pass in the del and keep lists to avoid risk of side effects and make the function reusable with other names.... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Dec 11 11:50:26 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 11 11:49:32 2003 Subject: [Tutor] Programming Classes References: <7CF258B9D970404D87A49BA5A76703A449BD73@lha5mubd01.peleliu.usmc.mil> Message-ID: <006001c3c006$e0b98fe0$6401a8c0@xp> > Does anyone know of a really good web site to read up > on python classes and how they work? Thanks. Do you know OOP already and want to know the mechanics of how Python does OOP internally? If so the Python language reference is a good start. Or do you know how to do OOP in another language but want to know how to do it in Python? In which case the Python tutor is a good place to look. Or do you not know OOP and want to learn itr, using Python as a language? In which case I think my OOP tutor is a good start, enough to let you read the official Python tutor with undersanding. Finally for a general intro to OOP visit the cetus-links.org web site, where lots of tutorials and papers await. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Dec 11 11:54:43 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 11 11:53:47 2003 Subject: [Tutor] creating text files References: <00ab01c3bfb7$28edcf60$da19a8c0@slu.edu.ph> Message-ID: <006a01c3c007$79ab7650$6401a8c0@xp> > am a newbie and was wondering how to create a new text file in python... Check out the files and text page in my tutorial. Basically you open it with myfile = open("foo.txt", "r") # to read myfile2 = open("foo2.txt", "w") # to create a new file for writing myfile3 = open("foo3.txt","a") # to write at the end of an existing file IN more odern versions of Python (v2.x?) you can substitute file() for open(): myfile = file("foo.txt","r") etc... The tutor explains how to read and write data with those files. Finally its a good idea to close the file when done: myfile.close() HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Dec 11 11:57:05 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 11 11:56:06 2003 Subject: [Tutor] Re: a list comp References: <3FD81F2E.4020606@aon.at> Message-ID: <007101c3c007$ce9d8680$6401a8c0@xp> > > >>> [index for index in del_list if index not in keep_list] > > [2, 4, 8] > > so I still would have expected it to be returned. You said it yourself > quote: > > > Using the fact, that the list comprehension > > itself constructs a new list, it goes simply like this: > > i.e were not asking newlist.append to return our newlist, were asking the [result of the list comp] > to be returned, which we both agree is our newlist :) And a list will be returned. But it is a list full of 'None's, one for each append operation. Alan G. From vicki.stanfield at ROCHE.COM Thu Dec 11 11:59:06 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Thu Dec 11 12:00:28 2003 Subject: [Tutor] creating text files Message-ID: A follow-up question if you don't mind.... I open a log file while my program is running, but sometimes the program crashes and leaves no log file. Is there any way to write the file prior to when I actually close it. I guess I could close it and reopen it, but I'd rather just flush the output to the file. --vicki -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Alan Gauld Sent: Thursday, December 11, 2003 11:55 AM To: ali; tutor@python.org Subject: Re: [Tutor] creating text files > am a newbie and was wondering how to create a new text file in python... Check out the files and text page in my tutorial. Basically you open it with myfile = open("foo.txt", "r") # to read myfile2 = open("foo2.txt", "w") # to create a new file for writing myfile3 = open("foo3.txt","a") # to write at the end of an existing file IN more odern versions of Python (v2.x?) you can substitute file() for open(): myfile = file("foo.txt","r") etc... The tutor explains how to read and write data with those files. Finally its a good idea to close the file when done: myfile.close() HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From john at duartedailey.org Thu Dec 11 12:03:12 2003 From: john at duartedailey.org (John Duarte) Date: Thu Dec 11 12:05:49 2003 Subject: [Tutor] Programming Classes In-Reply-To: <006001c3c006$e0b98fe0$6401a8c0@xp> References: <7CF258B9D970404D87A49BA5A76703A449BD73@lha5mubd01.peleliu.usmc.mil> <006001c3c006$e0b98fe0$6401a8c0@xp> Message-ID: <200312110903.12939.john@duartedailey.org> On Thursday 11 December 2003 8:50 am, Alan Gauld wrote: > > Does anyone know of a really good web site to read up > > on python classes and how they work? Thanks. > Or do you not know OOP and want to learn itr, using > Python as a language? > > In which case I think my OOP tutor is a good start, enough > to let you read the official Python tutor with undersanding. > > Finally for a general intro to OOP visit the cetus-links.org > web site, where lots of tutorials and papers await. IMHO, one of the best introductions to the concept of objects is Chapter 1 of Bruce Eckel's "Thinking in Java". http://www.mindview.net/Books/TIJ/ -John From hec.villafuerte at telgua.com.gt Thu Dec 11 14:07:51 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Thu Dec 11 12:06:30 2003 Subject: [Tutor] How to define a callback Message-ID: <3FD8C087.3000807@telgua.com.gt> Hi all! I'm using the ftplib module and need to look for certain files. I'm planning on using string.find on the output of LIST. The question is: how to define a callback for the ftplib function retrlines? i.e. I don't want to print to sys.stdout, I want to print to a string. retrlines(command[, callback]) Retrieve a file or directory listing in ASCII transfer mode. command should be an appropriate "RETR" command (see retrbinary()) or a "LIST" command (usually just the string 'LIST'). The callback function is called for each line, with the trailing CRLF stripped. The default callback prints the line to sys.stdout. Thanks for your help. From bwinton at latte.ca Thu Dec 11 12:11:39 2003 From: bwinton at latte.ca (Blake Winton) Date: Thu Dec 11 12:11:44 2003 Subject: [Tutor] Re: python photo gallery software??? In-Reply-To: <1n26pjudx2odi.195lqo9c5ppud$.dlg@40tude.net> Message-ID: <015f01c3c009$d76a9170$6401a8c0@phantomfiber.com> (Sorry about the duplicate message, Andrei, I hit the wrong key by accident!) > > Can anybody recommend software for organizing, creating > > thumbnails, providing web access to (etc...) a photo gallery, > > written in Python, or have you heard of such a thing? There > > are plenty of software out there > > Cornice (http://web.tiscali.it/agriggio/cornice.html) is an > image viewer. I don't know if it creates thumbnails and > webpages, but if it doesn't, you could probably extend it. > > If that's not good enough, a quick search on the Vaults of > Parnassus for "thumbnail" also reveals three results: > http://py.vaults.ca/apyllo.py?find=thumbnail&findtype=ts&o=d&od=d&b=a > > Have a look at them, there's bound to be something in there > which suits your needs :). I also kept a copy of the following message from the Daily Python Url, which might be what you're looking for: > Per Jensen: Gallery2.py ["Gallery2.py is a small utility which > creates galleries from pictures. It includes a little Tkinter- > based GUI."] http://www.pythonware.com/daily/#106975404340209721 Later, Blake. From hec.villafuerte at telgua.com.gt Thu Dec 11 14:23:27 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Thu Dec 11 12:22:06 2003 Subject: [Tutor] How to define a callback In-Reply-To: <3FD8C087.3000807@telgua.com.gt> References: <3FD8C087.3000807@telgua.com.gt> Message-ID: <3FD8C42F.5090502@telgua.com.gt> H?ctor Villafuerte D. wrote: > Hi all! > > I'm using the ftplib module and need to look for certain > files. I'm planning on using string.find on the output of > LIST. The question is: how to define a callback for the > ftplib function retrlines? i.e. I don't want to print to > sys.stdout, I want to print to a string. > > > retrlines(command[, callback]) > Retrieve a file or directory listing in ASCII transfer mode. > command should be an appropriate "RETR" command (see retrbinary()) > or a "LIST" command (usually just the string 'LIST'). > The callback function is called for each line, with the trailing > CRLF stripped. The default callback prints the line to sys.stdout. > > > Thanks for your help. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Ok, I worked around the callback problem using the 'nlst' functions instead of 'retrlines'. I'm still curious about that callback thing though :) Greetings, Hector ------------------------------------ str_list = '' try: LIST = ftp.nlst('*.' + day) except: print 'not found' for x in range(len(LIST)): str_list = str_list + LIST[x] ------------------------------------ From tpc at csua.berkeley.edu Thu Dec 11 12:23:37 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Dec 11 12:23:46 2003 Subject: [Tutor] do_it() In-Reply-To: Message-ID: <20031211084123.W1075-100000@localhost.name> hi Eddie, I was mulling this over recently, and while it is true the overhead is much higher with OOP, the payoff is easier to read and more functional code. Let me give you an example. I recently wrote a search engine that takes as user input a query and returns results from an audio and video archive. One of the things I needed to do was filter common, or stop, words (e.g., who, is, what, the, of) from go words that would be used in other functions to look up and return results in the index. I also wanted to print out the words filtered to the user, so I had to either duplicate the body of code for a function to return both, or I could write a class called Filter and have two methods in it, getUserGoWords(self) and getUserStopWords(self) using the same logic. The non-OOP way of doing this would be: def getUserGoWords(terms): stop_words_list = ['a', 'about', 'all', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'can', 'did', 'do', 'does', 'for', 'from', 'he', 'how', 'i', 'if', 'in', 'is', 'it', 'may', 'no', 'not', 'of', 'on', 'or', 'that', 'the', 'then', 'these', 'this', 'those', 'to', 'was', 'we', 'what', 'when', 'where', 'which', 'who', 'why', 'with'] terms_list = terms.split() user_go_words = [] for word in terms_list: if word.lower() not in stop_words_list: filtered_terms_list.append(word) return user_go_words def getUserStopWords(terms): stop_words_list = ['a', 'about', 'all', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'can', 'did', 'do', 'does', 'for', 'from', 'he', 'how', 'i', 'if', 'in', 'is', 'it', 'may', 'no', 'not', 'of', 'on', 'or', 'that', 'the', 'then', 'these', 'this', 'those', 'to', 'was', 'we', 'what', 'when', 'where', 'which', 'who', 'why', 'with'] terms_list = terms.split() user_stop_words = [] for word in terms_list: if word.lower() in stop_words_list: user_stop_words.append(word) return user_stop_words and the OOP way of doing this would be: class Filter: def __init__(self, terms): # replace ' with '' for MySQL INSERT terms = terms.replace("'", "''") # this is currently how I handle context searches in Audio Video Archive terms = terms.replace('"', "") stop_words_list = ['&', 'a', 'about', 'all', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'can', 'do', 'does', 'for', 'from', 'he', 'how', 'i', 'if', 'in', 'is', 'it', 'may', 'no', 'not', 'of', 'on', 'or', 'that', 'the', 'then', 'these', 'this', 'those', 'to', 'was', 'we', 'what', 'when', 'where', 'which', 'who', 'why', 'with'] terms_list = terms.split() self.user_go_words = [] self.user_stop_words = [] for word in terms_list: if word.lower() not in stop_words_list: self.user_go_words.append(word) else: self.user_stop_words.append(word) def getUserGoWords(self): return self.user_go_words def getUserStopWords(self): return self.user_stop_words Maybe there is another way of doing this so that one function can return two values, but as far as I know there is no doubt in my mind which makes more sense with respect to future readers of my code and the holy mantra of programming, Keep It Short and Simple. I hope that helps you. On Thu, 11 Dec 2003, Eddie Comber wrote: > I see that often when people write OO code they have a main() something > like: > > obj = myObject(param, param, param) > obj.do_it() #or obj.action() etc > > Are there any commanding advantages to making this sort of functionality > into an object? > > The above example is easier written and used as: > > myfunc(param, param, param) > > I ask because I have just written a MAKE utility, and having started off as > an object I really don't know what the advantages are above a simple > function. > > Best, > Eddie. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python at dhumketu.cjb.net Thu Dec 11 08:26:35 2003 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Thu Dec 11 12:42:36 2003 Subject: [Tutor] Re: Incrementing a line? In-Reply-To: <3FD5B7E4.6060102@bcuc.ac.uk> References: <3FD5B7E4.6060102@bcuc.ac.uk> Message-ID: <20031211132635.GA1011@dhumketu.homeunix.net> +++ Jim Boone [09-12-03 11:54 +0000]: | Howdy all, i hope this is the right list for my query, pythons a bit new | to me, and I'm trying dto something that I can't figure out: | | for s in userlog.readlines(): | for word in s.split(): | if word == ("19(Constraint"): | constraintlog.write(s + "\n") | print "\n\n*****Constraint Violations exist!!*****\n\n" | constraintlog.close() | | Is a section of code i have, it reads a log file and cranks out a log | file on a certain condition, I can get it to write out the same line | which is in the original log file, which is useful, but, what would be | much more useful is if i could write out the line thats 10 lines after | the "19(Constraint", because it's more pertinent, but of course s+10 is | stupidly wrong. | | Any help appreciated, Thanks! | | -- | Jim Boone Well, if you are using *nix, then grep -A no_of_lines_after_match word_to_be_matched logfile > contraintlog Shantanoo From Janssen at rz.uni-frankfurt.de Thu Dec 11 13:04:34 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Dec 11 13:04:42 2003 Subject: [Tutor] creating text files In-Reply-To: References: Message-ID: On Thu, 11 Dec 2003, Stanfield, Vicki {D167~Indianapolis} wrote: > A follow-up question if you don't mind.... > > I open a log file while my program is running, but sometimes the program > crashes and leaves no log file. Is there any way to write the file prior > to when I actually close it. I guess I could close it and reopen it, but > I'd rather just flush the output to the file. file_object.flush() # writes immediatly back to disk you might notice a performance impact when you do it very often (e.g. several/ many times per second) Michael From paul at entropia.co.uk Thu Dec 11 12:59:34 2003 From: paul at entropia.co.uk (paul@entropia.co.uk) Date: Thu Dec 11 13:15:19 2003 Subject: [Tutor] Re: Photo gallery In-Reply-To: Message-ID: <3FD8B086.28474.F6AB685@localhost> Try http://www.net-es.dk/~pj/python/ Gallery.py HTH Paul Butler From dyoo at hkn.eecs.berkeley.edu Thu Dec 11 13:35:18 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 11 13:35:28 2003 Subject: [Tutor] ANN: BayPIGies meeting for Thursday, December 11, 2003 In-Reply-To: Message-ID: (My apologies for the late announcement!) When: Thursday, December 11, 2003 Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: pyNMS features Speaker: Keith Dart About the talk Keith Dart will talk about pyNMS, a project he has hosted on SourceForge. pyNMS allows one to develop network management applications. There will be discussion of the project, as well as discussion about a distributed Python software repository (ala CPAN or Gentoo). For driving directions to Carnegie, as well as information about BayPIGgies, please visit: http://www.baypiggies.net From alan.gauld at blueyonder.co.uk Thu Dec 11 14:33:53 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 11 14:32:53 2003 Subject: [Tutor] reference to main module References: <3FD87054.4070009@terra.com.br> Message-ID: <009101c3c01d$b5f65470$6401a8c0@xp> > I discovery the answer, take a look: Sorry I'm still confused. > import sys > main = sys.modules['__main__'] This assigns to main whatever is the current main module, ie the one you passed to the python interpreter. > # now I can call some function on the fly > # Ex: > > def test(): > print 'yessss' > > def testStart(funct): > getattrib(funct)() > > # Example using it > > testStart('test') But none of this uses the main module anywhere?! test is defined in your local scope and the getattrib('test') just pulls it from the local namespace. You might as well just have called test() directly. What your main variable does allow is for you to do some wacky stuff like this(in pseudo code): for name in dir(main): if type(name) == type(lambda : pass): try: name() except ParameterError: print 'oops it needed args but I duinno what!' In other words you could attempt to find out the functions in the main module and call them, hoping they worked with no arguments... I have no idea why you might want to do that, but you could... But its not what you seem to be trying to do? Alan G. From alan.gauld at blueyonder.co.uk Thu Dec 11 14:39:05 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 11 14:38:04 2003 Subject: [Tutor] Detecting different list elements and counting them References: <3FD8899F.8010801@img-online.de> Message-ID: <009a01c3c01e$7070fa30$6401a8c0@xp> > my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ] > > It would be nice to have the information which elements are in the list > and how many times these elements appear in the list. > > A dictionary as the result like the following would be fine. > > my_dict = {'ABC':3, 'E':1, 'HJ':2} You just answered your own question, coz that's exactly what to do. my_dict = {} for item in my_list: if item in my_dict: my_dict[item] += 1 else: my_dict[item] = 1 There might be a slightly cleverer way to do it using my_dict(get) but I can't be bothered thinking about it... :-) Alan g. From tpc at csua.berkeley.edu Thu Dec 11 14:39:17 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Dec 11 14:39:29 2003 Subject: [Tutor] do_it() In-Reply-To: Message-ID: <20031211111700.S2242-100000@localhost.name> hi Eddie, Wow you are right, I had no idea a function could return two lists. So yes, you could then reduce everything to just one function instead of writing a class. From what I've read though, OO is superior to writing functions because you are then able to: 1) model your problem better 2) reuse code 3) ultimately spend less time finding the best solution I hope that helps you. On Thu, 11 Dec 2003, Edward Comber wrote: > Fair enough, but you could have kept the list of words external to the > functions and used by both. > > Also you can return two lists like... > > def stop_n_go_words(terms): > blah > return stop_list, go_list > > a_stop_list, a_go_list = stop_n_go_words(terms) > > From alan.gauld at blueyonder.co.uk Thu Dec 11 14:48:18 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 11 14:47:17 2003 Subject: [Tutor] do_it() References: Message-ID: <009f01c3c01f$b9f05380$6401a8c0@xp> > obj = myObject(param, param, param) > obj.do_it() #or obj.action() etc > > Are there any commanding advantages to making this sort of functionality > into an object? No, but there some minor advantages. > The above example is easier written and used as: > > myfunc(param, param, param) Only easier used if you never change the program. Making do_it a method allows you to subclass the entire program and change the way it starts by overriding the do_it() method. You can then have another object use your program as a sub-application by calling the do_it method. So far the function approach works fine too, but... You can in fact can have a list of such applets and call each in turn, or in random order or from a menu system etc, by using a single bit of common code: for applet in app_list: applet.do_it(p,p1,p2) And in fact your applet launcher doesn't need to be changed when you create another variation of your applet either... Its not compelling, but can be handy. The real reason for doing it is that its just folowing the OO paradigm to its logical conclusion. Everything in the application is an object, including the application itself... > I ask because I have just written a MAKE utility, and having started off as > an object I really don't know what the advantages are above a simple > function. If its a single object with a single function, probably none. I would expect a Make program to have classes representing files, commands, rules, dependencies etc... The Make application object then binds those together with attributes containing lists of rules, and files and the rules in turn containing commands, file-patterns etc. But maybe thats what you have? Alan G From alan.gauld at blueyonder.co.uk Thu Dec 11 14:51:14 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 11 14:50:19 2003 Subject: [Tutor] creating text files References: Message-ID: <00b401c3c020$22d22630$6401a8c0@xp> > crashes and leaves no log file. Is there any way to write > the file prior to when I actually close it. I guess I could > close it and reopen it, but I'd rather just flush the output > to the file. So why not use the flush() method... :-) Alan G. From tim.one at comcast.net Thu Dec 11 14:54:32 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu Dec 11 14:54:28 2003 Subject: [Tutor] do_it() In-Reply-To: <20031211111700.S2242-100000@localhost.name> Message-ID: [tpc@csua.berkeley.edu] > hi Eddie, > > Wow you are right, I had no idea a function could return two > lists. It really can't, but a Python function can return any object, and, e.g., return a, b returns a tuple object with two elements (a and b). Same thing here: >> Also you can return two lists like... >> >> def stop_n_go_words(terms): >> blah >> return stop_list, go_list That returns a (single) tuple containing two lists, and >> a_stop_list, a_go_list = stop_n_go_words(terms) unpacks the tuple's two elements and binds them to two names. It's really the same thing mechanism as when you do, e.g.: x, y = y, x to "swap" two values. That is, there's nothing special about functions or "return" in this, the mechanism underlying all of these is that the syntax a, b, ..., z in an expression constructs a tuple object (you can parentheses around that too: (a, b, ..., z) and sometimes that can be clearer). >>> def f(): ... return 1, 2 ... >>> a = f() >>> type(a) >>> len(a) 2 >>> a (1, 2) >>> x, y = a >>> x 1 >>> y 2 >>> x, y, z = a Traceback (most recent call last): File "", line 1, in ? ValueError: unpack tuple of wrong size >>> From sigurd at 12move.de Thu Dec 11 15:20:20 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Dec 11 15:25:07 2003 Subject: [Tutor] do_it() In-Reply-To: <20031211111700.S2242-100000@localhost.name> (tpc@csua.berkeley.edu's message of "Thu, 11 Dec 2003 11:39:17 -0800 (PST)") References: <20031211111700.S2242-100000@localhost.name> Message-ID: An unnamed person wrote: > Wow you are right, I had no idea a function could return two > lists. So yes, you could then reduce everything to just one function > instead of writing a class. From what I've read though, OO is superior to > writing functions because you are then able to: You don't write functions if you write OO style? What are methods then? Or do you mean functional style compared with object orienttated style? > 1) model your problem better Why? IMO it depends on the problem. > 2) reuse code That's also perfectly possible with eg. code written in a functional style or imperative style (what are the libs in C? clearly code reuse). > 3) ultimately spend less time finding the best solution I think that's true for every programming style you have a lot of practice in. Karl -- Please do *not* send copies of replies to me. I read the list From chris at heisel.org Thu Dec 11 16:12:56 2003 From: chris at heisel.org (Chris Heisel) Date: Thu Dec 11 16:13:04 2003 Subject: [Tutor] Parsing HTML file Message-ID: <3FD8DDD8.1000600@heisel.org> Hi, I'm working on a Python script that will go through a series of directories and parse some HTML files. I'd like to be able to read the HTML and extract certain components and put them into a MySQL database. For instance, in these files there will be a document title like this:

This is the documents header

There would be content marked like this:

Some content

Some more content

A sub head

Again

I'm wondering what the best way to approach this problem is? I was reading up on htmllib and HTMLParser. Should I use them or do some regexp searches of the files for "

*

"? If I should use htmllib and HTMLParser any suggestions on their use? I gather than I can set event handlers for say, an

, tag, but can I set event handlers for classes, like

, or for blocks of commments like and In a perferct world I would have gotten all this data in an XML format, that would make my life easier, but the files are already there in HTML and I've got to figure out how to extract some of the semantic content and stuff it into a MySQL DB... Many, many thanks in advance for your help, Chris From jfrench at gmsi1.com Thu Dec 11 16:45:41 2003 From: jfrench at gmsi1.com (Joshua French) Date: Thu Dec 11 16:45:51 2003 Subject: [Tutor] Extending Library In-Reply-To: References: <20031211111700.S2242-100000@localhost.name> Message-ID: <1071179140.15385.102.camel@tomservo> I want to extend the telnetlib, and essentially rewrite interact(). Is there a clean/modular way to do this, or would it be easier to just recreate it, and modify it for my own purposes? Thanks, -Josh From littledanehren at yahoo.com Thu Dec 11 17:14:14 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Dec 11 17:14:18 2003 Subject: [Tutor] Extending Library In-Reply-To: <1071179140.15385.102.camel@tomservo> Message-ID: <20031211221414.31255.qmail@web41807.mail.yahoo.com> Joshua French wrote: > I want to extend the telnetlib, and essentially > rewrite interact(). Is > there a clean/modular way to do this, or would it be > easier to just > recreate it, and modify it for my own purposes? > > Thanks, > -Josh Telnetlib is written in pure Python, so you could always just edit it, but you probably don't want to do that. You should probably instead just subclass the Telnet class instead. Assuming you don't use any of the constants defined in telnetlib, your module could look something like this: from telnetlib import Telnet as dumbtelnet class Telnet(dumbtelnet): def interact(self): print "This is where your code goes" but if you use the constants, you should probably just do from telnetlib import *. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Thu Dec 11 17:21:50 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 11 17:21:54 2003 Subject: [Tutor] Parsing HTML file In-Reply-To: <3FD8DDD8.1000600@heisel.org> Message-ID: On Thu, 11 Dec 2003, Chris Heisel wrote: > I'm working on a Python script that will go through a series of > directories and parse some HTML files. [some text cut] > I'm wondering what the best way to approach this problem is? > > I was reading up on htmllib and HTMLParser. Should I use them or do some > regexp searches of the files for "

*

"? Hi Chris, Avoid processing HTML with regular expressions if you can. *grin* There are quite a few HTML parsers in Python, and 'HTMLParser' from the Standard Library is a fine one: http://www.python.org/doc/lib/module-HTMLParser.html > I gather than I can set event handlers for say, an

, tag, but can I > set event handlers for classes, like

, or for blocks > of commments like and HTMLParser handles comments through the 'handle_comment()' event handler. For example, here's a class that extracts comments from HTML text: ### >>> import HTMLParser >>> class CommentExtractor(HTMLParser.HTMLParser): ... def __init__(self): ... HTMLParser.HTMLParser.__init__(self) ... self.comments = [] ... def handle_comment(self, data): ... self.comments.append(data) ... def get_comments(self): ... return self.comments ... >>> >>> extractor = CommentExtractor() >>> extractor.feed(""" ...

Some content

...

Some more content

...

A sub head

...

Again

... """) >>> >>> >>> extractor.get_comments() ['START CONTENT', 'END CONTENT'] ### HTMLParser doesn't, by itself, support handlers by the HTML 'class' attribute , but that functionality is something that we can add on top of HTMLParser. It will probably involve adding handle_starttag() and handle_endtag() handlers, since that's where we can check for that 'class' attribute. If you're parsing XHTML, your program should be even nicer, because then you can use one of the Document Object Model (DOM) modules. > In a perferct world I would have gotten all this data in an XML format, > that would make my life easier, but the files are already there in HTML > and I've got to figure out how to extract some of the semantic content > and stuff it into a MySQL DB... Ah. Ok. No XHTML then, I guess. *grin* But if you can use something like HTML-Tidy: http://www.w3.org/People/Raggett/tidy/ to transform messy HTML into XHTML, then we might be able to use something dom-ish. The minidom and pulldom modules are especially nice: http://www.python.org/doc/lib/module-xml.dom.minidom.html http://www.python.org/doc/lib/module-xml.dom.pulldom.html because they have a method called 'getElementsByTagName()'. That function provides a nice way to dive into the tree structure: ### >>> text = ''' ... ... ...

Some content

... ...

Some more content

... ...

A sub head

... ...

Again

... ... ... ''' >>> >>> from xml.dom.minidom import parseString >>> dom = parseString(text) >>> >>> for paragraph in dom.getElementsByTagName('p'): ... for textNode in paragraph.childNodes: ... print textNode.data ... Some content Some more content Again ### I hope these examples help. Good luck to you! From carroll at tjc.com Thu Dec 11 18:07:01 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 11 18:07:05 2003 Subject: [Tutor] Detecting different list elements and counting them In-Reply-To: <009a01c3c01e$7070fa30$6401a8c0@xp> Message-ID: On Thu, 11 Dec 2003, Alan Gauld wrote: > my_dict = {} > for item in my_list: > if item in my_dict: > my_dict[item] += 1 > else: my_dict[item] = 1 What I've done is: my_dict = {} for item in my_list: my_dict[item] = my_dict.get(item,0) + 1 my_dict.get returns the value of my_dict[item], if it exists, or zero if it does not; then you add one. > There might be a slightly cleverer way to do it using > my_dict(get) This is probably what you had in mind. -- Terry Carroll Santa Clara, CA carroll@tjc.com From littledanehren at yahoo.com Thu Dec 11 18:11:09 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Dec 11 18:11:14 2003 Subject: [Tutor] Parsing HTML file In-Reply-To: <3FD8DDD8.1000600@heisel.org> Message-ID: <20031211231109.50759.qmail@web41808.mail.yahoo.com> Chris Heisel wrote: > Hi, > > I'm working on a Python script that will go through > a series of > directories and parse some HTML files. > > I'd like to be able to read the HTML and extract > certain components and > put them into a MySQL database. > > For instance, in these files there will be a > document title like this: >

This is the documents header

> > There would be content marked like this: > >

Some content

>

Some more content

>

A sub head

>

Again

> > > I'm wondering what the best way to approach this > problem is? > > I was reading up on htmllib and HTMLParser. Should I > use them or do some > regexp searches of the files for "

class="header">*

"? > > If I should use htmllib and HTMLParser any > suggestions on their use? > > I gather than I can set event handlers for say, an >

, tag, but can I > set event handlers for classes, like

class="header">, or for blocks > of commments like and > > In a perferct world I would have gotten all this > data in an XML format, > that would make my life easier, but the files are > already there in HTML > and I've got to figure out how to extract some of > the semantic content > and stuff it into a MySQL DB... > > Many, many thanks in advance for your help, > > Chris I think htmllib or HTMLParser would be overkill. They both go through the whole document and send all of the tags into user-defined functions. This would make a much slower program for it to have to go through all of those tags. It would be much faster to just search for it with regexps. Use the re, not regex, module. The regexp you gave didn't do what you wanted it to, so here's what it should have been: (?s)

(.*?)

Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From zak at harlekin-maus.com Thu Dec 11 18:25:41 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Thu Dec 11 18:25:49 2003 Subject: [Tutor] Detecting different list elements and counting them In-Reply-To: References: <009a01c3c01e$7070fa30$6401a8c0@xp> Message-ID: <2529.192.206.201.184.1071185141.squirrel@webmail.harlekin-maus.com> Hey! And this solves the "count number of matching items in two lists" nicely: ### def count(alist, blist): clist = alist + blist adict = {} for key in clist: if key not in adict: adict[key] = 0 else: adict[key] += 1 return reduce(lambda x, y: x + y, adict.values()) ### --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From carroll at tjc.com Thu Dec 11 18:41:03 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 11 18:41:11 2003 Subject: [Tutor] How to define a callback In-Reply-To: <3FD8C087.3000807@telgua.com.gt> Message-ID: On Thu, 11 Dec 2003, "H?ctor Villafuerte D." wrote: > I'm using the ftplib module and need to look for certain > files. I'm planning on using string.find on the output of > LIST. The question is: how to define a callback for the > ftplib function retrlines? i.e. I don't want to print to > sys.stdout, I want to print to a string. Here's an example of using a callback w/ftplib. I used this as a proof-of-concept for an approach I never went through on on a particular project: ######### import ftplib server = "ftp.fu-berlin.de" remote_dir = "/pub/misc/movies/database/" local_dir = "./IMDB-gzfiles/" filename = "ratings.list.gz" def mycallback(parm): # print "rec'ved ", len(parm), "bytes." outfile.write(parm) outfile = open(local_dir+filename,"wb") f = ftplib.FTP(server) resp = f.login() print resp resp = f.cwd(remote_dir) print resp resp = f.retrbinary("RETR "+filename, mycallback) print resp resp = f.quit() print resp ######### (You can delete the "print resp" statements, they just make me feel bette as I watch.) Basically, when you call f.retrbinary, it will call the routine mycallback every time it receives data. In my routine, I simply write that data out to the file; but you can do something else, like append it to a string, if you want. This is a binary call, but it's basically the same idea for a non-binary calll (your retrlines). -- Terry Carroll Santa Clara, CA carroll@tjc.com From cybersamurai at terra.com.br Thu Dec 11 18:57:56 2003 From: cybersamurai at terra.com.br (Luiz Siqueira) Date: Thu Dec 11 18:53:05 2003 Subject: [Tutor] reference to main module In-Reply-To: References: Message-ID: <3FD90484.4050407@terra.com.br> Ops... sorry. change getattrib to getattr. :) And thanks about your help. Magnus Lycka wrote: >Luiz Siqueira Neto wrote: > > >>I discovery the answer, take a look: >> >>import sys >> >>main = sys.modules['__main__'] >> >># now I can call some function on the fly >># Ex: >> >>def test(): >> print 'yessss' >> >>def testStart(funct): >> getattrib(funct)() >> >># Example using it >> >>testStart('test') >> >> > >Here I get "NameError: global name 'getattrib' is not defined" > >If you are in the same scope, you can do: > > > >>>>def x(): >>>> >>>> > print 'Hello' > > > > >>>>vars()['x']() >>>> >>>> >Hello > >If your idea is to access code in the main module from >a submodule imported directly or indirectly by __main__, >I advice against it. Creating mutual dependencies between >modules like that is a bad practice, and a programmer of >one module does not expect that an *imported* module >expects to find certain functions, or calls code, in the >*importing* module. > >If the submodule need something from the main module, >the main module should pass it in as a parameter in a >call, or possibly set a variable in the submodule. > > > > From jhansmn at hotmail.com Thu Dec 11 19:13:37 2003 From: jhansmn at hotmail.com (j hansen) Date: Thu Dec 11 19:13:42 2003 Subject: [Tutor] newbie evalpostfix Message-ID: How do I modify evalpostfix to parse from left to right so that it follows the order of operations? _________________________________________________________________ Shop online for kids toys by age group, price range, and toy category at MSN Shopping. No waiting for a clerk to help you! http://shopping.msn.com From dyoo at hkn.eecs.berkeley.edu Thu Dec 11 19:31:56 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 11 19:32:00 2003 Subject: [Tutor] newbie evalpostfix [writing a infix parser in Python] In-Reply-To: Message-ID: On Fri, 12 Dec 2003, j hansen wrote: > How do I modify evalpostfix to parse from left to right so that it > follows the order of operations? Hi j, Are you referring to the 'evalpostfix' from 'How To Think Like a Computer Scientist': http://www.ibiblio.org/obp/thinkCSpy/chap18.htm Please don't force us to guess. *grin* Try to make it easier for people to help you with your question. It sounds like you'd like to try writing an 'infix' parser. Infix parsers are actually a little bit harder to do than a postfix parser, because of the whole issue of operator precedence (as well as parenthesized expressions). If you don't need to handle parenthesized expressions, then it won't be so difficult. Will you try to handle things like: (a + b) * c as well as a + b * c ? If you do try to handle the parenthesized expressions, then you're in for some work. *grin* Tell us more about the problem. Good luck to you! From carroll at tjc.com Thu Dec 11 20:43:27 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 11 20:43:31 2003 Subject: [Tutor] Sample9.py and Sample9.pyc & seting path to Python open files ... In-Reply-To: Message-ID: On Tue, 25 Nov 2003, Danny Yoo wrote: > >>> import dis > >>> dis.dis(hello) I love this list. I never knew about the dis module. -- Terry Carroll Santa Clara, CA carroll@tjc.com From chris at heisel.org Thu Dec 11 22:15:34 2003 From: chris at heisel.org (Chris Heisel) Date: Thu Dec 11 22:15:40 2003 Subject: [Tutor] Parsing HTML file In-Reply-To: References: Message-ID: <3FD932D6.6050504@heisel.org> Actually, the HTML might very well be XHTML. The files I've examined have been valid XHTML, however the files were hand coded by a variety of folks so some of them might not be valid, would that cause the dom handler to spaz out? Thanks, Chris Danny Yoo wrote: > > On Thu, 11 Dec 2003, Chris Heisel wrote: > > >>I'm working on a Python script that will go through a series of >>directories and parse some HTML files. > > > [some text cut] > > >>I'm wondering what the best way to approach this problem is? >> >>I was reading up on htmllib and HTMLParser. Should I use them or do some >>regexp searches of the files for "

*

"? > > > > Hi Chris, > > > Avoid processing HTML with regular expressions if you can. *grin* There > are quite a few HTML parsers in Python, and 'HTMLParser' from the Standard > Library is a fine one: > > http://www.python.org/doc/lib/module-HTMLParser.html > > > > >>I gather than I can set event handlers for say, an

, tag, but can I >>set event handlers for classes, like

, or for blocks >>of commments like and > > > HTMLParser handles comments through the 'handle_comment()' event handler. > For example, here's a class that extracts comments from HTML text: > > > ### > >>>>import HTMLParser >>>>class CommentExtractor(HTMLParser.HTMLParser): > > ... def __init__(self): > ... HTMLParser.HTMLParser.__init__(self) > ... self.comments = [] > ... def handle_comment(self, data): > ... self.comments.append(data) > ... def get_comments(self): > ... return self.comments > ... > >>>>extractor = CommentExtractor() >>>>extractor.feed(""" > > ...

Some content

> ...

Some more content

> ...

A sub head

> ...

Again

> ... """) > >>>> >>>>extractor.get_comments() > > ['START CONTENT', 'END CONTENT'] > ### > > > HTMLParser doesn't, by itself, support handlers by the HTML 'class' > attribute , but that functionality is something that we can add on top of > HTMLParser. It will probably involve adding handle_starttag() and > handle_endtag() handlers, since that's where we can check for that 'class' > attribute. > > > > > If you're parsing XHTML, your program should be even nicer, because then > you can use one of the Document Object Model (DOM) modules. > > >>In a perferct world I would have gotten all this data in an XML format, >>that would make my life easier, but the files are already there in HTML >>and I've got to figure out how to extract some of the semantic content >>and stuff it into a MySQL DB... > > > Ah. Ok. No XHTML then, I guess. *grin* > > > But if you can use something like HTML-Tidy: > > http://www.w3.org/People/Raggett/tidy/ > > to transform messy HTML into XHTML, then we might be able to use something > dom-ish. The minidom and pulldom modules are especially nice: > > http://www.python.org/doc/lib/module-xml.dom.minidom.html > http://www.python.org/doc/lib/module-xml.dom.pulldom.html > > because they have a method called 'getElementsByTagName()'. That function > provides a nice way to dive into the tree structure: > > ### > >>>>text = ''' > > ... > ... ...

Some content

> ... ...

Some more content

> ... ...

A sub head

> ... ...

Again

> ... ... > ... ''' > >>>>from xml.dom.minidom import parseString >>>>dom = parseString(text) >>>> >>>>for paragraph in dom.getElementsByTagName('p'): > > ... for textNode in paragraph.childNodes: > ... print textNode.data > ... > Some content > Some more content > Again > ### > > > I hope these examples help. Good luck to you! > From python at dhumketu.cjb.net Thu Dec 11 13:04:23 2003 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Fri Dec 12 00:46:13 2003 Subject: [Tutor] Re: creating text files In-Reply-To: References: Message-ID: <20031211180423.GA975@dhumketu.homeunix.net> +++ Stanfield, Vicki {D167~Indianapolis} [11-12-03 11:59 -0500]: | A follow-up question if you don't mind.... | | I open a log file while my program is running, but sometimes the program | crashes and leaves no log file. Is there any way to write the file prior | to when I actually close it. I guess I could close it and reopen it, but | I'd rather just flush the output to the file. | | --vicki | f=open('test.file','w') f.write('this is a test') f.flush() .... .... .... f.close() f.flush() will write the files to HDD. It flushes the I/O buffer. Shantanoo From Harm_Kirchhoff at mail.digital.co.jp Fri Dec 12 00:51:26 2003 From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp) Date: Fri Dec 12 00:51:31 2003 Subject: [Tutor] round() yields in-expected results/commercial rounding Message-ID: I have the following problem: >>> float(8.7) 8.6999999999999993 >>> float(870)/100 8.6999999999999993 >>> 8.7 * 100 869.99999999999989 >>> round(8.7,2) 8.6999999999999993 >>> math.modf(8.7) (0.69999999999999929, 8.0) >>> int(float(8.7*100)) 869 especially anoying is: >>> n = float(8.7*100) ; print n 870.0 >>> n 869.99999999999989 >>> How can I ensure that 8.7 stays 8.7, so that 8.7 * 100 = 870 and not 869.9999... The way I came up with is: >>> f = float(8.7*100) ; i = int(f) ; i,f (869, 869.99999999999989) >>> if f>=(i+.5): i += 1 ; i 870 I am writing a commercial sales database. To save memory I use integers internally, rather than floats. This means that an amount of 8.70 is converted to 870 internally. if it is converted to 869 I loose 1/10. From alan.gauld at blueyonder.co.uk Fri Dec 12 03:49:13 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Dec 12 03:48:04 2003 Subject: [Tutor] reference to main module References: <3FD87054.4070009@terra.com.br> <009101c3c01d$b5f65470$6401a8c0@xp> <3FD90909.2050405@terra.com.br> Message-ID: <004e01c3c08c$d1417bf0$6401a8c0@xp> Luiz, I'm adding the tutor list to the reply because someone there might have a better idea. My response is below... ----- Original Message ----- From: "Luiz Siqueira" To: "Alan Gauld" Sent: Friday, December 12, 2003 12:17 AM Subject: Re: [Tutor] reference to main module > Sorry, I am not very good with words. : ) > > I make a mistake, > please change getattrib to getattr. > > My idea is use a name of some data in XML > to call the correct function in current module > without needed of make a declaration for all > function. In this way I can grow the number of > functions easily. To use a function you must declare it somewhere, or more accurately you must define it somewhere. Now what I think you mean here is that you want to read the name of a function from an XML file (the creator of which would need to know the function name in advance?) and execute it? The normal way to do this is to use a dictionary. You can either create your own, or use the module's internal dictionary. Personally I prefer to create my own and leave Python to mess with its own internals. Something like: def foo(): pass def bar(): pass my_funcs = { "foo" : foo, "bar" : bar } Then I can process the file(pseudo code warning!): for line in xmlmsg: if line in my_funcs: my_funcs[line]() Is that what you mean? And of course you could map any name to the functions, the dictionary key does not need to match the function name. > suppose I have a data type Carnaval. > Than I use the type name to call the > correct function, and if inside of this > data I have another like Samba, simple I > repeat the same cycle. > > --- > Tell me if you now can understand. :) I think so, but if what I described above isn't what you mean, then sorry, no. Alan G. From python at comber.cix.co.uk Fri Dec 12 03:25:32 2003 From: python at comber.cix.co.uk (Eddie Comber) Date: Fri Dec 12 04:03:56 2003 Subject: [Tutor] do_it() In-Reply-To: <009f01c3c01f$b9f05380$6401a8c0@xp> Message-ID: Thanks Alan, that's clear. I suppose that it's best to OO it to later solve problems still unknown, IYSWIM. My rules and dependencies can at the moment be in dict, but who knows? Eddie. -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: 11 December 2003 19:48 To: Eddie Comber; tutor@python.org Subject: Re: [Tutor] do_it() > obj = myObject(param, param, param) > obj.do_it() #or obj.action() etc > > Are there any commanding advantages to making this sort of functionality > into an object? No, but there some minor advantages. > The above example is easier written and used as: > > myfunc(param, param, param) Only easier used if you never change the program. Making do_it a method allows you to subclass the entire program and change the way it starts by overriding the do_it() method. You can then have another object use your program as a sub-application by calling the do_it method. So far the function approach works fine too, but... You can in fact can have a list of such applets and call each in turn, or in random order or from a menu system etc, by using a single bit of common code: for applet in app_list: applet.do_it(p,p1,p2) And in fact your applet launcher doesn't need to be changed when you create another variation of your applet either... Its not compelling, but can be handy. The real reason for doing it is that its just folowing the OO paradigm to its logical conclusion. Everything in the application is an object, including the application itself... > I ask because I have just written a MAKE utility, and having started off as > an object I really don't know what the advantages are above a simple > function. If its a single object with a single function, probably none. I would expect a Make program to have classes representing files, commands, rules, dependencies etc... The Make application object then binds those together with attributes containing lists of rules, and files and the rules in turn containing commands, file-patterns etc. But maybe thats what you have? Alan G From magnus at thinkware.se Fri Dec 12 04:23:22 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Fri Dec 12 04:23:36 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUGFyc2luZyBIVE1MIGZpbGU=?= Message-ID: Chris Heisel wrote: > Actually, the HTML might very well be XHTML. The files I've examined > have been valid XHTML, however the files were hand coded by a variety of > folks so some of them might not be valid, would that cause the dom > handler to spaz out? It might, but so might any RE-based program you write. I'd suggest using a tried and tested parser or dom as you have been discussing. If you have problems with data, I suggest adding a step to check and fix data before the processing. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Janssen at rz.uni-frankfurt.de Fri Dec 12 05:21:09 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Dec 12 05:24:14 2003 Subject: [Tutor] round() yields in-expected results/commercial rounding In-Reply-To: References: Message-ID: On Fri, 12 Dec 2003 Harm_Kirchhoff@mail.digital.co.jp wrote: > I have the following problem: > > >>> float(8.7) > 8.6999999999999993 > >>> float(870)/100 > 8.6999999999999993 > >>> 8.7 * 100 > 869.99999999999989 > >>> round(8.7,2) > 8.6999999999999993 > >>> math.modf(8.7) > (0.69999999999999929, 8.0) > >>> int(float(8.7*100)) > 869 This is what int is suppose to do. As lib/built-in-funcs.html states: "Conversion of floating point numbers to integers truncates (towards zero)." better: [user@host]# wget http://starship.python.net/crew/aahz/FixedPoint.py [user@host]# python >>> import FixedPoint >>> dir(FixedPoint) ['DEFAULT_PRECISION', 'FixedPoint', '__builtins__', '__doc__', '__file__', '__name__', '__version__', '_mkFP', '_norm', '_parser', '_roundquotient', '_string2exact', '_tento', '_test'] >>> f = FixedPoint.FixedPoint(8.7) >>> f FixedPoint('8.70', 2) >>> f * 100 FixedPoint('870.00', 2) >>> int(f * 100) 870 ---> a simple programming-language arithmetic isn't good enough for Money Application. You will loose some money when you use it (or gain some ;-). So you should look out for solutions made for this problem (google for "python+money"). FixedPoint seems for me like a very good starting point to write your programm correctly. Perhaps FixedPoint offers allready everything you need. But you might also want support different types of commercial rounding conventions (Shall $4.225 be rounded up or down?). I've heard some people work on a Money class to solve exactly these type of things but it is still in progress. There was a python-dev thread not long ago: http://mail.python.org/pipermail/python-dev/2003-October/038902.html This was a "prePEP" (which stands for Python Enhancemeent Proposal) as you notice but it (and the further discussion) might give you some very valueable informations. Michael From cybersamurai at terra.com.br Fri Dec 12 06:49:19 2003 From: cybersamurai at terra.com.br (Luiz Siqueira Neto) Date: Fri Dec 12 05:51:25 2003 Subject: [Tutor] Re: Tutor Digest, Vol 5, Issue 39 In-Reply-To: References: Message-ID: <3FD9AB3F.9070700@terra.com.br> I send to you my unfinished code, here you can see the idea more clear. If you pay attention you see the dictionary implicit inside of module, I use this to make a reference to the correct function declared on end of the code. The general idea of this algorithim is simulate a biological tree growing, with this I can map easyli some data in layout mode (like bits in memory) on a XML model data. -------------- next part -------------- ################################################################################ # Internode and seed ################################################################################ # a set of functions to make a tree grow ################################################################################ """ Author Luiz Siqueira Neto """ from xml.dom.ext.reader.Sax2 import FromXmlFile from xml import xpath import sys self_module = sys.modules[__name__] def seed(XMLmodel, fontFile): """ seed(XMLmodel_file_name, Font_file_name) -> XML DOM tree a seed to start the new tree """ XMLmodel = FromXmlFile(XMLmodel) self_module.tecniquie = xpath.Evaluate('/layout/tecniquie', XMLmodel)[0].childNodes[0].nodeValue internode( XMLmodel.documentElement, open(fontFile).read() ) return XMLmodel class internode: def __init__(self, node, data): """ x.__init__(XML_node, font_string_data) start the growth of the current node if needed. """ for child in node.childNodes: self.data_list = getattr(self_module, 'load_' + node.nodeName)(child, data) for data_part in self.data_list: i = 1 + node.childNodes.index(child) node.childNodes.insert( i, child.cloneNode(True) ) if child.nodeName == u'celula': if not child.getAttribute('key'): child.childNodes[0]._set_nodeValue(data_part) else internode(node.childNodes[i], data_part) def load_layout(node, data): """ load and separe all groups in a list """ groups = None if self_module.tecniquie == u'layout': startFlag = node.getAttribute('startFlag') groups = map( lambda x: startFlag + x, data.split('\x00\n' + startFlag) ) return groups def load_group(node, data): """ load and separe all dataSets in a list """ def load_dataSet(node, data): """ load and separe all celulas in a list """ From vicki at thepenguin.org Fri Dec 12 13:15:14 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Fri Dec 12 13:20:53 2003 Subject: [Tutor] Reuse of callback Message-ID: <38399.206.53.226.235.1071252914.squirrel@www.thepenguin.org> I have a function which is called via a button callback. I would like to reuse this function based on the setting of a radio box button. The existing function is like this: def Pass2ME(self,event): something() and it is called by this: self.pass2mebutton = wxButton(self, 32, label= "Pass to ME", style = wxBU_BOTTOM ,size=(150,20), name = "Pass2ME") EVT_BUTTON(self, 32, self.Pass2ME) now I want to call the same Pass2ME function from a toggle button if the setting is ME. I have the code to create the radio box coded like this: self.MyController=wxRadioBox(self, 35, majorDimension = 1, choices=['UI','ME'], style= wxSUNKEN_BORDER | wxALIGN_BOTTOM|wxRB_SINGLE) EVT_RADIOBOX(self, 35, self.SetMyController) self.SetMyController looks like this: def SetMyController(self,event): if event.GetString() == 'ME': Pass2ME(self, event) else: somethingelse() I am getting an error due to the number of parameters passed to the Pass2ME function. The error is: Traceback (most recent call last): File "F:\wxComTool9.5.py", line 2109, in ? frame=MyFrame(NULL, -1, "Communication Tool") File "F:\wxComTool9.5.py", line 2083, in __init__ panel1 = ComboBoxPanel(self,-1, wxDefaultSize, style=wxSUNKEN_BORDER) File "F:\wxComTool9.5.py", line 98, in __init__ style= wxSUNKEN_BORDER | wxALIGN_BOTTOM|wxRB_SINGLE) File "C:\Python23\Lib\site-packages\wxPython\controls.py", line 969, in __init __ self.this = controlsc.new_wxRadioBox(*_args,**_kwargs) TypeError: new_wxRadioBox() takes at least 3 arguments (2 given) 13:18:13: Debug: e:\Projects\wx2.4\src\msw\app.cpp(439): 'UnregisterClass(canvas )' failed with error 0x00000584 (class still has open windows.). Any help is greatly appreciated. --vicki From dyoo at hkn.eecs.berkeley.edu Fri Dec 12 14:10:45 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 12 14:10:56 2003 Subject: [Tutor] Parsing HTML file [using HTML-Tidy] In-Reply-To: <3FD932D6.6050504@heisel.org> Message-ID: On Thu, 11 Dec 2003, Chris Heisel wrote: > Actually, the HTML might very well be XHTML. The files I've examined > have been valid XHTML, however the files were hand coded by a variety of > folks so some of them might not be valid, would that cause the dom > handler to spaz out? Hi Chris, Yeah, things would probably break without some validation --- the DOM modules require "well-formed" xml. The program HTML-Tidy is meant to take messy HTML, though, and output a variety of well-formed outputs. http://tidy.sourceforge.net/ M.A. Lemburg has written a Python module that exposes HTML-Tidy nicely: http://www.lemburg.com/files/python/mxTidy.html Here's a quicky example of it in action: ### >>> from mx.Tidy import tidy >>> results = tidy('

hello

paragraph 2', output_xhtml=1) >>> print results[2]

hello

paragraph 2

### So one way to approach the problem is to pass all HTML through HTML-Tidy, force it into a nicer structure, and then do your extraction on that well-formed data. And even if you don't take a XML-parsing approach, it's still probably a good idea to use HTML-Tidy as a first curation step, since it'll make the HTML more regular and easier to process. You have to assume that any hand-written HTML has the possiblity of being really wacky --- better for HTML-Tidy to try to figure it out than us. *grin* From vicki at thepenguin.org Fri Dec 12 14:43:24 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Fri Dec 12 14:49:01 2003 Subject: [Tutor] Re: Reuse of callback Message-ID: <49235.206.53.226.235.1071258204.squirrel@www.thepenguin.org> > I have a function which is called via a button callback. I would like to reuse this function based on the setting of a radio box button. The existing function is like this: While I am still continually confused by callback functions which require a different number of parameters than I expect, I did manage to figure this one out. Thanks. --vicki From piir at earthlink.net Fri Dec 12 15:08:08 2003 From: piir at earthlink.net (Todd G. Gardner) Date: Fri Dec 12 15:08:14 2003 Subject: [Tutor] Python used in Data Acquisition systems? Message-ID: Hello all, I would like to use python in my data acquisition system. I have been using LabVIEW which is built around easy DAQ programming. Any suggestions on where to get started. Platform: Windows XP and Linux Thanks, Todd From alan.gauld at blueyonder.co.uk Fri Dec 12 15:15:23 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Dec 12 15:24:32 2003 Subject: [Tutor] Re: Tutor Digest, Vol 5, Issue 39 References: <3FD9AB3F.9070700@terra.com.br> Message-ID: <001a01c3c0ec$ace94750$6401a8c0@xp> > If you pay attention you see the dictionary implicit inside of module, > I use this to make a reference to the correct function declared on end of > the code. Maybe.... > self_module = sys.modules[__name__] This just gets you a reference to your own module. > def seed(XMLmodel, fontFile): > self_module.tecniquie = xpath.Evaluate('/layout/tecniquie', > XMLmodel)[0].childNodes[0].nodeValue And this creates a new module scope variable called tecniquie. Which you could have done with an initialisation to None outside (or by using the global specifier in the function). > class internode: > def __init__(self, node, data): > for child in node.childNodes: > self.data_list = getattr(self_module, > 'load_' + node.nodeName)(child, data) Now this bit is more interesting because here you are getting one of two possible functions ddepending on the data. However you could have domne that by declaring an explicit dictionary: loadFuncs = { "load_group" : load_group, "load_dataSet" : load_dataSet } And then referencing the dictionary: > self.data_list = loadFuncs['load_' + node.nodeName'](child, data) > def load_layout(node, data): > if self_module.tecniquie == u'layout': And this just needs to be a variable reference, no need even for the global qualifier. > def load_group(node, data): > def load_dataSet(node, data): These would need to be defined before the dictionary. At least I think that's how it would work. Its how I would try coding it because I think its easier to see the intent. Alan G. From piir at earthlink.net Fri Dec 12 23:48:11 2003 From: piir at earthlink.net (Todd G. Gardner) Date: Fri Dec 12 23:48:17 2003 Subject: [Tutor] Accessing hardware drivers written in "C"? In-Reply-To: <20031213035203.94199.qmail@web41806.mail.yahoo.com> Message-ID: Hello Daniel, I do need to learn more of the basics in Python so thank you for the suggestions! I would like to use a more robust language and Python seems like an excellent choice. The obstacle to using Python is primarily interfacing to the various Data Acquisition hardware. Most data acquisition boards have drivers written in "C" for Windows and Comedi for Linux. If there are no previous experiences with specific manufactures I guess I will need to learn how Python can access the drivers for the cards that I currently use in LabVIEW. For now I'll specify the National Instruments DAQCard 6062E. Now the question becomes more specific. How to access National Instruments DAQCard 6062E via Ni-DAQ or how to communicate with a program written in "C". I can currently write simple GUIs in Python using wxPython and make simple 2D plots using wxPyPlot. I would like too also do some basic Fourier and statistical analysis, processing and data basing. I would like to output analog and digital signals based on this analysis. I would like to write, distribute <2 Mb applications and that can be prohibitively expensive or completely impossible in LabVIEW. Also, LabVIEW is a great language but as my programs grow more and more complex I find that maintenance can sometimes become cumbersome given the data flow design paradigm. Thank you for any pointers as to how to get started accessing these or any drivers to DAQ or GPIB hardware. Todd > -----Original Message----- > From: Daniel Ehrenberg [mailto:littledanehren@yahoo.com] > Sent: Friday, December 12, 2003 10:52 PM > To: Todd G. Gardner > Subject: Re: [Tutor] Python used in Data Acquisition systems? > > > "Todd G. Gardner" wrote: > > Hello all, > > > > I would like to use python in my data acquisition > > system. I have been using > > LabVIEW which is built around easy DAQ programming. > > > > Any suggestions on where to get started. > > > > Platform: Windows XP and Linux > > > > Thanks, > > > > Todd > > What, specifically, do you want Python to do in this > system? Do you want Python to be just doing rote data > acquisition without much processing? In that case, you > should probably stick with LabVIEW. I would like to write and distribute applications and that is prohibitively expensive in LabVIEW. > Do you want Python > to get the data and do some complex processing with > it? Do you want Python to interact with an existing > LabVIEW program to process data? I would like to write simple GUIs do some basic Fourier and statistical analysis, processing and data basing. I would like to output analog and digital signals based on this analysis. > In those two cases, > you should probably start with learning Python.\ I can currently write simple GUIs in Python using wxPython and make simple 2D plots using wxPyPlot. > Whether you know nothing about Python or you're > already good on most of the basics, the How To Think > Like a Computer Scientist (in Python) tutorial at > http://www.ibiblio.org/obp/thinkCSpy/ would be > beneficial. > > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ From littledanehren at yahoo.com Sat Dec 13 09:47:06 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 13 09:47:11 2003 Subject: [Tutor] Re: Accessing hardware drivers written in "C"? In-Reply-To: Message-ID: <20031213144706.68649.qmail@web41805.mail.yahoo.com> "Todd G. Gardner" wrote: > Hello Daniel, > > I do need to learn more of the basics in Python so > thank you for the > suggestions! I would like to use a more robust > language and Python seems > like an excellent choice. The obstacle to using > Python is primarily > interfacing to the various Data Acquisition > hardware. > > Most data acquisition boards have drivers written in > "C" for Windows and > Comedi for Linux. If there are no previous > experiences with specific > manufactures I guess I will need to learn how Python > can access the drivers > for the cards that I currently use in LabVIEW. For > now I'll specify the > National Instruments DAQCard 6062E. Now the > question becomes more specific. > How to access National Instruments DAQCard 6062E via > Ni-DAQ or how to > communicate with a program written in "C". There are several ways to interface with C code, but unless you want to write in C or write cumbersome configuration files, both of which require the source of the driver, your best bet is ctypes. Ctypes can interface with any existing code that's compiled into a library without having to leave Python. There's probably no existing library to interface with that device as there is with other things like printers. > > I can currently write simple GUIs in Python using > wxPython and make simple > 2D plots using wxPyPlot. I would like too also do > some basic Fourier and > statistical analysis, processing and data basing. I > would like to output > analog and digital signals based on this analysis. > I would like to write, > distribute <2 Mb applications and that can be > prohibitively expensive or > completely impossible in LabVIEW. Also, LabVIEW is > a great language but as > my programs grow more and more complex I find that > maintenance can sometimes > become cumbersome given the data flow design > paradigm. > > Thank you for any pointers as to how to get started > accessing these or any > drivers to DAQ or GPIB hardware. > > Todd __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From littledanehren at yahoo.com Sat Dec 13 11:57:51 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 13 11:57:55 2003 Subject: [Tutor] round() yields in-expected results/commercial rounding In-Reply-To: Message-ID: <20031213165751.49634.qmail@web41806.mail.yahoo.com> Harm_Kirchhoff@mail.digital.co.jp wrote: > I have the following problem: > > >>> float(8.7) > 8.6999999999999993 > >>> float(870)/100 > 8.6999999999999993 > >>> 8.7 * 100 > 869.99999999999989 > >>> round(8.7,2) > 8.6999999999999993 > >>> math.modf(8.7) > (0.69999999999999929, 8.0) > >>> int(float(8.7*100)) > 869 > > especially anoying is: > >>> n = float(8.7*100) ; print n > 870.0 > >>> n > 869.99999999999989 > >>> > > How can I ensure that 8.7 stays 8.7, so that > 8.7 * 100 = 870 and not 869.9999... > > The way I came up with is: > >>> f = float(8.7*100) ; i = int(f) ; i,f > (869, 869.99999999999989) > >>> if f>=(i+.5): i += 1 ; i > > 870 > > I am writing a commercial sales database. To save > memory I use integers > internally, rather than floats. > This means that an amount of 8.70 is converted to > 870 internally. > if it is converted to 869 I loose 1/10. This is annoying, but the only way short of using a library to perform this simple task that I can thing of is to convert the float into a string and then into an integer. Here's a simple function that does that: >>> convert = lambda x: int(str(x*100)[:-2]) >>> convert(8.7) 870 You need the [:-2] to truncate the last two letters because otherwise it would be in the form '870.0', which it can't handle. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From justinstraube at charter.net Sat Dec 13 13:49:50 2003 From: justinstraube at charter.net (justinstraube@charter.net) Date: Sat Dec 13 13:50:05 2003 Subject: [Tutor] [newb] ascii questions Message-ID: <200312131849.hBDInoZN085817@mxsf25.cluster1.charter.net> Hello Tutors, Sorry folks I hit the Send button on accident. I will resend when I finish the mail. sorry. justin From justinstraube at charter.net Sat Dec 13 13:48:39 2003 From: justinstraube at charter.net (justinstraube@charter.net) Date: Sat Dec 13 13:50:14 2003 Subject: [Tutor] [newb] ascii questions Message-ID: <200312131848.hBDImdhU078841@mxsf09.cluster1.charter.net> Hello Tutors, Im working on this and am running into a couple problems I can't figure out. Can anyone offer any hints or anything? My questions follow this little bit import random def process(val): r = val + random.randint(n, amnt) if r < 0: r = r + 26 elif r > 26: r = r - 26 return r count = 0 name = Uname = raw_input('What is your name? ') while 1: #user # as an int and verifies its in range amnt = int(raw_input('Number 1 to 26? ')) if amnt > 26: print 'That number is out of range' continue else: #negetive user # n = -amnt break #processes the users name 5 times while count < 6: #assigns the values of names name = Uname xname = '' #gets 1st characters value for x in name: name_x = ord(name[0]) #uppercase if name_x >= 65 and name_x <= 90: name_x = name_x - 65 x = process(name_x) + 65 #lowercase elif name_x >= 97 and name_x <= 122: name_x = name_x - 96 x = process(name_x) + 96 #if name[0] is a [space] elif name_x == 32: x = 32 name = name[0:] #adds the values character to the processed name xname = xname + chr(x) count = count + 1 print xname if count == 6: print print 'Hit Enter for more' print 'Or ctrl-c to quit' raw_input() count = 0 Im not sure where the problem is in here. When I enter a name with all lower case and a lower number for amnt I get back the results I am expecting. From littledanehren at yahoo.com Sat Dec 13 15:50:42 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 13 15:50:46 2003 Subject: [Tutor] How to define a callback In-Reply-To: <3FD8C087.3000807@telgua.com.gt> Message-ID: <20031213205042.34925.qmail@web41812.mail.yahoo.com> --- "H嶰tor_Villafuerte_D." wrote: > Hi all! > > I'm using the ftplib module and need to look for > certain > files. I'm planning on using string.find on the > output of > LIST. The question is: how to define a callback for > the > ftplib function retrlines? i.e. I don't want to > print to > sys.stdout, I want to print to a string. > > > retrlines(command[, callback]) > Retrieve a file or directory listing in ASCII > transfer mode. > command should be an appropriate "RETR" command > (see retrbinary()) > or a "LIST" command (usually just the string > 'LIST'). > The callback function is called for each line, > with the trailing > CRLF stripped. The default callback prints the > line to sys.stdout. > > > Thanks for your help. What you need to do is make a class that emulates sys.stdout but then change the .write() function to use a string instead. Here's a minimalistic example of how to do that: >>> class strout(object): ... def __init__(self, string=''): ... self.string = string ... def write(self, newstring): ... self.string += newstring ... __str__ = lambda self: self.string You can also have it go to a list, which I think would be more convienent: >>> class listout(object): ... def __init__(self, string=''): ... self.list = [] ... def write(self, newstring): ... self.list.append(newstring) ... __str__ = lambda self: str(self.list) I can't figure out how to make these inherit from the str or list classes, which would make it much more convienent. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From bgailer at alum.rpi.edu Sat Dec 13 20:36:58 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Dec 13 20:37:12 2003 Subject: [Tutor] [newb] ascii questions In-Reply-To: <200312131848.hBDImdhU078841@mxsf09.cluster1.charter.net> References: <200312131848.hBDImdhU078841@mxsf09.cluster1.charter.net> Message-ID: <6.0.0.22.0.20031213164917.0409abd8@mail.mric.net> At 11:48 AM 12/13/2003, justinstraube@charter.net wrote: >Hello Tutors, > >Im working on this and am running into a couple problems I can't figure >out. Can anyone offer any hints or anything? Unfortunately I don' t know the objective of the program or the problems you are having, so I can't help. However there is opportunity to comment a bit about the program. >My questions follow this little bit > >import random >def process(val): The function would be easier to read and understand if n and amnt were also passed as parameters > r = val + random.randint(n, amnt) > if r < 0: > r = r + 26 > elif r > 26: This will never happen! > r = r - 26 > return r >count = 0 >name = Uname = raw_input('What is your name? ') >while 1: > #user # as an int and verifies its in range > amnt = int(raw_input('Number 1 to 26? ')) Consider exception handlers here for user canceling or not entering a number: try: amnt =raw_input('Number 1 to 26? ') except KeyboardInterrupt: sys.exit(0) try: amnt = int(amnt) except ValueError: print 'That is not a number' continue > if amnt > 26: Do you mean: if amnt > 26 or amnt < 1: > print 'That number is out of range' > continue continue here is superfluous. > else: > #negetive user # do you mean NEGATE? > n = -amnt > break >#processes the users name 5 times >while count < 6: > #assigns the values of names > name = Uname > xname = '' > #gets 1st characters value > for x in name: x is not used; in fact it is overridden at x = process.... > name_x = ord(name[0]) You could take advantage of the fact that x takes on successive characters in name: name_x = ord(x) Then you would not need name = name[0:] > #uppercase > if name_x >= 65 and name_x <= 90: > name_x = name_x - 65 > x = process(name_x) + 65 > #lowercase > elif name_x >= 97 and name_x <= 122: > name_x = name_x - 96 > x = process(name_x) + 96 > #if name[0] is a [space] > elif name_x == 32: > x = 32 > name = name[0:] > #adds the values character to the processed name > xname = xname + chr(x) > count = count + 1 > print xname > if count == 6: > print > print 'Hit Enter for more' > print 'Or ctrl-c to quit' > raw_input() > count = 0 > > >Im not sure where the problem is in here. When I enter a name with all >lower case and a lower number for amnt I get back the results I am >expecting. Here is an alternate version, in which I've packaged the input processing in a new function getInput() that handles all the exceptions, put all the character handling in process(), avoided the upper/lower issue by getting a random number in (n, amnt), testing for negative, then adding the ord, and used list comprehension to construct xname, and used some other Python shortcuts. If we knew the purpose of the program there might be some more suggestions. See what you think. import random, string def getInput(prompt, low, high): try: r = raw_input(prompt) except KeyboardInterrupt: return None if valueRange: try: r = int(r) except ValueError: print 'That is not a number' r = None if not low <= r <= high: print 'That number is out of range' r = None return r def process(nameChar, numericLimit): r = random.randint(-numericLimit, numericLimit) if r < 0: r += 26 return chr(r + ord(nameChar)) name = getInput('What is your name? ') while 1: amnt = getInput('Number 1 to 26? ', 1, 26) if amnt: break for y in xrange(1,999999): xname = ''.join([process(x, amnt) for x in name]) print xname if not y % 6: if not getInput('\nHit Enter for more\nOr ctrl-c to quit'): break Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.548 / Virus Database: 341 - Release Date: 12/5/2003 From justinstraube at charter.net Sun Dec 14 06:08:48 2003 From: justinstraube at charter.net (justinstraube@charter.net) Date: Sun Dec 14 06:10:09 2003 Subject: [Tutor] [newb] ascii questions Message-ID: <200312141108.hBEB8mGH009008@mxsf17.cluster1.charter.net> On Sat, 13 Dec 2003 18:36:58 -0700, bgailer@alum.rp... wrote: >>Im working on this and am running into a couple problems I can't figure >>out. Can anyone offer any hints or anything? >Unfortunately I don' t know the objective of the program or the problems >you are having, so I can't help. However there is opportunity to comment a >bit about the program. Thank you, Bob for still taking the time to reply. I accidentally hit send as I went to save the message. My objective is to adjust the users name by a random # of steps either up or down. Within a range of the user given number and its opposite. Then return 5 variations and the option for more. This is similar to an "extrapolate word" feature I had seen in a random word generator program. I was able to do this with dictionaries, name.lower(), and no [space] characters allowed. But am trying to use ord() and chr() to allow for upper and lowercase and the [space] characters. Im trying to filter out non-alpha ascii characters and when 'z' or 'a' are reached it would countinue its steps from the other end. >>import random >>def process(val): >The function would be easier to read and understand if n and amnt were also >passed as parameters I had thought about this but thought in a smaller program I could get away with this. Though you do make a good point about readability for others. >> r = val + random.randint(n, amnt) >> if r < 0: >> r = r + 26 >> elif r > 26: > >This will never happen! Im not sure I understand why not. What Im thinking happens here is that say name[0] = 's' which is 19th in the alphabet, and say the random integer was 9 I would count to 26 and start back at zero and continue until 2 for 'b'. >> r = r - 26 >> return r >>count = 0 >>name = Uname = raw_input('What is your name? ') >>while 1: >> #user # as an int and verifies its in range >> amnt = int(raw_input('Number 1 to 26? ')) > >Consider exception handlers here for user canceling or not entering a number: > try: > amnt =raw_input('Number 1 to 26? ') > except KeyboardInterrupt: > sys.exit(0) > try: > amnt = int(amnt) > except ValueError: > print 'That is not a number' > continue Ive seen exception handlers in my book but havent read up to it yet. Im still tripping over some of the earlier things. >> if amnt > 26: > >Do you mean: > if amnt > 26 or amnt < 1: Yes, thanks. >> print 'That number is out of range' >> continue > >continue here is superfluous. I read again about countinues and breaks and I think Ive got it now. >> else: >> #negetive user # > >do you mean NEGATE? yes, thanks >> n = -amnt >> break >>#processes the users name 5 times >>while count < 6: >> #assigns the values of names >> name = Uname >> xname = '' >> #gets 1st characters value >> for x in name: > >x is not used; in fact it is overridden at x = process.... ok I see now. Ive to try my ideas to be sure though. >> name_x = ord(name[0]) > >You could take advantage of the fact that x takes on successive characters >in name: > name_x = ord(x) >Then you would not need name = name[0:] > >> #uppercase >> if name_x >= 65 and name_x <= 90: >> name_x = name_x - 65 >> x = process(name_x) + 65 >> #lowercase >> elif name_x >= 97 and name_x <= 122: >> name_x = name_x - 96 >> x = process(name_x) + 96 >> #if name[0] is a [space] >> elif name_x == 32: >> x = 32 >> name = name[0:] >> #adds the values character to the processed name >> xname = xname + chr(x) >> count = count + 1 >> print xname >> if count == 6: >> print >> print 'Hit Enter for more' >> print 'Or ctrl-c to quit' >> raw_input() >> count = 0 >Here is an alternate version, in which I've packaged the input processing >in a new function getInput() that handles all the exceptions, put all the >character handling in process(), avoided the upper/lower issue by getting a >random number in (n, amnt), testing for negative, then adding the ord, and >used list comprehension to construct xname, and used some other Python >shortcuts. If we knew the purpose of the program there might be some more >suggestions. See what you think. Im reading over your other pointers and comments and also the alternate version. I havent tested this yet but from what Ive read already, I see a few things which help. Ill work on this some more and hopefully be a bit more gracefull when composing further messages. :) Thanks, Justin >import random, string >def getInput(prompt, low, high): > try: > r = raw_input(prompt) > except KeyboardInterrupt: > return None > if valueRange: > try: > r = int(r) > except ValueError: > print 'That is not a number' > r = None > if not low <= r <= high: > print 'That number is out of range' > r = None > return r >def process(nameChar, numericLimit): > r = random.randint(-numericLimit, numericLimit) > if r < 0: > r += 26 > return chr(r + ord(nameChar)) >name = getInput('What is your name? ') >while 1: > amnt = getInput('Number 1 to 26? ', 1, 26) > if amnt: > break >for y in xrange(1,999999): > xname = ''.join([process(x, amnt) for x in name]) > print xname > if not y % 6: > if not getInput('\nHit Enter for more\nOr ctrl-c to quit'): > break > >Bob Gailer >bgailer@alum.rpi. From pythontutor at venix.com Sun Dec 14 14:47:54 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sun Dec 14 14:47:47 2003 Subject: [Tutor] How to define a callback In-Reply-To: <20031213205042.34925.qmail@web41812.mail.yahoo.com> References: <20031213205042.34925.qmail@web41812.mail.yahoo.com> Message-ID: <3FDCBE6A.2000707@venix.com> The StringIO class (in the StringIO module) probably does what you want. It supports file operations with a buffer that's held in memory. Besides read(), it also supports a method, getvalue() for retrieving the buffer contents as a string. There's also a variant cStringIO that is similar but less flexible with higher performance. Daniel Ehrenberg wrote: > --- "H?ctor_Villafuerte_D." wrote: > >>Hi all! >> >>I'm using the ftplib module and need to look for >>certain >>files. I'm planning on using string.find on the >>output of >>LIST. The question is: how to define a callback for >>the >>ftplib function retrlines? i.e. I don't want to >>print to >>sys.stdout, I want to print to a string. >> >> >>retrlines(command[, callback]) >> Retrieve a file or directory listing in ASCII >>transfer mode. >> command should be an appropriate "RETR" command >>(see retrbinary()) >> or a "LIST" command (usually just the string >>'LIST'). >> The callback function is called for each line, >>with the trailing >> CRLF stripped. The default callback prints the >>line to sys.stdout. >> >> >>Thanks for your help. > > > What you need to do is make a class that emulates > sys.stdout but then change the .write() function to > use a string instead. Here's a minimalistic example of > how to do that: > > >>>>class strout(object): > > ... def __init__(self, string=''): > ... self.string = string > ... def write(self, newstring): > ... self.string += newstring > ... __str__ = lambda self: self.string > > You can also have it go to a list, which I think would > be more convienent: > > >>>>class listout(object): > > ... def __init__(self, string=''): > ... self.list = [] > ... def write(self, newstring): > ... self.list.append(newstring) > ... __str__ = lambda self: str(self.list) > > I can't figure out how to make these inherit from the > str or list classes, which would make it much more > convienent. > > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From barnabydscott at yahoo.com Sun Dec 14 19:09:25 2003 From: barnabydscott at yahoo.com (Barnaby Scott) Date: Sun Dec 14 19:09:30 2003 Subject: [Tutor] returning a web page (and also path to web root) Message-ID: <20031215000925.67079.qmail@web41410.mail.yahoo.com> I am trying to write a cgi script in which under rare circumstances I want the user to see a particular web page (from the same server). I am not very experienced and would be very grateful for help on the right way to tackle this - without knowing a sensible direction to go in I am likely to waste huge amounts of time developing a stupid or overly-complex solution! Presumably if I just read the page in and spat it back out to the user, all the relative links, image sources etc would be wrong. However I was a little reluctant to start messing with the SimpleHTTPServer module - a. because I find it daunting and b. I wondered if there was something altogether simple and obvious I could do. One more quick question: is there an easy way of returning the actual path of the webserver's web root? (Forgive my terminology if it's not right - I mean the root directory as far as the someone accessing the site is concerned). __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From alan.gauld at blueyonder.co.uk Sun Dec 14 19:42:05 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Dec 14 19:42:33 2003 Subject: [Tutor] [newb] ascii questions References: <200312131848.hBDImdhU078841@mxsf09.cluster1.charter.net> Message-ID: <006c01c3c2a4$4381c8f0$6401a8c0@xp> I'm not sure what exactly you are trying to achieve but nonetheless here are some comments and opinions... > def process(val): > r = val + random.randint(n, amnt) > if r < 0: > r = r + 26 > elif r > 26: > r = r - 26 > return r You use n and amnt in the function so you would be better to pass n and amnt in as parameters rather than rely on global variables. > count = 0 > name = Uname = raw_input('What is your name? ') > while 1: > #user # as an int and verifies its in range > amnt = int(raw_input('Number 1 to 26? ')) > if amnt > 26: > print 'That number is out of range' > continue > else: > #negetive user # > n = -amnt > break If the user types a "correct" value then n is set to the negative. Even if amnt is itself negative? Shouldn't the check for invalid also test for <=0? That is: if 0 >= amnt < 26: n = -amnt break else: print... If the user types zero as it is then process(val) will return val when val is between 0 and 26, is that correct behaviour? > #processes the users name 5 times > while count < 6: Using a while count when you know you want to do it 5 times is both counter intuitive and less readable - especially with count intialised many lines above. Better to use for count in range(5) > #assigns the values of names > name = Uname > xname = '' > #gets 1st characters value > for x in name: > name_x = ord(name[0]) > #uppercase > if name_x >= 65 and name_x <= 90: > name_x = name_x - 65 > x = process(name_x) + 65 Why write assembler in Python? Why not just compare to 'A' etc? Or even the isupper and islower string methods. It might be marginally slower but it's much more readable. We could rewrite it like this: for c in name: if c.isupper(): name_x = ord(c) - 65 x = process(name_x) + 65 > #lowercase > elif name_x >= 97 and name_x <= 122: > name_x = name_x - 96 > x = process(name_x) + 96 and elif c.islower(): name_x = ord(c) - 96 x = process(name_x) + 96 and shouldn't 96 be 97?? > #if name[0] is a [space] > elif name_x == 32: > x = 32 and elif c = ' ': x = 32 > name = name[0:] This line does nothing at all! Or more accurately it assigns name to a new copy of itself... > #adds the values character to the processed name > xname = xname + chr(x) Now we repeat for as many characters are in name, but always processing the first letter? Assuming you wanted to process each letter in turn then you could have done it more simply without doing the extraction and reassignment. I'm not really sure whether you mean to repeatedly process the first letter or to process each letter in turn? > count = count + 1 > print xname > if count == 6: > print > print 'Hit Enter for more' > print 'Or ctrl-c to quit' > raw_input() > count = 0 This test could be rewritten: again = raw_input("Repeat [y/n]? ") if again in 'nN': break else : count = 0 Asking users to hit control keys etc is a bit unfriendly IMHO. Of course this test is why you used the while lop and not a 'for' as suggested above. But if you use a test as I've shown you can use a more radable while, like repeat = '' while repeat not in 'nN': ...for loop here... repeat = raw_input("Repeat [y/n]? ") > Im not sure where the problem is in here. When I enter a name with all > lower case and a lower number for amnt I get back the results I am > expecting. I'm not sure what you get back at other times, but make your code easier to read and it will be easier to debug too... Alan g. From littledanehren at yahoo.com Sun Dec 14 20:48:15 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Dec 14 20:48:20 2003 Subject: [Tutor] returning a web page (and also path to web root) In-Reply-To: <20031215000925.67079.qmail@web41410.mail.yahoo.com> Message-ID: <20031215014815.47877.qmail@web41802.mail.yahoo.com> Barnaby Scott wrote: > I am trying to write a cgi script in which under > rare > circumstances I want the user to see a particular > web > page (from the same server). > > I am not very experienced and would be very grateful > for help on the right way to tackle this - without > knowing a sensible direction to go in I am likely to > waste huge amounts of time developing a stupid or > overly-complex solution! > > Presumably if I just read the page in and spat it > back > out to the user, all the relative links, image > sources > etc would be wrong. > > However I was a little reluctant to start messing > with > the SimpleHTTPServer module - a. because I find it > daunting and b. I wondered if there was something > altogether simple and obvious I could do. > Try using the Twisted framework. Among several other protocalls, Twisted can act as a web server. It is written completely in Python so it's very portable. With Twisted's web server, you can use static websites or traditional CGI, but it's much more efficient to use Twisted's own persistent framework with all of these great templating and distributed object tools. > One more quick question: is there an easy way of > returning the actual path of the webserver's web > root? > (Forgive my terminology if it's not right - I mean > the > root directory as far as the someone accessing the > site is concerned). I'm not really sure what you mean. Don't you have to define that on the web server software itself and it isn't some kind of underlying thing available from every program? This might be possible with something like mod_python, but not in a more general way. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Mon Dec 15 04:22:28 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 15 04:22:34 2003 Subject: [Tutor] newbie evalpostfix [writing a infix parser in Python] In-Reply-To: Message-ID: On Fri, 12 Dec 2003, j hansen wrote: > You raise some good points. I need the evalpostfix (from ch.18) to > evaluate "5*4+300/(5-2)*(6+4)+4". So far, I'm able to tokenize this > expression and to convert it to a polish post order format. > Unfortunately, the evalpostfix does not operate correctly because it > uses "*" before "/". Hello! (Please keep tutor@python.org in CC; this makes sure that someone can continue the discussion, even if I get negligent in checking my email...) Both multiplication and division should have the same order of precedence. Something like: "5*4+300/(5-2)*(6+4)+4" should be transformed into: [+ [+ [* 5 4] [* [/ 300 [- 5 2]] [+ 6 4]]] 4] in "prefix" notation. I'm just using prefix notation because I'm more used to it, but going from this "prefix" notation to "postfix" notation just involves a little reordering of things. > Thus, it does not evaluate according to the order of precedence. Can you show us how your program translates the original string? Writing an infix parser is not exactly a trivial thing to do. It's actually a classic exercise for people who are learning how to build programming language compilers! But I'll sketch some of the steps that a person would use to write this parser from scratch. Actually, the easy approach would be to not try to write things from scratch, but to use one of the automatic "parser-generator" modules. For example: http://theory.stanford.edu/~amitp/Yapps/ provides a tools called Yapps that automatically generates a program, given a specification of the "grammar". And Amit Patel already has a parser for arithmetic expressions: http://theory.stanford.edu/~amitp/Yapps/expr.py so you may just want to swipe his code. *grin* One of the first steps for parsing a string is to design a grammar for the language that interests us. For stuff like arithmetic expressions, we can design a "grammar" for a language of arithmetic. It might look something like this: """ expression ::= factor | factor '+' factor | factor '-' factor factor ::= term | term '*' term | term '/' term term ::= NUMBER | '(' expression ')' """ This grammar is still non-executable at the moment, but let's use it for a moment. In a "grammar", we define the names of "rules" on the left side of the '::=' symbol, and their expansions on the right side. In the above grammar, we say that an 'expression' can be a single factor, or it can be expanded out as two factors that are being added or subtracted. For example: 5 * 6 + 7 can be seen as two 'factors' being added together. The first factor itself is a product of two 'terms'. Let me draw it more graphically: expression / | \ / | \ factor '+' factor / | \ | / | \ term term '*' term | | | NUMBER(7) NUMBER(5) NUMBER(6) It's not obvious at first, but these rules are designed in a way so that the 'precedence' of an expression is built in --- multiplication binds more tightly because of the relationship between 'terms' and 'factors', so something like '5 + 6 * 7' will have a parse tree that reflects the precedences that we'd expect from multiplication and addition. Another way to represent a parse tree like the above is with nested lists. Something like: ['+', ['*', 5, 6], 7] captures the structure of the parse tree above, if we assume that the operator is the first element of each list, and the operands are the rest of the list. If we can take a string and break it down into a nested list structure like this, then it becomes easier to generate a 'postfix' representation, because all that's involved is a bit of list manipulation, although you will probably need to write something recursive. Anyway, for convenience, here's some very rough Python code that can translate arithmetic strings into parsed expression lists. ### """A small parser for arithmetic expressions. Demonstration of recursive descent parsing. Transforms expressions into prefix form, using nested lists. For example, we expect something like: "5*4+300/(5-2)*(6+4)+4" to be parsed into the nested list: ['+', ['+', ['*', 5, 4], ['*', ['/', 300, ['-', 5, 2]], ['+', 6, 4]]], 4] Each nested list represents a subexpression, and has three components: [operator, left_subexpression, right_subexpression] For reference, the grammar that we parse is: expression ::= factor | factor '+' factor | factor '-' factor factor ::= term | term '*' term | term '/' term term ::= NUMBER | '(' expression ')' (We use a small trick with 'while' loops to avoid doing explicit recursion.) """ """Here are the symbolic tokens that we'll process:""" PLUS = '+' MINUS = '-' TIMES = '*' DIVIDE = '/' LPAREN = '(' RPAREN = ')' EOF = 'EOF' def main(): """Some test code.""" ## test of parsing: "5*4+300/(5-2)*(6+4)+4" print ArithmeticParser([ 5, TIMES, 4, PLUS, 300, DIVIDE, LPAREN, 5, MINUS, 2, RPAREN, TIMES, LPAREN, 6, PLUS, 4, RPAREN, PLUS, 4, EOF]).parse_expression() class ArithmeticParser: """Parses a token list and returns a nested expression structure in prefix form.""" def __init__(self, tokens): self.tokens = tokens def peek_token(self): """Looks at the next token in our token stream.""" return self.tokens[0] def consume_token(self): """Pops off the next token in our token stream.""" next_token = self.tokens[0] del self.tokens[0] return next_token def parse_expression(self): """Returns a parsed expression. An expression may consist of a bunch of chained factors.""" expression = self.parse_factor() while True: if self.peek_token() in (PLUS, MINUS): operation = self.consume_token() factor = self.parse_factor() expression= [operation, expression, factor] else: break return expression def parse_factor(self): """Returns a parsed factor. A factor may consist of a bunch of chained terms.""" factor = self.parse_term() while True: if self.peek_token() in (TIMES, DIVIDE): operation = self.consume_token() term = self.parse_term() factor = [operation, factor, term] else: break return factor def parse_term(self): """Returns a parsed term. A term may consist of a number, or a parenthesized expression.""" if self.peek_token() != LPAREN: return int(self.consume_token()) else: self.consume_token() ## eat up the lparen expression = self.parse_expression() self.consume_token() ## eat up the rparen return expression if __name__ == '__main__': main() ### The main() function shows a really minimal test of the system --- it parses a list of tokens that represents the string "5*4+300/(5-2)*(6+4)+4". I took a lot of shortcuts here --- I'm not doing any error trapping here, and I'm sure there's still some bugs in there somewhere. Since this code is only meant to be a minimal example of a parser, I hope you don't mind. *grin* Does this help? Good luck to you! From hameedkhaan at yahoo.com Mon Dec 15 06:13:58 2003 From: hameedkhaan at yahoo.com (Hameed Khan) Date: Mon Dec 15 06:14:04 2003 Subject: [Tutor] strange difference between two functions Message-ID: <20031215111358.38075.qmail@web20419.mail.yahoo.com> hi, i was reading the tutorial comes with python documentation. i found 2 example functions in it. but i cant understand these functions because of their different output. so if any one of you out there can tell me why there are giving different outputs just because of a if check. that will be very nice of you. below is the output directly copied from interactive python prompt. # function one # >>> # function one ... def f(a, L=[]): ... L.append(a) ... return L ... >>> f(1) [1] >>> f(2) [1, 2] >>> f(3) [1, 2, 3] # function two # >>> # function two ... def f2(a, L=[]): ... if not L: ... L = [] ... L.append(a) ... return L ... >>> f2(1) [1] >>> f2(2) [2] >>> f2(3) [3] >>> Thanks in advance. Hameed Khaan __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From barnabydscott at yahoo.com Mon Dec 15 09:02:15 2003 From: barnabydscott at yahoo.com (Barnaby Scott) Date: Mon Dec 15 09:02:20 2003 Subject: [Tutor] returning a web page (and also path to web root) Message-ID: <20031215140215.14738.qmail@web41413.mail.yahoo.com> Thanks for your reply, but I am still unclear. I know nothing about the Twisted framework, and I feel it is likely to be way over the top for what I want - I was after 2 or lines of code! I just want to serve up an exisitng page if certain conditions are met - mostly the script is not in the business of being a webserver, as it is running on a 'proper' one anyway. As to the path to the web root, I suspect I am not being clear. What I am after is the actual path as far as the machine is concerned, to the root directory as far as the http host is concerned. I feel sure there must be a way of returning it, in much the same way as you can get at the actual path to the script with os.getenv('SCRIPT_FILENAME') or os.path.abspath(sys.argv[0]). I mean, I know what the path is, but if the configuration of the server was to change, or I wanted to install the script elsewhere, I don't want to have to rewrite it. > Barnaby Scott wrote: > > I am trying to write a cgi script in which under > > rare > > circumstances I want the user to see a particular > > web > > page (from the same server). > > > > I am not very experienced and would be very grateful > > for help on the right way to tackle this - without > > knowing a sensible direction to go in I am likely to > > waste huge amounts of time developing a stupid or > > overly-complex solution! > > > > Presumably if I just read the page in and spat it > > back > > out to the user, all the relative links, image > > sources > etc would be wrong. > > > > However I was a little reluctant to start messing > > with > > the SimpleHTTPServer module - a. because I find it > > daunting and b. I wondered if there was something > > altogether simple and obvious I could do. > > > Try using the Twisted framework. Among several other > protocalls, Twisted can act as a web server. It is > written completely in Python so it's very portable. > With Twisted's web server, you can use static websites > or traditional CGI, but it's much more efficient to > use Twisted's own persistent framework with all of > these great templating and distributed object tools. > > > One more quick question: is there an easy way of > > returning the actual path of the webserver's web > > root? > > (Forgive my terminology if it's not right - I mean > > the > > root directory as far as the someone accessing the > > site is concerned). > > I'm not really sure what you mean. Don't you have to > define that on the web server software itself and it > isn't some kind of underlying thing available from > every program? This might be possible with something > like mod_python, but not in a more general way. > > Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From magnus at thinkware.se Mon Dec 15 10:15:07 2003 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon Dec 15 10:15:26 2003 Subject: [Tutor] returning a web page (and also path to web root) In-Reply-To: <20031215000925.67079.qmail@web41410.mail.yahoo.com> Message-ID: <5.2.1.1.0.20031215155201.023822e0@www.thinkware.se> At 16:09 2003-12-14 -0800, Barnaby Scott wrote: >I am trying to write a cgi script in which under rare >circumstances I want the user to see a particular web >page (from the same server). That's easy. Just return the location of the page from the CGI script: print "Location: http://www.example.com/index.html\n\n" The web browser will then fetch that page. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From pythontutor at venix.com Mon Dec 15 10:22:43 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Dec 15 10:22:48 2003 Subject: [Tutor] returning a web page (and also path to web root) In-Reply-To: <20031215014815.47877.qmail@web41802.mail.yahoo.com> References: <20031215014815.47877.qmail@web41802.mail.yahoo.com> Message-ID: <3FDDD1C3.2000702@venix.com> I believe that a simpler approach would be to use a Location HTTP header to force the client browser to load the desired page. A standalone script like this should work: #! /usr/local/bin/python # redirect.py print "Location: http://www.MYDOMAIN.com/some_page.html\n" Point your browser to: http://www.MYDOMAIN.com/cgi-bin/redirect.py Your browser should switch to the alternative web page. NOTE the \n at the end of the Location: header line. The headers are spearated from the body of the output stream by a blank line. print will automatically append a newline. The "\n" forces an additional line which will be blank. Prove that this simple script works for you. Then update the logic of your CGI script to output this header when appropriate. Daniel Ehrenberg wrote: > Barnaby Scott wrote: > >>I am trying to write a cgi script in which under >>rare >>circumstances I want the user to see a particular >>web >>page (from the same server). >> >>I am not very experienced and would be very grateful >>for help on the right way to tackle this - without >>knowing a sensible direction to go in I am likely to >>waste huge amounts of time developing a stupid or >>overly-complex solution! >> >>Presumably if I just read the page in and spat it >>back >>out to the user, all the relative links, image >>sources >>etc would be wrong. >> >>However I was a little reluctant to start messing >>with >>the SimpleHTTPServer module - a. because I find it >>daunting and b. I wondered if there was something >>altogether simple and obvious I could do. >> > > Try using the Twisted framework. Among several other > protocalls, Twisted can act as a web server. It is > written completely in Python so it's very portable. > With Twisted's web server, you can use static websites > or traditional CGI, but it's much more efficient to > use Twisted's own persistent framework with all of > these great templating and distributed object tools. > > >>One more quick question: is there an easy way of >>returning the actual path of the webserver's web >>root? >>(Forgive my terminology if it's not right - I mean >>the >>root directory as far as the someone accessing the >>site is concerned). > > > I'm not really sure what you mean. Don't you have to > define that on the web server software itself and it > isn't some kind of underlying thing available from > every program? This might be possible with something > like mod_python, but not in a more general way. > > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From pythontutor at venix.com Mon Dec 15 10:44:16 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Dec 15 10:44:22 2003 Subject: [Tutor] returning a web page (and also path to web root) In-Reply-To: <20031215000925.67079.qmail@web41410.mail.yahoo.com> References: <20031215000925.67079.qmail@web41410.mail.yahoo.com> Message-ID: <3FDDD6D0.7040206@venix.com> (I already suggested using the Location: HTTP header, but decided to add more.) Barnaby Scott wrote: > I am trying to write a cgi script in which under rare > circumstances I want the user to see a particular web > page (from the same server). > > I am not very experienced and would be very grateful > for help on the right way to tackle this - without > knowing a sensible direction to go in I am likely to > waste huge amounts of time developing a stupid or > overly-complex solution! > > Presumably if I just read the page in and spat it back > out to the user, all the relative links, image sources > etc would be wrong. Not true. Your script will operate relative to the cgi-bin directory. However, if you simply copy a page of HTML back to the browser, the browser will not know that your CGI sent the HTML as opposed to the regular HTTPD server. It will simply process the HTML it receives. Your script would have trouble resolving the image tags and relative links, but it does not have to resolve anything within the HTML. > > However I was a little reluctant to start messing with > the SimpleHTTPServer module - a. because I find it > daunting and b. I wondered if there was something > altogether simple and obvious I could do. > > One more quick question: is there an easy way of > returning the actual path of the webserver's web root? > (Forgive my terminology if it's not right - I mean the > root directory as far as the someone accessing the > site is concerned). Shell Environment: DOCUMENT_ROOT /var/www/html The os.environment() method should give you the DOCUMENT_ROOT. The test method of the cgi module will show the environment provided by your web server along with any parameters. To see it yourself, this is all you need: #!/usr/local/bin/python import cgi cgi.test() Fix the shebang for your situation. > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From Michael.Dunn at mpi.nl Mon Dec 15 11:04:55 2003 From: Michael.Dunn at mpi.nl (Michael Dunn) Date: Mon Dec 15 11:05:05 2003 Subject: [Tutor] problem importing module Message-ID: Dear Tutor, I'm struggling with installing cx_Oracle (a module to let me talk to our Oracle db using python). It builds and (apparently) installs alright, but when I try to run anything that imports the cx_Oracle modulem, I get an import error: ImportError: ld.so.1: python: fatal: libclntsh.so.8.0: open failed: No such file or directory In the README to my python installation (I have a python installed locally), it says: ### When the dynamic loader complains about errors finding shared libraries, such as ld.so.1: ./python: fatal: libstdc++.so.5: open failed: No such file or directory you need to first make sure that the library is available on your system. Then, you need to instruct the dynamic loader how to find it. You can choose any of the following strategies: 1. When compiling Python, set LD_RUN_PATH to the directories containing missing libraries. 2. When running Python, set LD_LIBRARY_PATH to these directories. 3. Use crle(8) to extend the search path of the loader. 4. Modify the installed GCC specs file, adding -R options into the *link: section. ### I chose option 2, and added /usr/lib and /etc/lib to $LD_LIBRARY_PATH in my personal login script (this is indeed where ld.so.1 is located and the path wasn't right before). [sun02:~] micdunn% echo $LD_LIBRARY_PATH /usr/lib:/etc/lib:/usr/local/lib:/usr/local/X11R6/lib:/usr/local/gnu/lib:/usr/openwin/lib However, when I check this from python, the path is still the old one >>> import os >>> os.environ.get('LD_LIBRARY_PATH') '/usr/local/lib:/usr/local/X11R6/lib:/usr/local/gnu/lib:/usr/openwin/lib' >>> ^D Does anyone know what the problem is? I have been googling like mad, and I have discovered I really don't understand how python works with environments. Thanks, Michael From Janssen at rz.uni-frankfurt.de Mon Dec 15 11:16:08 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon Dec 15 11:16:18 2003 Subject: [Tutor] strange difference between two functions In-Reply-To: <20031215111358.38075.qmail@web20419.mail.yahoo.com> References: <20031215111358.38075.qmail@web20419.mail.yahoo.com> Message-ID: On Mon, 15 Dec 2003, Hameed Khan wrote: > hi, > i was reading the tutorial comes with python > documentation. i found 2 example functions in it. but > i cant understand these functions because of their > different output. so if any one of you out there can > tell me why there are giving different outputs just > because of a if check. that will be very nice of you. > below is the output directly copied from interactive > python prompt. > > > # function one # > >>> # function one > ... def f(a, L=[]): > ... L.append(a) > ... return L > ... > >>> f(1) > [1] > >>> f(2) > [1, 2] > >>> f(3) > [1, 2, 3] > > > # function two # > >>> # function two > ... def f2(a, L=[]): > ... if not L: > ... L = [] > ... L.append(a) > ... return L > ... > >>> f2(1) > [1] > >>> f2(2) > [2] > >>> f2(3) > [3] > >>> The python tutorial (setcion 4.71) claims "The default value is evaluated only once" and continues with the much more astonishing story about python mutuable types like lists. "evaluated only once" is probably better shown this way: >>> import time >>> def yet(t=time.time()): ... return t ... >>> yet() 1071502070.145452 >>> yet() 1071502070.145452 >>> --> the current time is evaluated when defining the function and won't change with subsequents calls of "yet" ("t" doesn't get reevaluated every time). Further: >>> yet(111) 111 >>> yet() 1071502070.145452 >>> ---> "yet" will "remember" the original value of "t" (this is what a function is suppose to do with keyword-arguments...). But where has this value been remembered? My answere (as a non expert) to this question is "somewhere deep in machines memory". Now look at "f" version1: def f(a, L=[]): ... L.append(a) ... return L ---> "L" is remembered "somewhere deep - and so on". Any call of "f" *without* an explicit value for "L" will use the value from "somewhere deep". It will use it and it will append "a" to this value. That's the story. How does it work? Python uses (at least it does so in my understanding) references to object. References are the names like "L", "f" or "yet". Objects can be lists, functions, strings, anything. One practical reason for this is: You can rename hugh list by creating another reference (and not by copiing several MB's in machines memory): >>> name1 = ["hugh", "...." ,"possibly really hugh"] >>> name2 = name1 # make a reference from name2 to target of name1 >>> id(name1);id(name2) # both aims to identicall data 1075964268 1075964268 The flipside is, that "name1.append('more stuff')" will show effect on name2 also (you know already why: name1 and name2 are references to the same data) now back to question: > >>> # function one > ... def f(a, L=[]): > ... L.append(a) > ... return L > ... > >>> f(1) > [1] > >>> f(2) > [1, 2] > >>> f(3) > [1, 2, 3] ---> this shows both: "evaluated only once" and "mutuable types might change while references stay". It's problably a little hard to understand, but the good thing is it's very important to understand ;-) (Feel free to ask further) But what does f2 do different? > >>> # function two > ... def f2(a, L=[]): > ... if not L: > ... L = [] > ... L.append(a) > ... return L In case "L" is empty the if-condition is true and "L" gets assigned to a brand new list: "L = []" creates a new (empty) list and set "L" as a reference (overwriting old "L"). This way "f2(1)", "f2(2)", and "f2(3)" starts all with their own brand new list. Michael From sigurd at 12move.de Mon Dec 15 12:04:58 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Dec 15 12:08:37 2003 Subject: [Tutor] strange difference between two functions In-Reply-To: <20031215111358.38075.qmail@web20419.mail.yahoo.com> (Hameed Khan's message of "Mon, 15 Dec 2003 03:13:58 -0800 (PST)") References: <20031215111358.38075.qmail@web20419.mail.yahoo.com> Message-ID: On 15 Dec 2003, Hameed Khan <- hameedkhaan@yahoo.com wrote: > i was reading the tutorial comes with python > documentation. i found 2 example functions in it. but > i cant understand these functions because of their > different output. so if any one of you out there can [...] > # function one # >>>> # function one > ... def f(a, L=[]): > ... L.append(a) > ... return L > ... [...] > # function two # >>>> # function two > ... def f2(a, L=[]): > ... if not L: > ... L = [] > ... L.append(a) > ... return L > ... [...] The explaination is in the paragraph above these functions in the tutorial; I'll cite it here: ,---- | *Important warning:* The default value is evaluated only once. This | makes a difference when the default is a mutable object such as a list, | dictionary, or instances of most classes. For example, the following | function accumulates the arguments passed to it on subsequent calls: `---- So what happens if you call f? As we can read the default value is only once evaluated; this means that every time we call that function without explicitly giving an value for L the default value is taken which happens to be the same object (the identic object). We can see that if we change the definition a bit. Python has the function `id()' which returns a number (an adrress). if two objects have the same id value they are the same object (also in memory; they exist only once). So change the above definition of to: def f(a, L=[]): print 'ID= ', id(L) L.append(a) return L Now at the repl we see: In [26]: f(1) ID= 11974284 Out[26]: [1] In [27]: f(2) ID= 11974284 Out[27]: [1, 2] So you see the very same list is used at every function call. Now change f2 the same way and you get: def f2(a, L=[]): print 'ID1= ', id(L) if not L: L = [] print 'ID2= ', id(L) L.append(a) return L In [29]: f2(1) ID1= 11976588 ID2= 11976652 Out[29]: [1] In [30]: f2(2) ID1= 11976588 ID2= 12013612 Out[30]: [2] You see the default value is also evaluated only once but that list isn't used when the appending happens but the (every function call) newly created list L. Karl -- Please do *not* send copies of replies to me. I read the list From barnabydscott at yahoo.com Mon Dec 15 17:07:21 2003 From: barnabydscott at yahoo.com (Barnaby Scott) Date: Mon Dec 15 17:07:26 2003 Subject: [Tutor] returning a web page (and also path to web root) In-Reply-To: <3FDDD6D0.7040206@venix.com> Message-ID: <20031215220721.84754.qmail@web41412.mail.yahoo.com> Thanks very much. In fact I like the look of your first idea the best - the Location: thing. Even shorter and more concise than I had hoped for! I think both my problems in fact stem from more lack of knowledge of http and webservers than Python, so forgive me if this is all slightly off-topic. The problem I feared does in fact occur - I used urllib to get a page and display it, and sure enough the images sources and some links failed to work. Because they are relative references, they went from the wrong starting point - i.e. not the web directory of the page, but cgi-bin where the script lives. As for the web root thing: I can get the DOCUMENT_ROOT to display, but this appears to be a totally different directory to the one I am interested in! My situation is that I have rented space on a server for 3 domains. The path I want returned takes the following form: /home/myaccountname/webs/www.oneofmydomains.com/htdocs The DOCUMENT_ROOT returns instead: /usr/local/www/data When I look there, the stuff is nothing to do with me at all! --- Lloyd Kvam wrote: > (I already suggested using the Location: HTTP > header, but decided to > add more.) > Barnaby Scott wrote: > > I am trying to write a cgi script in which under > rare > > circumstances I want the user to see a particular > web > > page (from the same server). > > > > I am not very experienced and would be very > grateful > > for help on the right way to tackle this - without > > knowing a sensible direction to go in I am likely > to > > waste huge amounts of time developing a stupid or > > overly-complex solution! > > > > Presumably if I just read the page in and spat it > back > > out to the user, all the relative links, image > sources > > etc would be wrong. > Not true. Your script will operate relative to the > cgi-bin directory. > However, if you simply copy a page of HTML back to > the browser, the > browser will not know that your CGI sent the HTML as > opposed to the > regular HTTPD server. It will simply process the > HTML it receives. > Your script would have trouble resolving the image > tags and relative > links, but it does not have to resolve anything > within the HTML. > > > > However I was a little reluctant to start messing > with > > the SimpleHTTPServer module - a. because I find it > > daunting and b. I wondered if there was something > > altogether simple and obvious I could do. > > > > One more quick question: is there an easy way of > > returning the actual path of the webserver's web > root? > > (Forgive my terminology if it's not right - I mean > the > > root directory as far as the someone accessing the > > site is concerned). > Shell Environment: > > DOCUMENT_ROOT > /var/www/html > > The os.environment() method should give you the > DOCUMENT_ROOT. > The test method of the cgi module will show the > environment provided > by your web server along with any parameters. > To see it yourself, this is all you need: > > #!/usr/local/bin/python > import cgi > cgi.test() > > Fix the shebang for your situation. > > > > __________________________________ > > Do you Yahoo!? > > New Yahoo! Photos - easier uploading and sharing. > > http://photos.yahoo.com/ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: 603-653-8139 > fax: 801-459-9582 > __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From pythontutor at venix.com Mon Dec 15 19:14:27 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Dec 15 19:14:32 2003 Subject: [Tutor] returning a web page (and also path to web root) In-Reply-To: <20031215220721.84754.qmail@web41412.mail.yahoo.com> References: <20031215220721.84754.qmail@web41412.mail.yahoo.com> Message-ID: <3FDE4E63.3020400@venix.com> Barnaby Scott wrote: > Thanks very much. In fact I like the look of your > first idea the best - the Location: thing. Even > shorter and more concise than I had hoped for! > > I think both my problems in fact stem from more lack > of knowledge of http and webservers than Python, so > forgive me if this is all slightly off-topic. > > The problem I feared does in fact occur - I used > urllib to get a page and display it, and sure enough > the images sources and some links failed to work. > Because they are relative references, they went from > the wrong starting point - i.e. not the web directory > of the page, but cgi-bin where the script lives. Below is the function I normally use to output an existing HTML file through a cgi script. Note that it is all done using normal file IO and avoids processing the HTML. urllib is probably "too smart" for what you are trying to do. This function should work for HTML files on your server. def copy_snippet( filename, out_file=None): if out_file is None: out_file = sys.stdout if os.path.exists( filename): snip = open( filename, 'r') shutil.copyfileobj( snip, out_file) snip.close() The variable name snip was used because these are usually snippets of HTML. (Server side includes may have been a better way to go.) > > As for the web root thing: I can get the DOCUMENT_ROOT > to display, but this appears to be a totally different > directory to the one I am interested in! My situation > is that I have rented space on a server for 3 domains. > The path I want returned takes the following form: > > /home/myaccountname/webs/www.oneofmydomains.com/htdocs > > The DOCUMENT_ROOT returns instead: > > /usr/local/www/data > > When I look there, the stuff is nothing to do with me > at all! ??? I'm not sure what to tell you. If you run cgi.test() you'll get a list of all of the environment variables. Perhaps there is a better one to use. Could you have mis-tested in looking up DOCUMENT_ROOT? I only have Apache running anywhere that I can check. All of those locations report the correct DOCUMENT_ROOT for the sites. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From Michael.Dunn at mpi.nl Tue Dec 16 05:15:06 2003 From: Michael.Dunn at mpi.nl (Michael Dunn) Date: Tue Dec 16 05:15:18 2003 Subject: [Tutor] problem importing data is solved! Message-ID: Hi everyone, Vicki suggested ldconfig, but this doesn't exist on my machine (sunos5). Since I asked this question yesterday I've learnt a bit more about unix than I knew before. The disappearing variables were not the problem -- I didn't know the difference between shell variables and environment variables. When I set the (environment) variables properly, using setenv rather than set, python could see them fine. The sad news is that setting LD_LIBRARY_PATH to the path for ld.so.1 didn't fix the problem, nor did setting LD_RUN_PATH and recompiling python. I still get: ImportError: ld.so.1: python: fatal: libclntsh.so.8.0: open failed: No such file or directory The file libclntsh.so.8.0 is in $ORACLE_HOME/lib -- could this be the problem? Well of course it is! Between writing that sentence and this I tried adding $ORACLE_HOME/lib to the LD_LIBRARY_PATH environment variable, and now everything works fine. Sorry for exposing you all to my fumbling discovery procedure. Maybe somebody will find it useful none the less. Since I've broken silence, I'd just like to add that tutor@python is absolutely brilliant -- thanks everybody who makes it so! Michael From tayi177 at hotmail.com Tue Dec 16 05:25:10 2003 From: tayi177 at hotmail.com (TADEY) Date: Tue Dec 16 05:26:43 2003 Subject: [Tutor] Pinging some requested IP with Python - usefull or not & some really basic examples needed ... Message-ID: Hello again ... - I realized, that the bigest barrier, when having basic knowledge (after reading, and making examples from one or two tutorials), knowing at least elementary commands, functions, etc., ... is starting to make (write own code for) programs on your own ... So I would be more than happy, if any of "moderators" (those, who has their own tutorials written and post here on mailing list), or anyone else here, reading tutor-mail list, would post some examples here, or probably better - send me them on my mail adress. I just need really basic, (but a little bit more complex - on a litle bit higher level), but still completely basic program examples. - Like, I have an idea (got it from one guy posting his question here - so it is actually his idea then) of writting some code, simple as possible, in Python, to ping my ISP from time to time (somewhere between 5 - 10 minutes). I am downloading music a lot, and having problems, that after there is no other activity (browsers, mail, etc.) for some time, ISP sometimes disconnect me. And I really don' want to install any program for this as they called it: "stay connected" option. Of course, if this is possible by Python, but I suppose it is. Actually, I would use those programs only, if someone here, who knows a lot about Python, would tell me, that in this case (running Python code for pinging some IP), Python would consume much more RAM, and other resources, than having some Pinging-type "stay connected" program running during intenet connection. Thanks, and please I would be happy to get as much examples you can send (of really simple code as possible, but on slightly higher level, than tutorials are written) ... Tadey - tayi177@hotmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031216/6e667d62/attachment.html From amonroe at columbus.rr.com Tue Dec 16 07:07:06 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Dec 16 06:57:43 2003 Subject: [Tutor] Pinging some requested IP with Python - usefull or not & some really basic examples needed ... In-Reply-To: References: Message-ID: <161389823256.20031216070706@columbus.rr.com> > here - so it is actually his idea then) of writting some code, > simple as possible, in Python, to ping my ISP from time to time > (somewhere between 5 - 10 minutes). I am downloading music a lot, > and having problems, that after there is no other activity Haven't tried it myself, but you could probably write a small program to wait a random amount of time, and then telnet to port 80 of a randomly chosen list of 4 or 5 of your favorite websites. Send a "GET /" and then just discard whatever comes back. Alan From pythontutor at venix.com Tue Dec 16 08:52:52 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Dec 16 08:52:58 2003 Subject: [Tutor] Pinging some requested IP with Python - usefull or not & some really basic examples needed ... In-Reply-To: References: Message-ID: <3FDF0E34.2050702@venix.com> TADEY wrote: > > > Hello again ... > > > - I realized, that the bigest barrier, when having basic knowledge > (after reading, and making examples from one or two tutorials), knowing > at least elementary commands, functions, etc., .. is starting to make > (write own code for) programs on your own .. > > So I would be more than happy, if any of "moderators" (those, who has > their own tutorials written and post here on mailing list), or anyone > else here, reading tutor-mail list, would post some examples here, or > probably better - send me them on my mail adress. I just need > really basic, (but a little bit more complex - on a litle bit higher > level), but still completely basic program examples. > (snipped) > > Thanks, and please I would be happy to get as much examples you can send > (of really simple code as possible, but on slightly higher level, than > tutorials are written) ... > A couple of sites with examples of short python programs: http://aspn.activestate.com/ASPN/Cookbook/Python ActiveState O'Reilly Python cookbook code samples ratings review (there is also a book with explaining many of the coding examples) http://www.uselesspython.com/ Useless Python! (anything but useless) -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From rob at jam.rr.com Tue Dec 16 09:03:38 2003 From: rob at jam.rr.com (Rob Andrews) Date: Tue Dec 16 09:04:13 2003 Subject: [Tutor] Pinging some requested IP with Python - usefull or not & some really basic examples needed ... In-Reply-To: <3FDF0E34.2050702@venix.com> References: <3FDF0E34.2050702@venix.com> Message-ID: <3FDF10BA.9010705@jam.rr.com> I guess this will be the informal announcement. The planned official site upgrade for Useless Python is 12/31/03 or 1/1/04, which will mark the 3rd anniversary of the date the site was initially suggested on the Tutor list. Anyone who wants to see the current progress can check out the (up to now, Top Secret): http://uselesspython.com/up2/ New features include the removal of email address links for contributors (thanks to spammers) and source code contributions sorted by category. Obligatory warning: Use of the search feature may turn up all sorts of odd side projects temporarily tucked away on the site. Pages not related to Useless Python will be removed at or around the time of the official site upgrade. -Rob > A couple of sites with examples of short python programs: > > http://aspn.activestate.com/ASPN/Cookbook/Python > ActiveState O'Reilly Python cookbook code samples ratings review > (there is also a book with explaining many of the coding examples) > > http://www.uselesspython.com/ > Useless Python! > (anything but useless) > From vicki.stanfield at ROCHE.COM Tue Dec 16 12:44:32 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Dec 16 12:45:49 2003 Subject: [Tutor] Changes to wxTextCtrl get repeated Message-ID: I have a gui that I am working with which contains, among other things, two wxTextCtrls. When I change the style of the first one, the second one exhibits behavior consistent with the change even though I don't actually change the code that creates it. Is there some kind of on-the-fly inheritance that I am not aware of? Specifically, I am changing the style from wxTE_READONLY to wxTE_READONLY|wxTE_WORDWRAP|wxTE_MULTILINE for the first box and want to leave the second box as wxTE_READONLY. If there were a wxTE_SINGLELINE, I could simply add that to the second one, but I'd rather understand the behavior I am seeing. Anyone? --vicki -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031216/21409752/attachment.html From magnus at thinkware.se Tue Dec 16 13:07:43 2003 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Dec 16 13:04:52 2003 Subject: [Tutor] Changes to wxTextCtrl get repeated In-Reply-To: Message-ID: <5.2.1.1.0.20031216190224.023be008@www.thinkware.se> At 12:44 2003-12-16 -0500, Stanfield, Vicki {D167~Indianapolis} wrote: >I have a gui that I am working with which contains, among other things, >two wxTextCtrls. When I change the style of the first one, the second one >exhibits behavior consistent with the change even though I don't actually >change the code that creates it. Is there some kind of on-the-fly >inheritance that I am not aware of? Specifically, I am changing the style >from wxTE_READONLY to wxTE_READONLY|wxTE_WORDWRAP|wxTE_MULTILINE for the >first box and want to leave the second box as wxTE_READONLY. If there were >a wxTE_SINGLELINE, I could simply add that to the second one, but I'd >rather understand the behavior I am seeing. Anyone? I'd guess you've made something odd to make this happen. It doesn't sound like normal wxPython behaviour. Perhaps you can put together a small program that shows the behaviour, and mail that to the list? (If nothing else, you might figure out what you did to cause this in the process. :^) For starters, you could post the lines of code where you define your two wxTextCtrls. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From vicki.stanfield at ROCHE.COM Tue Dec 16 13:14:25 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Dec 16 13:15:50 2003 Subject: [Tutor] Changes to wxTextCtrl get repeated Message-ID: Okay, here are the two lines: #Create a box to which to write output self.outputbox = wxTextCtrl(self,-1,"",size=wxDefaultSize,style=wxTE_READONLY|wxTE_WORDWRAP|wxTE_MULTILINE ) #Create a box where parameters can be entered self.parameters=wxTextCtrl(self,44,"", size=wxDefaultSize,style=wxTE_READONLY) I'm working on deleting a bunch of stuff to create a simple program to post. --vicki -----Original Message----- From: Magnus Lyck? [mailto:magnus@thinkware.se] Sent: Tuesday, December 16, 2003 1:08 PM To: Stanfield, Vicki {D167~Indianapolis}; tutor@python.org Subject: Re: [Tutor] Changes to wxTextCtrl get repeated At 12:44 2003-12-16 -0500, Stanfield, Vicki {D167~Indianapolis} wrote: >I have a gui that I am working with which contains, among other things, >two wxTextCtrls. When I change the style of the first one, the second one >exhibits behavior consistent with the change even though I don't actually >change the code that creates it. Is there some kind of on-the-fly >inheritance that I am not aware of? Specifically, I am changing the style >from wxTE_READONLY to wxTE_READONLY|wxTE_WORDWRAP|wxTE_MULTILINE for the >first box and want to leave the second box as wxTE_READONLY. If there were >a wxTE_SINGLELINE, I could simply add that to the second one, but I'd >rather understand the behavior I am seeing. Anyone? I'd guess you've made something odd to make this happen. It doesn't sound like normal wxPython behaviour. Perhaps you can put together a small program that shows the behaviour, and mail that to the list? (If nothing else, you might figure out what you did to cause this in the process. :^) For starters, you could post the lines of code where you define your two wxTextCtrls. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From aon.912502367 at aon.at Thu Dec 11 05:11:53 2003 From: aon.912502367 at aon.at (aon.912502367@aon.at) Date: Tue Dec 16 14:10:38 2003 Subject: [Tutor] Re: a list comp In-Reply-To: References: <3FD81F2E.4020606@aon.at> Message-ID: <1071137513.3fd842e9484e2@webmail.jet2web.at> ----- Original von: RoT : > Basically you can observe this here: > > >>> newlist = [] > >>> print newlist.append(3) > None > >>> newlist > [3] > >>> print newlist.append(5) > None > >>> newlist > [3, 5] > >>> newlist = [] > >>> print [newlist.append(x) for x in 1,3,5] > [None, None, None] even though newlist.append(x) returns None, the list comp 'does' evaluate to a new list doesn,t it > >>> [index for index in del_list if index not in keep_list] > [2, 4, 8] so I still would have expected it to be returned. It's shown in the above example: the list comprehension returned [None, None, None] because each call of the append-method returns None- Gregor ------------------------------------------- Versendet durch AonWebmail (webmail.aon.at) From philip at pacer.co.za Thu Dec 11 06:16:28 2003 From: philip at pacer.co.za (philip gilchrist) Date: Tue Dec 16 14:11:01 2003 Subject: [Tutor] Timing errors Message-ID: <598B5E93DCDC614C9C1FE22406A0F5BE35EC@pacer-server.pacer.local> Hi all Could someone please educate me why this simple interface waits 10 seconds and then draws the rectangle?? >From livewires import * Import time begin_graphics() move (500,100) draw (550,100) draw (550,250) draw (500,250) draw (500,100) time.sleep(10) end_graphics() regards Philip Gilchrist Pacer Computers Cell 0824589733 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031211/baa0ec31/attachment-0001.html From philip at pacer.co.za Thu Dec 11 06:13:40 2003 From: philip at pacer.co.za (philip gilchrist) Date: Tue Dec 16 14:11:20 2003 Subject: [Tutor] python photo gallery software??? Message-ID: <598B5E93DCDC614C9C1FE22406A0F5BE35EB@pacer-server.pacer.local> www.zope.org regards Philip Gilchrist Pacer Computers Cell 0824589733 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of nihilo Sent: 11 December 2003 12:15 PM To: Tutor Subject: [Tutor] python photo gallery software??? hi, Can anybody recommend software for organizing, creating thumbnails, providing web access to (etc...) a photo gallery, written in Python, or have you heard of such a thing? There are plenty of software out there for doing this sort of thing, but I haven't found anything in python -- just php and perl, usually with mysql. It's only for personal use, so it doesn't have to be heavy duty, but i'd like it to be in python so that i can easily modify it for my own use. thanks -n. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From comber at cix.co.uk Thu Dec 11 10:59:54 2003 From: comber at cix.co.uk (Edward Comber) Date: Tue Dec 16 14:11:32 2003 Subject: [Tutor] Detecting different list elements and counting them In-Reply-To: <3FD8899F.8010801@img-online.de> Message-ID: I would imagine something like my_dict = {} for item in my_list: if my_dict.haskey(item): my_dict[item] = my_dict[item] + 1 else: my_dict[item] = 0 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Michael Grabietz Sent: 11 December 2003 15:14 To: tutor@python.org Subject: [Tutor] Detecting different list elements and counting them Hi, I have a list like the following: my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ] It would be nice to have the information which elements are in the list and how many times these elements appear in the list. A dictionary as the result like the following would be fine. my_dict = {'ABC':3, 'E':1, 'HJ':2} Thank you for any ideas or hints. Michael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From comber at cix.co.uk Thu Dec 11 11:21:54 2003 From: comber at cix.co.uk (Edward Comber) Date: Tue Dec 16 14:11:41 2003 Subject: [Tutor] Detecting different list elements and counting them In-Reply-To: Message-ID: Bugger. This works.. my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ] my_dict = {} for item in my_list: if my_dict.has_key(item): my_dict[item] = my_dict[item] + 1 else: my_dict[item] = 1 print my_dict -----Original Message----- From: Edward Comber [mailto:comber@cix.co.uk] Sent: 11 December 2003 16:00 To: Michael Grabietz; tutor@python.org Subject: RE: [Tutor] Detecting different list elements and counting them I would imagine something like my_dict = {} for item in my_list: if my_dict.haskey(item): my_dict[item] = my_dict[item] + 1 else: my_dict[item] = 0 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Michael Grabietz Sent: 11 December 2003 15:14 To: tutor@python.org Subject: [Tutor] Detecting different list elements and counting them Hi, I have a list like the following: my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ] It would be nice to have the information which elements are in the list and how many times these elements appear in the list. A dictionary as the result like the following would be fine. my_dict = {'ABC':3, 'E':1, 'HJ':2} Thank you for any ideas or hints. Michael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From comber at cix.co.uk Thu Dec 11 13:02:27 2003 From: comber at cix.co.uk (Edward Comber) Date: Tue Dec 16 14:11:49 2003 Subject: [Tutor] do_it() In-Reply-To: <20031211084123.W1075-100000@localhost.name> Message-ID: Fair enough, but you could have kept the list of words external to the functions and used by both. Also you can return two lists like... def stop_n_go_words(terms): blah return stop_list, go_list a_stop_list, a_go_list = stop_n_go_words(terms) -----Original Message----- From: tpc@csua.berkeley.edu [mailto:tpc@csua.berkeley.edu] Sent: 11 December 2003 17:24 To: Eddie Comber Cc: tutor@python.org Subject: Re: [Tutor] do_it() hi Eddie, I was mulling this over recently, and while it is true the overhead is much higher with OOP, the payoff is easier to read and more functional code. Let me give you an example. I recently wrote a search engine that takes as user input a query and returns results from an audio and video archive. One of the things I needed to do was filter common, or stop, words (e.g., who, is, what, the, of) from go words that would be used in other functions to look up and return results in the index. I also wanted to print out the words filtered to the user, so I had to either duplicate the body of code for a function to return both, or I could write a class called Filter and have two methods in it, getUserGoWords(self) and getUserStopWords(self) using the same logic. The non-OOP way of doing this would be: def getUserGoWords(terms): stop_words_list = ['a', 'about', 'all', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'can', 'did', 'do', 'does', 'for', 'from', 'he', 'how', 'i', 'if', 'in', 'is', 'it', 'may', 'no', 'not', 'of', 'on', 'or', 'that', 'the', 'then', 'these', 'this', 'those', 'to', 'was', 'we', 'what', 'when', 'where', 'which', 'who', 'why', 'with'] terms_list = terms.split() user_go_words = [] for word in terms_list: if word.lower() not in stop_words_list: filtered_terms_list.append(word) return user_go_words def getUserStopWords(terms): stop_words_list = ['a', 'about', 'all', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'can', 'did', 'do', 'does', 'for', 'from', 'he', 'how', 'i', 'if', 'in', 'is', 'it', 'may', 'no', 'not', 'of', 'on', 'or', 'that', 'the', 'then', 'these', 'this', 'those', 'to', 'was', 'we', 'what', 'when', 'where', 'which', 'who', 'why', 'with'] terms_list = terms.split() user_stop_words = [] for word in terms_list: if word.lower() in stop_words_list: user_stop_words.append(word) return user_stop_words and the OOP way of doing this would be: class Filter: def __init__(self, terms): # replace ' with '' for MySQL INSERT terms = terms.replace("'", "''") # this is currently how I handle context searches in Audio Video Archive terms = terms.replace('"', "") stop_words_list = ['&', 'a', 'about', 'all', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'can', 'do', 'does', 'for', 'from', 'he', 'how', 'i', 'if', 'in', 'is', 'it', 'may', 'no', 'not', 'of', 'on', 'or', 'that', 'the', 'then', 'these', 'this', 'those', 'to', 'was', 'we', 'what', 'when', 'where', 'which', 'who', 'why', 'with'] terms_list = terms.split() self.user_go_words = [] self.user_stop_words = [] for word in terms_list: if word.lower() not in stop_words_list: self.user_go_words.append(word) else: self.user_stop_words.append(word) def getUserGoWords(self): return self.user_go_words def getUserStopWords(self): return self.user_stop_words Maybe there is another way of doing this so that one function can return two values, but as far as I know there is no doubt in my mind which makes more sense with respect to future readers of my code and the holy mantra of programming, Keep It Short and Simple. I hope that helps you. On Thu, 11 Dec 2003, Eddie Comber wrote: > I see that often when people write OO code they have a main() something > like: > > obj = myObject(param, param, param) > obj.do_it() #or obj.action() etc > > Are there any commanding advantages to making this sort of functionality > into an object? > > The above example is easier written and used as: > > myfunc(param, param, param) > > I ask because I have just written a MAKE utility, and having started off as > an object I really don't know what the advantages are above a simple > function. > > Best, > Eddie. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From chouyiyu at hotmail.com Sun Dec 14 15:37:34 2003 From: chouyiyu at hotmail.com (Yi-Yu Chou) Date: Tue Dec 16 14:11:55 2003 Subject: [Tutor] How to integrate python, vtk and C++ ? Message-ID: Dear all, I want to integrate python, vtk and my own C++ object. Is it possible to do it by using python/C API ? Where can I find the examples ? Thanks in advance !!! Best, YY _________________________________________________________________ 想戀愛?交朋友?MSN 線上交友:由 Match.com 提供,全世界最受歡迎的線上交友服 務 http://match.msn.com.tw From mhansen at cso.atmel.com Tue Dec 16 14:51:43 2003 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue Dec 16 14:51:27 2003 Subject: [Tutor] Useless Python In-Reply-To: References: Message-ID: <3FDF624F.5000808@cso.atmel.com> Hmmm...looks bluerobot(www.bluerobot.com) influenced.(Looks at source. Yep!) I like it a lot! A great look for a great site. Mike > Subject: > Re: [Tutor] Pinging some requested IP with Python - usefull or not & > some really basic examples needed ... > From: > Rob Andrews > Date: > Tue, 16 Dec 2003 08:03:38 -0600 > To: > tutor@python.org > > To: > tutor@python.org > > > I guess this will be the informal announcement. The planned official > site upgrade for Useless Python is 12/31/03 or 1/1/04, which will mark > the 3rd anniversary of the date the site was initially suggested on > the Tutor list. > > Anyone who wants to see the current progress can check out the (up to > now, Top Secret): http://uselesspython.com/up2/ > > New features include the removal of email address links for > contributors (thanks to spammers) and source code contributions sorted > by category. > > Obligatory warning: Use of the search feature may turn up all sorts of > odd side projects temporarily tucked away on the site. Pages not > related to Useless Python will be removed at or around the time of the > official site upgrade. > > -Rob > >> A couple of sites with examples of short python programs: >> >> http://aspn.activestate.com/ASPN/Cookbook/Python >> ActiveState O'Reilly Python cookbook code samples ratings review >> (there is also a book with explaining many of the coding examples) >> >> http://www.uselesspython.com/ >> Useless Python! >> (anything but useless) >> > > > From dyoo at hkn.eecs.berkeley.edu Tue Dec 16 15:34:10 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 16 15:34:19 2003 Subject: [Tutor] Timing errors In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE35EC@pacer-server.pacer.local> Message-ID: > Could someone please educate me why this simple interface waits 10 > seconds and then draws the rectangle?? Ah! Use the 'sleep()' method that comes with livewires --- time.sleep() from the Standard Library actually interferes with the 'Tkinter' graphic event loop, preventing it from redrawing the screen. The fix should be easy: just substitute: sleep(...) wherever you see: time.sleep(...) and your livewires code should be fine. Good luck! From arkamir at softhome.net Tue Dec 16 15:34:17 2003 From: arkamir at softhome.net (arkamir@softhome.net) Date: Tue Dec 16 15:34:30 2003 Subject: [Tutor] Inheritance Message-ID: I'm just starting to learn classes and have run into trouble understanding how classes inherit. One question is if class A inherits from class B and C. And then B inherits from M and N. And C inherits from F and G, while F and N inherit from class z which inherits from object, what is the name resolution. Z M N F G B C A Also can someone explain to me what super() does, i need something pretty basic. Next using the same classes as above, if z.__init__: connects to a database, how can I make sure that it is only called once, while initializing all the classes. Would the connection have to be just within the body, and how would that work?? class test: def __init__(): self.x = 'hello' print self.x Tha above code raises an error. What can I do to make it work?? From littledanehren at yahoo.com Tue Dec 16 16:17:49 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Dec 16 16:17:54 2003 Subject: [Tutor] How to integrate python, vtk and C++ ? In-Reply-To: Message-ID: <20031216211749.58006.qmail@web41809.mail.yahoo.com> Yi-Yu Chou wrote: > Dear all, > > I want to integrate python, vtk and my own C++ > object. > Is it possible to do it by using python/C API ? > Where can I find the examples ? > Thanks in advance !!! > > Best, > YY VTK has bindings to both C++ and Python, so you should have no problem using it. The Python/C API is somewhat cumbersome, though. People usually use higher-level interfaces. One of the most popular higher-level interfaces is SWIG. With SWIG, you just need a C or C++ source and some configuration files, and then SWIG preprocesses the files and does all of the Python/C API for you. Another popular choice is Boost.Python, but it has some bugs when using Python 2.3. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From littledanehren at yahoo.com Tue Dec 16 16:50:05 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Dec 16 16:50:10 2003 Subject: [Tutor] Inheritance In-Reply-To: Message-ID: <20031216215005.60369.qmail@web41810.mail.yahoo.com> arkamir@softhome.net wrote: > I'm just starting to learn classes and have run into > trouble understanding > how classes inherit. > > One question is if class A inherits from class B and > C. And then B inherits > from M and N. And C inherits from F and G, while F > and N inherit from class > z which inherits from object, what is the name > resolution. > > > > Z > M N F G > B C > A > > Starting in Python 2.2, the inheritance model changed slightly. Everything should (but doesn't have to) inheret from object, which makes it use the new inheritance model, but if you're inhereting from any other class, you don't need to inheret from object. With the new inheritance model, the class traverses the tree (using your model as a visual aide) starting at the bottom going across the entire row, left to right. Then it goes up to the next row and inherets from it, left to right. Then the next row and so on. So in this example, the inheritance order would be A, B, C, M, N, F, G, Z, object. You can get that list from A.__mro__ > > Also can someone explain to me what super() does, i > need something pretty > basic. You won't need super if you're doing something really basic. It's used to partially override inheritance -- it's complicated. > > Next using the same classes as above, if z.__init__: > connects to a database, > how can I make sure that it is only called once, > while initializing all the > classes. Would the connection have to be just within > the body, and how would > that work?? > > > class test: > def __init__(): > self.x = 'hello' > print self.x > > > Tha above code raises an error. What can I do to > make it work?? First of all, you should be inheriting from object, but that's not what's causing the error. Your __init__ method needs to have at least one argument. Whenever an object's method is called, the first thing it sends to the method is itself. By convention, this is called self, but it can be called anything you want. Your print statement is outside your __init__ method. No code can be outside of methods except for variable settings. For both of these, you don't need the self prefix. It looks like print self.x was intended to be executed only once, when you created the object, so it should be inside the __init__ method. In your code, the variable x was not dependent on what you put in __init__, so it should be outside of the __init__ function. Here's your class with my modifications on it: class test: x = 'hello' def __init__(self): print self.x Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Tue Dec 16 18:28:06 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 16 18:28:10 2003 Subject: [Tutor] Finding quoted strings in a text? A hands-on tutorial on DFA->regex conversion Message-ID: [Warning: there's heavy regular expression and finite state automata stuff in this message. Skip if it gets really confusing.] Hi everyone, For a small project that I'm working on, I've calculated out a regular expression for finding quoted strings, but it's just absolutely hideous. By quoted string, I mean a string surrounded with quotes, also allowing for escaped quote charactesr. For example: r'this is a "\"test\""' is an example where I want to capture r"\"test\"" as a whole. I'd like to get some input from the group to see the "best" way of doing this, with regular expressions. I need a regular expression solution because I'm trying to combine this with other existing regular expressions. Here's my regular expression for detecting quoted strings: ### regex = re.compile(r'(?:"[^"]*\\(?:.[^"]*\\)*.[^"]*")|(?:"[^"]*")') ### This is one of the ugliest regexes I've written. *grin* I wanted to avoid using lookahead since older versions of Python have potential recursion problems with it and long strings. This solution only depends on character classes and the '*' repetition operator. The monster actually works: ### >>> regex.findall('this is a piece of "quoted" text.') ['"quoted"'] >>> regex.findall('"hello" world, this is "another test".') ['"hello"', '"another test"'] >>> regex.findall(r'"this" even allows for "\"escaped\"" quotes, "yes?"') ['"this"', '"\\"escaped\\""', '"yes?"'] ### On the other hand, it's ugly, and probably nonoptimal. Let me show how I constructed the beast. Constructing the regular expression by hand wasn't actually too bad. In a previous discussion, we mentioned that regular expressions and finite state machines are equivalent to each other, and there's an easy finite state machine for detecting quoted strings. Here's a picture of it: n - / / q v / q START--------> STATE1 -------->FINAL | ^ b| | | | a V | STATE2 In the picture, q stands for the quote symbol " n stands for any non-quote character [^"] b stands for the backslash symbol \ a stands for any character . This finite state machine has four states, but it's not a regular expression yet. One systematic way of transforming it into a regular expression is to iteratively "rip" out states until we're left with only START and FINAL. As we "rip" states out, we need to repair the damage to the machine. For example, if we had something like: c - / / a v / b STATE1 -----> STATE2 ------> STATE3 | ^ | | \--------------------------/ d then we can rip out STATE2, and our resulting machine will look like: (ac*b) | d STATE1 ------------> STATE3 Rip repair focuses on modifying edges between pairs of states so that paths that go across the ripped state take account of any missing edges. In the example above, the self-loop at STATE2 gets absorbed into the edge between STATE1 and STATE3, as part of the 'c*' section of the regular expression. So here's what things look like as we start ripping states out. Given our original machine: n - / / q v / q START--------> STATE1 -------->FINAL | ^ b| | | | a V | STATE2 we can rip out STATE1, repair the eges, and get a machine with three states: an*b - / / qn*b v / an*q START--------> STATE2 -------->FINAL | ^ | | \----------------------------/ qn*q This still does the same work that the original machine does. Now we can rip out STATE2, and patch up the edges again: (qn*b(an*b)*an*q) | (qn*q) START------------------------->FINAL Finally, I substituted back 'a', 'n', 'b', and 'q' with the real symbols that they stood for, and got back that huge ugly regular expression: r'("[^"]*\\(.[^"]*\\)*.[^"]*")|("[^"]*")' The only difference between this and the regex from way above: regex = re.compile(r'(?:"[^"]*\\(?:.[^"]*\\)*.[^"]*")|(?:"[^"]*")') is the addition of '?:' so that the groups that are defined aren't "capturing" things. So the regular expression is ugly, but the process of calculating it is actually pretty systematic. Anyway, I hope this was interesting! From fredm at smartypantsco.com Tue Dec 16 18:58:30 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Tue Dec 16 19:01:34 2003 Subject: [Tutor] Useless Python v2 In-Reply-To: <3FDF10BA.9010705@jam.rr.com> References: <3FDF0E34.2050702@venix.com> <3FDF0E34.2050702@venix.com> Message-ID: <5.1.0.14.0.20031217105231.03a93530@192.168.1.1> Hi Rob: Congratulations on a very good looking site. I always enjoyed 'Useless Python' and this is much nicer looking. One issue I have, though, is that it is difficult to comment on a script or to make a suggestion back to the author. As a quick example, I just had a look at Danny Yoo's script "test_pack_forget.py" from the "Browse GUI Programs" section. This code is interesting, but there is a line missing preventing it from working properly (specifically "f1.pack()" or similar). I don't know what the long-term solution to updating programs and inviting reader feedback should be, but I thought I'd mention it anyway. Thanks again and keep up the good work, Fred From alan.gauld at blueyonder.co.uk Tue Dec 16 19:05:18 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Dec 16 19:06:50 2003 Subject: [Tutor] Timing errors References: <598B5E93DCDC614C9C1FE22406A0F5BE35EC@pacer-server.pacer.local> Message-ID: <003401c3c431$74d45560$6401a8c0@xp> > Could someone please educate me why this simple > interface waits 10 seconds and then draws the rectangle?? I know zilch about livewoiires but... >From livewires import * Import time begin_graphics() move (500,100) draw (550,100) draw (550,250) draw (500,250) draw (500,100) time.sleep(10) <--- wait 10 seconds end_graphics() <-- finish graphics work so draw the result This type of behaviour is fairly common in GUI graphics toolkits. The graphics often draw to a second screen buffer then when you complete all the work it just swaps the displayed buffer with the scratchpad. It makes for smoother screen updates. Reversing the end_graphics and sleep calls should change the behaviour. I assume that's what's happening in Livewire... Alan G. From helena_b2001 at yahoo.com Tue Dec 16 20:18:48 2003 From: helena_b2001 at yahoo.com (helena bhaska) Date: Tue Dec 16 20:18:54 2003 Subject: [Tutor] socket send problem Message-ID: <20031217011848.47318.qmail@web20413.mail.yahoo.com> Hi, I have just started playing with python and sockets, and here is the code that I wrote: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) for x in self.command: sent = s.send(x) print "amount sent: "+sent s.close() where command is a list of strings. For some reason I never get to the print statement. The receiving end listens for connections, as soon as it gets one, it creates a thread which deals with the data sent through, with recv() statement. Any help/pointers would be greatly appreciated! Thanks, Helena __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Tue Dec 16 20:25:24 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 16 20:25:32 2003 Subject: [Tutor] Finding quoted strings in a text? A hands-on tutorial on DFA->regex conversion In-Reply-To: Message-ID: On Tue, 16 Dec 2003, Danny Yoo wrote: > > [Warning: there's heavy regular expression and finite state automata > stuff in this message. Skip if it gets really confusing.] > > > For a small project that I'm working on, I've calculated out a regular > expression for finding quoted strings, but it's just absolutely hideous. Hi everyone, I'm just a dunce sometimes. *grin* I've figured out a much nicer regular expression to do the same quoted string matching: ### regex = re.compile(r''' " ## A leading quote (?: ## with any number of (?:\\.) ## escaped character | (?:[^"]) ## or non-quote characters )* " ''', re.VERBOSE) ### This actually makes a lot more intuitive sense to me, as a human, than the previous regular expression. I would have derived it from my original DFA machine: n - / / q v / q START--------> STATE1 -------->FINAL | ^ b| | | | a V | STATE2 if I had only ripped out STATE2 first, and then followed up with ripping out STATE1. Well, at least I know better now that the order of ripping states out makes a huge difference. *grin* It's fascinating that these two regular expressions, r'"(?:(?:\\.)|(?:[^"]))*"' and r'(?:"[^"]*\\(?:.[^"]*\\)*.[^"]*")|(?:"[^"]*")' are saying the exact same thing. Regular expressions are so evil sometimes... *grin* Thanks again! From rmangaliag at slu.edu.ph Tue Dec 16 21:57:43 2003 From: rmangaliag at slu.edu.ph (ali) Date: Tue Dec 16 21:48:01 2003 Subject: [Tutor] lucene... in python? Message-ID: <1071629863.3fdfc627eb04c@mbox.slu.edu.ph> is there a lucene-like application written in python??? i really need a powerful text search tool (like java's lucene) and i was hoping a python port/alternative is available... thanks... ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From david at graniteweb.com Tue Dec 16 23:01:01 2003 From: david at graniteweb.com (David Rock) Date: Tue Dec 16 23:05:33 2003 Subject: [Tutor] Finding quoted strings in a text? A hands-on tutorial on DFA->regex conversion In-Reply-To: References: Message-ID: <20031217040101.GB21218@wdfs.graniteweb.com> * Danny Yoo [2003-12-16 17:25]: > > > On Tue, 16 Dec 2003, Danny Yoo wrote: > > > > > [Warning: there's heavy regular expression and finite state automata > > stuff in this message. Skip if it gets really confusing.] > > > > > > For a small project that I'm working on, I've calculated out a regular > > expression for finding quoted strings, but it's just absolutely hideous. Any chance this is for csv file parsing? If yes, the new csv stuff in 2.3 is a much simpler way of dealing with it. If not, I'm sorry for you ;-) -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031216/ddd0f29c/attachment.bin From speno at isc.upenn.edu Wed Dec 17 00:22:15 2003 From: speno at isc.upenn.edu (John P Speno) Date: Wed Dec 17 00:22:22 2003 Subject: [Tutor] lucene... in python? In-Reply-To: <1071629863.3fdfc627eb04c@mbox.slu.edu.ph> References: <1071629863.3fdfc627eb04c@mbox.slu.edu.ph> Message-ID: <20031217052215.GP11248@isc.upenn.edu> On Wed, Dec 17, 2003 at 10:57:43AM +0800, ali wrote: > > > is there a lucene-like application written in python??? Yes. Lupy. http://www.divmod.org/Lupy/index.html Lupy is a is a full-text indexer and search engine written in Python. It is a port of Jakarta Lucene 1.2 to Python. Specifically, it reads and writes indexes in Lucene binary format. Like Lucene, it is sophisticated and scalable. From sylvainl at uniserve.com Wed Dec 17 00:53:07 2003 From: sylvainl at uniserve.com (Sylvain & Maureen Leclerc) Date: Wed Dec 17 00:55:27 2003 Subject: [Tutor] Python or MySQL/PostgreSQL? Message-ID: <004801c3c462$593fd320$5c3622cf@computer> Python or MySQL/PostgreSQL? This question must have been asked a million times before, but I need to ask it. But first, some background. I need to create a different database (or rather a different set of databases) for my office to integrate a number of disparate functions. My office uses index cards, ACT! database, paper filing, email, Post-it notes, and each staff has her/his notebokk into which everybody else write reminders. You guess the results: a mishmash of information everywhere; training new staff is a nightmare, and it is difficult to track information/communication for each of our members (we are a non-profit society). My plan to deal with this is to minimize paper as much as possible and integrate as many functions as possible into a central repository. I was thinking of using for instance ZOPE to create an Intranet into which our policies, procedures, and training manuals can be posted (and updated once) and easily keyword-searched. I was also thinking of integrating written communication (fax, email, papermail) with the database(s) so that all the information pertaining to a member can be retrieved here. One of the reasons for this is that we have field staff who need as much current and complete information as possible to be effective in helping our members. Our field staff are disseminated over a large geographical area so it seems that it would be more logical for them to have access to our database in real time over a secure network. I just stumbled over Python a couple of weeks ago when looking at ZOPE and am wondering if developing a database using OOP would be more effective than using the traditional (yet more familiar) relational database model. Someone mentioned that I may limit myself going Python instead of, say, MySQL or PostgreSQL, given the complexity I am getting into (it also has to convert data from ACT!, not all of which is easily exportable, and it has to have the features one would normally expect of a database). My issue is the following: we are currently converting our systems from Windows to Linux and I will need to learn a new database program anyway since the ones with which I am familiar are neither available or affordable. My experience with databases is from a design perspective only; I haven't programmed anything but generally can read scripts and understand/modify them. All the database applications I learned in the past had GUIs which allowed me to design from menu-driven interfaces and objects. In addition, computer support and database design are not my main function, nor part of my training. I am an administrator in this office and I happen to know more about computers than the other staff. The job's gotta be done and I just have to do it (we can't afford paying someone to do this). Therefore my initial question (Python or MySQL/PostgreSQL) is loaded with the above situation. In other words: 1. Will Python allow me to do what I intend to do? 2. What are the limits in Python that MySQL or PostgreSQL do not have. What can it not do that the SQLs can do? 3. Same question as above but in reverse: what can Python do that the others can't? 4. Comparatively-speaking, what is the learning curve in both cases (Python vs the SQLs)? (I am not a programmer) 5. How fast can I get results? I was thinking of developing the database modularly. First by replacing our ACT! database (and perhaps breaking the heavily-customized database into smaller, more manageable parts all linked together) thus requiring importing DBF files and ACT! memo fields, then by creating and linking other databases (computer and paper-form), and finally by linking emails and other documents to it. 6. How easy will it be to get support when I hit a wall? Thanks for reading this and for helping me in my quandary. Once I made a decision as to which way I choose, there will be no turning back since I need to forge ahead and get all those issues behind me. Sylvain Leclerc -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031216/24f8f3b7/attachment.html From alan.gauld at blueyonder.co.uk Wed Dec 17 03:17:54 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 17 03:19:22 2003 Subject: [Tutor] Inheritance References: Message-ID: <006901c3c476$45895900$6401a8c0@xp> > One question is if class A inherits from class B and C. And then B inherits > from M and N. And C inherits from F and G, while F and N inherit from class > z which inherits from object, what is the name resolution. > > > > Z > M N F G > B C > A > A,B,M,N,Z,C,F,Z,G I think. Python works left to right in declaration order. And it stops with the first successful find. > Also can someone explain to me what super() does, Sorry, its a new feature and I've not got round to using it yet. I just tried a wee experiment and it didn't work how I expected so I need to go rad the docs I think! :-) > Next using the same classes as above, if z.__init__: connects to a database, > how can I make sure that it is only called once, You could test for the existence of the connection in the init()... But it looks a bit grubby, thee might be a better way someone else can think of... class Z: def __init__(self,Database): try: if self.db: pass except AttributeError: self.db = connect(Database) > class test: > def __init__(): > self.x = 'hello' > print self.x > > > Tha above code raises an error. What can I do to make it work?? Add a self parameter to the init method def __init__(self): HTH, Alan G. From alan.gauld at blueyonder.co.uk Wed Dec 17 03:21:52 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 17 03:23:19 2003 Subject: [Tutor] Inheritance References: <20031216215005.60369.qmail@web41810.mail.yahoo.com> Message-ID: <007001c3c476$d36284e0$6401a8c0@xp> > Starting in Python 2.2, the inheritance model changed > slightly. ...With the new inheritance model, the class traverses > the tree (using your model as a visual aide) starting > at the bottom going across the entire row, left to > right. Then it goes up to the next row and inherets > from it, left to right. Oops, looks like I got that one wrong then. I didn't realize the order of search had changed... Alan G. From magnus at thinkware.se Wed Dec 17 04:18:30 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 17 04:18:40 2003 Subject: =?ISO-8859-1?B?UmU6IFJFOiBbVHV0b3JdIENoYW5nZXMgdG8gd3hUZXh0Q3RybCBnZXQgcmVwZWF0ZWQ=?= Message-ID: "Stanfield, Vicki {D167~Indianapolis}" wrote: > #Create a box to which to write output > self.outputbox = wxTextCtrl(self,-1,"",size=wxDefaultSize,style=wxTE_READONLY|wxTE_WORDWRAP|wxTE_MULTILINE ) Ok, fine. > #Create a box where parameters can be entered > self.parameters=wxTextCtrl(self,44,"", size=wxDefaultSize,style=wxTE_READONLY) Is there any particular reason why you use id 44 here instead of -1? It seems dangerous to me to have some control ids automatically assigned and other set manually like this. I doubt that it has to do with your problem if you see two different controls, but it's something to consider. If you need the id for self.parameters, you can get it with(if I remember correctly) self.parameters.GetId(). You can also use wxNewId() to get ids that don't overlap, as in: parameter_id = wxNewId() self.parameters=wxTextCtrl(self,parameter_id,"", size=wxDefaultSize,style=wxTE_READONLY) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Dec 17 05:45:34 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Dec 17 05:45:42 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHl0aG9uIG9yIE15U1FML1Bvc3RncmVTUUw/?= Message-ID: Sylvain Leclerc wrote: > I need to create a different database (or rather a different set of databases) for my office to integrate a number of disparate functions. My office uses index cards, ACT! database, paper filing, email, Post-it notes, and each staff has her/his notebokk into which everybody else write reminders. You guess the results: a mishmash of information everywhere; training new staff is a nightmare, and it is difficult to track information/communication for each of our members (we are a non-profit society). I always get worried when I see statements like that. While I understand your concern, I must caution you about trying to solve too much at once. Neither Python nor SQL is a silver bullet that will solve all your problems. If lack of order is the problem, a computerized system might just make it worse. This might actually be a management problem, rather than a technical problem... Would the people in question actually use your system, or would they just continue with their post-it notes? I'm sure many of us recognize your situation, and have tried to do what you did and failed. I think it's important to develop a tool like this in close cooperation with the users. Both to make sure that you solve something they see as a real problem, and that they feel that they are taking part in solving it. This should increase the chance that they will actually use the system. IF those emails, ACT! stuff, post-it and notebook notes etc all describe the same kind of information--for instance appointments, then it's probably not so difficult to write an application that takes care of this, but paper notes have a flexibility and adaptability which is difficult to model in a database--particularly in a relational database. I'd suggest that you start off with a clearly limited function, and try to solve that first, without too much consideration for its integration with other parts of the system. > My plan to deal with this is to minimize paper as much as possible and integrate as many functions as possible into a central repository. I was thinking of using for instance ZOPE to create an Intranet into which our policies, procedures, and training manuals can be posted (and updated once) and easily keyword-searched. This seems sensible. You might like to look at a Zope application like Plone for that. I also think you should consider a more light weight and flexible solution such as a wiki wiki, for instance MoinMoin (or ZWiki if you use Zope anyway). >I was also thinking of integrating written communication (fax, email, papermail) with the database(s) so that all the information pertaining to a member can be retrieved here. One of the reasons for this is that we have field staff who need as much current and complete information as possible to be effective in helping our members. Our field staff are disseminated over a large geographical area so it seems that it would be more logical for them to have access to our database in real time over a secure network. This is not an easy task, and I suggest that you look at that in a second step. It will require a lot of work to set it up, and also constant work to scan and index all the papers. Are you sure it's worth it? > Therefore my initial question (Python or MySQL/PostgreSQL) is loaded with the above situation. In other words: > 1. Will Python allow me to do what I intend to do? Python is well suited for this type of task. > 2. What are the limits in Python that MySQL or PostgreSQL do not have. What can it not do that the SQLs can do? SQL provides builtin support for atomic transactions, storage, database schemas, user authentication etc. All these things can be handled in Python, but it's a non-trivial effort. SQL is well suited for small regular sets of information that is updated often and needs to be kept under strict control, such as accounting systems, booking systems etc. It's not very well suited for other types of data such as documents or web sites. > 3. Same question as above but in reverse: what can Python do that the others can't? You can't build any application with *only* MySQL or PostgreSQL. They don't provide the facilities you need for user interfaces or business logic. They basically provide the feature I mention above. The typical solution would be to use a programming language like Python AND a relational (or other) database. What kind of user interface did you have in mind? Only a web based UI (through Zope) or a GUI or something else? > 4. Comparatively-speaking, what is the learning curve in both cases (Python vs the SQLs)? (I am not a programmer) If you intend to use SQL you need to learn both. SQL being a very narrow language (with only four different commands: SELECT, INSERT, UPDATE and DELETE, to work with once your application is rolling) is probably easier to grasp, but it's hopeless beyond its narrow scope. Python is certainly one of the easiest generic programming languages you can learn. Have a look at some tutorial. > 5. How fast can I get results? That depends on you much more than it depends on Python... I was thinking of developing the database modularly. First by replacing our ACT! database (and perhaps breaking the heavily-customized database into smaller, more manageable parts all linked together) thus requiring importing DBF files and ACT! memo fields, This is a fairly specific application, and I don't know how to solve that most conveniently. Can you access those database tables via ODBC? In that case it should be fairly simple to transfer them to PostgreSQL or MySQL. > then by creating and linking other databases (computer and paper-form), and finally by linking emails and other documents to it. > 6. How easy will it be to get support when I hit a wall? The Python community is very friendly, and both this mailing list and comp.lang.python etc can provide a lot of assistance, with advice and solutions to specific problems. I'm also sure you could get more extensive support from some of the many professional delvelopers in the community if you would need it and have a budget for that. > Thanks for reading this and for helping me in my quandary. Once I made a decision as to which way I choose, there will be no turning back since I need to forge ahead and get all those issues behind me. Now you worry me again... It's not easy for a non-programmer to get things like this right at once, and if you don't allow yourself to change your mind as you go along, you might just charge off in the wrong direction. (Or take all too long making up your mind.) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From lumbricus at gmx.net Wed Dec 17 06:15:04 2003 From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=) Date: Wed Dec 17 06:15:09 2003 Subject: [Tutor] socket send problem References: <20031217011848.47318.qmail@web20413.mail.yahoo.com> Message-ID: <16786.1071659704@www48.gmx.net> > Hi, > I have just started playing with python and sockets, > and here is the code that I wrote: > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((HOST, PORT)) > > for x in self.command: > sent = s.send(x) BTW: You may check, whether all data has been sent and - if not - call send again. This is necessary for large amounts of data. f.e.: sent = 0 while sent < len(x): sent = sent + s.send(x) > print "amount sent: "+sent print "amount sent: " + str(sent) ? > s.close() After the first run you try to send data through a closed socket. [ snip ] > Any help/pointers would be greatly appreciated! > Thanks, > Helena HTH and Greets, J"o! -- "Wir k?nnen alles sehen, was sich bewegt und wir k?nnen alles zerst?ren, was wir sehen." -- Richard Perle +++ GMX - die erste Adresse f?r Mail, Message, More +++ Neu: Preissenkung f?r MMS und FreeMMS! http://www.gmx.net From op73418 at mail.telepac.pt Wed Dec 17 07:11:28 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Dec 17 07:09:25 2003 Subject: [Tutor] Inheritance In-Reply-To: References: Message-ID: <33f0uv4k7mis388b7bhjaebqlmbj6ln1ch@4ax.com> On Tue, 16 Dec 2003 13:34:17 -0700, you wrote: >I'm just starting to learn classes and have run into trouble understanding >how classes inherit. > >One question is if class A inherits from class B and C. And then B inherits >from M and N. And C inherits from F and G, while F and N inherit from class >z which inherits from object, what is the name resolution. > > > > Z > M N F G > B C > A > > > >Also can someone explain to me what super() does, i need something pretty >basic. > D. Ehrenberg already answered some of your questions so I'll try to explain the why's and the how's of super. super is explained by the BDFL himself in an essay (all advanced stuff) http://www.python.org/2.2/descrintro.html (Warning: long and I dare say, advanced, post ahead) For starters imagine we have the following inheritance graph object A B C D Let me be more specific and write the class definitions >>> class A(object): ... def __init__(self): ... print "A" ... >>> class B(A): ... def __init__(self): ... print "B" ... >>> class C(A): ... def __init__(self): ... print "C" ... >>> class D(B,C): ... def __init__(self): ... print "D" ... >>> d = D() D The class D inherits from B and C (and from A indirectly) but the initializer __init__ never calls it's super classe's __init__. But this is almost always never what you want! Since the super classe's __init__ can contain fundamental initialization code for their instances to work. So the problem is: How to call from D.__init__ all the super classe's __init__? As you know, when Python, finds something like d. it uses (roughly - there are details I'm hiding) the following name look up rule: 1. Look in the instance's dictionary d.__dict__ 2. If 1. fails look in the instance's class dictionary d.__class__.__dict__ 3. If 2. fails crawl through the super classe's dictionary looking in their dictionaries. 4. If 3. fails call __getattr__ I'm interested in point 3. This crawling "through the super classe's" is achieved by linearizing the inheritance graph, that is, we transform the graph into a list. You can see that by calling mro on the *class* object: >>> D.mro() [, , , , ] So the search order is D, B, C, A, object. We can fold this knowledge in coding our __init__. >>> class D(B,C): ... def __init__(self): ... B.__init__(self) ... print "D" ... >>> d = D() B D Hmm... still not enough. We have to change B and C's __init__ to call their super classe's __init__. >>> class B(A): ... def __init__(self): ... A.__init__(self) ... print "B" ... >>> b = B() A B >>> class C(A): ... def __init__(self): ... A.__init__(self) ... print "C" ... >>> c = C() A C We don't do it with the A class, because object.__init__ is a no-op - does nothing. But for the classe's B and C things seem to be working - The super classe's __init__ is being called. Let us now test D, the base of our diamond inheritance graph: >>> d = D() A B D Hmmm... C.__init__ is not being called. Can you see why it is so? (D.__init__ calls B.__init__ calls A.__init__) Let us recode it and call it explicitely: >>> class D(B,C): ... def __init__(self): ... B.__init__(self) ... C.__init__(self) ... print "D" ... >>> d = D() A B A C D Now A.__init__ is being called twice! Can you see why it is so? (D.__init__ calls B.__init__ calls A.__init__. Then it calls C.__init__ calls A.__init__) Not good, since what we want is that each super classe's __init__ to be called exactly *once*. Notice that if you had single inheritance the above scheme would work just fine and dandy. It is multiple inheritance (D inherits from B and C) that makes things tougher. And this is precisely the problem that super is designed to solve. >>> class B(A): ... def __init__(self): ... super(B, self).__init__() ... print "B" ... >>> b = B() A B >>> class C(A): ... def __init__(self): ... super(C, self).__init__() ... print "C" ... >>> c = C() A C >>> class D(B,C): ... def __init__(self): ... super(D, self).__init__() ... print "D" ... >>> d = D() A C B D >>> Now it all works as you see. The structure of the super call is very simple: super(, ).() The online help is more explicit: >>> help(super) Help on class super in module __builtin__: class super(object) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) | Typical use to call a cooperative superclass method: | class C(B): | def meth(self, arg): | super(C, self).meth(arg) | .... Hope it helps, with my best regards, G. Rodrigues From vicki.stanfield at ROCHE.COM Wed Dec 17 11:51:27 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Wed Dec 17 11:54:50 2003 Subject: [Tutor] Questions about sizing RadioBox Message-ID: I have a couple of RadioBoxes. I would like the little box that appears around the buttons to be shorter. I have tried specifying a size, and I can affect the width of the box, but not the height. There are only two buttons in the box, and I have them side by side. Can anyone explain how the size parameter works with regard to RadioBoxes in wxPython, or does a question specific to wxPython belong on a different list? The code is: #Create the radio box that displays the input source options. wxRB_SINGLE makes them appear side by side self.source=wxRadioBox(self, -1, majorDimension = 1, label='Select input source:', choices=['Select command below','Read input from file'], size=(280,0), style= wxRB_SINGLE) EVT_RADIOBOX(self, -1, self.SetMode) --vicki -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031217/eaf39c9d/attachment.html From alan.gauld at blueyonder.co.uk Wed Dec 17 12:19:59 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 17 12:21:20 2003 Subject: [Tutor] Inheritance References: <33f0uv4k7mis388b7bhjaebqlmbj6ln1ch@4ax.com> Message-ID: <001f01c3c4c2$002f5f70$6401a8c0@xp> > ...I'll try to explain the why's and the how's of super... > Hope it helps, with my best regards, Hi Goncalo, thanks for the explanation, saves me going off to the docs. It works almost as I had expected except I wasn't expecting super to return an object... But the way it does work is actually more flexible and powerful than what I thought it did. thanks, Alan G From dyoo at hkn.eecs.berkeley.edu Wed Dec 17 12:27:20 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 17 12:27:35 2003 Subject: [Tutor] Finding quoted strings in a text? A hands-on tutorial on DFA->regex conversion In-Reply-To: <20031217040101.GB21218@wdfs.graniteweb.com> Message-ID: > > > [Warning: there's heavy regular expression and finite state automata > > > stuff in this message. Skip if it gets really confusing.] > > > > > > > > > For a small project that I'm working on, I've calculated out a > > > regular expression for finding quoted strings, but it's just > > > absolutely hideous. > > Any chance this is for csv file parsing? If yes, the new csv stuff in > 2.3 is a much simpler way of dealing with it. If not, I'm sorry for you > ;-) Hi David, No, it's more for a configuration file lexer/parser project. Don't be sorry for me: I think I'm enjoying myself a little too much to deserve much sympathy. *grin* It's fun for me to review all that theoretical CS stuff I learned from: http://www-math.mit.edu/~sipser/book.html and I think it's cool that even "esoteric" stuff like finite state automata can apply to the construction of regular expressions. I can't help but feel that it's useful, even though it takes me a few tries to get the regex looking somewhat decent... *grin* Talk to you later! From pythontutor at venix.com Wed Dec 17 15:26:49 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Dec 17 15:26:52 2003 Subject: [Tutor] returning a web page (and also path to web root) In-Reply-To: <20031216235355.12871.qmail@web41414.mail.yahoo.com> References: <20031216235355.12871.qmail@web41414.mail.yahoo.com> Message-ID: <3FE0BC09.4080707@venix.com> Barnaby Scott wrote: > More thanks - but more problems! > > The copy_snippet function won't work for me because I > actually need the document to be *served* to the > client, rather than read and printed to stdout. > Reason: it is likely to be a server-parsed document! > (In any case surely this will also suffer from the > relative links problem?) I guess I don't really understand your environment. Typically, a cgi script is running with stdout piped back to the web server. You need to print the header(s), e.g.: print "Content-type: test/html" print a blank line separator (I say print because the headers are line oriented and you need to include line marks to delimit each line. print will do that for you.) and finally print the page contents. The web server passes this stream of data on to the client browser. What mechanism are you using to pass data to the client browser? Are we talking about CGI? I am not sure what you mean by *served* to the client other than what I describe above, writing (or printing) through the server to the browser. > > Sadly, Location: isn't working for me either, though > that looked such a good option. I think the reason is > that the request to the script is a POST, and the > 're-request' (is there such a word?) forced by the > Location header seems to be attempted with another > POST - and therefore fails (see - I'm learning fast! I > never knew half this stuff 48 hours ago). Post means that arguments from the browser to your script are in the data stream and NOT tagged on the end of the URL. Python's cgi module insulates you from this difference. I'd expect that there is something else going on. The browser should simply load the page specified by the Location: header. Are you sure there are no other headers or content to confuse things? I'd recommend getting trivial little scripts (4 or 5 lines) working and then joining the pieces together. > > At this point I have been reduced to returning a META > HTTP-EQUIV="Refresh" tag to the the client. I don't > like it a) because I believe it is browser-dependent, > and b) it shows a blank page momentarily (even with > CONTENT=0) > > Don't worry if you have come to the end of your > suggestion list! I just wanted to report back with > thanks and an update. > > > > --- Lloyd Kvam wrote: > >>Barnaby Scott wrote: >> >> >>>Thanks very much. In fact I like the look of your >>>first idea the best - the Location: thing. Even >>>shorter and more concise than I had hoped for! >>> >>>I think both my problems in fact stem from more >> >>lack >> >>>of knowledge of http and webservers than Python, >> >>so >> >>>forgive me if this is all slightly off-topic. >>> >>>The problem I feared does in fact occur - I used >>>urllib to get a page and display it, and sure >> >>enough >> >>>the images sources and some links failed to work. >>>Because they are relative references, they went >> >>from >> >>>the wrong starting point - i.e. not the web >> >>directory >> >>>of the page, but cgi-bin where the script lives. >> >>Below is the function I normally use to output an >>existing HTML file >>through a cgi script. Note that it is all done >>using normal file IO >>and avoids processing the HTML. urllib is probably >>"too smart" for >>what you are trying to do. This function should >>work for HTML files >>on your server. >> >>def copy_snippet( filename, out_file=None): >> if out_file is None: >> out_file = sys.stdout >> if os.path.exists( filename): >> snip = open( filename, 'r') >> shutil.copyfileobj( snip, out_file) >> snip.close() >> >>The variable name snip was used because these are >>usually snippets of >>HTML. (Server side includes may have been a better >>way to go.) >> >> >>>As for the web root thing: I can get the >> >>DOCUMENT_ROOT >> >>>to display, but this appears to be a totally >> >>different >> >>>directory to the one I am interested in! My >> >>situation >> >>>is that I have rented space on a server for 3 >> >>domains. >> >>>The path I want returned takes the following form: >>> >>> >> > /home/myaccountname/webs/www.oneofmydomains.com/htdocs > >>>The DOCUMENT_ROOT returns instead: >>> >>>/usr/local/www/data >>> >>>When I look there, the stuff is nothing to do with >> >>me >> >>>at all! >> >>??? >>I'm not sure what to tell you. If you run >>cgi.test() you'll get >>a list of all of the environment variables. Perhaps >>there is a >>better one to use. Could you have mis-tested in >>looking up >>DOCUMENT_ROOT? I only have Apache running anywhere >>that I can check. >>All of those locations report the correct >>DOCUMENT_ROOT for the sites. >> >>-- >>Lloyd Kvam >>Venix Corp. >>1 Court Street, Suite 378 >>Lebanon, NH 03766-1358 >> >>voice: 603-653-8139 >>fax: 801-459-9582 >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From piir at earthlink.net Wed Dec 17 19:26:29 2003 From: piir at earthlink.net (Todd G. Gardner) Date: Wed Dec 17 19:26:34 2003 Subject: [Tutor] Calling dlls from python Message-ID: Hello all, Any recomendations on where to look regarding this? I have read in this link http://mail.python.org/pipermail/python-list/2002-April/095937.html that there is a "calldll" module but I am not sure where to look? Thanks in advance, Todd From the_investor at arach.net.au Wed Dec 17 19:37:11 2003 From: the_investor at arach.net.au (Ryan Sheehy) Date: Wed Dec 17 19:38:00 2003 Subject: [Tutor] Self Message-ID: Could someone please explain to me why the call 'self' is needed in methods and functions? I'm having difficulty trying to understand it. Thanks, Ryan --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003 From dyoo at hkn.eecs.berkeley.edu Wed Dec 17 20:56:06 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 17 20:56:17 2003 Subject: [Tutor] Self In-Reply-To: Message-ID: On Thu, 18 Dec 2003, Ryan Sheehy wrote: > Could someone please explain to me why the call 'self' is needed in > methods and functions? > > I'm having difficulty trying to understand it. Hi Ryan, Let's use a concrete example. Let's say we have a Person: ### class Person: def pat_head(self): print "I'm patting my head" def rub_stomach(self): print "I'm rubbing my stomach" ### Let's say that we'd like to add one more method to this Person, some way of telling the person to both rub its head and stomach sequentially: ### class Person: def pat_head(self): print "I'm patting my head" def rub_stomach(self): print "I'm rubbing my stomach" def play_game(self): self.pat_head() self.rub_stomach() ### Ok, the pieces are set. *grin* What happens if there aren't any 'self' parameters being passed around? Let's imagine it: ### class BadPerson: """Note: this class will not work.""" def pat_head(): print "I'm patting my head" def rub_stomach(): print "I'm rubbing my stomach" def play_game(): pat_head() ## ?? rub_stomach() ## ?? ### The first two methods might look ok still, but what about the third? The commented lines with the '??' should draw our attention: what in particular is trying to pat_head() and rub_stomach()? Nothing is, so this is syntactically weird --- Just from inspection, this doesn't look like a method call in Python. (Note: if you're coming from a language like C++ or Java, you may be wondering what happened to 'this'. Python does not have any support for 'this', but instead opts for a more explicit model of passing 'self' around.) Without a way of accessing the instance, there's no way of writing methods that themselves call other methods on the same instance. So having 'self' around lets us write things like play_game(). Does this make sense so far? Good luck to you! From littledanehren at yahoo.com Wed Dec 17 21:26:09 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Dec 17 21:26:17 2003 Subject: [Tutor] Calling dlls from python In-Reply-To: Message-ID: <20031218022609.62560.qmail@web41811.mail.yahoo.com> "Todd G. Gardner" wrote: > Hello all, > > Any recomendations on where to look regarding this? > > I have read in this link > http://mail.python.org/pipermail/python-list/2002-April/095937.html > that there is a "calldll" module but I am not sure > where to look? > > Thanks in advance, > > Todd I can't find it, but CTypes performs the function of reading dll's, which is probably what you want to do. It can also work on Linux and other Unixes, including Mac OS X. It also can be used to create and manipulate C datatypes. Here's a testimonial from their main page: I am using it and much prefer it to the calldll/windll ... easy to use, well documented ... - Ben C There are a bunch of others that say how much easier it is to acess windows internal functions, but it's probably the same as with calldll. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From the_investor at arach.net.au Wed Dec 17 21:35:37 2003 From: the_investor at arach.net.au (Ryan Sheehy) Date: Wed Dec 17 21:36:24 2003 Subject: [Tutor] Self In-Reply-To: Message-ID: Thanks Todd and Danny! Danny: Okay... 'self' is required if calls need to be made to methods and functions that reside in the same class. Is that right? If so, could the call 'Person.pat_head()' still give the same result in the play_game method? Thanks, Ryan -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Thursday, 18 December 2003 9:56 AM To: Ryan Sheehy Cc: tutor@python.org Subject: Re: [Tutor] Self On Thu, 18 Dec 2003, Ryan Sheehy wrote: > Could someone please explain to me why the call 'self' is needed in > methods and functions? > > I'm having difficulty trying to understand it. Hi Ryan, Let's use a concrete example. Let's say we have a Person: ### class Person: def pat_head(self): print "I'm patting my head" def rub_stomach(self): print "I'm rubbing my stomach" ### Let's say that we'd like to add one more method to this Person, some way of telling the person to both rub its head and stomach sequentially: ### class Person: def pat_head(self): print "I'm patting my head" def rub_stomach(self): print "I'm rubbing my stomach" def play_game(self): self.pat_head() self.rub_stomach() ### Ok, the pieces are set. *grin* What happens if there aren't any 'self' parameters being passed around? Let's imagine it: ### class BadPerson: """Note: this class will not work.""" def pat_head(): print "I'm patting my head" def rub_stomach(): print "I'm rubbing my stomach" def play_game(): pat_head() ## ?? rub_stomach() ## ?? ### The first two methods might look ok still, but what about the third? The commented lines with the '??' should draw our attention: what in particular is trying to pat_head() and rub_stomach()? Nothing is, so this is syntactically weird --- Just from inspection, this doesn't look like a method call in Python. (Note: if you're coming from a language like C++ or Java, you may be wondering what happened to 'this'. Python does not have any support for 'this', but instead opts for a more explicit model of passing 'self' around.) Without a way of accessing the instance, there's no way of writing methods that themselves call other methods on the same instance. So having 'self' around lets us write things like play_game(). Does this make sense so far? Good luck to you! --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003 From littledanehren at yahoo.com Wed Dec 17 21:59:41 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Dec 17 21:59:45 2003 Subject: [Tutor] functions instead of classes Message-ID: <20031218025941.13423.qmail@web41804.mail.yahoo.com> I was trying to learn PyGTK, but I thought the style of object orientation used was a bit odd because it didn't need to be inherited from anything, most of the code was in __init__, and only one function, main() was ever run externally. I rewrote it to be a function that locally contains some functions. This is what wxLua uses to construct its GUIs, roughly, and it makes for much shorter code. Here's a simple application that makes a window appear that has a button with Hello world on it, and when you click it, it writes Hello world to the console. import gtk def HelloWorld(): def hello(widget, data=None): print "Hello World" def destroy(widget, data=None): gtk.main_quit() window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("delete_event", destroy) window.connect("destroy", destroy) window.set_border_width(10) button = gtk.Button("Hello World") button.connect("clicked", hello, None) window.add(button) button.show() window.show() gtk.main() if __name__ == "__main__": HelloWorld() This is around 5 lines shorter than when using objects, and with objects you have to always use those annoying prefixes. Is there anything wrong with this coding style? I've heard that object orientation makes it more reusable, but when are you going to reuse a GUI layout? It's in a function so it can already be called more than once. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From syrinx at simplecom.net Thu Dec 18 02:31:21 2003 From: syrinx at simplecom.net (Scott) Date: Thu Dec 18 02:33:31 2003 Subject: [Tutor] SAX Message-ID: <20031218013121.31017673.syrinx@simplecom.net> Where is the best down and dirty SAX tutorial on the web? I've never fooled around with XML much. Isn't SAX what I want if I may be confronted with HUGE files, that I can't possibly load totally. And I can just prod around and poke them? Thanks. From glingl at aon.at Thu Dec 18 02:59:55 2003 From: glingl at aon.at (Gregor Lingl) Date: Thu Dec 18 02:59:01 2003 Subject: [Tutor] Self In-Reply-To: References: Message-ID: <3FE15E7B.20405@aon.at> Ryan Sheehy schrieb: >Thanks Todd and Danny! > >Danny: > >Okay... 'self' is required if calls need to be made to methods and functions >that reside in the same class. Is that right? > >If so, could the call 'Person.pat_head()' still give the same result in the >play_game method? > >Thanks, > > Hi Ryan! I'll try to elaborate a bit Danny's example. Suppose you have: class Person: def __init__(self, name): self.name = name def pat_head(self): print "I'm", self.name,"and", print "I'm patting my head" def rub_stomach(self): print "I'm", self.name, "and", print "I'm rubbing my stomach" ## The class Person can be used this way: >>> danny = Person("Danny") >>> ryan = Person("Ryan") >>> danny.rub_stomach() I'm Danny and I'm rubbing my stomach >>> ryan.pat_head() I'm Ryan and I'm patting my head ## We want Danny to play a game and define a function: >>> def play_game(): danny.pat_head() danny.rub_stomach() >>> play_game() I'm Danny and I'm patting my head I'm Danny and I'm rubbing my stomach ## But what if Ryan also wants to play the game? ## We can redefine play_game with a parameter, ## so we can pass the person to play to it as ## an argument. >>> def play_game(somebody): somebody.pat_head() somebody.rub_stomach() >>> play_game(danny) I'm Danny and I'm patting my head I'm Danny and I'm rubbing my stomach >>> play_game(ryan) I'm Ryan and I'm patting my head I'm Ryan and I'm rubbing my stomach ## works fine. Now we can make this to ## a method of Person by simply putting it into the class statement that defines Person: class Person: def __init__(self, name): self.name = name def pat_head(self): print "I'm", self.name,"and", print "I'm patting my head" def rub_stomach(self): print "I'm", self.name, "and", print "I'm rubbing my stomach" def play_game(somebody): somebody.pat_head() somebody.rub_stomach() ## and try it out: >>> ================================ RESTART ================================ >>> danny = Person("Danny") >>> ryan = Person("Ryan") >>> danny.play_game() I'm Danny and I'm patting my head I'm Danny and I'm rubbing my stomach >>> ryan.play_game() I'm Ryan and I'm patting my head I'm Ryan and I'm rubbing my stomach ## works fine. Incidentally there is the *convention* ## to call the parameter that points to the object ## it*self* self. ## Alas, Your proposition to use Person.pat_head() ## won't work, as it leaves open who should pat his head. ## But you *can* use a method like a function bound to a class, ## passing the appropriate argument as earlier, like this: >>> Person.play_game(ryan) I'm Ryan and I'm patting my head I'm Ryan and I'm rubbing my stomach >>> Hope this makes something more clear for you Gregor From alan.gauld at blueyonder.co.uk Thu Dec 18 03:41:42 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 18 03:42:51 2003 Subject: [Tutor] functions instead of classes References: <20031218025941.13423.qmail@web41804.mail.yahoo.com> Message-ID: <005001c3c542$c2f47560$6401a8c0@xp> > coding style? I've heard that object orientation makes > it more reusable, but when are you going to reuse a > GUI layout? When its a dialog box :-) but in general you are right. Alan G From barnabydscott at yahoo.com Thu Dec 18 09:00:11 2003 From: barnabydscott at yahoo.com (Barnaby Scott) Date: Thu Dec 18 09:00:24 2003 Subject: [Tutor] buffering print statement Message-ID: <20031218140011.40364.qmail@web41405.mail.yahoo.com> Is there a simple way of redirecting the output of 'print' statements in a script, until such time as I actually want them sent to stdout, and they can all be sent at once? I guess I could create a file-like object and then use 'print >>' to it, but this is not what I am after ideally. Equally I know I could assign sys.stdout to my 'buffer', but I don't know how to reverse the process and get at the output when I want it! As you can tell from my ramblings, I'm none too advanced, and would be grateful for a steer! __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From pythontutor at venix.com Thu Dec 18 10:08:09 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Dec 18 10:08:15 2003 Subject: [Tutor] LunaticPython bridges Lua and Python Message-ID: <3FE1C2D9.1040300@venix.com> There was a recent inquiry about Python vs. Lua. The enclosed link describes a product allows python programs to use Lua and Lua programs to use python. So the author must see these languages as complementary. https://moin.conectiva.com.br/LunaticPython LunaticPython - CncMoin I saw the link to LunaticPython at: http://www.pythonware.com/daily/index.htm Daily Python-URL -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From john at duartedailey.org Thu Dec 18 11:27:50 2003 From: john at duartedailey.org (John Duarte) Date: Thu Dec 18 11:30:30 2003 Subject: [Tutor] PyWin Install problem Message-ID: <200312180827.50289.john@duartedailey.org> Help. I am trying to install PyWin on a Windows 2000 machine. I have Python 2.3a2 installed. The PyWin version is: win32all-163 I get the following errors: 1. The procedure entry point PyGILState_Release could not be located in the dynamic link library python23.dll 2. Registration of the AXScript Engine COM server failed. Installation will continue, but this server will require manual registration before it will function. pywintypes.error:(127, 'LoadLibrary', 'The specified procedure could not be found.') 3. Registration of the Python Interpreter COM server failed. Installation will continue, but this server will require manual registration before it will function. exceptions.AttributeError: 'module' object has no attribute 'com_error'. 4. Registration of the Python Dictionary COM server failed. Installation will continue, but this server will require manual registration before it will function. exceptions.ImportError: cannot import name DISPATCH_METHOD. Does anybody have any insight into this problem?? Thanks, -John From op73418 at mail.telepac.pt Thu Dec 18 11:43:39 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Dec 18 11:41:37 2003 Subject: [Tutor] Re: Inheritance In-Reply-To: References: <33f0uv4k7mis388b7bhjaebqlmbj6ln1ch@4ax.com> Message-ID: On Wed, 17 Dec 2003 13:50:27 -0700, you wrote: I'm forwarding this back to the list. Always reply (also) to the list, since other people may learn and possibly even correct me! > >Thanks a lot that was really helpful. Couple questions though. >In this part why is C called before B?? > This is just a concequence of the linearization algorithm. There is a paper on the web by Michele Simionato explaining the one that made it in 2.3. It's called C3 and was borrowed from Dylan. http://www.python.org/2.3/mro.html This is heavy stuff (at least it is for me) - you've been warned. >>>> class D(B,C): >... def __init__(self): >... super(D, self).__init__() >... print "D" >... >>>> d = D() >A >C >B >D >>>> > >Also(I hope I dont regret asking) > >How does Super make sure that only 1 instance of A is called Why don't we explore it together? To give a convenient, accurate and 100% correct picture we would have to go down to the bowels of the C implementation, and this is a Python Tutor list not a C Tutor list. Besides, I haven't touched C in more than 10 years so it's like Huh, isn't C the third letter in the alphabet? So i'll just try to give a mental picture of how things work - as I understand them, if anyone is reading, feel free to correct me!: First, super returns an *object* as you can see from the online help: Help on class super in module __builtin__: class super(object) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) ... As such we can ask what are its attributes: >>> for elem in dir(super): ... print elem ... __class__ __delattr__ __doc__ __get__ __getattribute__ __hash__ __init__ __new__ __reduce__ __reduce_ex__ __repr__ __self__ __self_class__ __setattr__ __str__ __thisclass__ Everything is standard here except those misteryous __thisclass__ and __self_class__ attributes. Let us try to see what they give in a concrete case. Let us go back to our diamond inheritance graph and write the __init__ methods as >>> class A(object): ... def __init__(self): ... print "A" ... >>> class B(A): ... def __init__(self): ... obj = super(B, self) ... print obj.__thisclass__ ... print obj.__self_class__ ... obj.__init__() ... >>> class C(A): ... def __init__(self): ... obj = super(C, self) ... print obj.__thisclass__ ... print obj.__self_class__ ... obj.__init__() ... >>> class D(C, B): ... def __init__(self): ... obj = super(D, self) ... print obj.__thisclass__ ... print obj.__self_class__ ... obj.__init__() ... Now let us test it: >>> d = D() A Ah Ah... see what's going on? When D.__init__ is first called, a super object is instantiated. __thisclass__ and __self_class__ point to the D class. But going up the call chain, the __thisclass__ reference is updated *according* to the mro linearization. This way super always knows where it is in the mro list and can call the right methods. If you didn't understood, no problem. I'm not sure I understand it myself fully! Anyway, hope it helped some, with my best regards, G. Rodrigues From ralobao at click21.com.br Thu Dec 18 11:42:07 2003 From: ralobao at click21.com.br (Ruivaldo Neto) Date: Thu Dec 18 11:52:16 2003 Subject: [Tutor] returning a web page (and also path to web root) In-Reply-To: <3FE0BC09.4080707@venix.com> References: <20031216235355.12871.qmail@web41414.mail.yahoo.com> <3FE0BC09.4080707@venix.com> Message-ID: <200312181442.07876.ralobao@click21.com.br> why you dont use replace ???? i think its is simple.. look the website that you want is: www.asite.com/post.php?name=itsme and it delivere a picture and your name like: (i dont know if its correct but....) and your name: itsme and you want to repassa for you client this page like a browser do, isnt it ?, you simples make a replace on the content like : string.replace(content,' Barnaby Scott wrote: > > More thanks - but more problems! > > > > The copy_snippet function won't work for me because I > > actually need the document to be *served* to the > > client, rather than read and printed to stdout. > > Reason: it is likely to be a server-parsed document! > > (In any case surely this will also suffer from the > > relative links problem?) > > I guess I don't really understand your environment. Typically, > a cgi script is running with stdout piped back to the web server. > You need to print the header(s), e.g.: > print "Content-type: test/html" > print a blank line separator > (I say print because the headers are line oriented and you need > to include line marks to delimit each line. print will do that > for you.) > and finally print the page contents. > > The web server passes this stream of data on to the client browser. > > What mechanism are you using to pass data to the client browser? > Are we talking about CGI? > > I am not sure what you mean by *served* to the client other than what > I describe above, writing (or printing) through the server to the browser. > > > Sadly, Location: isn't working for me either, though > > that looked such a good option. I think the reason is > > that the request to the script is a POST, and the > > 're-request' (is there such a word?) forced by the > > Location header seems to be attempted with another > > POST - and therefore fails (see - I'm learning fast! I > > never knew half this stuff 48 hours ago). > > Post means that arguments from the browser to your script > are in the data stream and NOT tagged on the end of the URL. > Python's cgi module insulates you from this difference. > > I'd expect that there is something else going on. The browser > should simply load the page specified by the Location: header. > Are you sure there are no other headers or content to confuse things? > > I'd recommend getting trivial little scripts (4 or 5 lines) working > and then joining the pieces together. > > > At this point I have been reduced to returning a META > > HTTP-EQUIV="Refresh" tag to the the client. I don't > > like it a) because I believe it is browser-dependent, > > and b) it shows a blank page momentarily (even with > > CONTENT=0) > > > > Don't worry if you have come to the end of your > > suggestion list! I just wanted to report back with > > thanks and an update. > > > > --- Lloyd Kvam wrote: > >>Barnaby Scott wrote: > >>>Thanks very much. In fact I like the look of your > >>>first idea the best - the Location: thing. Even > >>>shorter and more concise than I had hoped for! > >>> > >>>I think both my problems in fact stem from more > >> > >>lack > >> > >>>of knowledge of http and webservers than Python, > >> > >>so > >> > >>>forgive me if this is all slightly off-topic. > >>> > >>>The problem I feared does in fact occur - I used > >>>urllib to get a page and display it, and sure > >> > >>enough > >> > >>>the images sources and some links failed to work. > >>>Because they are relative references, they went > >> > >>from > >> > >>>the wrong starting point - i.e. not the web > >> > >>directory > >> > >>>of the page, but cgi-bin where the script lives. > >> > >>Below is the function I normally use to output an > >>existing HTML file > >>through a cgi script. Note that it is all done > >>using normal file IO > >>and avoids processing the HTML. urllib is probably > >>"too smart" for > >>what you are trying to do. This function should > >>work for HTML files > >>on your server. > >> > >>def copy_snippet( filename, out_file=None): > >> if out_file is None: > >> out_file = sys.stdout > >> if os.path.exists( filename): > >> snip = open( filename, 'r') > >> shutil.copyfileobj( snip, out_file) > >> snip.close() > >> > >>The variable name snip was used because these are > >>usually snippets of > >>HTML. (Server side includes may have been a better > >>way to go.) > >> > >>>As for the web root thing: I can get the > >> > >>DOCUMENT_ROOT > >> > >>>to display, but this appears to be a totally > >> > >>different > >> > >>>directory to the one I am interested in! My > >> > >>situation > >> > >>>is that I have rented space on a server for 3 > >> > >>domains. > >> > >>>The path I want returned takes the following form: > > > > /home/myaccountname/webs/www.oneofmydomains.com/htdocs > > > >>>The DOCUMENT_ROOT returns instead: > >>> > >>>/usr/local/www/data > >>> > >>>When I look there, the stuff is nothing to do with > >> > >>me > >> > >>>at all! > >> > >>??? > >>I'm not sure what to tell you. If you run > >>cgi.test() you'll get > >>a list of all of the environment variables. Perhaps > >>there is a > >>better one to use. Could you have mis-tested in > >>looking up > >>DOCUMENT_ROOT? I only have Apache running anywhere > >>that I can check. > >>All of those locations report the correct > >>DOCUMENT_ROOT for the sites. > >> > >>-- > >>Lloyd Kvam > >>Venix Corp. > >>1 Court Street, Suite 378 > >>Lebanon, NH 03766-1358 > >> > >>voice: 603-653-8139 > >>fax: 801-459-9582 > >> > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > __________________________________ > > Do you Yahoo!? > > New Yahoo! Photos - easier uploading and sharing. > > http://photos.yahoo.com/ -- RS: Ruivaldo Neto From carroll at tjc.com Thu Dec 18 13:11:25 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 18 13:11:30 2003 Subject: [Tutor] SAX In-Reply-To: <20031218013121.31017673.syrinx@simplecom.net> Message-ID: On Thu, 18 Dec 2003, Scott wrote: > Where is the best down and dirty SAX tutorial on the web? I haven't found one, but I strongly recommend obtaining or borrowing the O'Reilley Python and XML book. It excels at this. (I was able to borrow a copy from the San Jose Public Library, but this is Silicon Valley; that might not be possible in many other areas.) -- Terry Carroll Santa Clara, CA carroll@tjc.com From carroll at tjc.com Thu Dec 18 13:35:29 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 18 13:35:33 2003 Subject: [Tutor] buffering print statement In-Reply-To: <20031218140011.40364.qmail@web41405.mail.yahoo.com> Message-ID: On Thu, 18 Dec 2003, Barnaby Scott wrote: > Is there a simple way of redirecting the output of > 'print' statements in a script, until such time as I > actually want them sent to stdout, and they can all be > sent at once? > > I guess I could create a file-like object and then use > 'print >>' to it, but this is not what I am after > ideally. That's what I would do. StringIO is good for this: ------------------ #test1.py import StringIO buf = StringIO.StringIO() for i in range(1,11): print >>buf, "Buffered line", i print "now processing line", i #now dump the StringIO print buf.getvalue() buf.close() ------------------ >python test1.py now processing line 1 now processing line 2 now processing line 3 now processing line 4 now processing line 5 now processing line 6 now processing line 7 now processing line 8 now processing line 9 now processing line 10 Buffered line 1 Buffered line 2 Buffered line 3 Buffered line 4 Buffered line 5 Buffered line 6 Buffered line 7 Buffered line 8 Buffered line 9 Buffered line 10 > Equally I know I could assign sys.stdout to my > 'buffer', but I don't know how to reverse the process > and get at the output when I want it! I wouldn't take that approach, but if you want, there are two ways to get it back. First, if you know that no one else has messed with stdout, the normal stdout is stored in sys.__stdout__. So you can do this: -------------------- import sys print "writing to normal stdout" outfile=open("output.txt","w") sys.stdout=outfile print "writing to file" outfile.close() sys.stdout=sys.__stdout__ print "back to the normal stdout again." -------------------- This does just what the code implies; you'll see the two lines "writing to normal stdout" and "back to the normal stdout again" on the console, and output.txt will contain the line "writing to file". Another, more general, approach, if you think that another part of the program or caller may have assigned stdout to something other than the normal stdout is simply to save it and restore it: ----------------------- import sys print "writing to normal stdout" outfile=open("output.txt","w") temp_file_object = sys.stdout sys.stdout=outfile print "writing to file" outfile.close() sys.stdout=temp_file_object print "back to the normal stdout again." ----------------------- But I think StringIO is probably the way to go. -- Terry Carroll Santa Clara, CA carroll@tjc.com From dyoo at hkn.eecs.berkeley.edu Thu Dec 18 14:02:10 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 18 14:02:17 2003 Subject: [Tutor] Self In-Reply-To: Message-ID: On Thu, 18 Dec 2003, Ryan Sheehy wrote: > If so, could the call 'Person.pat_head()' still give the same result in > the play_game method? Hi Ryan, This almost works. However, it's a requirement in Python that the first parameter in each method has to be 'self'. (I'm actually lying. *grin* That last statement was true until Python 2.2. I'll explain more fully in the bottom of this message.) Here's one reason for this constraint: if we allow a method that doesn't take 'self', it would mean that the 'method' doesn't care about its instance, and in that case, why is it even a method? *grin* Methods are really functions that are attached to an object. These methods are meant to care about the instance that they're attached to --- otherwise, it would be more approprate to just write a function. And in fact, with the original example: ### class Person: def pat_head(self): print "I'm patting my head" def rub_stomach(self): print "I'm rubbing my stomach" def play_game(self): self.pat_head() self.rub_stomach() ### it makes little sense for Person to be a class with those methods: it would be so much more simpler to just use functions: ### def pat_head(): print "I'm patting my head" def rub_stomach(): print "I'm rubbing my stomach" def play_game(): pat_head() rub_stomach() ### which is fine. So the example from before was actually a very bad one in terms of showing what objects are good for, since none of the methods actually did anything with 'self'. Let me augment the original example a bit more more: ### class Person: def __init__(self, name): self.name = name self.count_heads = 0 self.count_stomachs = 0 def summarize(self): print "I,", self.name, print "have patted my head", self.count_heads, "times", print "and rubbed my stomach", self.count_stomachs, "times." def pat_head(self): print "I,", self.name, "am patting my head" self.count_heads += 1 def rub_stomach(self): print "I,", self.name, "am rubbing my stomach" self.count_stomachs += 1 def play_game(self): self.pat_head() self.rub_stomach() ### Now these methods use 'self' as a way of sharing and remembering the status of the object --- we're using 'self' here as a place to store counts of things. It should be a little easier to see that passing 'self' around is useful now. Most classes will have methods that pay attention to the state that's stuffed in 'self' --- it's less common to have methods that totally disregard 'self'. Going back to your question: > If so, could the call 'Person.pat_head()' still give the same result in > the play_game method? The reason we mentioned this "almost" works is because in newer versions of Python, it actually is possible to do this, using "static methods". We can tell the system that, yes, we don't really need 'self' on certain methods, by marking them with 'staticmethod': ### class Person: def pat_head(): print "I'm patting my head" pat_head = staticmethod(pat_head) def rub_stomach(): print "I'm rubbing my stomach" rub_stomach = staticmethod(rub_stomach) def play_game(): Person.pat_head() Person.rub_stomach() play_game = staticmethod(play_game) ### And then it works. The details of this are defined in: http://python.org/2.2/descrintro.html#staticmethods I have to admit: I have this uncomfortable feeling about staticmethod(), and not just because it's a recent addition to the language. It just seems to me that allowing static methods adds little power to the language, and at the very high cost of complicating explanations like this one. *grin* Anyway, I hope this helps! From john at duartedailey.org Thu Dec 18 14:19:12 2003 From: john at duartedailey.org (John Duarte) Date: Thu Dec 18 14:21:44 2003 Subject: [Tutor] PyWin Install problem In-Reply-To: <20031218185840.49715.qmail@web41804.mail.yahoo.com> References: <20031218185840.49715.qmail@web41804.mail.yahoo.com> Message-ID: <200312181119.12933.john@duartedailey.org> Dan, Maybe my terminology is incorrect. I am not installing a new version of Python. I am just trying to install "Mark Hammond's Python Extentions for Windows". I thought these were also known as 'PyWin'. My apologies if this is incorrect. -John On Thursday 18 December 2003 10:58 am, you wrote: > John Duarte wrote: > > Help. > > I am trying to install PyWin on a Windows 2000 > > machine. > > I have Python 2.3a2 installed. > > The PyWin version is: win32all-163 > > > > I get the following errors: > > > > 1. The procedure entry point PyGILState_Release > > could not be located in the > > dynamic link library python23.dll > > > > 2. Registration of the AXScript Engine COM server > > failed. Installation will > > continue, but this server will require manual > > registration before it will > > function. > > pywintypes.error:(127, 'LoadLibrary', 'The > > specified procedure could not > > be found.') > > > > 3. Registration of the Python Interpreter COM server > > failed. Installation will > > continue, but this server will require manual > > registration before it will > > function. > > exceptions.AttributeError: 'module' object has > > no attribute 'com_error'. > > > > 4. Registration of the Python Dictionary COM server > > failed. Installation will > > continue, but this server will require manual > > registration before it will > > function. > > exceptions.ImportError: cannot import name > > DISPATCH_METHOD. > > > > Does anybody have any insight into this problem?? > > > > Thanks, > > -John > > Try uninstalling the earlier version of Python first. > > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ From helena_b2001 at yahoo.com Thu Dec 18 16:10:04 2003 From: helena_b2001 at yahoo.com (helena bhaska) Date: Thu Dec 18 16:10:24 2003 Subject: [Tutor] server design issue Message-ID: <20031218211004.7755.qmail@web20418.mail.yahoo.com> Hi, I am writing a simple server application, which loops waiting for connections, and as soon as it receives one, it creates a thread to deal with it. The server thread is supposed to loop forever, and if it receives data through a socket it sends the data to a serial port and exits, or if it receives data through a serial port it sends it on through a socket and keeps on looping. Now, the problem is if i use blocking socket, the loop will get stuck on recv() statement and never get to reading data from serial port part, and if i use nonblocking socket, it will get to reading data from serial port part no problem, but the recv() statement will for some reason receive the data in one big chunk, even though I am sending it one byte at a time. And i really want it in one byte at a time - which is what i get with blocking socket. The only solution i see is to separate reading and writing funcionality into different classes(and use different ports maybe), but maybe there is a more elegant solution for this. Thanks for any ideas! __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From alan.gauld at blueyonder.co.uk Thu Dec 18 17:18:04 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 18 17:19:04 2003 Subject: [Tutor] buffering print statement References: <20031218140011.40364.qmail@web41405.mail.yahoo.com> Message-ID: <007b01c3c5b4$ce8b80e0$6401a8c0@xp> > Is there a simple way of redirecting the output of > 'print' statements in a script, until such time as I > actually want them sent to stdout, and they can all be > sent at once? Umm, I may be missing something but that sounds like a string variable? Just send formatted strings to a string variable, then at the end print the string... buffer = "Hello world\n" foo = 27 + 42 buffer += str(foo) + '\n' etc/... print buffer You could even write a short function (printbuff, say) to take care of adding newlines etc. Or is there something else you want to do? Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Dec 18 17:20:42 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 18 17:20:47 2003 Subject: [Tutor] SAX In-Reply-To: <20031218013121.31017673.syrinx@simplecom.net> Message-ID: On Thu, 18 Dec 2003, Scott wrote: > Where is the best down and dirty SAX tutorial on the web? I've never > fooled around with XML much. Isn't SAX what I want if I may be > confronted with HUGE files, that I can't possibly load totally. And I > can just prod around and poke them? Hi Scott, If you're going to handle huge files, SAX will work. An alternative is to use something that partially constructs the XML tree structure on demand. The 'pulldom' module is a good module to know about: http://www.python.org/doc/lib/module-xml.dom.pulldom.html But the documentation on pulldom is filled with little '...' "fill-me-in" sort of things, which is really not so good. *sigh* There's slightly better documentation on pulldom here: http://www.prescod.net/python/pulldom.html The pulldom approach is nice because it's a hybrid between the "stream" approach of SAX and the structured approach of the DOM. As a concrete example, let's say we have the following XML text: ### xmlText = """ 68414.t07192 51530.t00029 Aug 23 2001 12:27AM F24J5.21 At1g68680 expressed protein 0 Aug 23 2001 12:27AM 25789169 25790587 """ ### We'd like to traverse through this XML using some kind of parser. Here's one approach, using the 'pulldom' module: ### from xml.dom import pulldom from StringIO import StringIO xmlFile = StringIO(xmlText) events = pulldom.parse(xmlFile) for event, node in events: print event, node.nodeName ### This has a sort of SAX-ish flavor: for every start tag, character data, and end tag, we get back a 2-tuple that makes up the "event" and the associated node. The node that we get back is mostly contentless, but at least we can look at the nodeName. We can do more, though --- we can tell the system that we'd like to expand a node so that we can get structural information from it. For example: ### from xml.dom import pulldom from StringIO import StringIO xmlFile = StringIO(xmlText) events = pulldom.parse(xmlFile) for event, node in events: if event == 'START_ELEMENT' and node.nodeName == 'COORDSET': events.expandNode(node) print node.toxml() print node.getElementsByTagName('END5')[0].childNodes print node.getElementsByTagName('END3')[0].childNodes ### Once we've expanded a node, we can start dealing with it with DOMish glee. *grin* The 'minidom' module and its discussion of the DOM applies pretty well on an "expanded" node: http://www.python.org/doc/current/lib/dom-node-objects.html http://www.python.org/doc/current/lib/dom-example.html The key to keeping memory usage down is to expand only the nodes that we're interested in. Instead of instantiating the whole tree at a time, we can be content to play with the subtrees that we're interested in. Please feel free to ask more questions about this. Good luck to you! From carroll at tjc.com Thu Dec 18 18:05:41 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 18 18:05:46 2003 Subject: [Tutor] buffering print statement In-Reply-To: Message-ID: Barnaby, after reading Alan'd reply, I think I missed what you wanted to do; you want a transparent way of having the print statement write to a buffer that can be printed out later, right? The two ideas from my last message (StringIO and saving/restoring sys.stdout) can do this for you: ============ import StringIO import sys print "first line to stdout" buf = StringIO.StringIO() #save stdout, and point stdout to StringIO buffer temp = sys.stdout sys.stdout = buf for i in range(1,11): print "Buffered line", i #these prints go to buf #restore stdout sys.stdout = temp print "second line to stdout" #now dump the StringIO print buf.getvalue() buf.close() ============ Run this, and you should see the "Buffered line" lines printed after the "second line to stdout" -- Terry Carroll Santa Clara, CA carroll@tjc.com From littledanehren at yahoo.com Thu Dec 18 18:26:36 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Dec 18 18:26:41 2003 Subject: [Tutor] PyWin Install problem In-Reply-To: <200312181119.12933.john@duartedailey.org> Message-ID: <20031218232636.76402.qmail@web41806.mail.yahoo.com> John Duarte wrote: > Dan, > Maybe my terminology is incorrect. > I am not installing a new version of Python. I am > just trying to install "Mark > Hammond's Python Extentions for Windows". I thought > these were also known as > 'PyWin'. My apologies if this is incorrect. > -John The webpage is confusing, but it actually comes with all of Python, or at least that's what happened when I installed it. I haven't used it in a while, so it might have changed. If it doesn't create a new installation of Python, then you should probably upgrade to 2.3.2 anyway. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From john at duartedailey.org Thu Dec 18 19:19:06 2003 From: john at duartedailey.org (John Duarte) Date: Thu Dec 18 19:21:36 2003 Subject: [Tutor] PyWin Install problem In-Reply-To: <20031218232608.63928.qmail@web41808.mail.yahoo.com> References: <20031218232608.63928.qmail@web41808.mail.yahoo.com> Message-ID: <200312181619.06529.john@duartedailey.org> Thanks, I upgraded Python, and the win32all extensions installed without a hitch. The extensions do not come with Python. -John On Thursday 18 December 2003 3:26 pm, you wrote: > John Duarte wrote: > > Dan, > > Maybe my terminology is incorrect. > > I am not installing a new version of Python. I am > > just trying to install "Mark > > Hammond's Python Extentions for Windows". I thought > > these were also known as > > 'PyWin'. My apologies if this is incorrect. > > -John > > The webpage is confusing, but it actually comes with > all of Python, or at least that's what happened when I > installed it. I haven't used it in a while, so it > might have changed. If it doesn't create a new > installation of Python, then you should probably > upgrade to 2.3.2 anyway. > > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ From the_investor at arach.net.au Thu Dec 18 19:52:00 2003 From: the_investor at arach.net.au (Ryan Sheehy) Date: Thu Dec 18 19:52:51 2003 Subject: [Tutor] Self In-Reply-To: Message-ID: Thanks Danny & Gregor! I think I am now beginning to understand. I don't know how to write it down in words, but yes I think I am beginning to get it. Thanks heaps, Ryan -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Friday, 19 December 2003 3:02 AM To: Ryan Sheehy Cc: Tutor Subject: RE: [Tutor] Self On Thu, 18 Dec 2003, Ryan Sheehy wrote: > If so, could the call 'Person.pat_head()' still give the same result in > the play_game method? Hi Ryan, This almost works. However, it's a requirement in Python that the first parameter in each method has to be 'self'. (I'm actually lying. *grin* That last statement was true until Python 2.2. I'll explain more fully in the bottom of this message.) Here's one reason for this constraint: if we allow a method that doesn't take 'self', it would mean that the 'method' doesn't care about its instance, and in that case, why is it even a method? *grin* Methods are really functions that are attached to an object. These methods are meant to care about the instance that they're attached to --- otherwise, it would be more approprate to just write a function. And in fact, with the original example: ### class Person: def pat_head(self): print "I'm patting my head" def rub_stomach(self): print "I'm rubbing my stomach" def play_game(self): self.pat_head() self.rub_stomach() ### it makes little sense for Person to be a class with those methods: it would be so much more simpler to just use functions: ### def pat_head(): print "I'm patting my head" def rub_stomach(): print "I'm rubbing my stomach" def play_game(): pat_head() rub_stomach() ### which is fine. So the example from before was actually a very bad one in terms of showing what objects are good for, since none of the methods actually did anything with 'self'. Let me augment the original example a bit more more: ### class Person: def __init__(self, name): self.name = name self.count_heads = 0 self.count_stomachs = 0 def summarize(self): print "I,", self.name, print "have patted my head", self.count_heads, "times", print "and rubbed my stomach", self.count_stomachs, "times." def pat_head(self): print "I,", self.name, "am patting my head" self.count_heads += 1 def rub_stomach(self): print "I,", self.name, "am rubbing my stomach" self.count_stomachs += 1 def play_game(self): self.pat_head() self.rub_stomach() ### Now these methods use 'self' as a way of sharing and remembering the status of the object --- we're using 'self' here as a place to store counts of things. It should be a little easier to see that passing 'self' around is useful now. Most classes will have methods that pay attention to the state that's stuffed in 'self' --- it's less common to have methods that totally disregard 'self'. Going back to your question: > If so, could the call 'Person.pat_head()' still give the same result in > the play_game method? The reason we mentioned this "almost" works is because in newer versions of Python, it actually is possible to do this, using "static methods". We can tell the system that, yes, we don't really need 'self' on certain methods, by marking them with 'staticmethod': ### class Person: def pat_head(): print "I'm patting my head" pat_head = staticmethod(pat_head) def rub_stomach(): print "I'm rubbing my stomach" rub_stomach = staticmethod(rub_stomach) def play_game(): Person.pat_head() Person.rub_stomach() play_game = staticmethod(play_game) ### And then it works. The details of this are defined in: http://python.org/2.2/descrintro.html#staticmethods I have to admit: I have this uncomfortable feeling about staticmethod(), and not just because it's a recent addition to the language. It just seems to me that allowing static methods adds little power to the language, and at the very high cost of complicating explanations like this one. *grin* Anyway, I hope this helps! --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003 From thomi at imail.net.nz Thu Dec 18 20:08:24 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Thu Dec 18 20:08:33 2003 Subject: [Tutor] confusion with dictionaries Message-ID: <200312191408.28061.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi guys, I was playing around with dictionaries, and came across something which I found rather... unexpected. here's a demonstration: >>> def foo(l = {}): ... l[random.choice(string.lowercase)] = random.random() ... return l ... >>> foo() {'m': 0.33204172040918167} >>> foo() {'m': 0.33204172040918167, 'l': 0.49843519723518959} >>> foo() {'u': 0.92434722065201858, 'm': 0.33204172040918167, 'l': 0.49843519723518959} >>> foo() {'u': 0.92434722065201858, 'm': 0.33204172040918167, 'l': 0.43003419699678858} >>> foo() {'u': 0.92434722065201858, 'z': 0.48421207726860993, 'm': 0.33204172040918167, 'l': 0.43003419699678858} I thought that if the dictionary 'l' was not stored in a variable outside the function it would be erased whenever the function foo() was terminated. This is very wierd... can anyone explain this? Furthermore, how can I ensure that a dictionary is clean when passing it as an optional argument to a function like this? Thanks, - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/4k+L2tSuYV7JfuERAmQpAJ4nSzARBW1IyVHQhU8/g132IKbLMgCgjNiZ 0c9MFtRUjplHvFl+dtkg70o= =S556 -----END PGP SIGNATURE----- From the_investor at arach.net.au Thu Dec 18 20:10:16 2003 From: the_investor at arach.net.au (Ryan Sheehy) Date: Thu Dec 18 20:11:03 2003 Subject: [Tutor] Returned values Message-ID: I am just wondering how you would know what a function returns when it is called. As an example, if I have code like so: >>> abc = 1 >>> xyz(abc) result of 'xyz' ... where 'xyz' is any function that can accept 'abc' (without errors), how will I know what type of value 'xyz' has returned (boolean? string? integer? float?), obviously I might be able to see what it has returned in IDLE, but what if I cannot (for whatever reason)? I hope my silly question makes sense. :o) Ryan --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003 From littledanehren at yahoo.com Thu Dec 18 20:46:40 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Dec 18 20:46:44 2003 Subject: [Tutor] Returned values In-Reply-To: Message-ID: <20031219014640.11044.qmail@web41812.mail.yahoo.com> Ryan Sheehy wrote: > I am just wondering how you would know what a > function returns when it is > called. > > As an example, if I have code like so: > > >>> abc = 1 > >>> xyz(abc) > result of 'xyz' > > ... where 'xyz' is any function that can accept > 'abc' (without errors), how > will I know what type of value 'xyz' has returned > (boolean? string? integer? > float?), obviously I might be able to see what it > has returned in IDLE, but > what if I cannot (for whatever reason)? > > I hope my silly question makes sense. :o) > > > Ryan Python is dynamically typed, so you usually shouldn't have to worry about types. But in general, you can tell the type of something just by what is returned by IDLE. When you just type something in to be evaluated, it really gives you repr(whatever_you_typed_in). The repr() function gives enough information to distinguish any thing from any other thing, so it will always have enough information to determine its type. Here are some distinguishing factors about different types: Ints: These numbers have no decimal point and no letters after them Floats: These have decimal points but no letters Longs: These have an L after them. Note that for almost anything, ints, floats, and longs are interchangable Strings: These have either single or double quotes around them. Lists: These have [brackets] around them Dicts: these have {curly:brackets} around them Functions: these start with and the second word is instance Modules: These start with , second word file Builtins: start with Message-ID: Hi Daniel, Thanks for your reply. It's just that I was wondering if there would ever be a case where I would type something in like so using xyz's output like so ... abc = 1 if xyz(abc) == 1: ...etc ... now if xyz's output was boolean or a string (or anything other than what I may have been expecting - i.e. 1) what would happen? This then brings me back to my original question - how would I know what the function returns so that I can create a proper conditional statement with it. Thanks heaps, Ryan -----Original Message----- From: tutor-bounces+the_investor=arach.net.au@python.org [mailto:tutor-bounces+the_investor=arach.net.au@python.org]On Behalf Of Daniel Ehrenberg Sent: Friday, 19 December 2003 9:47 AM To: pytutor Subject: Re: [Tutor] Returned values Ryan Sheehy wrote: > I am just wondering how you would know what a > function returns when it is > called. > > As an example, if I have code like so: > > >>> abc = 1 > >>> xyz(abc) > result of 'xyz' > > ... where 'xyz' is any function that can accept > 'abc' (without errors), how > will I know what type of value 'xyz' has returned > (boolean? string? integer? > float?), obviously I might be able to see what it > has returned in IDLE, but > what if I cannot (for whatever reason)? > > I hope my silly question makes sense. :o) > > > Ryan Python is dynamically typed, so you usually shouldn't have to worry about types. But in general, you can tell the type of something just by what is returned by IDLE. When you just type something in to be evaluated, it really gives you repr(whatever_you_typed_in). The repr() function gives enough information to distinguish any thing from any other thing, so it will always have enough information to determine its type. Here are some distinguishing factors about different types: Ints: These numbers have no decimal point and no letters after them Floats: These have decimal points but no letters Longs: These have an L after them. Note that for almost anything, ints, floats, and longs are interchangable Strings: These have either single or double quotes around them. Lists: These have [brackets] around them Dicts: these have {curly:brackets} around them Functions: these start with and the second word is instance Modules: These start with , second word file Builtins: start with >I was playing around with dictionaries, and came across something which I >found rather... unexpected. here's a demonstration: > >>>>def foo(l = {}): >... l[random.choice(string.lowercase)] = random.random() >... return l >>>>foo() >{'m': 0.33204172040918167} >>>>foo() >{'m': 0.33204172040918167, 'l': 0.49843519723518959} >I thought that if the dictionary 'l' was not stored in a variable outside >the >function it would be erased whenever the function foo() was terminated. > That is pretty much true. The trick is that the default values for parameters are evaluated only once -- when the function is created. And since the function itself still exists, the dictionary it uses for that default value has to be kept alive too. If you want a new dict with each call, try something like this: def foo(l=None): if l is None: l = {} I believe that is the standard python idiom. It's the one I use regularly, anyhow. _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From missive at hotmail.com Thu Dec 18 21:39:33 2003 From: missive at hotmail.com (Lee Harr) Date: Thu Dec 18 21:39:38 2003 Subject: [Tutor] Re: Returned values Message-ID: >I am just wondering how you would know what a function returns when it is >called. > >As an example, if I have code like so: > > >>> abc = 1 > >>> xyz(abc) > result of 'xyz' > It is an interesting question. I guess my response would be ... How did you find out about xyz in the first place? Normally when programming, you will use library or builtin functions and methods and you will discover how they work by reading the API (Application Programming Interface) -- (the documentation :o) If you are working from the python interactive interpreter, the help() function is quite helpful: help(xyz) should tell you something about it -- depending on what the person who wrote xyz put in the docstring.... >>>def bar(): ... "this does something" ... >>>help(bar) Help on function bar in module __main__: bar() this does something Not very helpful... >>>def foo(): ... "returns None" ... >>>help(foo) Help on function foo in module __main__: foo() returns None Better... _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From project5 at redrival.net Thu Dec 18 21:45:56 2003 From: project5 at redrival.net (Andrei) Date: Thu Dec 18 21:48:40 2003 Subject: [Tutor] Re: Returned values References: <20031219014640.11044.qmail@web41812.mail.yahoo.com> Message-ID: <1cx7hs1omt4fy$.19xzoi2kgk66z$.dlg@40tude.net> Ryan Sheehy wrote on Fri, 19 Dec 2003 10:05:51 +0800: > abc = 1 > if xyz(abc) == 1: > ...etc > > ... now if xyz's output was boolean or a string (or anything other than what > I may have been expecting - i.e. 1) what would happen? You can always try this kind of things out in the interpreter, it's one of the great strenghts of Python. If you do that, you'll find out that you can compare anything to anything. That means that if xyz doesn't return the integer 1, that "==" will evaluate to False (regardless of what type the result of xyz is). So your code as presented above would work just fine, regardless of the returns of xyz. You should also note that you can often do this: if xyz(abc): #something Then if xyz returns anything but 0, None, False, or empty dictionaries/sequences, it will be interpreted as True and #something is executed > This then brings me back to my original question - how would I know what the > function returns so that I can create a proper conditional statement with > it. I don't think you need to know the type, based on the info you gave. If you believe type matters in your case, explain what you need in more detail. Note that it is possible to get type info very easily using type(), it's just that in the overwhelming majority of the cases it really isn't necessary despite what you might think if coming from a statically typed language. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From the_investor at arach.net.au Thu Dec 18 21:56:47 2003 From: the_investor at arach.net.au (Ryan Sheehy) Date: Thu Dec 18 21:57:36 2003 Subject: [Tutor] Re: Returned values In-Reply-To: <1cx7hs1omt4fy$.19xzoi2kgk66z$.dlg@40tude.net> Message-ID: Thanks Lee and Andrei. I have done some basic programming in a software package where the help files contained info for a function and would be written as such: xyz(whatever_variable: integer); boolean ... where the 'whatever_variable' would need to be an integer and the function 'xyz' would return a boolean result. And I thought this would be the norm with any programming language! :o) I couldn't see these features in Python help files and was wondering how I would know what the result would be. I'm glad it can be done through the ways mentioned by all who responded... as I need to unwire my brain from my previous function encounter and at the moment this is the only way I can relate and understand Python. Thanks again, Ryan -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Andrei Sent: Friday, 19 December 2003 10:46 AM To: tutor@python.org Subject: [Tutor] Re: Returned values Ryan Sheehy wrote on Fri, 19 Dec 2003 10:05:51 +0800: > abc = 1 > if xyz(abc) == 1: > ...etc > > ... now if xyz's output was boolean or a string (or anything other than what > I may have been expecting - i.e. 1) what would happen? You can always try this kind of things out in the interpreter, it's one of the great strenghts of Python. If you do that, you'll find out that you can compare anything to anything. That means that if xyz doesn't return the integer 1, that "==" will evaluate to False (regardless of what type the result of xyz is). So your code as presented above would work just fine, regardless of the returns of xyz. You should also note that you can often do this: if xyz(abc): #something Then if xyz returns anything but 0, None, False, or empty dictionaries/sequences, it will be interpreted as True and #something is executed > This then brings me back to my original question - how would I know what the > function returns so that I can create a proper conditional statement with > it. I don't think you need to know the type, based on the info you gave. If you believe type matters in your case, explain what you need in more detail. Note that it is possible to get type info very easily using type(), it's just that in the overwhelming majority of the cases it really isn't necessary despite what you might think if coming from a statically typed language. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 11/12/2003 From Janssen at rz.uni-frankfurt.de Fri Dec 19 08:10:17 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Dec 19 08:10:31 2003 Subject: [Tutor] Re: Returned values In-Reply-To: References: Message-ID: On Fri, 19 Dec 2003, Ryan Sheehy wrote: > I have done some basic programming in a software package where the help > files contained info for a function and would be written as such: > > xyz(whatever_variable: integer); boolean > > ... where the 'whatever_variable' would need to be an integer and the > function 'xyz' would return a boolean result. And I thought this would be > the norm with any programming language! :o) > > I couldn't see these features in Python help files and was wondering how I > would know what the result would be. indeed the python documentation doesn't do much formal description (but should say in plain text what happens). When you want to get a description like "xyz(whatever_variable: integer); boolean" you must use the online help. For example: "help(int)" enters help-mode and shows the definition of the int-class (one might expect it shows the definition of the int *function* but int acts both as class and function (it's a special case)). Now the relevant output: """ Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer """ ---> voila! This online help is generated from docstrings (compare http://www.python.org/doc/essays/styleguide.html for docstrings). Since they are written within code they are more out of the view of a programmer. In case even the docstring doesn't reveal the type of the return value, you will take a look at the source and try to figure out, what it might return (this might be called "documentation by good-to-read syntax" ;-) Michael From sigurd at 12move.de Fri Dec 19 12:31:21 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Dec 19 12:32:13 2003 Subject: [Tutor] confusion with dictionaries In-Reply-To: <200312191408.28061.thomi@imail.net.nz> (Thomi Richards's message of "Fri, 19 Dec 2003 14:08:24 +1300") References: <200312191408.28061.thomi@imail.net.nz> Message-ID: On 19 Dec 2003, Thomi Richards <- thomi@imail.net.nz wrote: > I was playing around with dictionaries, and came across something which I > found rather... unexpected. here's a demonstration: >>>> def foo(l = {}): > ... l[random.choice(string.lowercase)] = random.random() > ... return l [...] > I thought that if the dictionary 'l' was not stored in a variable outside the > function it would be erased whenever the function foo() was terminated. No. Some days ago we had a thread here with exactly the same problem. Don't you read the list? I cite from the Python tutorial: ,----[ Python tutorial ] | *Important warning:* The default value is evaluated only once. This | makes a difference when the default is a mutable object such as a list, | dictionary, or instances of most classes. For example, the following | function accumulates the arguments passed to it on subsequent calls: | | def f(a, L=[]): | L.append(a) | return L | | print f(1) | print f(2) | print f(3) | | This will print | | [1] | [1, 2] | [1, 2, 3] | | If you don't want the default to be shared between subsequent calls, | you can write the function like this instead: | | def f(a, L=None): | if L is None: | L = [] | L.append(a) | return L `---- So what happens here is that your default value gets only once evaluated: the time you create the function. All further calls to the function which don't give the default value will use exactly the same dictionary: the one which was created the moment the function definition was evaluated. > This is very wierd... can anyone explain this? Furthermore, how can I ensure see above. > that a dictionary is clean when passing it as an optional argument to a > function like this? When you pass a dictionary the default one won't get used. So there's no problem. Or use the technique shown in the tutorial. Karl -- Please do *not* send copies of replies to me. I read the list From cybersamurai at terra.com.br Fri Dec 19 17:13:11 2003 From: cybersamurai at terra.com.br (Luiz Siqueira Neto) Date: Fri Dec 19 16:15:29 2003 Subject: [Tutor] I need speed-up !!!!!!!!!!!!! Message-ID: <3FE377F7.1000004@terra.com.br> I have a algorithm to make a XML document using as source a file with data like a memory layout, the algorithm work fine but get 100 MB of memory and is 18x more slow than the same algorithm using Delphi and MSXML. Yes, I know, is impossible have the same speed, but, if I have some like 20 MB of use and 6x more slow than MSXML I will be very happy. In fact if I have some a little bit more than I have now I will be happy too. :) I try python tips for speed-up but I have more memory use; I try psyco but don't work ( I don't know if the problem is my self); My idea is use this algorithm like a multplataform framework, if this is very hard or impossible maybe I need forgot the idea of use Python. :( From alan.gauld at blueyonder.co.uk Fri Dec 19 19:33:50 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Dec 19 19:35:42 2003 Subject: [Tutor] confusion with dictionaries References: <200312191408.28061.thomi@imail.net.nz> Message-ID: <00d601c3c690$f064bd30$6401a8c0@xp> > I was playing around with dictionaries, and came across > something which I found rather... unexpected. >>> def foo(l = {}): ... l[random.choice(string.lowercase)] = random.random() ... return l ... >>> foo() {'m': 0.33204172040918167} >>> foo() {'m': 0.33204172040918167, 'l': 0.49843519723518959} > I thought that if the dictionary 'l' was not stored in a > variable outside the function it would be erased whenever > the function foo() was terminated. This has nothing to do with dictionaries per se but rather is a feature of how Python evaluates default values of parameters. Basically the value is computed the first time and then reused - a useful feature for some things and exploited in several Python "tricks" Thus: def f(p=42): return p+7 f() -> 49 f(23) -> 30 f() -> 49 So far so good because 42 is immutable and so cannot be changed. def f(p=[]): p.append(42) return p[:] # a copy of p f() -> [42] f() -> [42,42] f([]) -> [42] f([23]) -> [23,42] f() -> [42,42,42] So the object used as default for p is kept(as was the 42) but this time we can change it because lists are mutable. Same with dictionaries and of course objects. class C: def __init__(self): self.data = [] def f(p = C()) p.data.append(42) return p.data f() -> [42] f(C()) -> [42] f() -> [42,42] c = C() c.data = [1,2,3] f(c) -> [1,2,3,42] So any mutable object used as a default value will stick around and can be modified. To get a fresh one each time you need to test for existence and overwrite it each time, or make the default None and create a new one each time - the latter seems the most common. Alan G. From alan.gauld at blueyonder.co.uk Fri Dec 19 19:41:31 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Dec 19 19:43:15 2003 Subject: [Tutor] Returned values References: Message-ID: <00db01c3c692$035b8440$6401a8c0@xp> > >>> abc = 1 > >>> xyz(abc) > result of 'xyz' > > ... where 'xyz' is any function that can accept 'abc' (without errors), how > will I know what type of value 'xyz' has returned You don't because some functions return different types depending on what they are passed as arguments. This is one of the features that makes dynamic languages like Python or Perl different from static ones like Java or C++ Consider: def double(aVal = 42): return aVal * 2 double() -> 42 double(123) -> 246 double(12.3) -> 24.6000000 double("foo") -> 'foofoo' double([1,2,3]) -> [1,2,3,1,2,3] double({1:2,3:4}) -> Oops error!, can't multiply dictionaries So the return value can be any type that supports multiplication and is passed as an argument. You can test the type of the return value but usually you try to write code that doesn't rely on the type. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ac007 at bluewin.ch Fri Dec 19 19:49:17 2003 From: ac007 at bluewin.ch (Alexandre) Date: Fri Dec 19 19:50:00 2003 Subject: [Tutor] confusion with dictionaries References: <200312191408.28061.thomi@imail.net.nz> Message-ID: <008301c3c693$1934d1d0$2101a8c0@Azbordation> >>> def foo(l = {}): ... l[random.choice(string.lowercase)] = random.random() ... return l ... >>> foo() {'m': 0.33204172040918167} >>> foo() {'m': 0.33204172040918167, 'l': 0.49843519723518959} >>> This is very wierd... can anyone explain this? Furthermore, how can I ensure >>> that a dictionary is clean when passing it as an optional argument to a >>> function like this? Hi Thomi, below a little extract from Python Tutorial : ************************************************************ Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) This will print [1] [1, 2] [1, 2, 3] If you don't want the default to be shared between subsequent calls, you can write the function like this instead: def f(a, L=None): if L is None: L = [] L.append(a) return L ************************************************************Hope that helps.Alexandre -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031220/f9e4cdda/attachment.html From alan.gauld at blueyonder.co.uk Fri Dec 19 19:49:29 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Dec 19 19:51:12 2003 Subject: [Tutor] Returned values References: Message-ID: <00e201c3c693$1fe26a10$6401a8c0@xp> > This then brings me back to my original question - how would I know what the > function returns so that I can create a proper conditional statement with > it. One of Pythons mottos is that its better to ask forgivness... So if in doubt 'try' and then handle the 'except'ion: foo = SomeSrangeFunction() try: anOperationOnFoo(foo) except TypeError: # handle the bad type scenario. In most cases anOperationOnFoo will just work, if it doesn't you decide how to handle it. That may include using an if/elif test chain to find out which of the possible incompatible types you have and dealing with it, but usually you do something like convert it to a string and then deal with the now known type... Or maybe just print an error message... Alan G. From littledanehren at yahoo.com Fri Dec 19 21:43:07 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Fri Dec 19 21:43:12 2003 Subject: [Tutor] Returned values In-Reply-To: <00db01c3c692$035b8440$6401a8c0@xp> Message-ID: <20031220024307.76963.qmail@web41808.mail.yahoo.com> --- Alan Gauld wrote: > > >>> abc = 1 > > >>> xyz(abc) > > result of 'xyz' > > > > ... where 'xyz' is any function that can accept > 'abc' (without > errors), how > > will I know what type of value 'xyz' has returned > > You don't because some functions return different > types depending > on what they are passed as arguments. This is one of > the features > that makes dynamic languages like Python or Perl > different from > static ones like Java or C++ > > Consider: > > def double(aVal = 42): > return aVal * 2 > > double() -> 42 > double(123) -> 246 > double(12.3) -> 24.6000000 > double("foo") -> 'foofoo' > double([1,2,3]) -> [1,2,3,1,2,3] > double({1:2,3:4}) -> Oops error!, can't multiply > dictionaries > > So the return value can be any type that supports > multiplication > and is passed as an argument. > > You can test the type of the return value but > usually you try > to write code that doesn't rely on the type. > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld Are you sure double() (with no arguments) would return 42? I got 84. __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From littledanehren at yahoo.com Fri Dec 19 22:16:20 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Fri Dec 19 22:16:25 2003 Subject: [Tutor] I need speed-up !!!!!!!!!!!!! In-Reply-To: <3FE377F7.1000004@terra.com.br> Message-ID: <20031220031620.72301.qmail@web41804.mail.yahoo.com> Luiz Siqueira Neto wrote: > I have a algorithm to make a XML document using as > source > a file with data like a memory layout, the algorithm > work fine > but get 100 MB of memory and is 18x more slow than > the same > algorithm using Delphi and MSXML. > Yes, I know, is impossible have the same speed, but, > if I have some > like 20 MB of use and 6x more slow than MSXML I will > be very happy. > In fact if I have some a little bit more than I have > now I will be happy > too. :) > > I try python tips for speed-up but I have more > memory use; > I try psyco but don't work ( I don't know if the > problem is my self); > > My idea is use this algorithm like a multplataform > framework, if this > is very hard or impossible maybe I need forgot the > idea of use Python. :( In this type of situation, most people write a C or C++ extention. However, it seems like that won't work in your case. Try switching to a lower level algorithm instead, such as nested lists with string manipulation. That won't require an XML library, eliminating a layer of processing. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From tony at tcapp.com Sat Dec 20 02:41:02 2003 From: tony at tcapp.com (Tony Cappellini) Date: Sat Dec 20 02:41:20 2003 Subject: [Tutor] strange path entry in sys.path Message-ID: <6.0.0.22.0.20031219231244.01e966d0@smtp.sbcglobal.net> Can anyone tell me why a zip file, which is not even on my system, show up in sys.path ? I have not manually modified sys.path, nor the path variable through the environment. This happened on 2 different physical computers, with different OS's: one is WIn98 and the other is Win XP, both with Python 2.3, WIn32all 1.63 >>> import sys >>> print sys.path ['', 'C:\\WINDOWS\\System32\\python23.zip', 'C:\\Python23\\lib\\site-packages\\Pythonwin', 'C:\\Python23\\lib\\site-packages\\win32', 'C:\\Python23\\lib\\site-packages\\win32\\lib', 'C:\\Python23\\lib\\site-packages', 'C:\\Python23\\DLLs', 'C:\\Python23\\lib', 'C:\\Python23\\lib\\plat-win', 'C:\\Python23\\lib\\lib-tk', 'C:\\Python23'] thanks Tony From carroll at tjc.com Sat Dec 20 04:07:05 2003 From: carroll at tjc.com (Terry Carroll) Date: Sat Dec 20 04:07:13 2003 Subject: [Tutor] strange path entry in sys.path In-Reply-To: <6.0.0.22.0.20031219231244.01e966d0@smtp.sbcglobal.net> Message-ID: On Fri, 19 Dec 2003, Tony Cappellini wrote: > Can anyone tell me why a zip file, which is not even on my system, show up > in sys.path ? > I have not manually modified sys.path, nor the path variable through the > environment. It's new in 2.3. If the file isn't there, it won't be searched, but this is a way to make it available. http://www.python.org/doc/2.3/whatsnew/node5.html http://www.python.org/peps/pep-0273.html (PEP 302 makes it show up in sys.path, even if it doesn't exist.) -- Terry Carroll Santa Clara, CA carroll@tjc.com From dyoo at hkn.eecs.berkeley.edu Fri Dec 19 19:20:13 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 20 09:59:35 2003 Subject: [Tutor] I need speed-up [Generating XML with XMLGenerator] In-Reply-To: <3FE377F7.1000004@terra.com.br> Message-ID: On Fri, 19 Dec 2003, Luiz Siqueira Neto wrote: > I have a algorithm to make a XML document using as source a file with > data like a memory layout, the algorithm work fine but get 100 MB of > memory and is 18x more slow than the same algorithm using Delphi and > MSXML. Hi Luiz, What is your algorithm? How are you measuring performance? Show us what code you're using to generate things, and we can probably point out a few things to help speed the code up. If you're trying to generate XML, you may want to look at the XMLGenerator class in the xml.sax.saxutils package: http://python.org/doc/lib/module-xml.sax.saxutils.html (Just wondering: is anyone else having difficulty reaching Python.org, or is it just me?) Anyway, XmlGenerator is designed to help us generate XML files, and it should be very resource efficient. Furthermore, it does proper XML quoting of character data. Here's a small example: ### """A small example of XMLGenerator.""" from xml.sax.saxutils import XMLGenerator from StringIO import StringIO f = StringIO() g = XMLGenerator(f) g.startElement("FOOBAR", {}) g.characters("this is a <>\n") g.endElement("FOOBAR") print f.getvalue() ### Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Dec 19 15:11:27 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 20 10:00:05 2003 Subject: [Tutor] Re: Returned values In-Reply-To: Message-ID: On Fri, 19 Dec 2003, Ryan Sheehy wrote: > I have done some basic programming in a software package where the help > files contained info for a function and would be written as such: > > xyz(whatever_variable: integer); boolean > > ... where the 'whatever_variable' would need to be an integer and the > function 'xyz' would return a boolean result. And I thought this would > be the norm with any programming language! :o) Hi Ryan, One big difference between Python and the languages you have previous epxerience may be this: Python depends more on the conventions of programmers than on restrictions imposed by the language itself. Python itself doesn't really say anything about the domains and ranges of functions --- often, it's more the role of the documentation to say such things. If the documentation isn't clear about what a function can take in, then that's a bug in the docs that needs to be fixed. *grin* > I couldn't see these features in Python help files and was wondering how > I would know what the result would be. The role of types in Python is a bit more fluid than in other languages. For example, multiplication between strings and numbers is perfectly valid: ### >>> "hello" * 3 'hellohellohello' ### and if we define a function called mul(): ### >>> def mul(x, y): ... return x * y ... >>> mul ### that's as much as Python can tell us at this point, that 'mul' is a function, but it actually has no idea what types 'x' and 'y' might be. ### >>> mul(3, 4) 12 >>> mul(0+1j, 0-1j) (1+0j) >>> mul('hello', 3) 'hellohellohello' ### So one function, like mul(), might take in many different kinds of things. The most we can say here is that 'mul()' is a function that takes two arguments 'x', and 'y', and as long as 'x' and 'y' support the multiplication operator, the function returns a good value. There is still type checking going on, but it's all dynamic: ### >>> mul('hello', 'world') Traceback (most recent call last): File "", line 1, in ? File "", line 2, in mul TypeError: unsupported operand type(s) for *: 'str' and 'str' ### So type errors do get caught, but at runtime. Type information are attached to Python values, not operators, so it's a little more difficult to pin down the exact types that a function will accept, since we can define whole new types that implement acceptable behavior. Strangely enough the lack of static type checking doesn't seem to be too bad! Most type errors can be corrected by just running the program run once, or by exercising the code with unit testing. Instead of focusing on specific types, it's easier to define the kind of 'contract' or 'interface' that the arguments should support. The Python documentation tries to follow this approach. For example, there are quite a few places where the documentation will refer to a "file-like object", because there are several types in Python that support file-like operations like read(). As a concrete example, xml.dom.pulldom.parse() takes in a file-like object to parse out XML files, and, by design, it doesn't restrict the input type to disk files. This is very nice because we can send it file-like objects from the network using urllib.urlopen(), or zipped archives with gzip.open(), and it all works out beautifully. Hope this helps! From amonroe at columbus.rr.com Sat Dec 20 10:59:23 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Dec 20 10:49:23 2003 Subject: [Tutor] Has anyone already done a python parser for the IMDB datafiles? Message-ID: <47749360313.20031220105923@columbus.rr.com> I recently discovered their data files are available for download: ftp://ftp.fu-berlin.de/pub/misc/movies/database/ But they're not (I was VERY surprised to find) in any kind of well-defined format. It looks like someone basically typed them into a text editor. Just glancing at it, it looks like: actor 1 movie 1 (year) (media) [role] movie 2 (year) [role] movie 3 etc. actor 2 movie 1 movie 2 movie 3 The fields after the movie appear to be optional, there may be others I overlooked. I didn't get any matches on Parnassus or Uselesspython, searching for "imdb". Probably wouldn't be too hard to cobble something together, but maybe it's already been done somewhere? Alan From trohland at absamail.co.za Sat Dec 20 11:23:30 2003 From: trohland at absamail.co.za (Tyron Rohland) Date: Sat Dec 20 11:27:27 2003 Subject: [Tutor] (no subject) Message-ID: Hello everyone I am new to programming all together. I downloaded Python and I am trying it out. When I have the >>> I follow the tutorial and everything works perfectly except when I ask the user to input something. How do I code the whole program then run it? I am using Windows 2000 Prof. Thanks for your time Tyron From tbstep at tampabay.rr.com Sat Dec 20 14:04:09 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Sat Dec 20 11:52:05 2003 Subject: [Tutor] I need speed-up [Generating XML with XMLGenerator] In-Reply-To: References: Message-ID: <3FE49D29.4050506@tampabay.rr.com> Danny Yoo wrote: > > http://python.org/doc/lib/module-xml.sax.saxutils.html > > (Just wondering: is anyone else having difficulty reaching Python.org, or > is it just me?) > As of 11 am EST 12/20/03, I can't reach it at all. From littledanehren at yahoo.com Sat Dec 20 12:45:37 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 20 12:45:46 2003 Subject: [Tutor] trouble with pygtk and different users Message-ID: <20031220174537.43407.qmail@web41801.mail.yahoo.com> In trying to learn PyGTK, I wrote a simple launcher program to make it easier to run things as root. It is attached. There's a label at the top that should say that you should click on one of the following buttons to run them as root (or whatever user it is run under, the point is that you only have to type the password once). Then there are buttons to get to various programs and a quit button. It works some, but there are some problems. The label, instead of saying which user owns the process, says which user is actually logged in. This is very confusing behavior. I think it's Linux's fault, but I still don't know how to fix it. When a program is launched from it, the GUI (of my Python script) freezes. Nothing can be done from it and if any other windows go over it, it is not updated. This isn't because Python is waiting for the program to finish; if I use PyShell to so os.system('nautilus'), it launches nautilus and returns 0, then there's the next command prompt. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ -------------- next part -------------- A non-text attachment was scrubbed... Name: gtkstuff.py Type: application/octet-stream Size: 1934 bytes Desc: gtkstuff.py Url : http://mail.python.org/pipermail/tutor/attachments/20031220/36913300/gtkstuff.obj From littledanehren at yahoo.com Sat Dec 20 14:47:15 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 20 14:47:23 2003 Subject: [Tutor] Returned values In-Reply-To: Message-ID: <20031220194715.25138.qmail@web41811.mail.yahoo.com> Ryan Sheehy wrote: > Hi Daniel, > > Thanks for your reply. > > It's just that I was wondering if there would ever > be a case where I would > type something in like so using xyz's output like so > ... > > abc = 1 > if xyz(abc) == 1: > ...etc > > ... now if xyz's output was boolean or a string (or > anything other than what > I may have been expecting - i.e. 1) what would > happen? > > This then brings me back to my original question - > how would I know what the > function returns so that I can create a proper > conditional statement with > it. > > Thanks heaps, > > > Ryan Generally, things must be of the same type to return True for an equality test. However, as I stated before, the distinction between integers and floats is weak, so if you test 1 == 1.0, it will return True. Here are some equality examples. >>> 1==1L True >>> [1, 2] == (1, 2) False >>> u'a' == 'a' #u'a' is unicode True >>> 1, 2 == (1, 2) #comma has higher precedence than == (1, True) >>> '1' == 1 False >>> [1] == 1 False >>> (1,) == 1 False >>> ['1', '2'] == '12' False I hope you can figure what's happening there; Python's system for testing equality is fairly complicated. The equality system in Python is less strict than in most other languages (like C) but less strict than in weakly-typed languages (like Visual Basic). There is a different operator called 'is' to test out if things are exactly the same (by checking their ids), but it requires that things must be the same instance of stuff. For example, [1, 2] is [1, 2] would return False, but x = [1, 2] ; y = x ; x is y would return True because x and y are refering to the same thing. It all has to do with Python's linking model for variables; it's very complicated. Here are some examples of the usage of is: >>> 1 is 1 True >>> [1] is [1] False >>> def test(): pass ... >>> test() is None #this is an idiom; if a function doesn't return anything, it returns None True >>> 'a' is 'a' True >>> u'a' is 'a' False >>> (1,) is (1,) False >>> 1 is 1.0 False >>> 1 is 1L False Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From fleming.j at comcast.net Sat Dec 20 14:59:28 2003 From: fleming.j at comcast.net (john fleming) Date: Sat Dec 20 14:59:35 2003 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <3FE4AA20.5010602@comcast.net> Tyron Rohland wrote: >Hello everyone > >I am new to programming all together. I downloaded Python and I am trying it >out. When I have the >>> I follow the tutorial and everything works >perfectly except when I ask the user to input something. How do I code the >whole program then run it? I am using Windows 2000 Prof. > >Thanks for your time >Tyron > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > In order to code a whole program before running you write a python script. Open up a text editor, (word pad or notepad in windows), type in your code , hitting enter at each line. Then save the file as "ProgramName.py", select Save as type: text document. Then double click on the snake icon that has your programs name on it. I prefer to open up a command window and cd to the directory the file was saved in and run: python ProgramName. That way if something is not right to the point the program wont run, I get feedback about why (more often then not anyway). Have fun! John F. From missive at hotmail.com Fri Dec 19 18:50:21 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Dec 20 15:09:00 2003 Subject: [Tutor] Re: I need speed-up !!!!!!!!!!!!! Message-ID: >I have a algorithm to make a XML document using as source >a file with data like a memory layout, the algorithm work fine >but get 100 MB of memory and is 18x more slow than the same >algorithm using Delphi and MSXML. >Yes, I know, is impossible have the same speed, but, if I have some >like 20 MB of use and 6x more slow than MSXML I will be very happy. >In fact if I have some a little bit more than I have now I will be happy >too. :) > >I try python tips for speed-up but I have more memory use; >I try psyco but don't work ( I don't know if the problem is my self); > >My idea is use this algorithm like a multplataform framework, if this >is very hard or impossible maybe I need forgot the idea of use Python. :( > I recommend asking this question on the main python mailing list. When you post there, use a subject along the lines of "Speeding up xml processing" with no exclamation points. Also, put in details about exactly which method you are using (especially, which exact xml library you are using, as I know there are several) There is probably also an xml-specific mailing list. _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From alan.gauld at blueyonder.co.uk Sat Dec 20 15:53:09 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 20 15:54:53 2003 Subject: [Tutor] (no subject) References: Message-ID: <000e01c3c73b$46a60870$6401a8c0@xp> > perfectly except when I ask the user to input something. How do I code the > whole program then run it? I am using Windows 2000 Prof. Just type it into a text file, using IDLE(File->New) or even Notepad. Make sure you save it with a file ending in .py and you can then run it from within IDLE or by double clicking on it in Explorer. You may need to add something like raw_input("Hit ENTER to quit...") as a last line to stop it closing before you see the results. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From carroll at tjc.com Sat Dec 20 16:32:37 2003 From: carroll at tjc.com (Terry Carroll) Date: Sat Dec 20 16:32:43 2003 Subject: [Tutor] Has anyone already done a python parser for the IMDB datafiles? In-Reply-To: <47749360313.20031220105923@columbus.rr.com> Message-ID: On Sat, 20 Dec 2003, R. Alan Monroe wrote: > I recently discovered their data files are available for download: > ftp://ftp.fu-berlin.de/pub/misc/movies/database/ I use XMLTV, a Perl program that downloads TV schedules and converts them to XML, and then optionally merges in the IMDB data. You might want to take a look at the IMDB logic (even though it's Perl) to get a better idea of the IMDB data format. The IDMB processing is nominally done in the tv_imdb script, but the guts of it seems to be in the XMLTV::IMDB module (IMDB.pm). XMLTV lives at and . -- Terry Carroll Santa Clara, CA carroll@tjc.com From thomi at imail.net.nz Sat Dec 20 16:50:10 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Dec 20 16:50:18 2003 Subject: [Tutor] confusion with dictionaries In-Reply-To: References: <200312191408.28061.thomi@imail.net.nz> Message-ID: <200312211050.10700.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > > So what happens here is that your default value gets only once > evaluated: the time you create the function. All further calls to the > function which don't give the default value will use exactly the same > dictionary: the one which was created the moment the function definition > was evaluated. > OK, that's....wierd, but I can handle it ;) I'm trying to learn C/ Lua/ Python, and Delphi all at the same time, sometimes I get a little confused between them. (It's not uncommon to see me trying to put semi colons at the end of my python statements). Anyway, thanks a lot for this; It's made it much clearer to me... - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/5MQS2tSuYV7JfuERAtYuAJwJYnMGcf7Qi49hj6TNXexnjdaxQwCfVTkv N9nHQZhodVxhAPM0kBHIntg= =M/HR -----END PGP SIGNATURE----- From hcohen2 at comcast.net Sat Dec 20 17:52:47 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 20 17:53:17 2003 Subject: [Tutor] Why has this syntax with multiple arguments ceased to work for the print command? Message-ID: <3FE4D2BF.4080801@comcast.net> I am certain code like this ran for me without any problem: print 'You are: %s? and It is the %dth of Dec.' % esp, int(cnt) both esp are gathered by ... = raw_input('Enter ...') and each works properly as a single argument in test strings. Now I get: Traceback (most recent call last): File "", line 1, in ? TypeError: not enough arguments for format string I tried to study the documentation on the print statement, but the syntax for the argument list left me confused. [How about some examples in the documentation?] It appears that the syntax has altered from what was working on version 2.0.x. I am running this under Mandrake Linux 9.1 using version 2.2.2. Where am I going wrong? Thanks From glingl at aon.at Sat Dec 20 18:16:13 2003 From: glingl at aon.at (Gregor Lingl) Date: Sat Dec 20 18:15:17 2003 Subject: [Tutor] Why has this syntax with multiple arguments ceased to work for the print command? In-Reply-To: <3FE4D2BF.4080801@comcast.net> References: <3FE4D2BF.4080801@comcast.net> Message-ID: <3FE4D83D.3040606@aon.at> hcohen2 schrieb: > I am certain code like this ran for me without any problem: > > print 'You are: %s? and It is the %dth of Dec.' % esp, int(cnt) > > both esp are gathered by ... = raw_input('Enter ...') and each works > properly as a single argument in test strings. > > Now I get: > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: not enough arguments for format string You simply forgot to put your arguments between parentheses (to form a tuple): >>> esp = "you" >>> cnt = 20 >>> print 'You are: %s? and It is the %dth of Dec.' % esp, int(cnt) Traceback (most recent call last): File "", line 1, in -toplevel- print 'You are: %s? and It is the %dth of Dec.' % esp, int(cnt) TypeError: not enough arguments for format string >>> print 'You are: %s? and It is the %dth of Dec.' % (esp, int(cnt)) You are: you? and It is the 20th of Dec. >>> HTH, Gregor P.S. It's not a matter of the print statement but of the %-Operator and operator precedence. I. e. your statement is interpreted as: print ('You are: %s? and It is the %dth of Dec.' % esp), int(cnt) instead of print 'You are: %s? and It is the %dth of Dec.' % (esp, int(cnt)) > From carroll at tjc.com Sat Dec 20 18:25:59 2003 From: carroll at tjc.com (Terry Carroll) Date: Sat Dec 20 18:26:03 2003 Subject: [Tutor] Why has this syntax with multiple arguments ceased to work for the print command? In-Reply-To: <3FE4D2BF.4080801@comcast.net> Message-ID: On Sat, 20 Dec 2003, hcohen2 wrote: > I am certain code like this ran for me without any problem: > > print 'You are: %s? and It is the %dth of Dec.' % esp, int(cnt) There should be *one* argument on each side of the "%"; although the rightmost one can be a tuple that contains two elements. Try, instead: print 'You are: %s? and It is the %dth of Dec.' % (esp, int(cnt)) > It appears that the syntax has altered from what was working on version > 2.0.x. I don't think so; the first fails with the same error for me on Pythons 1.5.2, 2.2.2 and 2.3.3; and the second works correctly on all three. -- Terry Carroll Santa Clara, CA carroll@tjc.com From trohland at absamail.co.za Sat Dec 20 18:28:53 2003 From: trohland at absamail.co.za (Tyron Rohland) Date: Sat Dec 20 18:32:28 2003 Subject: [Tutor] Beginner ... Message-ID: <001301c3c751$088d1d10$274827c4@cider> Running: win 2000 prof I was told to use a text editor such as notepad to create a program for use with Python. I write the little program i.e >>> the_world_is_flat = 1 >>> if the_world_is_flat: ... print "Be careful not to fall off!" ... Be careful not to fall off!save it as test.pyThen i go onto the ' IDLE (Python GUI), choose open and is opened in another window. I choose run and it gives me 'invalid syntax.As I am a beginner please feel free to give me pointers and please try not to use such technical language.Thank you. Your help is most appreciated.Tyron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031221/ef4f6874/attachment-0001.html From missive at hotmail.com Sat Dec 20 19:07:59 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Dec 20 19:08:03 2003 Subject: [Tutor] Re: trouble with pygtk and different users Message-ID: >The label, instead of saying which user owns the >process, says which user is actually logged in. This >is very confusing behavior. I think it's Linux's >fault, but I still don't know how to fix it. > label = gtk.Label('Choose a program to run as %s' % os.getenv('USERNAME')) On my system (FreeBSD) there is a USER env variable, but no USERNAME Make sure you do su - and not just su Are you allowing other users to connect to your x-server (xhost +) Be very careful any time you run things as root (especially running things automatically from a script) _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From missive at hotmail.com Sat Dec 20 19:13:01 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Dec 20 19:13:06 2003 Subject: [Tutor] Re: Beginner ... Message-ID: >I was told to use a text editor such as notepad to create a program for = >use with Python. I write the little program=20 >i.e >>>>the_world_is_flat =3D 1 >>>>if the_world_is_flat: >... print "Be careful not to fall off!" >...=20 >Be careful not to fall off! Hard to tell here what exactly you have saved to test.py Be sure not to include the >>> characters in your script. Your file should just have: the_world_is_flat = 1 if the_world_is_flat: print "Be careful not to fall off!" _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From trohland at absamail.co.za Sat Dec 20 19:19:16 2003 From: trohland at absamail.co.za (Tyron Rohland) Date: Sat Dec 20 19:23:11 2003 Subject: [Tutor] (no subject) Message-ID: <000e01c3c758$1ec6cb60$864b27c4@cider> Sorry about writing that rubbish, I was in a rush. Thank you for the start off Lee Harr. Thanks Tyron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031221/5b133ac1/attachment.html From alan.gauld at blueyonder.co.uk Sat Dec 20 19:32:29 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 20 19:34:10 2003 Subject: [Tutor] Why has this syntax with multiple arguments ceased towork for the print command? References: <3FE4D2BF.4080801@comcast.net> <3FE4D83D.3040606@aon.at> Message-ID: <003201c3c759$eab17120$6401a8c0@xp> > You simply forgot to put your arguments between parentheses > (to form a tuple): > > >>> print 'You are: %s? and It is the %dth of Dec.' % (esp, int(cnt)) > You are: you? and It is the 20th of Dec. > >>> > P.S. It's not a matter of the print statement but of the %-Operator and > operator precedence. I. e. your statement is interpreted as: > > print ('You are: %s? and It is the %dth of Dec.' % esp), int(cnt) > > instead of > > print 'You are: %s? and It is the %dth of Dec.' % (esp, int(cnt)) And just to add the point that the parens aren't needed (although recoommended) if you didn't use the print statement, that is: s = 'You are: %s? and It is the %dth of Dec.' % esp, int(cnt) print s would also work. It's just the fact that the comma acts as a separator within the print statement that causes Python to get confused and require the parens. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sat Dec 20 19:35:04 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 20 19:36:45 2003 Subject: [Tutor] Beginner ... References: <001301c3c751$088d1d10$274827c4@cider> Message-ID: <003c01c3c75a$46f37410$6401a8c0@xp> >>> the_world_is_flat = 1 >>> if the_world_is_flat: ... print "Be careful not to fall off!" Close, but the >>> and ... bits are produced by the Python interactive interpreter. The program itself looks like this: the_world_is_flat = 1 if the_world_is_flat: print "Be careful not to fall off!" So thats all you need to type into your .py file HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From littledanehren at yahoo.com Sat Dec 20 20:36:07 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Dec 20 20:36:11 2003 Subject: [Tutor] Re: trouble with pygtk and different users In-Reply-To: Message-ID: <20031221013607.82656.qmail@web41803.mail.yahoo.com> Lee Harr wrote: > label = gtk.Label('Choose a program to run as %s' % > os.getenv('USERNAME')) > > That's exactly what I have. > > On my system (FreeBSD) there is a USER env variable, > but no USERNAME > Make sure you do su - and not just su > Are you allowing other users to connect to your > x-server (xhost +) > Be very careful any time you run things as root > (especially running > things automatically from a script) su and not just su?Since this program was created solely as a GUI (everything could be easily done from the command line), I use gksu (GNOME's GUI to su) instead, but when I tested it, su had the same problem. I found that the HOME environment variable did change with su/gksu, so I'll try to work something out with that, but there should be a better way. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From hcohen2 at comcast.net Sat Dec 20 21:38:35 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 20 21:39:04 2003 Subject: [Tutor] Why has this syntax with multiple arguments ceased towork for the print command? In-Reply-To: <003201c3c759$eab17120$6401a8c0@xp> References: <3FE4D2BF.4080801@comcast.net> <3FE4D83D.3040606@aon.at> <003201c3c759$eab17120$6401a8c0@xp> Message-ID: <3FE507AB.7030004@comcast.net> Alan Gauld wrote: >>You simply forgot to put your arguments between parentheses >>(to form a tuple): >> >> >>> print 'You are: %s? and It is the %dth of Dec.' % (esp, >> >> >int(cnt)) > > >>You are: you? and It is the 20th of Dec. >> >>> >>P.S. It's not a matter of the print statement but of the >> >> >%-Operator and > > >>operator precedence. I. e. your statement is interpreted as: >> >>print ('You are: %s? and It is the %dth of Dec.' % esp), >> >> >int(cnt) > > >>instead of >> >>print 'You are: %s? and It is the %dth of Dec.' % (esp, >> >> >int(cnt)) > >And just to add the point that the parens aren't needed (although >recoommended) >if you didn't use the print statement, that is: > >s = 'You are: %s? and It is the %dth of Dec.' % esp, int(cnt) >print s > >would also work. It's just the fact that the comma acts as a >separator >within the print statement that causes Python to get confused and >require the parens. > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > > > > I just would like to thank everyone for their quick and knowledgeable replies. I look forward to the time when I can reciprocate by answering questions posed on this forum. From klappnase at freenet.de Sat Dec 20 21:29:46 2003 From: klappnase at freenet.de (Michael Lange) Date: Sat Dec 20 21:41:30 2003 Subject: [Tutor] trouble with pygtk and different users In-Reply-To: <20031220174537.43407.qmail@web41801.mail.yahoo.com> References: <20031220174537.43407.qmail@web41801.mail.yahoo.com> Message-ID: <20031221032946.71303485.klappnase@freenet.de> On Sat, 20 Dec 2003 09:45:37 -0800 (PST) Daniel Ehrenberg wrote: > In trying to learn PyGTK, I wrote a simple launcher > program to make it easier to run things as root. It is > attached. There's a label at the top that should say > that you should click on one of the following buttons > to run them as root (or whatever user it is run under, > the point is that you only have to type the password > once). Then there are buttons to get to various > programs and a quit button. It works some, but there > are some problems. > > The label, instead of saying which user owns the > process, says which user is actually logged in. This > is very confusing behavior. I think it's Linux's > fault, but I still don't know how to fix it. > I can guess here: On my box I have no USERNAME variable at all if I am logged in as a normal user. As root USERNAME is root. So maybe on your box it is vice versa, then you open a console and USERNAME is set to "daniel" or whatever, then you su and USERNAME stays "daniel" because for root there is nothing specified to overwrite this. This happens when I su to root first and then su to "pingu": [pingu@localhost pingu]$ echo $USERNAME [pingu@localhost pingu]$ su Password: [root@localhost pingu]# echo $USERNAME root [root@localhost pingu]# su pingu [pingu@localhost pingu]$ echo $USERNAME root [pingu@localhost pingu]$ Maybe you just need to add: USERNAME="root" export USERNAME to /root/.bashrc > When a program is launched from it, the GUI (of my > Python script) freezes. Nothing can be done from it > and if any other windows go over it, it is not > updated. This isn't because Python is waiting for the > program to finish; if I use PyShell to so > os.system('nautilus'), it launches nautilus and > returns 0, then there's the next command prompt. I have never seen this behavior, my python shell freezes just like your app. Use "nautilus &" instead. Cheers (and a nice christmas) Michael From missive at hotmail.com Sun Dec 21 08:24:16 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Dec 21 08:24:23 2003 Subject: [Tutor] Re: trouble with pygtk and different users Message-ID: > > On my system (FreeBSD) there is a USER env variable, > > but no USERNAME > > Make sure you do su - and not just su > > Are you allowing other users to connect to your > > x-server (xhost +) > > Be very careful any time you run things as root > > (especially running > > things automatically from a script) > >su and not just su? Sorry, there was no punctuation on that line... su - and not su (From the su man page ... -l Simulate a full login. The environment is discarded except for HOME, SHELL, PATH, TERM, and USER. HOME and SHELL are modified as above. USER is set to the target login. - (no letter) The same as -l. ) >Since this program was created >solely as a GUI (everything could be easily done from >the command line), I use gksu (GNOME's GUI to su) >instead, but when I tested it, su had the same >problem. I found that the HOME environment variable >did change with su/gksu, so I'll try to work something >out with that, but there should be a better way. > It may be that (typical of linux/unix) the commandline version of su has more features available than the gui version. I also liked the suggestion to use os.system('command &') and see if that makes a difference... _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From david at graniteweb.com Sun Dec 21 10:00:36 2003 From: david at graniteweb.com (David Rock) Date: Sun Dec 21 10:05:45 2003 Subject: [Tutor] I need speed-up [Generating XML with XMLGenerator] In-Reply-To: <3FE49D29.4050506@tampabay.rr.com> References: <3FE49D29.4050506@tampabay.rr.com> Message-ID: <20031221150036.GC9695@wdfs.graniteweb.com> * Todd Stephens [2003-12-20 11:04]: > Danny Yoo wrote: > > > > > http://python.org/doc/lib/module-xml.sax.saxutils.html > > > >(Just wondering: is anyone else having difficulty reaching Python.org, or > >is it just me?) > > > > As of 11 am EST 12/20/03, I can't reach it at all. There was an anouncement on the Python Announce mailing list explaining a problem with the transfer of the domain from CNRI to PSF. An error in the DNS information got propogated. It has been fixed, but the fix is taking time to propogate. -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031221/72474a62/attachment.bin From python at keep-trying.com Sun Dec 21 11:18:17 2003 From: python at keep-trying.com (richard) Date: Sun Dec 21 11:19:04 2003 Subject: [Tutor] Help with AppendText Syntax Message-ID: <6.0.0.22.0.20031221160207.01ba3168@192.168.5.1> Greetings, The script below is adapted from one of the wxpython examples. What I wish to do is when the SQL button is pressed it puts some text retrieved from a database field in the "tester" wxTextCtrl along similar lines as the "button" does with the "logger" wxTextCtrl. My problem is how do I pass the variable "field1" to the Appendtext Control. The best I keep getting is the "field1" variable does not exist in Form1 Any help appreciated. (I have it working under Tkinter so the connection is OK) Best Regards Richard ====Script Begins ====> from wxPython.wx import * from pyPgSQL import PgSQL # set some strings dbname = 'dbname' dbhost = 'host' dbuser = 'user' dbpass = 'password' class Form1(wxPanel): def __init__(self, parent, id): wxPanel.__init__(self, parent, id) self.quote = wxStaticText(self, -1, "Your quote :",wxPoint(20, 30)) self.logger = wxTextCtrl(self,5, "",wxPoint(20,70), wxSize(100,200),wxTE_MULTILINE | wxTE_READONLY) self.tester = wxTextCtrl(self,6, "",wxPoint(150,70), wxSize(100,200),wxTE_MULTILINE | wxTE_READONLY) self.button =wxButton(self, 10, "Save", wxPoint(100, 30)) EVT_BUTTON(self, 10, self.OnClick) self.close =wxButton(self, 11, "Close", wxPoint(180, 30)) EVT_BUTTON(self, 11, self.Close) self.sql =wxButton(self, 12, "SQL", wxPoint(180, 10)) EVT_BUTTON(self, 12, self.query) def OnClick(self,event): self.logger.AppendText(" Click on object with Id %d\n" %event.GetId()) def Close(self,event): import sys sys.exit() def query(self,event): mydb = PgSQL.connect(host=dbhost,database=dbname,user=dbuser,password=dbpass) c = mydb.cursor() sqlquery = ("Select * from fmna where code = 'USS001'") c.execute(sqlquery) for row in c.fetchall(): field1 = row[0] field2 = row[1] mydb.close self.tester.AppendText("Code returned is:" self.field1) app = wxPySimpleApp() frame = wxFrame(None, -1, " Testing Form", pos=wxDefaultPosition, size=(400, 300)) Form1(frame,-1) frame.Show(1) app.MainLoop() =====> End of Script From missive at hotmail.com Sun Dec 21 11:36:10 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Dec 21 11:36:17 2003 Subject: [Tutor] Re: Help with AppendText Syntax Message-ID: > for row in c.fetchall(): > field1 = row[0] > field2 = row[1] > mydb.close > self.tester.AppendText("Code returned is:" self.field1) You retrieve the value in to field1, but then try to use self.field1 to put the text in to tester. Try: self.tester.AppendText("Code returned is:" field1) That is interesting that the two string values together with no operator get concatenated ... I did not know that would work! _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From roypython at hotmail.com Sun Dec 21 12:09:00 2003 From: roypython at hotmail.com (roy ollis) Date: Sun Dec 21 12:09:10 2003 Subject: [Tutor] Beginner ... Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031221/c83198a0/attachment.html From trohland at absamail.co.za Sun Dec 21 12:43:52 2003 From: trohland at absamail.co.za (Tyron Rohland) Date: Sun Dec 21 12:44:22 2003 Subject: [Tutor] (no subject) Message-ID: <002501c3c7ea$0018b600$165827c4@cider> To resonse to Roy, when you do it your way it always gives you an invalid syntax. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031221/4743e42d/attachment.html From vbabu at cse.iitk.ac.in Sun Dec 21 12:57:51 2003 From: vbabu at cse.iitk.ac.in (Venkatesh Babu) Date: Sun Dec 21 12:56:26 2003 Subject: [Tutor] Importing global variables and classes from other modules In-Reply-To: <002501c3c7ea$0018b600$165827c4@cider> Message-ID: Hi, I have a main module which has few functions and in one of the functions, I have given an import statement so that I can get the functions and global variables present in other module into my main module's name space. The code is something like this main.py def f1(): from sub import * if __name__ == "__main__": f1() But my problem is that the functions and other global variables present sub are not getting imported to my main module. Can any body suggest me what is the right method to do, the condition being that the import should happen only if I call f1. Thanks in advance, Venkatesh -------------------------------------------------------------------------- Venkatesh Babu K R, Residence M.Tech, Department of CSE, #B311, Hall 4, IIT Kanpur IIT Kanpur e-mail: vbabu@cse.iitk.ac.in website: www.cse.iitk.ac.in/users/vbabu -------------------------------------------------------------------------- From littledanehren at yahoo.com Sun Dec 21 13:58:15 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Dec 21 13:58:19 2003 Subject: [Tutor] Importing global variables and classes from other modules In-Reply-To: Message-ID: <20031221185815.82320.qmail@web41810.mail.yahoo.com> Venkatesh Babu wrote: > Hi, > > I have a main module which has few functions and in > one of the functions, > I have given an import statement so that I can get > the functions and > global variables present in other module into my > main module's name space. > The code is something like this > > main.py > > def f1(): > from sub import * > > if __name__ == "__main__": > f1() > > But my problem is that the functions and other > global variables present > sub are not getting imported to my main module. Can > any body suggest me > what is the right method to do, the condition being > that the import should > happen only if I call f1. > > Thanks in advance, > Venkatesh When you import something inside a function, the imported things are scoped. The only thing I can think of to do that is to use the low-levelo __import__ function and make everything that is imported be global, but I don't think you really want that. It would be better to just write 'from sub import *' whenever you need it. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From littledanehren at yahoo.com Sun Dec 21 14:13:09 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Dec 21 14:13:14 2003 Subject: [Tutor] Re: trouble with pygtk and different users In-Reply-To: Message-ID: <20031221191309.76121.qmail@web41802.mail.yahoo.com> Lee Harr wrote: > su - > and not > su > > (From the su man page ... > > -l Simulate a full login. The environment > is discarded except for > HOME, SHELL, PATH, TERM, and USER. > HOME and SHELL are modified > as above. USER is set to the target > login. > > - (no letter) The same as -l. > ) > > > > It may be that (typical of linux/unix) the > commandline version > of su has more features available than the gui > version. gksu has the -l option (although not the - option), but for some reason, it causes an error in importing gtk (su does the same thing). Maybe I'll just hard-code it to say that it's root. > > I also liked the suggestion to use > os.system('command &') > and see if that makes a difference... Thanks, that fixes it. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From sigurd at 12move.de Sun Dec 21 14:44:46 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sun Dec 21 14:46:23 2003 Subject: [Tutor] Importing global variables and classes from other modules In-Reply-To: (Venkatesh Babu's message of "Sun, 21 Dec 2003 23:27:51 +0530 (IST)") References: Message-ID: On 21 Dec 2003, Venkatesh Babu <- vbabu@cse.iitk.ac.in wrote: > I have a main module which has few functions and in one of the functions, > I have given an import statement so that I can get the functions and > global variables present in other module into my main module's name space. That won't work. The imported variables and functions are only valid in the scope of the function definition. You must use the global statement if you want to see the bindings in outer scope. Here is an excerpt from the Python library reference. ,---- | Import statements are executed in two steps: (1) find a module, and | initialize it if necessary; (2) define a name or names in the local | namespace (of the scope where the `import' statement occurs). The | first form (without `from') repeats these steps for each identifier in | the list. The form with `from' performs step (1) once, and then | performs step (2) repeatedly. `---- > The code is something like this > main.py > def f1(): > from sub import * And that can't work also; first because you won't see the variables in the surrounding scope, second because that form is not allowed here (at least for Python 2.3). If I enter that here I get: $ python Python 2.3.2 (#1, Oct 9 2003, 12:03:29) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> def f1(): from t import * ... :1: SyntaxWarning: import * only allowed at module level >>> > if __name__ == "__main__": > f1() > But my problem is that the functions and other global variables present > sub are not getting imported to my main module. Can any body suggest me > what is the right method to do, the condition being that the import should > happen only if I call f1. Can't you use something else as toggle? if something_is_true: from sub import * Or you write: def f1(): global s import sub as s Then you would have the prefix but you could use a function for the global import. Karl -- Please do *not* send copies of replies to me. I read the list From python at keep-trying.com Sun Dec 21 15:01:20 2003 From: python at keep-trying.com (richard) Date: Sun Dec 21 15:02:13 2003 Subject: [Tutor] Re: Help with AppendText Syntax Message-ID: <6.0.0.22.0.20031221194545.01e0b4a0@192.168.5.1> Greetings, I tried the following but still no luck. self.tester.AppendText("Code returned is:" field1) The error is still invalid syntax. I think I am missing something to prefix "field1" but do not know what. Regards Richard From missive at hotmail.com Sun Dec 21 17:25:53 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Dec 21 17:25:58 2003 Subject: [Tutor] Re: Help with AppendText Syntax Message-ID: >I tried the following but still no luck. > >self.tester.AppendText("Code returned is:" field1) > >The error is still invalid syntax. I think I am missing >something to prefix "field1" but do not know what. > Ah. Ok, I guess you can only do that with string literals ... >>>"Code returned is:" "code" 'Code returned is:code' >>>field1 = 'code' >>>"Code returned is:" field1 File "", line 1 "Code returned is:" field1 ^ SyntaxError: invalid syntax So, probably what you want is ... self.tester.AppendText("Code returned is: %s" % field1) _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From dyoo at hkn.eecs.berkeley.edu Sun Dec 21 23:06:47 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Dec 21 23:06:51 2003 Subject: [Tutor] Re: Help with AppendText Syntax In-Reply-To: Message-ID: On Sun, 21 Dec 2003, Lee Harr wrote: > >I tried the following but still no luck. > > > >self.tester.AppendText("Code returned is:" field1) > > > >The error is still invalid syntax. I think I am missing something to > >prefix "field1" but do not know what. > > Ah. Ok, I guess you can only do that with string literals ... Yes, strings literals get put together if they're adjacent. The official Python tutorial talks about this near the middle of: http://python.org/doc/current/tut/node5.html#SECTION005120000000000000000 It's cute, but I have to admit I don't use this feature too much. *grin* For regular string concatenation, we can use '+' or string formatting. By the way, if we find outselves gluing a lot of strings together, it's good to use a specialized string joiner like the join() method of strings: http://python.org/doc/current/lib/string-methods.html#l2h-188 but for small string joining, addition or formatting works out fine. > So, probably what you want is ... > > self.tester.AppendText("Code returned is: %s" % field1) Yes, this should be syntactically correct. Good luck! From dyoo at hkn.eecs.berkeley.edu Sun Dec 21 23:29:38 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Dec 21 23:29:47 2003 Subject: [Tutor] Importing global variables and classes from other modules In-Reply-To: Message-ID: On Sun, 21 Dec 2003, Venkatesh Babu wrote: > I have a main module which has few functions and in one of the > functions, I have given an import statement so that I can get the > functions and global variables present in other module into my main > module's name space. Hi Venkatesh, Other folks have already pointed out why the above isn't working. But just as a reality check: are you sure you want to do this? It's usually a very bad idea to do a 'from foo import *' --- it ties together your module extremely closely to the imported module, and it becomes a lot more difficult to see where a certain variable came from. Simple example: if I see the code, ### def f(): print 'hello' from some_module import * f() ### then I have no idea if the last function call, 'f()', refers to the f that's just been defined at the top. Why would I feel worried? Because any name in 'some_module' may have clobbered things in my own namespace, and if 'some_module' itself defines an 'f', that'll override my 'f'. The official Python Tutorial mentions 'from foo import *' is a statement to avoid writing in real code: http://python.org/doc/current/tut/node8.html#SECTION008410000000000000000 If you must make a module with global variables, it might be best to just do the simple import: ### import global_module ### and refer to values in that module by explicitely refering to global_module: ### print global_module.some_variable_name ### > But my problem is that the functions and other global variables present > sub are not getting imported to my main module. Can any body suggest me > what is the right method to do, the condition being that the import > should happen only if I call f1. Wait, wait. Doing a conditional import might be a very bad idea from a debugging standpoint. Can you show us why you want to import this way? That context might help us to suggest better alternatives, if there are any. Good luck to you! From python at comber.cix.co.uk Mon Dec 22 03:27:15 2003 From: python at comber.cix.co.uk (Eddie Comber) Date: Mon Dec 22 04:03:54 2003 Subject: [Tutor] Subclassing Message-ID: Suppose I want to subclass 'list' to provide mylist which has different behaviour. Say I only want to modify the '+' operator __add(self, other)__ as the other operators and functions are fine. The problem is what type should '+' return? If it returns type == list then a = mylist() b = mylist() c = mylist() d = a + b + c means after b + c the type is 'list' and a + b is (mylist + list) rather than (mylist + mylist). The trouble with returning type mylist is that it looks to me like all the 'list' operators and functions need to be trivially subclassed to return type mylist. Am I right in this? ta, Eddie, From python at comber.cix.co.uk Mon Dec 22 07:12:27 2003 From: python at comber.cix.co.uk (Eddie Comber) Date: Mon Dec 22 08:03:52 2003 Subject: [Tutor] Stuffing keystrokes into windows App. Message-ID: I have a 3rd party Windows app that does have a COM interface but I can't work it all out. I think I need just to bring the windows app to the focus and stuff keystrokes into it. Any suggestions as to how this might be done? I think it will help a lot to look at this Excel Macro that does what I want. AppActivate "LV-ST" For j = 1 To 50 'THIS SENDS THE CONTENTS OF THE a(ITEMNO) WITH A CARRIAGE RETURN 'CHARACTER (y) THEN BACKSPACE SendKeys a$(j) & Chr$(13) & "y" & "{BS}", True Next j Tall order perhaps but thanks in anticipation, Eddie. From Christian.Wyglendowski at greenville.edu Mon Dec 22 09:27:13 2003 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Mon Dec 22 09:27:18 2003 Subject: [Tutor] Stuffing keystrokes into windows App. Message-ID: A quick google for "python sendkeys" turned this up: http://www.rutherfurd.net/python/sendkeys/ Don't know if it works with python beyond 2.1, but I imagine it would. The following page has examples using the WSH COM interface to get to sendkeys (that way you don't need to download a separate module). http://aspn.activestate.com/ASPN/Mail/Message/activepython/544878 That should get you going! Christian > -----Original Message----- > From: Eddie Comber [mailto:python@comber.cix.co.uk] > Sent: Monday, December 22, 2003 6:12 AM > To: tutor@python.org > Subject: [Tutor] Stuffing keystrokes into windows App. > > > I have a 3rd party Windows app that does have a COM interface > but I can't work it all out. > > I think I need just to bring the windows app to the focus and > stuff keystrokes into it. > > Any suggestions as to how this might be done? > > I think it will help a lot to look at this Excel Macro that > does what I want. > > AppActivate "LV-ST" > For j = 1 To 50 > 'THIS SENDS THE CONTENTS OF THE a(ITEMNO) WITH A > CARRIAGE RETURN > 'CHARACTER (y) THEN BACKSPACE > SendKeys a$(j) & Chr$(13) & "y" & "{BS}", True > Next j > > Tall order perhaps but > thanks in anticipation, > Eddie. > > > > From vbabu at cse.iitk.ac.in Mon Dec 22 11:11:05 2003 From: vbabu at cse.iitk.ac.in (Venkatesh Babu) Date: Mon Dec 22 11:09:35 2003 Subject: [Tutor] Importing global variables and classes from other modules In-Reply-To: Message-ID: On Sun, 21 Dec 2003, Danny Yoo wrote: > > > But my problem is that the functions and other global variables present > > sub are not getting imported to my main module. Can any body suggest me > > what is the right method to do, the condition being that the import > > should happen only if I call f1. > > Wait, wait. Doing a conditional import might be a very bad idea from a > debugging standpoint. > > Can you show us why you want to import this way? That context might help > us to suggest better alternatives, if there are any. Hi Danny, My program will be creating classes dynamically and I wish to save those class definitions into the file and retrive these definitions at some other point in time. I first thought of a simple strategy of storing the class definition in file as a string and later executing the string so that the class is created. But the class gets created inside the function in which i call exec and its scope is confined to that function, so I thought of using import instead of executing the string. Can u suggest any other strategy for my problem. Thank you, Venkatesh > > > Good luck to you! > -------------------------------------------------------------------------- Venkatesh Babu K R, Residence M.Tech, Department of CSE, #B311, Hall 4, IIT Kanpur IIT Kanpur e-mail: vbabu@cse.iitk.ac.in website: www.cse.iitk.ac.in/users/vbabu -------------------------------------------------------------------------- From vicki.stanfield at ROCHE.COM Mon Dec 22 11:16:11 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Mon Dec 22 11:17:10 2003 Subject: [Tutor] Importing global variables and classes from other modules Message-ID: Subject: Re: [Tutor] Importing global variables and classes from other modules On Sun, 21 Dec 2003, Danny Yoo wrote: > > > But my problem is that the functions and other global variables > > present sub are not getting imported to my main module. Can any body > > suggest me what is the right method to do, the condition being that > > the import should happen only if I call f1. > > Wait, wait. Doing a conditional import might be a very bad idea from > a debugging standpoint. > > Can you show us why you want to import this way? That context might > help us to suggest better alternatives, if there are any. Isn't a conditional import often done for multi-platform work? If my program is intended to run on Windows and Linux, I often do conditional importing. Is there a problem with that that I don't know of? --vicki From bgailer at alum.rpi.edu Mon Dec 22 13:09:52 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Dec 22 13:10:04 2003 Subject: [Tutor] Subclassing In-Reply-To: References: Message-ID: <6.0.0.22.0.20031222105553.0406fbe8@mail.mric.net> At 01:27 AM 12/22/2003, Eddie Comber wrote: >Suppose I want to subclass 'list' to provide mylist which has different >behaviour. Say I only want to modify the '+' operator __add(self, other)__ >as the other operators and functions are fine. > >The problem is what type should '+' return? > >If it returns type == list then > >a = mylist() >b = mylist() >c = mylist() > >d = a + b + c > >means after b + c the type is 'list' and a + b is (mylist + list) rather >than (mylist + mylist). >The trouble with returning type mylist is that it looks to me like all the >'list' operators and functions need to be trivially subclassed to return >type mylist. Try this: class mylist(list): def __init__(self, inList=None): if inList: self[:] = inList def __add__(self, other): self.extend(other) return mylist(self) a = mylist([1]) b = mylist([2]) c = mylist([3]) d = a + b + c print d # displays [1, 2, 3] x = 3 i = 1 j = 2 n = 3 t = [5, 6] print x in s # 1 if an item of s is equal to x, else 0 print x not in s # 0 if an item of s is equal to x, else 1 print s + t # the concatenation of s and t print s * n , n * s # n shallow copies of s concatenated (1) print s[i] # i'th item of s, origin 0 (2) print s[i:j] # slice of s from i to j (2), (3) print len(s) # length of s print min(s) # smallest item of s print max(s) s[i] = x ; print s # item i of s is replaced by x s[i:j] = t ; print s # slice of s from i to j is replaced by t del s[i:j] ; print s # same as s[i:j] = [] s.append(x) ; print s # same as s[len(s):len(s)] = [x] (1) s.extend([x]) ; print s # same as s[len(s):len(s)] = x (2) s.count(x) ; print s # return number of i's for which s[i] == x s.index(x) ; print s # return smallest i such that s[i] == x (3) s.insert(i, x) ; print s # same as s[i:i] = [x] if i >= 0 (4) s.pop(i) ; print s #same as x = s[i]; del s[i]; return x (5) s.remove(x) ; print s #same as del s[s.index(x)] (3) s.reverse() ; print s #reverses the items of s in place (6) s.sort() ; print s #sort the items of s in place Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 12/11/2003 From python at keep-trying.com Mon Dec 22 13:20:46 2003 From: python at keep-trying.com (richard) Date: Mon Dec 22 13:21:41 2003 Subject: [Tutor] Re: Help with AppendText Syntax [Works] In-Reply-To: References: Message-ID: <6.0.0.22.0.20031222181628.03209688@192.168.5.1> Greetings, The following: self.tester.AppendText("Code returned is: %s" % field1) worked fine, thanks for help. Also thanks for pointing out the information on using strings. All is clear now. I had spent sometime looking for help on the AppendText when really it was the use of strings which was my problem. (Well one any way) Regards Richard At 04:06 22/12/2003, you wrote: >On Sun, 21 Dec 2003, Lee Harr wrote: > > > >I tried the following but still no luck. > > > > > >self.tester.AppendText("Code returned is:" field1) > > > > > >The error is still invalid syntax. I think I am missing something to > > >prefix "field1" but do not know what. > > > > Ah. Ok, I guess you can only do that with string literals ... > > >Yes, strings literals get put together if they're adjacent. The official >Python tutorial talks about this near the middle of: > >http://python.org/doc/current/tut/node5.html#SECTION005120000000000000000 > >It's cute, but I have to admit I don't use this feature too much. *grin* > > >For regular string concatenation, we can use '+' or string formatting. >By the way, if we find outselves gluing a lot of strings together, it's >good to use a specialized string joiner like the join() method of strings: > > http://python.org/doc/current/lib/string-methods.html#l2h-188 > >but for small string joining, addition or formatting works out fine. > > > > > So, probably what you want is ... > > > > self.tester.AppendText("Code returned is: %s" % field1) > >Yes, this should be syntactically correct. > > >Good luck! > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From tayi177 at hotmail.com Mon Dec 22 14:10:24 2003 From: tayi177 at hotmail.com (David) Date: Mon Dec 22 14:09:59 2003 Subject: [Tutor] Fw: Reinstalling Python might help ... error message Message-ID: Hello ... Something very strange started to happen with my Python installation. Soon after starting Python today, some very strange "windows apllication error message" appeared (the one marked with the red sign), saying something like: "an (this and this) application error occured, ... file/key (or something) is missing, ... or is invalid, ... reinstalling Python might help" I am really mad at myself for not making screenshot of that error, cause I ALWAYS archive that kind of stuff to describe problem better. I know, that without knowing true error message text, you can't help me at all (I just assume there was something like "... file/key (or something) is missing"), but I am just interested, if someone has any clue, what kind of error could be that, causing that kind of pop-up window - "... reinstalling Python might help" - cause I am 100 % sure for that part of error message ... Thanks, Tadey -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031222/03fb1c2d/attachment.html From littledanehren at yahoo.com Mon Dec 22 15:00:19 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Dec 22 15:00:50 2003 Subject: [Tutor] Importing global variables and classes from other modules In-Reply-To: Message-ID: <20031222200019.59056.qmail@web41807.mail.yahoo.com> > Isn't a conditional import often done for > multi-platform work? If my > program is intended to run on Windows and Linux, I > often do conditional > importing. Is there a problem with that that I don't > know of? > > --vicki I always thought that you're supposed to do exception handling for importing, that way it's better for the future. For example, let's say you have an application that requires PyGTK. At the time of the writing of the program, PyGTK is only on Linux and Windows. So if you use conditionals, you'd write: if sys.platform in ('win', 'win32', 'linux', linux2'): import gtk else: print 'this will not work' But then what happens when they write a PyGTK port to Mac OS X? Your application will not work correctly on Macs, when it could. So you write it like this instead: try: import gtk except ImportError: print 'this will not work' That way, any computer that has PyGTK on it will work, and any that doesn't will print 'this will not work'. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From littledanehren at yahoo.com Mon Dec 22 15:05:05 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Dec 22 15:05:45 2003 Subject: [Tutor] Importing global variables and classes from other modules In-Reply-To: Message-ID: <20031222200505.79323.qmail@web41811.mail.yahoo.com> Venkatesh Babu wrote: > Hi Danny, > > My program will be creating classes dynamically and > I wish to save those > class definitions into the file and retrive these > definitions at some > other point in time. I first thought of a simple > strategy of storing the > class definition in file as a string and later > executing the string so > that the class is created. But the class gets > created inside the function > in which i call exec and its scope is confined to > that function, so I > thought of using import instead of executing the > string. > > Can u suggest any other strategy for my problem. > > Thank you, > Venkatesh Try using the pickle module. It lets you easily store any datatype (including classes) in a file or string. If your class is dependent on a module (like inheringing from a module or something), pickle will handle everything for you, automatically. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Mon Dec 22 15:16:36 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 22 15:16:45 2003 Subject: [Tutor] Importing global variables and classes from other modules In-Reply-To: Message-ID: On Mon, 22 Dec 2003, Stanfield, Vicki {D167~Indianapolis} wrote: > > > But my problem is that the functions and other global variables > > > present sub are not getting imported to my main module. Can any body > > > > suggest me what is the right method to do, the condition being that > > > the import should happen only if I call f1. > > > > Wait, wait. Doing a conditional import might be a very bad idea from > > a debugging standpoint. > > > > Can you show us why you want to import this way? That context might > > help us to suggest better alternatives, if there are any. > > Isn't a conditional import often done for multi-platform work? If my > program is intended to run on Windows and Linux, I often do conditional > importing. Is there a problem with that that I don't know of? I should be less polemical. *grin* Multi-platform work is one place where doing a conditional import is probably ok. And pygame --- a popular module for doing games/GUI programming --- itself uses a lot of conditional imports to fail safely if the sound device isn't working. For example, here's a portion of what Pygame does when it tries loading in its modules: ### #next, the "standard" modules #we still allow them to be missing for stripped down pygame distributions try: import pygame.cdrom except (ImportError,IOError), msg:cdrom=MissingModule("cdrom", msg, 1) try: import pygame.cursors except (ImportError,IOError), msg:cursors=MissingModule("cursors", msg, 1) try: import pygame.display except (ImportError,IOError), msg:display=MissingModule("display", msg, 1) ### http://cvs.seul.org/cgi-bin/cvsweb-1.80.cgi/games/pygame/lib/__init__.py?rev=1.29&content-type=text/x-cvsweb-markup So this conditional import is a technique that is used. But its use is fairly limited to things like loading platform-dependent libraries. In Venkatesh's case, though, I'm not sure that it's such a good idea to do a conditional import. Let's see his message: > My program will be creating classes dynamically and I wish to save those > class definitions into the file and retrive these definitions at some > other point in time. I first thought of a simple strategy of storing the > class definition in file as a string and later executing the string so > that the class is created. Yes, this sounds reasonable. > But the class gets created inside the function in which i call exec and > its scope is confined to that function Are you sure about this? I'm not quite sure I understand why scope is significant here --- it should be perfectly possible to construct classes from an evaluated class definition, regardless of the scope. Here's an example: ### >>> s = ''' ... class Person: ... def sayHello(self): ... print "Hello world!" ... ''' >>> d = {'__name__': 'DynamicCode', '__builtins__': None} >>> exec s in d ### Here, the Person class doesn't live directly in the global namespace, ### >>> Person Traceback (most recent call last): File "", line 1, in ? NameError: name 'Person' is not defined ### But it resides in the small dictionary 'd' that we've set up. ### >>> d['Person'] ### And we can still construct Person instances: ### >>> joe = d['Person']() >>> joe.sayHello() Hello world! ### This has the slight advantage of being able to limit the scope of the dynamic classes to a small dictionary, so that it doesn't have the opportunity to kludge up our namespace. If we package this up in a nice function, everything works as expected still: ### >>> def extractClass(text, class_name): ... d = {'__name__': 'DynamicCode', '__builtins__' : None} ... exec text in d ... return d[class_name] ... >>> MyClass = extractClass(s, 'Person') >>> mary = MyClass() >>> mary.sayHello() Hello world! ### Venkatesh, would this be ok for you? Good luck! From littledanehren at yahoo.com Mon Dec 22 16:53:00 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Dec 22 16:53:05 2003 Subject: [Tutor] parsing configuration files Message-ID: <20031222215300.64343.qmail@web41810.mail.yahoo.com> I'm trying to write a program to make it easier to automate the making of GTK+ GUIs by making configuration files that use a simplified YAML-like syntax (see yaml.org; it looks kinda like Python). (Glade files were not meant to be made by hand, so that's why I'm doing a new thing) I wrote a simple parser but it acts strangely. Here's a sample configuration file, what its output should be, and the parser that doesn't work correctly, in that order: nRadio: _Nautilus nautilus Gnome's file manager tRadio: _Terminal gnome-terminal command line powered by Gnome gRadio: _Gedit gedit simple text editor sRadio: _Synaptic synaptic GUI for apt-get {'nRadio': ['_Nautilus', 'nautilus', "Gnome's file manager"], 'tRadio': ['gnome-terminal', 'command line powered by Gnome'], 'gRadio': ['_Gedit', 'gedit', 'simple text editor'], 'sRadio': ['_Synaptic', 'synaptic', 'GUI for apt-get']} def parsefile(filename): stuff2parse = open(filename) data = {} for line in stuff2parse.xreadlines(): if line: if not line.startswith(' '): currentSection = line[:-1] data[currentSection] = [] else: try: data[currentSection] += line.strip() except: pass return data Instead of returning what it should, it returns one of two outputs. If it is run with PyShell, it returns {'nRadio:': []} But if it is run by itself in a file, it returns {'': [], 'gRadio:': ['_', 'G', 'e', 'd', 'i', 't', 'g', 'e', 'd', 'i', 't', 's', 'i', 'm', 'p', 'l', 'e', ' ', 't', 'e', 'x', 't', ' ', 'e', 'd', 'i', 't', 'o', 'r'], 'tRadio:': ['_', 'T', 'e', 'r', 'm', 'i', 'n', 'a', 'l', 'g', 'n', 'o', 'm', 'e', '-', 't', 'e', 'r', 'm', 'i', 'n', 'a', 'l', 'c', 'o', 'm', 'm', 'a', 'n', 'd', ' ', 'l', 'i', 'n', 'e', ' ', 'p', 'o', 'w', 'e', 'r', 'e', 'd', ' ', 'b', 'y', ' ', 'G', 'n', 'o', 'm', 'e'], 'nRadio:': ['_', 'N', 'a', 'u', 't', 'i', 'l', 'u', 's', 'n', 'a', 'u', 't', 'i', 'l', 'u', 's', 'G', 'n', 'o', 'm', 'e', "'", 's', ' ', 'f', 'i', 'l', 'e', ' ', 'm', 'a', 'n', 'a', 'g', 'e', 'r'], 'sRadio:': ['_', 'S', 'y', 'n', 'a', 'p', 't', 'i', 'c', 's', 'y', 'n', 'a', 'p', 't', 'i', 'c', 'G', 'U', 'I', ' ', 'f', 'o', 'r', ' ', 'a', 'p', 't', '-', 'g', 'e', 't']} which appears to split it up by character instead of by line, like it should. I know I could just use a python dictionary stored in a file and then evaluate it, like PythonCard does, but then the syntax isn't as clean. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From missive at hotmail.com Mon Dec 22 17:18:30 2003 From: missive at hotmail.com (Lee Harr) Date: Mon Dec 22 17:18:35 2003 Subject: [Tutor] Re: parsing configuration files Message-ID: > I wrote a simple >parser but it acts strangely. >>>a = [] >>>a += 'foo' >>>a ['f', 'o', 'o'] >>>a = [] >>>a.append('foo') >>>a ['foo'] _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo at hkn.eecs.berkeley.edu Mon Dec 22 19:20:12 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 22 19:20:17 2003 Subject: [Tutor] parsing configuration files In-Reply-To: <20031222215300.64343.qmail@web41810.mail.yahoo.com> Message-ID: On Mon, 22 Dec 2003, Daniel Ehrenberg wrote: > I'm trying to write a program to make it easier to > automate the making of GTK+ GUIs by making > configuration files that use a simplified YAML-like > syntax (see yaml.org; it looks kinda like Python). Sounds good. Let's take a look at the code: > def parsefile(filename): > stuff2parse = open(filename) > data = {} > for line in stuff2parse.xreadlines(): > if line: > if not line.startswith(' '): > currentSection = line[:-1] > data[currentSection] = [] > else: > try: > data[currentSection] += line.strip() > except: pass > > return data Side note: it might be nicer to have parsefile() take in a file-like object, rather than a filename. ### def parsefile(stuff2parse): data = {} for line in stuff2parse.xreadlines(): ... ### The reason this adjustment might help is because it becomes easier to test out the code, since we can make a string look like a file with the StringIO module: http://www.python.org/doc/lib/module-StringIO.html and be able to quickly test it with: ### from StringIO import StringIO sample_conffile = ''' gRadio: _Gedit gedit simple text editor sRadio: _Synaptic synaptic GUI for apt-get ''' print parsefile(StringIO(sample_conffile)) ### and it might be a good idea to make this a formal unit test. But I think I'm getting off the subject. *grin* Looking at the main loop: ### for line in stuff2parse: if line: if not line.startswith(' '): currentSection = line[:-1] data[currentSection] = [] else: try: data[currentSection] += line.strip() except: pass ### There's a subtle type error going on, and it has to do with 'data'. In the first case, data[currentSection] = [] shows that data[currentSection] must be a list, so we need to deal with it with list methods. The second block: data[currentSection] += line.strip() tries to deal with it as if it were a string! What ends up happening is something akin to: ### >>> l = [] >>> l += "hello world" >>> l ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] ### By the way, this is bizarre! *grin* I had really expected a TypeError at this point, like: ### >>> [] + "foo" Traceback (most recent call last): File "", line 1, in ? TypeError: can only concatenate list (not "str") to list ### but the difference is due to the behavior of the '+=' operator on lists: The behavior of '+=' on lists is equivalent to list.extend(): ### >>> l = [] >>> l.extend("hello") >>> l ['h', 'e', 'l', 'l', 'o'] ### This explains why we got such strange string-to-character-transforming behavior from '+='. But this is surprising; I'll have to keep my eye out for this next time it happens. *grin* Anyway, you meant to use the append() method of lists, so instead of: data[currentSection] += line.strip() use data[currentSection].append(line.strip()) and that should fix the problem. On other style note: when you're iterating over a file, you can just say: for line in some_file: Files are iterable in Python, so there's no more need to say: for line in some_file.xreadlines() as long as you're using a relatively recent version of Python. I hope this helps! From littledanehren at yahoo.com Mon Dec 22 21:24:54 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Dec 22 21:24:59 2003 Subject: [Tutor] parsing configuration files In-Reply-To: Message-ID: <20031223022454.25913.qmail@web41809.mail.yahoo.com> Danny Yoo wrote: > Side note: it might be nicer to have parsefile() > take in a file-like > object, rather than a filename. > OK, I'll change that. > > Looking at the main loop: > > ### > for line in stuff2parse: > if line: > if not line.startswith(' '): > currentSection = line[:-1] > data[currentSection] = [] > else: > try: > data[currentSection] += > line.strip() > except: pass > ### > > There's a subtle type error going on, and it has to > do with 'data'. Hmm. I guess this is one of the disadvantages of Python's relatively weak typing. > On other style note: when you're iterating over a > file, you can just say: > > for line in some_file: > > Files are iterable in Python, so there's no more > need to say: > > for line in some_file.xreadlines() > > as long as you're using a relatively recent version > of Python. > > > I hope this helps! > Oops. I just put that in because I thought it somehow could have been the problem. It used to be 'for line in some_file:', and now it's fixed to be that again. Thanks for your help. Daniel Ehrenberg __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From pythontutor at venix.com Mon Dec 22 21:56:13 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Dec 22 21:56:17 2003 Subject: [Tutor] parsing configuration files In-Reply-To: <20031223022454.25913.qmail@web41809.mail.yahoo.com> References: <20031223022454.25913.qmail@web41809.mail.yahoo.com> Message-ID: <3FE7AECD.1070106@venix.com> Daniel Ehrenberg wrote: > Danny Yoo wrote: >>There's a subtle type error going on, and it has to >>do with 'data'. > > > Hmm. I guess this is one of the disadvantages of > Python's relatively weak typing. I don't think it is weak typing so much as the fact that a string, list and tuple are all sequences. (Unless this broadness of sequence is what you mean by weak typing.) I usually create this kind of bug when I pass a single fieldname to a function that expects a list of fieldnames. The function will happily attempt to process a sequence of one character names unless I put in a check to catch strings and turn them into single item lists. On balance, I still like the ease of slicing strings that comes from including strings in the "sequence family". -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Mon Dec 22 22:33:56 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 22 22:34:01 2003 Subject: [Tutor] parsing configuration files In-Reply-To: <3FE7AECD.1070106@venix.com> Message-ID: On Mon, 22 Dec 2003, Lloyd Kvam wrote: > >>There's a subtle type error going on, and it has to do with 'data'. > > > > Hmm. I guess this is one of the disadvantages of Python's relatively > > weak typing. > > I don't think it is weak typing so much as the fact that a string, list > and tuple are all sequences. Hi Daniel, I should have been more careful with my phrasing. What I meant was that there was a "conceptual" type error in that code. The bug is one of semantics, and that's something that computers won't figure out for a while. As far as Python is concerned, all the typing there was fine. Looking back at an example: ### >>> l = [] >>> l1 = [1, 2, 3] >>> l2 = [4, 5, 6] >>> l1.extend(l2) >>> l1 [1, 2, 3, 4, 5, 6] ### the extend() method takes in a 'sequence' as its argument, and adds all the elements in that sequence in. Actually, I'm not quite telling the truth again. The extend() method actually wants an 'iterable'. An 'iterable' is anything that can return single elements at a time. Anyway, Python treats strings as a sequence of characters --- that's what allows us to do things like: ### >>> for letter in 'hello': ... print letter ... h e l l o ### As a consequence of this, if we extend a list by a string, what we're really asking Python to do is add every element --- every character --- as an element of that list. In fact, it's useful for it to do this! ### >>> buffer = list("hello") >>> buffer ['h', 'e', 'l', 'l', 'o'] >>> buffer.extend("world") >>> buffer ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] ### (Instant java.lang.StringBuffer, for folks who are familiar with Java. *grin*) So the original "buggy" code is perfectly correct in terms of typing. If it were not, we would have seen TypeError exceptions flying around, and would have caught the bug sooner. The problem is that the code is doing exactly what it is told, and not what we really mean. *grin* Hope this clears things up! From bgailer at alum.rpi.edu Mon Dec 22 23:46:10 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Dec 22 23:46:20 2003 Subject: [Tutor] Why has this syntax with multiple arguments ceased to work for the print command? In-Reply-To: <3FE4D2BF.4080801@comcast.net> References: <3FE4D2BF.4080801@comcast.net> Message-ID: <6.0.0.22.0.20031222214351.03f01598@mail.mric.net> At 03:52 PM 12/20/2003, hcohen2 wrote: >I am certain code like this ran for me without any problem: > >print 'You are: %s? and It is the %dth of Dec.' % esp, int(cnt) > >both esp are gathered by ... = raw_input('Enter ...') and each works >properly as a single argument in test strings. > >Now I get: > >Traceback (most recent call last): > File "", line 1, in ? >TypeError: not enough arguments for format string > >I tried to study the documentation on the print statement, but the syntax >for the argument list left me confused. [How about some examples in the >documentation?] It appears that the syntax has altered from what was >working on version 2.0.x. > >I am running this under Mandrake Linux 9.1 using version 2.2.2. > >Where am I going wrong? Try: print 'You are: %s? and It is the %dth of Dec.' % (esp, int(cnt)) % expects a tuple. Without the parentheses the precedence rules evaluate % before , making the statement look like: print ('You are: %s? and It is the %dth of Dec.' % esp) , int(cnt) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.551 / Virus Database: 343 - Release Date: 12/11/2003 From arkamir at softhome.net Tue Dec 23 18:19:35 2003 From: arkamir at softhome.net (arkamir@softhome.net) Date: Tue Dec 23 18:19:40 2003 Subject: [Tutor] (no subject) Message-ID: Hello, I have a question concerning turning strings into variables. Say I have a list like x: x = ['hello', 'bye'] What I need is the final result to look like this, or the equivelant of this. How would I do this??? hello = re.compile(r'') bye = re.compile(r'') I think it would look something like for y in x: #string to variable# = re.compile(r'<--INSERT %s HERE-->' % y) Is this the most effecient way, and how would I convert y to capitols. Also can someone explain lambdas too me. Whenever I do something like: x = lambda x: x + 1, (1) I get (, 2) Thanks a lot, Conrad Koziol From piir at earthlink.net Tue Dec 23 20:22:03 2003 From: piir at earthlink.net (Todd G. Gardner) Date: Tue Dec 23 20:22:28 2003 Subject: [Tutor] trying to call function in dll Message-ID: Hello all, /* DLL Function int32 DAQmxCreateTask (const char taskName[], TaskHandle *taskHandle); I have installed ctypes-0.6.2a.win32-py2.3.exe. I am not sure where to start asking questions so I figured I would dive in and give this a shot. My goal is to be acquire an analog voltage using a data acquisition card from National Instruments and the python language. Pardon my ignorance as I am quite the newbie regarding python. Also, I have done minimal programming in "c". I have done 12 years or programming in LabVIEW. The card is a PCMCIA DacCard model 6062E. Currently I read this card using LabVIEW which inturn calls the nidaq32.dll. My newbie questions start with the dll function "DAQmxCreateTask()" and the following text details the codes successes and failures that I have been having. /* This next three lines of python code seem to work however, I am not sure if the result is correct. >>> from ctypes import * >>> ni = windll.nidaq32 >>> print ni /* The nidaq32.dll manual shows the syntax to this call as. /* int32 DAQmxCreateTask (const char taskName[], TaskHandle *taskHandle); /* This next two lines of python code seem to work... >>> taskHandle = c_void_p >>> print taskHandle /* This next line of python code does not work and generates the Traceback shown. >>> ptaskHandle = pointer(taskHandle) Traceback (most recent call last): File "", line 1, in -toplevel- ptaskHandle = pointer(taskHandle) File "C:\Python23\Lib\site-packages\ctypes\__init__.py", line 206, in pointer return POINTER(type(inst))(inst) File "C:\Python23\Lib\site-packages\ctypes\__init__.py", line 189, in POINTER {'_type_': cls}) TypeError: _type_ must have storage info >>> /* This next line of python code generates the Traceback error shown. /* What syntax should be used? >>> ni.DAQmxCreateTask("",taskHandle) Traceback (most recent call last): File "", line 1, in -toplevel- ni.DAQmxCreateTask("",taskHandle) File "C:\Python23\Lib\site-packages\ctypes\__init__.py", line 250, in __getattr__ func = self._StdcallFuncPtr(name, self) AttributeError: function 'DAQmxCreateTask' not found >>> /*************************************************** /* FYI: Below, I have copied the "ContAcq-IntClk-AnlgStart_Fn.c" written by National Instruments(see below). /* I don't understand all of this function however, I included it to lend some idea of what actually should be occuring. /* Every function call starting with "DAQmx..." is a call to a dll function call. /*************************************************** #include "NIDAQmx.h" #include "ContAcq-IntClk-AnlgStart_Fn.h" // Configures the task. // Recommended parameters: // chan = "Dev1/ai0" // min = -10.0 // max = 10.0 // samplesPerChan = 1000 // rate = 10000.0 // triggerSource = "PFI0" // triggerSlope = DAQmx_Val_Rising // triggerLevel = 0.0 int32 Configure_ContAcqIntClkAnlgStart(const char chan[], float64 min, float64 max, uInt32 samplesPerChan, float64 rate, const char triggerSource[], uInt32 triggerSlope, float64 triggerLevel, uInt32 *numChannels, TaskHandle *taskHandle) { int32 error=0; /********************************************************************* * 1. Create a task. * 2. Create an analog input voltage channel. * 3. Set the rate for the sample clock. Additionally, define the * sample mode to be finite. * 4. Define the parameters for an Analog Slope Start Trigger. *********************************************************************/ DAQmxErrChk (DAQmxCreateTask("",taskHandle)); DAQmxErrChk (DAQmxCreateAIVoltageChan(*taskHandle,chan,"",DAQmx_Val_Cfg_Default,min,max, DAQmx_Val_Volts,NULL)); DAQmxErrChk (DAQmxCfgSampClkTiming(*taskHandle,"",rate,DAQmx_Val_Rising,DAQmx_Val_ContSa mps,samplesPerChan)); DAQmxErrChk (DAQmxCfgAnlgEdgeStartTrig(*taskHandle,triggerSource,triggerSlope,triggerLev el)); if( numChannels ) DAQmxErrChk (DAQmxGetTaskAttribute(*taskHandle,DAQmx_Task_NumChans,numChannels)); Error: return error; } // Starts the task. int32 Start_ContAcqIntClkAnlgStart(TaskHandle taskHandle) { return DAQmxStartTask(taskHandle); } // Reads data into user allocated buffer. // Recommended parameters: // bufferSize = 1000 int32 Read_ContAcqIntClkAnlgStart(TaskHandle taskHandle, uInt32 sampsPerChan, float64 data[], uInt32 bufferSize, int32 *read) { return DAQmxReadAnalogF64(taskHandle,sampsPerChan,10.0,DAQmx_Val_GroupByScanNumber, data,bufferSize,read,NULL); } // Stops the task. int32 Stop_ContAcqIntClkAnlgStart(TaskHandle taskHandle) { int32 error=0; error = DAQmxStopTask(taskHandle); DAQmxClearTask(taskHandle); return error; } /*************************************************************************** ******************************* Any information or ideas would be greatly apprecieted! Thank you, Todd -- Todd Gardner San Jose, CA From missive at hotmail.com Tue Dec 23 23:20:02 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Dec 23 23:20:13 2003 Subject: [Tutor] Re: (no subject) Message-ID: >I have a question concerning turning strings into variables. > >Say I have a list like x: > >x = ['hello', 'bye'] > >What I need is the final result to look like this, or the equivelant of >this. How would I do this??? > >hello = re.compile(r'') >bye = re.compile(r'') > >I think it would look something like > >for y in x: > #string to variable# = re.compile(r'<--INSERT %s HERE-->' % y) > I think, generally, you don't really want to do that. How about creating a dictionary instead? Or another list? my_regexps = {} for find_this in x: my_regexps[find_this] = re.compile(r'<--INSERT %s HERE-->' % find_this) >Is this the most effecient way, and how would I convert y to capitols. > >>>dir('hello') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>>'hello'.upper() 'HELLO' >Also can someone explain lambdas too me. Whenever I do something like: > >x = lambda x: x + 1, (1) > >I get (, 2) I think what you want is x = lambda x: x + 1 x(1) what you have is a tuple of a lambda and a number. Also, I think if you are assigning the lambda to a name, then you may as well just use def ... def x(number): return number + 1 _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From clay at shirky.com Wed Dec 24 07:19:39 2003 From: clay at shirky.com (Clay Shirky) Date: Wed Dec 24 07:19:47 2003 Subject: [Tutor] EOF error with pickle? Message-ID: I'm trying to use pickle to store some nested lists. The program writes to the output file fine, but when I read the same file as input, I get an EOF error. Here's the test script I wrote to reproduce the error: import pickle test_list = range(100) f = open("pickle.dat", 'w') pickle.dump(test_list, f) print "dumped..." # this works g = open("pickle.dat") new_list = pickle.load(g) print new_list # this generates the error below ----- /Users/cshirky/test> test_pickle.py dumped... Traceback (most recent call last): File "./test_pickle.py", line 17, in ? new_list = pickle.load(g) File "/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/pickle.py", line 1390, in load return Unpickler(file).load() File "/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/pickle.py", line 894, in load_eof raise EOFError EOFError From missive at hotmail.com Wed Dec 24 08:48:51 2003 From: missive at hotmail.com (Lee Harr) Date: Wed Dec 24 08:48:55 2003 Subject: [Tutor] Re: EOF error with pickle? Message-ID: >I'm trying to use pickle to store some nested lists. The program writes to >the output file fine, but when I read the same file as input, I get an EOF >error. > >Here's the test script I wrote to reproduce the error: > >import pickle >test_list = range(100) > >f = open("pickle.dat", 'w') >pickle.dump(test_list, f) >print "dumped..." # this works > >g = open("pickle.dat") >new_list = pickle.load(g) >print new_list # this generates the error below You need to close the file and reopen it. Otherwise, I think the file pointer is still pointing to the end of the file. _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From malex at purdue.edu Wed Dec 24 10:05:34 2003 From: malex at purdue.edu (O. Moskalenko) Date: Wed Dec 24 10:05:43 2003 Subject: [Tutor] [support@deltawebhosting.com: Re: Python cgi Message-ID: <20031224150534.GD19205@purdue.edu> Would someone more experienced make a comment I could pass on to those guys ;)? Merry Christmas and Happy New Year to all pythonistas celebrating them around this time of year. Alex. ----- Forwarded message from DeltaWebHosting Support ----- > From: DeltaWebHosting Support > > Hi Alex, > > Currently we are offering just this options you can find on our "Hosting > Services" page. Due to higher risk of abuse with python we are not planing > to include that in our packages, at least not soon. > > Regards, > Delta Web Hosting > > > > > Name: Alex > > Email: malex@purdue.edu > > > > Message: Hi, > > > > Do you plan on adding python (www.python.org) as a cgi option? You seem to > offer a lot more than my current host, but I can't find any info on the > question above on your site. > > > > Thanks, > > > > Alex. > > From carroll at tjc.com Wed Dec 24 12:15:55 2003 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 24 12:16:01 2003 Subject: [Tutor] EOF error with pickle? In-Reply-To: Message-ID: On Wed, 24 Dec 2003, Clay Shirky wrote: > Here's the test script I wrote to reproduce the error: > > import pickle > test_list = range(100) > > f = open("pickle.dat", 'w') > pickle.dump(test_list, f) > print "dumped..." # this works f.close() > g = open("pickle.dat") > new_list = pickle.load(g) > print new_list # this generates the error below I recognize this error; you must have copied it from me! As an aside, if you decide to use binary pickling (slightly more efficient): pickle.dump(test_list, f, bin=1) and you're on Windows, you'll want to make sure your opens are binary: f = open("pickle.dat", 'wb') ... g = open("pickle.dat", 'rb') -- Terry Carroll Santa Clara, CA carroll@tjc.com From shaleh at speakeasy.net Wed Dec 24 12:30:37 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Wed Dec 24 12:30:54 2003 Subject: [Tutor] [support@deltawebhosting.com: Re: Python cgi In-Reply-To: <20031224150534.GD19205@purdue.edu> References: <20031224150534.GD19205@purdue.edu> Message-ID: <200312240930.37318.shaleh@speakeasy.net> On Wednesday 24 December 2003 07:05, O. Moskalenko wrote: > Would someone more experienced make a comment I could pass on to those > guys ;)? > Do they offer cgi at all? In what languages / ways? If they allow you to use perl then there is no reason to exclude python. Perhaps they could explain how they feel it is less secure than what they are currently offering? From their experience they may have valid reasons. There is no good response we can provide to either you or your would-be hosts. More information is needed. Be polite with them, security is very important for web hosters. One serious mistake could cost them their business. Remember, you will usually end up on a virtual host so if you get hacked every other domain on the host gets hacked. 6 years ago we were hosting 20+ domains on a single linux box. From carroll at tjc.com Wed Dec 24 12:54:20 2003 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 24 12:54:25 2003 Subject: [Tutor] [support@deltawebhosting.com: Re: Python cgi In-Reply-To: <200312240930.37318.shaleh@speakeasy.net> Message-ID: On Wed, 24 Dec 2003, Sean 'Shaleh' Perry wrote: > Do they offer cgi at all? In what languages / ways? If they allow you > to use perl then there is no reason to exclude python. Perl does have a couple advantages over Python here: restricted execution and tainting. -- Terry Carroll Santa Clara, CA carroll@tjc.com From piir at earthlink.net Wed Dec 24 13:21:43 2003 From: piir at earthlink.net (Todd G. Gardner) Date: Wed Dec 24 13:21:47 2003 Subject: [Tutor] TypeError: while constructing argument 4: Message-ID: Hello all, I need to ask for some of your expertise. How to define the variable so that I can pass it as an array of 16 bit integers? ... ni = windll.nidaq32 buffer = c_int * 100 status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, sampleRate) >>> Traceback (most recent call last): File "", line 1, in ? File "C:\Documents and Settings\tnt\My Documents\pc\ctypes\DAQ_Op1.py", line 21, in ? status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, sampleRate) TypeError: while constructing argument 4: Don't know how to convert parameter 4 >>> """ BEGIN DEFINITION of the variable array {buffer} buffer [i16] contains the acquired data buffer is an integer array. buffer has a length equal to or greater than count. When DAQ_Op returns with an error number equal to zero, buffer contains the acquired data. The buffer must be aligned on a 4-byte boundary. If the buffer is allocated as an array of i32s, it must be typecast to an i16 pointer when passing its address to DAQ_Op. If the buffer is allocated as a double-sized array of i16s, the user must check that the buffer is aligned on a 4-byte boundary before passing the buffer to DAQ_Op. END DEFINITION of the variable array {buffer} """ Thank you SO much for any information, Todd -- P.S. Sorry if this is a repost. I am not sure if this was posted before so I am resending it. From alan.gauld at blueyonder.co.uk Wed Dec 24 13:28:52 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 24 13:28:42 2003 Subject: [Tutor] [support@deltawebhosting.com: Re: Python cgi References: <20031224150534.GD19205@purdue.edu> Message-ID: <003001c3ca4b$c849bee0$6401a8c0@xp> > Would someone more experienced make a comment I could pass on to those > guys ;)? Given we don't know what other options they offer its hard to be objective. > > Services" page. Due to higher risk of abuse with python we are not planing > > to include that in our packages, at least not soon. I assume they mean that because Python is easier to use than most other CGI options more people might take advantage of the facility therefore they don't want to risk their server being overloaded, otherwise I can't imagine what they mean? :-) Alan g. From alan.gauld at blueyonder.co.uk Wed Dec 24 13:36:03 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Dec 24 13:35:53 2003 Subject: [Tutor] (no subject) References: Message-ID: <003501c3ca4c$c8ea4f30$6401a8c0@xp> > Also can someone explain lambdas too me. Whenever I do something like: > > x = lambda x: x + 1, (1) > > I get (, 2) Lambdas are explained in my Functional programming page of my tutorial. Basically they are expressions which return function objects. Lets look at your case: x = lambda x: x + 1, (1) Canbe re-written as: x = ( (lambda x: x + 1) , (1) ) So x becomes a tuple of two items, the first being a lamda expression, the second the number 1. The lambda itself is nearly equivalent to: def f(x): return x+1 But has no name 'f'. If we change your expression to: x = lambda x: x+1 (1) # no comma then we assign the return value of the lambda, that is it is equivalent, using our definition of f, to: x = f(1) Alternatively if we just write x = lambda x: x+1 x(1) We have defined x to be the function and evaluated it with 1 as argument. Without knowing what you are trying to do I can't comment further. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Mouseruth at aol.com Wed Dec 24 13:48:19 2003 From: Mouseruth at aol.com (Mouseruth@aol.com) Date: Wed Dec 24 13:48:30 2003 Subject: [Tutor] UDP problem Message-ID: <146.1f3e01bc.2d1b3973@aol.com> Hi all, I'm trying to learn about UDP socket programming. I have 2 questions - firstly, is it possible to make receiving data event driven (like in VB) - i.e. when data arrives, something automatically happens. Secondly, when receiving data, is there any way to tell the size of the data or even if the data exists at all, before trying to receive it? Trying to receive nonexistent data freezes my IDLE up. I'm on Win98 SE. Can anybody help? Thanks, James Morgan From shaleh at speakeasy.net Wed Dec 24 15:21:02 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Wed Dec 24 15:21:18 2003 Subject: [Tutor] [support@deltawebhosting.com: Re: Python cgi In-Reply-To: References: Message-ID: <200312241221.02211.shaleh@speakeasy.net> On Wednesday 24 December 2003 09:54, Terry Carroll wrote: > On Wed, 24 Dec 2003, Sean 'Shaleh' Perry wrote: > > Do they offer cgi at all? In what languages / ways? If they allow you > > to use perl then there is no reason to exclude python. > > Perl does have a couple advantages over Python here: restricted execution > and tainting. once could argue perl needs those features (-: From shaleh at speakeasy.net Wed Dec 24 15:21:57 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Wed Dec 24 15:22:20 2003 Subject: [Tutor] UDP problem In-Reply-To: <146.1f3e01bc.2d1b3973@aol.com> References: <146.1f3e01bc.2d1b3973@aol.com> Message-ID: <200312241221.57574.shaleh@speakeasy.net> On Wednesday 24 December 2003 10:48, Mouseruth@aol.com wrote: > Hi all, > I'm trying to learn about UDP socket programming. I have 2 questions - > firstly, is it possible to make receiving data event driven (like in VB) - > i.e. when data arrives, something automatically happens. Secondly, when > receiving data, is there any way to tell the size of the data or even if > the data exists at all, before trying to receive it? Trying to receive > nonexistent data freezes my IDLE up. I'm on Win98 SE. Can anybody help? > Thanks, > see twisted python, lots of cool networking code and examples. Quick websearch should find it. From clay at shirky.com Wed Dec 24 16:08:20 2003 From: clay at shirky.com (Clay Shirky) Date: Wed Dec 24 16:08:29 2003 Subject: [Tutor] EOF error with pickle? In-Reply-To: Message-ID: > On Wed, 24 Dec 2003, Clay Shirky wrote: > >> Here's the test script I wrote to reproduce the error: >> >> import pickle >> test_list = range(100) >> >> f = open("pickle.dat", 'w') >> pickle.dump(test_list, f) >> print "dumped..." # this works > > f.close() D'oh! Thanks. I always find that the stupidest python errors I make are when I'm thinking perlishly -- I expected the second open to auto-close the file first. Explicit is better than implicit -- maybe I should put a big "WWPD?"* sign over my desk. -clay * What Wouldn't Perl Do? From dyoo at hkn.eecs.berkeley.edu Wed Dec 24 18:36:44 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 24 18:36:48 2003 Subject: [Tutor] Re: EOF error with pickle? In-Reply-To: Message-ID: > >I'm trying to use pickle to store some nested lists. The program writes to > >the output file fine, but when I read the same file as input, I get an EOF > >error. > > > >Here's the test script I wrote to reproduce the error: > > > >import pickle > >test_list = range(100) > > > >f = open("pickle.dat", 'w') > >pickle.dump(test_list, f) > >print "dumped..." # this works [some text cut] > You need to close the file and reopen it. > > Otherwise, I think the file pointer is still pointing to the end of the > file. The fix is correct, but the reason it works needs clarification. Doing close() on a file that we're writting is a necessity because file writes are 'buffered', and our operating system may not immediately write the bytes to disk till it feels it's worth it to flush the buffer. The documentation on write() mentions this buffering behavior: http://www.python.org/doc/lib/bltin-file-objects.html With that, that 'EOFError' should make more sense now --- the file probably contained was cut off in "mid-sentence", and the pickle.load() expected to see more bytes out the file. Hope this helps! From missive at hotmail.com Wed Dec 24 22:34:02 2003 From: missive at hotmail.com (Lee Harr) Date: Wed Dec 24 22:34:09 2003 Subject: [Tutor] Re: EOF error with pickle? Message-ID: >>You need to close the file and reopen it. >> >>Otherwise, I think the file pointer is still pointing to the end of the >>file. > > >The fix is correct, but the reason it works needs clarification. > >Doing close() on a file that we're writting is a necessity because file >writes are 'buffered', and our operating system may not immediately write >the bytes to disk till it feels it's worth it to flush the buffer. Sure enough. Looks like you may not even need to close the file ... >>>import pickle >>>l = range(100) >>>f = file('temp', 'w') >>>pickle.dump(l, f) >>>f.flush() >>>g = file('temp') >>>l2 = pickle.load(g) >>>l2 [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, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] >>>l3 = range(0, 10, 2) >>>pickle.dump(l3, f) >>>f.flush() >>>l4 = pickle.load(g) >>>l4 [0, 2, 4, 6, 8] Although I am not sure how good an idea that would be. _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From dyoo at hkn.eecs.berkeley.edu Wed Dec 24 22:56:42 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 24 22:56:49 2003 Subject: [Tutor] TypeError: while constructing argument 4: In-Reply-To: Message-ID: On Wed, 24 Dec 2003, Todd G. Gardner wrote: > Hello all, > > I need to ask for some of your expertise. How to define the variable so > that I can pass it as an array of 16 bit integers? > > ... > ni = windll.nidaq32 > buffer = c_int * 100 > status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, sampleRate) Hi Toddy, I can't test this, but perhaps something from the 'array' module might work: http://www.python.org/doc/lib/module-array.html It sounds like it, as the reference to 'i16' in the documentation: > """ > BEGIN DEFINITION of the variable array {buffer} > buffer [i16] contains the acquired data > matches the type code definition 'i' in the 'array' documenation. You should be able to say something like: ### >>> import array >>> buffer = array.array('i', [0] * 100) ### to initialize an array for 100 16-bit signed integers. I'm not not sure, though, if this buffer can be passed into windll.nidaq32.DAQ_Op. You may want to ask your question on the Python-Win32 list, since the folks there may know more about what the windll functions expect. You can contact the Python-win32 list here: http://mail.python.org/mailman/listinfo/python-win32 Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Dec 24 23:00:50 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 24 23:00:54 2003 Subject: [Tutor] TypeError: while constructing argument 4: In-Reply-To: Message-ID: > > > > ... > > ni = windll.nidaq32 > > buffer = c_int * 100 > > status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, sampleRate) > > Hi Toddy, ^^^^^ Doh! I'm sorry Todd; I don't know how that extra 'y' got appended there. I'm not used to typing on a laptop, but it's still a lame excuse for getting your name wrong. *grin* From carroll at tjc.com Wed Dec 24 23:55:31 2003 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 24 23:55:36 2003 Subject: [Tutor] EOF error with pickle? In-Reply-To: Message-ID: On Wed, 24 Dec 2003, Clay Shirky wrote: > I always find that the stupidest python errors I make are when I'm thinking > perlishly -- I expected the second open to auto-close the file first. Perl will do that? If you open a new file object, it will auto-close a different file object that refers to the same file? That strikes me as fiendishly unexpected. -- Terry Carroll Santa Clara, CA carroll@tjc.com From alan.gauld at blueyonder.co.uk Thu Dec 25 05:38:03 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Dec 25 05:37:43 2003 Subject: [Tutor] [support@deltawebhosting.com: Re: Python cgi References: Message-ID: <008f01c3cad3$2cd59190$6401a8c0@xp> > > Do they offer cgi at all? In what languages / ways? If they allow you > > to use perl then there is no reason to exclude python. > > Perl does have a couple advantages over Python here: restricted execution > and tainting. Python has a restricted execution mode, how does it differ from Perl's? And what is tainting? I've never heard of that before? Alan G. From carroll at tjc.com Thu Dec 25 10:01:17 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 25 10:01:25 2003 Subject: [Tutor] [support@deltawebhosting.com: Re: Python cgi In-Reply-To: <008f01c3cad3$2cd59190$6401a8c0@xp> Message-ID: On Thu, 25 Dec 2003, Alan Gauld wrote: > Python has a restricted execution mode, how does it differ from > Perl's? Python doesn't have restricted execution any longer, does it? My understanding is that it wasn't really robust and could be circumvented, and it was dropped in 2.3. > And what is tainting? I've never heard of that before? Perl has a "taint" mode, in which variables can be classified as secure or insecure ("tainted"), based on whther their content comes, directly or indirectly, from user input. In this mode, a tainted variable cannot be used in any statement that modifies a file or process. So, if Python had a taint mode, it would work something like this: name=raw_input("enter your name") # name is tainted filein = name + ".input" # filein is also tainted fileout = name + ".output" # as is fileout print "Hello, %s, your info will be taken from %s and will be saved to %s" % (name, filename) # okay, even with tainted variables f_in=open(filein,"r") # okay; although filein is tainted, # this is a read-only file operation f_out=open(fileout,"w") # exception; operation on a file that # modifies it, using tainted variable # fileout -- Terry Carroll Santa Clara, CA carroll@tjc.com From dyoo at hkn.eecs.berkeley.edu Thu Dec 25 14:27:13 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 25 14:27:26 2003 Subject: [Tutor] [support@deltawebhosting.com: Re: Python cgi In-Reply-To: Message-ID: > Perl has a "taint" mode, in which variables can be classified as secure or > insecure ("tainted"), based on whther their content comes, directly or > indirectly, from user input. In this mode, a tainted variable cannot be > used in any statement that modifies a file or process. There's some good information on Perl's 'taint' mode here: http://www.w3.org/Security/faq/wwwsf4.html#CGI-Q15 http://gunther.web66.com/FAQS/taintmode.html It is a Python feature request (feature request #500698), so there's a possibility that that Python might adopt this concept some day. https://sourceforge.net/tracker/?func=detail&atid=355470&aid=500698&group_id=5470 Happy holidays! From hcohen2 at comcast.net Sat Dec 27 13:19:59 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 13:21:10 2003 Subject: [Tutor] Dumb question on emacs and python ... Message-ID: <3FEDCD4F.1000608@comcast.net> I have had a considerable amount of problems trying to get a python script to execute. In this instance, I essentially copied the file from a disc to a newly named file for my editing. Nothing has worked, then I noticed the reserved words were not color coded or highlighted. The files have exactly the same attributes read and execute for owner, group and public. What have I encountered, or what stupid thing am I doing? I am running under Mandrake Linux 9.1 and using Python ver.: 2.2.2 TIA PS While bash under Linux is in many respects easier to use than the Kohn shell on UNIX, I am finding that actions I perform on emacs on UNIX do not work on Linux, e.g. typing into a hightlighted (selected) region does not delete that region under Linux. From marilyn at deliberate.com Sat Dec 27 13:27:53 2003 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Dec 27 13:27:59 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <3FEDCD4F.1000608@comcast.net> Message-ID: On Sat, 27 Dec 2003, hcohen2 wrote: > I have had a considerable amount of problems trying to get a python > script to execute. > > In this instance, I essentially copied the file from a disc to a newly > named file for my editing. Nothing has worked, then I noticed the > reserved words were not color coded or highlighted. What is the name of the file? It needs to be something.py for emacs to know what to do. > > The files have exactly the same attributes read and execute for owner, > group and public. > > What have I encountered, or what stupid thing am I doing? > > I am running under Mandrake Linux 9.1 and using Python ver.: 2.2.2 > > TIA > > PS While bash under Linux is in many respects easier to use than the > Kohn shell on UNIX, I am finding that actions I perform on emacs on UNIX > do not work on Linux, e.g. typing into a hightlighted (selected) region > does not delete that region under Linux. I don't know about this. I use key-stroke-driven emacs. Good luck. Marilyn Davis > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From amych at mindspring.com Sat Dec 27 13:33:28 2003 From: amych at mindspring.com (Amy Hendrix) Date: Sat Dec 27 13:33:33 2003 Subject: [Tutor] Dumb question on emacs and python ... Message-ID: <27610920.1072550009314.JavaMail.root@wamui03.slb.atl.earthlink.net> -----Original Message----- From: hcohen2 Sent: Dec 27, 2003 1:19 PM To: tutor@python.org Subject: [Tutor] Dumb question on emacs and python ... >The files have exactly the same attributes read and execute for owner, >group and public. Aside from the filename issue that Marilyn suggested, you won't be able to save your edits if you don't have write permission. The highlighting and color-coding are emacs-specific problems and not python ones -- I'm afraid I can't help you there. Best of luck, Amy Hendrix From hcohen2 at comcast.net Sat Dec 27 13:42:40 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 13:43:31 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: References: Message-ID: <3FEDD2A0.6060504@comcast.net> Marilyn Davis wrote: >On Sat, 27 Dec 2003, hcohen2 wrote: > > > >>I have had a considerable amount of problems trying to get a python >>script to execute. >> >>In this instance, I essentially copied the file from a disc to a newly >>named file for my editing. Nothing has worked, then I noticed the >>reserved words were not color coded or highlighted. >> >> > >What is the name of the file? It needs to be something.py for emacs >to know what to do. > > > >>The files have exactly the same attributes read and execute for owner, >>group and public. >> >>What have I encountered, or what stupid thing am I doing? >> >>I am running under Mandrake Linux 9.1 and using Python ver.: 2.2.2 >> >>TIA >> >>PS While bash under Linux is in many respects easier to use than the >>Kohn shell on UNIX, I am finding that actions I perform on emacs on UNIX >>do not work on Linux, e.g. typing into a hightlighted (selected) region >>does not delete that region under Linux. >> >> > >I don't know about this. I use key-stroke-driven emacs. > >Good luck. > >Marilyn Davis > > > > >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > Marilyn, Just added a few more characters to the file name: was fgrepwc.py* to fgrepwc_allcnt.py*. It is code from a Python book: Core Python Programming. When I edit I give myself write rights to the file. The function of the file is simple: count the total number of lines containing the text you are seaching for. That is, really independent of emacs. Thanks From hcohen2 at comcast.net Sat Dec 27 13:47:38 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 13:48:28 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <27610920.1072550009314.JavaMail.root@wamui03.slb.atl.earthlink.net> References: <27610920.1072550009314.JavaMail.root@wamui03.slb.atl.earthlink.net> Message-ID: <3FEDD3CA.4080108@comcast.net> Amy Hendrix wrote: >-----Original Message----- >From: hcohen2 >Sent: Dec 27, 2003 1:19 PM >To: tutor@python.org >Subject: [Tutor] Dumb question on emacs and python ... > > > > >>The files have exactly the same attributes read and execute for owner, >>group and public. >> >> > >Aside from the filename issue that Marilyn suggested, you won't be able to save your edits if you don't have write permission. > >The highlighting and color-coding are emacs-specific problems and not python ones -- I'm afraid I can't help you there. > >Best of luck, >Amy Hendrix > > > Amy, I change to read/write/exec rights prior to editing - I think the color coding and highlighting is significant. When I made errors in coding the color change for a reserved word would not appear and forgetting the ':' causes a failure in the indentation of subsequent lines. In other cases i wrote the files from scratch and have seen both the color and highlighting appear. One copy - with no changes fails to execute using the same command. The only difference is that the file ends with a '1', i.e. fgrepwc.py* -> fgrepwc1.py*. Thanks From marilyn at deliberate.com Sat Dec 27 13:57:31 2003 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Dec 27 13:57:35 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <3FEDD2A0.6060504@comcast.net> Message-ID: On Sat, 27 Dec 2003, hcohen2 wrote: [much deleted] > > > Marilyn, > > Just added a few more characters to the file name: was fgrepwc.py* to > fgrepwc_allcnt.py*. Well, that '*' at the end messes you up. Try subtracting that and maybe emacs will behave for you. Good luck. Marilyn From hcohen2 at comcast.net Sat Dec 27 14:01:47 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 14:02:39 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: References: Message-ID: <3FEDD71B.6010906@comcast.net> Marilyn Davis wrote: >On Sat, 27 Dec 2003, hcohen2 wrote: > >[much deleted] > > > >>Marilyn, >> >>Just added a few more characters to the file name: was fgrepwc.py* to >>fgrepwc_allcnt.py*. >> >> > >Well, that '*' at the end messes you up. Try subtracting that and >maybe emacs will behave for you. > >Good luck. > >Marilyn > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > Marilyn, That's what I thought too, but (repeated it again) openning the file without the '*' yields an empty file. It looks crazy to me too. I guess I am just going to write the file by pasting lines, or typing it in new. The change in appearance and the failure to execute are too strong hints to ignore. Thanks for your help. Herschel From marilyn at deliberate.com Sat Dec 27 14:10:20 2003 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Dec 27 14:10:25 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <3FEDD71B.6010906@comcast.net> Message-ID: On Sat, 27 Dec 2003, hcohen2 wrote: > Marilyn Davis wrote: > > >On Sat, 27 Dec 2003, hcohen2 wrote: > > > >[much deleted] > > > > > > > >>Marilyn, > >> > >>Just added a few more characters to the file name: was fgrepwc.py* to > >>fgrepwc_allcnt.py*. > >> > >> > > > >Well, that '*' at the end messes you up. Try subtracting that and > >maybe emacs will behave for you. > > > >Good luck. > > > >Marilyn > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > Marilyn, > > That's what I thought too, but (repeated it again) openning the file > without the '*' yields an empty file. It looks crazy to me too. > > I guess I am just going to write the file by pasting lines, or typing it > in new. The change in appearance and the failure to execute are too > strong hints to ignore. > > Thanks for your help. I guess I couldn't help. I'm clueless. M. > Herschel > > > -- From neal at bcn.boulder.co.us Sat Dec 27 14:26:03 2003 From: neal at bcn.boulder.co.us (Neal McBurnett) Date: Sat Dec 27 14:26:11 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <3FEDD71B.6010906@comcast.net> References: <3FEDD71B.6010906@comcast.net> Message-ID: <20031227192603.GN1322@feynman> The "*" is a special character used differently in different contexts. To the shell, it is a wildcard, matching anything. In a listing of files (by, e.g. ls), it sometimes is appended to simply indicate that the file is executable. If you're just starting to learn emacs, (or any other editor) I would just suggest it can take a while to pick up some of the quirks. I personally absolutely love emacs and the great power it provides for working on many many types of files. But it does have a learning curve. You may have a file that is actually named fgrepwc_allcnt.py* which can add a lot of problems and confusion as has been noted. running mv 'fgrepwc_allcnt.py*' fgrepwc_allcnt.py will change the name after which you can open it up fresh in emacs. Note the quotes - they cause the * to be treated as a real character. Neal McBurnett http://bcn.boulder.co.us/~neal/ Signed and/or sealed mail encouraged. GPG/PGP Keyid: 2C9EBA60 On Sat, Dec 27, 2003 at 02:01:47PM -0500, hcohen2 wrote: > Marilyn Davis wrote: > >On Sat, 27 Dec 2003, hcohen2 wrote: > >>Marilyn, > >>Just added a few more characters to the file name: was fgrepwc.py* to > >>fgrepwc_allcnt.py*. > > > >Well, that '*' at the end messes you up. Try subtracting that and > >maybe emacs will behave for you. > > That's what I thought too, but (repeated it again) openning the file > without the '*' yields an empty file. It looks crazy to me too. > > I guess I am just going to write the file by pasting lines, or typing it > in new. The change in appearance and the failure to execute are too > strong hints to ignore. > > Thanks for your help. > Herschel From hcohen2 at comcast.net Sat Dec 27 14:58:39 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 14:59:47 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <20031227192603.GN1322@feynman> References: <3FEDD71B.6010906@comcast.net> <20031227192603.GN1322@feynman> Message-ID: <3FEDE46F.3020701@comcast.net> Neal McBurnett wrote: >The "*" is a special character used differently in different contexts. >To the shell, it is a wildcard, matching anything. >In a listing of files (by, e.g. ls), it sometimes is appended to >simply indicate that the file is executable. > >If you're just starting to learn emacs, (or any other editor) I would >just suggest it can take a while to pick up some of the quirks. I >personally absolutely love emacs and the great power it provides for >working on many many types of files. But it does have a learning >curve. > >You may have a file that is actually named > fgrepwc_allcnt.py* >which can add a lot of problems and confusion as has been >noted. > >running > mv 'fgrepwc_allcnt.py*' fgrepwc_allcnt.py >will change the name after which you can open it up fresh in emacs. >Note the quotes - they cause the * to be treated as a real character. > >Neal McBurnett http://bcn.boulder.co.us/~neal/ >Signed and/or sealed mail encouraged. GPG/PGP Keyid: 2C9EBA60 > >On Sat, Dec 27, 2003 at 02:01:47PM -0500, hcohen2 wrote: > > >>Marilyn Davis wrote: >> >> >>>On Sat, 27 Dec 2003, hcohen2 wrote: >>> >>> >>>>Marilyn, >>>>Just added a few more characters to the file name: was fgrepwc.py* to >>>>fgrepwc_allcnt.py*. >>>> >>>> >>>Well, that '*' at the end messes you up. Try subtracting that and >>>maybe emacs will behave for you. >>> >>> >>That's what I thought too, but (repeated it again) openning the file >>without the '*' yields an empty file. It looks crazy to me too. >> >>I guess I am just going to write the file by pasting lines, or typing it >>in new. The change in appearance and the failure to execute are too >>strong hints to ignore. >> >>Thanks for your help. >>Herschel >> >> > > > Neal, Thanks, I am new to emacs only under Linux though I do not regard myself as an expert it is my primary editor and is at least my secondary method of executing SQL against Sybase. Under Linux, I find many of the commands work as I would expect, e.g. the keystrokes ^C^S, ^C^C, ^X-u, etc, but the file names and colors had me thrown. Also as I mentioned I still am disappointed the highlighting a region seems only useful for copying. Well it could be worse, I still have to access UNIX using terminal windows from a Windows system - and each differs, and the laptop that is used for a remote connection does not even support copying. Thanks for your explanations on the file system - I thought it denoted an executable and I opened files dropping it (these were the files I wrote) but this ceased to work with these few copied instances. Herschel From hcohen2 at comcast.net Sat Dec 27 15:09:58 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 15:10:49 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: References: Message-ID: <3FEDE716.6030101@comcast.net> Marilyn Davis wrote: >On Sat, 27 Dec 2003, hcohen2 wrote: > > > >>Marilyn Davis wrote: >> >> >> >>>On Sat, 27 Dec 2003, hcohen2 wrote: >>> >>>[much deleted] >>> >>> >>> >>> >>> >>>>Marilyn, >>>> >>>>Just added a few more characters to the file name: was fgrepwc.py* to >>>>fgrepwc_allcnt.py*. >>>> >>>> >>>> >>>> >>>Well, that '*' at the end messes you up. Try subtracting that and >>>maybe emacs will behave for you. >>> >>>Good luck. >>> >>>Marilyn >>> >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>> >>> >>Marilyn, >> >>That's what I thought too, but (repeated it again) openning the file >>without the '*' yields an empty file. It looks crazy to me too. >> >>I guess I am just going to write the file by pasting lines, or typing it >>in new. The change in appearance and the failure to execute are too >>strong hints to ignore. >> >>Thanks for your help. >> >> > >I guess I couldn't help. I'm clueless. > >M. > > > > >>Herschel >> >> >> >> >> > > > Marilyn, Thanks for trying, just perhaps I was not as stupid as I thought. I will let you know if my suspicions about the color coding and the hightlighting prove to be significant. Perhaps it might save someone else the grief. Herschel From tayiper at volja.net Mon Dec 22 10:18:01 2003 From: tayiper at volja.net (Tadey) Date: Sat Dec 27 15:36:39 2003 Subject: [Tutor] Reinstalling Python might help ... error message Message-ID: <008101c3c89f$02a68a90$f54748d9@mz9s680eu689tz> Hello ... Something very strange started to happen with my Python installation. Soon after starting Python today, some very strange "windows apllication error message" appeared (the one marked with the red sign), saying something like: "an (this and this) application error occured, ... file/key (or something) is missing, ... or is invalid, ... reinstalling Python might help" I am really mad at myself for not making screenshot of that error, cause I ALWAYS archive that kind of stuff to describe problem better. I know, that without knowing true error message text, you can't help me at all (I just assume there was something like "... file/key (or something) is missing"), but I am just interested, if someone has any clue, what kind of error could be that, causing that kind of pop-up window - "... reinstalling Python might help" - cause I am 100 % sure for that part of error message ... Thanks, Tadey -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031222/aa6927fd/attachment.html From BSchultz at innovishealth.com Tue Dec 23 12:34:06 2003 From: BSchultz at innovishealth.com (Schultz, Bob) Date: Sat Dec 27 15:36:46 2003 Subject: [Tutor] Just beginning Message-ID: <0F1B5B95F64F5341BE3B6E5D3D9122EA30F0A0@exchange01.dakcl.com> I am new to programming, but have decided on Python after much researching and reading on the web. My question is this: I have an extra computer that am going to use solely for programming and experimenting. Should I use Linux or windows as my OS or doesn't it matter? Does Python work better on one platform than the other. I am excited to get going! Bob Fargo, ND -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031223/7de2e044/attachment.html From shaleh at speakeasy.net Tue Dec 23 20:15:26 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sat Dec 27 15:36:52 2003 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <200312231715.26160.shaleh@speakeasy.net> On Tuesday 23 December 2003 15:19, arkamir@softhome.net wrote: > Hello, > > I have a question concerning turning strings into variables. > > Say I have a list like x: > > x = ['hello', 'bye'] > > What I need is the final result to look like this, or the equivelant of > this. How would I do this??? > > hello = re.compile(r'') > bye = re.compile(r'') > > I think it would look something like > > for y in x: > #string to variable# = re.compile(r'<--INSERT %s HERE-->' % y) > > Is this the most effecient way, hmm, perhaps I am not fully understanding you, but would this work? transforms = { 'hello': '', 'bye': '' } for y in x: if y in transforms: print transforms[y] If this is not what you meant, how about specifying your needs by giving us some sample input and output? For example if we start with: Hello, World! we should end up with: , World! > and how would I convert y to capitols. >>> name = 'bob' >>> name.title() 'Bob' >>> name.upper() 'BOB' > > Also can someone explain lambdas too me. Whenever I do something like: > in general you should stick to asking one type of question at a time. Makes it easier for people to follow the thread and especially for people searching the archives later on. > x = lambda x: x + 1, (1) > > I get (, 2) > lambda is a way to generate small functions during execution instead of during compilation / parsing. It is used most often for event handlers where the action is usually simple and used once so defining a function would make the program longer or harder to follow. People who like to program in a more functional (instead of OO) style like to use it as well. For instance: for word in map(lambda y: y.upper(), x): # re-use you list from above print word Current python uses a different idiom: for word in [ y.upper() for y in x ]: print word You can write plenty of python and never use lambda. Especially with python 2.2 and newer. From shaleh at speakeasy.net Tue Dec 23 20:17:24 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sat Dec 27 15:36:57 2003 Subject: [Tutor] back from nowhere Message-ID: <200312231717.24975.shaleh@speakeasy.net> Hey all, life got hectic for a bit so I stayed away from my Net attachments for a while. I will still be a slow contributor for a while, but I am back. From akshay at sarathi.ncst.ernet.in Thu Dec 25 23:43:08 2003 From: akshay at sarathi.ncst.ernet.in (Akshay Thapliyal) Date: Sat Dec 27 15:37:03 2003 Subject: [Tutor] cgi-ssl programming Message-ID: <3FEBBC5C.4080708@sarathi.ncst.ernet.in> Hello. Im a novice at python looking at implementing someting in cgi.I have apache with mod-ssl. I wanted to use python for the server side scripting. I havent been able to find out how to use ssl decryption. Could someone please point out some web resources for the same. Thanks, Akshay. From hcohen2 at comcast.net Sat Dec 27 15:38:22 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 15:39:13 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <20031227192603.GN1322@feynman> References: <3FEDD71B.6010906@comcast.net> <20031227192603.GN1322@feynman> Message-ID: <3FEDEDBE.80109@comcast.net> Neal McBurnett wrote: >The "*" is a special character used differently in different contexts. >To the shell, it is a wildcard, matching anything. >In a listing of files (by, e.g. ls), it sometimes is appended to >simply indicate that the file is executable. > >If you're just starting to learn emacs, (or any other editor) I would >just suggest it can take a while to pick up some of the quirks. I >personally absolutely love emacs and the great power it provides for >working on many many types of files. But it does have a learning >curve. > >You may have a file that is actually named > fgrepwc_allcnt.py* >which can add a lot of problems and confusion as has been >noted. > >running > mv 'fgrepwc_allcnt.py*' fgrepwc_allcnt.py >will change the name after which you can open it up fresh in emacs. >Note the quotes - they cause the * to be treated as a real character. > >Neal McBurnett http://bcn.boulder.co.us/~neal/ >Signed and/or sealed mail encouraged. GPG/PGP Keyid: 2C9EBA60 > >On Sat, Dec 27, 2003 at 02:01:47PM -0500, hcohen2 wrote: > > >>Marilyn Davis wrote: >> >> >>>On Sat, 27 Dec 2003, hcohen2 wrote: >>> >>> >>>>Marilyn, >>>>Just added a few more characters to the file name: was fgrepwc.py* to >>>>fgrepwc_allcnt.py*. >>>> >>>> >>>Well, that '*' at the end messes you up. Try subtracting that and >>>maybe emacs will behave for you. >>> >>> >>That's what I thought too, but (repeated it again) openning the file >>without the '*' yields an empty file. It looks crazy to me too. >> >>I guess I am just going to write the file by pasting lines, or typing it >>in new. The change in appearance and the failure to execute are too >>strong hints to ignore. >> >>Thanks for your help. >>Herschel >> >> > > > Well the copying instructions worked with the new file showing the expected color coding. Moreover, it attempts to execute, but is probably hung is a bit of flawed loop code (mine). Now I can concentrate on trying to get it right! Thanks to everyone. From dyoo at hkn.eecs.berkeley.edu Sat Dec 27 15:50:29 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 27 15:50:34 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <3FEDE716.6030101@comcast.net> Message-ID: > >>That's what I thought too, but (repeated it again) openning the file > >>without the '*' yields an empty file. It looks crazy to me too. > >> > >>I guess I am just going to write the file by pasting lines, or typing > >>it in new. The change in appearance and the failure to execute are > >>too strong hints to ignore. Hello! Ok, I think we're flailing about a bit too much here. *grin* Let's make sure we all understand what the problem is. Can you show us what happens if you type: ### $ ls -l fgrepwc_allcnt.py ### at your command line prompt? And what happens if you type: ### $ ls -l fgrepwc_allcnt.py* ### Are the outputs of these two shell commands different? Once we see those outputs, we'll be more sure if the file name has anything to do with the problem. Emacs, by default, may not support Python out of the box! You may actually need to install 'python-mode' to let your Emacs text editor to recognize Python's syntax. We can find instructions on enabling python-mode here: http://www.python.org/cgi-bin/moinmoin/EmacsEditor There can be several possiblities why Emacs isn't treating your source file nicely. Let's eliminate each possibility first. We can first check to see if python-mode actually works in emacs: can you actually go into python-mode from the '*scratch*' emacs buffer? What happens if you do a 'M-x python-mode' from emacs? Do you see a change in the status line? Or do you get an error message? Installation problems are always a bit tricky and frustrating, because the cause of the problem is probably something really stupid. *grin* Let's see if we can fix this one quickly so you can start doing more interesting things. Good luck to you! From alan.gauld at blueyonder.co.uk Sat Dec 27 15:55:39 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 27 15:54:37 2003 Subject: [Tutor] Dumb question on emacs and python ... References: <3FEDD71B.6010906@comcast.net> <20031227192603.GN1322@feynman> <3FEDE46F.3020701@comcast.net> Message-ID: <014f01c3ccbb$c8fd25d0$6401a8c0@xp> > Thanks, I am new to emacs only under Linux though I do not regard myself > as an expert it is my primary editor and is at least my secondary method > of executing SQL against Sybase. > > Under Linux, I find many of the commands work as I would expect, e.g. > the keystrokes ^C^S, ^C^C, ^X-u, etc, but the file names and colors had > me thrown. Also as I mentioned I still am disappointed the highlighting > a region seems only useful for copying. These are all controlled by a combination of the system .emacs and your personal .emacs files. It sounds like you are seeing vanilla emacs behaviour, try copying your .emacs file from your UNIX system to your Linux system - you may get lots of errors though as the file paths may well be different... Remember and male a copy of the current Linux version first! Compare the diffeences and you should see the lines you need to modify to restore your favoured mode of working. OTOH I stopped using real emacs when I moved to NT, a long time ago now... Alan G. From bgailer at alum.rpi.edu Sat Dec 27 15:58:28 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Dec 27 15:58:37 2003 Subject: [Tutor] Just beginning In-Reply-To: <0F1B5B95F64F5341BE3B6E5D3D9122EA30F0A0@exchange01.dakcl.co m> References: <0F1B5B95F64F5341BE3B6E5D3D9122EA30F0A0@exchange01.dakcl.com> Message-ID: <6.0.0.22.0.20031227135555.04010b18@mail.mric.net> Skipped content of type multipart/alternative-------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.556 / Virus Database: 348 - Release Date: 12/26/2003 From dyoo at hkn.eecs.berkeley.edu Sat Dec 27 16:00:32 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 27 16:00:37 2003 Subject: [Tutor] Just beginning In-Reply-To: <0F1B5B95F64F5341BE3B6E5D3D9122EA30F0A0@exchange01.dakcl.com> Message-ID: On Tue, 23 Dec 2003, Schultz, Bob wrote: > I am new to programming, but have decided on Python after much > researching and reading on the web. Hi Bob, welcome aboard! > My question is this: I have an extra computer that am going to use > solely for programming and experimenting. Should I use Linux or windows > as my OS or doesn't it matter? Does Python work better on one platform > than the other. I am excited to get going! Python works well on both Windows and Linux. I'd recommend using whatever platform you are most familiar with --- Python as a language is platform agnostic. We'll try to point you toward good resources for exploring Python. Have you had a chance to see: http://python.org/topics/learn/ yet? It has links to a lot of good Python tutorials, and it should help you find out more about the language. As you're learning Python, please feel free to bring up your questions on tutor@python.org --- all of us here will be happy to chat with you about Python. Don't worry if the questions seem 'silly' --- we're all 'newbies' here, in one form or another. *grin* By the way, as you're posting questions on Python-Tutor, if you are getting messages about 'Moderator need to check your message...' or something like that, that is because you need to subscribe to the mailing list. We're restricting posting privileges to subscribers only, as a spam-filtering measure. You can find details about subscription here: http://mail.python.org/mailman/listinfo/tutor Good luck to you! From marilyn at deliberate.com Sat Dec 27 16:12:22 2003 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Dec 27 16:12:28 2003 Subject: [Tutor] Just beginning In-Reply-To: Message-ID: On Sat, 27 Dec 2003, Danny Yoo wrote: > > > On Tue, 23 Dec 2003, Schultz, Bob wrote: > > > I am new to programming, but have decided on Python after much > > researching and reading on the web. > > Hi Bob, welcome aboard! > > > > My question is this: I have an extra computer that am going to use > > solely for programming and experimenting. Should I use Linux or windows > > as my OS or doesn't it matter? Does Python work better on one platform > > than the other. I am excited to get going! > > Python works well on both Windows and Linux. I'd recommend using whatever > platform you are most familiar with --- Python as a language is platform > agnostic. What about the development environment? Do you have a recommendation there? I found idle difficult to install on Linux. Is it easier on Windows? I like emacs for development, but emacs has a learning curve. I spent some time trying to use the debugging feature in idle, but didn't do very well. That was a year ago so maybe the new release is better? If you have any hints about these things, I'd be grateful. Thank you. Marilyn Davis > > We'll try to point you toward good resources for exploring Python. Have > you had a chance to see: > > http://python.org/topics/learn/ > > yet? It has links to a lot of good Python tutorials, and it should help > you find out more about the language. > > > As you're learning Python, please feel free to bring up your questions on > tutor@python.org --- all of us here will be happy to chat with you about > Python. Don't worry if the questions seem 'silly' --- we're all 'newbies' > here, in one form or another. *grin* > > > By the way, as you're posting questions on Python-Tutor, if you are > getting messages about 'Moderator need to check your message...' or > something like that, that is because you need to subscribe to the mailing > list. We're restricting posting privileges to subscribers only, as a > spam-filtering measure. > > You can find details about subscription here: > > http://mail.python.org/mailman/listinfo/tutor > > > Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From dyoo at hkn.eecs.berkeley.edu Sat Dec 27 16:19:27 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 27 16:19:32 2003 Subject: [Tutor] Just beginning In-Reply-To: Message-ID: On Sat, 27 Dec 2003, Danny Yoo wrote: > On Tue, 23 Dec 2003, Schultz, Bob wrote: > > > I am new to programming, but have decided on Python after much > > researching and reading on the web. > > Hi Bob, welcome aboard! Well, this is depressing --- Bob's email address isn't correct --- it appears to be bouncing now. Is there any way we can get this information to him? From missive at hotmail.com Sat Dec 27 17:42:46 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Dec 27 17:42:51 2003 Subject: [Tutor] Re: cgi-ssl programming Message-ID: >Im a novice at python looking at implementing someting in cgi.I have >apache with mod-ssl. I wanted to use python for the server side >scripting. I havent been able to find out how to use ssl decryption. >Could someone please point out some web resources for the same. I think using ssl is really orthogonal to using cgi. By the time any data gets to your cgi script mod_ssl should already have everything decrypted for you. You may need to modify your httpd.conf to allow execution of scripts, and I believe there is a special section of the file relating to ssl access. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From hcohen2 at comcast.net Sat Dec 27 18:22:24 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 18:23:16 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: References: Message-ID: <3FEE1430.10300@comcast.net> Danny Yoo wrote: >>>>That's what I thought too, but (repeated it again) openning the file >>>>without the '*' yields an empty file. It looks crazy to me too. >>>> >>>>I guess I am just going to write the file by pasting lines, or typing >>>>it in new. The change in appearance and the failure to execute are >>>>too strong hints to ignore. >>>> >>>> > >Hello! > >Ok, I think we're flailing about a bit too much here. *grin* Let's make >sure we all understand what the problem is. > >Can you show us what happens if you type: > >### >$ ls -l fgrepwc_allcnt.py >### > >at your command line prompt? And what happens if you type: > >### >$ ls -l fgrepwc_allcnt.py* >### > >Are the outputs of these two shell commands different? Once we see those >outputs, we'll be more sure if the file name has anything to do with the >problem. > > >Emacs, by default, may not support Python out of the box! You may >actually need to install 'python-mode' to let your Emacs text editor to >recognize Python's syntax. We can find instructions on enabling >python-mode here: > > http://www.python.org/cgi-bin/moinmoin/EmacsEditor > >There can be several possiblities why Emacs isn't treating your source >file nicely. Let's eliminate each possibility first. We can first check >to see if python-mode actually works in emacs: can you actually go into >python-mode from the '*scratch*' emacs buffer? What happens if you do a >'M-x python-mode' from emacs? Do you see a change in the status line? >Or do you get an error message? > > >Installation problems are always a bit tricky and frustrating, because the >cause of the problem is probably something really stupid. *grin* Let's >see if we can fix this one quickly so you can start doing more interesting >things. > >Good luck to you! > > > > Dan, Where were you before I went to dinner? ;-) Did not bother to check, upon my return - played with my code a bit more and it is running and counting multiple instances of match text strings along the same line. Ugly code, however. I have another problem if you are willing to humor me: tell me about getopt and how this can be used to see lower or mixed case matches. I am confused by the documentation I found through the python.org site. It seems to imply that the gnu getopt is unlike the one in UNIX and may not work in the same manner. Moreover, I cannot see how any of the options are of any use to me for this problem. I was right about the lack of color coding of the code was significant, though I have no idea how the simple cp command so altered the file. Thanks, Herschel From tim at johnsons-web.com Sat Dec 27 18:29:26 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Sat Dec 27 18:28:14 2003 Subject: [Tutor] Just beginning In-Reply-To: References: Message-ID: <20031227232926.GK1263@johnsons-web.com> * Marilyn Davis [031227 12:25]: > > What about the development environment? Do you have a recommendation > there? > > I found idle difficult to install on Linux. Is it easier on Windows? Hi Marilyn: I've had problems with idle on linux myself. The pythonwin environment for windows is very nice, though. > I like emacs for development, but emacs has a learning curve. I use vim extensively (on linux) for python. Vim has many plugin features available, however, they are of adhoc natures. On the other hand Xemacs comes with a python mode already installed. It has the additional feature of being able to run the interpreter as an inferior process. Python mode for either Lucid emacs or GNU emacs is very mature. Vim's my preference, but I'm learning xemacs too, for python. (X)emacs also has an Object Browser 'plugin' available, but I have not experimented with it much. I've taken the time to learn emacs because of extendability, which I believe that I will eventually find the time worthwhile. Caution: vimmers and emacs-heads can have near-religious adherences to the respective editors. > I spent some time trying to use the debugging feature in idle, but > didn't do very well. That was a year ago so maybe the new release is > better? > If you have any hints about these things, I'd be grateful. The last time we interviewed for another programmer, the candidate talked at length about the debuggers that he was familiar with. We didn't hire him. We consider debugger abuse a chronic condition. Seriously, my debugger kit consists of a keystroke macro to insert print stubs and a try/except block construct for sys.exit() I also recommend Alan Gauld's Book. Tim > Thank you. > > Marilyn Davis > > > > > We'll try to point you toward good resources for exploring Python. Have > > you had a chance to see: > > > > http://python.org/topics/learn/ > > > > yet? It has links to a lot of good Python tutorials, and it should help > > you find out more about the language. > > > > > > As you're learning Python, please feel free to bring up your questions on > > tutor@python.org --- all of us here will be happy to chat with you about > > Python. Don't worry if the questions seem 'silly' --- we're all 'newbies' > > here, in one form or another. *grin* > > > > > > By the way, as you're posting questions on Python-Tutor, if you are > > getting messages about 'Moderator need to check your message...' or > > something like that, that is because you need to subscribe to the mailing > > list. We're restricting posting privileges to subscribers only, as a > > spam-filtering measure. > > > > You can find details about subscription here: > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > Good luck to you! > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From hcohen2 at comcast.net Sat Dec 27 18:31:19 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sat Dec 27 18:32:11 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <014f01c3ccbb$c8fd25d0$6401a8c0@xp> References: <3FEDD71B.6010906@comcast.net> <20031227192603.GN1322@feynman> <3FEDE46F.3020701@comcast.net> <014f01c3ccbb$c8fd25d0$6401a8c0@xp> Message-ID: <3FEE1647.5020401@comcast.net> Alan Gauld wrote: >>Thanks, I am new to emacs only under Linux though I do not regard >> >> >myself > > >>as an expert it is my primary editor and is at least my secondary >> >> >method > > >>of executing SQL against Sybase. >> >>Under Linux, I find many of the commands work as I would expect, >> >> >e.g. > > >>the keystrokes ^C^S, ^C^C, ^X-u, etc, but the file names and colors >> >> >had > > >>me thrown. Also as I mentioned I still am disappointed the >> >> >highlighting > > >>a region seems only useful for copying. >> >> > >These are all controlled by a combination of the system .emacs >and your personal .emacs files. It sounds like you are seeing >vanilla emacs behaviour, try copying your .emacs file from your >UNIX system to your Linux system - you may get lots of errors >though as the file paths may well be different... > >Remember and male a copy of the current Linux version first! >Compare the diffeences and you should see the lines you need >to modify to restore your favoured mode of working. > >OTOH I stopped using real emacs when I moved to NT, a long time >ago now... > >Alan G. > > > > Alan, You are right about the .emacs file - it was a pain setting up my UNIX environment and customizing it. Even began to study lisp to see what I had to do - but luckily I found that was not really necessary. Odd - NT when I first started using NT-4 seriously back in '99 I was fairly impressed until queries stopped working for not reason and garbage results were generated shortly after getting good data sets. Learned to reboot at least once a week, since then run into many other problems. So much so, that so far XP seems superior on a corporate desktop. System works better with UNIX too. I try to use UNIX and Linux as much as possible, even when it sometimes seems easier to use the tools available under Windows. When I get a bit further with python I will be checking the emacs configuration file. Herschel From alan.gauld at blueyonder.co.uk Sat Dec 27 18:45:18 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 27 18:45:15 2003 Subject: [Tutor] Dumb question on emacs and python ... References: <3FEDD71B.6010906@comcast.net> <20031227192603.GN1322@feynman> <3FEDE46F.3020701@comcast.net> <014f01c3ccbb$c8fd25d0$6401a8c0@xp> <3FEE1647.5020401@comcast.net> Message-ID: <015601c3ccd3$7bdfb4d0$6401a8c0@xp> > Odd - NT when I first started using NT-4 seriously back in '99 I was > fairly impressed until queries stopped working for not reason Sounds like NT :-( I don;t use it because I like it, I use it because I have to. Actually Win2000 is much better than NT4 and XP is what I use at home. But the key to all of them for me is cygwin, I'd go mad without it. > I try to use UNIX and Linux as much as possible, even when it sometimes > seems easier to use the tools available under Windows. I used Linux from 1993 (v 0.9) to 2002 as my server at home but then I bought a Mac iBook with OS X. By comparison Linux is clunky and horrid and as soon as I can afford and justify it I will be moving my server to a Mac... Alan G. From alan.gauld at blueyonder.co.uk Sat Dec 27 18:50:18 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Dec 27 18:50:15 2003 Subject: [Tutor] Just beginning References: <0F1B5B95F64F5341BE3B6E5D3D9122EA30F0A0@exchange01.dakcl.com> Message-ID: <016c01c3ccd4$2eb80210$6401a8c0@xp> > going to use solely for programming and experimenting. If thats the main focus use whatever OS you are most familiar with, learning one thing at a time will make for less headaches. > Should I use Linux or windows as my OS or doesn't it matter? But if you already use Linux and Windows I'd opt for Linux because the integration of Python and Linux is much easier and more direct and the tools on Linux are far more powerful (unless you have cygwin installed) for working with source code. Also Linux is an experimenters wonderland you can change just about anything if you want to and know (or figure out) how. Windows (2000 or XP) are OK for programming on but they are not as amenable to exploration. XP or Linux should be sufficiently reliable for that not to be a major issue. Python works fine on all of them but the integration with Linux OS is easier to use IMHO. 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 Sat Dec 27 21:06:47 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 27 21:06:52 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: <3FEE1430.10300@comcast.net> Message-ID: > I have another problem if you are willing to humor me: tell me about > getopt and how this can be used to see lower or mixed case matches. I > am confused by the documentation I found through the python.org site. > It seems to imply that the gnu getopt is unlike the one in UNIX and may > not work in the same manner. Hi Herschel, 'getopt' is actually a little dated --- if you're trying to read option flags from the command line, you may want to use the 'optparse' module instead: http://www.python.org/doc/lib/module-optparse.html > Moreover, I cannot see how any of the options are of any use to me for > this problem. Hmmm... What kind of problem are you trying to solve? >From your previous question, it sounded like you were trying to write a 'grep' string searching program. If so, you may want to look at the regular expression library ('re'): http://www.python.org/doc/lib/module-re.html A.M. Kuckling has written a small "howto" tutorial on regular expressions that you may find useful: http://www.amk.ca/python/howto/regex/ The option parsing libraries are meant to be used when we want to define what kind of flags the user can set for us at the command line. In our last email, I asked if you could do this at the command line: ls -l some_filename If we were to write our own version of th 'ls' command, then an option parsing library would be responsible for looking at that '-l' section and tell us that the user's requesting a "long" output. So optparse/getopt is a command-line user interface thing. Are you trying to parse command line arguments? Tell us more about the problem you're trying to solve. > I was right about the lack of color coding of the code was significant, > though I have no idea how the simple cp command so altered the file. >From reading the thread, my best guess at the moment was that your file had a literal asterisk at the end of the filename. The file extension of your program, then, was perhaps literally something like: .py* There's a section in your .emacs configuration that tells Emacs the file extensions it should use to detect Python source files. That extension is '.py', not '.py*', so renaming the file to have no asterisk fixed the problem, and allowed Emacs to recognize the file as Python source code. (In any case, having an asterisk in there is probably a bad idea in Unix, because the shell treats unescaped asterisks as 'globbing' metacharacters that can stand for anything.) Anyway, I hope this helps! Please feel free to ask more questions. From arkamir at softhome.net Sat Dec 27 15:35:05 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Sun Dec 28 14:19:21 2003 Subject: [Tutor] lambdas Message-ID: <1072557305.7361.6.camel@quercus> How do you make a lambda expression that returns the time?? I got this >>> lambda time: '%s-%s-%s: %s.%s:%s' % (time[0], time[1], time[2], time[3], time[4], time[5], time[6]), (time.localtime(time.time())) which returns this, which is not what I want. ( at 0x8a2791c>, (2003, 12, 27, 12, 30, 20, 5, 361, 0)) i need something like 2003-15-03 1.45:45 How would I do this?? Also how do I get rid of this part: at 0x8a2791c> because i get an error message(too many arguements) when passing it to a function like this: def test(hello): print hello From carroll at tjc.com Sun Dec 28 16:17:19 2003 From: carroll at tjc.com (Terry Carroll) Date: Sun Dec 28 16:17:24 2003 Subject: [Tutor] lambdas In-Reply-To: <1072557305.7361.6.camel@quercus> Message-ID: On Sat, 27 Dec 2003, Conrad Koziol wrote: > How do you make a lambda expression that returns the time?? > > I got this > > >>> lambda time: '%s-%s-%s: %s.%s:%s' % (time[0], time[1], time[2], > time[3], time[4], time[5], time[6]), (time.localtime(time.time())) > > which returns this, which is not what I want. > > ( at 0x8a2791c>, (2003, 12, 27, 12, 30, 20, 5, 361, > 0)) > > i need something like 2003-15-03 1.45:45 I'm not sure you want lambda here. What's your context? You can get the string you want like this, without resorting to lambda: >>> import time >>> '%s-%s-%s: %s.%s:%s' % time.localtime()[0:6] '2003-12-28: 13.15:12' [Aside: did you want the time part in form 13.15:12 or 13:15:12?] -- Terry Carroll Santa Clara, CA carroll@tjc.com From sigurd at 12move.de Sun Dec 28 16:31:22 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sun Dec 28 16:36:49 2003 Subject: [Tutor] lambdas In-Reply-To: <1072557305.7361.6.camel@quercus> (Conrad Koziol's message of "Sat, 27 Dec 2003 12:35:05 -0800") References: <1072557305.7361.6.camel@quercus> Message-ID: On 27 Dec 2003, Conrad Koziol <- arkamir@softhome.net wrote: > How do you make a lambda expression that returns the time?? Would you mind telling us why you want something like that in Python? Lambda expressions in Python are very weak (sadly). > I got this >>>> lambda time: '%s-%s-%s: %s.%s:%s' % (time[0], time[1], time[2], > time[3], time[4], time[5], time[6]), (time.localtime(time.time())) > which returns this, which is not what I want. > ( at 0x8a2791c>, (2003, 12, 27, 12, 30, 20, 5, 361, > 0)) This is a tuple of two objects: your lambda form and the result of (time.localtime(time.time()) (which is another tuple). What you wanted to do (I think) was to call your lambda form with one argument: the output from time.localtime(); you don't need to supply time.time as argument since this is the default. Furthermore your lambda form is buggy (you have six %s on the left side but seven args on the right side. Python won't like that. > i need something like 2003-15-03 1.45:45 But why with a lambda form? And you pick the wrong indices if you wanted such a form. You want year, month, day but if you look at the docstring of time.localtime you will find: ,---- | In [49]: time.localtime? | Type: builtin_function_or_method | Base Class: | String Form: | Namespace: Interactive | Docstring: | localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst) | | Convert seconds since the Epoch to a time tuple expressing local time. | When 'seconds' is not passed in, convert the current time instead. `---- So you need (indices given) 0,2,1,3,4,5 But here an example with lambda (although I don't think it's what you really should do): In [59]: (lambda t: '%s-%s-%s: %s.%s:%s' % (t[0], t[2], t[1], t[3], t[4], t[5]))(time.localtime()) Out[59]: '2003-28-12: 22.9:44' Most of the time I like lambdas but here it seems to me unnecessary ugly. What happens is the creation of the lambda form: (lambda t: '%s-%s-%s: %s.%s:%s' % (t[0], t[2], t[1], t[3], t[4], t[5])) It's enclosed in parentheses so it can be called with an argument. (time.localtime()) This is the argument to the lambda form and it is also written in parentheses like nearly every function you call. Furthermore ugly at the moment is that no minimum field width is given. So seconds aren't written as eg. 09 but 9. But that's easily corrected. In [61]: (lambda t: '%s-%02i-%02i: %02i.%02i:%02i' % (t[0], t[2], t[1], t[3], t[4], t[5]))(time.localtime()) > How would I do this?? Also how do I get rid of this part: see above. > at 0x8a2791c> See above. You didn't create a function and called it with an argument but created a tuple of two objects: your function and the value of the argument given. > because i get an error message(too many arguements) when passing it to a > function like this: > def test(hello): > print hello How do you pass it? Why do you write it so complicated? I hope that's no homework. Karl -- Please do *not* send copies of replies to me. I read the list From hcohen2 at comcast.net Sun Dec 28 17:18:39 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sun Dec 28 17:19:32 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: References: Message-ID: <3FEF56BF.7080902@comcast.net> Danny Yoo wrote: >Hi Herschel, > >'getopt' is actually a little dated --- if you're trying to read option >flags from the command line, you may want to use the 'optparse' module >instead: > > http://www.python.org/doc/lib/module-optparse.html > > Looked at this - appears interesting, certainly more pertinent that what I read about getopt! >Hmmm... What kind of problem are you trying to solve? > > >>From your previous question, it sounded like you were trying to write a >'grep' string searching program. If so, you may want to look at the >regular expression library ('re'): > > http://www.python.org/doc/lib/module-re.html > >A.M. Kuckling has written a small "howto" tutorial on regular expressions >that you may find useful: > > http://www.amk.ca/python/howto/regex/ > The program is more word count than regular expression matching. Sorry I delayed in responding - my code for catching multiple instances of matching on a single line was flawed. Finally it came down to a single critical typo. Works and counts correctly!! The need for the optget was a suggestion by the author to do the simplier program but using a case insensitive search. Suspect it will take more that simply using optparse to solve. Somewhat at a lose at how to begin. Attaching the code for the unalterted file. Thanks both of these are now links for python documentation. One aside: why is this link so usless? http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/python/api/api.html Must one become a member to have the search utitlity work? Failed at every search, even 'if', string.find(), find and others. > >The option parsing libraries are meant to be used when we want to define >what kind of flags the user can set for us at the command line. In our >last email, I asked if you could do this at the command line: > > ls -l some_filename > >If we were to write our own version of th 'ls' command, then an option >parsing library would be responsible for looking at that '-l' section and >tell us that the user's requesting a "long" output. > >So optparse/getopt is a command-line user interface thing. Are you trying >to parse command line arguments? Tell us more about the problem you're >trying to solve. > > > I think you have it exactly correct, in this latest case I included the '*' as part of the file name and since it probably just denotes an executable file it was my mistake. >>From reading the thread, my best guess at the moment was that your file >had a literal asterisk at the end of the filename. The file extension of >your program, then, was perhaps literally something like: > > .py* > >There's a section in your .emacs configuration that tells Emacs the file >extensions it should use to detect Python source files. That extension is >'.py', not '.py*', so renaming the file to have no asterisk fixed the >problem, and allowed Emacs to recognize the file as Python source code. > >(In any case, having an asterisk in there is probably a bad idea in Unix, >because the shell treats unescaped asterisks as 'globbing' metacharacters >that can stand for anything.) > > >Anyway, I hope this helps! Please feel free to ask more questions. > > > > Dan, You are magnificent - and a great help. See comments above. Have any idea where the expected .emacs file might be hidden? There is a: .emacs-places that is NOT the expected emacs configuration file. Moreover, no sign of .xemacs that seems to tag along with the .emacs file I have on UNIX. The 'find' command did not help much either. There were some links, but did not appear useful. Have to attend to some for 'pay' work that requires my attention. I will be back, and for everyones sake I hope more informed about python behaviour and syntax under Linux. Thanks again, Herschel From hcohen2 at comcast.net Sun Dec 28 17:27:26 2003 From: hcohen2 at comcast.net (hcohen2) Date: Sun Dec 28 17:28:19 2003 Subject: [Tutor] Dumb question on emacs and python ... In-Reply-To: References: Message-ID: <3FEF58CE.2090102@comcast.net> As soon as I say something does not work - I find out it does: drop my remark about not getting any matches the ActiveState Programming Network!!! More than I have time to look at!!! From zanshou at wanadoo.fr Mon Dec 29 08:11:45 2003 From: zanshou at wanadoo.fr (Twily) Date: Mon Dec 29 08:16:55 2003 Subject: [Tutor] Newbie self-introduction + little encoding problem Message-ID: <001701c3ce0e$237e2740$74c20f50@nagetb3uxkybix> Hello ^_^ I'm Twily, French, 22 years old... I've juste begun to learn programming, and consequently, Python is the first language I'm trying to master. I'm currently studying with the textbook "Apprendre programmer avec Python" by G?rard Swinnen (adaptation from "How to think like a computer scientist"), and I have a little problem with ex 23...so I was wondering if someone here could help me... The aim of the exercise is to combine two lists t1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] and t2 = ['Janvier','Fevrier','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre ','Octobre','Novembre','Decembre'] in a new list, which contains alternatively elements from t1 & t2 (31, 'Janvier', 28, 'Fevrier', etc...) The program I've written works perfectly if I use no French accents at all. However, if I add accents at "F?vrier", "Ao?t", and "D?cembre", as it should be the case to write months' names in French, here is what I obtain when I run the program : >>> [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars', 30, 'Avril', 31, 'Mai', 30, 'Juin', 31, 'Juillet', 31, 'Ao\xfbt', 30, 'Septembre', 31, 'Octobre', 30, 'Novembre', 31, 'D\xe9cembre'] >>> As you can see, the accents go completely wrong... It doesn't change anything to add # -*- coding: iso-8859-1 -*- at the beginning of the program (utf-8 doesn't work either). Nonetheless, if I specify the encoding in the first line of the source, if I then add one line like this >>> print "F?vrier" below the exercise, the accents are printed properly. So, it seems that the problem lies in forcing the Latin encoding to work for strings included into lists...is there a (simple ?) way to do this ? ^^; Thank you very much ^_^ Twily From w.richert at gmx.net Mon Dec 29 09:16:15 2003 From: w.richert at gmx.net (Willi Richert) Date: Mon Dec 29 09:16:23 2003 Subject: [Tutor] The biggest snake on earth is a Python ;-) Message-ID: <200312291516.15752.w.richert@gmx.net> Hi, I'm sorry, the article is only in German. But the image is in international ;-) http://www.spiegel.de/panorama/0,1518,280028,00.html Have fun, wr -- A fool with a tool is just a fool. With a tool. From hec.villafuerte at telgua.com.gt Mon Dec 29 13:48:37 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Mon Dec 29 11:47:02 2003 Subject: [Tutor] Async Events (or How to manage interrupts in Python?) Message-ID: <3FF07705.10405@telgua.com.gt> Hi all, First, let me tell you what all this is about. I have a very nice script that does the following: 1. It checks if there is a file in an Open VMS server. 2. If it finds the file, it connects via TELNET (using telnetlib, of course!) and ZIP's it. 3. Once the file is compressed, it GET's it via FTP (using ftplib) 4. When the file is in my local machine, the script does some processing on it. 5. If the script was given more than one file to look at the VMS server it goes back to Step 1. Quite simple, right? The thing is that I don't want this to perform sequentially... it's such a waste of time! Because while the script is in Steps 3 and 4, it could perfectly be executing Steps 1 and 2. When I used to program microcontrollers (PICs) we had good old interrupts to handle things like this. Any ideas how to do this in Python? Thank you so much, in advance. Hector From vicki.stanfield at ROCHE.COM Mon Dec 29 11:52:18 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Mon Dec 29 11:52:44 2003 Subject: [Tutor] Async Events (or How to manage interrupts in Python?) Message-ID: I would think that this requires threading. I recently saw a decent explanation of how to do it in Python. I will look for it, and if no one beats me to it, I will post it later. --vicki -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of "H?ctor Villafuerte D." Sent: Monday, December 29, 2003 1:49 PM To: tutor@python.org Subject: [Tutor] Async Events (or How to manage interrupts in Python?) Hi all, First, let me tell you what all this is about. I have a very nice script that does the following: 1. It checks if there is a file in an Open VMS server. 2. If it finds the file, it connects via TELNET (using telnetlib, of course!) and ZIP's it. 3. Once the file is compressed, it GET's it via FTP (using ftplib) 4. When the file is in my local machine, the script does some processing on it. 5. If the script was given more than one file to look at the VMS server it goes back to Step 1. Quite simple, right? The thing is that I don't want this to perform sequentially... it's such a waste of time! Because while the script is in Steps 3 and 4, it could perfectly be executing Steps 1 and 2. When I used to program microcontrollers (PICs) we had good old interrupts to handle things like this. Any ideas how to do this in Python? Thank you so much, in advance. Hector _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ATrautman at perryjudds.com Mon Dec 29 12:02:10 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Mon Dec 29 12:02:21 2003 Subject: [Tutor] Async Events (or How to manage interrupts in Python?) Message-ID: <06738462136C054B8F8872D69DA140DB01C08BF5@corp-exch-1.pjinet.com> Hector, I can think of three options: 1. Multithreading of the whole procedure. i.e.... start seeker, if it finds file(s), trigger a thread for each files found. 2. Recursive copying of the files to and from the server. If each function returns true then trigger tee next function. (come to think of it, it might be useful to thread the resulting processing of the files) 3. Create a class object that handles all of the functions and assign each file found to a different class object. The __init__ functions will do all of the inbound processing and when you are ready to move back all of the objects create a function that copies back all copied objects with a status of "done" or something. Many combinations of these will work just trying to give you some ideas. HTH, Alan -----Original Message----- From: "H?ctor Villafuerte D." [mailto:hec.villafuerte@telgua.com.gt] Sent: Monday, December 29, 2003 12:49 PM To: tutor@python.org Subject: [Tutor] Async Events (or How to manage interrupts in Python?) Hi all, First, let me tell you what all this is about. I have a very nice script that does the following: 1. It checks if there is a file in an Open VMS server. 2. If it finds the file, it connects via TELNET (using telnetlib, of course!) and ZIP's it. 3. Once the file is compressed, it GET's it via FTP (using ftplib) 4. When the file is in my local machine, the script does some processing on it. 5. If the script was given more than one file to look at the VMS server it goes back to Step 1. Quite simple, right? The thing is that I don't want this to perform sequentially... it's such a waste of time! Because while the script is in Steps 3 and 4, it could perfectly be executing Steps 1 and 2. When I used to program microcontrollers (PICs) we had good old interrupts to handle things like this. Any ideas how to do this in Python? Thank you so much, in advance. Hector _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From python at comber.cix.co.uk Mon Dec 29 12:54:13 2003 From: python at comber.cix.co.uk (Eddie Comber) Date: Mon Dec 29 13:03:58 2003 Subject: [Tutor] Subclassing In-Reply-To: <6.0.0.22.0.20031222105553.0406fbe8@mail.mric.net> Message-ID: Yes but look at: f = d[1:2] print f, type(f) The type of f is and this would require me to subclass, or overload, the slice operator to give me the correct return type (and every other operator valid for a type) class mylist(list): def __init__(self, inList=None): if inList: self[:] = inList def __add__(self, other): self.extend(other) return mylist(self) a = mylist([1]) b = mylist([2]) c = mylist([3]) d = a + b + c f = d[1:2] print f, type(f) -----Original Message----- From: Bob Gailer [mailto:bgailer@alum.rpi.edu] Sent: 22 December 2003 18:10 To: Eddie Comber; tutor@python.org Subject: Re: [Tutor] Subclassing At 01:27 AM 12/22/2003, Eddie Comber wrote: >Suppose I want to subclass 'list' to provide mylist which has different >behaviour. Say I only want to modify the '+' operator __add(self, other)__ >as the other operators and functions are fine. > >The problem is what type should '+' return? > >If it returns type == list then > >a = mylist() >b = mylist() >c = mylist() > >d = a + b + c > >means after b + c the type is 'list' and a + b is (mylist + list) rather >than (mylist + mylist). >The trouble with returning type mylist is that it looks to me like all the >'list' operators and functions need to be trivially subclassed to return >type mylist. Try this: class mylist(list): def __init__(self, inList=None): if inList: self[:] = inList def __add__(self, other): self.extend(other) return mylist(self) a = mylist([1]) b = mylist([2]) c = mylist([3]) d = a + b + c print d # displays [1, 2, 3] x = 3 i = 1 j = 2 n = 3 t = [5, 6] print x in s # 1 if an item of s is equal to x, else 0 print x not in s # 0 if an item of s is equal to x, else 1 print s + t # the concatenation of s and t print s * n , n * s # n shallow copies of s concatenated (1) print s[i] # i'th item of s, origin 0 (2) print s[i:j] # slice of s from i to j (2), (3) print len(s) # length of s print min(s) # smallest item of s print max(s) s[i] = x ; print s # item i of s is replaced by x s[i:j] = t ; print s # slice of s from i to j is replaced by t del s[i:j] ; print s # same as s[i:j] = [] s.append(x) ; print s # same as s[len(s):len(s)] = [x] (1) s.extend([x]) ; print s # same as s[len(s):len(s)] = x (2) s.count(x) ; print s # return number of i's for which s[i] == x s.index(x) ; print s # return smallest i such that s[i] == x (3) s.insert(i, x) ; print s # same as s[i:i] = [x] if i >= 0 (4) s.pop(i) ; print s #same as x = s[i]; del s[i]; return x (5) s.remove(x) ; print s #same as del s[s.index(x)] (3) s.reverse() ; print s #reverses the items of s in place (6) s.sort() ; print s #sort the items of s in place Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From sigurd at 12move.de Mon Dec 29 14:03:55 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Dec 29 14:04:58 2003 Subject: [Tutor] Newbie self-introduction + little encoding problem In-Reply-To: <001701c3ce0e$237e2740$74c20f50@nagetb3uxkybix> (Twily's message of "Mon, 29 Dec 2003 14:11:45 +0100") References: <001701c3ce0e$237e2740$74c20f50@nagetb3uxkybix> Message-ID: On 29 Dec 2003, Twily <- zanshou@wanadoo.fr wrote: > The program I've written works perfectly if I use no French accents at all. > However, if I add accents at "F?vrier", "Ao?t", and "D?cembre", as it should > be the case to write months' names in French, here is what I obtain when I > run the program : > [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars', 30, 'Avril', 31, 'Mai', 30, > 'Juin', 31, 'Juillet', 31, 'Ao\xfbt', 30, 'Septembre', 31, 'Octobre', 30, > 'Novembre', 31, 'D\xe9cembre'] (that's a repost; it seems the first e-mail got lost). But that's right. Did you try to print such a string? > As you can see, the accents go completely wrong... They don't. You simple see the intern representation of the strings. >>>> print "F?vrier" > below the exercise, the accents are printed properly. In [23]: mon = [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars', 30, 'Avril', 31, 'Mai', 30, ....: m 'Juin', 31, 'Juillet', 31, 'Ao\xfbt', 30, 'Septembre', 31, 'Octobre', 30, ....: 'Novembre', 31, 'D\xe9cembre'] In [24]: for d, m in zip(mon[::2], mon[1::2]): ....: print "%s %s" % (d, m) ....: 31 Janvier 28 F?vrier 31 Mars 30 Avril 31 Mai 30 Juin 31 Juillet 31 Ao?t 30 Septembre 31 Octobre 30 Novembre 31 D?cembre If you can read German there is a good FAQ which might help you to understand what happens: http://p-nand-q.com/python/unicode_faq.html Karl -- Please do *not* send copies of replies to me. I read the list From red_necks25 at yahoo.com Mon Dec 29 16:07:29 2003 From: red_necks25 at yahoo.com (moore william) Date: Mon Dec 29 16:07:36 2003 Subject: [Tutor] Input Message-ID: <20031229210729.59709.qmail@web13607.mail.yahoo.com> I am trying to create a phone book. I have most of it done at this point and am now tryign to make it work! LOL. The problem is I am looking for the script to mak the program look up names, remember input, and find names in the data base. My program is capable of puttign in the input and quiting right now. Here is what I have so far: import shelve import string def print_menu(): print 'Welcome to the Phone Roster' print '1. Add Name' print '2. Delete Name' print '3. Look Up Name' print '9. Quit' print numbers = {} menu_choice = 0 print_menu() while menu_choice != 9: menu_choice = input("Type in a number (1-9):") if menu_choice == 1: print "Add Number:" Name = raw_input ("Name:") Work = raw_input ("Work Number:") Home = raw_input ("Home Number:") FAX = raw_input ("Fax Number:") Cell = raw_input ("Cell Number:") elif menu_choice == 2: print "Delete Name;" Name = raw_input ("Name:") elif menu_choice == 3: print "Look Up Name;" Name = raw_input ("Name:") print "Name: "'x'" \tNumber: ",numbers[x] print UNKNOWN = 0 HOME = 1 WORK = 2 FAX = 3 CELL = 4 class phoneentry: def __init__(self, name = 'Unknown', number = 'Unknown', type = UNKNOWN): self.name = name self.number = number self.type = type # create string representation def __repr__(self): return('%s:%d' % ( self.name, self.type )) # fuzzy compare or two items def __cmp__(self, that): this = string.lower(str(self)) that = string.lower(that) if string.find(this, that) >= 0: return(0) return(cmp(this, that)) def showtype(self): if self.type == UNKNOWN: return('Unknown') if self.type == HOME: return('Home') if self.type == WORK: return('Work') if self.type == FAX: return('Fax') if self.type == CELL: return('Cellular') class phonedb: def __init__(self, dbname = 'phonedata'): self.dbname = dbname; self.shelve = shelve.open(self.dbname); def __del__(self): self.shelve.close() self.shelve = None def add(self, name, number, type = HOME): e = phoneentry(name, number, type) self.shelve[str(e)] = e def lookup(self, string): list = [] for key in self.shelve.keys(): e = self.shelve[key] if cmp(e, string) == 0: list.append(e) return(list) # if not being loaded as a module, run a small test if __name__ == '__main__': foo = phonedb() foo.add('Sean Reifschneider', '970-555-1111', HOME) foo.add('Sean Reifschneider', '970-555-2222', CELL) foo.add('Evelyn Mitchell', '970-555-1111', HOME) print 'First lookup:' for entry in foo.lookup('reifsch'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) print print 'Second lookup:' for entry in foo.lookup('e'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) # end of phonedb.py __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From alan.gauld at blueyonder.co.uk Mon Dec 29 16:53:16 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Dec 29 16:52:42 2003 Subject: [Tutor] Newbie self-introduction + little encoding problem References: <001701c3ce0e$237e2740$74c20f50@nagetb3uxkybix> Message-ID: <01f401c3ce56$2a6a3a60$6401a8c0@xp> > The program I've written works perfectly if I use no French accents at all. > However, if I add accents at "F?vrier", "Ao?t", and "D?cembre", as it should > be the case to write months' names in French, here is what I obtain when I > run the program : > > >>> > [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars', 30, 'Avril', 31, 'Mai', 30, > 'Juin', 31, 'Juillet', 31, 'Ao\xfbt', 30, 'Septembre', 31, 'Octobre', 30, > 'Novembre', 31, 'D\xe9cembre'] > >>> That will actually work OK when you try to print it, it's just that Python is showing up the accented characters in their hexadecimal form. Try this: dates = [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars', 30, 'Avril', 31, 'Mai', 30, 'Juin', 31, 'Juillet', 31, 'Ao\xfbt', 30, 'Septembre', 31, 'Octobre', 30, 'Novembre', 31, 'D\xe9cembre'] for index in range(0,len(dates),step=2): print dates[index], ' ', dates[index+1] You should find the printed names are as you expect. This is due to a subtlty in the way the python interpreter works. If you evaluate an expression at the >>> prompt python uses the repr() function to display it. By convention repr() is intended to assist programmers and shows a data centric view of the data, whereas the print command uses the str() representation which is aimed at end users and shows a more user friendly representation. For many things repr() and str() are the same but for somne things - like unicode strings - they are different. TO prove the point lets look at the simpler case of: >>> s = 'F\xe9vrier' >>> s 'F\xe9vrier' Notice both the quote marks and the hex substitution. >>> print s F?vrier No quotes and the accented character. Finally look at these and think about why they come out as they do... >>> repr(s) "'F\\xe9vrier'" >>> str(s) 'F\xe9vrier' >>> print repr(s) 'F\xe9vrier' >>> print str(s) F?vrier >>> HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Mon Dec 29 16:56:25 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Dec 29 16:55:50 2003 Subject: [Tutor] Async Events (or How to manage interrupts in Python?) References: <3FF07705.10405@telgua.com.gt> Message-ID: <01f901c3ce56$9b1accc0$6401a8c0@xp> > First, let me tell you what all this is about. I have a very nice script > that does the following: > 1. It checks if there is a file in an Open VMS server. > 2. If it finds the file, it connects via TELNET (using telnetlib, of > course!) and ZIP's it. > 3. Once the file is compressed, it GET's it via FTP (using ftplib) > 4. When the file is in my local machine, the script does some processing > on it. > 5. If the script was given more than one file to look at the VMS server > it goes back to Step 1. > > Quite simple, right? > The thing is that I don't want this to perform sequentially... > it's such a waste of time! Quite right, look at the thread module, it's for allowing parallel threads of execution. Write the bit that can be done in parallel as a function - making sure to avoid using any global variables! - and call that function in a new thread. See the thread module documentation for that. 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 Dec 29 16:58:32 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 29 16:58:38 2003 Subject: [Tutor] Newbie self-introduction + little encoding problem In-Reply-To: Message-ID: > > [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars', 30, 'Avril', 31, 'Mai', 30, > > 'Juin', 31, 'Juillet', 31, 'Ao\xfbt', 30, 'Septembre', 31, 'Octobre', 30, > > 'Novembre', 31, 'D\xe9cembre'] > > (that's a repost; it seems the first e-mail got lost). > > But that's right. Did you try to print such a string? > > > As you can see, the accents go completely wrong... > > They don't. You simple see the intern representation of the strings. Hi Twilly, Yes, what we are seeing when we print a list is the 'repr()' of each element in our list. http://www.python.org/doc/lib/built-in-funcs.html#l2h-59 repr() is another string-converting function that's similar to str() --- but it's subtly different because it shows exactly what we'd need to type at the interpreter to get that value. Hmmm... that was a little difficult to scan. Maybe an example will help: ### >>> s = 'this is a test' >>> print str(s) this is a test >>> print repr(s) 'this is a test' ### Here, we can see that str() and repr() do give back subtly different things, because strings need quotes around them. And for your amusement: doing a repeated repr() on a string adds more and more quotes: ### >>> print s this is a test >>> print repr(s) 'this is a test' >>> print repr(repr(s)) "'this is a test'" >>> print repr(repr(repr(s))) '"\'this is a test\'"' >>>>>> print '"\'this is a test\'"' "'this is a test'" ### Anyway, accents on some systems don't print the way you might expect them to, but repr() shows them all in all their hexidecimal glory. The hexadecimal characters print the same way, regardless of our current encoding scheme, so that's why we're seeing things like: > > [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars', 30, 'Avril', 31, 'Mai', 30, > > 'Juin', 31, 'Juillet', 31, 'Ao\xfbt', 30, 'Septembre', 31, 'Octobre', 30, > > 'Novembre', 31, 'D\xe9cembre'] Normally, when we say something like: print foo we're asking Python to first call str() to convert 'foo' into a nice, human-readable string, and then Python prints that. It turns out, though, that str()ing a list will repr() every element in that list as it constructs the string representation. And that's where your accents are being shown as hexadecimal constants. If we want to change that behavior, we need to be more explicit by transforming our list into a string: ### >>> def list_to_string(mylist): ... stringed_elements = [] ... for x in mylist: ... stringed_elements.append(str(x)) ... return '[' + ', '.join(stringed_elements) + ']' ... >>> >>> entries = [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars'] >>> print entries [31, 'Janvier', 28, 'F\xe9vrier', 31, 'Mars'] >>> print list_to_string(entries) [31, Janvier, 28, F?vrier, 31, Mars] ### Note that I'm getting question marks on my system, because my system's native encoding is utf-8, and not iso-8859-1. But on your system, list_to_string() should show the accents that you expect. Hope this helps! From helena_b2001 at yahoo.com Mon Dec 29 17:34:55 2003 From: helena_b2001 at yahoo.com (helena bhaska) Date: Mon Dec 29 17:35:00 2003 Subject: [Tutor] import MySQLdb problem In-Reply-To: <16786.1071659704@www48.gmx.net> Message-ID: <20031229223455.65344.qmail@web20422.mail.yahoo.com> Hi, I realize that this has already been discussed, but I am unable to solve the following problem: I am trying to import MySQLdb in a script that is running on apache server. The proposed solutions mentioned writing a wrapper shell script that would set LD_LIBRARY_PATH variable before executing python script. However, my script is not executed from command prompt, it is called through urllib.urlopen() and I am not sure how to go to shell script from this. I have tried using SetEnv and PassEnv in httpd.conf in apache, but that did not fix the problem, the behavior was exactly the same as before. (ImportError: No module named MySQLdb). I am probably misunderstanding how to use LS_LIBRARY_PATH, I assumed that I was supposed to give path to where MySQLdb is, so here is what I have done: SetEnv LD_LIBRARY_PATH /usr/local/lib/python2.3/site-packages/ PassEnv LD_LIBRARY_PATH site-packages contain MySQLdb subdir. So is there a way to call a shell script though urllib.urlopen() or should httpd.conf be modified, and if so what am I doing wrong? Thank you very much! -Helena __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From matteolovatti at mac.com Mon Dec 29 18:09:05 2003 From: matteolovatti at mac.com (matteo) Date: Mon Dec 29 18:09:17 2003 Subject: [Tutor] need a little help Message-ID: hi everybody i'm new to the list i'm now starting to build my first "pyhtons" but i'm hang with this... import poplib M = poplib.POP3("serverpop") M.user("aaa") M.pass_("bbb") numMessages = len(M.list()[1]) for i in range(numMessages): for j in M.retr(i+1)[1]: print j i really would like to have j printed only if the line in the "j" variable begins with the string "subject:" but i'm not able to do that can someone please help me ? thanks matteo -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 547 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031230/46760fb5/attachment-0001.bin From arkamir at softhome.net Mon Dec 29 18:57:24 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Mon Dec 29 18:57:53 2003 Subject: [Tutor] Re: Tutor Digest, Vol 5, Issue 70 In-Reply-To: References: Message-ID: <1072742243.9948.19.camel@quercus> Hmm I got MySQLdb to work for me. I'm using 2.2.3 Fedora Core 1 Mysql v4.0.15 and Mysql-python v0.9.1-9. I'm using apache too. The trick I *think* cant quite remember is to go to an older version of MySQLdb. Also as a sidenote does MySQLdb even work on your interpreter??(I dont think it does but just making sure) From tim at johnsons-web.com Mon Dec 29 19:04:06 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Dec 29 19:02:41 2003 Subject: [Tutor] need a little help In-Reply-To: References: Message-ID: <20031230000406.GT1263@johnsons-web.com> * matteo [031229 14:18]: > hi everybody i'm new to the list > i'm now starting to build my first "pyhtons" but i'm hang with this... > > import poplib > > M = poplib.POP3("serverpop") > > M.user("aaa") > > M.pass_("bbb") > > numMessages = len(M.list()[1]) > for i in range(numMessages): > for j in M.retr(i+1)[1]: > print j > > i really would like to have j printed only if the line in the "j" > variable begins with the string "subject:" > but i'm not able to do that > can someone please help me ? Hi Matteo: Below is a console session that might help. Since I don't have a working version of your code to test with. I proceed with the assumption that `j` is a string. >>> M = "subject: Question" >>> M.find("subject:") 0 # succesful find, index is 0 # Example of not found >>> M.find("Subject:") -1 You cound get around case sensitivity by forcing both string to upper case or lower case >>> M.upper().find("Subject:".upper()) 0 So your test construct might be something like this: >>> if not M.upper().find("Subject".upper()): ... print M ... subject: Question # Yikes! That's counterintuitive, isn't it. # That's why I might write a function like: def is_head(Str,sub): found = Str.find(sub) if found == 0: return 1 else: return None # OR return 0 if you like # Notice that this function doesn't address # Case, an optional argument for case # Sensitivity would be in order Then our test would be #untested code if is_head(M.upper(),"Subject".upper()): print j I hope this helps a bit. Try it with substring "Question" , and see what happens Tim > thanks > > > matteo > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Mon Dec 29 19:06:35 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Dec 29 19:05:09 2003 Subject: [Tutor] need a little help/OOPS! In-Reply-To: <20031230000406.GT1263@johnsons-web.com> References: <20031230000406.GT1263@johnsons-web.com> Message-ID: <20031230000635.GU1263@johnsons-web.com> * Tim Johnson [031229 15:04]: > * matteo [031229 14:18]: > > hi everybody i'm new to the list > > i'm now starting to build my first "pyhtons" but i'm hang with this... > > > > import poplib > > > > M = poplib.POP3("serverpop") > > > > M.user("aaa") > > > > M.pass_("bbb") > > > > numMessages = len(M.list()[1]) > > for i in range(numMessages): > > for j in M.retr(i+1)[1]: > > print j > > > > i really would like to have j printed only if the line in the "j" > > variable begins with the string "subject:" > > but i'm not able to do that > > can someone please help me ? OOPS! I got a little ahead of myself, not 'binding' the console session to your example. I should have use 'j' as the variable name See below: > Hi Matteo: > Below is a console session that might help. > Since I don't have a working version of your code to > test with. > I proceed with the assumption that `j` is a string. > >>> j = "subject: Question" > >>> j.find("subject:") > 0 # succesful find, index is 0 > > # Example of not found > >>> j.find("Subject:") > -1 > > You cound get around case sensitivity > by forcing both string to upper case > or lower case > >>> j.upper().find("Subject:".upper()) > 0 > > So your test construct might be something like this: > >>> if not j.upper().find("Subject".upper()): > ... print j > ... > subject: Question > > # Yikes! That's counterintuitive, isn't it. > # That's why I might write a function like: > def is_head(Str,sub): > found = Str.find(sub) > if found == 0: return 1 > else: return None # OR return 0 if you like > # Notice that this function doesn't address > # Case, an optional argument for case > # Sensitivity would be in order > > Then our test would be #untested code > if is_head(j.upper(),"Subject".upper()): > print j > > I hope this helps a bit. Try it with substring > "Question" , and see what happens > > Tim > > > thanks > > > > > > matteo > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > -- > Tim Johnson > http://www.alaska-internet-solutions.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at blueyonder.co.uk Mon Dec 29 19:11:31 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Dec 29 19:10:56 2003 Subject: [Tutor] need a little help References: Message-ID: <022901c3ce69$7a830280$6401a8c0@xp> > for j in M.retr(i+1)[1]: > print j > > i really would like to have j printed only if the line in the "j" > variable begins with the string "subject:" > but i'm not able to do that can someone please help me ? Look at the documentation for the startswith() string method. Alan G. From sigurd at 12move.de Mon Dec 29 19:10:46 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Dec 29 19:11:49 2003 Subject: [Tutor] need a little help In-Reply-To: (matteo's message of "Tue, 30 Dec 2003 00:09:05 +0100") References: Message-ID: On 30 Dec 2003, matteo <- matteolovatti@mac.com wrote: > import poplib > > M = poplib.POP3("serverpop") > > M.user("aaa") > > M.pass_("bbb") > > numMessages = len(M.list()[1]) > for i in range(numMessages): > for j in M.retr(i+1)[1]: > print j > > i really would like to have j printed only if the line in the "j" > variable begins with the string "subject:" That's nearly the example from the library so let's extend it a bit. You could use a regular expression or since it's very simple here you can use a builtin method of strings: `startswith' Then your code becomes (not ready yet): for i in range(1, len(M.list()[1]) + 1): for line in M.retr(i)[1]: if line.startswith('Subject'): print line That works but the string 'Subject' only matches if the capitalization in your e-mail is exactly the same; that may or may not be the case. Strings have another method: lower(); and you can chain methods. So eg. In [34]: s = "Test foo bar" In [35]: s.lower() Out[35]: 'test foo bar' In [36]: s.lower().startswith('test') Out[36]: True So you might write: for i in range(1, len(M.list()[1]) + 1): for line in M.retr(i)[1]: if line.lower().startswith('subject'): print line And last but not least; if you search only for the subject header in e-mails you can stop searching after the first match and go on to the next e-mail. A loop can be prematurely left with `break'. So finally you get: for i in range(1, len(M.list()[1]) + 1): for line in M.retr(i)[1]: if line.lower().startswith('subject'): print line break Karl -- Please do *not* send copies of replies to me. I read the list From helena_b2001 at yahoo.com Mon Dec 29 20:50:10 2003 From: helena_b2001 at yahoo.com (helena bhaska) Date: Mon Dec 29 20:50:15 2003 Subject: [Tutor] import MySQLdb problem In-Reply-To: <20031229223455.65344.qmail@web20422.mail.yahoo.com> Message-ID: <20031230015010.33805.qmail@web20414.mail.yahoo.com> To all those linux newbies like me who get stuck with problems like this, here is what solved my problem: I added the path to MySQLdb to /etc/ld.so.conf. That's it! :) --- helena bhaska wrote: > Hi, > I realize that this has already been discussed, but > I > am unable to solve the following problem: > I am trying to import MySQLdb in a script that is > running on apache server. > The proposed solutions mentioned writing a wrapper > shell script that would set LD_LIBRARY_PATH variable > before executing python script. However, my script > is > not executed from command prompt, it is called > through > urllib.urlopen() and I am not sure how to go to > shell > script from this. > I have tried using SetEnv and PassEnv in httpd.conf > in > apache, but that did not fix the problem, the > behavior > was exactly the same as before. (ImportError: No > module named MySQLdb). > I am probably misunderstanding how to use > LS_LIBRARY_PATH, I assumed that I was supposed to > give > path to where MySQLdb is, so here is what I have > done: > > SetEnv LD_LIBRARY_PATH > /usr/local/lib/python2.3/site-packages/ > PassEnv LD_LIBRARY_PATH > > site-packages contain MySQLdb subdir. > So is there a way to call a shell script though > urllib.urlopen() or should httpd.conf be modified, > and > if so what am I doing wrong? > Thank you very much! > -Helena > > > __________________________________ > Do you Yahoo!? > New Yahoo! Photos - easier uploading and sharing. > http://photos.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From clay at shirky.com Mon Dec 29 21:51:55 2003 From: clay at shirky.com (Clay Shirky) Date: Mon Dec 29 21:52:12 2003 Subject: [Tutor] Treating a string as a list of one? Message-ID: I want to be able to pass a function either a string or a list, and have it treat the string as a list of one item. I thought this would work try: _loop.extend(items) except: _loop.append(items) for item in items: # other stuff here thinking that when .extend got something that wasn't a list, it would raise an exception. Instead, it treats the string as a list of chars. Is there a simple way to say "if its a list, extend the _loop variable, and if its a string, append it?" -clay From karl.fast at pobox.com Mon Dec 29 22:26:03 2003 From: karl.fast at pobox.com (Karl Fast) Date: Mon Dec 29 22:26:11 2003 Subject: [Tutor] Treating a string as a list of one? In-Reply-To: ; from clay@shirky.com on Mon, Dec 29, 2003 at 09:51:55PM -0500 References: Message-ID: <20031229212603.A32476@signal.lights.com> > I want to be able to pass a function either a string or a list, and > have it treat the string as a list of one item. One solution is to check the variable type. If you've got a string, just make it a single item list, and then process as normal. Otherwise you just assume it's a list. Something like this: import types def myfunc(item): if isinstance(item, types.StringTypes): item = [item] ...process the list as you want to Note that types.StringTypes will check for both regular and unicode strings (my first crack only checked for normal strings and it took me a few hours to figure out why it failed every so often). If you want to avoid importing the types module you can use the builtin function type....but I found the types module a little bit nicer. hope this helps... --karl From matteolovatti at mac.com Mon Dec 29 22:39:46 2003 From: matteolovatti at mac.com (matteo) Date: Mon Dec 29 22:39:54 2003 Subject: [Tutor] need a little help In-Reply-To: References: Message-ID: many thanks to all of you that answered my question, the search works perfectly !! i have two other little trubles, this is one, how can i send an email using python ? for what i've read in the manual the poplibs are able only to receive... thanks again matteo PS. sorry Karl for te wrong message delivery, made a mistake with my client From matteolovatti at mac.com Mon Dec 29 23:07:13 2003 From: matteolovatti at mac.com (matteo) Date: Mon Dec 29 23:07:21 2003 Subject: [Tutor] need a little help In-Reply-To: References: Message-ID: On 30/dic/03, at 04:39, matteo wrote: > i have two other little trubles, this is one, how can i send an email > using python ? > for what i've read in the manual the poplibs are able only to > receive... > ops.. i've found.. the smtplib. but if i write server_smtp.sendmail("matteolovatti@mac.com","matteolovatti@mac.com",var iable) i get a message with matteolovatti@mac.com as "from:" but there's nothing in the "To:" !! can someone help ? matteo -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 520 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031230/ed3424eb/attachment.bin From tony at tcapp.com Mon Dec 29 23:55:17 2003 From: tony at tcapp.com (Tony Cappellini) Date: Mon Dec 29 23:55:26 2003 Subject: [Tutor] Calling append() method in a list Message-ID: <6.0.0.22.0.20031229204609.03cf1ca8@smtp.sbcglobal.net> In the example code below, I'm trying to understand why the else clause is even necessary def add(self, occasion, function): if self.connections.has_key(occasion) == 0: self.connections[occasion]=[function] else: self.connections[occasion].append(function) Why not just code the above as def add(self, occasion, function): if self.connections.has_key(occasion) == 0: self.connections[occasion].append(function) If I do the following python interactive interpreter l1=[] l1.append(1) l1.append(2) l1.append(3) print l1 [1,2,3] is displayed. So - does omitting the else clause cause any problems ? (Assuming the list is initialized to [] before referencing it's contents) From chenren at tydic.com Tue Dec 30 00:06:56 2003 From: chenren at tydic.com (=?GB2312?Q?=B3=C2=C8=CE?=) Date: Tue Dec 30 00:11:09 2003 Subject: [Tutor] how to make .py file to .exe file? Message-ID: <200312301314765.SM01292@chenren> Everyone: Hello!Happy New Year! I'm a real beginner.I want to ask a question. How to make a executable file so that I can click it and run it directly? Thanks. ????????Joe Blank ????????chenren@tydic.com ??????????2003-12-30 From chenren at tydic.com Tue Dec 30 00:16:55 2003 From: chenren at tydic.com (=?GB2312?Q?=B3=C2=C8=CE?=) Date: Tue Dec 30 00:20:27 2003 Subject: [Tutor] Are there any free project to download for studying? Message-ID: <200312301324625.SM01292@chenren> python-Tutor?Hello? When I first touch Python,I have loved it.I use it to complete several assignment that my teacher gave us. But I want to see what else Python can do. So I want to see other good programs and project. Is there anyone who can tell me how I can get them.Thanks! Joe ????????chenren@tydic.com ??????????2003-12-30 From tony at tcapp.com Tue Dec 30 00:30:52 2003 From: tony at tcapp.com (Tony Cappellini) Date: Tue Dec 30 00:31:06 2003 Subject: [Tutor] re:Tutor] how to make .py file to .exe file? Message-ID: <6.0.0.22.0.20031229212916.03cf0de0@smtp.sbcglobal.net> Message: 12 Date: Tue, 30 Dec 2003 13:6:56 +0800 From: " ?? " Subject: [Tutor] how to make .py file to .exe file? To: python-Tutor Message-ID: <200312301314765.SM01292@chenren> Content-Type: text/plain; charset="GB2312" Everyone: Hello!Happy New Year! I'm a real beginner.I want to ask a question. How to make a executable file so that I can click it and run it directly? Thanks. For starters, Look at py2exe http://starship.python.net/crew/theller/py2exe/ Good Luck Tony From dyoo at hkn.eecs.berkeley.edu Tue Dec 30 01:10:39 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 30 01:10:45 2003 Subject: [Tutor] Calling append() method in a list In-Reply-To: <6.0.0.22.0.20031229204609.03cf1ca8@smtp.sbcglobal.net> Message-ID: On Mon, 29 Dec 2003, Tony Cappellini wrote: > In the example code below, I'm trying to understand why the else clause > is even necessary > > def add(self, occasion, function): > if self.connections.has_key(occasion) == 0: > self.connections[occasion]=[function] > else: > self.connections[occasion].append(function) > > Why not just code the above as > > def add(self, occasion, function): > if self.connections.has_key(occasion) == 0: > self.connections[occasion].append(function) Hi Tony, Ah! In the second version of the code: ### def add(self, occasion, function): if self.connections.has_key(occasion) == 0: self.connections[occasion].append(function) ### imagine what happens if self.connections is an empty dictionary. What happens to the condition that's being tested by the 'if' statement? However, the first version of the code: ### def add(self, occasion, function): if self.connections.has_key(occasion) == 0: self.connections[occasion]=[function] else: self.connections[occasion].append(function) ### can be shortened if we know about a list's setdefault() method: ### def add(self, occasion, function): self.connections.setdefault(occasion, []).append(function) ### Good luck to you! From dyoo at hkn.eecs.berkeley.edu Tue Dec 30 01:18:37 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 30 01:18:45 2003 Subject: [Tutor] Are there any free project to download for studying? In-Reply-To: <200312301324625.SM01292@chenren> Message-ID: > When I first touch Python,I have loved it.I use it to complete several > assignment that my teacher gave us. But I want to see what else Python > can do. So I want to see other good programs and project. Is there > anyone who can tell me how I can get them.Thanks! Hi Joe, Here are some links to programs that people have been written in Python: http://pygame.org -- Arcade games. http://uselesspython.com -- 'Useless' Python programs. http://scipy.org -- Scientific tools with Python. I chose those three links because they show different applications: games, curious tinkering, and science. But Python's so "general-purpose" that I know I'm ignoring another good application somewhere... *grin* There are some other program repositories out there; you may find: http://www.python.org/pypi and http://www.vex.net/parnassus/ useful. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Tue Dec 30 01:23:29 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 30 01:23:34 2003 Subject: [Tutor] Calling append() method in a list In-Reply-To: Message-ID: > Ah! In the second version of the code: > > ### > def add(self, occasion, function): > if self.connections.has_key(occasion) == 0: > self.connections[occasion].append(function) > ### > > imagine what happens if self.connections is an empty dictionary. What > happens to the condition that's being tested by the 'if' statement? Hi Tony, I should be a little more explicit, just in case. *grin*. You tested: ### l1=[] l1.append(1) l1.append(2) l1.append(3) ### and this is fine. But it might be more relevant to test the situation with the dictionary: ### d = {} d['names'].append('tony') ### Hope this helps! From kennethg at pd.jaring.my Tue Dec 30 10:18:30 2003 From: kennethg at pd.jaring.my (Kenneth Gomez) Date: Tue Dec 30 10:05:38 2003 Subject: [Tutor] How to store key->multiple values? Message-ID: <5.2.0.9.0.20031230224251.02ce9df0@mbox.jaring.my> Hello, I would like some advice on how to store data of these types : Material Name Young's Modulus Poisson's Ratio Density Aluminum 200e5 .27 2700 Steel 200e9 .33 8020 I would like this to be in an array where I can access the first subscript and get the rest of the values. I thought of using a dictionary but I found that dictionary only allows one value per key. Can I use lists instead? How do I create a multidimensional list or tuple? How would I insert the values into a multidimensional list? I would really appreciate some advice. Thank you. Cheers, Kenneth Gomez, http://www.kgomez.com 'I didn't lose my mind, it's backed up on tape somewhere.' From rick at niof.net Tue Dec 30 10:11:05 2003 From: rick at niof.net (Rick Pasotto) Date: Tue Dec 30 10:09:49 2003 Subject: [Tutor] How to store key->multiple values? In-Reply-To: <5.2.0.9.0.20031230224251.02ce9df0@mbox.jaring.my> References: <5.2.0.9.0.20031230224251.02ce9df0@mbox.jaring.my> Message-ID: <20031230151105.GE21244@niof.net> On Tue, Dec 30, 2003 at 11:18:30PM +0800, Kenneth Gomez wrote: > Hello, > > I would like some advice on how to store data of these types : > > Material Name Young's Modulus Poisson's Ratio Density > Aluminum 200e5 .27 2700 > Steel 200e9 .33 8020 > > I would like this to be in an array where I can access the first > subscript and get the rest of the values. > > I thought of using a dictionary but I found that dictionary only > allows one value per key. That 'one value' can easily be a tuple or list of values. -- "The man who produces while others dispose of his product is a slave." -- Ayn Rand Rick Pasotto rick@niof.net http://www.niof.net From tpc at csua.berkeley.edu Tue Dec 30 10:22:50 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Dec 30 10:23:01 2003 Subject: [Tutor] The biggest snake on earth is a Python ;-) In-Reply-To: <200312291516.15752.w.richert@gmx.net> Message-ID: <20031230072206.R61631-100000@localhost.name> http://news.bbc.co.uk/2/hi/in_depth/photo_gallery/3356945.stm Four more pictures of this Python without garbage collection ;-) On Mon, 29 Dec 2003, Willi Richert wrote: > Hi, > > I'm sorry, the article is only in German. But the image is in > international ;-) > > http://www.spiegel.de/panorama/0,1518,280028,00.html > > Have fun, > wr > > -- > A fool with a tool is just a fool. With a tool. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Janssen at rz.uni-frankfurt.de Tue Dec 30 10:22:58 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Tue Dec 30 10:23:12 2003 Subject: [Tutor] How to store key->multiple values? In-Reply-To: <5.2.0.9.0.20031230224251.02ce9df0@mbox.jaring.my> References: <5.2.0.9.0.20031230224251.02ce9df0@mbox.jaring.my> Message-ID: On Tue, 30 Dec 2003, Kenneth Gomez wrote: > I would like some advice on how to store data of these types : > > Material Name Young's Modulus Poisson's Ratio Density > Aluminum 200e5 .27 2700 > Steel 200e9 .33 8020 > > I would like this to be in an array where I can access the first subscript > and get the rest of the values. > > I thought of using a dictionary but I found that dictionary only allows one > value per key. Can I use lists instead? How do I create a multidimensional > list or tuple? How would I insert the values into a multidimensional list? Lists and dictionaries can easily nest (Just another one of python's strengths?). To do it store another list/dict as the value: >>> d = {} >>> d["Aluminum"] = {"Young's Modulus": 200e5, ... "Poisson's Ratio": .27, ... "Density": 2700, ... } >>> d["Aluminum"]["Density"] 2700 perhaps it's easier to store the second level into a list (values are then identified by list-index, eg d["Aluminum"][2] always shows Density). When your data gets more and more complicated, you might want to see how it looks pretty: >>> import pprint >>> pprint.pprint(d) [snip: pretty printed representation of d] Michael From vicki.stanfield at ROCHE.COM Tue Dec 30 10:22:14 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Dec 30 10:23:37 2003 Subject: FW: [Tutor] Async Events (or How to manage interrupts in Python?) Message-ID: I wasn't able to look for it last night, but I believe I at least have sample code at home. When I get home tonight, I will look. In the meantime, can anyone point us to a tutorial on threads? --vicki -----Original Message----- From: "H?ctor Villafuerte D." [mailto:hec.villafuerte@telgua.com.gt] Sent: Tuesday, December 30, 2003 11:59 AM To: Stanfield, Vicki {D167~Indianapolis} Subject: Re: [Tutor] Async Events (or How to manage interrupts in Python?) Ok, let's try threads. Would you please post that explanation you mention? Thanks Vicki! Hector Stanfield, Vicki {D167~Indianapolis} wrote: >I would think that this requires threading. I recently saw a decent >explanation of how to do it in Python. I will look for it, and if no >one beats me to it, I will post it later. > >--vicki > >-----Original Message----- >From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On >Behalf Of "H?ctor Villafuerte D." >Sent: Monday, December 29, 2003 1:49 PM >To: tutor@python.org >Subject: [Tutor] Async Events (or How to manage interrupts in Python?) > > >Hi all, >First, let me tell you what all this is about. I have a very nice >script >that does the following: >1. It checks if there is a file in an Open VMS server. >2. If it finds the file, it connects via TELNET (using telnetlib, of >course!) and ZIP's it. >3. Once the file is compressed, it GET's it via FTP (using ftplib) 4. When the file is in my local machine, the script does some processing >on it. >5. If the script was given more than one file to look at the VMS server >it goes back to Step 1. > >Quite simple, right? >The thing is that I don't want this to perform sequentially... it's >such >a waste of time! >Because while the script is in Steps 3 and 4, it could perfectly be >executing Steps 1 and 2. >When I used to program microcontrollers (PICs) we had good old >interrupts to handle things >like this. Any ideas how to do this in Python? > >Thank you so much, in advance. >Hector > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From vicki.stanfield at ROCHE.COM Tue Dec 30 10:54:19 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Dec 30 10:55:21 2003 Subject: [Tutor] Async Events (or How to manage interrupts in Python?) Message-ID: Here is a page that might get you started. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65222 --vicki -----Original Message----- From: "H?ctor Villafuerte D." [mailto:hec.villafuerte@telgua.com.gt] Sent: Tuesday, December 30, 2003 11:59 AM To: Stanfield, Vicki {D167~Indianapolis} Subject: Re: [Tutor] Async Events (or How to manage interrupts in Python?) Ok, let's try threads. Would you please post that explanation you mention? Thanks Vicki! Hector Stanfield, Vicki {D167~Indianapolis} wrote: >I would think that this requires threading. I recently saw a decent >explanation of how to do it in Python. I will look for it, and if no >one beats me to it, I will post it later. > >--vicki > >-----Original Message----- >From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On >Behalf Of "H?ctor Villafuerte D." >Sent: Monday, December 29, 2003 1:49 PM >To: tutor@python.org >Subject: [Tutor] Async Events (or How to manage interrupts in Python?) > > >Hi all, >First, let me tell you what all this is about. I have a very nice >script >that does the following: >1. It checks if there is a file in an Open VMS server. >2. If it finds the file, it connects via TELNET (using telnetlib, of >course!) and ZIP's it. >3. Once the file is compressed, it GET's it via FTP (using ftplib) 4. When the file is in my local machine, the script does some processing >on it. >5. If the script was given more than one file to look at the VMS server >it goes back to Step 1. > >Quite simple, right? >The thing is that I don't want this to perform sequentially... it's >such >a waste of time! >Because while the script is in Steps 3 and 4, it could perfectly be >executing Steps 1 and 2. >When I used to program microcontrollers (PICs) we had good old >interrupts to handle things >like this. Any ideas how to do this in Python? > >Thank you so much, in advance. >Hector > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From arkamir at softhome.net Mon Dec 29 18:57:24 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Tue Dec 30 11:59:01 2003 Subject: [Tutor] Re: Tutor Digest, Vol 5, Issue 70 In-Reply-To: References: Message-ID: <1072742243.9948.19.camel@quercus> Hmm I got MySQLdb to work for me. I'm using 2.2.3 Fedora Core 1 Mysql v4.0.15 and Mysql-python v0.9.1-9. I'm using apache too. The trick I *think* cant quite remember is to go to an older version of MySQLdb. Also as a sidenote does MySQLdb even work on your interpreter??(I dont think it does but just making sure) From sigurd at 12move.de Tue Dec 30 12:11:12 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Dec 30 12:15:21 2003 Subject: [Tutor] need a little help In-Reply-To: (matteo's message of "Tue, 30 Dec 2003 05:07:13 +0100") References: Message-ID: On 30 Dec 2003, matteo <- matteolovatti@mac.com wrote: > but if i write > server_smtp.sendmail("matteolovatti@mac.com","matteolovatti@mac.com",variable) > i get a message with matteolovatti@mac.com as "from:" > but there's nothing in the "To:" !! What is the value of ?variable?? You need to distinguish the envelope from (MAIL FROM: in rrc 2822) and the envelope recipient (RCPT TO: in rfc2822) from what you can read in an email header as From: and To:. These are different things. The two first are for the system to find the recipient of a message the later two are only for human readers; they are part of what comes after `DATA' in a smtp dialog. Perhaps you read first rfc2821 and rfc2822 before you try to send e-mails with Python. Karl -- Please do *not* send copies of replies to me. I read the list From red_necks25 at yahoo.com Tue Dec 30 13:08:35 2003 From: red_necks25 at yahoo.com (moore william) Date: Tue Dec 30 13:08:39 2003 Subject: [Tutor] Saving Data Message-ID: <20031230180835.74569.qmail@web13608.mail.yahoo.com> I am lookign for a toutorial on how to save data created in a program so that it can be used when the parogram is started again. __________________________________ Do you Yahoo!? Find out what made the Top Yahoo! Searches of 2003 http://search.yahoo.com/top2003 From tpc at csua.berkeley.edu Tue Dec 30 13:24:40 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Dec 30 13:24:46 2003 Subject: [Tutor] Saving Data In-Reply-To: <20031230180835.74569.qmail@web13608.mail.yahoo.com> Message-ID: <20031230101334.I62381-100000@localhost.name> hi William, If you are creating a standalone application that will need to save state info so it can read from this file upon restart, have you looked at Python pickle ? I hope that helps you. On Tue, 30 Dec 2003, moore william wrote: > I am lookign for a toutorial on how to save data > created in a program so that it can be used when the > parogram is started again. > > __________________________________ > Do you Yahoo!? > Find out what made the Top Yahoo! Searches of 2003 > http://search.yahoo.com/top2003 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From darnold02 at sprynet.com Tue Dec 30 13:51:09 2003 From: darnold02 at sprynet.com (don arnold) Date: Tue Dec 30 13:51:20 2003 Subject: [Tutor] Saving Data References: <20031230180835.74569.qmail@web13608.mail.yahoo.com> Message-ID: <03d601c3cf05$e5196a20$ce11ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "moore william" To: "Python" Sent: Tuesday, December 30, 2003 12:08 PM Subject: [Tutor] Saving Data > I am lookign for a toutorial on how to save data > created in a program so that it can be used when the > parogram is started again. > While not a tutorial, here's a simple example that uses the shelve module. This module lets you use a dictionary-like object to manage persistent data. import shelve s = shelve.open('c:/temp2/mydata') if s.has_key('score'): s['score'] += 10 else: s['score'] = 0 print 'score is %d' % s['score'] s.close() Here's a few sample runs: C:\Python22\mystuff>\python22\python shelf.py score is 0 C:\Python22\mystuff>\python22\python shelf.py score is 10 C:\Python22\mystuff>\python22\python shelf.py score is 20 HTH, Don From dyoo at hkn.eecs.berkeley.edu Tue Dec 30 14:31:47 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 30 14:31:57 2003 Subject: [Tutor] Saving Data In-Reply-To: <20031230180835.74569.qmail@web13608.mail.yahoo.com> Message-ID: On Tue, 30 Dec 2003, moore william wrote: > I am lookign for a tutorial on how to save data created in a program so > that it can be used when the parogram is started again. Hi Moore, What kind of data are you trying to save? Alan Gauld's tutorial may help: it has a section on file "input/output": http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm and that tutorial should give you a better grasp for open()ing, write()ing, and close()ing files. You may also find the 'shelve' module useful: http://www.python.org/doc/lib/module-shelve.html Shelves act like dictionaries --- except that when we put things into them, they actually store on disk! So they should allow you to save the state of your program so that you can restore it later. If you have more questions on this, please feel free to send another question on Python-Tutor; we'll be happy to help. Good luck! From red_necks25 at yahoo.com Tue Dec 30 14:54:57 2003 From: red_necks25 at yahoo.com (moore william) Date: Tue Dec 30 14:55:01 2003 Subject: [Tutor] Questor Message-ID: <20031230195457.54072.qmail@web13607.mail.yahoo.com> Did anyone every find the anwser to Questor.py? __________________________________ Do you Yahoo!? Find out what made the Top Yahoo! Searches of 2003 http://search.yahoo.com/top2003 From darnold02 at sprynet.com Tue Dec 30 15:00:46 2003 From: darnold02 at sprynet.com (don arnold) Date: Tue Dec 30 15:00:57 2003 Subject: [Tutor] Saving Data References: <20031230192635.87846.qmail@web13608.mail.yahoo.com> Message-ID: <03fa01c3cf0f$9e2e2830$ce11ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "moore william" To: "don arnold" Sent: Tuesday, December 30, 2003 1:26 PM Subject: Re: [Tutor] Saving Data > Thanks, will this work with a phone book application > to save names and nubers? Sure. Basically, you attempt to load your variable from the shelve, modify it, then save it back to the shelve. Here's some quick (and not too pretty code): import shelve s = shelve.open('c:/temp2/mydata') if s.has_key('phonebook'): phonebook = s['phonebook'] else: phonebook = {} while 1: print print print '1. Enter a phone number' print '2. Show all numbers' print '3. Quit' print choice = int(raw_input('Enter your choice: ')) if choice == 1: name = raw_input('Name : ') phone = raw_input('Phone: ') phonebook[name] = phone elif choice == 2: print for name, phone in phonebook.items(): print '%-20s : %-14s' % (name, phone) elif choice == 3: break ##save phonebook when done s['phonebook'] = phonebook s.close() [First run to get some data in the phonebook:] C:\Python22\mystuff>c:\python22\python shelf2.py 1. Enter a phone number 2. Show all numbers 3. Quit Enter your choice: 1 Name : Don Arnold Phone: 402-123-4567 1. Enter a phone number 2. Show all numbers 3. Quit Enter your choice: 1 Name : John Smith Phone: 301-596-9384 1. Enter a phone number 2. Show all numbers 3. Quit Enter your choice: 1 Name : Bob Davis Phone: 495-030-3030 1. Enter a phone number 2. Show all numbers 3. Quit Enter your choice: 2 John Smith : 301-596-9384 Bob Davis : 495-030-3030 Don Arnold : 402-123-4567 1. Enter a phone number 2. Show all numbers 3. Quit Enter your choice: 3 [Second run to show data was saved:] C:\Python22\mystuff>c:\python22\python shelf2.py 1. Enter a phone number 2. Show all numbers 3. Quit Enter your choice: 2 John Smith : 301-596-9384 Bob Davis : 495-030-3030 Don Arnold : 402-123-4567 1. Enter a phone number 2. Show all numbers 3. Quit Enter your choice: 3 C:\Python22\mystuff> HTH, Don PS: Be sure to hit 'Reply All' when responding to Tutor emails. That way, everyone on the list has a chance to contribute to the discussion. From arkamir at softhome.net Tue Dec 30 15:22:03 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Tue Dec 30 15:22:05 2003 Subject: [Tutor] mistake naming class Message-ID: <1072815723.7933.0.camel@quercus> Recently while programming I made a mistake of naming a class open. In it it uses the builtin open(). When I run it I get an error saying that __init__() takes 3 arguements but only 1 is given. For example, this is quite similiar to what I have: class open(object): def __init__(world, person, animal): open('foo.txt', 'r') Any solutions other then renaming my class, because going through the code looking for calls to class open is not going to be fun Can anyone give me insight why this does not work. It works fine in the interpreter. class open(object): def __init__(self): layout = __builtins__.open('login.html', 'r') but it never works in a script. I get an error saying dict object has no attribute open From arkamir at softhome.net Tue Dec 30 15:22:51 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Tue Dec 30 15:22:36 2003 Subject: [Tutor] Lambdas Message-ID: <1072815771.7933.2.camel@quercus> Okay well I guess I chose I bad example for lambdas, but i cant find any good tutorials on them on the web. So I guess a better question is. Where is an in depth tutorial on lambdas. Even though there not all that necessary From vicki.stanfield at ROCHE.COM Tue Dec 30 15:26:03 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Dec 30 15:26:50 2003 Subject: [Tutor] mistake naming class Message-ID: I recommend that you bite the bullet now and use some editor with a global search to change them all. You really don't want to leave that problem around for reuse. You might be able to get around it, but I don't recommend doing so. --vicki -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Conrad Koziol Sent: Tuesday, December 30, 2003 3:22 PM To: tutor@python.org Subject: [Tutor] mistake naming class Recently while programming I made a mistake of naming a class open. In it it uses the builtin open(). When I run it I get an error saying that __init__() takes 3 arguements but only 1 is given. For example, this is quite similiar to what I have: class open(object): def __init__(world, person, animal): open('foo.txt', 'r') Any solutions other then renaming my class, because going through the code looking for calls to class open is not going to be fun Can anyone give me insight why this does not work. It works fine in the interpreter. class open(object): def __init__(self): layout = __builtins__.open('login.html', 'r') but it never works in a script. I get an error saying dict object has no attribute open _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From helena_b2001 at yahoo.com Tue Dec 30 17:06:59 2003 From: helena_b2001 at yahoo.com (helena bhaska) Date: Tue Dec 30 17:07:07 2003 Subject: [Tutor] import MySQLdb problem In-Reply-To: <21519.1072750114@www60.gmx.net> Message-ID: <20031230220659.79792.qmail@web20405.mail.yahoo.com> Hi, Thanks for the suggestion, but this does not fix the problem. My previous idea about modifying ld.so.conf stopped working too for some reason after I played with it for a while. I have also tried the following in shell: LD_LIBRARY_PATH=path to MySQLdb export LD_LIBRARY_PATH python blah.py but this does not work either, again getting the same ImportError! simply going to python and saying import MySQLdb works, ti does know where to look for it, it's only broken when I try to do that on a server. :((( As I mentioned before SetEnv and PassEnv in apache conf file does not fix this problem either (Can someone please explain how these work in more detail than in the man pages?) I have also tried reinstalling MySQLdb. sorry, this is probably a stupid problem, but I am stuck with it and getting desperate :( -Helena --- "J顤g_W闤ke" wrote: > > Hi, > > Hello! > > [ snip ] > > > I am probably misunderstanding how to use > > LS_LIBRARY_PATH, I assumed that I was supposed to > give > ^ > D? > > > path to where MySQLdb is, so here is what I have > done: > > > > SetEnv LD_LIBRARY_PATH > > /usr/local/lib/python2.3/site-packages/ > > PassEnv LD_LIBRARY_PATH > > os.environ['LD_LIBRARY_PATH']='/usr/local/lib/python2.3/site-packages/' > at the beginning of your python script? > > [ snip ] > > > -Helena > > HTH, HAND - J"o! > > > -- > "Wir k霵nen alles sehen, was sich bewegt > und wir k霵nen alles zerst顤en, was wir sehen." > -- Richard Perle > > +++ GMX - die erste Adresse fr Mail, Message, More > +++ > Neu: Preissenkung fr MMS und FreeMMS! > http://www.gmx.net > > __________________________________ Do you Yahoo!? Find out what made the Top Yahoo! Searches of 2003 http://search.yahoo.com/top2003 From zanshou at wanadoo.fr Tue Dec 30 17:29:34 2003 From: zanshou at wanadoo.fr (Twily) Date: Tue Dec 30 17:28:37 2003 Subject: [Tutor] Newbie self-introduction + little encoding problem References: Message-ID: <002201c3cf24$69cd2450$0bbd0d50@nagetb3uxkybix> Sorry for the short message...but I wanted to say thank you everyone for the answers, it really helped me to understand what was going on with my list ^__^ Twily From cspears2002 at yahoo.com Tue Dec 30 18:30:33 2003 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue Dec 30 18:30:41 2003 Subject: [Tutor] writing a program in Python Message-ID: <20031230233033.26483.qmail@web12403.mail.yahoo.com> I guess this is a stupid question, but I am going to ask anyway... How do you actually write a program in Python? I know how to use IDLE to manipulate data, but how do I write several lines of code that goes out and does stuff. ===== "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "Far more creativity, today, goes into the marketing of products than into the products themselves..." -"Pattern Recognition" by William Gibson From matteolovatti at mac.com Tue Dec 30 19:29:54 2003 From: matteolovatti at mac.com (matteo) Date: Tue Dec 30 19:30:09 2003 Subject: [Tutor] Looking for a Python IDE Message-ID: <742DADBF-3B28-11D8-9C38-00039314F97E@mac.com> hi everybody, can someone please suggest me a good python IDE for Mac Os X ? thanks matteo From klappnase at freenet.de Tue Dec 30 19:55:17 2003 From: klappnase at freenet.de (Michael Lange) Date: Tue Dec 30 20:02:44 2003 Subject: [Tutor] writing a program in Python In-Reply-To: <20031230233033.26483.qmail@web12403.mail.yahoo.com> References: <20031230233033.26483.qmail@web12403.mail.yahoo.com> Message-ID: <20031231015517.611bc923.klappnase@freenet.de> On Tue, 30 Dec 2003 15:30:33 -0800 (PST) Christopher Spears wrote: > I guess this is a stupid question, but I am going to > ask anyway... > > How do you actually write a program in Python? I know > how to use IDLE to manipulate data, but how do I write > several lines of code that goes out and does stuff. > Hi Christopher! You just have to write your program in any text editor (if your using IDLE select from the menu File --> New) and store it. If your using windows you should store it with the ".py" extension, so you can run it from your file browser with a double-click like any other program (you will see then a DOS box pop up every time you start your program; if you want to avoid this use the extension ."pyw" instead of ".py" ). On linux the ".py" extension is not necessarily required, however you will have to make the file you wrote executable first ("chmod -v 755 path-to-your-file"). You can run it then with "python path-to-your-file" (if you make the first line of your file: #!/usr/bin/env python you can run it like any other program without calling the python interpreter every time). I hope this helped Good luck Michael From hcohen2 at comcast.net Tue Dec 30 20:06:34 2003 From: hcohen2 at comcast.net (hcohen2) Date: Tue Dec 30 20:07:32 2003 Subject: [Tutor] Saving Data In-Reply-To: <20031230180835.74569.qmail@web13608.mail.yahoo.com> References: <20031230180835.74569.qmail@web13608.mail.yahoo.com> Message-ID: <3FF2211A.3040906@comcast.net> moore william wrote: >I am lookign for a toutorial on how to save data >created in a program so that it can be used when the >parogram is started again. > >__________________________________ >Do you Yahoo!? >Find out what made the Top Yahoo! Searches of 2003 >http://search.yahoo.com/top2003 > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > this may well be a case where: "... if the only tool you know is a hammer - every problem looks like a nail ..." How much data? If it is a fair amount, wouldn't it be safer and more efficient to store it in a database? There are several reasons for my posing this possibility, one may be ascribed to the pity saying above, the other is my encountering clients' fears of databases. Despite my predilection, as a data tool they are extremely useful. If this is off the mark, please ignore me ;-) From SiggymakerCorp at aol.com Tue Dec 30 20:37:38 2003 From: SiggymakerCorp at aol.com (SiggymakerCorp@aol.com) Date: Tue Dec 30 20:37:50 2003 Subject: [Tutor] subscribe me off ( i will report aol on u if u dont subscribe me off Message-ID: <1d5.17836d1d.2d238262@aol.com> From ralobao at click21.com.br Tue Dec 30 21:51:23 2003 From: ralobao at click21.com.br (Ruivaldo Neto) Date: Tue Dec 30 21:52:34 2003 Subject: [Tutor] OFF I want to know about the universities In-Reply-To: <20031230072206.R61631-100000@localhost.name> References: <20031230072206.R61631-100000@localhost.name> Message-ID: <200312310049.21086.ralobao@click21.com.br> Hi everybody, sorry for the off-topic but i know there are many students of universities from other countrys in this list, i am Brazilian, and i want to know if it is possible to i make my university on your country and if it is difficult to get in it ? please answer me i am very curious about it. -- RS: Ruivaldo Neto From carroll at tjc.com Tue Dec 30 22:51:22 2003 From: carroll at tjc.com (Terry Carroll) Date: Tue Dec 30 22:51:29 2003 Subject: FW: [Tutor] Async Events (or How to manage interrupts in Python?) In-Reply-To: Message-ID: On Tue, 30 Dec 2003, Stanfield, Vicki {D167~Indianapolis} wrote: > In the meantime, can anyone point us to a tutorial on threads? I don't know of an online source, but I recently finished up Thomas Christopher's "Python Programming Patterns"; while most of the book's style didn't agree with me, I thought his explanation of threads was excellent. (By the way, I'm not dissing the rest of the book; it was just a style that doesn't work for me. Others may find it perfectly good.) -- Terry Carroll Santa Clara, CA carroll@tjc.com From missive at hotmail.com Tue Dec 30 23:40:59 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Dec 30 23:41:03 2003 Subject: [Tutor] Re: mistake naming class Message-ID: >Recently while programming I made a mistake of naming a class open. In >it it uses the builtin open(). When I run it I get an error saying that >__init__() takes 3 arguements but only 1 is given. >For example, this is quite similiar to what I have: > >class open(object): > def __init__(world, person, animal): > open('foo.txt', 'r') > >Any solutions other then renaming my class, because going through the >code looking for calls to class open is not going to be fun file is now the recommended way to open a file, so ... class open(object): def __init__(world, person, animal): file('foo.txt', 'r') would work. Or, you could do something like ... save_open = open class open(object): def __init__(world, person, animal): save_open('foo.txt', 'r') _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From carroll at tjc.com Wed Dec 31 01:31:58 2003 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 31 01:32:02 2003 Subject: [Tutor] Pythonwin bug (or misfeature)? Message-ID: I suspect I've found a bug (or perhaps just an unimplemented feature) in PythonWin. Apparently, the "browse" facility will not work with an instance of a class inherited from a dictionary (although it will, if you instead inherit from UserDict.UserDict). First, a check: is this really a bug, or am I just doing something wrong? Here's my code: ----------------------------------------------- class udict1(dict): def __init__(self, indices=None, entries=None): dict.__init__(self) if indices is not None: for i in range(0,len(indices)): self[indices[i]] = entries[i] import UserDict class udict2(UserDict.UserDict): def __init__(self, indices=None, entries=None): UserDict.UserDict.__init__(self) if indices is not None: for i in range(0,len(indices)): self.data[indices[i]] = entries[i] z1 = udict1([1,2,3,4,5], ['a1', 'b1','c1', 'd1', 'e1']) z2 = udict2([1,2,3,4,5], ['a2', 'b2','c2', 'd2', 'e2']) print " dict: len is", len(z1), z1 print "userdict: len is", len(z2), z2 ----------------------------------------------- Both instances print, as expected: dict: len is 5 {1: 'a1', 2: 'b1', 3: 'c1', 4: 'd1', 5: 'e1'} userdict: len is 5 {1: 'a2', 2: 'b2', 3: 'c2', 4: 'd2', 5: 'e2'} It also runs okay under pythonwin; but, underpythonwin, when I use the Tools / Browser menu item, I can browse z2 (the UserDict-based instance), but not z1 (the dict-based instance). Trying to browse z1 gives an error "This object cannot be browsed." Am I making an error either in my code or in Pythonwin? Second question: I'm using the Activestate Python (2.3.2). Pythonwin is not a standard part of Python, right? If that's right, I wouldn't report this as a bug through the Python project at Sourceforge; but where would I report it (I don't think it's Activestate's, either)? -- Terry Carroll Santa Clara, CA carroll@tjc.com From abli at freemail.hu Wed Dec 31 10:27:15 2003 From: abli at freemail.hu (Abel Daniel) Date: Wed Dec 31 10:27:21 2003 Subject: [Tutor] Re: how to make .py file to .exe file? In-Reply-To: <200312301314765.SM01292@chenren> (chenren@tydic.com's message of "Tue, 30 Dec 2003 13:6:56 +0800") References: <200312301314765.SM01292@chenren> Message-ID: "??" writes: > I'm a real beginner.I want to ask a question. How to make a executable file > so that > I can click it and run it directly? Thanks. I don't think you have to make it into an executable file for that. IIRC, under Windows, the default install of python associates the .py and .pyw endings with pythonw.exe, so clicking on a file whose name ends in .py runs it. The problem might be that this opens a command-line window which is closed when the program finishes, so you might not be able to inspect the results (and only see the screen flash as the window is opened and the closed). (see http://www.python.org/doc/faq/windows.html#how-do-i-make-python-scripts-executable) To make the command-line window stay open, you should make it wait for a keypress when it is finished, with the getch( ) function of the msvcrt module (for example) -- Abel Daniel From dyoo at hkn.eecs.berkeley.edu Wed Dec 31 13:19:42 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 31 13:20:09 2003 Subject: [Tutor] subscribe me off ( i will report aol on u if u dont subscribe me off [How to unsubscribe] In-Reply-To: <1d5.17836d1d.2d238262@aol.com> Message-ID: Hi SiggymakerCorp, No need for the threat! You can unsubscribe yourself by visiting: http://mail.python.org/mailman/listinfo/tutor Go down to the form near the bottom of the page --- you should see an 'Edit Options' form. From there, you should be able to see an 'unsubscribe' button. If you have problems unsubscribing yourself, please contact the list administrator at: 'tutor-admin@python.org', and the administrators will be happy to help you unsubscribe. Sincerely, Danny Yoo From dyoo at hkn.eecs.berkeley.edu Wed Dec 31 13:20:32 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 31 13:20:38 2003 Subject: [Tutor] Saving Data (fwd) Message-ID: ---------- Forwarded message ---------- Date: Wed, 31 Dec 2003 10:58:48 -0500 (EST) From: Vicki Stanfield To: Danny Yoo Subject: Re: [Tutor] Saving Data > > You may also find the 'shelve' module useful: > > http://www.python.org/doc/lib/module-shelve.html > > Shelves act like dictionaries --- except that when we put things into > them, they actually store on disk! So they should allow you to save the > state of your program so that you can restore it later. Do I need to change the protocol passed depending on whether I am working on a Windows machine or a Linux box? It appears not. Is there more information on this protocol variable? I have only found that it may be None, 1, 2, or 3 and that only None and 1 work. There seems to be a shortage of information on this option (in pickle or shelve descriptions). --vicki From dyoo at hkn.eecs.berkeley.edu Wed Dec 31 13:51:50 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 31 13:51:56 2003 Subject: [Tutor] Lambdas In-Reply-To: <1072815771.7933.2.camel@quercus> Message-ID: On Tue, 30 Dec 2003, Conrad Koziol wrote: > Okay well I guess I chose I bad example for lambdas, but i cant find any > good tutorials on them on the web. So I guess a better question is. > Where is an in depth tutorial on lambdas. Even though there not all that > necessary Hi Conrad, A tongue-in-cheek response to this might be something like: http://mitpress.mit.edu/sicp/full-text/book/book.html *grin* No, actually, there are a few articles by David Mertz that you might like: http://gnosis.cx/publish/tech_index_cp.html Mertz writes extensively on functional programming in Python, and anything that has the word 'functional programming' there on that page will most likely have a lambda. But lambda's shouldn't cause too many problems: they're just expressions that evaluate to functions. We're basically doing something like 'lambda' (plus a little more) whenever we define a function: ### >>> def square(x): ... return x * x ... >>> square ### Here, square is just a variable name for a function value. And values in Python can be passed around, just like numbers and strings: ### >>> def compose(f, g, x): ... """Returns f(g(x)).""" ... return f(g(x)) ... >>> def double(x): ... return x * 2 ... >>> compose(double, square, 42) 3528 ### Now, we can get a handle on the same kind of value through 'lambda': ### >>> square >>> >>> lambda x: x * x at 0x60ab0> ### And this value behaves the same way as 'square': ### >>> square(4) 16 >>> >>> (lambda x: x * x)(4) 16 >>> >>> compose(lambda x: 2*x, ... lambda x: x * x, ... 42) 3528 ### So whenever we're defining a function with 'def', we are actually doing something like a 'lambda': we are creating a function value, but we're also binding that function value to a name. When we use 'lambda' directly, we don't have to bind that value to a name. So 'lambda' is simply a way of creating functions that we can pass around, without having to store them immediately as variable names. If it helps, think of the distinction between naming a value with a variable and using it: ### >>> x = 17 >>> square(x) 289 ### as opposed to using that value 'on the fly': ### >>> 17 17 >>> square(17) 289 ### Python's version of 'lambda' is actually designed to be a lot weaker than the 'lambda' in most 'functional' programming languages. The rationale, I think, is that if we're going to be playing with functions, it'll be good to give them explicit names for human maintainability. The language itself encourages us to use 'def' instead of 'lambda' to force us to name the majority of our functions. If you really want to play around with the full power of lambdas, perhaps the "tongue-in-cheek" reference at the very top won't be so tongue-in-cheek for you. *grin* It sounds like you're interested, so you may want to play with the Scheme language if you have some time --- 'lambda' is more powerful in that language. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Dec 31 13:59:13 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 31 13:59:17 2003 Subject: [Tutor] writing a program in Python In-Reply-To: <20031230233033.26483.qmail@web12403.mail.yahoo.com> Message-ID: On Tue, 30 Dec 2003, Christopher Spears wrote: > I guess this is a stupid question, but I am going to ask anyway... Hi Christopher, This is not a stupid question at all. It's a very crucial one! > How do you actually write a program in Python? I know how to use IDLE > to manipulate data, but how do I write several lines of code that goes > out and does stuff. I wrote a small tutorial that shows how to write a program in IDLE: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html The screen-captures are a little dated --- I need to fix my Windows box someday... --- but should help show how to save and run Python programs. The main idea is that we'll need to save our individual program instructions in a separate 'program file'. Think of a Word document, except that instead of saving English text, we're saving Python source code. Once we save our program file to disk, then whenever we want to run that program, we can tell Python to run across the whole program file. Hope this helps! From pythontutor at venix.com Wed Dec 31 14:04:43 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Dec 31 14:04:46 2003 Subject: [Tutor] Saving Data (fwd) In-Reply-To: References: Message-ID: <3FF31DCB.2090703@venix.com> http://www.python.org/doc/lib/node63.html 3.14.2 Data stream format This specifies: 0 ascii data 1 binary data (but new style classes use a log of bytes) 2 binary data (stores new style classes efficiently) protocol replaces the old bin parameter which was true/false for binary. protocol 2 is new in Python2.3 (I can't test that easily, but believe it is true.) Danny Yoo wrote: > > ---------- Forwarded message ---------- > Date: Wed, 31 Dec 2003 10:58:48 -0500 (EST) > From: Vicki Stanfield > To: Danny Yoo > Subject: Re: [Tutor] Saving Data > > >>You may also find the 'shelve' module useful: >> >> http://www.python.org/doc/lib/module-shelve.html >> >>Shelves act like dictionaries --- except that when we put things into >>them, they actually store on disk! So they should allow you to save the >>state of your program so that you can restore it later. > > > Do I need to change the protocol passed depending on whether I am working > on a Windows machine or a Linux box? It appears not. Is there more > information on this protocol variable? I have only found that it may be > None, 1, 2, or 3 and that only None and 1 work. There seems to be a > shortage of information on this option (in pickle or shelve descriptions). > > --vicki > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From vicki.stanfield at ROCHE.COM Wed Dec 31 14:14:16 2003 From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Wed Dec 31 14:15:43 2003 Subject: [Tutor] Saving Data (fwd) Message-ID: Okay, the description of format 2 is a little lean on that site. It doesn't say that it is binary although had I understood pickling better, I'd have gotten it. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Lloyd Kvam Sent: Wednesday, December 31, 2003 2:05 PM Cc: Tutor Subject: Re: [Tutor] Saving Data (fwd) http://www.python.org/doc/lib/node63.html 3.14.2 Data stream format This specifies: 0 ascii data 1 binary data (but new style classes use a log of bytes) 2 binary data (stores new style classes efficiently) protocol replaces the old bin parameter which was true/false for binary. protocol 2 is new in Python2.3 (I can't test that easily, but believe it is true.) Danny Yoo wrote: > > ---------- Forwarded message ---------- > Date: Wed, 31 Dec 2003 10:58:48 -0500 (EST) > From: Vicki Stanfield > To: Danny Yoo > Subject: Re: [Tutor] Saving Data > > >>You may also find the 'shelve' module useful: >> >> http://www.python.org/doc/lib/module-shelve.html >> >>Shelves act like dictionaries --- except that when we put things into >>them, they actually store on disk! So they should allow you to save >>the state of your program so that you can restore it later. > > > Do I need to change the protocol passed depending on whether I am > working on a Windows machine or a Linux box? It appears not. Is there > more information on this protocol variable? I have only found that it > may be None, 1, 2, or 3 and that only None and 1 work. There seems to > be a shortage of information on this option (in pickle or shelve > descriptions). > > --vicki > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Wed Dec 31 14:17:02 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 31 14:17:06 2003 Subject: [Tutor] Saving Data (fwd) In-Reply-To: Message-ID: > > Shelves act like dictionaries --- except that when we put things into > > them, they actually store on disk! So they should allow you to save the > > state of your program so that you can restore it later. > > Do I need to change the protocol passed depending on whether I am > working on a Windows machine or a Linux box? It appears not. Is there > more information on this protocol variable? I have only found that it > may be None, 1, 2, or 3 and that only None and 1 work. There seems to be > a shortage of information on this option (in pickle or shelve > descriptions). Hi Vicki, The protocols should be compatible with all platforms. There's a short description of the differences between protocol 0, 1, and 2 in the Library Documentation of the 'pickle' module: http://www.python.org/doc/lib/node63.html Protocol 0 is a text-based format, and protocols 1 and 2 are binary formats. They're all very Python specific, so if you need an output format that's more platform independent, you may want to use something like xml_pickle: http://www-106.ibm.com/developerworks/xml/library/x-matters11.html Hope this helps! From Christian.SAVEAN at communaute-urbaine-nantes.fr Tue Dec 30 09:39:01 2003 From: Christian.SAVEAN at communaute-urbaine-nantes.fr (SAVEAN Christian) Date: Mon Jan 5 13:48:33 2004 Subject: [Tutor] help leraning python Message-ID: I 'm learning by myself the Python's language, starting from an e-book called 'How to think like a computer scientist' traduced in french by Gerard Swinnen Some exercises are difficult and whitout solution described in the e-book Does somebody know where I can find the solution, or other examples with their comments, to support my learning lessons? Thanks a lot > Christian SAVEAN > Direction Int?gration/Support Applications > D?l?gation aux syst?mes d'information > communaut?urbainedeNantes > 44923 Nantes cedex 9 > T?l?phone : 02.40.41.50.86 > Portable : 06.75.24.99.79 > T?l?copie : 02.40.20.38.48 > >