From alan.gauld at freenet.co.uk Wed Nov 1 00:32:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 31 Oct 2006 23:32:12 -0000 Subject: [Tutor] One million and counting Message-ID: <000301c6fd44$cb513c60$04000100@XPpro> Hi folks, In just thought I'd mention that my web tutor has now passed the million visitors mark. Thanks to all those on the tutor list who have paid a visit. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jgcox39 at highstream.net Wed Nov 1 03:37:27 2006 From: jgcox39 at highstream.net (Joe Cox) Date: Tue, 31 Oct 2006 18:37:27 -0800 Subject: [Tutor] Simple calculator Message-ID: I found this simple calculator on the web: from Tkinter import * from math import * ###http://sunsite.uakom.sk/sunworldonline/swol-02-1998/swol-02-python.htmlBy Cameron Laird and Kathryn Soraiz...Getting Started with Python### def evaluate(event): label['text'] = "Result: " + str(eval(expression.get())) frame = Frame(None) entry = Entry(frame) entry['textvariable'] = expression = StringVar() entry.bind("", evaluate) label = Label(frame) button = Button(frame, text = "Submit", command = evaluate) frame.pack() entry.pack() label.pack() button.pack() frame.mainloop() I get this: >>> Traceback (most recent call last): File "D:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "D:\Python24\Calculator\Calc.py", line 12, in ? entry.bind("", evaluate) File "D:\Python24\lib\lib-tk\Tkinter.py", line 933, in bind return self._bind(('bind', self._w), sequence, func, add) File "D:\Python24\lib\lib-tk\Tkinter.py", line 888, in _bind self.tk.call(what + (sequence, cmd)) TclError: no events specified in binding Please have a look for me thanks! Joe Cox 513-293-4830 From pyro9219 at gmail.com Wed Nov 1 00:38:42 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 31 Oct 2006 15:38:42 -0800 Subject: [Tutor] One million and counting In-Reply-To: <000301c6fd44$cb513c60$04000100@XPpro> References: <000301c6fd44$cb513c60$04000100@XPpro> Message-ID: Very cool! Congrats! On 10/31/06, Alan Gauld wrote: > > Hi folks, > > In just thought I'd mention that my web tutor has now passed > the million visitors mark. Thanks to all those on the tutor > list who have paid a visit. > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/5e0d8645/attachment.html From alan.gauld at btinternet.com Wed Nov 1 00:47:23 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 31 Oct 2006 23:47:23 -0000 Subject: [Tutor] Mapping to object attributes References: <000301c6fd3c$09c10e70$28645f0a@1430A0316> Message-ID: "Mike Hansen" wrote > I've got a web form with a lot of form fields. I'd like to be able > to map > the form fields to an object's attributes. I'm having a little > trouble > figuring out how. John has answered that bit. > There will be some fields I'll need to validate(boolean or int), but > the > majority are just text fields that can be passed to the object. One thing you can do is store the validation functions in the dictionary with the value. def intValidator(i): try: return int(i) except: return None def boolValidator(b): try: return b and True or False except: return None mapping = { 'field': (intvalue, intValidator), 'another': (boolvalue,boolValidator)...} You can then access the validator like so: value = mapping[fieldname][0] validator = mapping[fieldname][1] value = validator(value) if value == None: #ooops! or more concisely: value = mapping[fieldname][1](mapping[fieldname]0]) This style of validation has the "benefit" (or side-effect if you prefer) of converting compatible types into true types. eg. validating a string or float representation of an integer returns the actual integer value. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jazedo at netcabo.pt Wed Nov 1 00:53:19 2006 From: jazedo at netcabo.pt (Jorge Azedo) Date: Tue, 31 Oct 2006 23:53:19 +0000 Subject: [Tutor] One million and counting In-Reply-To: <000301c6fd44$cb513c60$04000100@XPpro> References: <000301c6fd44$cb513c60$04000100@XPpro> Message-ID: <4547E1EF.5040800@netcabo.pt> Congrats! I know that what I know about Python I learned from your guide, so a personal thanks from me :) Alan Gauld wrote: > Hi folks, > > In just thought I'd mention that my web tutor has now passed > the million visitors mark. Thanks to all those on the tutor > list who have paid a visit. > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pwigginpy at yahoo.com Wed Nov 1 00:48:59 2006 From: pwigginpy at yahoo.com (Peter Wig) Date: Tue, 31 Oct 2006 15:48:59 -0800 (PST) Subject: [Tutor] python and mingw home directory problem Message-ID: <20061031234859.9544.qmail@web58101.mail.re3.yahoo.com> Hi everyone, I'm trying to run some commands with mingw from python. However, somehow my home directory (for mingw) is being changed when I initialize tk. Here's an example: import os from Tkinter import Tk os.system("C:/msys/1.0/bin/sh.exe --login -i -c 'pwd' ") # just print my home directory root = Tk() os.system("C:/msys/1.0/bin/sh.exe --login -i -c 'pwd' ") # just print my home directory ^^^^^^^^^^^^^^^^^^^^^^^^^^^ output: /home/Pete /c/Documents and Settings/Pete As you can see, initializing Tk has somehow changed my mingw home directory from "/home/Pete" to "/c/Documents and Settings/Pete". Since "/home/Pete" has my login script, this is a major problem. The actual change happens at _tkinter.create(.....) during Tk(). Any ideas? Thanks, Pete --------------------------------- Get your email and more, right on the new Yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/40b75f45/attachment.htm From carroll at tjc.com Wed Nov 1 01:19:05 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 31 Oct 2006 16:19:05 -0800 (PST) Subject: [Tutor] One million and counting In-Reply-To: <000301c6fd44$cb513c60$04000100@XPpro> Message-ID: On Tue, 31 Oct 2006, Alan Gauld wrote: > In just thought I'd mention that my web tutor has now passed > the million visitors mark. Thanks to all those on the tutor > list who have paid a visit. I've visted that site a few times. Thanks and congratulations. From amadeo.bellotti at gmail.com Wed Nov 1 02:25:45 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Tue, 31 Oct 2006 20:25:45 -0500 Subject: [Tutor] off topic GNOME background Message-ID: my background just disappeared it shows a black screen like it cant find the default background. if that makes sense I've added my own and it cant seem to find it i removed it and re added it it doesn't seem to be working though anyone have any ideas? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/d4081248/attachment.html From jazedo at netcabo.pt Wed Nov 1 02:26:55 2006 From: jazedo at netcabo.pt (Jorge Azedo) Date: Wed, 01 Nov 2006 01:26:55 +0000 Subject: [Tutor] Suggestions about documenting a function In-Reply-To: References: <4546A6F5.8060203@netcabo.pt> Message-ID: <4547F7DF.6060609@netcabo.pt> Thanks for all your help guys, but after trying to read just bits and pieces of the manual and not understanding a single sentence, much less a single chapter, I decided to just put this function on hold until I read the whole Tutorial from start to finish. I just hope it doesn't take to long... From cappy2112 at gmail.com Wed Nov 1 02:34:19 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 31 Oct 2006 17:34:19 -0800 Subject: [Tutor] Running multiple version of Python on 1 windows Message-ID: <8249c4ac0610311734p653a31f7q36ef07fbce237ead@mail.gmail.com> >From Kent >>You don't say what OS you are running but under Windows it is trivial to >>have multiple versions of Python installed, I have 2.3, 2.4 and 2.5. >>They are each in their own directories, all in the system path. I have >>aliases called py23, py24 and py25 that let me launch the version I >>want. I'm pretty sure you can do something similar with other OSes. If you want script abc.py to run with python 2.3, and script xyz.py to run with 2.5, how can you control this form the command line? python abc.py vs python xyz.py? One task I'm faced with is evaluating the benefits of migrating a huge framework from 2.3 to 2.4? I'd rather use two machines for this rather than install 2.4 on my 2.3machine. If I need to make any changes in the scripts to work on 2.4, I don't want that interfering with a fully-working 2.3 environment. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061031/223350eb/attachment-0001.htm From gtnorton at earthlink.net Wed Nov 1 03:17:34 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Tue, 31 Oct 2006 20:17:34 -0600 Subject: [Tutor] One million and counting In-Reply-To: <000301c6fd44$cb513c60$04000100@XPpro> References: <000301c6fd44$cb513c60$04000100@XPpro> Message-ID: <454803BE.2090400@earthlink.net> Alan Gauld wrote: >Hi folks, > >In just thought I'd mention that my web tutor has now passed >the million visitors mark. Thanks to all those on the tutor >list who have paid a visit. > >Alan Gauld >Author of the Learn to Program web site >http://www.freenetpages.co.uk/hp/alan.gauld >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Congratulations Alan! I visited your site many times when first learning Python. Keep up the good work. Glenn -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From prem.sah at gmail.com Wed Nov 1 05:45:26 2006 From: prem.sah at gmail.com (Premnath Sah) Date: Wed, 1 Nov 2006 10:15:26 +0530 Subject: [Tutor] immutable objects In-Reply-To: References: <795ac870610310458mf07d9c4ra385b2375c46d3e0@mail.gmail.com> <454758D6.4080109@tds.net> <795ac870610310626p532f5bbajc5fbbcbc74ea9317@mail.gmail.com> Message-ID: <795ac870610312045v231f835cr5d426045b1865756@mail.gmail.com> On 10/31/06, Danny Yoo wrote: > > > Im facing a problem with SOAPpy which checks for recursive objects using > > id(obj). > > > > In my case value for 2 SOAP headers are same and iam getting a recursion > > error. if i pass different object with same value SOAPpy does not > complain > > (by using str(value) and unicode(value)). > > If you can include a stack trace of that error with SOAPpy, that would be > excellent. This sounds bizarre. > > You won't be able to do anything with the ints: some of them are > internally interned by the runtime, and you can't control this. So I'd > instead focus on why SOAPpy is failing. It shouldn't have to worry about > recursively traversing the ints: they don't have any structure to > traverse! So a stack trace would be useful. > here is the stack trace. i know that SOAPpy is doing wrong by not checking the type of the element along with id(ele). I thought if there is any work around the problem i could use that without upgrading SOAPpy after it is fixed. >>> import SOAPpy >>> rmt = SOAPpy.SOAPProxy(url, header = SOAPpy.Types.headerType(data={'username': 'prem', 'password': 'prem'})) Traceback (most recent call last): File "", line 1, in ? NameError: name 'url' is not defined >>> url = "http://soap.test.com/" >>> rmt = SOAPpy.SOAPProxy(url, header = SOAPpy.Types.headerType(data={'username': 'prem', 'password': 'prem'})) >>> rmt.testcall() Traceback (most recent call last): File "", line 1, in ? File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/Client.py", line 453, in __call__ return self.__r_call(*args, **kw) File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/Client.py", line 475, in __r_call self.__hd, self.__ma) File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/Client.py", line 338, in __call config = self.config, noroot = self.noroot) File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/SOAPBuilder.py", line 624, in buildSOAP return t.build() File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/SOAPBuilder.py", line 112, in build self.dump(self.header, "Header", typed = typed) File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/SOAPBuilder.py", line 294, in dump meth(obj, tag, typed, ns_map) File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/SOAPBuilder.py", line 580, in dump_instance self.dump(getattr(obj,k), k, typed, ns_map) File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/SOAPBuilder.py", line 294, in dump meth(obj, tag, typed, ns_map) File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/SOAPBuilder.py", line 358, in dump_string id = self.checkref(obj, tag, ns_map) File "/cv/vendor/lib/python2.4/site-packages/SOAPpy/SOAPBuilder.py", line 260, in checkref raise RecursionError, "Cannot serialize recursive object" SOAPpy.Errors.RecursionError: >>> -- With Regards, Premnath Sah T. H. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061101/413d46e0/attachment.htm From wescpy at gmail.com Wed Nov 1 09:44:34 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 1 Nov 2006 00:44:34 -0800 Subject: [Tutor] Running multiple version of Python on 1 windows machine In-Reply-To: <4546AE4B.9060006@tds.net> References: <44290fe50610301720v43cfc357p91e5756516c3722f@mail.gmail.com> <4546AE4B.9060006@tds.net> Message-ID: <78b3a9580611010044y2ea9d8b2t9f976c311812453d@mail.gmail.com> > try > import sqlite3 as sqlite # Python 2.5 > except ImportError: > from pysqlite2 import dbapi2 as sqlite i second kent's suggestion here. in fact, i ran into a very similar issue while working on the database chapter for the new edition of the book. i had 2.4.2 with pysqlite 2.1.3 on it, and then when the first release of 2.5 came out, discovered sqlite3. for testing and compatibility reasons, i wanted the example app to run under both, so i added practically the same lines to the code for ushuffle_db.py: if db == 'sqlite': try: import sqlite3 except ImportError, e: try: from pysqlite2 import dbapi2 as sqlite3 except ImportError, e: return None DB_EXC = sqlite3 : i save off the same module again as DB_EXC to catch exceptions -- this value is different for different databases, i.e. "import _mysql_exceptions as DB_EXC" or "from gadfly import gadfly; DB_EXC = gadfly". then in other parts of the code, i can do stuff like: try: cur.execute('SELECT * FROM table') except DB_EXC.OperationalError, e: # handle error for any database type the entire source can be found here if you're interested: http://corepython.com -> Source Code -> ch21 -> ushuffle_db.py good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ajkadri at googlemail.com Wed Nov 1 11:14:45 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 1 Nov 2006 10:14:45 +0000 Subject: [Tutor] How to capture 'Ctrl+c' in Python Message-ID: Hi folks, How can I know that the user has pressed a particular key or a combination of keys.. for example 'q' or 'Ctrl-c' ....? Thanks in anticipation. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061101/c1f4ac6e/attachment.htm From kent37 at tds.net Wed Nov 1 12:07:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Nov 2006 06:07:07 -0500 Subject: [Tutor] Running multiple version of Python on 1 windows In-Reply-To: <8249c4ac0610311734p653a31f7q36ef07fbce237ead@mail.gmail.com> References: <8249c4ac0610311734p653a31f7q36ef07fbce237ead@mail.gmail.com> Message-ID: <45487FDB.40605@tds.net> Tony Cappellini wrote: > >From Kent > >>You don't say what OS you are running but under Windows it is trivial to > >>have multiple versions of Python installed, I have 2.3, 2.4 and 2.5. > >>They are each in their own directories, all in the system path. I have > >>aliases called py23, py24 and py25 that let me launch the version I > >>want. I'm pretty sure you can do something similar with other OSes. > > If you want script abc.py to run with python 2.3, and script xyz.py to > run with 2.5, how can you control this form the command line? I have Python 2.3, 2.4 and 2.5 all installed on my PC. All three directories are in my PATH. As it happens Python2.4 is first in the path so if I just run 'python' I get Python 2.4. In each Python directory I have a copy of python.exe that is named py2x; i.e. py23.exe, py24.exe, py25.exe. python.exe is small so I don't mind copying it; a shortcut would probably work as well. Since each dir is in the path, I can select which version to run by the name of the exe. > > python abc.py py23 abc.py > > vs > > python xyz.py? py24 xyz.py > > > One task I'm faced with is evaluating the benefits of migrating a huge > framework from 2.3 to 2.4? > I'd rather use two machines for this rather than install 2.4 on my 2.3 > machine. > > If I need to make any changes in the scripts to work on 2.4, I don't > want that interfering with a fully-working 2.3 environment. You should be able to have two copies of the scripts on your machine, a working production copy and a development copy. Kent > From kent37 at tds.net Wed Nov 1 12:22:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Nov 2006 06:22:07 -0500 Subject: [Tutor] Simple calculator In-Reply-To: References: Message-ID: <4548835F.7030601@tds.net> Joe Cox wrote: > I found this simple calculator on the web: > > from Tkinter import * > from math import * > ###http://sunsite.uakom.sk/sunworldonline/swol-02-1998/swol-02-python.htmlBy > Cameron Laird and Kathryn Soraiz...Getting Started with Python### > > def evaluate(event): > label['text'] = "Result: " + str(eval(expression.get())) Note that eval() is highly insecure. For this program maybe it doesn't matter but in general you should avoid using eval(). > > frame = Frame(None) > > entry = Entry(frame) > entry['textvariable'] = expression = StringVar() > entry.bind("", evaluate) You need to say what kind of event you want to bind to the evaluate function. In this case you probably want to bind the Enter key so you would use entry.bind("", evaluate) Kent > > label = Label(frame) > > button = Button(frame, text = "Submit", command = evaluate) > > frame.pack() > entry.pack() > label.pack() > button.pack() > frame.mainloop() > > I get this: > >>>> Traceback (most recent call last): > File > "D:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "D:\Python24\Calculator\Calc.py", line 12, in ? > entry.bind("", evaluate) > File "D:\Python24\lib\lib-tk\Tkinter.py", line 933, in bind > return self._bind(('bind', self._w), sequence, func, add) > File "D:\Python24\lib\lib-tk\Tkinter.py", line 888, in _bind > self.tk.call(what + (sequence, cmd)) > TclError: no events specified in binding > > Please have a look for me thanks! > > > > > Joe Cox > 513-293-4830 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From klappnase at freenet.de Wed Nov 1 12:31:59 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 1 Nov 2006 12:31:59 +0100 Subject: [Tutor] Simple calculator In-Reply-To: References: Message-ID: <20061101123159.501769e5.klappnase@freenet.de> Hi Joe, On Tue, 31 Oct 2006 18:37:27 -0800 "Joe Cox" wrote: > I found this simple calculator on the web: > > from Tkinter import * > from math import * > ###http://sunsite.uakom.sk/sunworldonline/swol-02-1998/swol-02-python.htmlBy > Cameron Laird and Kathryn Soraiz...Getting Started with Python### > > def evaluate(event): > label['text'] = "Result: " + str(eval(expression.get())) > > frame = Frame(None) > > entry = Entry(frame) > entry['textvariable'] = expression = StringVar() > entry.bind("", evaluate) > > label = Label(frame) > > button = Button(frame, text = "Submit", command = evaluate) > > frame.pack() > entry.pack() > label.pack() > button.pack() > frame.mainloop() > > I get this: > > >>> Traceback (most recent call last): > File > "D:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "D:\Python24\Calculator\Calc.py", line 12, in ? > entry.bind("", evaluate) > File "D:\Python24\lib\lib-tk\Tkinter.py", line 933, in bind > return self._bind(('bind', self._w), sequence, func, add) > File "D:\Python24\lib\lib-tk\Tkinter.py", line 888, in _bind > self.tk.call(what + (sequence, cmd)) > TclError: no events specified in binding > this code seems to be quite old, so I guess that the line entry.bind("", evaluate) used to be legal in older version of Tk. I don't know what it is supposed to do, though. Maybe there was some default event defined for such cases. In today's Tk you need to specify an event sequence the callback should be bound to, like entry.bind("", evaluate) This does not work either, because you will get a syntax error on "incomplete" expressions like "3*" when trying to type in "3*3" , so the evaluate() callback will have to catch this syntax error: def evaluate(event): try: label['text'] = "Result: " + str(eval(expression.get())) except SyntaxError: pass This still does not work, when you press the "submit" button you get: Traceback (most recent call last): File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) TypeError: evaluate() takes exactly 1 argument (0 given) so the constructor must be changed like: def evaluate(event=None): (...) because the Tkinter.Button's "command" callback is called without any arguments (again I don't know if this was different in old Tk versions). With these changes at least the few simple examples I tried seem to work. I hope this helps Michael From andreas at kostyrka.org Wed Nov 1 12:59:45 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 01 Nov 2006 12:59:45 +0100 Subject: [Tutor] How to capture 'Ctrl+c' in Python In-Reply-To: References: Message-ID: <1162382385.18283.38.camel@andi-lap> Am Mittwoch, den 01.11.2006, 10:14 +0000 schrieb Asrarahmed Kadri: > > > Hi folks, > How can I know that the user has pressed a particular key or c > combination of keys.. for example 'q' or 'Ctrl-c' ....? In practice that depends upon your environment. Unix/Linux, MacOS, Windows, GUI vs. cmdline have all different ways to "read" from the keyboard. Ctrl-c OTOH, usually sends the interrupt signal to the process, and as such can caught via the KeyboardInterrupt exception: try: somework except KeyboardInterrupt: ctrlc_caught Andreas > > Thanks in anticipation. > > Regards, > > Asrarahmed > > > > -- > To HIM you shall return. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061101/254f59fe/attachment.pgp From Mike.Hansen at atmel.com Wed Nov 1 15:50:43 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 1 Nov 2006 07:50:43 -0700 Subject: [Tutor] Mapping to object attributes Message-ID: <57B026980605A64F9B23484C5659E32E3CA2B0@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld > Sent: Tuesday, October 31, 2006 4:47 PM > To: tutor at python.org > Subject: Re: [Tutor] Mapping to object attributes > > > "Mike Hansen" wrote > > > I've got a web form with a lot of form fields. I'd like to be able > > to map > > the form fields to an object's attributes. I'm having a little > > trouble > > figuring out how. > > John has answered that bit. > > > There will be some fields I'll need to validate(boolean or > int), but > > the > > majority are just text fields that can be passed to the object. > > One thing you can do is store the validation functions in the > dictionary with the value. > > def intValidator(i): > try: return int(i) > except: return None > > def boolValidator(b): > try: return b and True or False > except: return None > > mapping = { 'field': (intvalue, intValidator), > 'another': (boolvalue,boolValidator)...} > > You can then access the validator like so: > > value = mapping[fieldname][0] > validator = mapping[fieldname][1] > value = validator(value) > if value == None: #ooops! > > or more concisely: > > value = mapping[fieldname][1](mapping[fieldname]0]) > > This style of validation has the "benefit" (or side-effect if you > prefer) > of converting compatible types into true types. eg. validating a > string > or float representation of an integer returns the actual integer > value. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > Thanks John and Alan. Your suggestions will make my code less nested. Mike From dyoo at hkn.eecs.berkeley.edu Wed Nov 1 16:31:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Nov 2006 07:31:39 -0800 (PST) Subject: [Tutor] immutable objects In-Reply-To: <795ac870610312045v231f835cr5d426045b1865756@mail.gmail.com> References: <795ac870610310458mf07d9c4ra385b2375c46d3e0@mail.gmail.com> <454758D6.4080109@tds.net> <795ac870610310626p532f5bbajc5fbbcbc74ea9317@mail.gmail.com> <795ac870610312045v231f835cr5d426045b1865756@mail.gmail.com> Message-ID: > here is the stack > trace. i know that SOAPpy is doing wrong by not checking the type of > the element along with id(ele). > I thought if there is any work around the problem i could use that without > upgrading SOAPpy after it is fixed. Hi Premnath, You might want to see if some other SOAP module might be better supported. The last version of SOAPpy that I've seen appears to have been released in 2005, and as far as I can tell, the project is languishing a bit. Most of the energy toward Python and SOAP seems to be focused on the Zolera SOAP Infrastructure (ZSI) project, which can be found at: http://pywebsvcs.sourceforge.net/ Thanks again for the stack trace; it helps pinpoint some problems. I did some quick checks on the stack trace; the line numbers from the stack trace aren't matching up with SOAPpy 0.12.0., so I'm not sure if this problem has already been fixed or not. You may want to make sure you have the latest release of SOAPpy if you continue using that module. The code for SOAPBuilder.dump_string() just doesn't look right to me. Why does one have to do a checkref() on it when serializing the string data, given that a string has no internal structure to speak of? I think the code there is just wrong. You're seeing this failure simply because you're passing in two strings with the same id, which should be perfectly legal and fine. SOAPpy is definitely at fault here. I kludged up the recursive-checking code on strings (i.e. turned it off), and now see the following: ########################################################################## >>> import SOAPpy >>> rmt = SOAPpy.SOAPProxy("http://soap.test.com", ... header = SOAPpy.Types.headerType( ... data = {'username': 'prem', ... 'password': 'prem'})) >>> rmt.testcall() Traceback (most recent call last): File "", line 1, in ? File "SOAPpy/Client.py", line 470, in __call__ return self.__r_call(*args, **kw) File "SOAPpy/Client.py", line 492, in __r_call self.__hd, self.__ma) File "SOAPpy/Client.py", line 363, in __call config = self.config) File "SOAPpy/Client.py", line 263, in call raise HTTPError(code, msg) SOAPpy.Errors.HTTPError: ########################################################################## which looks a little more promising. In fact, you can see this yourself by playing a small trick: ####################################################################### >>> rmt = SOAPpy.SOAPProxy("http://soap.test.com", header = SOAPpy.Types.headerType(data={'username': 'p' + 'rem', 'password': 'p' + 'rem'})) >>> rmt.testcall() Traceback (most recent call last): File "", line 1, in ? File "SOAPpy/Client.py", line 470, in __call__ return self.__r_call(*args, **kw) File "SOAPpy/Client.py", line 492, in __r_call self.__hd, self.__ma) File "SOAPpy/Client.py", line 363, in __call config = self.config) File "SOAPpy/Client.py", line 263, in call raise HTTPError(code, msg) SOAPpy.Errors.HTTPError: ####################################################################### Forcing the manual string concatenation lets you go on, but this is just a silly kludge around what is fundamentally a bad SOAPYpy bug. My current recommendation is to try using ZSI instead: the SOAPpy code base appears to have a bit of bit rot. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Nov 1 16:33:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Nov 2006 07:33:48 -0800 (PST) Subject: [Tutor] off topic GNOME background In-Reply-To: References: Message-ID: On Tue, 31 Oct 2006, Amadeo Bellotti wrote: > my background just disappeared it shows a black screen like it cant find > the default background. if that makes sense I've added my own and it > cant seem to find it i removed it and re added it it doesn't seem to be > working though anyone have any ideas? Try asking on a GNOME-specific forum; I don't think any of us have good technical expertise on the GNOME desktop. Try: http://www.gnome.org/support/ I'm sure the people there will be happy to help you. From zhangyi5 at gmail.com Wed Nov 1 16:39:10 2006 From: zhangyi5 at gmail.com (yuz10@psu.edu) Date: Wed, 1 Nov 2006 10:39:10 -0500 Subject: [Tutor] how to test .mov file using python Message-ID: I know that python has many packages such as nose, which is for testing. Now I am going to test a quicktime file to find out if it works properly. Are there an existing python package could do that? And how to write the program? Thanks, Yi -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061101/f8a04ba0/attachment.html From ajkadri at googlemail.com Wed Nov 1 17:16:31 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 1 Nov 2006 16:16:31 +0000 Subject: [Tutor] Help me with graphs...using tkinter Message-ID: Hi folks, I want to draw bar-charts using Tkinter. I am not able to find material on this topic. Help me........ Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061101/f3516688/attachment-0001.htm From kent37 at tds.net Wed Nov 1 17:18:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Nov 2006 11:18:27 -0500 Subject: [Tutor] I am terribly confused about "generators" and "iterators".. Help me In-Reply-To: <45423541.4020306@tds.net> References: <45422F86.1070401@alum.rpi.edu> <45423541.4020306@tds.net> Message-ID: <4548C8D3.6080908@tds.net> Kent Johnson wrote: > Bob Gailer wrote: >> Asrarahmed Kadri wrote: >>> >>> What are generators and iterators...??And why are they are needed..?? >>> >>> I can do my stuff with a 'for' or a 'while' loop.. so why do I need an >>> ITERATOR..? >> iterators & generators do not replace while or for loops! > > No, actually iterators and generators are the foundation of for loops. > Whenever you write a for loop, Python creates an iterator to return the > values that are assigned to the loop variables. > > Writing your own iterator is a way to make a new kind of thing that can > be iterated in a for loop. Generators are a convenient way to make > iterators. They can be used to encapsulate loop logic. For some examples > see these recent threads: > http://thread.gmane.org/gmane.comp.python.tutor/36068/focus=36069 > http://article.gmane.org/gmane.comp.python.tutor/36105/match=generator Here is another good article about what happens behind the scenes of a for loop: http://online.effbot.org/2006_11_01_archive.htm#for Kent From prem.sah at gmail.com Wed Nov 1 18:03:11 2006 From: prem.sah at gmail.com (Premnath Sah) Date: Wed, 1 Nov 2006 22:33:11 +0530 Subject: [Tutor] immutable objects In-Reply-To: References: <795ac870610310458mf07d9c4ra385b2375c46d3e0@mail.gmail.com> <454758D6.4080109@tds.net> <795ac870610310626p532f5bbajc5fbbcbc74ea9317@mail.gmail.com> <795ac870610312045v231f835cr5d426045b1865756@mail.gmail.com> Message-ID: <795ac870611010903r55b559c3tab435cc39a129a03@mail.gmail.com> On 11/1/06, Danny Yoo wrote: > > > here is the stack > > trace. i know that SOAPpy is doing wrong by not checking the type of > > the element along with id(ele). > > I thought if there is any work around the problem i could use that > without > > upgrading SOAPpy after it is fixed. > > Hi Premnath, > > You might want to see if some other SOAP module might be better supported. > The last version of SOAPpy that I've seen appears to have been released in > 2005, and as far as I can tell, the project is languishing a bit. Most of > the energy toward Python and SOAP seems to be focused on the Zolera SOAP > Infrastructure (ZSI) project, which can be found at: > > http://pywebsvcs.sourceforge.net/ > > > Thanks again for the stack trace; it helps pinpoint some problems. I did > some quick checks on the stack trace; the line numbers from the stack > trace aren't matching up with SOAPpy 0.12.0., so I'm not sure if this > problem has already been fixed or not. You may want to make sure you have > the latest release of SOAPpy if you continue using that module. > > > The code for SOAPBuilder.dump_string() just doesn't look right to me. > Why does one have to do a checkref() on it when serializing the string > data, given that a string has no internal structure to speak of? I think > the code there is just wrong. You're seeing this failure simply because > you're passing in two strings with the same id, which should be perfectly > legal and fine. SOAPpy is definitely at fault here. > > I kludged up the recursive-checking code on strings (i.e. turned it off), > and now see the following: > > ########################################################################## > >>> import SOAPpy > >>> rmt = SOAPpy.SOAPProxy("http://soap.test.com", > ... header = SOAPpy.Types.headerType( > ... data = {'username': 'prem', > ... 'password': 'prem'})) > >>> rmt.testcall() > Traceback (most recent call last): > File "", line 1, in ? > File "SOAPpy/Client.py", line 470, in __call__ > return self.__r_call(*args, **kw) > File "SOAPpy/Client.py", line 492, in __r_call > self.__hd, self.__ma) > File "SOAPpy/Client.py", line 363, in __call > config = self.config) > File "SOAPpy/Client.py", line 263, in call > raise HTTPError(code, msg) > SOAPpy.Errors.HTTPError: > ########################################################################## > > which looks a little more promising. > > > In fact, you can see this yourself by playing a small trick: > > ####################################################################### > >>> rmt = SOAPpy.SOAPProxy("http://soap.test.com", header = > SOAPpy.Types.headerType(data={'username': 'p' + 'rem', 'password': 'p' + > 'rem'})) > >>> rmt.testcall() > Traceback (most recent call last): > File "", line 1, in ? > File "SOAPpy/Client.py", line 470, in __call__ > return self.__r_call(*args, **kw) > File "SOAPpy/Client.py", line 492, in __r_call > self.__hd, self.__ma) > File "SOAPpy/Client.py", line 363, in __call > config = self.config) > File "SOAPpy/Client.py", line 263, in call > raise HTTPError(code, msg) > SOAPpy.Errors.HTTPError: > ####################################################################### > > Forcing the manual string concatenation lets you go on, but this is just a > silly kludge around what is fundamentally a bad SOAPYpy bug. > > > My current recommendation is to try using ZSI instead: the SOAPpy code > base appears to have a bit of bit rot. > > > Good luck to you! > Thanks for your reply. I will definitely look into ZSI -- With Regards, Premnath Sah T. H. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061101/8263db95/attachment.html From andreas at kostyrka.org Wed Nov 1 18:35:55 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 01 Nov 2006 18:35:55 +0100 Subject: [Tutor] how to test .mov file using python In-Reply-To: References: Message-ID: <1162402555.18283.42.camel@andi-lap> Am Mittwoch, den 01.11.2006, 10:39 -0500 schrieb yuz10 at psu.edu: > I know that python has many packages such as nose, which is for > testing. Now I am going to test a quicktime file to find out if it > works properly. Are there an existing python package could do that? > And how to write the program? AFAIK, quicktime mov files are complicated beasts, with an embedded scripting language and all. Depending upon your requirement, you can use mplayer to test if the video track decodes, or need manual testing with the quicktime player. Andreas > > Thanks, > Yi > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061101/edcd4a71/attachment.pgp From klappnase at freenet.de Wed Nov 1 21:25:09 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 1 Nov 2006 21:25:09 +0100 Subject: [Tutor] Help me with graphs...using tkinter In-Reply-To: References: Message-ID: <20061101212509.617f2a06.klappnase@freenet.de> Hi Asrarahmed, On Wed, 1 Nov 2006 16:16:31 +0000 "Asrarahmed Kadri" wrote: > Hi folks, > > I want to draw bar-charts using Tkinter. I am not able to find material on > this topic. > have a look at the Canvas widget and especially at its create_rectangle() method. Documentation is here: I hope this helps Michael From pyro9219 at gmail.com Wed Nov 1 21:54:24 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 1 Nov 2006 12:54:24 -0800 Subject: [Tutor] How to capture 'Ctrl+c' in Python In-Reply-To: <1162382385.18283.38.camel@andi-lap> References: <1162382385.18283.38.camel@andi-lap> Message-ID: Do you by chance know of a way to capture special keys like "Print Screen"? I have a small script to grab all they keycodes, but it doesn't seem to catch several keys on the keyboard. I've got a utility that I'd like to be able to automagically get a screenshot when something goes wrong so I dont have to hope the user can re-create the error. Universal support would be best, but WinXP is the main OS. On 11/1/06, Andreas Kostyrka wrote: > > Am Mittwoch, den 01.11.2006, 10:14 +0000 schrieb Asrarahmed Kadri: > > > > > > Hi folks, > > How can I know that the user has pressed a particular key or c > > combination of keys.. for example 'q' or 'Ctrl-c' ....? > > In practice that depends upon your environment. Unix/Linux, MacOS, > Windows, GUI vs. cmdline have all different ways to "read" from the > keyboard. > > Ctrl-c OTOH, usually sends the interrupt signal to the process, and as > such can caught via the KeyboardInterrupt exception: > > try: > somework > except KeyboardInterrupt: > ctrlc_caught > > Andreas > > > > > Thanks in anticipation. > > > > Regards, > > > > Asrarahmed > > > > > > > > -- > > To HIM you shall return. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061101/f3356eaa/attachment.htm From zhangyi5 at gmail.com Wed Nov 1 21:57:38 2006 From: zhangyi5 at gmail.com (yuz10@psu.edu) Date: Wed, 1 Nov 2006 15:57:38 -0500 Subject: [Tutor] how to test .mov file using python In-Reply-To: <1162402555.18283.42.camel@andi-lap> References: <1162402555.18283.42.camel@andi-lap> Message-ID: Andreas, Thank you very much for your reply. "Using mplayer to test if the video track decodes" sounds like a good idea. I am a new python user. Could you please talk more details about how to do that. Thanks again, Yi On 11/1/06, Andreas Kostyrka wrote: > > Am Mittwoch, den 01.11.2006, 10:39 -0500 schrieb yuz10 at psu.edu: > > I know that python has many packages such as nose, which is for > > testing. Now I am going to test a quicktime file to find out if it > > works properly. Are there an existing python package could do that? > > And how to write the program? > > AFAIK, quicktime mov files are complicated beasts, with an embedded > scripting language and all. Depending upon your requirement, you can use > mplayer to test if the video track decodes, or need manual testing with > the quicktime player. > > Andreas > > > > > Thanks, > > Yi > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061101/7bbcba92/attachment-0001.html From rkrajeshin at hotmail.com Wed Nov 1 22:21:18 2006 From: rkrajeshin at hotmail.com (Rajesh R) Date: Wed, 01 Nov 2006 21:21:18 +0000 Subject: [Tutor] Writing Classes in python Message-ID: I am new to Python and i have a very basic question about writing classes. Lets say i have the following code : class Sample: 'A simple class' def method1(): print 'Inside Method1' When i create an instance of the class and when i try to call the method method1, i get an error message. What i do is on the promt, i import the class, create an instance say obj=Sample and i call the method obj.method1 Am i doing something wrong or i might have not understood the class coding in Python. Thanks Rajesh _________________________________________________________________ Spice up your IM conversations. New, colorful and animated emoticons. Get chatting! http://server1.msn.co.in/SP05/emoticons/ From hugonz-lists at h-lab.net Wed Nov 1 22:25:49 2006 From: hugonz-lists at h-lab.net (Hugo Gonzalez M) Date: Wed, 01 Nov 2006 15:25:49 -0600 Subject: [Tutor] how to test .mov file using python In-Reply-To: References: <1162402555.18283.42.camel@andi-lap> Message-ID: <454910DD.6050808@h-lab.net> yuz10 at psu.edu wrote: > Andreas, > Thank you very much for your reply. "Using mplayer to test if the video > track decodes" sounds like a good idea. I am a new python user. Could > you please talk more details about how to do that. Hi, mplayer is a separate program and has nothing to do with Python (apart from the fact that you could somehow control it) You can find it at www.mplayerhq.hu There is AFAIK, no python module for working with quicktime files. For writing one, you'd need specifics on how qicktime works, but it is not meant for newbies. I recommend you pick some other project if you want to start working with Python; for the QT file, use mplayer. It even has a verbose mode for outputting lots of debugging information about the QT file. HTH Hugo From kent37 at tds.net Wed Nov 1 22:28:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Nov 2006 16:28:43 -0500 Subject: [Tutor] Writing Classes in python In-Reply-To: References: Message-ID: <4549118B.9030308@tds.net> Rajesh R wrote: > I am new to Python and i have a very basic question about writing classes. > Lets say i have the following code : > > class Sample: > 'A simple class' > > def method1(): > print 'Inside Method1' > > When i create an instance of the class and when i try to call the method > method1, i get an error message. > What i do is on the promt, i import the class, create an instance say > obj=Sample and i call the method obj.method1 > > Am i doing something wrong or i might have not understood the class coding > in Python. You need parentheses for calls in Python. Try obj=Sample() and obj.method1(). Kent From dyoo at hkn.eecs.berkeley.edu Wed Nov 1 22:36:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 Nov 2006 13:36:33 -0800 (PST) Subject: [Tutor] Writing Classes in python In-Reply-To: References: Message-ID: On Wed, 1 Nov 2006, Rajesh R wrote: > I am new to Python and i have a very basic question about writing > classes. Lets say i have the following code : > [code cut] Hi Rajesh, Take a look at a Python class tutorial: http://www.diveintopython.org/object_oriented_framework/defining_classes.html The syntax you're writing is almost right, but there are some specifics that you're missing. In Python, methods need to take an explicit 'self' parameter. Good luck! From andreas at kostyrka.org Wed Nov 1 22:38:18 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 01 Nov 2006 22:38:18 +0100 Subject: [Tutor] how to test .mov file using python In-Reply-To: References: <1162402555.18283.42.camel@andi-lap> Message-ID: <1162417098.18283.49.camel@andi-lap> Am Mittwoch, den 01.11.2006, 15:57 -0500 schrieb yuz10 at psu.edu: > Andreas, > Thank you very much for your reply. "Using mplayer to test if the Well, that's nothing python related. mplayer is an Linux movie player that can be used for all kinds of secondary uses. Andreas > video track decodes" sounds like a good idea. I am a new python user. > Could you please talk more details about how to do that. > > Thanks again, > Yi > > On 11/1/06, Andreas Kostyrka wrote: > Am Mittwoch, den 01.11.2006, 10:39 -0500 schrieb > yuz10 at psu.edu: > > I know that python has many packages such as nose, which is > for > > testing. Now I am going to test a quicktime file to find out > if it > > works properly. Are there an existing python package could > do that? > > And how to write the program? > > AFAIK, quicktime mov files are complicated beasts, with an > embedded > scripting language and all. Depending upon your requirement, > you can use > mplayer to test if the video track decodes, or need manual > testing with > the quicktime player. > > Andreas > > > > > Thanks, > > Yi > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061101/23ed0187/attachment.pgp From andreas at kostyrka.org Wed Nov 1 22:39:57 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 01 Nov 2006 22:39:57 +0100 Subject: [Tutor] Writing Classes in python In-Reply-To: References: Message-ID: <1162417197.18283.51.camel@andi-lap> class Sample: def method1(self): print "method1" s = Sample() s.method1() Please notice, you need () to invoke a method in Python, and you need an explicit self argument on the method definition. Andreas Am Mittwoch, den 01.11.2006, 21:21 +0000 schrieb Rajesh R: > I am new to Python and i have a very basic question about writing classes. > Lets say i have the following code : > > class Sample: > 'A simple class' > > def method1(): > print 'Inside Method1' > > When i create an instance of the class and when i try to call the method > method1, i get an error message. > What i do is on the promt, i import the class, create an instance say > obj=Sample and i call the method obj.method1 > > Am i doing something wrong or i might have not understood the class coding > in Python. > > Thanks > Rajesh > > _________________________________________________________________ > Spice up your IM conversations. New, colorful and animated emoticons. Get > chatting! http://server1.msn.co.in/SP05/emoticons/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061101/9c04a3cd/attachment.pgp From rkrajeshin at hotmail.com Wed Nov 1 23:04:42 2006 From: rkrajeshin at hotmail.com (Rajesh R) Date: Wed, 01 Nov 2006 22:04:42 +0000 Subject: [Tutor] Writing Classes in python In-Reply-To: <1162417197.18283.51.camel@andi-lap> Message-ID: Thanks All, It worked. Rajesh >From: Andreas Kostyrka >To: Rajesh R >CC: Tutor at python.org >Subject: Re: [Tutor] Writing Classes in python >Date: Wed, 01 Nov 2006 22:39:57 +0100 > >class Sample: > def method1(self): > print "method1" > >s = Sample() >s.method1() > >Please notice, you need () to invoke a method in Python, and you need an >explicit self argument on the method definition. > >Andreas > >Am Mittwoch, den 01.11.2006, 21:21 +0000 schrieb Rajesh R: > > I am new to Python and i have a very basic question about writing >classes. > > Lets say i have the following code : > > > > class Sample: > > 'A simple class' > > > > def method1(): > > print 'Inside Method1' > > > > When i create an instance of the class and when i try to call the method > > method1, i get an error message. > > What i do is on the promt, i import the class, create an instance say > > obj=Sample and i call the method obj.method1 > > > > Am i doing something wrong or i might have not understood the class >coding > > in Python. > > > > Thanks > > Rajesh > > > > _________________________________________________________________ > > Spice up your IM conversations. New, colorful and animated emoticons. >Get > > chatting! http://server1.msn.co.in/SP05/emoticons/ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor ><< signature.asc >> _________________________________________________________________ Live the life in style with MSN Lifestyle. Check out! http://content.msn.co.in/Lifestyle/Default From rdm at rcblue.com Thu Nov 2 00:43:36 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 01 Nov 2006 15:43:36 -0800 Subject: [Tutor] Using sys.exit() In-Reply-To: References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> Message-ID: <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> At 12:14 AM 10/31/2006, Alan Gauld wrote: >"Dick Moores" wrote > > I'd like to know how to use sys.exit() to quit a program. > > > >I see that you already figured that out. >You can also quit by raising SystemExit, which is >what sys.exit does... but you don't need to import sys... I'm afraid I don't know what you mean. How do I raise SystemExit, and why don't I need to import sys? > > Is there a way to use it the way I want to? Maybe with an argument? > >You can use an argument if you want to pass an error value >back to the OS. This is good practice if your script might be >used in a batch file or shell script So what should that value be? But if answering is a lot of bother, don't, because I don't (yet) use python to write either batch files or shell scripts. > > I'm writing a script, which in a couple of places I can't > > use "break" to quit. > >break is not intended to quit programs, break is intended >to quit loops. To exit a program you should use sys.exit() >and if its an abnormal exit provide an argument. Of course, I've been using break to exit only when it works. Why is it wrong to do so? Thanks, Dick Moores >Alan G. > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From andreas at kostyrka.org Thu Nov 2 00:56:02 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 02 Nov 2006 00:56:02 +0100 Subject: [Tutor] Using sys.exit() In-Reply-To: <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> Message-ID: <1162425362.18283.54.camel@andi-lap> Am Mittwoch, den 01.11.2006, 15:43 -0800 schrieb Dick Moores: > At 12:14 AM 10/31/2006, Alan Gauld wrote: > > >"Dick Moores" wrote > > > I'd like to know how to use sys.exit() to quit a program. > > > > > > >I see that you already figured that out. > >You can also quit by raising SystemExit, which is > >what sys.exit does... but you don't need to import sys... > > I'm afraid I don't know what you mean. How do I raise SystemExit, and > why don't I need to import sys? raise SystemExit(2) is equal to sys.exit(2) (actually sys.exit(2) just raises SystemExit(2)) >>> try: ... import sys ... sys.exit(2) ... except SystemExit, v: ... print v ... 2 And you don't need to import sys, because SystemExit is a standard exception that are builtin, available everywhere. Andreas > > > > Is there a way to use it the way I want to? Maybe with an argument? > > > >You can use an argument if you want to pass an error value > >back to the OS. This is good practice if your script might be > >used in a batch file or shell script > > So what should that value be? But if answering is a lot of bother, > don't, because I don't (yet) use python to write either batch files > or shell scripts. > > > > I'm writing a script, which in a couple of places I can't > > > use "break" to quit. > > > >break is not intended to quit programs, break is intended > >to quit loops. To exit a program you should use sys.exit() > >and if its an abnormal exit provide an argument. > > Of course, I've been using break to exit only when it works. Why is > it wrong to do so? > > Thanks, > > Dick Moores > > > >Alan G. > > > > > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061102/a38185aa/attachment.pgp From pyro9219 at gmail.com Thu Nov 2 02:58:14 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 1 Nov 2006 17:58:14 -0800 Subject: [Tutor] str.strip() help Message-ID: I can't figure out a way to .strip("string") Example might look like this: >>> myStr = "I want to strip my words." >>> print myStr.strip("my") >>> 'I want to strip words.' Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061101/05b24ce0/attachment-0001.htm From john at fouhy.net Thu Nov 2 03:11:10 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 2 Nov 2006 15:11:10 +1300 Subject: [Tutor] str.strip() help In-Reply-To: References: Message-ID: <5e58f2e40611011811u47520ec5ta97e64e0ecfdadf0@mail.gmail.com> On 02/11/06, Chris Hengge wrote: > I can't figure out a way to .strip("string") > > Example might look like this: > > >>> myStr = "I want to strip my words." > >>> print myStr.strip("my") > >>> 'I want to strip words.' .strip() only removes text from the beginning and end of the string. eg: >>> myStr = 'my words are what I want to strip' >>> print myStr.strip('my') words are what I want to strip You can use .replace() to be more general. >>> myStr = 'I want to strip my words' >>> print myStr.replace('my', '') I want to strip words -- John. From rdm at rcblue.com Thu Nov 2 07:16:35 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 01 Nov 2006 22:16:35 -0800 Subject: [Tutor] Using sys.exit() In-Reply-To: <1162425362.18283.54.camel@andi-lap> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> <1162425362.18283.54.camel@andi-lap> Message-ID: <7.0.1.0.2.20061101220649.079398c0@rcblue.com> At 03:56 PM 11/1/2006, Andreas Kostyrka wrote: >Am Mittwoch, den 01.11.2006, 15:43 -0800 schrieb Dick Moores: > > At 12:14 AM 10/31/2006, Alan Gauld wrote: > > > > >"Dick Moores" wrote > > > > I'd like to know how to use sys.exit() to quit a program. > > > > > > > > > >I see that you already figured that out. > > >You can also quit by raising SystemExit, which is > > >what sys.exit does... but you don't need to import sys... > > > > I'm afraid I don't know what you mean. How do I raise SystemExit, and > > why don't I need to import sys? > >raise SystemExit(2) > >is equal to sys.exit(2) (actually sys.exit(2) just raises SystemExit(2)) OK, that works well. But why the 2? BTW at the command line, "raise SystemExit(2)" produces a completely silent exit. In Win IDE I get "SystemExit: 2". With IDLE: Traceback (most recent call last): File "E:\Python25\dev\1unitConversion5a.py", line 425, in main() File "E:\Python25\dev\1unitConversion5a.py", line 413, in main s = formatAndCheckStringFromUser(s) File "E:\Python25\dev\1unitConversion5a.py", line 342, in formatAndCheckStringFromUser s = stripResponseAndCheckForUserRequestForHelpOrToQuit(s) File "E:\Python25\dev\1unitConversion5a.py", line 253, in stripResponseAndCheckForUserRequestForHelpOrToQuit raise SystemExit(2) SystemExit: 2 If I can manage to use "break", all 3 exits are silent. Why is it wrong to use "break" to exit? Dick Moores Dick Moores From rdm at rcblue.com Thu Nov 2 07:57:07 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 01 Nov 2006 22:57:07 -0800 Subject: [Tutor] Using sys.exit() In-Reply-To: <7.0.1.0.2.20061101220649.079398c0@rcblue.com> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> <1162425362.18283.54.camel@andi-lap> <7.0.1.0.2.20061101220649.079398c0@rcblue.com> Message-ID: <7.0.1.0.2.20061101225608.079410c8@rcblue.com> At 10:16 PM 11/1/2006, Dick Moores wrote: >BTW at the command line, "raise SystemExit(2)" produces a completely >silent exit. In Win IDE I get "SystemExit: 2". With IDLE: > >Traceback (most recent call last): > File "E:\Python25\dev\1unitConversion5a.py", line 425, in > main() > File "E:\Python25\dev\1unitConversion5a.py", line 413, in main > s = formatAndCheckStringFromUser(s) > File "E:\Python25\dev\1unitConversion5a.py", line 342, in >formatAndCheckStringFromUser > s = stripResponseAndCheckForUserRequestForHelpOrToQuit(s) > File "E:\Python25\dev\1unitConversion5a.py", line 253, in >stripResponseAndCheckForUserRequestForHelpOrToQuit > raise SystemExit(2) >SystemExit: 2 I should have added that Ulipad is also completely silent. Dick Moores From rabidpoobear at gmail.com Thu Nov 2 08:09:28 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 01:09:28 -0600 Subject: [Tutor] Using sys.exit() In-Reply-To: <7.0.1.0.2.20061101220649.079398c0@rcblue.com> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> <1162425362.18283.54.camel@andi-lap> <7.0.1.0.2.20061101220649.079398c0@rcblue.com> Message-ID: <454999A8.5010402@gmail.com> Dick Moores wrote: > At 03:56 PM 11/1/2006, Andreas Kostyrka wrote: > >> Am Mittwoch, den 01.11.2006, 15:43 -0800 schrieb Dick Moores: >> >>> At 12:14 AM 10/31/2006, Alan Gauld wrote: >>> >>> >>>> "Dick Moores" wrote >>>> >>>>> I'd like to know how to use sys.exit() to quit a program. >>>>> >>>>> >>>> I see that you already figured that out. >>>> You can also quit by raising SystemExit, which is >>>> what sys.exit does... but you don't need to import sys... >>>> >>> I'm afraid I don't know what you mean. How do I raise SystemExit, and >>> why don't I need to import sys? >>> >> raise SystemExit(2) >> >> is equal to sys.exit(2) (actually sys.exit(2) just raises SystemExit(2)) >> > > OK, that works well. But why the 2? > > BTW at the command line, "raise SystemExit(2)" produces a completely > silent exit. In Win IDE I get "SystemExit: 2". With IDLE: > > Traceback (most recent call last): > File "E:\Python25\dev\1unitConversion5a.py", line 425, in > main() > File "E:\Python25\dev\1unitConversion5a.py", line 413, in main > s = formatAndCheckStringFromUser(s) > File "E:\Python25\dev\1unitConversion5a.py", line 342, in > formatAndCheckStringFromUser > s = stripResponseAndCheckForUserRequestForHelpOrToQuit(s) > File "E:\Python25\dev\1unitConversion5a.py", line 253, in > stripResponseAndCheckForUserRequestForHelpOrToQuit > raise SystemExit(2) > SystemExit: 2 > Whenever an error is raised, IDEs catch the error and display it for you. The SystemExit ended the process that was running your python script, just not the IDE. So the IDE is around to display the error. Imagine if whenever you tried to read in a file, and got an IOError, your IDE didn't catch it. Wouldn't that be inconvenient? The fact that it's called SystemExit doesn't change the fact that it's an exception. 'stripResponseAndCheckForUserRequestForHelpOrToQuit' is rather a long function name. Perhaps you need more concise function names. > If I can manage to use "break", all 3 exits are silent. Why is it > wrong to use "break" to exit? > 'break' doesn't exit. It ends a loop. It's not wrong to use a 'break' to exit a loop. That's what it's there for. But what if you were doing something after the loop? 'break' wouldn't help you there. A SystemExit immediately ends the program at that call (unless you catch the exception :) example: import random a = random.randint(1,5) i = 0 while i < 5: if i == a: break print "A is greater than %s" % i print "A must be 5!" See, if you were to raise a SystemExit there, then the final print statement wouldn't ever take place unless a was actually 5. The reason the exits with break are 'silent' is because no exceptions are occurring. SystemExit is an exception. There's nothing wrong with using it. You could raise an IOError if you wanted. > Dick Moores > > Dick Moores > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rdm at rcblue.com Thu Nov 2 10:05:42 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 02 Nov 2006 01:05:42 -0800 Subject: [Tutor] Using sys.exit() In-Reply-To: <454999A8.5010402@gmail.com> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> <1162425362.18283.54.camel@andi-lap> <7.0.1.0.2.20061101220649.079398c0@rcblue.com> <454999A8.5010402@gmail.com> Message-ID: <7.0.1.0.2.20061102005716.07a01230@rcblue.com> At 11:09 PM 11/1/2006, Luke Paireepinart wrote: >>If I can manage to use "break", all 3 exits are silent. Why is it >>wrong to use "break" to exit? >> >'break' doesn't exit. It ends a loop. >It's not wrong to use a 'break' to exit a loop. That's what it's there for. >But what if you were doing something after the loop? >'break' wouldn't help you there. Yes, I realize that. But what if I'm not doing anything after the loop? In that case is there anything wrong with using break to end the script? I'm getting the idea from the responses that there IS something wrong, but I don't see what it is. >A SystemExit immediately ends the program at that call >(unless you catch the exception :) > >The reason the exits with break are 'silent' >is because no exceptions are occurring. But that's exactly what I want--a silent exit. >SystemExit is an exception. >There's nothing wrong with using it. >You could raise an IOError if you wanted. Please explain how to do that, and why I would want to. Thanks, Dick From rabidpoobear at gmail.com Thu Nov 2 10:21:42 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 03:21:42 -0600 Subject: [Tutor] Using sys.exit() In-Reply-To: <7.0.1.0.2.20061102005716.07a01230@rcblue.com> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> <1162425362.18283.54.camel@andi-lap> <7.0.1.0.2.20061101220649.079398c0@rcblue.com> <454999A8.5010402@gmail.com> <7.0.1.0.2.20061102005716.07a01230@rcblue.com> Message-ID: <4549B8A6.5080602@gmail.com> > > Yes, I realize that. But what if I'm not doing anything after the > loop? In that case is there anything wrong with using break to end the > script? I'm getting the idea from the responses that there IS > something wrong, but I don't see what it is. Generally, something that exits with a break would be a normal exit case for a loop. An exception would be an abnormal exit case. Like... while 1: x = raw_input('choice? "hi", "exit" ') if x == 'exit': break elif x == 'hi': print "Hello!" else: raise SystemExit see, it only raises the error if the user inputs an invalid value. > >> A SystemExit immediately ends the program at that call >> (unless you catch the exception :) >> >> The reason the exits with break are 'silent' >> is because no exceptions are occurring. > > But that's exactly what I want--a silent exit. So don't use exceptions then. The point of exceptions is so that there's a traceback that the developer can see and use to debug. If that's not what you're trying to do, don't use an exception. I never read your original code, so I'm not sure what you were doing, and there may be other factors that the other Tutor subscribers felt contributed to the decision of using SystemExit over break. Just remember, SystemExit will always exit your program where you tell it to, and depending on not having code after your loops so that it's not executed when you break is probably a 'bad idea.' > >> SystemExit is an exception. >> There's nothing wrong with using it. >> You could raise an IOError if you wanted. > > Please explain how to do that, and why I would want to. How to do it: raise IOError why? No reason. I was just pointing out that it doesn't particularly matter that you're raising a SystemExit. Your program will terminate at any exception that's raised, and you will get an identical traceback. The only reason you want to use SystemExit, is so that if someone else is using your function, they can capture the SystemExit (with an except: statement) and do something with it. An example of this would be, if you had the function def convert_to_int(astr): for item in astr: if item.isalpha() == True: raise SystemExit return int(astr) and I wanted to use it to convert user input to an integer, I'd do try: a = convert_to_int(raw_input('please enter an integer: ')) except SystemExit: print "You entered some alpha characters!" Note that ValueError would be more appropriate here, instead of SystemExit. Also note the function doesn't check for characters that aren't alpha or numbers, so a $ will pass our item.isalpha() test, and when the function attempts to return int(astr) the int call will raise a ValueError. Obviously, it would be less helpful if everything just raised one type of error, so that's why there's different types. It's up to you to standardize their usage, though. You can write classes that raises ValueErrors whenever anything goes wrong, but why would you want to? Remember, Python expects that the developer will be responsible. It won't keep you from shooting yourself in the foot. So try to raise reasonable exceptions. I think SystemExit may have some extra magic, and it's not just a normal exception, but I'm not sure about this. Someone else know? HTH, -Luke From rdm at rcblue.com Thu Nov 2 10:32:47 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 02 Nov 2006 01:32:47 -0800 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns Message-ID: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> I'm working on a program named unitConversion.py. In it, I give the user a chance to see a list of all the measurement units the program handles, and their abbreviations. The user needs the abbreviations to do the conversions. So I have a couple of functions (see below) that together will print a list of unit abbreviations and their full names (but not their respective categories). At this point there are 46 units, and that's a long list for the user to see if the printing is done one unit per line. What I'd like to do is print the list in maybe 3 neat columns. I'm sure this is possible, but after hours of experimentation, I can't get a neat one to print. I know I could stick a neat 3-column one in the script, but I'd like to learn how it could be done with just the two functions allUnitsAndTheirAbbreviationsAndCategories() and a modification of printListOfAllUnitsAndAbbreviations(). BTW allUnitsAndTheirAbbreviationsAndCategories() is used elsewhere in the program, so I don't want to change it, if possible. Thanks very much, Dick Moores def allUnitsAndTheirAbbreviationsAndCategories(): """ A list of all units, their abbreviations and categories. """ abbs = [ 'l mi: mile', 'l km: kilometer', 'l m: meter', 'l yd: yard', 'l ft: foot', 'l in: inch', 'l cm: centimeter', 'l mm: millimeter', 'l fur: furlong', 'l lea: league', 'l nm: nautical mile', 'a ha: hectare', 'a ac: acre', 'a mi2: square mile', 'a km2: square kilometer', 'a m2: square meter', 'a yd2: square yard', 'a ft2: square foot', 'a in2: square inch', 'a cm2: square centimeter', 'w kg: kilogram', 'w lb: pound', 'w gm: gram', 'w oz: ounce', 'v qt: quart', 'v oz: ounce', 'v l: liter', 'v ml: milliliter', 'v gal: gallon', 'v tbsp: tablespoon', 'v tsp: teaspoon', 'v impgal: Imperial Gallon', 'v yd3: cubic yard', 'v m3: cubic meter', 'v ft3: cubic foot', 'v mi3: cubic mile', 'v km3: cubic kilometer', 't F: Fahrenheit', 't C: Celsius', 't K: Kelvin', 's mph: miles per hour', 's knots: knots', 's mps: miles per second', 's fps: feet per second', 'd deg: degree', 'd rad: radian' ] return abbs def printListOfAllUnitsAndAbbreviations(): """ Prints a list of all units and their abbreviations, but not their categories. """ lstAll = allUnitsAndTheirAbbreviationsAndCategories() for x in lstAll: print x[2:] print From andreas at kostyrka.org Thu Nov 2 10:45:25 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 02 Nov 2006 10:45:25 +0100 Subject: [Tutor] Using sys.exit() In-Reply-To: <7.0.1.0.2.20061101220649.079398c0@rcblue.com> References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> <1162425362.18283.54.camel@andi-lap> <7.0.1.0.2.20061101220649.079398c0@rcblue.com> Message-ID: <1162460725.18283.67.camel@andi-lap> Am Mittwoch, den 01.11.2006, 22:16 -0800 schrieb Dick Moores: > At 03:56 PM 11/1/2006, Andreas Kostyrka wrote: > >Am Mittwoch, den 01.11.2006, 15:43 -0800 schrieb Dick Moores: > > > At 12:14 AM 10/31/2006, Alan Gauld wrote: > > > > > > >"Dick Moores" wrote > > > > > I'd like to know how to use sys.exit() to quit a program. > > > > > > > > > > > > >I see that you already figured that out. > > > >You can also quit by raising SystemExit, which is > > > >what sys.exit does... but you don't need to import sys... > > > > > > I'm afraid I don't know what you mean. How do I raise SystemExit, and > > > why don't I need to import sys? > > > >raise SystemExit(2) > > > >is equal to sys.exit(2) (actually sys.exit(2) just raises SystemExit(2)) > > OK, that works well. But why the 2? 2 is the usual error code for invalid cmdline parameters in the Unix world. Just an example here. > > BTW at the command line, "raise SystemExit(2)" produces a completely > silent exit. In Win IDE I get "SystemExit: 2". With IDLE: > > Traceback (most recent call last): > File "E:\Python25\dev\1unitConversion5a.py", line 425, in > main() > File "E:\Python25\dev\1unitConversion5a.py", line 413, in main > s = formatAndCheckStringFromUser(s) > File "E:\Python25\dev\1unitConversion5a.py", line 342, in > formatAndCheckStringFromUser > s = stripResponseAndCheckForUserRequestForHelpOrToQuit(s) > File "E:\Python25\dev\1unitConversion5a.py", line 253, in > stripResponseAndCheckForUserRequestForHelpOrToQuit > raise SystemExit(2) > SystemExit: 2 > > If I can manage to use "break", all 3 exits are silent. Why is it > wrong to use "break" to exit? Because it does not: for i in xrange(50): for j in xrange(50, 100): if j == 77: break will not stop the program when it hits the break. But yes, there are no reason why you should not let your script just end. Andreas > > Dick Moores > > Dick Moores > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061102/477eabbf/attachment-0001.pgp From rabidpoobear at gmail.com Thu Nov 2 10:45:23 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 03:45:23 -0600 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> Message-ID: <4549BE33.3060702@gmail.com> Instead of helping you with your specific problem, I'll give you this information and see what you can make of it. >>> print 'a'.ljust(20)+'b'.ljust(20) a b >>> print 'carrah'.ljust(20)+'foobar'.ljust(20) carrah foobar Notice how they're all lined up on the left (if the font in this e-mail is fixed-width. Either way, the number of spaces for both columns is the same.) ljust's functionality is essentially this: def left_justify(astr,width): x = len(astr) while x < width: astr += ' ' x += 1 HTH, -Luke From rdm at rcblue.com Thu Nov 2 11:19:38 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 02 Nov 2006 02:19:38 -0800 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <4549BE33.3060702@gmail.com> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> Message-ID: <7.0.1.0.2.20061102021534.07a2ff58@rcblue.com> At 01:45 AM 11/2/2006, Luke Paireepinart wrote: >Instead of helping you with your specific problem, I'll give you this >information and see what you can make of it. > > >>> print 'a'.ljust(20)+'b'.ljust(20) >a b > >>> print 'carrah'.ljust(20)+'foobar'.ljust(20) >carrah foobar > > >Notice how they're all lined up on the left (if the font in this e-mail >is fixed-width. Either way, the number of spaces for both columns is >the same.) > >ljust's functionality is essentially this: > >def left_justify(astr,width): > x = len(astr) > while x < width: > astr += ' ' > x += 1 Ah, that's beautiful! Thanks, Luke! (And thanks Python!) Didn't know about ljust(). Here's my modified printListOfAllUnitsAndAbbreviations(). def printListOfAllUnitsAndAbbreviations(): """ Prints a list of all units and their abbreviations, but not their categories. """ lstAll = allUnitsAndTheirAbbreviationsAndCategories() for i in range(0, len(lstAll)-1, 3): print lstAll[i][2:].ljust(27) + lstAll[i+1][2:].ljust(27) + lstAll[i+2][2:].ljust(27) print Dick From kent37 at tds.net Thu Nov 2 12:13:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Nov 2006 06:13:58 -0500 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <4549BE33.3060702@gmail.com> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> Message-ID: <4549D2F6.6040507@tds.net> Luke Paireepinart wrote: > Instead of helping you with your specific problem, I'll give you this > information and see what you can make of it. > > >>> print 'a'.ljust(20)+'b'.ljust(20) > a b > >>> print 'carrah'.ljust(20)+'foobar'.ljust(20) > carrah foobar Another way to do this is with string formatting, I think it is a more readable and flexible solution: In [1]: print '%-20s %-20s' % ('a', 'b') a b In [2]: print '%-20s %-20s' % ('carrah', 'foobar') carrah foobar See this page for details: http://docs.python.org/lib/typesseq-strings.html Kent From rdm at rcblue.com Thu Nov 2 12:31:18 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 02 Nov 2006 03:31:18 -0800 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <4549D2F6.6040507@tds.net> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> <4549D2F6.6040507@tds.net> Message-ID: <7.0.1.0.2.20061102032850.07a21300@rcblue.com> At 03:13 AM 11/2/2006, Kent Johnson wrote: >Luke Paireepinart wrote: > > Instead of helping you with your specific problem, I'll give you this > > information and see what you can make of it. > > > > >>> print 'a'.ljust(20)+'b'.ljust(20) > > a b > > >>> print 'carrah'.ljust(20)+'foobar'.ljust(20) > > carrah foobar > >Another way to do this is with string formatting, I think it is a more >readable and flexible solution: > >In [1]: print '%-20s %-20s' % ('a', 'b') >a b > >In [2]: print '%-20s %-20s' % ('carrah', 'foobar') >carrah foobar > >See this page for details: >http://docs.python.org/lib/typesseq-strings.html Thanks, Kent. I agree. So now that function has become def printListOfAllUnitsAndAbbreviations(): """ Prints a 3-column list of all units and their abbreviations, but not their categories. """ lstAll = allUnitsAndTheirAbbreviationsAndCategories() for i in range(0, len(lstAll)-1 ,3): print '%-27s %-27s %-27s' % (lstAll[i][2:], lstAll[i+1][2:], lstAll[i+2][2:]) print From ajkadri at googlemail.com Thu Nov 2 12:41:05 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 2 Nov 2006 11:41:05 +0000 Subject: [Tutor] Cal command in python... Message-ID: Folks, Does anybody have an idea of the logic used in cal command... I want to know the algorithm so that I can implement in Python. A pseudo code might be helpful... TIA. Regards, ~Asrarahmed~ -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/9aee0d10/attachment.html From kent37 at tds.net Thu Nov 2 13:30:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Nov 2006 07:30:47 -0500 Subject: [Tutor] Cal command in python... In-Reply-To: References: Message-ID: <4549E4F7.3000409@tds.net> Asrarahmed Kadri wrote: > > > Folks, > > Does anybody have an idea of the logic used in cal command... I want to > know the algorithm so that I can implement in Python. See the calendar module. Source code in the library if you want to see how it is done. In [1]: import calendar In [2]: calendar.prmonth(2006, 10) October 2006 Mo Tu We Th Fr Sa Su 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 Kent From ajkadri at googlemail.com Thu Nov 2 13:43:05 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 2 Nov 2006 12:43:05 +0000 Subject: [Tutor] Cal command in python... In-Reply-To: <4549E4F7.3000409@tds.net> References: <4549E4F7.3000409@tds.net> Message-ID: I got the command and saw its output..? But where to look for the source code..? Which library ? TIA. Regards, Asrarahmed On 11/2/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > > > > > Folks, > > > > Does anybody have an idea of the logic used in cal command... I want to > > know the algorithm so that I can implement in Python. > > See the calendar module. Source code in the library if you want to see > how it is done. > > In [1]: import calendar > > In [2]: calendar.prmonth(2006, 10) > October 2006 > Mo Tu We Th Fr Sa Su > 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 > > Kent > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/d6b6f1c6/attachment.htm From kent37 at tds.net Thu Nov 2 13:52:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Nov 2006 07:52:26 -0500 Subject: [Tutor] Cal command in python... In-Reply-To: References: <4549E4F7.3000409@tds.net> Message-ID: <4549EA0A.5000409@tds.net> Asrarahmed Kadri wrote: > > I got the command and saw its output..? But where to look for the source > code..? > Which library ? In the Python standard library. Much of the library is written in Python and supplied as source. On Windows it will be something like C:\Python25\Lib\calendar.py. On other platforms I don't know the path but it will be part of the Python installation. Kent > > TIA. > > Regards, > Asrarahmed > > > > On 11/2/06, *Kent Johnson* > wrote: > > Asrarahmed Kadri wrote: > > > > > > Folks, > > > > Does anybody have an idea of the logic used in cal command... I > want to > > know the algorithm so that I can implement in Python. > > See the calendar module. Source code in the library if you want to see > how it is done. > > In [1]: import calendar > > In [2]: calendar.prmonth (2006, 10) > October 2006 > Mo Tu We Th Fr Sa Su > 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 > > Kent > > > > > -- > To HIM you shall return. From simon at brunningonline.net Thu Nov 2 14:00:21 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 2 Nov 2006 13:00:21 +0000 Subject: [Tutor] Cal command in python... In-Reply-To: <4549EA0A.5000409@tds.net> References: <4549E4F7.3000409@tds.net> <4549EA0A.5000409@tds.net> Message-ID: <8c7f10c60611020500p35519192j3326f66baceef83c@mail.gmail.com> On 11/2/06, Kent Johnson wrote: > In the Python standard library. Much of the library is written in Python > and supplied as source. On Windows it will be something like > C:\Python25\Lib\calendar.py. On other platforms I don't know the path > but it will be part of the Python installation. If you do: import calendar print calendar.__file__ That will tell you where it is on your system. Works for any module. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From rdm at rcblue.com Thu Nov 2 15:14:32 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 02 Nov 2006 06:14:32 -0800 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <7.0.1.0.2.20061102032850.07a21300@rcblue.com> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> <4549D2F6.6040507@tds.net> <7.0.1.0.2.20061102032850.07a21300@rcblue.com> Message-ID: <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> At 03:31 AM 11/2/2006, you wrote: >At 03:13 AM 11/2/2006, Kent Johnson wrote: > >Luke Paireepinart wrote: > > > Instead of helping you with your specific problem, I'll give you this > > > information and see what you can make of it. > > > > > > >>> print 'a'.ljust(20)+'b'.ljust(20) > > > a b > > > >>> print 'carrah'.ljust(20)+'foobar'.ljust(20) > > > carrah foobar > > > >Another way to do this is with string formatting, I think it is a more > >readable and flexible solution: > > > >In [1]: print '%-20s %-20s' % ('a', 'b') > >a b > > > >In [2]: print '%-20s %-20s' % ('carrah', 'foobar') > >carrah foobar > > > >See this page for details: > >http://docs.python.org/lib/typesseq-strings.html > >Thanks, Kent. I agree. So now that function has become > >def printListOfAllUnitsAndAbbreviations(): > """ > Prints a 3-column list of all units and their abbreviations, >but not their categories. > """ > lstAll = allUnitsAndTheirAbbreviationsAndCategories() > for i in range(0, len(lstAll)-1 ,3): > print '%-27s %-27s %-27s' % (lstAll[i][2:], >lstAll[i+1][2:], lstAll[i+2][2:]) > print Oops! Got overconfident. Didn't check to see if it actually printed the whole list. It didn't. Left off "rad: radian", because there are 46 items in the list (46%3 is 1, not 0). So now the only way I could see to print all 46 was to add 2 empty dummies to make 48, which is divisible by 3, and also modify the range in the second function. Is there a better way, which is also a general solution that will work when I subtract or add to the list? See the two modified functions below. Dick def allUnitsAndTheirAbbreviationsAndCategories(): """ A list of all units, their abbreviations and categories. """ abbs = [ 'l mi: mile', 'l km: kilometer', 'l m: meter', 'l yd: yard', 'l ft: foot', 'l in: inch', 'l cm: centimeter', 'l mm: millimeter', 'l fur: furlong', 'l lea: league', 'l nm: nautical mile', 'a ha: hectare', 'a ac: acre', 'a mi2: square mile', 'a km2: square kilometer', 'a m2: square meter', 'a yd2: square yard', 'a ft2: square foot', 'a in2: square inch', 'a cm2: square centimeter', 'w kg: kilogram', 'w lb: pound', 'w gm: gram', 'w oz: ounce', 'v qt: quart', 'v oz: ounce', 'v l: liter', 'v ml: milliliter', 'v gal: gallon', 'v tbsp: tablespoon', 'v tsp: teaspoon', 'v impgal: Imperial Gallon', 'v yd3: cubic yard', 'v m3: cubic meter', 'v ft3: cubic foot', 'v mi3: cubic mile', 'v km3: cubic kilometer', 't F: Fahrenheit', 't C: Celsius', 't K: Kelvin', 's mph: miles per hour', 's knots: knots', 's mps: miles per second', 's fps: feet per second', 'd deg: degree', 'd rad: radian', ' ', ' ' ] return abbs def printListOfAllUnitsAndAbbreviations(): """ Prints a 3-column list of all units and their abbreviations, but not their categories. """ lstAll = allUnitsAndTheirAbbreviationsAndCategories() for i in range(0, len(lstAll), 3): print '%-27s %-27s %-27s' % (lstAll[i][2:], lstAll[i+1][2:], lstAll[i+2][2:]) print From ajkadri at googlemail.com Thu Nov 2 16:44:13 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 2 Nov 2006 15:44:13 +0000 Subject: [Tutor] Performing arithmetic operations with date Message-ID: Hello Guys... I want to perform arithmetic operations on date supplied by the user on the command line. Is there any built-in utility for this..?? TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/7d8862ea/attachment.html From rabidpoobear at gmail.com Thu Nov 2 16:48:35 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 09:48:35 -0600 Subject: [Tutor] Performing arithmetic operations with date In-Reply-To: References: Message-ID: <454A1353.404@gmail.com> Asrarahmed Kadri wrote: [question about dates and times] Asrarahmed, please check google.com and other resources before asking on the list. A google of 'python date module' brought the page http://pleac.sourceforge.net/pleac_python/datesandtimes.html as the first link, which has examples on usage. The second link down is http://docs.python.org/lib/module-datetime.html which is the module definition from Python.org. HTH, -Luke From chris.arndt at web.de Thu Nov 2 16:57:01 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 02 Nov 2006 16:57:01 +0100 Subject: [Tutor] str.strip() help In-Reply-To: <5e58f2e40611011811u47520ec5ta97e64e0ecfdadf0@mail.gmail.com> References: <5e58f2e40611011811u47520ec5ta97e64e0ecfdadf0@mail.gmail.com> Message-ID: <454A154D.5020405@web.de> John Fouhy schrieb: > On 02/11/06, Chris Hengge wrote: >>>>> myStr = "I want to strip my words." >>>>> print myStr.strip("my") >>>>> 'I want to strip words.' > > .strip() only removes text from the beginning and end of the string. It is generally used to remove whitespace from the start/end of a string, e.g. removing the newline character from the end of a line of text. But you can also specify which characters to strip. Note that the argument is not a string to strip off, but rather a collection of characters, any of which should be stripped off, e.g. >>> r = "I want to strip my words." >>> r.strip('I. ') # note the space 'want to strip my words' Chris From chris.arndt at web.de Thu Nov 2 17:04:55 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 02 Nov 2006 17:04:55 +0100 Subject: [Tutor] Performing arithmetic operations with date In-Reply-To: References: Message-ID: <454A1727.2080004@web.de> Asrarahmed Kadri schrieb: > I want to perform arithmetic operations on date supplied by the user on the > command line. > > Is there any built-in utility for this..?? Not built-in, but very useful: http://labix.org/python-dateutil Chris From pyro9219 at gmail.com Thu Nov 2 19:41:52 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 2 Nov 2006 10:41:52 -0800 Subject: [Tutor] Print Screen Message-ID: I posted this in a similar thread a few days ago, and no replies so I think it needs its own listing. Anyone know of a way to capture special keys like "Print Screen"? I have a small script to grab all they keycodes, but it doesn't seem to catch several keys on the keyboard. I've got a utility that I'd like to be able to automagically get a screenshot when something goes wrong so I dont have to hope the user can re-create the error. Universal support would be best, but WinXP is the main OS Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/52a97b7f/attachment.htm From rabidpoobear at gmail.com Thu Nov 2 19:42:58 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 12:42:58 -0600 Subject: [Tutor] Print Screen In-Reply-To: References: Message-ID: <454A3C32.4090001@gmail.com> Chris Hengge wrote: > I posted this in a similar thread a few days ago, and no replies so I > think it needs its own listing. > > Anyone know of a way to capture special keys like "Print Screen"? > I have a small script to grab all they keycodes, but it doesn't seem > to catch several keys on the keyboard. I've got a utility that I'd > like to be able to automagically get a screenshot when something goes > wrong so I dont have to hope the user can re-create the error. > Universal support would be best, but WinXP is the main OS Why do you need to capture the keypress 'print screen' if you're automatically taking screenshots when something goes wrong? > > Thanks. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From markusro at element.fkp.physik.tu-darmstadt.de Thu Nov 2 20:33:00 2006 From: markusro at element.fkp.physik.tu-darmstadt.de (Markus Rosenstihl) Date: Thu, 2 Nov 2006 20:33:00 +0100 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> <4549D2F6.6040507@tds.net> <7.0.1.0.2.20061102032850.07a21300@rcblue.com> <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> Message-ID: Am 02.11.2006 um 15:14 schrieb Dick Moores: > At 03:31 AM 11/2/2006, you wrote: >> At 03:13 AM 11/2/2006, Kent Johnson wrote: >>> Luke Paireepinart wrote: >>>> Instead of helping you with your specific problem, I'll give you >>>> this >>>> information and see what you can make of it. >>>> >>>>>>> print 'a'.ljust(20)+'b'.ljust(20) >>>> a b >>>>>>> print 'carrah'.ljust(20)+'foobar'.ljust(20) >>>> carrah foobar >>> >>> Another way to do this is with string formatting, I think it is a >>> more >>> readable and flexible solution: >>> >>> In [1]: print '%-20s %-20s' % ('a', 'b') >>> a b >>> >>> In [2]: print '%-20s %-20s' % ('carrah', 'foobar') >>> carrah foobar >>> >>> See this page for details: >>> http://docs.python.org/lib/typesseq-strings.html >> >> Thanks, Kent. I agree. So now that function has become >> >> def printListOfAllUnitsAndAbbreviations(): >> """ >> Prints a 3-column list of all units and their abbreviations, >> but not their categories. >> """ >> lstAll = allUnitsAndTheirAbbreviationsAndCategories() >> for i in range(0, len(lstAll)-1 ,3): >> print '%-27s %-27s %-27s' % (lstAll[i][2:], >> lstAll[i+1][2:], lstAll[i+2][2:]) >> print > > Oops! Got overconfident. Didn't check to see if it actually printed > the whole list. It didn't. Left off "rad: radian", because there are > 46 items in the list (46%3 is 1, not 0). So now the only way I could > see to print all 46 was to add 2 empty dummies to make 48, which is > divisible by 3, and also modify the range in the second function. Is > there a better way, which is also a general solution that will work > when I subtract or add to the list? See the two modified functions > below. > > Dick > > > def allUnitsAndTheirAbbreviationsAndCategories(): > """ > A list of all units, their abbreviations and categories. > """ > abbs = [ > 'l mi: mile', > 'l km: kilometer', > 'l m: meter', > 'l yd: yard', > 'l ft: foot', > 'l in: inch', > 'l cm: centimeter', > 'l mm: millimeter', > 'l fur: furlong', > 'l lea: league', > 'l nm: nautical mile', > 'a ha: hectare', > 'a ac: acre', > 'a mi2: square mile', > 'a km2: square kilometer', > 'a m2: square meter', > 'a yd2: square yard', > 'a ft2: square foot', > 'a in2: square inch', > 'a cm2: square centimeter', > 'w kg: kilogram', > 'w lb: pound', > 'w gm: gram', > 'w oz: ounce', > 'v qt: quart', > 'v oz: ounce', > 'v l: liter', > 'v ml: milliliter', > 'v gal: gallon', > 'v tbsp: tablespoon', > 'v tsp: teaspoon', > 'v impgal: Imperial Gallon', > 'v yd3: cubic yard', > 'v m3: cubic meter', > 'v ft3: cubic foot', > 'v mi3: cubic mile', > 'v km3: cubic kilometer', > 't F: Fahrenheit', > 't C: Celsius', > 't K: Kelvin', > 's mph: miles per hour', > 's knots: knots', > 's mps: miles per second', > 's fps: feet per second', > 'd deg: degree', > 'd rad: radian', > ' ', > ' ' > ] > return abbs > > def printListOfAllUnitsAndAbbreviations(): > """ > Prints a 3-column list of all units and their abbreviations, > but not their categories. > """ > lstAll = allUnitsAndTheirAbbreviationsAndCategories() > for i in range(0, len(lstAll), 3): > print '%-27s %-27s %-27s' % (lstAll[i][2:], > lstAll[i+1][2:], lstAll[i+2][2:]) > print > Try somthing like this: In [32]: a=range(100) In [33]: for i in range(0,len(a)): ....: print '%-27s'%a[i], ....: if (i+1)%3 == 0: print "\n" 0 1 2 3 4 5 ... 93 94 95 96 97 98 99 Note the comma after the first print statement Regards Markus From kent37 at tds.net Thu Nov 2 20:51:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Nov 2006 14:51:48 -0500 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> <4549D2F6.6040507@tds.net> <7.0.1.0.2.20061102032850.07a21300@rcblue.com> <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> Message-ID: <454A4C54.3090301@tds.net> Dick Moores wrote: > Oops! Got overconfident. Didn't check to see if it actually printed > the whole list. It didn't. Left off "rad: radian", because there are > 46 items in the list (46%3 is 1, not 0). So now the only way I could > see to print all 46 was to add 2 empty dummies to make 48, which is > divisible by 3, and also modify the range in the second function. Is > there a better way, which is also a general solution that will work > when I subtract or add to the list? See the two modified functions below. There are almost enough grouping recipes in the cookbook to give them their own category. They tend to be fairly obscure. There is one in the comment on this page that would work for you: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496958 Or you could make a new list and pad it with spaces when you print, or use Markus' solution which is simple and clear. From rdm at rcblue.com Thu Nov 2 21:19:33 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 02 Nov 2006 12:19:33 -0800 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> <4549D2F6.6040507@tds.net> <7.0.1.0.2.20061102032850.07a21300@rcblue.com> <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> Message-ID: <7.0.1.0.2.20061102121641.0743e668@rcblue.com> At 11:33 AM 11/2/2006, Markus Rosenstihl wrote: >Try somthing like this: > >In [32]: a=range(100) >In [33]: for i in range(0,len(a)): > ....: print '%-27s'%a[i], > ....: if (i+1)%3 == 0: print "\n" > >0 1 2 > >3 4 5 >... >93 94 95 > >96 97 98 > >99 > > >Note the comma after the first print statement Yes, thanks, but the reason I wanted 3 columns was to compress the height of the list printout for the user, so I don't want all those blank lines. Dick From rdm at rcblue.com Thu Nov 2 21:26:38 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 02 Nov 2006 12:26:38 -0800 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <454A4C54.3090301@tds.net> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> <4549D2F6.6040507@tds.net> <7.0.1.0.2.20061102032850.07a21300@rcblue.com> <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> <454A4C54.3090301@tds.net> Message-ID: <7.0.1.0.2.20061102122228.0743ca68@rcblue.com> At 11:51 AM 11/2/2006, Kent Johnson wrote: >Dick Moores wrote: >>Oops! Got overconfident. Didn't check to see if it actually printed >>the whole list. It didn't. Left off "rad: radian", because there >>are 46 items in the list (46%3 is 1, not 0). So now the only way I >>could see to print all 46 was to add 2 empty dummies to make 48, >>which is divisible by 3, and also modify the range in the second >>function. Is there a better way, which is also a general solution >>that will work when I subtract or add to the list? See the >>two modified functions below. > >There are almost enough grouping recipes in the cookbook to give >them their own category. They tend to be fairly obscure. There is >one in the comment on this page that would work for you: >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496958 Thanks for digging that out, Kent. If you think that one in the comment is obscure, imagine how it looks to me. It'll take a lot of study. I may ask some questions.. Dick From kent37 at tds.net Thu Nov 2 21:35:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Nov 2006 15:35:12 -0500 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <7.0.1.0.2.20061102121641.0743e668@rcblue.com> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> <4549D2F6.6040507@tds.net> <7.0.1.0.2.20061102032850.07a21300@rcblue.com> <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> <7.0.1.0.2.20061102121641.0743e668@rcblue.com> Message-ID: <454A5680.2040808@tds.net> Dick Moores wrote: > At 11:33 AM 11/2/2006, Markus Rosenstihl wrote: >> Try somthing like this: >> >> In [32]: a=range(100) >> In [33]: for i in range(0,len(a)): >> ....: print '%-27s'%a[i], >> ....: if (i+1)%3 == 0: print "\n" >> >> 0 1 2 >> >> 3 4 5 >> ... >> 93 94 95 >> >> 96 97 98 >> >> 99 >> >> >> Note the comma after the first print statement > > Yes, thanks, but the reason I wanted 3 columns was to compress the > height of the list printout for the user, so I don't want all those > blank lines. Just change 'print "\n"' to 'print' Kent From rdm at rcblue.com Thu Nov 2 21:45:49 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 02 Nov 2006 12:45:49 -0800 Subject: [Tutor] Need to be taught a trick or two about printing in neat columns In-Reply-To: <454A5680.2040808@tds.net> References: <7.0.1.0.2.20061102011355.07a2ff58@rcblue.com> <4549BE33.3060702@gmail.com> <4549D2F6.6040507@tds.net> <7.0.1.0.2.20061102032850.07a21300@rcblue.com> <7.0.1.0.2.20061102055622.07a375d8@rcblue.com> <7.0.1.0.2.20061102121641.0743e668@rcblue.com> <454A5680.2040808@tds.net> Message-ID: <7.0.1.0.2.20061102124302.07411548@rcblue.com> At 12:35 PM 11/2/2006, Kent Johnson wrote: >Dick Moores wrote: >>At 11:33 AM 11/2/2006, Markus Rosenstihl wrote: >>>Try somthing like this: >>> >>>In [32]: a=range(100) >>>In [33]: for i in range(0,len(a)): >>> ....: print '%-27s'%a[i], >>> ....: if (i+1)%3 == 0: print "\n" >>> >>>0 1 2 >>> >>>3 4 5 >>>... >>>93 94 95 >>> >>>96 97 98 >>> >>>99 >>> >>> >>>Note the comma after the first print statement >>Yes, thanks, but the reason I wanted 3 columns was to compress the >>height of the list printout for the user, so I don't want all those >>blank lines. > >Just change 'print "\n"' to 'print' > >Kent Of course! Don't know why I didn't see that. Thanks again, Kent and Markus. Dick From pyro9219 at gmail.com Thu Nov 2 22:40:33 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 2 Nov 2006 13:40:33 -0800 Subject: [Tutor] Print Screen In-Reply-To: <454A3C32.4090001@gmail.com> References: <454A3C32.4090001@gmail.com> Message-ID: Because I dont know any other way to capture the screen? (In my mind using print screen would be universal) =P On 11/2/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I posted this in a similar thread a few days ago, and no replies so I > > think it needs its own listing. > > > > Anyone know of a way to capture special keys like "Print Screen"? > > I have a small script to grab all they keycodes, but it doesn't seem > > to catch several keys on the keyboard. I've got a utility that I'd > > like to be able to automagically get a screenshot when something goes > > wrong so I dont have to hope the user can re-create the error. > > Universal support would be best, but WinXP is the main OS > Why do you need to capture the keypress 'print screen' if you're > automatically taking screenshots when something goes wrong? > > > > Thanks. > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/9776dcb4/attachment.html From rabidpoobear at gmail.com Thu Nov 2 23:23:44 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 16:23:44 -0600 Subject: [Tutor] Print Screen In-Reply-To: References: <454A3C32.4090001@gmail.com> Message-ID: <454A6FF0.4040201@gmail.com> Chris Hengge wrote: > Because I dont know any other way to capture the screen? (In my mind > using print screen would be universal) =P The print screen button doesn't do anything. It generates a keycode just like any other button on the keyboard. Windows captures this keypress and interprets it as you wanting a screenshot. There is no inherent operation tied to this specific button that creates a screenshot. So yeah, you could probably go the route of generating a printscreen keypress, but there are much easier ways to do that. For example, Install PIL, then do >>> import ImageGrab >>> ImageGrab.grab().save('temp.jpg') That's all there is to it. From rabidpoobear at gmail.com Fri Nov 3 01:10:22 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 18:10:22 -0600 Subject: [Tutor] Print Screen In-Reply-To: References: <454A3C32.4090001@gmail.com> <454A6FF0.4040201@gmail.com> Message-ID: <454A88EE.20609@gmail.com> Chris Hengge wrote: > Awesome! Thanks again Luke > > How do I capture the keycode for print screen? (now I'm just curious, > because like I said, I've got a script that grabs all but maybe half a > dozen keys) Well, how are you doing it now? That's the important part. > > On 11/2/06, *Luke Paireepinart* > wrote: > > Chris Hengge wrote: > > Because I dont know any other way to capture the screen? (In my mind > > using print screen would be universal) =P > The print screen button doesn't do anything. > It generates a keycode just like any other button on the keyboard. > Windows captures this keypress and interprets it as you wanting a > screenshot. > There is no inherent operation tied to this specific button that > creates > a screenshot. > So yeah, you could probably go the route of generating a printscreen > keypress, but > there are much easier ways to do that. > For example, > Install PIL, > then do > >>> import ImageGrab > >>> ImageGrab.grab().save('temp.jpg') > That's all there is to it. > > From carroll at tjc.com Fri Nov 3 01:14:41 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Nov 2006 16:14:41 -0800 (PST) Subject: [Tutor] Print Screen In-Reply-To: <454A6FF0.4040201@gmail.com> Message-ID: On Thu, 2 Nov 2006, Luke Paireepinart wrote: > >>> import ImageGrab > >>> ImageGrab.grab().save('temp.jpg') I never knew about that. Thanks, that's pretty cool. From alan.gauld at btinternet.com Fri Nov 3 01:40:33 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Nov 2006 00:40:33 -0000 Subject: [Tutor] Using sys.exit() References: <7.0.1.0.2.20061030163602.0318b238@rcblue.com> <7.0.1.0.2.20061101153713.07860bc0@rcblue.com> Message-ID: "Dick Moores" wrote >>You can use an argument if you want to pass an error value >>back to the OS. This is good practice if your script might be >>used in a batch file or shell script > > So what should that value be? Zero means no errors and is the default value. But you can define any non zero values that you like and so long as you document them users of tyour script can tell why the script stopped. Thus in MSDOS you could write a batch file: PYTHON MYSCRIPT.PY IF ERRORLEVEL == 1 ECHO 'NO INPUT' IF ERRORLEVEL == 2 ECHO 'INVALID INPUTS' etc etc. > don't, because I don't (yet) use python to write either batch files > or shell scripts. Its not about using Python to write the scripts itcs about *using* a python script inside a batch file/shell script This also applies if you use a script from within an os.system() call since os.system() returns the exit value of the command that you execute. Thus err = os.system("python myscript.py") print err err will contain the value passed out by myscript.py as an exit code. The default will be zero which implies that myscript ran successfully. But if you provide meaningful exit codes you can test for those when using os.system(). >>break is not intended to quit programs, break is intended >>to quit loops. To exit a program you should use sys.exit() >>and if its an abnormal exit provide an argument. > > Of course, I've been using break to exit only when it works. Why is > it wrong to do so? Only in that there will be no error value passed back. break sdoesn't really exit the program it just forces execution to fall off the end of your script. for n in range(10): pass Will execute silently and end n = 0 while True: if n > 9: break will do exactly the same Both programs exit when they run out of code to execute. sys.exit() just provides a bit more control over how the script exits and this makes it slightly easier to use the script within a batch file etc.. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Nov 3 01:45:57 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Nov 2006 00:45:57 -0000 Subject: [Tutor] How to capture 'Ctrl+c' in Python References: <1162382385.18283.38.camel@andi-lap> Message-ID: "Chris Hengge" wrote > Do you by chance know of a way to capture special keys like "Print > Screen"? Try the key capture code in my Event Driven topic. So far as I know it works for all keys including the special ones. It also points out that those keys have a two part code... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From frank.hoffsummer at gmail.com Fri Nov 3 01:54:23 2006 From: frank.hoffsummer at gmail.com (frank h.) Date: Fri, 3 Nov 2006 01:54:23 +0100 Subject: [Tutor] setlocale on windows Message-ID: <60fae7c30611021654l254636e2ke19435f956409076@mail.gmail.com> Hello all, I wrote a script on UNIX that uses the following statements: import locale, datetime locale.setlocale(locale.LC_ALL, 'sv_Se') with that, I can get localized dates like this > datetime.datetime.today().strftime('%A') 'Fredag' problem is, this doesnt work on windows! I get: locale.Error: unsupported locale setting how can I set the locale to Swedish on a windows box? thanks for any insight you might have -frank -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/a395d6c5/attachment.htm From billburns at pennswoods.net Fri Nov 3 02:09:59 2006 From: billburns at pennswoods.net (Bill Burns) Date: Thu, 02 Nov 2006 20:09:59 -0500 Subject: [Tutor] Print Screen In-Reply-To: References: Message-ID: <454A96E7.5050502@pennswoods.net> Chris Hengge wrote: > I posted this in a similar thread a few days ago, and no replies so I > think it needs its own listing. > > Anyone know of a way to capture special keys like "Print Screen"? > I have a small script to grab all they keycodes, but it doesn't seem to > catch several keys on the keyboard. I've got a utility that I'd like to > be able to automagically get a screenshot when something goes wrong so I > dont have to hope the user can re-create the error. Universal support > would be best, but WinXP is the main OS > I'm not exactly sure what you want here :-) but if you want to capture when the 'Print Screen' key (or any other key) has actually been pressed, try pyHook. Note: pyHook only works on Windows! Here's some sample code: """ Captures a press of the 'Print Screen' key. The following requires ctypes and pyHook. ctypes is standard in Python2.5. ctypes -> http://sourceforge.net/projects/ctypes/ pyHook -> http://www.cs.unc.edu/Research/assist/developer.shtml """ from ctypes import windll, byref from ctypes.wintypes import MSG import pyHook user32 = windll.user32 def keyboardEvent(event): if event.KeyID == 44: print "You hit 'Print Screen'!" return True hm = pyHook.HookManager() hm.KeyDown = keyboardEvent hm.HookKeyboard() msg = MSG() while user32.GetMessageA(byref(msg), None, 0, 0): user32.TranslateMessage(byref(msg)) user32.DispatchMessageA(byref(msg)) HTH, Bill From simplebob at gmail.com Fri Nov 3 02:13:35 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Thu, 2 Nov 2006 20:13:35 -0500 Subject: [Tutor] One million and counting In-Reply-To: <454803BE.2090400@earthlink.net> References: <000301c6fd44$cb513c60$04000100@XPpro> <454803BE.2090400@earthlink.net> Message-ID: <6d87ecf40611021713h1cc355ffk3040ef762d78abdd@mail.gmail.com> I second Jorge, I also learned from your site. well done, On 10/31/06, Glenn T Norton wrote: > > Alan Gauld wrote: > > >Hi folks, > > > >In just thought I'd mention that my web tutor has now passed > >the million visitors mark. Thanks to all those on the tutor > >list who have paid a visit. > > > >Alan Gauld > >Author of the Learn to Program web site > >http://www.freenetpages.co.uk/hp/alan.gauld > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > Congratulations Alan! I visited your site many times when first learning > Python. > Keep up the good work. > > Glenn > > -- > "Ketchup. For the good times... " - Ketchup Advisory Board > Glenn Norton > Application Developer > Nebraska.gov > 1-402-471-2777 > glenn at nebraska.gov > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Daniel McQuay boxster.homelinux.org H: 814.825.0847 M: 814-341-9013 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/23b21998/attachment.htm From rabidpoobear at gmail.com Fri Nov 3 03:36:18 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 20:36:18 -0600 Subject: [Tutor] Print Screen In-Reply-To: <454A96E7.5050502@pennswoods.net> References: <454A96E7.5050502@pennswoods.net> Message-ID: <454AAB22.5020100@gmail.com> >> Anyone know of a way to capture special keys like "Print Screen"? >> I have a small script to grab all they keycodes, but it doesn't seem to >> catch several keys on the keyboard. I've got a utility that I'd like to >> be able to automagically get a screenshot when something goes wrong so I >> dont have to hope the user can re-create the error. Universal support >> would be best, but WinXP is the main OS >> >> > > I'm not exactly sure what you want here :-) but if you want to capture > when the 'Print Screen' key (or any other key) has actually been > pressed, try pyHook. Note: pyHook only works on Windows! > Also note that if you want all of the keypresses, but you _don't_ care about the application with focus receiving the input, you can do a complete key grab using TKInter or Pygame, and probably the other GUI packages too. But, like I said, if you were, for example, typing an e-mail and you started a script that did a complete grab like this, you'd no longer be able to type into the e-mail window. Using pyHook, your program could see all the keypresses, but they'd also still be sent to the e-mail program. Actually, I've never tried it, but I'm pretty sure that's how the GUI packages' key capturing works. You may be asking 'well, it sounds like pyHook does a better job of this anyway!' Yeah, you're right. However, as Alan exclaimed, pyHook works only on Windows! So the solution I offered would be more portable. Hope that helps, -Luke From python-tutor at ccoker.net Fri Nov 3 04:23:35 2006 From: python-tutor at ccoker.net (Chuck Coker) Date: Thu, 02 Nov 2006 19:23:35 -0800 Subject: [Tutor] Syntax Error? Variable Scope? Message-ID: <454AB637.2050107@ccoker.net> Hi Folks, I am new to Python, but I have many years experience in software development. I have a question about variable scope. I'm having a problem that I suspect is merely a syntax error or something of that nature. I'm not real clear on variable scoping rules, either. I can't figure out how to declare a variable containing a file pointer outside a class and then access the variable from inside a method inside the class. I could be creating errors when trying to use the "global" keyword due to not fully understanding the scope rules. The examples I found so far in books and on the web are to simplistic for what I want to do. I am using a load-testing app named The Grinder (version 3, beta 30) and Python 2.5. I want my script to open an external CSV (comma-separated values) file containing x number of records with people's names, addresses, etc. I want the file opened outside the TestRunner class (the main class for The Grinder) when the script is first started. Then I want each instance of the TestRunner class to read one line from the external CSV file. After it gets the line from the file, I want to split the line at the commas into components and do the processing stuff. After the last instance of TestRunner finishes, I want the script to close the file and exit nicely. My reasoning for opening and closing the CSV file outside the class is that I want the file to stay open and have the file cursor maintain its location after each read. For example, if I am running 2,000 threads, the file gets opened, whatever thread gets there first reads line 1, the next thread that gets there reads line 2, and so on until all 2,000 threads have had a chance to get a different line from the file. Then I want the file to close. Here are some code snippets: ---------------------------------------------------------------------- from net.grinder.script import Test from net.grinder.script.Grinder import grinder from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest from HTTPClient import NVPair connectionDefaults = HTTPPluginControl.getConnectionDefaults() httpUtilities = HTTPPluginControl.getHTTPUtilities() [... snip ...] fileNewUserInfo = 'new-user-info.csv' fileNewUserInfoIsOpen = 0 [... snip ...] class TestRunner: """A TestRunner instance is created for each worker thread.""" # The instance initialization method. def __init__(self): print 'We are in TestRunner.__init__()' global infile global fileNewUserInfoIsOpen if (fileNewUserInfoIsOpen == 0): infile = open(fileNewUserInfo, "r") fileNewUserInfoIsOpen += 1; print 'We are inside the open if statement' #global infile self._userTokenCtx = '' self._userTokenRi = '' self._userInfo = [] for line in infile.readlines(): self._userInfo.append(string.split((line),',')) print line print self._userInfo def nextMethod(self): [... snip ...] ---------------------------------------------------------------------- The script blows up at this line inside the for loop: self._userInfo.append(string.split((line),',')) with this error message in my error log: 11/2/06 7:12:20 PM (thread 0): Aborting thread due to Jython exception "NameError: string" whilst creating per-thread test runner object NameError: string File "new-user-registration.py", line 356, in __init__ I've tried using "import string" and it doesn't like that. I'm sure I'm missing something very basic here due to my newness with Python. Can anyone offer any insights? Thanks, Chuck -- ====================================================================== Chuck Coker, Software Developer python-tutor at ccoker.net Tyrell Software Corporation http://www.tyrell.com Office: +1 949 458 1911 x 203 Cell: +1 714 326 5939 ====================================================================== From pyro9219 at gmail.com Fri Nov 3 05:30:56 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 2 Nov 2006 20:30:56 -0800 Subject: [Tutor] How to capture 'Ctrl+c' in Python In-Reply-To: References: <1162382385.18283.38.camel@andi-lap> Message-ID: I've got your code at home, and I know it picks up shift and ctrl modified items, but it wont register print screen (among a few others). I can post the code I have at home later if you want to verify it. I've been given a few methods to try in my other thread I just started on here which are more practical, but I'm still interested in this. On 11/2/06, Alan Gauld wrote: > > > "Chris Hengge" wrote > > Do you by chance know of a way to capture special keys like "Print > > Screen"? > > Try the key capture code in my Event Driven topic. > > So far as I know it works for all keys including the special ones. > It also points out that those keys have a two part code... > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/1028d69e/attachment.htm From rabidpoobear at gmail.com Fri Nov 3 05:40:38 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 02 Nov 2006 22:40:38 -0600 Subject: [Tutor] How to capture 'Ctrl+c' in Python In-Reply-To: References: <1162382385.18283.38.camel@andi-lap> Message-ID: <454AC846.3010407@gmail.com> Chris Hengge wrote: > I've got your code at home, and I know it picks up shift and ctrl > modified items, but it wont register print screen (among a few > others). I can post the code I have at home later if you want to > verify it. I've been given a few methods to try in my other thread I > just started on here which are more practical, but I'm still > interested in this. Pygame can capture it just fine. import pygame from pygame.locals import * pygame.init() scr = pygame.display.set_mode((640,480)) while 1: pygame.display.update() for event in pygame.event.get(): if event.type == KEYDOWN: print event if event.key == K_ESCAPE: pygame.quit() raise SystemExit when you hit print screen you will see that the keycode is 311, so just do a if event.key == 311: if you want to check if they hit print screen. But this doesn't really help you probably because I don't think you're using Pygame. Just thought i'd mention that. > > On 11/2/06, *Alan Gauld* > wrote: > > > "Chris Hengge" > wrote > > Do you by chance know of a way to capture special keys like "Print > > Screen"? > > Try the key capture code in my Event Driven topic. > > So far as I know it works for all keys including the special ones. > It also points out that those keys have a two part code... > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dustin at v.igoro.us Fri Nov 3 05:56:18 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Thu, 02 Nov 2006 22:56:18 -0600 Subject: [Tutor] Syntax Error? Variable Scope? In-Reply-To: <454AB637.2050107@ccoker.net> References: <454AB637.2050107@ccoker.net> Message-ID: <454ACBF2.7060107@v.igoro.us> Chuck Coker wrote: > from net.grinder.script import Test > from net.grinder.script.Grinder import grinder > from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest > from HTTPClient import NVPair > connectionDefaults = HTTPPluginControl.getConnectionDefaults() > httpUtilities = HTTPPluginControl.getHTTPUtilities() > > [... snip ...] > > fileNewUserInfo = 'new-user-info.csv' > fileNewUserInfoIsOpen = 0 > > [... snip ...] > > class TestRunner: > """A TestRunner instance is created for each worker thread.""" > > # The instance initialization method. > def __init__(self): > print 'We are in TestRunner.__init__()' > global infile > global fileNewUserInfoIsOpen > if (fileNewUserInfoIsOpen == 0): > infile = open(fileNewUserInfo, "r") > fileNewUserInfoIsOpen += 1; > print 'We are inside the open if statement' > #global infile > self._userTokenCtx = '' > self._userTokenRi = '' > self._userInfo = [] > > for line in infile.readlines(): > self._userInfo.append(string.split((line),',')) > print line > > print self._userInfo > > def nextMethod(self): > > [... snip ...] > ---------------------------------------------------------------------- > > The script blows up at this line inside the for loop: > > self._userInfo.append(string.split((line),',')) > > with this error message in my error log: > > 11/2/06 7:12:20 PM (thread 0): Aborting thread due to Jython exception > "NameError: string" whilst creating per-thread test runner object > > NameError: string > File "new-user-registration.py", line 356, in __init__ > > I've tried using "import string" and it doesn't like that. I'm sure > I'm missing something very basic here due to my newness with Python. > Can anyone offer any insights? Python's scoping is a little weird, but you're actually using it right. Adding 'import string' to the top of your module should have fixed this problem, but that's old (like Py 2.1, I think) behavior. Nowadays, you can write e.g., self._userInfo.append(",".split(line)). Also, there's a CSV module that will take care of reading and splitting CSV files for you. Personally, I would write this all out a little differently, taking advantage of the fact that performing operations in the global context is allowed: ... import csv ... userInfo = csv.reader(file('new-user-info.csv', 'rb')) class TestRunner: def __init__(self): for row in userInfo: # row is a tuple of cells print row hopefully that helps. Dustin From pyro9219 at gmail.com Fri Nov 3 08:25:40 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 2 Nov 2006 23:25:40 -0800 Subject: [Tutor] How to capture 'Ctrl+c' in Python In-Reply-To: References: <1162382385.18283.38.camel@andi-lap> Message-ID: I'm not sure where I got this from, but I think its from your site.. import msvcrt def doKeyEvent(key): if key == '\x00' or key == '\xe0': # non ASCII key = msvcrt.getch() # fetch second character print ord(key) def doQuitEvent(key): raise SystemExit # First, clear the screen of clutter then warn the user # of what to do to quit lines = 25 # set to number of lines in console for line in range(lines): print print "Hit space to end..." print # Now mainloop runs "forever" while True: ky = msvcrt.getch() length = len(ky) if length != 0: # send events to event handling functions if ky == " ": # check for quit event doQuitEvent(ky) else: doKeyEvent(ky) On 11/2/06, Alan Gauld wrote: > > > "Chris Hengge" wrote > > Do you by chance know of a way to capture special keys like "Print > > Screen"? > > Try the key capture code in my Event Driven topic. > > So far as I know it works for all keys including the special ones. > It also points out that those keys have a two part code... > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/59e4eb11/attachment.htm From pyro9219 at gmail.com Fri Nov 3 08:31:35 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 2 Nov 2006 23:31:35 -0800 Subject: [Tutor] How to capture 'Ctrl+c' in Python In-Reply-To: References: <1162382385.18283.38.camel@andi-lap> Message-ID: Nevermind, I just realised my problem with the script I just sent. I'm using a laptop right now and the print screen key is FN+ Insert.... FN isn't mappable. Works fine on an external keyboard, so I guess I'll try one of the other recommendations. Thanks alot for the time guys. On 11/2/06, Chris Hengge wrote: > > I'm not sure where I got this from, but I think its from your site.. > > import msvcrt > > def doKeyEvent(key): > if key == '\x00' or key == '\xe0': # non ASCII > key = msvcrt.getch() # fetch second character > print ord(key) > > def doQuitEvent(key): > raise SystemExit > > > # First, clear the screen of clutter then warn the user > # of what to do to quit > lines = 25 # set to number of lines in console > for line in range(lines): print > > print "Hit space to end..." > print > > # Now mainloop runs "forever" > while True: > ky = msvcrt.getch() > length = len(ky) > if length != 0: > # send events to event handling functions > if ky == " ": # check for quit event > doQuitEvent(ky) > else: > doKeyEvent(ky) > > > On 11/2/06, Alan Gauld wrote: > > > > > > "Chris Hengge" wrote > > > Do you by chance know of a way to capture special keys like "Print > > > Screen"? > > > > Try the key capture code in my Event Driven topic. > > > > So far as I know it works for all keys including the special ones. > > It also points out that those keys have a two part code... > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061102/30308999/attachment-0001.html From pyro9219 at gmail.com Fri Nov 3 09:08:19 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 3 Nov 2006 00:08:19 -0800 Subject: [Tutor] Print Screen In-Reply-To: <454AAB22.5020100@gmail.com> References: <454A96E7.5050502@pennswoods.net> <454AAB22.5020100@gmail.com> Message-ID: Wow.. I have visions of writing a little wanna-be VNC client/server now using the ImageGrab.grab() =D This ImageGrab trick does exactly what I wanted. Thanks for the tip! Actually, I want to write a little package for the learning experience sometime over the holidays (plus I use VNC fairly often), but I can't find any direction, or any already made packages for python for the VNC protocol (no libs?). On 11/2/06, Luke Paireepinart wrote: > > > >> Anyone know of a way to capture special keys like "Print Screen"? > >> I have a small script to grab all they keycodes, but it doesn't seem to > >> catch several keys on the keyboard. I've got a utility that I'd like to > >> be able to automagically get a screenshot when something goes wrong so > I > >> dont have to hope the user can re-create the error. Universal support > >> would be best, but WinXP is the main OS > >> > >> > > > > I'm not exactly sure what you want here :-) but if you want to capture > > when the 'Print Screen' key (or any other key) has actually been > > pressed, try pyHook. Note: pyHook only works on Windows! > > > Also note that if you want all of the keypresses, but you _don't_ care > about the application with focus > receiving the input, you can do a complete key grab using TKInter or > Pygame, and probably the other GUI packages too. > But, like I said, if you were, for example, typing an e-mail and you > started a script that did a complete grab like this, you'd no longer be > able to type > into the e-mail window. Using pyHook, your program could see all the > keypresses, but they'd also still be sent to the e-mail program. > Actually, I've never tried it, but I'm pretty sure that's how the GUI > packages' key capturing works. > You may be asking 'well, it sounds like pyHook does a better job of this > anyway!' > Yeah, you're right. > However, as Alan exclaimed, pyHook works only on Windows! > So the solution I offered would be more portable. > Hope that helps, > -Luke > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/7f2cbe57/attachment.htm From rabidpoobear at gmail.com Fri Nov 3 09:35:41 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 03 Nov 2006 02:35:41 -0600 Subject: [Tutor] Print Screen In-Reply-To: References: <454A96E7.5050502@pennswoods.net> <454AAB22.5020100@gmail.com> Message-ID: <454AFF5D.4050000@gmail.com> Chris Hengge wrote: > Wow.. I have visions of writing a little wanna-be VNC client/server > now using the ImageGrab.grab() =D > This ImageGrab trick does exactly what I wanted. Thanks for the tip! > > Actually, I want to write a little package for the learning experience > sometime over the holidays (plus I use VNC fairly often), but I can't > find any direction, or any already made packages for python for the > VNC protocol (no libs?). Heh, I was actually writing my own VNC, that's when I ran into the ImageGrab function. I also did something cool, which is : self.prevscr = self.currscr self.currscr = ImageGrab.grab().resize((800,600)) diff = ImageChops.difference(self.prevscr,self.currscr) Obviously you need a currscr before you start, which I declared during the initialization of the class. The cool part of this is that the ImageChops difference will return black pixels in any area of the screen that hasn't changed. so you can just send the changed parts over the network (if you have a good algorithm to discard the unchanged portions). Would be much faster than sending the whole screen every frame, obviously. Not CPU-faster, but network-faster. From ajkadri at googlemail.com Fri Nov 3 11:51:14 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 3 Nov 2006 10:51:14 +0000 Subject: [Tutor] Checking the format of IP address... Message-ID: Hi Folks, I want to implement a simple program that verifies the IP provided by the user is in the right format or not. How to go about it..? Any suggestions.. TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/1718a735/attachment.htm From kent37 at tds.net Fri Nov 3 12:08:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Nov 2006 06:08:29 -0500 Subject: [Tutor] Syntax Error? Variable Scope? In-Reply-To: <454AB637.2050107@ccoker.net> References: <454AB637.2050107@ccoker.net> Message-ID: <454B232D.5090106@tds.net> Chuck Coker wrote: > Hi Folks, > > I am new to Python, but I have many years experience in software > development. I have a question about variable scope. I'm having a > problem that I suspect is merely a syntax error or something of that > nature. > > I'm not real clear on variable scoping rules, either. I can't figure > out how to declare a variable containing a file pointer outside a > class and then access the variable from inside a method inside the > class. I could be creating errors when trying to use the "global" > keyword due to not fully understanding the scope rules. The examples > I found so far in books and on the web are to simplistic for what I > want to do. Actually you seem to be using 'global' correctly. > > I am using a load-testing app named The Grinder (version 3, beta 30) > and Python 2.5. I think you mean Jython. > > I want my script to open an external CSV (comma-separated values) file > containing x number of records with people's names, addresses, etc. I > want the file opened outside the TestRunner class (the main class for > The Grinder) when the script is first started. > > Then I want each instance of the TestRunner class to read one line > from the external CSV file. After it gets the line from the file, I > want to split the line at the commas into components and do the > processing stuff. > > After the last instance of TestRunner finishes, I want the script to > close the file and exit nicely. > > My reasoning for opening and closing the CSV file outside the class is > that I want the file to stay open and have the file cursor maintain > its location after each read. For example, if I am running 2,000 > threads, the file gets opened, whatever thread gets there first reads > line 1, the next thread that gets there reads line 2, and so on until > all 2,000 threads have had a chance to get a different line from the > file. Then I want the file to close. This is a very strange design. Why do you want to split the processing of the file among 2,000 threads? Why not have a single thread that loops over the lines of the file and processes them? To open the file outside the thread, just open it at global scope as Dustin suggested. Additionally you could pass the open file to __init__() and not rely on it being global. More comments inline. > > Here are some code snippets: > > ---------------------------------------------------------------------- > from net.grinder.script import Test > from net.grinder.script.Grinder import grinder > from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest > from HTTPClient import NVPair > connectionDefaults = HTTPPluginControl.getConnectionDefaults() > httpUtilities = HTTPPluginControl.getHTTPUtilities() > > [... snip ...] > > fileNewUserInfo = 'new-user-info.csv' > fileNewUserInfoIsOpen = 0 > > [... snip ...] > > class TestRunner: > """A TestRunner instance is created for each worker thread.""" > > # The instance initialization method. > def __init__(self): > print 'We are in TestRunner.__init__()' > global infile > global fileNewUserInfoIsOpen > if (fileNewUserInfoIsOpen == 0): > infile = open(fileNewUserInfo, "r") > fileNewUserInfoIsOpen += 1; > print 'We are inside the open if statement' If you have multiple TestRunners this is a race condition waiting to happen. You need a lock on fileNewUserInfoIsOpen to prevent two threads from passing the condition and both opening the file. I would use infile itself as the flag though, if you really have to do it this way. > #global infile > self._userTokenCtx = '' > self._userTokenRi = '' > self._userInfo = [] > > for line in infile.readlines(): > self._userInfo.append(string.split((line),',')) > print line This processes the entire file at once, it is not processing a single line as you described. > > print self._userInfo > > def nextMethod(self): > > [... snip ...] > ---------------------------------------------------------------------- > > The script blows up at this line inside the for loop: > > self._userInfo.append(string.split((line),',')) > > with this error message in my error log: > > 11/2/06 7:12:20 PM (thread 0): Aborting thread due to Jython exception > "NameError: string" whilst creating per-thread test runner object > > NameError: string > File "new-user-registration.py", line 356, in __init__ > > I've tried using "import string" and it doesn't like that. I'm sure > I'm missing something very basic here due to my newness with Python. > Can anyone offer any insights? import string should work, what error do you get? Though as Dustin mentioned, the split() method of line, or the csv module, is recommended. He got the spelling wrong, though - you would use line.split(','). Jython doesn't have a csv module but there are some add-on modules that work. Kent > > Thanks, > Chuck > From kent37 at tds.net Fri Nov 3 12:13:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Nov 2006 06:13:58 -0500 Subject: [Tutor] Checking the format of IP address... In-Reply-To: References: Message-ID: <454B2476.301@tds.net> Asrarahmed Kadri wrote: > > Hi Folks, > > I want to implement a simple program that verifies the IP provided by > the user is in the right format or not. > > How to go about it..? > Any suggestions.. How about googling 'python ip address'? You seem to come here first when you need to do something new. A little effort on your part would be appreciated. Kent From ajkadri at googlemail.com Fri Nov 3 12:17:16 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 3 Nov 2006 11:17:16 +0000 Subject: [Tutor] Checking the format of IP address... In-Reply-To: <454B2476.301@tds.net> References: <454B2476.301@tds.net> Message-ID: Sorry. I will try to first go to GOOGLE and if I cannot find there, then I'll post my query. Thanks for all the support till now. Regards, Asrarahmed On 11/3/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > > > Hi Folks, > > > > I want to implement a simple program that verifies the IP provided by > > the user is in the right format or not. > > > > How to go about it..? > > Any suggestions.. > > How about googling 'python ip address'? > > You seem to come here first when you need to do something new. A little > effort on your part would be appreciated. > > Kent > > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/ab7929b6/attachment.html From guillermo.fernandez.castellanos at gmail.com Fri Nov 3 12:18:58 2006 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Fri, 3 Nov 2006 12:18:58 +0100 Subject: [Tutor] Checking the format of IP address... In-Reply-To: <7d7029e70611030318v38baa2b0m2c7307d64fdd8e0e@mail.gmail.com> References: <7d7029e70611030318v38baa2b0m2c7307d64fdd8e0e@mail.gmail.com> Message-ID: <7d7029e70611030318o790e98afka18fade18925ef93@mail.gmail.com> Hi, I would probably take the string, separate the numbers and check they are acceptable: def correct_ip(ip): # Check if my IP address has 4 numbers separated by dots num=ip.split('.') if not len(num)==4: return False # Check each of the 4 numbers is between 0 and 255 for n in num: try: if int(n) < 0 or int(n) > 255: return False except: return False return True You could also go the regexp way, but I find it a bit more complicated. Hope it helps, G On 11/3/06, Asrarahmed Kadri wrote: > > Hi Folks, > > I want to implement a simple program that verifies the IP provided by the > user is in the right format or not. > > How to go about it..? > Any suggestions.. > > TIA. > Regards, > Asrarahmed > > > -- > To HIM you shall return. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From euoar at yahoo.es Fri Nov 3 14:27:47 2006 From: euoar at yahoo.es (euoar) Date: Fri, 03 Nov 2006 14:27:47 +0100 Subject: [Tutor] question about classes and atributes Message-ID: <454B43D3.6000905@yahoo.es> I think I don't understand the OOP in python, could anyone explain why this code works? class example: atribute = "hello world" print example.atribute Why you don't have to make an object of the class to access to the atribute? ( class example: atribute = "hello world" obj = example() print obj.atribute Thanks in advance. ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From andreas at kostyrka.org Fri Nov 3 15:17:48 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 03 Nov 2006 15:17:48 +0100 Subject: [Tutor] question about classes and atributes In-Reply-To: <454B43D3.6000905@yahoo.es> References: <454B43D3.6000905@yahoo.es> Message-ID: <1162563468.16439.16.camel@andi-lap> Because your atribute is a class attribute: class C: ca = 123 print C.ca # 123 c1 = C() print c1.ca # 123 c1.ca = 140 print c1.ca # 140 print C.ca # 123 c2 = C() print c2.ca # 123 C.ca = 141 print C.ca # 141 print c1.ca # 140 print c2.ca # 141 Basically, when an instance does not have an attribute, it looks them up in the class, which might recurse into base classes. Furthermore, objects & classes 101 material: class C: def method(self): print self c = C() print c.method # bound method to c print C.method # unbound method, checks that first argument is a C print C.__dict__["method"] # function, does NOT check first argument. So basically, the whole self argument handling is magic that happpens during attribute lookup. Andreas Am Freitag, den 03.11.2006, 14:27 +0100 schrieb euoar: > I think I don't understand the OOP in python, could anyone explain why > this code works? > > class example: > atribute = "hello world" > > print example.atribute > > Why you don't have to make an object of the class to access to the > atribute? > > ( class example: > atribute = "hello world" > > obj = example() > print obj.atribute > > > Thanks in advance. > > > ______________________________________________ > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. > http://es.voice.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061103/09d14e7c/attachment.pgp From euoar at yahoo.es Fri Nov 3 16:11:16 2006 From: euoar at yahoo.es (euoar) Date: Fri, 03 Nov 2006 16:11:16 +0100 Subject: [Tutor] question about classes and atributes In-Reply-To: <1162563468.16439.16.camel@andi-lap> References: <454B43D3.6000905@yahoo.es> <1162563468.16439.16.camel@andi-lap> Message-ID: <454B5C14.7070109@yahoo.es> Andreas Kostyrka escribi?: > Because your atribute is a class attribute: > > class C: > ca = 123 > > print C.ca # 123 > c1 = C() > print c1.ca # 123 > c1.ca = 140 > print c1.ca # 140 > print C.ca # 123 > c2 = C() > print c2.ca # 123 > C.ca = 141 > print C.ca # 141 > print c1.ca # 140 > print c2.ca # 141 > > Basically, when an instance does not have an attribute, it looks them up > in the class, which might recurse into base classes. > > Furthermore, objects & classes 101 material: > > class C: > def method(self): > print self > > c = C() > print c.method # bound method to c > print C.method # unbound method, checks that first argument is a C > print C.__dict__["method"] > # function, does NOT check first argument. > > So basically, the whole self argument handling is magic that happpens > during attribute lookup. > > Andreas > > Am Freitag, den 03.11.2006, 14:27 +0100 schrieb euoar: > >> I think I don't understand the OOP in python, could anyone explain why >> this code works? >> >> class example: >> atribute = "hello world" >> >> print example.atribute >> >> Why you don't have to make an object of the class to access to the >> atribute? >> >> ( class example: >> atribute = "hello world" >> >> obj = example() >> print obj.atribute >> >> >> Thanks in advance. >> >> >> ______________________________________________ >> LLama Gratis a cualquier PC del Mundo. >> Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. >> http://es.voice.yahoo.com >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> Thank you for your answer and the examples. So without self it is an instance variable (like "static" in java/c#). But then, I don't understand how is it possible this in your example: c1.ca = 140 or down: print C.method Are you creating new atributes and methods at run time? Is that what has happened? In fact I have tried also this: class example: atribute = "green" obj = example() obj.a_new_atribute = "white" And even this seems to be correct: class example: atribute = "green" example._other_atribute = "yellow" So, in python, you can add methods at run time to an object, and even you can add them to a class at run time? ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From euoar at yahoo.es Fri Nov 3 16:28:12 2006 From: euoar at yahoo.es (euoar) Date: Fri, 03 Nov 2006 16:28:12 +0100 Subject: [Tutor] One million and counting In-Reply-To: <000301c6fd44$cb513c60$04000100@XPpro> References: <000301c6fd44$cb513c60$04000100@XPpro> Message-ID: <454B600C.3040809@yahoo.es> Alan Gauld escribi?: > Hi folks, > > In just thought I'd mention that my web tutor has now passed > the million visitors mark. Thanks to all those on the tutor > list who have paid a visit. > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Congratulations Alan, that's really a nice web, nice place to begin with programing ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From rabidpoobear at gmail.com Fri Nov 3 17:07:07 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 03 Nov 2006 10:07:07 -0600 Subject: [Tutor] question about classes and atributes In-Reply-To: <454B5C14.7070109@yahoo.es> References: <454B43D3.6000905@yahoo.es> <1162563468.16439.16.camel@andi-lap> <454B5C14.7070109@yahoo.es> Message-ID: <454B692B.3010107@gmail.com> >>> I think I don't understand the OOP in python, could anyone explain why >>> this code works? >>> >>> class example: >>> atribute = "hello world" >>> >>> print example.atribute >>> >>> Why you don't have to make an object of the class to access to the >>> atribute? >>> because that attribute is part of the Class object that's created when you declare a class. As you can see by the following code: >>> class example: attribute = 'hello, world!' >>> example there is actually a type of object called 'class.' when you make an instance of a class, >>> a = example() >>> a <__main__.example instance at 0x00B40440> it is now a example object instance. > Thank you for your answer and the examples. So without self it is an > instance variable (like "static" in java/c#). But then, I don't > understand how is it possible this in your example: > > c1.ca = 140 > Because c1 is an instance of the class 'C', it has the attribute .ca already in it. This is a reference to the class attribute 'ca' which is equal to 123. However, when you change c1.ca, because the class attribute 'ca' is immutable (since it's an integer) a local copy of ca is created with the value 140 in it. C.ca is still 123. If you now do C.ca = 234, c1.ca is still 140, because it now has a local (instance) attribute called 'ca' that hides the class attribute. However, if you do something like this... class C: ca = 123 c1 = C() C.ca = 567 print c1.ca you will get an output of '567'. because c1 never got the local instance attribute to replace the reference to the class-wide attribute, so changing the C.ca will also affect c1.ca. > or down: > > print C.method > > Are you creating new atributes and methods at run time? Is that what has happened? In fact I have tried also this: > > class example: > atribute = "green" > > obj = example() > obj.a_new_atribute = "white" > > And even this seems to be correct: > > class example: > atribute = "green" > > example._other_atribute = "yellow" > > > So, in python, you can add methods at run time to an object, and even you can add them to a class at run time? > No, you're confusing Python with a compiled language. You're not adding methods to an object at run-time because there's not a distinction between runtime and compile-time in Python, because compile-time doesn't exist. You can add attributes to classes any time you want inside your program. Just like I can add an element to a list any time I want. a = [1,2,3] a.append(4) Classes are just objects, as lists are, and integers are, and .... everything else is as well. And when I execute the code, Python knows how to do all of these things. You see, an interpreted session is not the same as you think of 'at run time' being. For the most part, an interpreted session is exactly the same as if I were to type the code into a text document, save it, and execute it. So yeah, anywhere in your program you can add methods to classes, but really saying 'at run-time' is confusing terminology. It implies that if I were running someone else's program I could just add methods in on the fly whenever I wanted to. This is not true, unless they've enabled this functionality. HTH, -Luke From mc_anjo at tamu.edu Fri Nov 3 17:59:39 2006 From: mc_anjo at tamu.edu (Chris Smith) Date: Fri, 03 Nov 2006 10:59:39 -0600 Subject: [Tutor] numpy help Message-ID: Howdy, I'm a college student and for one of we are writing programs to numerically compute the parameters of antenna arrays. I decided to use Python to code up my programs. Up to now I haven't had a problem, however we have a problem set where we are creating a large matrix and finding it's inverse to solve the problem. To invert the matrix I've tried using numpy.numarray.linear_algebra.inverse and numpy.oldnumeric.linear_algebra.inverse which both give me the same error ( I was hoping they called different routines but I think they call the same one ). This is the error message I receive: Traceback (most recent call last): File "C:\Documents and Settings\Chris & Esther\Desktop\636_hw5_2\elen636_hw5_2.py", line 60, in matrix_inverse = numpy.numarray.linear_algebra.generalized_inverse(matrix) File "C:\Python25\lib\site-packages\numpy\oldnumeric\linear_algebra.py", line 59, in generalized_inverse return linalg.pinv(a, rcond) File "C:\Python25\lib\site-packages\numpy\linalg\linalg.py", line 557, in pinv u, s, vt = svd(a, 0) File "C:\Python25\lib\site-packages\numpy\linalg\linalg.py", line 485, in svd a = _fastCopyAndTranspose(t, a) File "C:\Python25\lib\site-packages\numpy\linalg\linalg.py", line 107, in _fastCopyAndTranspose cast_arrays = cast_arrays + (_fastCT(a.astype(type)),) TypeError: can't convert complex to float; use abs(z) I've tried inverting small complex matrices and it worked fine. Does anyone know why it won't work for this larger matrix? Any ideas how I can work around this problem and get the correct inverse matrix? Chris P.S. elen636_math.py is my personal library of functions I've create to solve the problem while elen636_hw5_2.py is the program that I'm actually running -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: elen636_math.py Url: http://mail.python.org/pipermail/tutor/attachments/20061103/98f9d6c5/attachment.asc -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: elen636_hw5_2.py Url: http://mail.python.org/pipermail/tutor/attachments/20061103/98f9d6c5/attachment.pot From alan.gauld at btinternet.com Fri Nov 3 18:18:26 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Nov 2006 17:18:26 -0000 Subject: [Tutor] question about classes and atributes References: <454B43D3.6000905@yahoo.es> <1162563468.16439.16.camel@andi-lap> <454B5C14.7070109@yahoo.es> Message-ID: "euoar" wrote in > Thank you for your answer and the examples. > So without self it is an instance variable (like "static" > in java/c#). Without self it is a class attribute like static etc in C++/Java. An instance variable is one that is unique to an instance! Although I think it may be more powerful since I seem to recall that static members are not accessible via inheritance whereas Python class variables are. Also i'm not sure if statics can be reached via an instance whereas Python class variables can. But my Java/C# is very rusty on statics... Note also that you can go even further by specifying class methods too but they need special syntax. If you are only familiar with Java style statics you might find the concept of class variables and methods a little different in Python, which follows the traditional OOP style of Lisp and SmallTalk rather than the hybrid OOP style of Java etc. That is, a class variable/method is usually treated as one that applies to the class itself, or one that is shared by all instances. Java tend to use static methods as a replacement for traditional functions, ie. things you can do without creating an instance. You can do both things in any of the languages but conceptually they tend to be treated differently, especially since Python supports stand-alone functions. > Are you creating new atributes and methods at run time? > Is that what has happened? In fact I have tried also this: Yes, Python classes are a special type of container (really a special type of dictionary) , so just as you can add new keys to a dictionary you an add new attributes to a class or object at run time. > So, in python, you can add methods at run time to an > object, and even you can add them to a class at run time? I'm not sure about adding methods at run time, I've never tried it but I think the magic around the self parameter might not work. But you can definitely add attributes. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pyro9219 at gmail.com Fri Nov 3 19:27:21 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 3 Nov 2006 10:27:21 -0800 Subject: [Tutor] Print Screen In-Reply-To: <454AFF5D.4050000@gmail.com> References: <454A96E7.5050502@pennswoods.net> <454AAB22.5020100@gmail.com> <454AFF5D.4050000@gmail.com> Message-ID: Oh wow! That is great trick for lowering network requirements. Have you actually implimented that into a working app for test? You could shave a bit more from the bandwidth using that trick if you locked to a specific window for transfer *thinking blinking tray icons etc would get stripped*. How are you doing the intelligent transfer? Did you setup a grid on the screen and only update if gridX has changes? Other then that, are there any resources you can share for getting me started with my own VNC? Or do you by chance have any design docs you created/followed I could review to get an idea of the process for this? I'm thinking I'll probably have to find something in another language and just try to duplicate it with python to get me started. On 11/3/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > Wow.. I have visions of writing a little wanna-be VNC client/server > > now using the ImageGrab.grab() =D > > This ImageGrab trick does exactly what I wanted. Thanks for the tip! > > > > Actually, I want to write a little package for the learning experience > > sometime over the holidays (plus I use VNC fairly often), but I can't > > find any direction, or any already made packages for python for the > > VNC protocol (no libs?). > Heh, I was actually writing my own VNC, that's when I ran into the > ImageGrab function. > I also did something cool, which is : > self.prevscr = self.currscr > self.currscr = ImageGrab.grab().resize((800,600)) > > diff = ImageChops.difference(self.prevscr,self.currscr) > > Obviously you need a currscr before you start, which I declared during > the initialization of the class. > The cool part of this is that the ImageChops difference will return > black pixels in any area of the screen that hasn't changed. > so you can just send the changed parts over the network (if you have a > good algorithm to discard the unchanged portions). > Would be much faster than sending the whole screen every frame, obviously. > Not CPU-faster, but network-faster. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/d4c55258/attachment.htm From kent37 at tds.net Fri Nov 3 19:43:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Nov 2006 13:43:37 -0500 Subject: [Tutor] question about classes and atributes In-Reply-To: References: <454B43D3.6000905@yahoo.es> <1162563468.16439.16.camel@andi-lap> <454B5C14.7070109@yahoo.es> Message-ID: <454B8DD9.9040507@tds.net> Alan Gauld wrote: > "euoar" wrote in >> So, in python, you can add methods at run time to an >> object, and even you can add them to a class at run time? > > I'm not sure about adding methods at run time, I've never > tried it but I think the magic around the self parameter > might not work. But you can definitely add attributes. Sure it works: In [1]: class foo(object): pass ...: In [2]: f=foo() In [3]: f.show() --------------------------------------------------------------------------- Traceback (most recent call last) D:\Projects\e3po\ in () : 'foo' object has no attribute 'show' In [4]: def show(self): print "Hi, I'm a foo" ...: In [5]: foo.show=show In [6]: f.show() Hi, I'm a foo More advanced explanation: The magic around the self parameter is actually built-in to every function object (or its class, anyway). Functions have __get__() methods which means they can be used as descriptors. When Python evaluates f.show(), quite a few steps happen: - find the value of the show attribute in the class definition. This finds the show function object. - the function object has a __get__() method, so call show.__get__(obj) where obj is the original object being accessed. - the __get__() method wraps obj and the original function into a new callable object and returns that. - finally the temporary callable is actually called (by calling its __call__() method) and the wrapper adds the self parameter to the argument list and dispatches to the wrapped (original) function. The descriptor mechanism is only used for class attributes, not instance attributes, so if you want to add a method to an individual instance you have to do a little more work using new.instancemethod: In [12]: def show2(self): print "I'm still a foo" ....: The naive approach won't work: In [14]: f.show2 = show2 In [15]: f.show2() : show2() takes exactly 1 argument (0 given) In [17]: import new In [21]: f.show2 = new.instancemethod(show2, f) In [22]: f.show2() I'm still a foo I hope that makes sense to someone; I had to see it about 10 times myself before a light bulb went on. (This is number 10 :-) More info here and in the references: http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION000320000000000000000 Kent From cappy2112 at gmail.com Fri Nov 3 20:32:26 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Fri, 3 Nov 2006 11:32:26 -0800 Subject: [Tutor] Print Screen Message-ID: <8249c4ac0611031132t122ebe11n7e0ad8985a23da77@mail.gmail.com> Date: Thu, 02 Nov 2006 20:09:59 -0500 From: Bill Burns Subject: Re: [Tutor] Print Screen To: Chris Hengge Cc: pythontutor Message-ID: <454A96E7.5050502 at pennswoods.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >>pressed, try pyHook. Note: pyHook only works on Windows! To elaborate, pyHook only works on Win2k and later. I had no success with Windows 98 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/80109d9b/attachment.htm From deandermo at hotmail.com Fri Nov 3 20:18:58 2006 From: deandermo at hotmail.com (dean dermody) Date: Fri, 03 Nov 2006 19:18:58 +0000 Subject: [Tutor] Tutor Digest, Vol 33, Issue 12 In-Reply-To: Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/c88614fe/attachment.html From lucidmonk at gmail.com Fri Nov 3 21:29:23 2006 From: lucidmonk at gmail.com (Todd Dahl) Date: Fri, 3 Nov 2006 15:29:23 -0500 Subject: [Tutor] GUI with Designer Message-ID: <44290fe50611031229o52e03fb8l1b7244e421db21c8@mail.gmail.com> I am wanting to get into some GUI coding with Python and have heard about PyQT and wxPython. Now I am definately not looking for some type of holy war but can anyone give me a good reason to pick one over the other. Also I would like to have a designer with it or a seperate designer that could be used with either. I plan on coding in Windows XP. Thanks, -Todd -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/007dc3a1/attachment.htm From euoar at yahoo.es Fri Nov 3 21:52:20 2006 From: euoar at yahoo.es (euoar) Date: Fri, 03 Nov 2006 21:52:20 +0100 Subject: [Tutor] question about classes and atributes Message-ID: <454BAC04.9010208@yahoo.es> Thank you folks, for your excellent answers. This is really a fantastic place to learn python :-) ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From pine508 at hotmail.com Fri Nov 3 22:37:13 2006 From: pine508 at hotmail.com (Pine Marten) Date: Fri, 03 Nov 2006 16:37:13 -0500 Subject: [Tutor] questions about having python GUI apps running in the background Message-ID: First, I have to thank Alan Gauld for his previous helpful posts--I didn't get to thank him last until the topic had changed much so I felt I missed that window. Also, big congratz on 1 millionth visitor to his great site (I like to think it may have been me that day or at least close). And thanks to others who continue to be so helpful. This is a pretty general topic, but it's Friday afternoon so here goes... I want to create a Python GUI app that is meant to open at start up (either on Windows, Mac, or Linux) and stay running all the time--what I may be incorrectly calling "running in the background". This would be for the reasons of wanting the user to be able to interact with it quickly without having to open the program every time--it partly will have a "stickies" type use--and also to send timed pop up dialogues or alarms to the user at various pre-set times (which may be randomly assigned, user assigned, or both). My concerns are: 1) The app may eat up too much memory if it is not done right. What is reasonable and how can I know how much RAM it's chewing up? 2) What is a good way to time the popups/alarms? The time module? wxTimer? Other? 3) How can it have it's own icon in the tray or the dock? Any input would be appreciated. Thanks _________________________________________________________________ Get FREE company branded e-mail accounts and business Web site from Microsoft Office Live http://clk.atdmt.com/MRT/go/mcrssaub0050001411mrt/direct/01/ From clsdaniel at gmail.com Fri Nov 3 22:56:54 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Fri, 3 Nov 2006 14:56:54 -0700 Subject: [Tutor] GUI with Designer In-Reply-To: <44290fe50611031229o52e03fb8l1b7244e421db21c8@mail.gmail.com> References: <44290fe50611031229o52e03fb8l1b7244e421db21c8@mail.gmail.com> Message-ID: <4fae7dfa0611031356q49cad025m374794f9fde20a2b@mail.gmail.com> wxPython is good for cross-platform stuff and has a few gui designers (Boa Constructor and others comes to mind), I don't know much about PyQT state in this, but PyGtk + Glade (Gui Designer) is a very good combo. Is about choise, I suggest you to do some simple tests with everything until you find something to be confortable with. * PyGtk + Glade * Boa Contructor * SPE + wxPython On 11/3/06, Todd Dahl wrote: > I am wanting to get into some GUI coding with Python and have heard about > PyQT and wxPython. Now I am definately not looking for some type of holy war > but can anyone give me a good reason to pick one over the other. > > Also I would like to have a designer with it or a seperate designer that > could be used with either. I plan on coding in Windows XP. > > Thanks, > > -Todd > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From pyro9219 at gmail.com Fri Nov 3 23:10:32 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 3 Nov 2006 14:10:32 -0800 Subject: [Tutor] GUI with Designer In-Reply-To: <4fae7dfa0611031356q49cad025m374794f9fde20a2b@mail.gmail.com> References: <44290fe50611031229o52e03fb8l1b7244e421db21c8@mail.gmail.com> <4fae7dfa0611031356q49cad025m374794f9fde20a2b@mail.gmail.com> Message-ID: I vouch for the SPE with wxGlade and XRC! (packaged together with IDE) On 11/3/06, Carlos Daniel Ruvalcaba Valenzuela wrote: > > wxPython is good for cross-platform stuff and has a few gui designers > (Boa Constructor and others comes to mind), I don't know much about > PyQT state in this, but PyGtk + Glade (Gui Designer) is a very good > combo. > > Is about choise, I suggest you to do some simple tests with everything > until you find something to be confortable with. > > * PyGtk + Glade > * Boa Contructor > * SPE + wxPython > > On 11/3/06, Todd Dahl wrote: > > I am wanting to get into some GUI coding with Python and have heard > about > > PyQT and wxPython. Now I am definately not looking for some type of holy > war > > but can anyone give me a good reason to pick one over the other. > > > > Also I would like to have a designer with it or a seperate designer that > > could be used with either. I plan on coding in Windows XP. > > > > Thanks, > > > > -Todd > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/2ca52cc4/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Fri Nov 3 23:55:16 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 Nov 2006 14:55:16 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 33, Issue 12 In-Reply-To: References: Message-ID: On Fri, 3 Nov 2006, dean dermody wrote: > > thank you .you can stop sending me these now thanks Done. In the future, please know that you can usually unsubscribe yourself from these kinds of technical mailing lists. Instructions on how to do so are usually at the footer of each message you receive. Good luck to you. From rdm at rcblue.com Sat Nov 4 00:46:35 2006 From: rdm at rcblue.com (Dick Moores) Date: Fri, 03 Nov 2006 15:46:35 -0800 Subject: [Tutor] GUI with Designer In-Reply-To: References: <44290fe50611031229o52e03fb8l1b7244e421db21c8@mail.gmail.com> <4fae7dfa0611031356q49cad025m374794f9fde20a2b@mail.gmail.com> Message-ID: <7.0.1.0.2.20061103154522.01ddf0f8@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/f088dfff/attachment.htm From dpotter at nc.rr.com Sat Nov 4 01:02:01 2006 From: dpotter at nc.rr.com (Doug Potter) Date: Fri, 03 Nov 2006 19:02:01 -0500 Subject: [Tutor] question Message-ID: <454BD879.7030209@nc.rr.com> I don't get the output I would expect from the following. The variable clean1 gives me an empty string. But if i change the for loop to print i[26:40] I get all the info. what do I need to do to capture all the data to clean1? Thanks. >>> a = open('arp.txt') >>> file = a.read() >>> file = file.split('\n') >>> a.close() >>> b = open('arplist.txt','w') >>> clean1 = [] >>> >>> for i in file: ... clean1 = i[26:40] ... >>> clean1 '' From alan.gauld at btinternet.com Sat Nov 4 01:21:43 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 4 Nov 2006 00:21:43 -0000 Subject: [Tutor] question about classes and atributes References: <454B43D3.6000905@yahoo.es><1162563468.16439.16.camel@andi-lap> <454B5C14.7070109@yahoo.es> <454B8DD9.9040507@tds.net> Message-ID: "Kent Johnson" wrote > Alan Gauld wrote: >> I'm not sure about adding methods at run time, I've never > Sure it works: > > In [1]: class foo(object): pass > ...: > In [4]: def show(self): print "Hi, I'm a foo" > > In [5]: foo.show=show > > In [6]: f.show() > Hi, I'm a foo Cool! I'm constantly amazed at the power and simplicity of Python. > More advanced explanation: Yes, it makes sense when its explained. But I'd never have intuitively thought of that! Thanks for the info Kent. Alan G. From pyro9219 at gmail.com Sat Nov 4 01:26:16 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 3 Nov 2006 16:26:16 -0800 Subject: [Tutor] GUI with Designer In-Reply-To: <7.0.1.0.2.20061103154522.01ddf0f8@rcblue.com> References: <44290fe50611031229o52e03fb8l1b7244e421db21c8@mail.gmail.com> <4fae7dfa0611031356q49cad025m374794f9fde20a2b@mail.gmail.com> <7.0.1.0.2.20061103154522.01ddf0f8@rcblue.com> Message-ID: Well, I use SPE which comes with wxGlade and XRC. For the small amount of gui I've done with python I think SPE offers the best IDE coder experience (coming from a VS world). The tools make sense to me. wxGlade is a GUI designer written in Python with the popular GUI toolkit wxPython , that helps you create wxWidgets/wxPython user interfaces. At the moment it can generate Python, C++, Perl and XRC (wxWidgets' XML resources) code. XRC(wxWidgets' XML resources) is nice because it allows you to abstract your interface design (think of any program that uses XML to format skins). Overall, I think everyone using python should give SPE a try, even without gui programming its a great tool for writing code. It's free, and written in python using wxPython.. Stani (the Dev) is a great person for helping out with questions on using his package, he puts out regular updates and fixes. He's got some help from a few other people so its packaged in .exe, .rpm and standalone .zip formats. It's also on the standard repo's for Ubuntu. If you like it, be kind and toss the guy a few bucks for his efforts. If you do, you will get your name mentioned on the SPE news page and get a nice copy of his user manual (pdf). If you want to know more about SPE, check out: http://www.serpia.org/spe or video demonstations at: http://showmedo.com/videos/series?name=PythonDevelopmentWithSPE On 11/3/06, Dick Moores wrote: > > At 02:10 PM 11/3/2006, Chris Hengge wrote: > > I vouch for the SPE with wxGlade and XRC! (packaged together with IDE) > > > I'd be very interested in hearing why you suggest that combination. > > Dick Moores > > > On 11/3/06, *Carlos Daniel Ruvalcaba Valenzuela* < clsdaniel at gmail.com> > wrote: > wxPython is good for cross-platform stuff and has a few gui designers > (Boa Constructor and others comes to mind), I don't know much about > PyQT state in this, but PyGtk + Glade (Gui Designer) is a very good > combo. > > Is about choise, I suggest you to do some simple tests with everything > until you find something to be confortable with. > > * PyGtk + Glade > * Boa Contructor > * SPE + wxPython > > On 11/3/06, Todd Dahl wrote: > > I am wanting to get into some GUI coding with Python and have heard > about > > PyQT and wxPython. Now I am definately not looking for some type of holy > war > > but can anyone give me a good reason to pick one over the other. > > > > Also I would like to have a designer with it or a seperate designer that > > could be used with either. I plan on coding in Windows XP. > > > > Thanks, > > > > -Todd > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061103/b64ce966/attachment.html From alan.gauld at btinternet.com Sat Nov 4 01:31:16 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 4 Nov 2006 00:31:16 -0000 Subject: [Tutor] question References: <454BD879.7030209@nc.rr.com> Message-ID: "Doug Potter" wrote >I don't get the output I would expect from the following. > >>> a = open('arp.txt') > >>> file = a.read() > >>> file = file.split('\n') Easier to do file = open('arp.txt').readlines() But file is a bad name since its an alias for open... > >>> b = open('arplist.txt','w') Not sure why you do this > >>> clean1 = [] > >>> clean is an empty list > >>> for i in file: > ... clean1 = i[26:40] clean is now overwritten by a string until you reach the end of the file upon which clean1 will be an empty string > >>> clean1 > '' Which it is... I think you may have meant to use the append method for i in file: clean1.append(i[26:40]) And since you can iterate over a file the whole thing shrinks to: clean1 = [] for i in open('arp.txt'): clean1.append(i[26:40]) print clean1 Or even more succinctly: clean1 = [i[26:40] for i in open('arp.txt')] print clean1 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sisson.j at gmail.com Fri Nov 3 19:38:59 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Fri, 03 Nov 2006 12:38:59 -0600 Subject: [Tutor] question In-Reply-To: <454BD879.7030209@nc.rr.com> References: <454BD879.7030209@nc.rr.com> Message-ID: <454B8CC3.4070406@gmail.com> Hi Doug, I'm not a Python guru, but shouldn't you be putting the output of file.split('\n') into a list, and not back into a string (for clarity's sake?). Also, if you have two trailing newlines on the file, your final string will be '', so you should be doing clean1.append(i[26:40]) in your for loop, right? Let me know if that helps... Jonathon Doug Potter wrote: > I don't get the output I would expect from the following. > The variable clean1 gives me an empty string. But if i change the for > loop to print i[26:40] I get all the info. > what do I need to do to capture all the data to clean1? > > Thanks. > > >>> a = open('arp.txt') > >>> file = a.read() > >>> file = file.split('\n') > >>> a.close() > >>> b = open('arplist.txt','w') > >>> clean1 = [] > >>> > >>> for i in file: > ... clean1 = i[26:40] > ... > >>> clean1 > '' > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sisson.j at gmail.com Sat Nov 4 04:14:36 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Fri, 03 Nov 2006 21:14:36 -0600 Subject: [Tutor] Print Screen In-Reply-To: References: <454A96E7.5050502@pennswoods.net> <454AAB22.5020100@gmail.com> Message-ID: <454C059C.4070101@gmail.com> Chris, I don't know if this has been mentioned yet, but this site might be useful: http://bdash.net.nz/blog/2003/12/24/python-vnc-client/ The code base has (last I heard) fallen stagnant, but it may very well be worth a look as a starting point for your VNC project idea. Jonathon Chris Hengge wrote: > Wow.. I have visions of writing a little wanna-be VNC client/server now > using the ImageGrab.grab() =D > This ImageGrab trick does exactly what I wanted. Thanks for the tip! > > Actually, I want to write a little package for the learning experience > sometime over the holidays (plus I use VNC fairly often), but I can't > find any direction, or any already made packages for python for the VNC > protocol (no libs?). > > On 11/2/06, *Luke Paireepinart* > wrote: > > > >> Anyone know of a way to capture special keys like "Print Screen"? > >> I have a small script to grab all they keycodes, but it doesn't > seem to > >> catch several keys on the keyboard. I've got a utility that I'd > like to > >> be able to automagically get a screenshot when something goes > wrong so I > >> dont have to hope the user can re-create the error. Universal > support > >> would be best, but WinXP is the main OS > >> > >> > > > > I'm not exactly sure what you want here :-) but if you want to > capture > > when the 'Print Screen' key (or any other key) has actually been > > pressed, try pyHook. Note: pyHook only works on Windows! > > > Also note that if you want all of the keypresses, but you _don't_ care > about the application with focus > receiving the input, you can do a complete key grab using TKInter or > Pygame, and probably the other GUI packages too. > But, like I said, if you were, for example, typing an e-mail and you > started a script that did a complete grab like this, you'd no longer be > able to type > into the e-mail window. Using pyHook, your program could see all the > keypresses, but they'd also still be sent to the e-mail program. > Actually, I've never tried it, but I'm pretty sure that's how the GUI > packages' key capturing works. > You may be asking 'well, it sounds like pyHook does a better job of > this > anyway!' > Yeah, you're right. > However, as Alan exclaimed, pyHook works only on Windows! > So the solution I offered would be more portable. > Hope that helps, > -Luke > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From pyro9219 at gmail.com Sat Nov 4 10:23:43 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 4 Nov 2006 01:23:43 -0800 Subject: [Tutor] Print Screen In-Reply-To: <454C059C.4070101@gmail.com> References: <454A96E7.5050502@pennswoods.net> <454AAB22.5020100@gmail.com> <454C059C.4070101@gmail.com> Message-ID: Wow, that hasn't come up in my searching, thanks! Looks like you are right and the project is dead, but the author did toss there code up for viewing so I can stumble around a bit there. On 11/3/06, Jonathon Sisson wrote: > > Chris, > > I don't know if this has been mentioned yet, but this site might be > useful: > > http://bdash.net.nz/blog/2003/12/24/python-vnc-client/ > > The code base has (last I heard) fallen stagnant, but it may very well > be worth a look as a starting point for your VNC project idea. > > Jonathon > > > Chris Hengge wrote: > > Wow.. I have visions of writing a little wanna-be VNC client/server now > > using the ImageGrab.grab() =D > > This ImageGrab trick does exactly what I wanted. Thanks for the tip! > > > > Actually, I want to write a little package for the learning experience > > sometime over the holidays (plus I use VNC fairly often), but I can't > > find any direction, or any already made packages for python for the VNC > > protocol (no libs?). > > > > On 11/2/06, *Luke Paireepinart* > > wrote: > > > > > > >> Anyone know of a way to capture special keys like "Print > Screen"? > > >> I have a small script to grab all they keycodes, but it doesn't > > seem to > > >> catch several keys on the keyboard. I've got a utility that I'd > > like to > > >> be able to automagically get a screenshot when something goes > > wrong so I > > >> dont have to hope the user can re-create the error. Universal > > support > > >> would be best, but WinXP is the main OS > > >> > > >> > > > > > > I'm not exactly sure what you want here :-) but if you want to > > capture > > > when the 'Print Screen' key (or any other key) has actually been > > > pressed, try pyHook. Note: pyHook only works on Windows! > > > > > Also note that if you want all of the keypresses, but you _don't_ > care > > about the application with focus > > receiving the input, you can do a complete key grab using TKInter or > > Pygame, and probably the other GUI packages too. > > But, like I said, if you were, for example, typing an e-mail and you > > started a script that did a complete grab like this, you'd no longer > be > > able to type > > into the e-mail window. Using pyHook, your program could see all > the > > keypresses, but they'd also still be sent to the e-mail program. > > Actually, I've never tried it, but I'm pretty sure that's how the > GUI > > packages' key capturing works. > > You may be asking 'well, it sounds like pyHook does a better job of > > this > > anyway!' > > Yeah, you're right. > > However, as Alan exclaimed, pyHook works only on Windows! > > So the solution I offered would be more portable. > > Hope that helps, > > -Luke > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061104/c103c374/attachment.htm From ajkadri at googlemail.com Sat Nov 4 11:36:58 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 4 Nov 2006 10:36:58 +0000 Subject: [Tutor] Two Questions...(i) Checking for None (ii) Making command line arguments mutually exclusive Message-ID: Hi Folks, I am trying to build a program which takes the following command-line arguments: *-s -D -n -t * the first argument which is -s (for source) can be replaced by -d (for destination) or -o (for observer) or -r (for reporter). Now what I want is to make sure that the user only supplies one of the options from the 4 alternatives. I am using 'optparse' module. It has got a nice feature taht enables you to give the option name, along with the variable-name to store the value of that option. The syntax is as under: from optparse import OptionParser parser = OptionParser() # make an object of OptionParser parser.add_option("-s", action="store", type="string", dest="source_ip" ) # mapping argument to the value and storing it in souce_ip My second question is about chekcing for None type. The issue is that optionParser sets the value = None for all the options that are not specified by the user. So suppose if the user doesnt specify -t, then time would be set to None. How to check the None type. TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061104/9a849935/attachment.html From alan.gauld at btinternet.com Sat Nov 4 14:30:45 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 4 Nov 2006 13:30:45 -0000 Subject: [Tutor] Two Questions...(i) Checking for None (ii) Making commandline arguments mutually exclusive References: Message-ID: "Asrarahmed Kadri" wrote > *-s -D -n -t > time>* > > the first argument which is -s (for source) can be replaced by -d > (for > destination) or -o (for observer) or -r (for reporter). Now what I > want is > to make sure that the user only supplies one of the options from the > 4 > alternatives. > I think you will need to hard-code the logic. Check to see which options have been defined and if more than one of the optional options exists print an error. if a and (b or c or d) or (b and (c or d)) or (c and d): print errorMessage Another way is to count the values: if len([val for val in [a,b,c,d] if val != None]) > 1: print errorMessage > My second question is about chekcing for None type. The issue is > that > optionParser sets the value = None for all the options that are not > specified by the user. So suppose if the user doesnt specify -t, > then time > would be set to None. How to check the None type. if x == None As simple as that. Alan G. From ajkadri at googlemail.com Sat Nov 4 16:46:22 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 4 Nov 2006 15:46:22 +0000 Subject: [Tutor] Amazing power of Regular Expressions... Message-ID: Hi Folks, I dont know much about Regular Expressions. But I just want to share my ideas. I was trying to implement error checking code on the date argument: I did this: import re # the user should enter date in the format: dd/mm/yyyy p = re.compile('\d\d/\d\d/\d\d\d\d') m = p.match(date) the function match will return an object of type SRE_Match only if the user has supplied the string in the form of dd/mm/yyyy. If the user tries to supply negative values, then match will return None. So no hassle of using all those Ifs and Elifs........ I think REGULAR Expressions can be quite powerful... Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061104/3c022b56/attachment.html From dustin at v.igoro.us Sat Nov 4 19:30:05 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Sat, 04 Nov 2006 12:30:05 -0600 Subject: [Tutor] Two Questions...(i) Checking for None (ii) Making commandline arguments mutually exclusive In-Reply-To: References: Message-ID: <454CDC2D.8080206@v.igoro.us> > if x == None > > As simple as that. In fact, I think the following is even a little more readable: if x is None and in fact that syntax has some advantages in various corner cases. It's largely a matter of preference. Dustin From ajkadri at googlemail.com Sat Nov 4 20:30:44 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 4 Nov 2006 19:30:44 +0000 Subject: [Tutor] A question abt exception handling Message-ID: Hi Folks, I want to know how we can print the error message when an exception is generated. I mean "the exact error message that is generated by the python interpreter." My code is as under: def check_date(date,num_days): # this function takes a date and number of days and returns the start and end dates if num_days < 0 or num_days > 31: print "The argument for -n has to be between 0 and 31" sys.exit(1) else: p = re.compile('\d\d/\d\d/\d\d\d\d') m = p.match(date) if m == None: print "The argument for -D has to be in the format: dd/mm/yyyy" sys.exit(1) else: try: date_list = m.group().split('/') date_list.reverse() startdate = datetime.date (int(date_list[0]),int(date_list[1]),int(date_list[2])) enddate = startdate + datetime.timedelta(days=num_days) except ValueError: #here i want to print the exact error message generated by the Python interpreter (it reduces the error checking from my side, the value error is generated if the User inputs an INVALID DATE) return (startdate,enddate) TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061104/feb39da8/attachment.htm From dustin at v.igoro.us Sat Nov 4 20:38:01 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Sat, 04 Nov 2006 13:38:01 -0600 Subject: [Tutor] A question abt exception handling In-Reply-To: References: Message-ID: <454CEC19.7080808@v.igoro.us> import traceback try: something_funny() except: traceback.print_exc() should do the trick for you. Dustin From sisson.j at gmail.com Sat Nov 4 14:54:13 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sat, 04 Nov 2006 07:54:13 -0600 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: References: Message-ID: <454C9B85.3080504@gmail.com> Asrarahmed Kadri wrote: > tries to supply negative values, then match will return None. > So no hassle of using all those Ifs and Elifs........ > I think REGULAR Expressions can be quite powerful... Indeed...Regular expressions were discovered etched into the blade of a sword that had been planted into a rock somewhere in ancient England...(yes, I'm kidding...but discovering RE's can make you feel that way...) Regular Expressions can be cryptic at first, but once you get the hang of them they're addicting... As Alan Gauld stated in another thread (I'm pretty sure it was Alan): You'll get to the point that you want to use (regular expressions) all the time, even if they aren't the right tool for the job. If something like a string function or a list slice can handle the job, don't go overkill on it. I speak from experience...listen to Alan's advice. I have used RE's where they weren't the right tool, and the deeper I got into the code the more I was made aware that RE's were a bad choice. It's tough to dump a week or two's worth of work because of one bad decision...most of the time the tendency is to force the bad decision, and this leads to bad code... To summarize: Regular Expressions: learn them, love them, use them...but put the sword down if a pen can handle the job better. Jonathon > > Hi Folks, > > > I dont know much about Regular Expressions. But I just want to share my > ideas. > > I was trying to implement error checking code on the date argument: > > I did this: > > import re > # the user should enter date in the format: dd/mm/yyyy > p = re.compile('\d\d/\d\d/\d\d\d\d') > > m = p.match(date) > > the function match will return an object of type SRE_Match only if the > user has supplied the string in the form of dd/mm/yyyy. If the user > > Regards, > Asrarahmed > -- > To HIM you shall return. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hmm at woolgathering.cx Sat Nov 4 22:04:29 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Sat, 4 Nov 2006 16:04:29 -0500 Subject: [Tutor] Encoding and XML troubles Message-ID: <20061104210429.GA31439@sillyrabbi.dyndns.org> I've been struggling with encodings in my XML input to Python programs. Here's the situation - my program has no declared encoding, so it defaults to ASCII. It's written in Unicode, but apparently that isn't confusing to the parser. Fine by me. I import some XML, probably encoded in the Windows character set (I don't remember what that's called now). I can read it for the most part - but it throws exceptions when it hits accented characters (some data is being input by French speakers). I am using ElementTree for my XML parsing What I'm trying to do is figure out what I need to do to get my program to not barf when it hits an accented character. I've tried adding an encoding line as suggested here: http://www.python.org/dev/peps/pep-0263/ What these do is make the program fail to parse the XML at all. Has anyone encountered this? Suggestions? Thanks. -- yours, William From alan.gauld at btinternet.com Sun Nov 5 00:29:50 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 4 Nov 2006 23:29:50 -0000 Subject: [Tutor] Amazing power of Regular Expressions... References: <454C9B85.3080504@gmail.com> Message-ID: "Jonathon Sisson" wrote > of them they're addicting... As Alan Gauld stated in another thread > (I'm > pretty sure it was Alan): You'll get to the point that you want to > use > (regular expressions) all the time, even if they aren't the right > tool Nope, it wasn't me, maybe Danny. But I sure agree with it. The problem with Regex is that they can be just a bit too powerful. To cite another programming proverb, this time by Bjarne Stroustrup I think: "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg." Regex can be like that too. > Regular Expressions: learn them, love them, use them...but put the > sword down if a pen can handle the job better. A great summary. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From broek at cc.umanitoba.ca Sun Nov 5 01:11:03 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 04 Nov 2006 18:11:03 -0600 Subject: [Tutor] shebang problem Message-ID: <454D2C17.5060705@cc.umanitoba.ca> Hi all, I'm still getting comfortable with Linux and this might be an OS rather than a python problem. I am trying to make a script directly executable. I've reviewed the 2nd ed of the Nutshell, and I cannot work out what I'm doing wrong. I'm running ubunutu 6.10 (edgy eft). Here's a copy past of my command line: brian at gottlob:~/test$ which python /usr/bin/python brian at gottlob:~/test$ ls -la shebangtest.py -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py brian at gottlob:~/test$ cat shebangtest.py #!/usr/bin/python if __name__ == '__main__': print "It works" brian at gottlob:~/test$ shebangtest bash: shebangtest: command not found brian at gottlob:~/test$ shebangtest.py bash: shebangtest.py: command not found I've also tried: #!/usr/bin python as my shebang line. I've been unable to get this to work. Clearly, there is something I've misunderstood. (`#!' is not an easy thing to google for :-) Best, Brian vdB From carlos.hanson at gmail.com Sun Nov 5 01:40:51 2006 From: carlos.hanson at gmail.com (Carlos Hanson) Date: Sat, 4 Nov 2006 16:40:51 -0800 (PST) Subject: [Tutor] shebang problem In-Reply-To: <454D2C17.5060705@cc.umanitoba.ca> References: <454D2C17.5060705@cc.umanitoba.ca> Message-ID: <1756.67.171.135.96.1162687251.squirrel@webmail.ttsd.k12.or.us> On Sat, November 4, 2006 4:11 pm, Brian van den Broek wrote: > Hi all, > > I'm still getting comfortable with Linux and this might be an OS > rather than a python problem. > > I am trying to make a script directly executable. I've reviewed the > 2nd ed of the Nutshell, and I cannot work out what I'm doing wrong. > I'm running ubunutu 6.10 (edgy eft). Here's a copy past of my command > line: > > brian at gottlob:~/test$ which python > /usr/bin/python > brian at gottlob:~/test$ ls -la shebangtest.py > -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py > brian at gottlob:~/test$ cat shebangtest.py > #!/usr/bin/python > > if __name__ == '__main__': > > print "It works" > brian at gottlob:~/test$ shebangtest > bash: shebangtest: command not found > brian at gottlob:~/test$ shebangtest.py > bash: shebangtest.py: command not found > > I've also tried: > > #!/usr/bin python > > as my shebang line. > > I've been unable to get this to work. Clearly, there is something I've > misunderstood. (`#!' is not an easy thing to google for :-) > > Best, > > Brian vdB > Your answer lies in the file permission. The file needs to be executable. If you look at the man pages for chmod, you will find your answer. The shebang line tells the shell what to use to run the script. For example, if the file is not executable, you would execute it as follows: $ python shebangtest.py As you found with `which python`, python is in /usr/bin, so executing the script is actually $ /usr/bin/python shebangtest.py Therefore, the shebang line needs to be as follows: #! /usr/bin/python Then once the script has execute permissions (man chmod), it will run as expected. -- Carlos Hanson Web and System Administrator Tigard-Tualatin School District 503.431.4053 From alan.gauld at btinternet.com Sun Nov 5 01:47:34 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 5 Nov 2006 00:47:34 -0000 Subject: [Tutor] shebang problem References: <454D2C17.5060705@cc.umanitoba.ca> Message-ID: brian at gottlob:~/test$ ls -la shebangtest.py -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py so the file is called shebangtest.py... > brian at gottlob:~/test$ shebangtest > bash: shebangtest: command not found but you try to run shebangtest... bash can't find the file. you didn't put the .py on the end Also you may not have . in your path. For security reasons it isn't there by default. Try brian at gottlob:~/test$ ./shebangtest.py HTH, Alan G. From rick at niof.net Sun Nov 5 01:30:16 2006 From: rick at niof.net (Rick Pasotto) Date: Sat, 4 Nov 2006 19:30:16 -0500 Subject: [Tutor] shebang problem In-Reply-To: <454D2C17.5060705@cc.umanitoba.ca> References: <454D2C17.5060705@cc.umanitoba.ca> Message-ID: <20061105003016.GE22925@niof.net> On Sat, Nov 04, 2006 at 06:11:03PM -0600, Brian van den Broek wrote: > Hi all, > > I'm still getting comfortable with Linux and this might be an OS > rather than a python problem. > > I am trying to make a script directly executable. I've reviewed the > 2nd ed of the Nutshell, and I cannot work out what I'm doing wrong. > I'm running ubunutu 6.10 (edgy eft). Here's a copy past of my command > line: > > brian at gottlob:~/test$ which python > /usr/bin/python > brian at gottlob:~/test$ ls -la shebangtest.py > -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py > brian at gottlob:~/test$ cat shebangtest.py > #!/usr/bin/python > > if __name__ == '__main__': > > print "It works" > brian at gottlob:~/test$ shebangtest > bash: shebangtest: command not found > brian at gottlob:~/test$ shebangtest.py > bash: shebangtest.py: command not found Most likely the current directory is not in your path. Type in 'echo $PATH' and look for a single period between colons. It is correct *not* to have the current directory in your path for security reasons. Now type in: './shebangtest' and your program should run. Putting the './' in front tells bash to use the command in the current directory. -- "Rousseau was convinced that God, nature and man were wrong. I know that this opinion still sways many minds, but mine is not one of them." -- Fr?d?ric Bastiat (1801-1850) Rick Pasotto rick at niof.net http://www.niof.net From rabidpoobear at gmail.com Sun Nov 5 02:06:17 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 4 Nov 2006 19:06:17 -0600 Subject: [Tutor] Print Screen In-Reply-To: References: <454A96E7.5050502@pennswoods.net> <454AAB22.5020100@gmail.com> <454C059C.4070101@gmail.com> Message-ID: I didn't set up a design doc or anything. I just randomly have ideas sometimes and I just make a prototype first so I can see what kind of problems arise, because when I just think about it I can't determine what I will need in order to make the app. For example, all the functions that I found to do this type of stuff. >_> Yeah, I don't plan ahead. Which is why I might fail my Software Engineering class when I'm a senior. Ah well. I'm in the process of learning how to make requirements sheets and such, and unit tests. I'm not good at that kind of stuff right at the moment. Well, the long and short of it is, I don't have anything that would be of help to you, except ideas about how things can be done. And the guy who wrote that vnc client probably has thought through all of these things more thoroughly than I have. One thing I was also trying to make a prototype of, so I could integrate it into the VNC app if I ever got around to it, was a VoIP client/server. I was going to use Speex as the audio codec, and use pyMedia as the microphone input. The only problem I had was that the pySpeex bindings were only compiled for python 2.2, and I'm trying to get them to compile for 2.4. I installed Visual Studio .net 2003, which is supposedly the compiler they used for python 2.4, but I still haven't managed to get the kinks worked out well enough for a compile to work. I think the speex guys changed around where all the source codes are located, so I've been trying to re-arrange everything into the directory structure the python compile script expects. So yeah. If I get that working, the actual VoIP part shouldn't be too hard. pySpeex looks like it should be able to integrate with pyMedia, and pyMedia makes microphone input super-easy. I'm not sure what version of Visual Studio 2.5 was built with, but if I can get a copy of it, I'll probably try to compile pySpeex for 2.5 also. On 11/4/06, Chris Hengge wrote: > > Wow, that hasn't come up in my searching, thanks! > Looks like you are right and the project is dead, but the author did toss > there code up for viewing so I can stumble around a bit there. > > On 11/3/06, Jonathon Sisson wrote: > > > > Chris, > > > > I don't know if this has been mentioned yet, but this site might be > > useful: > > > > http://bdash.net.nz/blog/2003/12/24/python-vnc-client/ > > > > The code base has (last I heard) fallen stagnant, but it may very well > > be worth a look as a starting point for your VNC project idea. > > > > Jonathon > > > > > > Chris Hengge wrote: > > > Wow.. I have visions of writing a little wanna-be VNC client/server > > now > > > using the ImageGrab.grab() =D > > > This ImageGrab trick does exactly what I wanted. Thanks for the tip! > > > > > > Actually, I want to write a little package for the learning experience > > > sometime over the holidays (plus I use VNC fairly often), but I can't > > > find any direction, or any already made packages for python for the > > VNC > > > protocol (no libs?). > > > > > > On 11/2/06, *Luke Paireepinart* > > > wrote: > > > > > > > > > >> Anyone know of a way to capture special keys like "Print > > Screen"? > > > >> I have a small script to grab all they keycodes, but it > > doesn't > > > seem to > > > >> catch several keys on the keyboard. I've got a utility that > > I'd > > > like to > > > >> be able to automagically get a screenshot when something goes > > > wrong so I > > > >> dont have to hope the user can re-create the error. Universal > > > support > > > >> would be best, but WinXP is the main OS > > > >> > > > >> > > > > > > > > I'm not exactly sure what you want here :-) but if you want to > > > capture > > > > when the 'Print Screen' key (or any other key) has actually > > been > > > > pressed, try pyHook. Note: pyHook only works on Windows! > > > > > > > Also note that if you want all of the keypresses, but you _don't_ > > care > > > about the application with focus > > > receiving the input, you can do a complete key grab using TKInter > > or > > > Pygame, and probably the other GUI packages too. > > > But, like I said, if you were, for example, typing an e-mail and > > you > > > started a script that did a complete grab like this, you'd no > > longer be > > > able to type > > > into the e-mail window. Using pyHook, your program could see all > > the > > > keypresses, but they'd also still be sent to the e-mail program. > > > Actually, I've never tried it, but I'm pretty sure that's how the > > GUI > > > packages' key capturing works. > > > You may be asking 'well, it sounds like pyHook does a better job > > of > > > this > > > anyway!' > > > Yeah, you're right. > > > However, as Alan exclaimed, pyHook works only on Windows! > > > So the solution I offered would be more portable. > > > Hope that helps, > > > -Luke > > > > > > > > > > > > > > ------------------------------------------------------------------------ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061104/03044ec1/attachment.htm From sisson.j at gmail.com Sat Nov 4 20:07:16 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sat, 04 Nov 2006 13:07:16 -0600 Subject: [Tutor] shebang problem In-Reply-To: <1756.67.171.135.96.1162687251.squirrel@webmail.ttsd.k12.or.us> References: <454D2C17.5060705@cc.umanitoba.ca> <1756.67.171.135.96.1162687251.squirrel@webmail.ttsd.k12.or.us> Message-ID: <454CE4E4.4080502@gmail.com> Brian, It's not a permissions issue... (from the original e-mail...see below) >> brian at gottlob:~/test$ ls -la shebangtest.py >> -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py This is clearly executable by brian, and clearly being executed by brian. The shebang line is correct (#!/usr/bin/python). The problem is *how* you are executing the file. If you simply type in the filename, your shell looks on your PATH to find the file. Unless ~/test is on PATH, you'll get a "command not found" error. Instead type in: ./shebangtest.py and see if that works. "./" tells the shell to look in your current working directory for the file. Let me know if that solved the problem... Jonathon Carlos Hanson wrote: > On Sat, November 4, 2006 4:11 pm, Brian van den Broek wrote: >> Hi all, >> >> I'm still getting comfortable with Linux and this might be an OS >> rather than a python problem. >> >> I am trying to make a script directly executable. I've reviewed the >> 2nd ed of the Nutshell, and I cannot work out what I'm doing wrong. >> I'm running ubunutu 6.10 (edgy eft). Here's a copy past of my command >> line: >> >> brian at gottlob:~/test$ which python >> /usr/bin/python >> brian at gottlob:~/test$ ls -la shebangtest.py >> -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py >> brian at gottlob:~/test$ cat shebangtest.py >> #!/usr/bin/python >> >> if __name__ == '__main__': >> >> print "It works" >> brian at gottlob:~/test$ shebangtest >> bash: shebangtest: command not found >> brian at gottlob:~/test$ shebangtest.py >> bash: shebangtest.py: command not found >> >> I've also tried: >> >> #!/usr/bin python >> >> as my shebang line. >> >> I've been unable to get this to work. Clearly, there is something I've >> misunderstood. (`#!' is not an easy thing to google for :-) >> >> Best, >> >> Brian vdB >> > > Your answer lies in the file permission. The file needs to be > executable. If you look at the man pages for chmod, you will find > your answer. > > The shebang line tells the shell what to use to run the script. For > example, if the file is not executable, you would execute it as > follows: > > $ python shebangtest.py > > As you found with `which python`, python is in /usr/bin, so executing > the script is actually > > $ /usr/bin/python shebangtest.py > > Therefore, the shebang line needs to be as follows: > > #! /usr/bin/python > > Then once the script has execute permissions (man chmod), it will run > as expected. > From rabidpoobear at gmail.com Sun Nov 5 02:11:39 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 4 Nov 2006 19:11:39 -0600 Subject: [Tutor] Encoding and XML troubles In-Reply-To: <20061104210429.GA31439@sillyrabbi.dyndns.org> References: <20061104210429.GA31439@sillyrabbi.dyndns.org> Message-ID: Inputting XML into a Python program has nothing to do with what encoding the python source is in. So it seems to me that that particular PEP doesn't apply in this case at all. I'm guessing that the ElementTree module has an option to use Unicode input. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061104/bb8d72c9/attachment.html From sisson.j at gmail.com Sat Nov 4 20:16:04 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sat, 04 Nov 2006 13:16:04 -0600 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: References: <454C9B85.3080504@gmail.com> Message-ID: <454CE6F4.6040102@gmail.com> Ahh, sorry, sorry. I haven't been able to locate the thread that I read that summarized passage from, so I can't say who exactly said all of that... Nice quote on C/C++...made me laugh. Jonathon Alan Gauld wrote: > "Jonathon Sisson" wrote > >> of them they're addicting... As Alan Gauld stated in another thread >> (I'm >> pretty sure it was Alan): You'll get to the point that you want to >> use >> (regular expressions) all the time, even if they aren't the right >> tool > > Nope, it wasn't me, maybe Danny. > > But I sure agree with it. The problem with Regex is that they can > be just a bit too powerful. To cite another programming proverb, > this time by Bjarne Stroustrup I think: > > "C makes it easy to shoot yourself in the foot; > C++ makes it harder, but when you do, > it blows away your whole leg." > > Regex can be like that too. > >> Regular Expressions: learn them, love them, use them...but put the >> sword down if a pen can handle the job better. > > A great summary. > From carlos.hanson at gmail.com Sun Nov 5 02:38:18 2006 From: carlos.hanson at gmail.com (Carlos Hanson) Date: Sat, 4 Nov 2006 17:38:18 -0800 (PST) Subject: [Tutor] shebang problem In-Reply-To: <454CE4E4.4080502@gmail.com> References: <454D2C17.5060705@cc.umanitoba.ca> <1756.67.171.135.96.1162687251.squirrel@webmail.ttsd.k12.or.us> <454CE4E4.4080502@gmail.com> Message-ID: <2017.67.171.135.96.1162690698.squirrel@webmail.ttsd.k12.or.us> On Sat, November 4, 2006 11:07 am, Jonathon Sisson wrote: > Brian, > > It's not a permissions issue... > > (from the original e-mail...see below) > >> brian at gottlob:~/test$ ls -la shebangtest.py -rwxr-xr-- 1 brian > >> brian 68 2006-11-04 02:29 shebangtest.py > > This is clearly executable by brian, and clearly being executed by > brian. The shebang line is correct (#!/usr/bin/python). > [...] Good call. I jumped on the answer without making sure I clearly read all the information provided. -- Carlos Hanson > > Carlos Hanson wrote: >> >> Your answer lies in the file permission. The file needs to be >> executable. If you look at the man pages for chmod, you will find >> your answer. >> From noufal at airtelbroadband.in Sun Nov 5 09:17:06 2006 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sun, 05 Nov 2006 13:47:06 +0530 Subject: [Tutor] Wrong module name and line number in logging package. Message-ID: <454D9E02.4010809@airtelbroadband.in> Greetings everyone, I'm using the python standard logging package for a personal project of mine and have initialised it like so. logger = logging.getLogger("pydagogue") handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("[%(levelname)s]%(pathname)s:%(lineno)d %(message)s")) logger.addHandler(handler) logger.setLevel(logging.DEBUG) Suppose I have a module called ui as part of this project, I want debug messages from it to be displayed like (assuming it's called from line 25) [DEBUG]ui.py:25 Debug message here. the level displays fine and so does the message. The pathname however prints the name logging/__init__.py and the lineno 1072 which I assume are from the logging module itself. Am I doing something wrong here? Peace. -- ~noufal From md at holisticgp.com.au Sun Nov 5 13:15:54 2006 From: md at holisticgp.com.au (Michael Daly) Date: Sun, 5 Nov 2006 23:15:54 +1100 Subject: [Tutor] python, python2 & python2.3 in /usr/bin In-Reply-To: <454D9E02.4010809@airtelbroadband.in> Message-ID: <000e01c700d4$25ad9c70$0100000a@P4> Greetings everyone Could someone please explain these links...python2 seems to have resulted from an installation of python 2.5 (in a specified dir via the --prefix switch) and is a symbolic link to 'python' The others - python and python2.3 are just files and predate the python2 file. I am worried that installing python 2.5 might have upset the 'path' for python (which I don't understand very well). When I type 'python -V' I get: python 2.3.4 which is what i want for centos / asterisk; however asterisk had trouble starting after a reboot (it is a python 2.3.4 dependent app) Does this sound normal? Thanks to anyone who can help Regards & remaining, Compused From kent37 at tds.net Sun Nov 5 16:02:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Nov 2006 10:02:56 -0500 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: References: <454C9B85.3080504@gmail.com> Message-ID: <454DFD20.8050403@tds.net> Alan Gauld wrote: > But I sure agree with it. The problem with Regex is that they can > be just a bit too powerful. To cite another programming proverb, > this time by Bjarne Stroustrup I think: > > "C makes it easy to shoot yourself in the foot; > C++ makes it harder, but when you do, > it blows away your whole leg." > > Regex can be like that too. I guess it's time to trot out the famous quote of Jamie Zawinsky: > Some people, when confronted with a problem, think > ?I know, I'll use regular expressions.? Now they have two problems. In this case I think regex is not the best solution. A better way to validate a date is to try to use it as a date. The regex '\d\d/\d\d/\d\d\d\d' accepts all kinds of non-dates such as 99/99/9999, not to mention accepting US format dates such as 12/25/2006 when you want 25/12/2006. I would use import time try: time.strptime(date, '%d/%m/%Y') # it's a valid date except ValueError: # not a valid date which at least restricts the input to something that is a valid date, though it won't detect that a user typed 11/5/2006 when they mean 5/11/2006. Regular expressions are an extremely powerful and useful tool that every programmer should master and then put away and not use when there is an alternative :-) Kent From ajkadri at googlemail.com Sun Nov 5 16:36:15 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sun, 5 Nov 2006 15:36:15 +0000 Subject: [Tutor] Help me to debug this script .. I tried but .... Message-ID: Hi Folks, I have a function defined in a module. I am using this module in a script but its giving me error: the traceback is as follows: 29/2/2003 ['29', '2', '2003'] Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\project stuff-programs\Scriptdate.py", line 18, in ? t1 = my_version_datecheck.dateCheck(dt1,0) File "my_version_datecheck.py", line 38, in dateCheck import traceback NameError: global name 'traceback' is not defined The module name is : my_version_datecheck.py import string import datetime import time def dateCheck(date1,num_days): flag = True startdate = None enddate = None if num_days < 0 or num_days > 31: flag = False print "The argument for -n has to be between 0 and 31" return (flag,startdate,enddate) else: print date1 date_lst = string.split(date1,"/") print date_lst ln = len(date_lst) if ln != 3: flag = False print "The argument for -D option has to be in the format: dd/mm/yyyy" return (flag,startdate,enddate) else: date_lst.reverse() try: startdate = datetime.date (int(date_lst[0]),int(date_lst[1]),int(date_lst[2])) enddate = startdate + datetime.timedelta(days=num_days) except ValueError: import traceback flag = False err_msg = traceback.format_exc() index = string.find(err_msg,'Value') print err_msg[index:] return (flag,startdate,enddate) return (flag,startdate,enddate) The code for test script is as follows: import my_version_datecheck import traceback dt = '12/3/2005' dt1 = '29/2/2003' dt2 = '3/32/5m' t = my_version_datecheck.dateCheck(dt,0) print t t1 = my_version_datecheck.dateCheck(dt1,0) print t1 t2 = my_version_datecheck.dateCheck(dt2,0) print t2 TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061105/3e4d88f3/attachment.htm From dustin at v.igoro.us Sun Nov 5 16:42:54 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Sun, 05 Nov 2006 09:42:54 -0600 Subject: [Tutor] Help me to debug this script .. I tried but .... In-Reply-To: References: Message-ID: <454E067E.7060203@v.igoro.us> Asrarahmed Kadri wrote: > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\project stuff-programs\Scriptdate.py", line 18, in ? > t1 = my_version_datecheck.dateCheck(dt1,0) > File "my_version_datecheck.py", line 38, in dateCheck > import traceback > NameError: global name 'traceback' is not defined This tells you everything you need to know right here. What version of Python are you using? I know traceback existed at least in 2.3. Might be time to consider an upgrade. Dustin From kent37 at tds.net Sun Nov 5 16:42:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Nov 2006 10:42:19 -0500 Subject: [Tutor] Encoding and XML troubles In-Reply-To: <20061104210429.GA31439@sillyrabbi.dyndns.org> References: <20061104210429.GA31439@sillyrabbi.dyndns.org> Message-ID: <454E065B.2010700@tds.net> William O'Higgins Witteman wrote: > I've been struggling with encodings in my XML input to Python programs. > > Here's the situation - my program has no declared encoding, so it > defaults to ASCII. It's written in Unicode, but apparently that isn't > confusing to the parser. Fine by me. I import some XML, probably > encoded in the Windows character set (I don't remember what that's > called now). I can read it for the most part - but it throws exceptions > when it hits accented characters (some data is being input by French > speakers). I am using ElementTree for my XML parsing > > What I'm trying to do is figure out what I need to do to get my program > to not barf when it hits an accented character. I've tried adding an > encoding line as suggested here: > > http://www.python.org/dev/peps/pep-0263/ > > What these do is make the program fail to parse the XML at all. Has > anyone encountered this? Suggestions? Thanks. As Luke says, the encoding of your program has nothing to do with the encoding of the XML or the types of data your program will accept. PEP 263 only affects the encoding of string literals in your program. It sounds like your XML is not well-formed. XML files can have an encoding declaration *in the XML*. If it in not present, the file is assumed to be in UTF-8 encoding. If your XML is in Cp1252 but lacks a correct encoding declaration, it is not valid XML because the Cp1252 characters are not valid UTF-8. Try including the line or as the first line of the XML. (windows-1252 is the official IANA-registered name for Cp1252; I'm not sure which name will actually work correctly.) Kent From gslindstrom at gmail.com Sat Nov 4 14:41:43 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sat, 4 Nov 2006 07:41:43 -0600 Subject: [Tutor] Two Questions...(i) Checking for None (ii) Making Message-ID: > Date: Sat, 4 Nov 2006 10:36:58 +0000 > From: "Asrarahmed Kadri" > Hi Folks, > > I am trying to build a program which takes the following command-line > arguments: > > *-s -D -n -t time>* > > the first argument which is -s (for source) can be replaced by -d (for > destination) or -o (for observer) or -r (for reporter). Now what I want is > to make sure that the user only supplies one of the options from the 4 > alternatives. > > I am using 'optparse' module. It has got a nice feature taht enables you > to > give the option name, along with the variable-name to store the value of > that option. The syntax is as under: if you import sys you can use sys.argv to look at a list of all the command line arguments (including the programs filename). You should be able to determine if you have duplicate flags ('-s','-d',etc). hth --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061104/216e2556/attachment.html From kent37 at tds.net Sun Nov 5 16:53:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Nov 2006 10:53:37 -0500 Subject: [Tutor] Help me to debug this script .. I tried but .... In-Reply-To: <454E067E.7060203@v.igoro.us> References: <454E067E.7060203@v.igoro.us> Message-ID: <454E0901.8060706@tds.net> Dustin J. Mitchell wrote: > Asrarahmed Kadri wrote: >> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", >> line 310, in RunScript >> exec codeObject in __main__.__dict__ >> File "C:\project stuff-programs\Scriptdate.py", line 18, in ? >> t1 = my_version_datecheck.dateCheck(dt1,0) >> File "my_version_datecheck.py", line 38, in dateCheck >> import traceback >> NameError: global name 'traceback' is not defined > > This tells you everything you need to know right here. > > What version of Python are you using? I know traceback existed at least in > 2.3. Might be time to consider an upgrade. If traceback was not a valid module name the import would raise ImportError, not NameError. Something strange is going on here; have you shown us all the code? Kent From dustin at v.igoro.us Sun Nov 5 16:55:59 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Sun, 05 Nov 2006 09:55:59 -0600 Subject: [Tutor] Encoding and XML troubles In-Reply-To: <454E065B.2010700@tds.net> References: <20061104210429.GA31439@sillyrabbi.dyndns.org> <454E065B.2010700@tds.net> Message-ID: <454E098F.6020105@v.igoro.us> For what it's worth, the vast majority of the XML out there (especially if you're parsing RSS feeds, etc.) is written by monkeys and is totally ill-formed. It seems the days of 'it looked OK in my browser' are still here. To find out if it's your app or the XML, you could try running the XML through a validating parser. There are also various tools out there which might be able to parse the XML anyway -- xmllint, I believe, can do this. Dustin (not by *any* stretch an expert on XML *or* Unicode) From dustin at v.igoro.us Sun Nov 5 16:59:36 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Sun, 05 Nov 2006 09:59:36 -0600 Subject: [Tutor] Help me to debug this script .. I tried but .... In-Reply-To: <454E0901.8060706@tds.net> References: <454E067E.7060203@v.igoro.us> <454E0901.8060706@tds.net> Message-ID: <454E0A68.9030908@v.igoro.us> Kent Johnson wrote: > Dustin J. Mitchell wrote: >> Asrarahmed Kadri wrote: >>> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", >>> line 310, in RunScript >>> exec codeObject in __main__.__dict__ >>> File "C:\project stuff-programs\Scriptdate.py", line 18, in ? >>> t1 = my_version_datecheck.dateCheck(dt1,0) >>> File "my_version_datecheck.py", line 38, in dateCheck >>> import traceback >>> NameError: global name 'traceback' is not defined >> This tells you everything you need to know right here. >> >> What version of Python are you using? I know traceback existed at least in >> 2.3. Might be time to consider an upgrade. > > If traceback was not a valid module name the import would raise > ImportError, not NameError. > > Something strange is going on here; have you shown us all the code? Python caches the text of programs, and will show that in later tracebacks. Try restarting your IDE and running the script again, or look on line 38 of my_version_datecheck.py -- I bet it doesn't say "import traceback". Dustin From ajkadri at googlemail.com Sun Nov 5 17:14:09 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sun, 5 Nov 2006 16:14:09 +0000 Subject: [Tutor] Help me to debug this script .. I tried but .... In-Reply-To: <454E0901.8060706@tds.net> References: <454E067E.7060203@v.igoro.us> <454E0901.8060706@tds.net> Message-ID: When I am running the script from the command line, its working fine but when I am trying to run from Pythonwin, its giving me error. Can anyone explain the reason? Regards, Asrarahmed On 11/5/06, Kent Johnson wrote: > > Dustin J. Mitchell wrote: > > Asrarahmed Kadri wrote: > >> > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > >> line 310, in RunScript > >> exec codeObject in __main__.__dict__ > >> File "C:\project stuff-programs\Scriptdate.py", line 18, in ? > >> t1 = my_version_datecheck.dateCheck(dt1,0) > >> File "my_version_datecheck.py", line 38, in dateCheck > >> import traceback > >> NameError: global name 'traceback' is not defined > > > > This tells you everything you need to know right here. > > > > What version of Python are you using? I know traceback existed at least > in > > 2.3. Might be time to consider an upgrade. > > If traceback was not a valid module name the import would raise > ImportError, not NameError. > > Something strange is going on here; have you shown us all the code? > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061105/cd8a4a5c/attachment.html From dyoo at hkn.eecs.berkeley.edu Sun Nov 5 20:30:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 5 Nov 2006 11:30:52 -0800 (PST) Subject: [Tutor] Help me to debug this script .. I tried but .... In-Reply-To: References: <454E067E.7060203@v.igoro.us> <454E0901.8060706@tds.net> Message-ID: On Sun, 5 Nov 2006, Asrarahmed Kadri wrote: > When I am running the script from the command line, its working fine but > when I am trying to run from Pythonwin, its giving me error. > > Can anyone explain the reason? Hi Asrarahmed, Did you see Kent's reply? He mentioned: >> Something strange is going on here; have you shown us all the code? I agree with Kent. I suspect something very funky is going on here, especially since the error message says that you're doing an 'import traceback' within a function called dateCheck(). That's highly unusual: people usually put their imports at the top level. The error message that's coming out has hints of weirdness in it: >> >> File "C:\project stuff-programs\Scriptdate.py", line 18, in ? >> >> t1 = my_version_datecheck.dateCheck(dt1,0) >> >> File "my_version_datecheck.py", line 38, in dateCheck >> >> import traceback >> >> NameError: global name 'traceback' is not defined Why would the code try to do an import on line 38? That's way deep in the middle of your program. Very strange. The most likely thing that's going on, given the information so far, is that the line numbers are wrong, and that 'my_version_datecheck' has been changed while the program is running. We don't have enough information to duplicate your error yet. So please show us your 'my_version_datecheck.py'. Otherwise, we really can't do much else except guess at the problem. From ms at cerenity.org Sun Nov 5 22:29:17 2006 From: ms at cerenity.org (Michael Sparks) Date: Sun, 5 Nov 2006 21:29:17 +0000 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: <454DFD20.8050403@tds.net> References: <454DFD20.8050403@tds.net> Message-ID: <200611052129.17955.ms@cerenity.org> On Sunday 05 November 2006 15:02, Kent Johnson wrote: ... > Regular expressions are an extremely powerful and useful tool that every > programmer should master and then put away and not use when there is an > alternative :-) There's always an alternative to a regular expression, so are you really suggesting *never* use a regex? (seriously though, I doubt you are, but taken in this context, that's how it looks). The most pathological example of regex avoidance I've seen in a while is this: def isPlain(text): plaindict = {'-': True, '.': True, '1': True, '0': True, '3': True, '2': True, '5': True, '4': True, '7': True, '6': True, '9': True, '8': True, 'A': True, 'C': True, 'B': True, 'E': True, 'D': True, 'G': True, 'F': True, 'I': True, 'H': True, 'K': True, 'J': True, 'M': True, 'L': True, 'O': True, 'N': True, 'Q': True, 'P': True, 'S': True, 'R': True, 'U': True, 'T': True, 'W': True, 'V': True, 'Y': True, 'X': True, 'Z': True, '_': True, 'a': True, 'c': True, 'b': True, 'e': True, 'd': True, 'g': True, 'f': True, 'i': True, 'h': True, 'k': True, 'j': True, 'm': True, 'l': True, 'o': True, 'n': True, 'q': True, 'p': True, 's': True, 'r': True, 'u': True, 't': True, 'w': True, 'v': True, 'y': True, 'x': True, 'z': True} for c in text: if plaindict.get(c, False) == False: return False return True (sadly this is from real code - in defence of the person who wrote it, they weren't even *aware* of regexes) That's equivalent to the regular expression: * ^[0-9A-Za-z_.-]*$ Now, which is clearer? If you learn to read & write regular expressions, then the short regular expression is the clearest form. It's also quicker. I'm not someone who advocates coding-by-regex, as happens rather heavily in perl (I like perl about as much as python), but to say "don't use them if there's an alternative" is a little strong. Aside from the argument that "you now have two problems" (which always applies if you think all problems can be hit with the same hammer), solving *everything* with regex is often slower. (since people then do one after another, after another - the most pathological example I've seen applied over 1000 regexes to a piece of text, one after another, and then the author wondered why their code was slow...) JWZ's quote is more aimed at people who think about solving every problem with regexes (and where you end up with 10 line monstrosities in perl with 5 levels of backtracking). Also, it's worth bearing in mind that there's more than one definition of what regex's are (awk, perl, python, and various C libraries all have slightly differing rules and syntax, even if they often share a common base). Rather than say there's one true way, it's worth bearing in mind that regexes are little more than a shorthand for structured parsing, and bearing this in mind, then it's worth recasting JWZ's point as: If your reaction to seeing a problem is "this looks like it can be solved using a regex", you should think to yourself: has someone else already hit this problem and have they come up with a specialised pattern matcher for it already? If not, why not? In this case that *should* have led the poster to the discovery of the specialised parser: time.strptime(date, '%d/%m/%Y') File globs are another good example of a specialised form of pattern matcher. Using a regex when it's appropriate is good. Finding a more appropriate specialised pattern matcher? Even better. Avoiding using regexes in the way I've shown above, because it's an alternative to using a regex? Bad, it's slow and unclear. :-) Michael. From kent37 at tds.net Sun Nov 5 22:46:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Nov 2006 16:46:27 -0500 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: <200611052129.17955.ms@cerenity.org> References: <454DFD20.8050403@tds.net> <200611052129.17955.ms@cerenity.org> Message-ID: <454E5BB3.6030801@tds.net> Michael Sparks wrote: > On Sunday 05 November 2006 15:02, Kent Johnson wrote: > ... >> Regular expressions are an extremely powerful and useful tool that every >> programmer should master and then put away and not use when there is an >> alternative :-) > > > > There's always an alternative to a regular expression, so are you really > suggesting *never* use a regex? (seriously though, I doubt you are, but taken > in this context, that's how it looks). OK, maybe a bit overstated. I use regexes regularly ;) and as I wrote I think every programmer should know how to use them. Kent > > The most pathological example of regex avoidance I've seen in a while > is this: > > def isPlain(text): > plaindict = {'-': True, '.': True, '1': True, '0': True, '3': True, > '2': True, '5': True, '4': True, '7': True, '6': True, '9': True, > '8': True, 'A': True, 'C': True, 'B': True, 'E': True, 'D': True, > 'G': True, 'F': True, 'I': True, 'H': True, 'K': True, 'J': True, > 'M': True, 'L': True, 'O': True, 'N': True, 'Q': True, 'P': True, > 'S': True, 'R': True, 'U': True, 'T': True, 'W': True, 'V': True, > 'Y': True, 'X': True, 'Z': True, '_': True, 'a': True, 'c': True, > 'b': True, 'e': True, 'd': True, 'g': True, 'f': True, 'i': True, > 'h': True, 'k': True, 'j': True, 'm': True, 'l': True, 'o': True, > 'n': True, 'q': True, 'p': True, 's': True, 'r': True, 'u': True, > 't': True, 'w': True, 'v': True, 'y': True, 'x': True, 'z': True} > > for c in text: > if plaindict.get(c, False) == False: > return False > return True > > (sadly this is from real code - in defence of the person > who wrote it, they weren't even *aware* of regexes) > > That's equivalent to the regular expression: > * ^[0-9A-Za-z_.-]*$ > > Now, which is clearer? If you learn to read & write regular expressions, then > the short regular expression is the clearest form. It's also quicker. > > I'm not someone who advocates coding-by-regex, as happens rather heavily in > perl (I like perl about as much as python), but to say "don't use them if > there's an alternative" is a little strong. Aside from the argument that "you > now have two problems" (which always applies if you think all problems can be > hit with the same hammer), solving *everything* with regex is often slower. > (since people then do one after another, after another - the most > pathological example I've seen applied over 1000 regexes to a piece > of text, one after another, and then the author wondered why their > code was slow...) > > JWZ's quote is more aimed at people who think about solving every problem with > regexes (and where you end up with 10 line monstrosities in perl with 5 > levels of backtracking). > > Also, it's worth bearing in mind that there's more than one definition of what > regex's are (awk, perl, python, and various C libraries all have slightly > differing rules and syntax, even if they often share a common base). Rather > than say there's one true way, it's worth bearing in mind that regexes are > little more than a shorthand for structured parsing, and bearing this in > mind, then it's worth recasting JWZ's point as: > > If your reaction to seeing a problem is "this looks like it can be solved > using a regex", you should think to yourself: has someone else already hit > this problem and have they come up with a specialised pattern matcher for it > already? If not, why not? > > In this case that *should* have led the poster to the discovery of the > specialised parser: > time.strptime(date, '%d/%m/%Y') > > File globs are another good example of a specialised form of pattern matcher. > > Using a regex when it's appropriate is good. Finding a more appropriate > specialised pattern matcher? Even better. Avoiding using regexes in the way > I've shown above, because it's an alternative to using a regex? Bad, it's > slow and unclear. > > :-) > > > Michael. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From sisson.j at gmail.com Sun Nov 5 17:01:42 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sun, 05 Nov 2006 10:01:42 -0600 Subject: [Tutor] GUI with Designer In-Reply-To: References: <44290fe50611031229o52e03fb8l1b7244e421db21c8@mail.gmail.com> <4fae7dfa0611031356q49cad025m374794f9fde20a2b@mail.gmail.com> <7.0.1.0.2.20061103154522.01ddf0f8@rcblue.com> Message-ID: <454E0AE6.2030600@gmail.com> Wow... SPE is in the Gentoo repository as well. I've been looking for something to replace Eric, so thanks for the tip, Chris! I'll check it out. Jonathon Chris Hengge wrote: > Well, I use SPE which comes with wxGlade and XRC. For the small amount > of gui I've done with python I think SPE offers the best IDE coder > experience (coming from a VS world). The tools make sense to me. > > wxGlade is a GUI designer written in Python with the popular GUI toolkit > wxPython , that helps you create > wxWidgets/wxPython user interfaces. At the moment it can generate > Python, C++, Perl and XRC (wxWidgets' XML resources) code. > > XRC(wxWidgets' XML resources) is nice because it allows you to abstract > your interface design (think of any program that uses XML to format skins). > > Overall, I think everyone using python should give SPE a try, even > without gui programming its a great tool for writing code. It's free, > and written in python using wxPython.. Stani (the Dev) is a great person > for helping out with questions on using his package, he puts out regular > updates and fixes. He's got some help from a few other people so its > packaged in .exe, .rpm and standalone .zip formats. It's also on the > standard repo's for Ubuntu. > > If you like it, be kind and toss the guy a few bucks for his efforts. If > you do, you will get your name mentioned on the SPE news page and get a > nice copy of his user manual (pdf). > > If you want to know more about SPE, check out: > http://www.serpia.org/spe > or video demonstations at: > http://showmedo.com/videos/series?name=PythonDevelopmentWithSPE > > > On 11/3/06, *Dick Moores* > wrote: > > At 02:10 PM 11/3/2006, Chris Hengge wrote: >> I vouch for the SPE with wxGlade and XRC! (packaged together with IDE) > > I'd be very interested in hearing why you suggest that combination. > > Dick Moores > > >> On 11/3/06, *Carlos Daniel Ruvalcaba Valenzuela* < >> clsdaniel at gmail.com > wrote: >> >> wxPython is good for cross-platform stuff and has a few gui >> designers >> (Boa Constructor and others comes to mind), I don't know much >> about >> PyQT state in this, but PyGtk + Glade (Gui Designer) is a very >> good >> combo. >> >> Is about choise, I suggest you to do some simple tests with >> everything >> until you find something to be confortable with. >> >> * PyGtk + Glade >> * Boa Contructor >> * SPE + wxPython >> >> On 11/3/06, Todd Dahl > > wrote: >> > I am wanting to get into some GUI coding with Python and have >> heard about >> > PyQT and wxPython. Now I am definately not looking for some >> type of holy war >> > but can anyone give me a good reason to pick one over the other. >> > >> > Also I would like to have a designer with it or a seperate >> designer that >> > could be used with either. I plan on coding in Windows XP. >> > >> > Thanks, >> > >> > -Todd >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > >> > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From broek at cc.umanitoba.ca Sun Nov 5 09:50:36 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 05 Nov 2006 02:50:36 -0600 Subject: [Tutor] shebang problem In-Reply-To: References: <454D2C17.5060705@cc.umanitoba.ca> Message-ID: <454DA5DC.4010405@cc.umanitoba.ca> Alan Gauld said unto the world upon 11/04/2006 06:47 PM: > brian at gottlob:~/test$ ls -la shebangtest.py > -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py > > so the file is called shebangtest.py... > >> brian at gottlob:~/test$ shebangtest >> bash: shebangtest: command not found > > but you try to run shebangtest... > > bash can't find the file. you didn't put the .py on the end Well, shebangtest.py also didn't work as evidenced by one of the lines you snipped. > Also you may not have . in your path. For security reasons it isn't > there by default. > > Try > > brian at gottlob:~/test$ ./shebangtest.py And that would be it. It didn't occur to me to try ./shebangtest.py in lieu of the bare shebangtest.py. My command-line instinct were installed back in the days of using DOS on an XT. DOS (at least the version I used) first checked the cwd and only then searched the path. The security implications that Alan and Rick pointed to make the POSIX/bash behaviour make perfect sense on reflection, though. Thanks to all who replied, both on and off list, Brian vdB From alan.gauld at btinternet.com Mon Nov 6 02:08:53 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 01:08:53 -0000 Subject: [Tutor] Amazing power of Regular Expressions... References: <454DFD20.8050403@tds.net> <200611052129.17955.ms@cerenity.org> Message-ID: "Michael Sparks" wrote > The most pathological example of regex avoidance I've seen in a > while > is this: > > def isPlain(text): > plaindict = {'-': True, '.': True, '1': True, '0': True, '3': > True, > '2': True, '5': True, '4': True, '7': True, '6': True, '9': > True, > '8': True, 'A': True, 'C': True, 'B': True, 'E': True, 'D': > True, > 'G': True, 'F': True, 'I': True, 'H': True, 'K': True, 'J': > True, > 'M': True, 'L': True, 'O': True, 'N': True, 'Q': True, 'P': > True, > 'S': True, 'R': True, 'U': True, 'T': True, 'W': True, 'V': > True, > 'Y': True, 'X': True, 'Z': True, '_': True, 'a': True, 'c': > True, > 'b': True, 'e': True, 'd': True, 'g': True, 'f': True, 'i': > True, > 'h': True, 'k': True, 'j': True, 'm': True, 'l': True, 'o': > True, > 'n': True, 'q': True, 'p': True, 's': True, 'r': True, 'u': > True, > 't': True, 'w': True, 'v': True, 'y': True, 'x': True, 'z': > True} > > for c in text: > if plaindict.get(c, False) == False: > return False > return True > > (sadly this is from real code - in defence of the person > who wrote it, they weren't even *aware* of regexes) > > That's equivalent to the regular expression: > * ^[0-9A-Za-z_.-]*$ While using a dictionary is probably overkill, so is a regex. A simple string holding all characters and an 'in' test would probably be both easier to read and faster. Which kind of illustrates the point of the thread I think! :-) > Now, which is clearer? If you learn to read & write regular > expressions, then > the short regular expression is the clearest form. It's also > quicker. Whether its quicker will depend on several factors including the implementation of the regex library as well as the length of the string. If its a single char I'd expect the dictionary lookup to be faster than a regex parse or the string inclusion test... In fact this is how the C standard library usually implements functions like toupper() and tolower() etc, and for speed reasons. > to say "don't use them if there's an alternative" is a little > strong. > Aside from the argument that "you now have two problems" > (which always applies if you think all problems can be hit with > the same hammer), solving *everything* with regex is often slower. regex can be faster than a sequential string search. It depends on the problem. The thing that we are all trying to say here (I think) is that regex are powerful tools but dangerously complex. Its nearly always safer and easier to use alternatives where they exist, but when used intelligently they can solve difficult problems very elegantly. > JWZ's quote is more aimed at people who think about solving > every problem with regexes (and where you end up with 10 line > monstrosities in perl with 5 levels of backtracking). Agreed and thats what the message of the thread is about. Use them ewhen they are the right solution, but look for altrernatives first. > Also, it's worth bearing in mind that there's more than one > definition of what > regex's are To be picky, there is only one definition of what regexd are, but there are many grammars or dialects. > If your reaction to seeing a problem is "this looks like it can be > solved > using a regex", you should think to yourself: has someone else > already hit > this problem and have they come up with a specialised pattern > matcher for it > already? If not, why not? Absolutely agree with this. > :-) Likewise :-) Alan g. From noufal at gmail.com Mon Nov 6 09:34:54 2006 From: noufal at gmail.com (Noufal Ibrahim) Date: Mon, 6 Nov 2006 08:34:54 +0000 (UTC) Subject: [Tutor] Wrong module name and line number in logging package. References: <454D9E02.4010809@airtelbroadband.in> Message-ID: Noufal Ibrahim airtelbroadband.in> writes: > > Greetings everyone, > I'm using the python standard logging package for a personal project > of mine and have initialised it like so. > > logger = logging.getLogger("pydagogue") > handler = logging.StreamHandler() > handler.setFormatter(logging.Formatter("[%(levelname)s]%(pathname)s:%(lineno)d > %(message)s")) > logger.addHandler(handler) > logger.setLevel(logging.DEBUG) I think there's a bug in the module. I'm running two Ubuntu machines. One with the latest release and one with an older one. The same code runs different on both machines. On the latest one, I get wrong module names and line numbers. On the older one, it works fine. Can someone else please try this out and check if it's a problem on my end or something genuinely wrong? Thanks. From ms at cerenity.org Mon Nov 6 11:32:32 2006 From: ms at cerenity.org (Michael Sparks) Date: Mon, 6 Nov 2006 10:32:32 +0000 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: References: <200611052129.17955.ms@cerenity.org> Message-ID: <200611061032.33142.ms@cerenity.org> On Monday 06 November 2006 01:08, Alan Gauld wrote: > While using a dictionary is probably overkill, so is a regex. No, in this case it's absolutely the right choice. > A simple string holding all characters and an 'in' test would probably > be both easier to read and faster. I'm stunned you think this. It's precisely this sort of naivete that baffles me with regard to regexes. > Which kind of illustrates the point of the thread I think! :-) Actually, no, it doesn't. A regex compiles to a jump table, and executes as a statemachine. (That or the implementation in the library is crap, and I don't believe for a second python would be that dumb) Given you can compile the regex and use it over and over again (as was the context the example code (isplain) was executed in) using a regex is absolutely the best way. I'd be extremely surprised if you could get your suggested approach faster. I also doubt it would actually be clearer, and in this case, that's MUCH more important. (heck, that's the reason regexes are useful - compact clear representations of a lexical structure that you want to check a string matches rather than obfuscated by the language doing the checking) * ^[0-9A-Za-z_.-]*$ Is a very simple pattern, and as a result an extremely simple specification. If any developer has a problem with that sort of pattern, they really need to go away and learn regexes, since they're missing important tools. (which shouldn't be over used). I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go away and relearn regexes. Michael. From ebrosh at nana.co.il Mon Nov 6 05:26:46 2006 From: ebrosh at nana.co.il (Eli Brosh) Date: Mon, 6 Nov 2006 06:26:46 +0200 Subject: [Tutor] executing script from script Message-ID: <957526FB6E347743AAB42B212AB54FDA95B9A9@NANAMAILBACK1.nanamail.co.il> Hello. I wish that my Python program will not be stored on a single file. how can I call one python script from another ? Thanks Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061106/70238e65/attachment.html From ebrosh at nana.co.il Mon Nov 6 05:23:52 2006 From: ebrosh at nana.co.il (Eli Brosh) Date: Mon, 6 Nov 2006 06:23:52 +0200 Subject: [Tutor] editing Path Message-ID: <957526FB6E347743AAB42B212AB54FDA95B9A8@NANAMAILBACK1.nanamail.co.il> Hello. I am beginning to use python on windows. how can I add a path to Python search-list where I can store my python scripts ? On IDLE the command browse path lets me to see the existing path but not to edit it. thanks Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061106/c79439a1/attachment.htm From samrobertsmith at gmail.com Mon Nov 6 12:37:04 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 6 Nov 2006 03:37:04 -0800 Subject: [Tutor] numpy and python Message-ID: <1d987df30611060337r3e12f064j6ff19b4d1c4486d6@mail.gmail.com> I use Python 2.4 IDLE to open a py code which import numeric. I have installed both scipy and numpy into my c:\python24. However, it was still reported as: from Numeric import * ImportError: No module named Numeric I got confused... From ajkadri at googlemail.com Mon Nov 6 13:25:15 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 6 Nov 2006 12:25:15 +0000 Subject: [Tutor] editing Path In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95B9A8@NANAMAILBACK1.nanamail.co.il> References: <957526FB6E347743AAB42B212AB54FDA95B9A8@NANAMAILBACK1.nanamail.co.il> Message-ID: Hi Eli, You really dont have to edit the search path, because if all the files lie in the same-directory as the top-level file, then Python automatically includes that directory in its search path. HTH, Regards, Asrarahmed On 11/6/06, Eli Brosh wrote: > > Hello. > I am beginning to use python on windows. > how can I add a path to Python search-list where I can store my python > scripts ? > On IDLE the command *browse path* lets me to see the existing path but not > to edit it. > > thanks > Eli > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061106/8f8ae1f6/attachment.htm From chris.arndt at web.de Mon Nov 6 13:25:26 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Mon, 06 Nov 2006 13:25:26 +0100 Subject: [Tutor] editing Path In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95B9A8@NANAMAILBACK1.nanamail.co.il> References: <957526FB6E347743AAB42B212AB54FDA95B9A8@NANAMAILBACK1.nanamail.co.il> Message-ID: <454F29B6.2050809@web.de> Eli Brosh schrieb: > Hello. > I am beginning to use python on windows. > how can I add a path to Python search-list where I can store my python > scripts ? > On IDLE the command *browse path* lets me to see the existing path but > not to edit it. Hello, you may be confusing* two different concepts here: 1) The system shell search path for executables, i.e. the PATH environment variable. This is used by the shell (i.e. cmd.exe aka the command box on Windows) to find executable programs when you type in only the name of a program without the full path. You can change the PATH environment variable in the 'System' dialog in the Windows control panel (somewhere on the "Advanced" tab). 2) The Python search path, which is used by the Python interpreter to locate modules that should be imported. This has a default value, which is compiled into the Python executable and can be queried and changed through the sys.path variable at runtime, e.g. $ python Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.path ['', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages', '/usr/lib/site-python'] This example shows the content of sys.path on my Linux system (I deleted a lot of additional entries for the sake of brevity), on a Windows system this will of course be different and will point to the library directory of your Python installation, usually in 'C:/Python24/Lib'. To change the path, just append/prepend entries to sys.path, which is a normal Python list, e.g. >>> sys.path.append('/home/joe/myproject/lib') >>> sys.path.insert(0, '/home/joe/myotherproject/lib') Changes to sys.path last only until your program exits. To make permanent changes to your Python path, you can set the PYTHONPATH environment variable. The contents of this variable will be prepended to the default sys.path. * At least your mentioning of "python scripts" makes me think so. The Python path only concerns Python *modules*, Python scripts are like any other executable, batch file, shell script etc. and need to be place in a directory in your PATH when you want to call them without a full path name. HTH, Chris From kent37 at tds.net Mon Nov 6 13:53:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Nov 2006 07:53:50 -0500 Subject: [Tutor] executing script from script In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95B9A9@NANAMAILBACK1.nanamail.co.il> References: <957526FB6E347743AAB42B212AB54FDA95B9A9@NANAMAILBACK1.nanamail.co.il> Message-ID: <454F305E.3000100@tds.net> Eli Brosh wrote: > Hello. > I wish that my Python program will not be stored on a single file. > how can I call one python script from another ? Put part of the script in a module that you import from another module. Read more here: http://docs.python.org/tut/node8.html Kent From ajkadri at googlemail.com Mon Nov 6 14:52:19 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 6 Nov 2006 13:52:19 +0000 Subject: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate Message-ID: Hi Folks, I have written a function that takes a date and an integer representing the number of days. Please test it, comment on the logic . Here is the code: """ The function takes two arguments, date and number of days. It checks for the right format and if the format is okay, it calculates the end date. """ import string import datetime import traceback def dateCheck(date1,num_days): flag = True startdate = None enddate = None if num_days < 0 or num_days > 31: flag = False print "The argument for -n has to be between 0 and 31" return (flag,startdate,enddate) else: date_lst = string.split(date1,"/") ln = len(date_lst) if ln != 3 : flag = False print "The argument for -D option has to be in the format: dd/mm/yyyy" return (flag,startdate,enddate) else: date_lst.reverse() print date_lst try: if int(date_lst[0]) < 2000: flag = False print "The year cannot be earlier than 2000 and it should be in the format 'yyyy'." return (flag,startdate,enddate) except ValueError: flag = False err_msg = traceback.format_exc() index = string.find(err_msg,'Value') print err_msg[index:] return (flag,startdate,enddate) try: startdate = datetime.date (int(date_lst[0]),int(date_lst[1]),int(date_lst[2])) enddate = startdate + datetime.timedelta(days=num_days) print startdate, enddate except ValueError: flag = False startdate = None enddate = None err_msg = traceback.format_exc() index = string.find(err_msg,'Value') print err_msg[index:] return (flag,startdate,enddate) if enddate > datetime.date.today(): enddate = datetime.date.today() if startdate > datetime.date.today(): flag = False startdate = None enddate = None print "The -D option should have a date not later than today's date" return (flag,startdate,enddate) TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061106/f270156b/attachment.html From carloslara at web.de Mon Nov 6 16:34:20 2006 From: carloslara at web.de (Carlos) Date: Mon, 06 Nov 2006 16:34:20 +0100 Subject: [Tutor] First real script Message-ID: <454F55FC.60309@web.de> Hello to all, This is my first script, I mean the first that I'm trying to do on my own. Its a very simple Cellular Automata thing, the idea is that the initial list A_List is rewritten based on some rules, in this case Wolfram's rule 30. You can modify the list length and its initial state, you can also set the number of iterations. What I would like is to see how it can be improved. The basic functionality is done, I just want to listen some advise from experts like you : ) For example how can I improve the way in which the rules are written? Would you use the same method that I have chosen? And what about the if and else that are right after the two loops? they are there because if not when the loop gets to the last number an exception arises. Thanks a lot Carlos Here is the code: Note: Right now maya is not needed to run the code. #My first try at Cellular Automata #A very basic script that lets you play with Wolfram's rule 30 #if you wish to see the results in maya, you will need CGKit and Maya #from maya.api import * #from maya.mel import * import time #This is the initial state. You can put as many integers as you wish A_List = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] A_Len = len(A_List) print 'A_List: ',A_List print 'A_Len: ', A_Len B_List = [] S = A_Len print S #This is the number of iterations. for r in range (50): for i in range (S): #if i < S-1: a = A_List[i-1] b = A_List[i] c = A_List[i+1] else: a = A_List[i-1] b = A_List[i] c = A_List[0] if a == 1 and b == 1 and c == 1: X = 0 elif a == 1 and b == 1 and c == 0: X = 0 elif a == 1 and b == 0 and c == 1: X = 0 elif a == 1 and b == 0 and c == 0: X = 1 elif a == 0 and b == 1 and c == 1: X = 1 elif a == 0 and b == 1 and c == 0: X = 1 elif a == 0 and b == 0 and c == 1: X = 1 elif a == 0 and b == 0 and c == 0: X = 0 #print i,a,b,c,X #if X == 1: #print r,i,X #polyCube() #move(r=(i,r,0)) B_List.append(X) print 'B_List: ',B_List A_List = B_List B_List = [] From dyoo at hkn.eecs.berkeley.edu Mon Nov 6 17:05:15 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 08:05:15 -0800 (PST) Subject: [Tutor] numpy and python In-Reply-To: <1d987df30611060337r3e12f064j6ff19b4d1c4486d6@mail.gmail.com> References: <1d987df30611060337r3e12f064j6ff19b4d1c4486d6@mail.gmail.com> Message-ID: On Mon, 6 Nov 2006, linda.s wrote: > I use Python 2.4 IDLE to open a py code which import numeric. > I have installed both scipy and numpy into my c:\python24. However, it > was still reported as: Hi Linda, We need more details. What version of scipy and numpy did you install? Where did you get them them from? This detail matters particularly for numpy, which has several different incarnations (Numeric, numarray, NumPy), and they all do similar-but-slightly-different things. Did you install the one from: http://numpy.scipy.org/ Also, what steps did you do to install those third-party modules? > from Numeric import * > ImportError: No module named Numeric > I got confused... If you're using NumPy, then the correct package name for it is 'numpy', not 'Numeric'. from numpy import * Good luck! From dyoo at hkn.eecs.berkeley.edu Mon Nov 6 17:09:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 08:09:29 -0800 (PST) Subject: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate In-Reply-To: References: Message-ID: On Mon, 6 Nov 2006, Asrarahmed Kadri wrote: > I have written a function that takes a date and an integer representing > the number of days. > > Please test it, comment on the logic . Hi Asrarahmed, You should be able to write your own tests too. You might want to look at: http://www.diveintopython.org/unit_testing/index.html for an example of how to write unit tests; the author there goes through an example with a Roman Numeral program written with unit tests. From dyoo at hkn.eecs.berkeley.edu Mon Nov 6 17:20:42 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 08:20:42 -0800 (PST) Subject: [Tutor] First real script In-Reply-To: <454F55FC.60309@web.de> References: <454F55FC.60309@web.de> Message-ID: On Mon, 6 Nov 2006, Carlos wrote: > This is my first script, I mean the first that I'm trying to do on my > own. Its a very simple Cellular Automata thing, the idea is that the > initial list A_List is rewritten based on some rules, in this case > Wolfram's rule 30. You can modify the list length and its initial state, > you can also set the number of iterations. Hi Carlos, Cool. I did something like this a while ago too! http://mail.python.org/pipermail/tutor/2002-September/017256.html Looking at your code, the only suggestion I could make is to encode the rules into some kind of lookup structure. That is, the block: > if a == 1 and b == 1 and c == 1: > X = 0 > elif a == 1 and b == 1 and c == 0: > X = 0 > elif a == 1 and b == 0 and c == 1: > X = 0 > elif a == 1 and b == 0 and c == 0: > X = 1 > elif a == 0 and b == 1 and c == 1: > X = 1 > elif a == 0 and b == 1 and c == 0: > X = 1 > elif a == 0 and b == 0 and c == 1: > X = 1 > elif a == 0 and b == 0 and c == 0: > X = 0 could be tweaked to be more compact. Conceptually, it takes in three values (X, Y, Z), and returns a result in X. If we look at it in a different light, that's a key->value lookup, where the "key" is going to be a 3-tuple. So you can encode the guts of rule 30 with a dictionary: rule_30 = { (1, 1, 1) : 0, (1, 1, 0) : 0, (1, 0, 1) : 0, (1, 0, 0) : 1, (0, 1, 1) : 1, (0, 1, 0) : 1, (0, 0, 1) : 1, (0, 0, 0) : 0, } After we have this, the assignment to X looks much more simple: X = rule_30[x, y, z] Good luck! From kent37 at tds.net Mon Nov 6 17:22:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Nov 2006 11:22:33 -0500 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: References: <454DFD20.8050403@tds.net> <200611052129.17955.ms@cerenity.org> Message-ID: <454F6149.1010003@tds.net> Alan Gauld wrote: > "Michael Sparks" wrote >> >> That's equivalent to the regular expression: >> * ^[0-9A-Za-z_.-]*$ > > While using a dictionary is probably overkill, so is a regex. > A simple string holding all characters and an 'in' test would probably > be both easier to read and faster. Which kind of illustrates the > point of the thread I think! :-) > >> Now, which is clearer? If you learn to read & write regular >> expressions, then >> the short regular expression is the clearest form. It's also >> quicker. > > Whether its quicker will depend on several factors including the > implementation of the regex library as well as the length of the > string. > If its a single char I'd expect the dictionary lookup to be faster > than > a regex parse or the string inclusion test... In fact this is how the > C standard library usually implements functions like toupper() > and tolower() etc, and for speed reasons. It's been a long time since I looked at the source for a C standard library but I remember these functions being implemented as direct table lookup - a static char* indexed by a character value - not dictionary lookup. If anyone really cares which Python implementation is faster, the timeit module is your friend. Assertions like "would probably be faster" or "it's also quicker" don't hold much weight. In Python, if you want to know what is faster, you must test. Kent, who doesn't have enough time or interest at the present to try timing it himself... From alan.gauld at btinternet.com Mon Nov 6 18:29:11 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 17:29:11 -0000 Subject: [Tutor] executing script from script References: <957526FB6E347743AAB42B212AB54FDA95B9A9@NANAMAILBACK1.nanamail.co.il> Message-ID: "Eli Brosh" wrote > I wish that my Python program will not be stored on a single file. > how can I call one python script from another ? As Kent says normally you don't call one script from another, instead you write a set of functions (or classes) that you put in one or more modules. You then import those modules into your top level script (the one you actually execute) and call the functions in the modules. You can read more about this in my Modules and Functions topic in my tutorial. If you really do want to call a Python script you do it the same way as you would call any other executable program from inside a script: using the subprocess module. This is described in my Operating System topic, in the "Other mechanisms for external program access" subsection. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Nov 6 18:23:29 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 17:23:29 -0000 Subject: [Tutor] editing Path References: <957526FB6E347743AAB42B212AB54FDA95B9A8@NANAMAILBACK1.nanamail.co.il> <454F29B6.2050809@web.de> Message-ID: > Eli Brosh schrieb: >> Hello. >> I am beginning to use python on windows. >> how can I add a path to Python search-list where I can store my >> python >> scripts ? As has been said there are two aspects. If you want your scripts to execute as programs you need to modify the PATH environment variable MyComputer->Properties->Advanced->Env Variables But note that this only works inside a DOS box, if you are using the Start-Run dialog then I think you need to modify the registry someplace (I can't recall where) But normally you just double click the icon in Windows Explorer... OTOH if you want to import your scripts as modules into other scripts then you need to set the PYTHONPATH environment variable. If you want to do both you need to modify both variables. Alan G. From alan.gauld at btinternet.com Mon Nov 6 18:59:52 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 17:59:52 -0000 Subject: [Tutor] Please help to debug this function.. it takes a date andnum. of days and returns startdate and enddate References: Message-ID: "Asrarahmed Kadri" wrote > Please test it, comment on the logic . I haven't tested it but here are some comments: > import string > import datetime > import traceback > > def dateCheck(date1,num_days): > flag = True > startdate = None > enddate = None > > if num_days < 0 or num_days > 31: > flag = False > print "The argument for -n has to be between 0 and 31" > return (flag,startdate,enddate) > > else: You don't need the else since the if block returns. Thus you only reach the followiong code if the test is false. This reduces the anumber of levels of indenting by one which improves readability and thus maintenance. > date_lst = string.split(date1,"/") better to use the string methods. ie date1.split('/') > ln = len(date_lst) > if ln != 3 : you could have combined those lines into one since you never use 'ln' except in the test. if len(date1.split('/') != 3: > flag = False > print "The argument for -D option has to be in the > format: > dd/mm/yyyy" > return (flag,startdate,enddate) > else: Same as above, the else is just adding levels of indentation. > date_lst.reverse() > print date_lst > try: > if int(date_lst[0]) < 2000: > flag = False > print "The year cannot be earlier than 2000 and > it > should be in the format 'yyyy'." > return (flag,startdate,enddate) > except ValueError: > flag = False > err_msg = traceback.format_exc() > index = string.find(err_msg,'Value') Again use the string method: index = err_msg.find('Value') > print err_msg[index:] > return (flag,startdate,enddate) > > try: > startdate = datetime.date > (int(date_lst[0]),int(date_lst[1]),int(date_lst[2])) > enddate = startdate + > datetime.timedelta(days=num_days) > print startdate, enddate > > except ValueError: > > flag = False > startdate = None > enddate = None > err_msg = traceback.format_exc() > index = string.find(err_msg,'Value') > print err_msg[index:] > return (flag,startdate,enddate) Since this block is essentially identical to the except block above you could package them both as a function which would shorten the code a little. > if enddate > datetime.date.today(): > enddate = datetime.date.today() > if startdate > datetime.date.today(): > flag = False > startdate = None > enddate = None > print "The -D option should have a date not later > than > today's date" Since this is a function and not part of the user interface there shouldn't really be any knowledge of the -D option in this code. What if you want to call it from another module that uses different options? It would be better to raise a ValueError which can be caught by the external program: raise ValueEerror ("startdate later than today") > return (flag,startdate,enddate) > HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tim at johnsons-web.com Mon Nov 6 18:16:01 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 6 Nov 2006 08:16:01 -0900 Subject: [Tutor] is gotchas? Message-ID: <20061106171601.GB1768@johnsons-web.com> I've been using python is 1.5* but haven't used `is` that much. 1)where do `is` and `==` yield the same results? 2)where do they not yield the same results? 3)is there a special method for `is'. 4)Pointers to docs are welcome. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at btinternet.com Mon Nov 6 19:11:04 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 18:11:04 -0000 Subject: [Tutor] First real script References: <454F55FC.60309@web.de> Message-ID: "Carlos" wrote > Here is the code: > Note: Right now maya is not needed to run the code. > > import time > > #This is the initial state. You can put as many integers as you wish > A_List = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] > > A_Len = len(A_List) > print 'A_List: ',A_List > print 'A_Len: ', A_Len > B_List = [] > S = A_Len > print S Not sure why you do this? Why not just use A_Len? > #This is the number of iterations. > for r in range (50): > for i in range (S): > #if i < S-1: > a = A_List[i-1] > b = A_List[i] > c = A_List[i+1] > else: > a = A_List[i-1] > b = A_List[i] > c = A_List[0] > > if a == 1 and b == 1 and c == 1: > X = 0 > elif a == 1 and b == 1 and c == 0: > X = 0 > elif a == 1 and b == 0 and c == 1: > X = 0 I would rewrite these tests to use tuples: if (a,b,c) == (1,1,1): X = 0 elif (a,b,c) == (1,1,0): X = 0 elif (a,b,c) == (1,0,1): X = 0 etc... You could also use a dictionary to make it sligtly more concise: tests = {(1,1,1): 0, (1,1,0): 0,....(1,0,0): 1....} then X = tests[(a,b,c)] I find either option easier to read and maintain than the boolean expressions. > B_List.append(X) > print 'B_List: ',B_List > A_List = B_List > B_List = [] HTH, Alan G. From kent37 at tds.net Mon Nov 6 20:19:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Nov 2006 14:19:40 -0500 Subject: [Tutor] is gotchas? In-Reply-To: <20061106171601.GB1768@johnsons-web.com> References: <20061106171601.GB1768@johnsons-web.com> Message-ID: <454F8ACC.9000202@tds.net> Tim Johnson wrote: > I've been using python is 1.5* but haven't used `is` that much. > > 1)where do `is` and `==` yield the same results? > > 2)where do they not yield the same results? is tests for object identity - 'a is b' is true if a is the same object as b. There is no special method, no specialization for different data types, just 'is it the same thing?' == tests for equality of value. It's exact meaning depends on the types of objects your are comparing. It can be specialized by defining a special method. a is b generally implies a == b because if a is b then a==b is the same as a==a which is true for pretty much anything - it would be a very strange type for which a == a is not true. Maybe NaN (Not a Number) compares false to itself, I'm not sure, I don't know how to create NaN on Windows. But really the meaning of == is defined by the underlying type so in your own classes you can make it do anything you want. a==b does not imply a is b - it is quite reasonable for two different things to have the same value: In [9]: a=[1,2] In [10]: b=[1,2] In [11]: a is b Out[11]: False In [12]: a==b Out[12]: True In [13]: a='abc**def' In [14]: b='abc' + '**def' In [15]: a is b Out[15]: False In [16]: a==b Out[16]: True > > 3)is there a special method for `is'. No. Kent > > 4)Pointers to docs are welcome. > > thanks > tim > From dyoo at hkn.eecs.berkeley.edu Mon Nov 6 20:22:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 11:22:29 -0800 (PST) Subject: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate (fwd) Message-ID: [Forwarding to Tutor; busy at the moment] ---------- Forwarded message ---------- Date: Mon, 6 Nov 2006 18:41:54 +0000 From: Asrarahmed Kadri To: Danny Yoo Subject: Re: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate Hi Danny, Can you please test it !!! Also I would like to know if it can be coded in a better way... TIA. Regards, Asrarahmed On 11/6/06, Danny Yoo wrote: > > > > On Mon, 6 Nov 2006, Asrarahmed Kadri wrote: > >> I have written a function that takes a date and an integer representing >> the number of days. >> >> Please test it, comment on the logic . > > > Hi Asrarahmed, > > You should be able to write your own tests too. You might want to look > at: > > http://www.diveintopython.org/unit_testing/index.html > > for an example of how to write unit tests; the author there goes through > an example with a Roman Numeral program written with unit tests. > -- To HIM you shall return. From alan.gauld at btinternet.com Mon Nov 6 19:40:37 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 18:40:37 -0000 Subject: [Tutor] Amazing power of Regular Expressions... References: <200611052129.17955.ms@cerenity.org> <200611061032.33142.ms@cerenity.org> Message-ID: "Michael Sparks" wrote > A regex compiles to a jump table, and executes as a statemachine. Sometimes, but it depends on the implementation. If someone uses a C++ compiler that uses the standard library implememation of regex (like say the Microsoft Visual C++ version up till V6 did) then they will not get that and they will have slow regex. The GNU compiler OTOH does provide fast regex. But it depends entirely on the implementation of the regex library. And can even depend on the compiler chosen in the case above since many dynamic languages use the underlying library for their regex implementation. > or the implementation in the library is crap, and I don't believe > for a > second python would be that dumb) Maybe not, but C/C++ can be! > Given you can compile the regex and use it over and over again (as > was > the context the example code (isplain) was executed in) using a > regex > is absolutely the best way. Fine if the user compiles it, but for one-off use its quite common not to compile regex. For one-off the compilation can be slower than the one-off execution. > I'd be extremely surprised if you could get your suggested approach > faster. Like I said it depends on an awful lot of factors. One reason perl is popular is that it has the worlds best regex implementation, it regularly beat compiled C programs when it first came out. Nowadays the regex libraries are improving, but the VB one, for example, is still pretty slow in my experience, even in VB.Net > important. (heck, that's the reason regexes are useful - compact > clear > representations of a lexical structure that you want to check a > string > matches rather than obfuscated by the language doing the checking) I've never heard anyone claim that regex's were clear before :-) > * ^[0-9A-Za-z_.-]*$ > > Is a very simple pattern, and as a result an extremely simple > specification. That is quite simple for a regex, but I'd still argue that for beginners (which is what this list is about) thats still quite an eyeful. > If any developer has a problem with that sort of pattern, they > really need to > go away and learn regexes, since they're missing important tools. > (which > shouldn't be over used). I agree totally. > I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, > go away > and relearn regexes. I think its complex for an novice amateur programmer. And to Kent's point re the C library, he is quite correct, toupper() etc use a lookup table not a dictionary, my mistake. But the difference between hashing and indexing is still less than a regex pattern match for a single character. And the point of timing is also valid, but I too can't be bothered to try... Alan G. From Barry.Carroll at psc.com Mon Nov 6 20:48:42 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 6 Nov 2006 11:48:42 -0800 Subject: [Tutor] (OT) Flame wars (was: Amazing power of Regular Expressions...) Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Greetings, all: > -----Original Message----- > Date: Mon, 6 Nov 2006 10:32:32 +0000 > From: Michael Sparks > Subject: Re: [Tutor] Amazing power of Regular Expressions... > To: tutor at python.org > Message-ID: <200611061032.33142.ms at cerenity.org> > Content-Type: text/plain; charset="iso-8859-1" > > On Monday 06 November 2006 01:08, Alan Gauld wrote: > > While using a dictionary is probably overkill, so is a rage. > > No, in this case it's absolutely the right choice. > > > A simple string holding all characters and an 'in' test would probably > > be both easier to read and faster. > > I'm stunned you think this. It's precisely this sort of naivete that > baffles > me with regard to regales. > > > Which kind of illustrates the point of the thread I think! :-) > > Actually, no, it doesn't. > <> > > I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go > away > and relearn regales. > > Michael. > With the final sentence above, this thread has ceased to be an intellectual discussion and become a religious argument. Until then, I was enjoying an informative discussion by knowledgeable people on a topic of considerable interest. Now I'm upset by the implications of the statement and embarrassed on behalf of the writer. When a person his so convinced of his/her rightness that they feel justified in insulting those in opposition, that person has substituted flaming for advocacy. They have also, in my opinion, seriously weakened their position on the subject. Why would someone resort to such an attack if they were, in fact, correct? I am disappointed to see such behavior on this list, and I hope it's occurrence will continue to be vanishingly small. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From pyro9219 at gmail.com Mon Nov 6 21:31:30 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 6 Nov 2006 12:31:30 -0800 Subject: [Tutor] (OT) Flame wars (was: Amazing power of Regular Expressions...) In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Message-ID: Wow... I had to click this e-mail just because I saw the first posts on the mentioned thread and could see it turning for the worst.. > I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go > away > and relearn regales. > > Michael. If this is your method to helping people, you should be the one to step back and go away. While your at it, go an take an educated look at debates.. You might learn that your tactics for trying to sway your side of the opinion are harsh and completely self killing. Any point you were trying to make just became invalid because of this childish b/s. On 11/6/06, Carroll, Barry wrote: > > Greetings, all: > > > -----Original Message----- > > Date: Mon, 6 Nov 2006 10:32:32 +0000 > > From: Michael Sparks > > Subject: Re: [Tutor] Amazing power of Regular Expressions... > > To: tutor at python.org > > Message-ID: <200611061032.33142.ms at cerenity.org> > > Content-Type: text/plain; charset="iso-8859-1" > > > > On Monday 06 November 2006 01:08, Alan Gauld wrote: > > > While using a dictionary is probably overkill, so is a rage. > > > > No, in this case it's absolutely the right choice. > > > > > A simple string holding all characters and an 'in' test would > probably > > > be both easier to read and faster. > > > > I'm stunned you think this. It's precisely this sort of naivete that > > baffles > > me with regard to regales. > > > > > Which kind of illustrates the point of the thread I think! :-) > > > > Actually, no, it doesn't. > > > <> > > > > I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go > > away > > and relearn regales. > > > > Michael. > > > > With the final sentence above, this thread has ceased to be an > intellectual discussion and become a religious argument. Until then, I > was enjoying an informative discussion by knowledgeable people on a > topic of considerable interest. Now I'm upset by the implications of > the statement and embarrassed on behalf of the writer. > > When a person his so convinced of his/her rightness that they feel > justified in insulting those in opposition, that person has substituted > flaming for advocacy. They have also, in my opinion, seriously weakened > their position on the subject. Why would someone resort to such an > attack if they were, in fact, correct? > > I am disappointed to see such behavior on this list, and I hope it's > occurrence will continue to be vanishingly small. > > Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning cathedrals. > > -Quarry worker's creed > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061106/4e25dd0d/attachment.htm From john at fouhy.net Mon Nov 6 22:56:46 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 7 Nov 2006 10:56:46 +1300 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: <454F6149.1010003@tds.net> References: <454DFD20.8050403@tds.net> <200611052129.17955.ms@cerenity.org> <454F6149.1010003@tds.net> Message-ID: <5e58f2e40611061356k380b7c54nd794a9ac1b036ddd@mail.gmail.com> On 07/11/06, Kent Johnson wrote: > If anyone really cares which Python implementation is faster, the timeit > module is your friend. Assertions like "would probably be faster" or > "it's also quicker" don't hold much weight. In Python, if you want to > know what is faster, you must test. Hmm, what exactly is the contentious code? Morpork:~ repton$ python -m timeit -s 's="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-"' '"J" in s' 1000000 loops, best of 3: 0.295 usec per loop Morpork:~ repton$ python -m timeit -s 'import re' -s 'r = re.compile("[0-9A-Za-z_.-]")' 'r.match("J")' 1000000 loops, best of 3: 1.16 usec per loop -- John. From carloslara at web.de Mon Nov 6 23:10:27 2006 From: carloslara at web.de (Carlos) Date: Mon, 06 Nov 2006 23:10:27 +0100 Subject: [Tutor] First real script In-Reply-To: References: Message-ID: <454FB2D3.60704@web.de> Hi again, Thanks for your comments they are really appreciated. Alan, yes you are right, there is no need to use S, A_Len works the same way. Beginner mistake The dictionary way seems to be way better than my idea, will give it a try. And Danny, your CA is very nice. Do you know a better way to do this? if i < A_Len-1: a = A_List[i-1] b = A_List[i] c = A_List[i+1] else: a = A_List[i-1] b = A_List[i] c = A_List[0] if I dont do this I get the following error: c = A_List[i+1] IndexError: list index out of range I have the impression that this can be done in a less clunky way. Again thanks for your comments. : ) Best Regards, Carlos. From dyoo at hkn.eecs.berkeley.edu Mon Nov 6 23:28:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 14:28:30 -0800 (PST) Subject: [Tutor] (OT) Flame wars In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Message-ID: > Wow... I had to click this e-mail just because I saw the first posts on the > mentioned thread and could see it turning for the worst.. Hi everyone, So let's try to squash this one now. There are more interesting problems to solve. Or other flame wars to fight. Let me see if we can do something constructive. I've been doing a shallow, superficial study of the Ruby language at the moment. One of the things I've been impressed about is that they've managed to make lambdas look non-threatening to people with their syntactic sugar of "code blocks". For example, ## Ruby ##################### def twice yield yield twice { puts "hello world" } ############################# This prints out "hello world" twice in a row: the twice() function takes in an implicit "code block", which it can later call by using their 'yield' statement. What the Ruby folks are doing is trying to make the use of higher-order procedures look really simple. In fact, most of the encouraged idiom style I've seen so far extensively uses this code style pervasively (especially for iteration), and that's very admirable. The exact functionality can be done in Python, but it does look a little more intimidating at first: ## Python def twice(f): f() f() twice(lambda: sys.stdout.write("hello world\n")) This does the same thing, but it looks a little scarier because the concepts needed to grasp his are superficially harder than that in the Ruby code. Anyway, let's derail off this regex flamewar and get us back to talking about code and about stuff that actually matters, like learning how to use functions well.. *wink* From dyoo at hkn.eecs.berkeley.edu Mon Nov 6 23:33:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 14:33:20 -0800 (PST) Subject: [Tutor] First real script In-Reply-To: <454FB2D3.60704@web.de> References: <454FB2D3.60704@web.de> Message-ID: > Do you know a better way to do this? > > if i < A_Len-1: > > a = A_List[i-1] > b = A_List[i] > c = A_List[i+1] > > else: > > a = A_List[i-1] > b = A_List[i] > c = A_List[0] Hi Carlos, Here's one way to handle it. If you're familiar with modulo "clock" arithmetic, you might want to apply it above. Here's an example: ######################################## >>> for i in [1, 2, 3, 11, 12, 13, 14]: ... print i, i % 12 ... 1 1 2 2 3 3 11 11 12 0 13 1 14 2 ######################################## The idea is that the second columns results are the result of doing: i % 12 and that number "rolls" around twelve. Your index can "roll" around A_Len. There are other alternative approaches to handle the boundary case. We can talk about them if you'd like. Good luck! From pyro9219 at gmail.com Mon Nov 6 23:33:22 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 6 Nov 2006 14:33:22 -0800 Subject: [Tutor] (OT) Flame wars In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Message-ID: I may have just missed the point to your attempt to derail this conversation =P However.. Why do all that when you can just str = "Hello World" print str * 2 (Maybe I missed some concept that this small example doesn't accuratly reflect) On 11/6/06, Danny Yoo wrote: > > > > Wow... I had to click this e-mail just because I saw the first posts on > the > > mentioned thread and could see it turning for the worst.. > > Hi everyone, > > So let's try to squash this one now. There are more interesting problems > to solve. Or other flame wars to fight. > > > Let me see if we can do something constructive. I've been doing a > shallow, superficial study of the Ruby language at the moment. One of the > things I've been impressed about is that they've managed to make lambdas > look non-threatening to people with their syntactic sugar of "code > blocks". > > For example, > > ## Ruby ##################### > def twice > yield > yield > twice { puts "hello world" } > ############################# > > This prints out "hello world" twice in a row: the twice() function takes > in an implicit "code block", which it can later call by using their > 'yield' statement. What the Ruby folks are doing is trying to make the > use of higher-order procedures look really simple. In fact, most of the > encouraged idiom style I've seen so far extensively uses this code style > pervasively (especially for iteration), and that's very admirable. > > > The exact functionality can be done in Python, but it does look a little > more intimidating at first: > > ## Python > def twice(f): > f() > f() > twice(lambda: sys.stdout.write("hello world\n")) > > This does the same thing, but it looks a little scarier because the > concepts needed to grasp his are superficially harder than that in the > Ruby code. > > > Anyway, let's derail off this regex flamewar and get us back to talking > about code and about stuff that actually matters, like learning how to use > functions well.. *wink* > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061106/609386ee/attachment.html From alan.gauld at btinternet.com Mon Nov 6 23:43:03 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 22:43:03 -0000 Subject: [Tutor] First real script References: <454FB2D3.60704@web.de> Message-ID: "Carlos" wrote in message news:454FB2D3.60704 at web.de... > Do you know a better way to do this? > > if i < A_Len-1: > a = A_List[i-1] > b = A_List[i] > c = A_List[i+1] > else: > a = A_List[i-1] > b = A_List[i] > c = A_List[0] You would think so, just by looking at it, but I must confess I can't offhand think of anytthing significantly better. The only way to make it more consistent would be to 1) implement a real circular list (there probably is one out there somewhere....) 2) always duplicate the first entry at the end of the list, then stop an len-2. HTH, Alan G. From alan.gauld at btinternet.com Mon Nov 6 23:44:14 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 22:44:14 -0000 Subject: [Tutor] First real script References: <454FB2D3.60704@web.de> Message-ID: "Danny Yoo" wrote > Here's one way to handle it. If you're familiar with modulo "clock" > arithmetic, you might want to apply it above. Indeed, I should have thought of that. Good catch Danny. Alan G. From samrobertsmith at gmail.com Mon Nov 6 23:45:10 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 6 Nov 2006 14:45:10 -0800 Subject: [Tutor] numpy and python In-Reply-To: References: <1d987df30611060337r3e12f064j6ff19b4d1c4486d6@mail.gmail.com> Message-ID: <1d987df30611061445q4c371029te4209f10ec5f3890@mail.gmail.com> On 11/6/06, Danny Yoo wrote: > > > On Mon, 6 Nov 2006, linda.s wrote: > > > I use Python 2.4 IDLE to open a py code which import numeric. > > I have installed both scipy and numpy into my c:\python24. However, it > > was still reported as: > > Hi Linda, > > We need more details. What version of scipy and numpy did you install? > Where did you get them them from? This detail matters particularly for > numpy, which has several different incarnations (Numeric, numarray, > NumPy), and they all do similar-but-slightly-different things. > > > Did you install the one from: > > http://numpy.scipy.org/ > > Also, what steps did you do to install those third-party modules? > > I downloaded 2.4 version of Numpy and Scipy from http://www.scipy.org/... and Numpy link leads to the same website as yours. I downloaded the exe files and click them to run and install. I found both numpy and scipy are under C:\Python24\Lib\site-packages > > > from Numeric import * > > ImportError: No module named Numeric > > I got confused... > > If you're using NumPy, then the correct package name for it is 'numpy', > not 'Numeric'. > > from numpy import * > > I think the code is suing Numeric (is it called numpy now? if so, how to make the change?) > Good luck! > From alan.gauld at btinternet.com Mon Nov 6 23:52:05 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Nov 2006 22:52:05 -0000 Subject: [Tutor] (OT) Flame wars References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Message-ID: "Danny Yoo" wrote > So let's try to squash this one now. There are more interesting > problems > to solve. Or other flame wars to fight. I wasn't aware we were having a war, but I'm happy to desist :-) > Let me see if we can do something constructive. I've been doing a > shallow, superficial study of the Ruby language at the moment. One > of the > things I've been impressed about is that they've managed to make > lambdas > look non-threatening to people with their syntactic sugar of "code > blocks". Ruby blocks are almost as good as Smalltalk blocks for this kind of thing and very powerful. Regular readers will know I have often expressed dissappointment at the limitations of Python's lambdas, it's one thing the Ruby boys have got right IMHO. > The exact functionality can be done in Python, but it does look a > little > more intimidating at first: > > ## Python > def twice(f): > f() > f() > twice(lambda: sys.stdout.write("hello world\n")) > > This does the same thing, but it looks a little scarier because the > concepts needed to grasp his are superficially harder than that in > the > Ruby code. The other advantage in Ruby is that the block can be arbitrarily complex, not just a single expression as in a Python lambda. This allows us to embed loops and all sorts, effectively adding new command structures to the language in a way that only Lisp and Tcl have really been good at up till now. Alan G. From rabidpoobear at gmail.com Tue Nov 7 00:04:12 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 06 Nov 2006 17:04:12 -0600 Subject: [Tutor] (OT) Flame wars In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Message-ID: <454FBF6C.1000006@gmail.com> Chris Hengge wrote: > I may have just missed the point to your attempt to derail this > conversation =P Ah, well, don't worry. I didn't learn of lambda until I'd been using Python for a year or more. I was trying to pass arguments to callbacks in TKinter. one of the Pythonistas (Alan, Danny, Kent) told me "Oh, that's trivial with lambda" and since then, I've tried to read up on lambda and Functional Programming in general. > However.. > > Why do all that when you can just > > str = "Hello World" > print str * 2 > > (Maybe I missed some concept that this small example doesn't accuratly > reflect) Yes, I do believe you're correct here, Chris :) I will not presume to know enough about lambda to explain it to you, but I will refer you to these articles: http://www.secnetix.de/~olli/Python/lambda_functions.hawk and Alan Gauld's tutorial, of course :) specifically, the page http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm Or browse there from the main page http://www.freenetpages.co.uk/hp/alan.gauld/ click 'functional programming' under Advanced Topics' if you want the menu frame to remain on the left of the screen. Consider this: You don't say outputstring = "Hello, World!" print outputstring because you're only using the string once, and it's not something that would look ugly all on one line. Instead, you do print "Hello, World!" An alternate example: a_list = [[a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a]] print a_list would make more sense than print [[a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a]] because then if you need to change the list, or use it again somewhere, you don't have to go through the pain of typing it out each time, since in the first case, you assigned it to a variable, a_list. The long and short of it is: (or more specifically, the short of it) lambda lets you define functions you don't have to bind to a name. so, supposing you have the function def call_a_function(a_function): a_function() That will call a function object, you can do something like this: def f(): sys.stdout.write("Hello, World!") call_a_function(f) or you could do call_a_function(lambda: sys.stdout.write("Hello, World!")) It's like the string example above. It's a waste to have the function definition on two lines, and the call on another line, if the function's compact enough to fit on a single line using lambda. But also note that you can't reuse the lambda function unless you store it in a variable. In this way, it's similar to the 'print "Hello, World!"' statement. I hope that helps you, Chris. -Luke From tim at johnsons-web.com Tue Nov 7 00:09:43 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 6 Nov 2006 14:09:43 -0900 Subject: [Tutor] (OT) Flame wars In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Message-ID: <20061106230943.GC1768@johnsons-web.com> * Alan Gauld [061106 14:01]: > > The other advantage in Ruby is that the block can be arbitrarily > complex, not just a single expression as in a Python lambda. This > allows us to embed loops and all sorts, effectively adding new > command structures to the language in a way that only Lisp > and Tcl have really been good at up till now. > Sorry Alan, but you are leaving out rebol. Command structures in rebol are are just functions and IMHO, easier to "roll your own" than lisp macros. But with freedom comes responsibility. (Tim: rebol = 50% python = 50%) -- Tim Johnson http://www.alaska-internet-solutions.com From rabidpoobear at gmail.com Tue Nov 7 00:08:48 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 06 Nov 2006 17:08:48 -0600 Subject: [Tutor] First real script In-Reply-To: References: <454FB2D3.60704@web.de> Message-ID: <454FC080.6070604@gmail.com> Danny Yoo wrote: >> Do you know a better way to do this? >> [snip stuff] >> > > Hi Carlos, > > Here's one way to handle it. If you're familiar with modulo "clock" > arithmetic, you might want to apply it above. > Also, consider this example, Carlos: >>> aList = [1,2,3,4,5,6] >>> a,b,c = aList[1:4] >>> a 2 >>> b 3 >>> c 4 HTH, -Luke From dyoo at hkn.eecs.berkeley.edu Tue Nov 7 00:18:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 15:18:00 -0800 (PST) Subject: [Tutor] (OT) Flame wars In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Message-ID: On Mon, 6 Nov 2006, Chris Hengge wrote: > I may have just missed the point to your attempt to derail this > conversation =P Hi Chris, Ah! Are we talking about regular expressions anymore? No? Good. *grin* > Why do all that when you can just > > str = "Hello World" > print str * 2 Let me do a more substantial example. As you know, Python's for loop works on "iterables": ##################### >>> for x in list("hello"): ... print x ... h e l l o ##################### We're running a for loop across a list of characters. In this case, our list is iterable. (We could iterate directly on the string itself, but let's stick with lists for the moment.) An "iterable" in Python is something that can give us an iterator. ############################### >>> my_iterator = iter(list("hello")) ############################### An iterator is something that responses to next() requests until we consume everything: ################################# >>> my_iterator.next() 'h' >>> my_iterator.next() 'e' >>> my_iterator.next() 'l' >>> my_iterator.next() 'l' >>> my_iterator.next() 'o' >>> my_iterator.next() Traceback (most recent call last): File "", line 1, in ? StopIteration ################################## So there's a few layers of indirection here. iterable -> iterator -> elements Ruby takes a different approach: they also have an iterator protocol, but what they require is something that provides an each() method. For example: #################################################### irb(main):002:0> 'hello'.split(//).each {|c| puts c} h e l l o #################################################### This each method takes in a code block, and runs it on every element in the thing we're iterating across. The iterable itself provides the looping mechanism instead of the client code. The concept sorta looks like this in Python: ####################################################### class MyString: def __init__(self, s): self.s = s def each(self, f): i = 0 while i < len(self.s): f(self.s[i]) i = i + 1 MyString("hello").each(lambda c: sys.stdout.write(c + '\n')) ######################################################## This, too, "iterates" across our iterable. The one handling the control flow is the 'each' method, which is a little wacky to think about at first. The Ruby folks make this work because their syntax is custom tailored for this pattern, so it's easier to read and write. I'm probably not doing it much justice with my ugly examples. *grin* From Barry.Carroll at psc.com Tue Nov 7 00:41:34 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 6 Nov 2006 15:41:34 -0800 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> Danny: > -----Original Message----- > Date: Mon, 6 Nov 2006 14:28:30 -0800 (PST) > From: Danny Yoo > Subject: Re: [Tutor] (OT) Flame wars > To: Chris Hengge > Cc: Tutor > Message-ID: > Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed > <> > > Let me see if we can do something constructive. I've been doing a > shallow, superficial study of the Ruby language at the moment. One of the > things I've been impressed about is that they've managed to make lambdas > look non-threatening to people with their syntactic sugar of "code > blocks". > > For example, > > ## Ruby ##################### > def twice > yield > yield > twice { puts "hello world" } > ############################# > > This prints out "hello world" twice in a row: the twice() function takes > in an implicit "code block", which it can later call by using their > 'yield' statement. What the Ruby folks are doing is trying to make the > use of higher-order procedures look really simple. In fact, most of the > encouraged idiom style I've seen so far extensively uses this code style > pervasively (especially for iteration), and that's very admirable. > > > The exact functionality can be done in Python, but it does look a little > more intimidating at first: > > ## Python > def twice(f): > f() > f() > twice(lambda: sys.stdout.write("hello world\n")) > > This does the same thing, but it looks a little scarier because the > concepts needed to grasp his are superficially harder than that in the > Ruby code. > <> > Thank you for this post. I was in a discussion of Ruby vs. Python at lunch today. The consensus was that Python was much better than Ruby in all ways. Since I know very little about Ruby, I had nothing to add to the conversation. I have struggled considerably with lambdas since taking up Python. I'm still not really comfortable using them in production code. I agree that Ruby's style is more intuative and easier to use. I wonder if a future version of Python could adopt this style. Regards, Barry barry.carroll at psc.com 541-302-1107 PS Your response to the recent unpleasantness was exceptional. I tried to be civil in my disapproval, but deflecting the thread back to a constructive, Python-based topic was more effective, I thought. Thank you again. BGC ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From dyoo at hkn.eecs.berkeley.edu Tue Nov 7 00:48:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 15:48:33 -0800 (PST) Subject: [Tutor] numpy and python In-Reply-To: <1d987df30611061445q4c371029te4209f10ec5f3890@mail.gmail.com> References: <1d987df30611060337r3e12f064j6ff19b4d1c4486d6@mail.gmail.com> <1d987df30611061445q4c371029te4209f10ec5f3890@mail.gmail.com> Message-ID: [Danny] >> If you're using NumPy, then the correct package name for it is 'numpy', >> not 'Numeric'. >> >> from numpy import * [Linda] > I think the code is suing Numeric (is it called numpy now? if so, how > to make the change?) So it's not your code? If it's not your own code then, nail down what the required external modules are, since that's important to know. Look for the word "Numeric" in their sources: if that's what they use, then they are using the older Numeric module, and not the numpy module that you've installed. In your case, assuming the old code is Numeric, I'd recommend just installing the old Numeric module as well. We want to avoid any weird backward-compatibility issues that might come up with numpy. (You can try to migrating that code to numpy later, once you're on a stable Numeric platform. See the top of http://numpy.scipy.org/ which mentions a program called numpy.oldnumeric.alter_code1 that should address this.) You can find Numeric here: http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=1351 From janos.juhasz at VELUX.com Tue Nov 7 00:54:47 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 7 Nov 2006 00:54:47 +0100 Subject: [Tutor] 3D rendered bar chart (made of glass) In-Reply-To: Message-ID: Dear Guys, I have downloaded CGkit and Aqsis and tried the examples from it. I run the samples, like the torus with grass. It is simple fantastic. I would like to make some artistic visualization with the power of python and the beauty of a professional renderer. I think about colored semitranslucent glass cubes. Like a simple bar graph, but the cube's 3D position, extension, color and text would be defined by database content and some calculus. It would be fine to make some axes and making the 3D view settings in an interactive 3D program. May you recommend any simple solution about it ? Yours sincerely, ______________________________ Janos Juhasz From samrobertsmith at gmail.com Tue Nov 7 01:00:23 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 6 Nov 2006 16:00:23 -0800 Subject: [Tutor] a line Message-ID: <1d987df30611061600j3b22cfbav5ed758122044c091@mail.gmail.com> What does Pythonw -i test.py -i do in Mac machine? From ms at cerenity.org Tue Nov 7 01:08:05 2006 From: ms at cerenity.org (Michael Sparks) Date: Tue, 7 Nov 2006 00:08:05 +0000 Subject: [Tutor] (OT) Flame wars In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> Message-ID: <200611070008.05250.ms@cerenity.org> On Monday 06 November 2006 22:52, Alan Gauld wrote: > I wasn't aware we were having a war, but I'm happy to desist :-) FWIW, I wasn't aware of one either. (Mind you I've often noticed what passes for plain speaking in the UK passes for vehement flame war elsewhere, so maybe that's it) Anyway, if that's what people here think a flame war looks like... Well, a) I'll try and avoid such /mild/ comments in future ;) b) good for such people, real flame wars are really nasty ! Michael. From tim at johnsons-web.com Tue Nov 7 01:22:29 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 6 Nov 2006 15:22:29 -0900 Subject: [Tutor] is gotchas? In-Reply-To: <454F8ACC.9000202@tds.net> References: <20061106171601.GB1768@johnsons-web.com> <454F8ACC.9000202@tds.net> Message-ID: <20061107002229.GA1780@johnsons-web.com> * Kent Johnson [061106 10:31]: > > In [9]: a=[1,2] > > In [10]: b=[1,2] Hmmm! Hmmm! Lookee here: ## console session >>> a=[1,2] >>> b=[1,2] >>> a is b False >>> c='1' ## one byte >>> d='1' ## one byte >>> c is d True >>> c='1,2' >>> d='1,2' >>> c is d False The Hmmm! is emmitted because I'm thinking that if everything is an object in python, then why does `c is d` evaluate to True when the assigned value is 1 byte and evaluate to False when the assigned value is more that 1 byte? I think I ran into this before and that's why I never used `is'. Good thread. Beats flame wars. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From ajikoe at gmail.com Tue Nov 7 01:28:26 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 7 Nov 2006 07:28:26 +0700 Subject: [Tutor] is gotchas? In-Reply-To: <20061107002229.GA1780@johnsons-web.com> References: <20061106171601.GB1768@johnsons-web.com> <454F8ACC.9000202@tds.net> <20061107002229.GA1780@johnsons-web.com> Message-ID: For small string object python has optimization method so it is really the same object! Cheers, pujo On 11/7/06, Tim Johnson wrote: > > * Kent Johnson [061106 10:31]: > > > > In [9]: a=[1,2] > > > > In [10]: b=[1,2] > > Hmmm! Hmmm! > Lookee here: > ## console session > >>> a=[1,2] > >>> b=[1,2] > >>> a is b > False > >>> c='1' ## one byte > >>> d='1' ## one byte > >>> c is d > True > >>> c='1,2' > >>> d='1,2' > >>> c is d > False > > The Hmmm! is emmitted because I'm thinking that if everything is an > object in python, then why does `c is d` evaluate to True when > the assigned value is 1 byte and evaluate to False when the assigned > value is more that 1 byte? > > I think I ran into this before and that's why I never used `is'. > > Good thread. Beats flame wars. > thanks > tim > > -- > Tim Johnson > http://www.alaska-internet-solutions.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061107/73ac0ce0/attachment.html From sisson.j at gmail.com Mon Nov 6 19:59:21 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Mon, 06 Nov 2006 12:59:21 -0600 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: <5e58f2e40611061356k380b7c54nd794a9ac1b036ddd@mail.gmail.com> References: <454DFD20.8050403@tds.net> <200611052129.17955.ms@cerenity.org> <454F6149.1010003@tds.net> <5e58f2e40611061356k380b7c54nd794a9ac1b036ddd@mail.gmail.com> Message-ID: <454F8609.6030903@gmail.com> Just out of curiousity (since I really can't say myself), does the code below import re each time it loops? I ran the same commands and saw quite similar results (0.176 usec per loop for the first test and 0.993 usec per loop for the second test), and I was just curious if that import (and the re.compile, for that matter) happen with each loop? Jonathon John Fouhy wrote: > On 07/11/06, Kent Johnson wrote: >> If anyone really cares which Python implementation is faster, the timeit >> module is your friend. Assertions like "would probably be faster" or >> "it's also quicker" don't hold much weight. In Python, if you want to >> know what is faster, you must test. > > Hmm, what exactly is the contentious code? > > Morpork:~ repton$ python -m timeit -s > 's="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-"' > '"J" in s' > 1000000 loops, best of 3: 0.295 usec per loop > Morpork:~ repton$ python -m timeit -s 'import re' -s 'r = > re.compile("[0-9A-Za-z_.-]")' 'r.match("J")' > 1000000 loops, best of 3: 1.16 usec per loop > From john at fouhy.net Tue Nov 7 02:28:11 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 7 Nov 2006 14:28:11 +1300 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: <454F8609.6030903@gmail.com> References: <454DFD20.8050403@tds.net> <200611052129.17955.ms@cerenity.org> <454F6149.1010003@tds.net> <5e58f2e40611061356k380b7c54nd794a9ac1b036ddd@mail.gmail.com> <454F8609.6030903@gmail.com> Message-ID: <5e58f2e40611061728s45a8883n70d199598c21b363@mail.gmail.com> On 07/11/06, Jonathon Sisson wrote: > Just out of curiousity (since I really can't say myself), does the code > below import re each time it loops? I ran the same commands and saw > quite similar results (0.176 usec per loop for the first test and 0.993 > usec per loop for the second test), and I was just curious if that > import (and the re.compile, for that matter) happen with each loop? Nope. Here's the command again: python -m timeit -s 'import re' -s 'r = re.compile("[0-9A-Za-z_.-]")' 'r.match("J")' -s means "startup code". So, 'import re' and 're.compile(...)' happen only once, before the main test starts. You can read help on timeit by typing 'import timeit; help(timeit)' in the python console. -- John. From sisson.j at gmail.com Mon Nov 6 20:57:01 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Mon, 06 Nov 2006 13:57:01 -0600 Subject: [Tutor] Amazing power of Regular Expressions... In-Reply-To: <5e58f2e40611061728s45a8883n70d199598c21b363@mail.gmail.com> References: <454DFD20.8050403@tds.net> <200611052129.17955.ms@cerenity.org> <454F6149.1010003@tds.net> <5e58f2e40611061356k380b7c54nd794a9ac1b036ddd@mail.gmail.com> <454F8609.6030903@gmail.com> <5e58f2e40611061728s45a8883n70d199598c21b363@mail.gmail.com> Message-ID: <454F938D.5040909@gmail.com> John, Thanks...I was a bit deep in a script trying to figure out why I kept getting global key errors (trying to make sure that re.compile and import re weren't run but once...doh?) when you responded. I guess that settles it, then...for this particular instance, '"J" in s' is indeed faster than 'r.match("J")'... Jonathon John Fouhy wrote: > On 07/11/06, Jonathon Sisson wrote: >> Just out of curiousity (since I really can't say myself), does the code >> below import re each time it loops? I ran the same commands and saw >> quite similar results (0.176 usec per loop for the first test and 0.993 >> usec per loop for the second test), and I was just curious if that >> import (and the re.compile, for that matter) happen with each loop? > > Nope. > > Here's the command again: > > python -m timeit -s 'import re' -s 'r = re.compile("[0-9A-Za-z_.-]")' > 'r.match("J")' > > -s means "startup code". So, 'import re' and 're.compile(...)' happen > only once, before the main test starts. > > You can read help on timeit by typing 'import timeit; help(timeit)' in > the python console. > From dyoo at hkn.eecs.berkeley.edu Tue Nov 7 03:24:43 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 Nov 2006 18:24:43 -0800 (PST) Subject: [Tutor] is gotchas? In-Reply-To: <20061107002229.GA1780@johnsons-web.com> References: <20061106171601.GB1768@johnsons-web.com> <454F8ACC.9000202@tds.net> <20061107002229.GA1780@johnsons-web.com> Message-ID: >>>> c='1' ## one byte >>>> d='1' ## one byte >>>> c is d > True >>>> c='1,2' >>>> d='1,2' >>>> c is d > False > > The Hmmm! is emmitted because I'm thinking that if everything is an > object in python, then why does `c is d` evaluate to True when > the assigned value is 1 byte and evaluate to False when the assigned > value is more that 1 byte? 'is' is the operator you want if you want to check for object identity. You should probably not use it for strings, or for immutables for that matter. Its value here is "undefined" above in the sense that our programs shouldn't depend on the behavior you're seeing there. (And you'll see different behavior depending on if Python is being run as an interpreter vs. on a whole program. On a whole program, all the duplicate string literals tend to be shared since Python strings are immutable.) A closer look at: http://docs.python.org/ref/objects.html is helpful, especially near the bottom. 'is' is relatively rare; I've seen it used most often in code dealing with object caches. From arcege at gmail.com Tue Nov 7 03:51:32 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Mon, 6 Nov 2006 21:51:32 -0500 Subject: [Tutor] is gotchas? In-Reply-To: <20061107002229.GA1780@johnsons-web.com> References: <20061106171601.GB1768@johnsons-web.com> <454F8ACC.9000202@tds.net> <20061107002229.GA1780@johnsons-web.com> Message-ID: <7e5ba9220611061851j30c7e1cdu47ecaf12c9df84ca@mail.gmail.com> On 11/6/06, Tim Johnson wrote: > > * Kent Johnson [061106 10:31]: > > > > In [9]: a=[1,2] > > > > In [10]: b=[1,2] > > Hmmm! Hmmm! > Lookee here: > ## console session > >>> a=[1,2] > >>> b=[1,2] > >>> a is b > False > >>> c='1' ## one byte > >>> d='1' ## one byte > >>> c is d > True > >>> c='1,2' > >>> d='1,2' > >>> c is d > False > > The Hmmm! is emmitted because I'm thinking that if everything is an > object in python, then why does `c is d` evaluate to True when > the assigned value is 1 byte and evaluate to False when the assigned > value is more that 1 byte? > > I think I ran into this before and that's why I never used `is'. > You might want to try: >>> a = 'a' >>> b = 'a' >>> a is b True Why? Interned strings. As Pujo aluded to, various simple or well-used objects (like the digits between 0 and 100), and strings that have been interned with the intern() function. There is a unique item: None. There is only one object of type NoneType. No matter how many times you reference it, it will always be the same object. So it is a perfect use of "is": def f(arg1, arg2, optarg=None): if optarg is None: -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061106/e0af3c1e/attachment.html From wescpy at gmail.com Tue Nov 7 04:13:08 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 6 Nov 2006 19:13:08 -0800 Subject: [Tutor] is gotchas? In-Reply-To: <20061106171601.GB1768@johnsons-web.com> References: <20061106171601.GB1768@johnsons-web.com> Message-ID: <78b3a9580611061913s45b42006k25e3e2f6e7700c22@mail.gmail.com> others already gave good responses, so mine are short. > 1)where do `is` and `==` yield the same results? "is" is object identity comparison while "==" is object value comparison > 2)where do they not yield the same results? they give different results when you have two different objects regardless of the equality of their values. > 3)is there a special method for `is'. no, not really. you can use id() and '==' to proxy for is: a is b <==> id(a) == id(b) > 4)Pointers to docs are welcome. http://docs.python.org/lib/comparisons.html http://docs.python.org/ref/comparisons.html hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ebrosh at nana.co.il Tue Nov 7 04:17:28 2006 From: ebrosh at nana.co.il (Eli Brosh) Date: Tue, 7 Nov 2006 05:17:28 +0200 Subject: [Tutor] How to set PYTHONPATH Message-ID: <957526FB6E347743AAB42B212AB54FDA95B9AB@NANAMAILBACK1.nanamail.co.il> How do i set the PYTHONPATH variable ? >From answers to my query on "editing path" I realized that this is what should be done if i want to include another folder in the Python search path. I tried: import sys sys.path.append('additional path') but it worked only at runtime and is forgotten when I restart Python. I would like to append the PYTHONPATH permanently. How is it done under Windows XP ? Thank you very much for your attention Eli Brosh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061107/4fe5870d/attachment.htm From alan.gauld at freenet.co.uk Tue Nov 7 09:28:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 7 Nov 2006 08:28:38 -0000 Subject: [Tutor] a line References: <1d987df30611061600j3b22cfbav5ed758122044c091@mail.gmail.com> Message-ID: <018e01c70246$b9e5cd40$04000100@XPpro> Linda, >----- Original Message ----- > From: "linda.s" > To: "Danny Yoo" > Cc: "Alan Gauld" ; "Tutor" > > Sent: Tuesday, November 07, 2006 12:00 AM > Subject: a line I can't speak for Danny, but I'd apprreciate if you could just post your questions to the tutor list and not CC Danny and me. I suspect you are using an old thread entry to reply, but nonetheless I get more than enough email as it is, thanks. > What does > Pythonw -i test.py -i > do in Mac machine? It executes pythonw with the -i option. Pythonw then executes test.py passing it a -i option. python -h will get you a list of all the commandline switches. -i forces python to end the program and stay in interactive mode (the >>> prompt), which is very useful for debugging unusual faults. pythonw runs without a console window. I assume the same applies on the Mac although I've never tried using pythonw on my Mac Alan G. From alan.gauld at btinternet.com Tue Nov 7 10:50:33 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Nov 2006 09:50:33 -0000 Subject: [Tutor] (OT) Flame wars References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> <20061106230943.GC1768@johnsons-web.com> Message-ID: "Tim Johnson" wrote >> allows us to embed loops and all sorts, effectively adding new >> command structures to the language in a way that only Lisp >> and Tcl have really been good at up till now. > > Sorry Alan, but you are leaving out rebol. Command structures > in rebol are are just functions and IMHO, easier to "roll your > own" than lisp macros. Quite right, I forgot rebol. I played with it briefly and it is a lot of fun for network programming, but ultimately I ran out of steam with it too often so gave up. Alan G. From alan.gauld at btinternet.com Tue Nov 7 10:56:42 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Nov 2006 09:56:42 -0000 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas References: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> Message-ID: "Carroll, Barry" wrote > Thank you for this post. I was in a discussion of Ruby vs. Python > at > lunch today. The consensus was that Python was much better than > Ruby in > all ways. That's a little hard on Ruby. There are many good features and several of them are arguably improvements on Python. But Python is still easier for me personally to grok, I'm not sure why exactly. > I have struggled considerably with lambdas since taking up Python. > I'm > still not really comfortable using them in production code. I agree > that Ruby's style is more intuative and easier to use. I wonder if > a > future version of Python could adopt this style. I think it would be difficult without adding block delimiters to the language, and most of the common symbols already have a role ([],(),{}, |, etc). Also Guido prefers explicit definition of functions to anonymous ones - explicit is better than implicit is one of Pythons principles after all. Alan G. From alan.gauld at btinternet.com Tue Nov 7 11:03:45 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Nov 2006 10:03:45 -0000 Subject: [Tutor] How to set PYTHONPATH References: <957526FB6E347743AAB42B212AB54FDA95B9AB@NANAMAILBACK1.nanamail.co.il> Message-ID: "Eli Brosh" wrote > How do i set the PYTHONPATH variable ? > How is it done under Windows XP ? Go to MyComputer and right click, select Properties Go to the Advanced Tab Click the EnvironmentVariables button In the lower window, labelled System Variables look for PYTHONPATH If it exists click Edit otherwise click New In the Name field type PYTHONPATH In the value field type a list of paths separated by semi-colons For example mine looks like: D:\PROJECTS\Python;D:\PROJECTS\Book\section4 Close all the boxes. You may need a restart to make it take effect I'm not sure on that... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From carloslara at web.de Tue Nov 7 11:13:25 2006 From: carloslara at web.de (Carlos) Date: Tue, 07 Nov 2006 11:13:25 +0100 Subject: [Tutor] First real script In-Reply-To: References: Message-ID: <45505C45.8080102@web.de> Hello to all, Ok, after reading your comments I ended up with this: #Easy_2DCA_01.py #A very basic 2D script that lets you play with Wolfram's rule 30 A_List = [0]*10+[1]+[0]*10 A_Len = len(A_List) B_List = [] print A_List Iterations = 5 rule_30 = { (1, 1, 1) : 0, (1, 1, 0) : 0, (1, 0, 1) : 0, (1, 0, 0) : 1, (0, 1, 1) : 1, (0, 1, 0) : 1, (0, 0, 1) : 1, (0, 0, 0) : 0, } for j in range (Iterations): for i in range (A_Len): x = A_List[i-1] y = A_List[i] if i < A_Len-1: z = A_List[i+1] else: z = A_List[0] X = rule_30[x,y,z] B_List.append (X) print B_List A_List = B_List B_List = [] Not bad I think :P It is compact and readable, even by a dummy like me. I took the ideas that I completely understand, there are others that are slightly too much for me now, but they are noted too. I want to thank all you guys for the comments. This is my first script, but I can see that this list a great resource for learning Python. As you may have noticed the name of the script has changed, I will now try a 3D CA. I have been thinking that the best way to do this would be to use a matrix, like those found in SciPy. Do you think this is a good idea? I'm afraid that my reasoning is too linear, to add another dimension to my script I will add another dimension to my initial list. Here is an example: import scipy a1 = scipy.zeros((4,5)) print a1 [[ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.]] Thats it for now. Thanks again, Carlos From alan.gauld at btinternet.com Tue Nov 7 00:02:39 2006 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 6 Nov 2006 23:02:39 +0000 (GMT) Subject: [Tutor] Please help to debug this function.. In-Reply-To: Message-ID: <20061106230239.82849.qmail@web86110.mail.ird.yahoo.com> Reposting to the list. --- Asrarahmed Kadri wrote: > > > except ValueError: > > > flag = False > > > startdate = None > > > enddate = None > > > err_msg = traceback.format_exc() > > > index = string.find(err_msg,'Value') > > > print err_msg[index:] > > > return (flag,startdate,enddate) > > > >Since this block is essentially identical to the except > >block above you could package them both as a function > >which would shorten the code a little. > It might seem silly, but can you just give a hint as to how to > put the code in a function.. def handleValueError(): flag = False startdate = None enddate = None err_msg = traceback.format_exc() index = err_msg.find('Value') print err_msg[index:] return (flag,startdate,enddate) And in your code above: except ValueError: return handleValueError() > > It would be better to raise a ValueError which can be caught > > by the external program: > How to catch the exception from one module into another ..??? Just use try/except as usual. There is no difference to exceptions thrown by your code and the ones thrown by the standard Python functions. Consider: ####### module.py ####### def f(): raise ValueError ########################## ###### main.py ########## import module try: module.f() except ValueError: print "It broke!" ######################### Is that clear? Alan G ___________________________________________________________ All new Yahoo! Mail "The new Interface is stunning in its simplicity and ease of use." - PC Magazine http://uk.docs.yahoo.com/nowyoucan.html From kent37 at tds.net Tue Nov 7 11:53:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Nov 2006 05:53:57 -0500 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> Message-ID: <455065C5.4000904@tds.net> Carroll, Barry wrote: > Thank you for this post. I was in a discussion of Ruby vs. Python at > lunch today. The consensus was that Python was much better than Ruby in > all ways. Since I know very little about Ruby, I had nothing to add to > the conversation. Sounds like you had a table full of Pythonistas. I barely know any Ruby but I think there are a few areas where it has advantages over Python. - Ruby blocks are much more powerful than Python lambdas and they are integrated pervasively into the language. They also allow interaction between the block and the container that I don't think you can do in Python, I don't understand it well enough to know. (Maybe the new generator features of Python 2.5 allow something comparable.) - Metaprogramming (modifying classes on the fly) seems to be much easier in Ruby than in Python. Interestingly, in the Ruby community this is considered a powerful feature and used frequently, whereas the Python community tends to think of it as a last resort. - Ruby is very good at creating domain-specific mini-languages. This is a consequence of the easy metaprogramming and optional parentheses on function calls. Take a look at a Ruby on Rails tutorial to see what I mean. Kent From alan.gauld at btinternet.com Tue Nov 7 11:56:40 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Nov 2006 10:56:40 -0000 Subject: [Tutor] First real script References: <45505C45.8080102@web.de> Message-ID: "Carlos" wrote > As you may have noticed the name of the script has changed, I will > now > try a 3D CA. I have been thinking that the best way to do this would > be > to use a matrix, like those found in SciPy. Do you think this is a > good > idea? Using a matrix is fine but unless you are using any of the other Scipy features you can just use a vanilla two dimensional Python list matrix = [][] Or to initialise it too: matrix = [[0]*width for n in range(height)] Just a thought, Alan G. From kent37 at tds.net Tue Nov 7 12:04:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Nov 2006 06:04:02 -0500 Subject: [Tutor] is gotchas? In-Reply-To: <78b3a9580611061913s45b42006k25e3e2f6e7700c22@mail.gmail.com> References: <20061106171601.GB1768@johnsons-web.com> <78b3a9580611061913s45b42006k25e3e2f6e7700c22@mail.gmail.com> Message-ID: <45506822.1090406@tds.net> wesley chun wrote: >> 3)is there a special method for `is'. > > no, not really. you can use id() and '==' to proxy for is: > > a is b <==> id(a) == id(b) No, not necessarily. id's are recycled which can lead to unexpected behaviour when comparing them. See for example this thread on c.l.py: http://tinyurl.com/yflknx Kent From andreas at kostyrka.org Tue Nov 7 12:20:16 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 07 Nov 2006 12:20:16 +0100 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> Message-ID: <1162898417.9452.18.camel@andi-lap> Am Dienstag, den 07.11.2006, 09:56 +0000 schrieb Alan Gauld: > "Carroll, Barry" wrote > > > Thank you for this post. I was in a discussion of Ruby vs. Python > > at > > lunch today. The consensus was that Python was much better than > > Ruby in > > all ways. That's bullshit. Python and Ruby are quite comparable. They differ only on stuff like: a) Syntax (I prefer the clean intended Python syntax, and Ruby claim to be Perlish is a major turnoff) b) Runtime/Library (When I learned Ruby sometime ago, the library support was bad) c) Python has a more general set of ideas, while Ruby is clearly patterned on Smalltalk, at least to me. One major cool thing that Ruby (and Smalltalk) has, are codeblocks. I've been thinking on and off for years how to add these to Python, but I have not really come up with a compact syntax that would transport the same functionality nicely. So no, Python is no way superior to Ruby in all ways. Nor is Ruby superior in all ways to Python. The point is, they live both in comparable ecological niches, and you can probably do everything you can do with Python in Ruby and the other way. As a decade long Python coder, I've taken a look at Ruby, found it quite ok, but I stay for my own stuff with Python, because: a) Did I mention the decade doing Python stuff, starting with Python 1.2? b) Ruby allows a number of interesting things easily, e.g. classes are never closed, and so on. OTOH, while it is not always as pretty, I can get 99% of that stuff hacked in Python too, and I'm not completely sure if I like some of these ideas, design-wise anyway. ;) c) I don't like the syntax that much, especial the referal to Perl. d) At the time I did evaluate Ruby, the Ruby library was poor compared to the Python offering. Andreas > > That's a little hard on Ruby. There are many good features and several > of them are arguably improvements on Python. But Python is > still easier for me personally to grok, I'm not sure why exactly. > > > I have struggled considerably with lambdas since taking up Python. > > I'm > > still not really comfortable using them in production code. I agree > > that Ruby's style is more intuative and easier to use. I wonder if > > a > > future version of Python could adopt this style. > > I think it would be difficult without adding block delimiters to > the language, and most of the common symbols already > have a role ([],(),{}, |, etc). > > Also Guido prefers explicit definition of functions to > anonymous ones - explicit is better than implicit is > one of Pythons principles after all. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061107/61f5920f/attachment.pgp From ajkadri at googlemail.com Tue Nov 7 15:36:35 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 7 Nov 2006 14:36:35 +0000 Subject: [Tutor] Help me with installing Soappymodule Message-ID: Hi Folks, I want to install SOAPpy module. As stated on http://pywebsvcs.sourceforge.net/soappy.txt, there are two modules that should be installed prior to installing SOAPpy. One in pyXML and the other is fpconst. I installed pyXML from the URL stated on teh above website. But the URL for fpconst download is not valid. Any idea as to where can I get the module . TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061107/a84da081/attachment.htm From jfabiani at yolo.com Tue Nov 7 16:02:59 2006 From: jfabiani at yolo.com (johnf) Date: Tue, 7 Nov 2006 07:02:59 -0800 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas In-Reply-To: <1162898417.9452.18.camel@andi-lap> References: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> <1162898417.9452.18.camel@andi-lap> Message-ID: <200611070702.59894.jfabiani@yolo.com> On Tuesday 07 November 2006 03:20, Andreas Kostyrka wrote: > That's bullshit. Python and Ruby are quite comparable Gee Andreas tell us how you really feel! BTW I agree that Python and Ruby are very close. John From rabidpoobear at gmail.com Tue Nov 7 16:37:59 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 07 Nov 2006 09:37:59 -0600 Subject: [Tutor] First real script In-Reply-To: <45505C45.8080102@web.de> References: <45505C45.8080102@web.de> Message-ID: <4550A857.9050405@gmail.com> Carlos wrote: > Hello to all, > > Ok, after reading your comments I ended up with this: > > #Easy_2DCA_01.py > #A very basic 2D script that lets you play with Wolfram's rule 30 > > A_List = [0]*10+[1]+[0]*10 > A_Len = len(A_List) > B_List = [] > print A_List > Iterations = 5 > > rule_30 = { > (1, 1, 1) : 0, > (1, 1, 0) : 0, > (1, 0, 1) : 0, > (1, 0, 0) : 1, > (0, 1, 1) : 1, > (0, 1, 0) : 1, > (0, 0, 1) : 1, > (0, 0, 0) : 0, > } > > for j in range (Iterations): > for i in range (A_Len): > It seems to me you could just iterate on a range of A_Len-1 and then you wouldn't have to wrap around. Perhaps you need it to work that way, though. I'm not sure. > x = A_List[i-1] > y = A_List[i] > > if i < A_Len-1: > z = A_List[i+1] > > else: > z = A_List[0] Can just become x,y,z = A_List[i-1:i+1] + [A_List[(i+1) % A_Len]] Though it's slightly less readable, it's also a bit shorter :) Alternately, you can leave your x and y definitions, and change the if/else stuff to z = A_List[(i+1) % A_Len] At least I think so :) HTH, -Luke From tim at johnsons-web.com Tue Nov 7 18:10:23 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 7 Nov 2006 08:10:23 -0900 Subject: [Tutor] comparing languages [was (OT) Flame wars] In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A12@eugsrv400.psc.pscnet.com> <20061106230943.GC1768@johnsons-web.com> Message-ID: <20061107171023.GB1780@johnsons-web.com> * Alan Gauld [061107 01:02]: > > "Tim Johnson" wrote > >> allows us to embed loops and all sorts, effectively adding new > >> command structures to the language in a way that only Lisp > >> and Tcl have really been good at up till now. > > > > Sorry Alan, but you are leaving out rebol. Command structures > > in rebol are are just functions and IMHO, easier to "roll your > > own" than lisp macros. > > Quite right, I forgot rebol. > > I played with it briefly and it is a lot of fun for network > programming, I'm well-acquainted with one 'shop' where hundreds of perl scripts are running doing regex work and hundreds of rebol scripts are running doing TCP/IP stuff. > but ultimately I ran out of steam with it too > often so gave up. IMHO: rebol is more designed for small applications and is easy to 'get off the ground' with, but python's strict engineering and well-designed OOP scales better, so I use it for the larger applications. MTCW tj -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at btinternet.com Tue Nov 7 18:22:52 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Nov 2006 17:22:52 -0000 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas References: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> <455065C5.4000904@tds.net> Message-ID: Apropos of nothing at all... "Kent Johnson" wrote > Carroll, Barry wrote: >> ... consensus was that Python was much better than Ruby > > Sounds like you had a table full of Pythonistas. And Andreas, Danny and I also argued for Ruby. And elsewhere Tim making a case for Rebol. It just strikes me as interesting that on a Python oriented mailing list we have people arguing in defence of other languages! This is not something you see every day on the internet, and indicative of the nature of the Python community I think. :-) Alan G. From andreas at kostyrka.org Tue Nov 7 19:43:43 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 07 Nov 2006 19:43:43 +0100 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> <455065C5.4000904@tds.net> Message-ID: <1162925024.9452.27.camel@andi-lap> Am Dienstag, den 07.11.2006, 17:22 +0000 schrieb Alan Gauld: > Apropos of nothing at all... > > "Kent Johnson" wrote > > Carroll, Barry wrote: > >> ... consensus was that Python was much better than Ruby > > > > Sounds like you had a table full of Pythonistas. > > And Andreas, Danny and I also argued for Ruby. Please note, that I did not argue for Ruby. I just mentioned, that it's a valid choice, for most purposes where Python is a valid choice and the other way around. And I explained why I feel better with Python for my personal stuff; it doesn't change a thing that we have a mixed Ruby (frontend)/ Python (backend) landscape at the "office". > And elsewhere Tim making a case for Rebol. > > It just strikes me as interesting that on a Python oriented mailing > list we have people arguing in defence of other languages! This languages are tools. And I guess I know a number of other languages too, despite being a Python guy. ;) Andreas > is not something you see every day on the internet, and indicative > of the nature of the Python community I think. > > :-) > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20061107/8cf323c2/attachment.pgp From tim at johnsons-web.com Wed Nov 8 00:27:25 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 7 Nov 2006 14:27:25 -0900 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A4304595A17@eugsrv400.psc.pscnet.com> <455065C5.4000904@tds.net> Message-ID: <20061107232725.GE1780@johnsons-web.com> * Alan Gauld [061107 08:27]: > Apropos of nothing at all... > > "Kent Johnson" wrote > > Carroll, Barry wrote: > >> ... consensus was that Python was much better than Ruby > > > > Sounds like you had a table full of Pythonistas. > > And Andreas, Danny and I also argued for Ruby. > And elsewhere Tim making a case for Rebol. > > It just strikes me as interesting that on a Python oriented mailing > list we have people arguing in defence of other languages! This > is not something you see every day on the internet, and indicative > of the nature of the Python community I think. 1) - it speaks well for the python community that one can at all comment on the advantages of another language without negative repercussions. 2) - I find that I learn more and think for flexibly when I work in more than one language. If one is to earn a living as a programming - it's a rare job where one will code in one PL all the time. And after all, I read in some python books about the languages that influenced the development of python.... In fact, if you do web programming, avoiding having to do Javascript would be difficult - :-) tj > :-) > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From Barry.Carroll at psc.com Wed Nov 8 00:45:39 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 7 Nov 2006 15:45:39 -0800 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A1C@eugsrv400.psc.pscnet.com> > -----Original Message----- > Date: Tue, 07 Nov 2006 12:20:16 +0100 > From: Andreas Kostyrka > Subject: Re: [Tutor] Ruby Code Blocks vs. Python Lambdas > To: Alan Gauld > Cc: tutor at python.org > Message-ID: <1162898417.9452.18.camel at andi-lap> > Content-Type: text/plain; charset="us-ascii" > > Am Dienstag, den 07.11.2006, 09:56 +0000 schrieb Alan Gauld: > > "Carroll, Barry" wrote > > > > > Thank you for this post. I was in a discussion of Ruby vs. Python > > > at > > > lunch today. The consensus was that Python was much better than > > > Ruby in > > > all ways. > > That's bullshit. Python and Ruby are quite comparable. > <> Awwwww. And here I thought we had just decided that such language was unnecessary and unappreciated on this list. Why not just say, "I disagree", and avoid all the unpleasantness. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From Barry.Carroll at psc.com Wed Nov 8 01:18:04 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 7 Nov 2006 16:18:04 -0800 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A1D@eugsrv400.psc.pscnet.com> Hello again. > -----Original Message----- > Date: Tue, 7 Nov 2006 09:56:42 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] Ruby Code Blocks vs. Python Lambdas > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > "Carroll, Barry" wrote > <> > > > The consensus was that Python was much better than Ruby in > > all ways. > > That's a little hard on Ruby. There are many good features and several > of them are arguably improvements on Python. > <> > In case anybody's interested, I wasn't giving my own opinion on Ruby; I don't know enough to have an opinion on Ruby. Sadly I don't have time at present to study the language right now. That's one reason why I'm enjoying this discussion. > > I have struggled considerably with lambdas since taking up Python. > > I'm > > still not really comfortable using them in production code. I agree > > that Ruby's style is more intuitive and easier to use. I wonder if > > a > > future version of Python could adopt this style. > > I think it would be difficult without adding block delimiters to > the language, and most of the common symbols already > have a role ([],(),{}, |, etc). I think a solution could be found if the desire for the capability was there (e.g. <>, ``, ...). > Also Guido prefers explicit definition of functions to > anonymous ones - explicit is better than implicit is > one of Pythons principles after all. Correct indeed. But lambda functions ARE anonymous. "Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". http://www.secnetix.de/~olli/Python/lambda_functions.hawk So that principle has already been bent. Since code blocks are more flexible and more intuitive than lambdas, why not add them to the tool box? To quote some more principles: * Beautiful is better than ugly. * Readability counts. * ... practicality beats purity. > > Alan G. > Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From john at fouhy.net Wed Nov 8 03:55:54 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 8 Nov 2006 15:55:54 +1300 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A1D@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A1D@eugsrv400.psc.pscnet.com> Message-ID: <5e58f2e40611071855g461b2750lc630e8cbc5e4809e@mail.gmail.com> On 08/11/06, Carroll, Barry wrote: > Correct indeed. But lambda functions ARE anonymous. > > "Python supports the creation of anonymous functions (i.e. > functions that are not bound to a name) at runtime, using > a construct called "lambda". > http://www.secnetix.de/~olli/Python/lambda_functions.hawk > > So that principle has already been bent. Since code blocks are more > flexible and more intuitive than lambdas, why not add them to the tool > box? To quote some more principles: PEP3099 (http://www.python.org/dev/peps/pep-3099/) makes this seem unlikely.. -- John. From yqiang at gmail.com Tue Nov 7 23:57:02 2006 From: yqiang at gmail.com (Yi Qiang) Date: Tue, 7 Nov 2006 14:57:02 -0800 Subject: [Tutor] hardware specs from python on OSX Message-ID: <3af8969a0611071457l4b1b678dsd1d6c96f748d1bc0@mail.gmail.com> Hi, I am trying to get some basic information about the computer's hardware specs in OSX in python. In linux I can get most of what I need from the /proc filesystem. Is there an equivalent in OSX? If not, where else can I get information about the system from? I need CPU model, # of cpus, cpu speed, physical memory, etc. Thanks, Yi From dyoo at hkn.eecs.berkeley.edu Wed Nov 8 05:31:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 Nov 2006 20:31:31 -0800 (PST) Subject: [Tutor] hardware specs from python on OSX In-Reply-To: <3af8969a0611071457l4b1b678dsd1d6c96f748d1bc0@mail.gmail.com> References: <3af8969a0611071457l4b1b678dsd1d6c96f748d1bc0@mail.gmail.com> Message-ID: On Tue, 7 Nov 2006, Yi Qiang wrote: > I am trying to get some basic information about the computer's hardware > specs in OSX in python. In linux I can get most of what I need from the > /proc filesystem. Is there an equivalent in OSX? If not, where else > can I get information about the system from? I need CPU model, # of > cpus, cpu speed, physical memory, etc. Hi Yi, This is a bit platform-specific; I'm not sure if we can help you with this. You may want to ask this on the MacPython mailing list: http://www.python.org/community/sigs/current/pythonmac-sig/ Good luck! From wescpy at gmail.com Wed Nov 8 05:47:26 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 7 Nov 2006 20:47:26 -0800 Subject: [Tutor] is gotchas? In-Reply-To: <45506822.1090406@tds.net> References: <20061106171601.GB1768@johnsons-web.com> <78b3a9580611061913s45b42006k25e3e2f6e7700c22@mail.gmail.com> <45506822.1090406@tds.net> Message-ID: <78b3a9580611072047p761662d1pb144799f20e49de4@mail.gmail.com> > > a is b <==> id(a) == id(b) > > No, not necessarily. id's are recycled which can lead to unexpected > behaviour when comparing them. See for example this thread on c.l.py: > http://tinyurl.com/yflknx wow, that is totally mind-blowing.. good post. i think that for most normal objects that are *not* created on the fly, the comparison is ok. still, i'd stick to using is... as-is. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Wed Nov 8 09:27:26 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Nov 2006 08:27:26 -0000 Subject: [Tutor] hardware specs from python on OSX References: <3af8969a0611071457l4b1b678dsd1d6c96f748d1bc0@mail.gmail.com> Message-ID: "Yi Qiang" wrote > I am trying to get some basic information about the computer's > hardware specs in OSX in python. In linux I can get most of what I > need from the /proc filesystem. Is there an equivalent in OSX? OSX is just BSD Unix so most things will be available in /proc. What happens when you try it? > not, where else can I get information about the system from? I need > CPU model, # of cpus, cpu speed, physical memory, etc. But I'm not sure if that specific info is available. The NSProcessInfo class also provides a lot of information, but mainly about the OS version etc, but it might have CPU details too, check the docs... HTH, Alan G. From ajkadri at googlemail.com Wed Nov 8 10:53:42 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 8 Nov 2006 09:53:42 +0000 Subject: [Tutor] Help needed to install SOAPpy Message-ID: Hi Folks, I want to install the SOAPpy module on my windows box. I have python 2.4.3 Can you help me with the steps and the URL from where can I get the download..?? TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/9ff7cdf6/attachment.html From chris.arndt at web.de Wed Nov 8 11:49:25 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 08 Nov 2006 11:49:25 +0100 Subject: [Tutor] Help needed to install SOAPpy In-Reply-To: References: Message-ID: <4551B635.6090500@web.de> Asrarahmed Kadri schrieb: > I want to install the SOAPpy module on my windows box. I have python > 2.4.3 > > Can you help me with the steps and the URL from where can I get the > download..?? What have you tried so far? Did you google for "SOAPpy download"? Are you experiencing any problems? Chris From antonioskatsikadamos at yahoo.com Wed Nov 8 11:52:08 2006 From: antonioskatsikadamos at yahoo.com (Antonios Katsikadamos) Date: Wed, 8 Nov 2006 02:52:08 -0800 (PST) Subject: [Tutor] module mx.DateTime Message-ID: <20061108105208.92273.qmail@web58102.mail.re3.yahoo.com> hi all folks. i am running python2.4 on suse linux and i would like to install the module mx.DateTime. does anyone know how i can install it? thanks for any help, Antonios --------------------------------- Sponsored Link Mortgage rates near 39yr lows. $420,000 Mortgage for $1,399/mo - Calculate new house payment -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/7d050383/attachment.html From greenbergj at wit.edu Wed Nov 8 05:29:23 2006 From: greenbergj at wit.edu (Jordan Greenberg) Date: Tue, 07 Nov 2006 23:29:23 -0500 Subject: [Tutor] hardware specs from python on OSX In-Reply-To: <3af8969a0611071457l4b1b678dsd1d6c96f748d1bc0@mail.gmail.com> References: <3af8969a0611071457l4b1b678dsd1d6c96f748d1bc0@mail.gmail.com> Message-ID: <45515D23.6080002@wit.edu> Yi Qiang wrote: > Hi, > I am trying to get some basic information about the computer's > hardware specs in OSX in python. In linux I can get most of what I > need from the /proc filesystem. Is there an equivalent in OSX? If > not, where else can I get information about the system from? I need > CPU model, # of cpus, cpu speed, physical memory, etc. > > Thanks, > Yi Somewhat unsurprisingly, a quick google for "python system information osx" turned up this recipe in the ActiveState cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303063 which should help. Looking into the sysctl command might also be useful. HTH, keep in mind that I'm *NOT* a Mac guy, at all. Jordan From ajkadri at googlemail.com Wed Nov 8 12:08:46 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 8 Nov 2006 11:08:46 +0000 Subject: [Tutor] My attempt...Re: Help needed to install SOAPpy Message-ID: Here is what I did. I searched through Google and found this URL: http://pywebsvcs.sourceforge.net/soappy.txt . Here it is mentioned that to install teh soappy, there are two modules that need to be installed before we can successfully install teh soappy module. the fist one is pyxml and the other one is fpconst. I installed the pyxml module, but the link for installing fpconst is not working. Any idea. BEst Regards, Asrarahmed On 11/8/06, Christopher Arndt wrote: > > Asrarahmed Kadri schrieb: > > I want to install the SOAPpy module on my windows box. I have python > > 2.4.3 > > > > Can you help me with the steps and the URL from where can I get the > > download..?? > > What have you tried so far? Did you google for "SOAPpy download"? > Are you experiencing any problems? > > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/1d03fa46/attachment.html From kent37 at tds.net Wed Nov 8 12:17:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Nov 2006 06:17:05 -0500 Subject: [Tutor] Help me with installing Soappymodule In-Reply-To: References: Message-ID: <4551BCB1.9090006@tds.net> Asrarahmed Kadri wrote: > > Hi Folks, > > I want to install SOAPpy module. As stated on > http://pywebsvcs.sourceforge.net/soappy.txt, there are two modules that > should be installed prior to installing SOAPpy. One in pyXML and the > other is fpconst. I installed pyXML from the URL stated on teh above > website. > But the URL for fpconst download is not valid. > > Any idea as to where can I get the module . Try this one: http://cheeseshop.python.org/pypi/fpconst/0.7.2 Kent From chris.arndt at web.de Wed Nov 8 12:23:25 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 08 Nov 2006 12:23:25 +0100 Subject: [Tutor] module mx.DateTime In-Reply-To: <20061108105208.92273.qmail@web58102.mail.re3.yahoo.com> References: <20061108105208.92273.qmail@web58102.mail.re3.yahoo.com> Message-ID: <4551BE2D.40603@web.de> Antonios Katsikadamos schrieb: > hi all folks. i am running python2.4 on suse linux and i would like to > install the module mx.DateTime. does anyone know how i can install it? If you want to install it from the source code, you need a C compiler and the Python development package. I don't know exactly, how these packages are called on suse, but I expect something like "gcc" and "python-devel" or "python-dev". Then it's the usual unpacking and "python setup.py install". But probably suse already has rpm packages for mxDateTime. Probably it is called something like egenix-mxdatetime or egenix-extensions. Do you have any specific need for mx.DateTime? Nowadays you can do almost everything you can do with mx.DateTime with the standard library module "datetime" and "dateutil" from http://labix.org/python-dateutil Chris From ajkadri at googlemail.com Wed Nov 8 12:24:43 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 8 Nov 2006 11:24:43 +0000 Subject: [Tutor] Can I run multiple python versions on the same machine.. I plan to install Python Enthought Edition Message-ID: Hi Folks, Just a quick advice of using Python Enthought Edition along with ActiveState Python. TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/3804b48c/attachment.htm From tomdrak at gmail.com Wed Nov 8 12:15:28 2006 From: tomdrak at gmail.com (tomd) Date: Wed, 8 Nov 2006 12:15:28 +0100 Subject: [Tutor] My attempt...Re: Help needed to install SOAPpy In-Reply-To: Message-ID: <2006118121528.909959@oem-up3sjowr2u8> http://www.warnes.net/rwndown or if that link doesn't work for you, just google it. -- Regards, Tom http://www.vscripts.net/ on Wed, 8 Nov 2006 11:08:46 +0000, you wrote: > I installed the pyxml module, but the link for installing fpconst is not working. From carloslara at web.de Wed Nov 8 13:00:30 2006 From: carloslara at web.de (Carlos) Date: Wed, 08 Nov 2006 13:00:30 +0100 Subject: [Tutor] First real script In-Reply-To: References: Message-ID: <4551C6DE.3030200@web.de> Hi Again, Luke, I left it this way now: x = A_List[i-1] y = A_List[i] z = A_List[(i+1) % A_Len] Probably the other way is shorter but right now I feel comfortable as it is now :-[ , Danny had already mentioned this method before, but it didn't sink properly until now. And yes I need it to wrap around because if not the behavior changes, at least it happened in my tests. Now I'm tring to make it possible to choose which rule to use, my first idea was: R_30 = [0,0,0,1,1,1,1,0] R_110 = [0,1,1,0,1,1,1,0] R = R_110 rule = { (1, 1, 1) : R[0], (1, 1, 0) : R[1], (1, 0, 1) : R[2], (1, 0, 0) : R[3], (0, 1, 1) : R[4], (0, 1, 0) : R[5], (0, 0, 1) : R[6], (0, 0, 0) : R[7], } I believe that in this way all possible rules could be defined by a list. The problem is that I'm going to need 256 lists. What would be real nice is to input a number, lets say 30 and have it converted to binary notation so it would look like 1110, then add enough zeros to the left and end up with 0001110, and finally convert this to a list than can be referenced in the dictionary. Here is the code: #This is a hacked version of 'tobinary' from: #http://gnosis.python-hosting.com/voting-project/OVC-Demo2/att-0020/convert.py def tobinary(dec): """Convert a decimal number to binary. Parameters: dec: The decimal number """ bin = [] while dec > 0: bit = int(dec % 2) bin.insert(0, bit) dec = (dec - bit)/2 print bin ## This area formats a Bin number between 0 and 255 ## so it conforms with CA rules formatting b_len = len(bin) print 'b_len: ', b_len while b_len < 8: bin[0:0] = [0] b_len = len(bin) print bin tobinary(30) Is this a good way to proceed? Alan, about going 3D, I agree a normal 2D list will do, but I'm really afraid of the list wrapping, this time squared (or is it cubed?). I'm going to need rules for center, corner and border cells. I'm afraid... Thanks a lot, Carlos From antonioskatsikadamos at yahoo.com Wed Nov 8 15:23:36 2006 From: antonioskatsikadamos at yahoo.com (Antonios Katsikadamos) Date: Wed, 8 Nov 2006 06:23:36 -0800 (PST) Subject: [Tutor] python Error: IndentationError: expected an indented block. Message-ID: <20061108142336.99373.qmail@web58113.mail.re3.yahoo.com> hi all. I am using python 2.4. I have to run an older python code and when i run it i get the following message IndentationError: expected an indented block. 1)what does this mean? 2)how can i overcome this problem Thanks for any advice. kind regards, Antonios --------------------------------- Sponsored Link Free Uniden 5.8GHz Phone System with Packet8 Internet Phone Service -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/1efea01b/attachment.html From ajkadri at googlemail.com Wed Nov 8 15:23:50 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 8 Nov 2006 14:23:50 +0000 Subject: [Tutor] Unable to run a simple client server code in in SOAPpy... Help me Message-ID: Hi, I have successfully installed the SOAPpy module. The version is 0.11.6 I am trying to run simple test program for server and cliet. The script for server is executing without any error; but the client script is giving me the error as below. *TRACEBACK:* C:\project stuff-programs>python client.py Traceback (most recent call last): File "client.py", line 4, in ? print server.hello() File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 453, in __call__ return self.__r_call(*args, **kw) File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 475, in __r_call self.__hd, self.__ma) File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 347, in __call config = self.config) File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in call r.endheaders() File "C:\Python24\lib\httplib.py", line 798, in endheaders self._send_output() File "C:\Python24\lib\httplib.py", line 679, in _send_output self.send(msg) File "C:\Python24\lib\httplib.py", line 646, in send self.connect() File "C:\Python24\lib\httplib.py", line 630, in connect raise socket.error, msg socket.error: (10061, 'Connection refused') *#server.py* import SOAPpy def hello(): return "Hello World" server = SOAP.SOAPServer(("localhost", 23000)) server.registerFunction(hello) server.serve_forever() *# client.py* import SOAPpy server = SOAPpy.SOAPProxy("http://localhost:23000/") print server.hello() TIA. Best Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/d8769975/attachment-0001.htm From rabidpoobear at gmail.com Wed Nov 8 15:29:16 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 08 Nov 2006 08:29:16 -0600 Subject: [Tutor] Unable to run a simple client server code in in SOAPpy... Help me In-Reply-To: References: Message-ID: <4551E9BC.7010903@gmail.com> Asrarahmed Kadri wrote: > > > > socket.error: (10061, 'Connection refused') Sounds like your firewall is blocking communication on this port. From kent37 at tds.net Wed Nov 8 16:03:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Nov 2006 10:03:56 -0500 Subject: [Tutor] python Error: IndentationError: expected an indented block. In-Reply-To: <20061108142336.99373.qmail@web58113.mail.re3.yahoo.com> References: <20061108142336.99373.qmail@web58113.mail.re3.yahoo.com> Message-ID: <4551F1DC.5080607@tds.net> Antonios Katsikadamos wrote: > hi all. I am using python 2.4. I have to run an older python code and > when i run it i get the following message > > IndentationError: expected an indented block. > > 1)what does this mean? > 2)how can i overcome this problem Python uses indentation to delimit blocks, for example an if statement will be followed by an indented block: if a < b: print 'a is less than b' One way you can get this error is if you mix tabs and spaces for the indent character. Common usage is to use four spaces for an indent. Check that your code is consistent in its use of tabs or spaces. It's also possible that you are just missing a character or two. Posting actual code and the full error message including the traceback might help, though whitespace problems might be hidden in email. Kent > > > Thanks for any advice. > > kind regards, > > Antonios > > ------------------------------------------------------------------------ > Sponsored Link > > Free Uniden 5.8GHz Phone System with Packet8 Internet Phone Service > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From antonioskatsikadamos at yahoo.com Wed Nov 8 16:45:26 2006 From: antonioskatsikadamos at yahoo.com (Antonios Katsikadamos) Date: Wed, 8 Nov 2006 07:45:26 -0800 (PST) Subject: [Tutor] python error: IndentationError: expected an indented block Message-ID: <20061108154527.12936.qmail@web58108.mail.re3.yahoo.com> hi all. I try to run an old python code and i get the following message File "/home/antonis/db/access.py", line 119 def DoCsubnet1 (action, subject, target, args): # DoC servers net ^ IndentationError: expected an indented block 1) and I don't know what causes it. I would be grate full if you could give me a tip. 2) how can i overcome it? Can i use the keyword pass? Kind regards, Antonios --------------------------------- Want to start your own business? Learn how on Yahoo! Small Business. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/4dc3cd02/attachment.htm From antonioskatsikadamos at yahoo.com Wed Nov 8 16:49:19 2006 From: antonioskatsikadamos at yahoo.com (Antonios Katsikadamos) Date: Wed, 8 Nov 2006 07:49:19 -0800 (PST) Subject: [Tutor] python Error:IndentationError: expected an indented block Message-ID: <20061108154919.14248.qmail@web58108.mail.re3.yahoo.com> hi all. I try to run an old python code and i get the following message File "/home/antonis/db/access.py", line 119 def DoCsubnet1 (action, subject, target, args): # DoC servers net ^ IndentationError: expected an indented block 1) and I don't know what causes it. I would be grate full if you could give me a tip. 2) how can i overcome it? Can i use the keyword pass?and if how ccan i use it Kind regards, Antonios --------------------------------- Sponsored Link Degrees online in as fast as 1 Yr - MBA, Bachelor's, Master's, Associate - Click now to apply -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/4108083c/attachment.htm From kent37 at tds.net Wed Nov 8 16:59:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Nov 2006 10:59:23 -0500 Subject: [Tutor] python error: IndentationError: expected an indented block In-Reply-To: <20061108154527.12936.qmail@web58108.mail.re3.yahoo.com> References: <20061108154527.12936.qmail@web58108.mail.re3.yahoo.com> Message-ID: <4551FEDB.4040908@tds.net> Antonios Katsikadamos wrote: > hi all. I try to run an old python code and i get the following message > > File "/home/antonis/db/access.py", line 119 > def DoCsubnet1 (action, subject, target, args): # DoC > servers net > ^ > IndentationError: expected an indented block > > 1) and I don't know what causes it. I would be grate full if you could > give me a tip. Please show the code at line 119. It is expecting the line you show to be indented more than it is. > > 2) how can i overcome it? Can i use the keyword pass? > > > Kind regards, > > Antonios > > ------------------------------------------------------------------------ > Want to start your own business? Learn how on Yahoo! Small Business. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hmm at woolgathering.cx Wed Nov 8 17:06:04 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Wed, 8 Nov 2006 11:06:04 -0500 Subject: [Tutor] Encoding and XML troubles In-Reply-To: <454E098F.6020105@v.igoro.us> References: <20061104210429.GA31439@sillyrabbi.dyndns.org> <454E065B.2010700@tds.net> <454E098F.6020105@v.igoro.us> Message-ID: <20061108160604.GA23842@sillyrabbi.dyndns.org> Thanks for the help thusfar. To recap - when parsing XML, ElementTree is barfing on extended characters. 1. Yes, most XML is written by monkeys, or the programs written by such monkeys - tough beans, I cannot make my input XML any cleaner without pre-processing - I am not generating it. 2. The documentation suggests that the default encoding of ElementTree is US-ASCII, which is not going to be sufficient. My XML is explicitly setting its encoding to 8859-1, and the XML is actually well-formed(!). 3. I muddied the waters by talking about Python code listing encoding, sorry. EXAMPLES: Vanilla (this works fine): #!/usr/bin/python from elementtree import ElementTree as etree eg = """redblue""" xml = etree.fromstring(eg) If I change the example string to this: redblu? I get the following error: xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 32) Okay, the default encoding for my program (and thus my example string) is US-ASCII, so I'll use 8859-1 instead, adding this line: # coding: iso-8859-1 I get the same error. Just for laughs I'll change the encoding to utf-8. Oops, I get the same error. Has anyone had any luck getting ElementTree to deal with extended characters? If not, has anyone got a suggestion for how to pre-process the text in the XML so it won't barf? Thanks. -- yours, William From wavingbrain at gmail.com Wed Nov 8 16:56:09 2006 From: wavingbrain at gmail.com (Waving Brain) Date: Wed, 8 Nov 2006 09:56:09 -0600 Subject: [Tutor] python Error:IndentationError: expected an indented block In-Reply-To: <20061108154919.14248.qmail@web58108.mail.re3.yahoo.com> References: <20061108154919.14248.qmail@web58108.mail.re3.yahoo.com> Message-ID: <55c516fa0611080756q462df9f0q16c2665459f4fe40@mail.gmail.com> Use the "pass" keyword like this: def DoCsubnet1 (action, subject, target, args): # DoC servers net pass On 11/8/06, Antonios Katsikadamos wrote: > hi all. I try to run an old python code and i get the following message > > File "/home/antonis/db/access.py", line 119 > def DoCsubnet1 (action, subject, target, args): # DoC > servers net > ^ > IndentationError: expected an indented block > > 1) and I don't know what causes it. I would be grate full if you could give > me a tip. > > 2) how can i overcome it? Can i use the keyword pass?and if how ccan i use > it > > > Kind regards, > > Antonios > > ________________________________ > Sponsored Link > > Degrees online in as fast as 1 Yr - MBA, Bachelor's, Master's, Associate - > Click now to apply > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From dyoo at hkn.eecs.berkeley.edu Wed Nov 8 18:01:27 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Nov 2006 09:01:27 -0800 (PST) Subject: [Tutor] Encoding and XML troubles In-Reply-To: <20061108160604.GA23842@sillyrabbi.dyndns.org> References: <20061104210429.GA31439@sillyrabbi.dyndns.org> <454E065B.2010700@tds.net> <454E098F.6020105@v.igoro.us> <20061108160604.GA23842@sillyrabbi.dyndns.org> Message-ID: > Vanilla (this works fine): > #!/usr/bin/python > > from elementtree import ElementTree as etree > > eg = """redblue""" > > xml = etree.fromstring(eg) > > If I change the example string to this: > redblu? > > I get the following error: > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, > column 32) According to: http://mail.python.org/pipermail/xml-sig/2006-May/011513.html the XML content must declare itself what encoding it uses. For example: ##################################################################### >>> text = """

\xed\x95\x98\xeb\xa3\xa8\xeb\x8f\x99\xec\x95\x88 IDLE\xea\xb0\x80\xec\xa7\x80\xea\xb3\xa0 \xeb\x86\x80\xea\xb8\xb0

""" ##################################################################### Note that the encoding declaration must be on the top of the document. Then it's ok to use fromstring() on it: ################################################## >>> doc = elementtree.ElementTree.fromstring(text) >>> doc.text u'\ud558\ub8e8\ub3d9\uc548\nIDLE\uac00\uc9c0\uace0 \ub180\uae30' ################################################## If I use the wrong encoding declaration, or if I'm missing the declaration altogether, then yes, I see the same errors that you seen. > Okay, the default encoding for my program (and thus my example string) > is US-ASCII, so I'll use 8859-1 instead, adding this line: # coding: > iso-8859-1 > > I get the same error. Just for laughs I'll change the encoding to > utf-8. Oops, I get the same error. The XML encoding has to be explicitely described as part of the XML document text. It's the difference between: ########################################################################### >>> text = 'redblu\xe9' >>> import elementtree.ElementTree >>> elementtree.ElementTree.fromstring(text) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/elementtree/ElementTree.py", line 960, in XML parser.feed(text) File "/usr/lib/python2.4/site-packages/elementtree/ElementTree.py", line 1242, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 32 ########################################################################## and: ########################################################## >>> text = ''' ... redblu\xe9''' >>> doc = elementtree.ElementTree.fromstring(text) ########################################################## which does work. If you're dealing with XML content, make sure that your XML documents have that encoding declaration, or else you're bound to run into these kinds of errors. Good luck! From alan.gauld at btinternet.com Wed Nov 8 19:33:22 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Nov 2006 18:33:22 -0000 Subject: [Tutor] python Error:IndentationError: expected an indented block References: <20061108154919.14248.qmail@web58108.mail.re3.yahoo.com> Message-ID: "Antonios Katsikadamos" wrote > hi all. I try to run an old python code and i get the following > message > > File "/home/antonis/db/access.py", line 119 > def DoCsubnet1 (action, subject, target, args): # > DoC servers net > ^ > IndentationError: expected an indented block > > 1) and I don't know what causes it. I would be grate full if you > could give me a tip. > > 2) how can i overcome it? Can i use the keyword pass?and if how ccan > i use it Please don't just keep posting the same question over and over. Kent has already explained what an indentation error is and asked you to post the actual code plus the error message. We cannot give you any more help with the data you have given us. We need to see the code to work out what is wrong. If the code file is very long then send, say, 10 lines before and after the line that the error is reported on. Alan G. From ajkadri at googlemail.com Wed Nov 8 19:49:11 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 8 Nov 2006 18:49:11 +0000 Subject: [Tutor] Please help to resolve this... Message-ID: Hi, I have successfully installed the SOAPpy module. The version is 0.11.6 I am trying to run simple test program for server and cliet. The script for server is executing without any error; but the client script is giving me the error as below. *TRACEBACK:* C:\project stuff-programs>python client.py Traceback (most recent call last): File "client.py", line 4, in ? print server.hello() File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 453, in __call__ return self.__r_call(*args, **kw) File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 475, in __r_call self.__hd, self.__ma) File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 347, in __call config = self.config) File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in call r.endheaders() File "C:\Python24\lib\httplib.py", line 798, in endheaders self._send_output() File "C:\Python24\lib\httplib.py", line 679, in _send_output self.send(msg) File "C:\Python24\lib\httplib.py", line 646, in send self.connect() File "C:\Python24\lib\httplib.py", line 630, in connect raise socket.error, msg socket.error: (10061, 'Connection refused') *#server.py* import SOAPpy def hello(): return "Hello World" server = SOAP.SOAPServer(("localhost", 23000)) server.registerFunction(hello) server.serve_forever() *# client.py* import SOAPpy server = SOAPpy.SOAPProxy("http://localhost:23000/") print server.hello() TIA. Best Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/ba4b23ef/attachment.html From andreas at kostyrka.org Wed Nov 8 20:01:20 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 8 Nov 2006 20:01:20 +0100 Subject: [Tutor] Please help to resolve this... In-Reply-To: References: Message-ID: <20061108190120.GB1392@andi-lap.la.revver.com> * Asrarahmed Kadri [061108 19:51]: > Hi, > > I have successfully installed the SOAPpy module. The version is 0.11.6 > > I am trying to run simple test program for server and cliet. The script for > server is executing without any error; but the client script is giving me Well, the error means that nothing is listening on port 23000 on localhost. Firewall? Andreas From rabidpoobear at gmail.com Wed Nov 8 20:00:16 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 08 Nov 2006 13:00:16 -0600 Subject: [Tutor] Please help to resolve this... In-Reply-To: References: Message-ID: <45522940.8040509@gmail.com> Asrarahmed Kadri wrote: > Hi, Asrarahmed: You posted this exact question only 4 hours ago. Reposting questions this quickly is an abuse of the mailing list, as far as I'm concerned. If you don't wait at _minimum_ a full day, preferably at least 2, for an answer, it just irritates people and makes it less likely for you to get an answer. People may completely disregard this question now, just as a matter of principle, so that they don't give you the idea that reposting is appreciated. Not mad or anything, just informing you. HTH, -Luke From dyoo at hkn.eecs.berkeley.edu Wed Nov 8 21:05:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Nov 2006 12:05:14 -0800 (PST) Subject: [Tutor] Please help to resolve this... In-Reply-To: References: Message-ID: > *#server.py* > import SOAPpy > > > def hello(): > return "Hello World" > > server = SOAP.SOAPServer(("localhost", 23000)) > server.registerFunction(hello) > server.serve_forever() Hi Asrarahmed, I also want to reiterate what Luke said: it does get a little irritating if we see the same question repeated. Try reading: http://catb.org/esr/faqs/smart-questions.html to get a better feel for what kind of things help us answer your questions better. Have you tried running server.py? There's a glaring error in it. (Hint: SOAP != SOAPpy) I know it might sound silly, but just to make sure you understand: the server must be up and running before you try contacting it with the client. Also, you may want to reconsider SOAPpy: we've had previous discussion where it was apparent SOAPpy is a dead project: http://mail.python.org/pipermail/tutor/2006-November/050530.html From dyoo at hkn.eecs.berkeley.edu Wed Nov 8 21:10:03 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Nov 2006 12:10:03 -0800 (PST) Subject: [Tutor] Please help to resolve this... In-Reply-To: References: Message-ID: >> def hello(): >> return "Hello World" >> >> server = SOAP.SOAPServer(("localhost", 23000)) >> server.registerFunction(hello) >> server.serve_forever() > > Have you tried running server.py? There's a glaring error in it. (Hint: SOAP > != SOAPpy) Actually, there's a much more glaring error in it. Note the early exit from 'return "hello world". The program is escaping out too quickly. From pyro9219 at gmail.com Wed Nov 8 23:56:56 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 8 Nov 2006 14:56:56 -0800 Subject: [Tutor] Questions about PIL Message-ID: I'm trying to figure out how to compare im1 to im2 and recognize the difference. I dont care what the difference is... something like if im1 is not im2: print "Not same" I've tried im.tostring() but that doesn't ever enter the loop either. ******************************************************************************************* Second question is this: Is there a way to divide the screen so I only grab maybe the lower right 200x200 pixels or some such? Or possibly a way to seperate the image into a grid so I could just take the grid I wanted? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/e2173d0b/attachment.htm From rabidpoobear at gmail.com Thu Nov 9 00:16:31 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 08 Nov 2006 17:16:31 -0600 Subject: [Tutor] Questions about PIL In-Reply-To: References: Message-ID: <4552654F.6070300@gmail.com> Chris Hengge wrote: > I'm trying to figure out how to compare im1 to im2 and recognize the > difference. I dont care what the difference is... > > something like > > if im1 is not im2: > print "Not same" Hey, Chris. I'm supposing here that you are checking if the images are _visually_ different, not if they are different objects or files. Remember when we were talking about the VNC? Specifically, the line diff = ImageChops.difference(self.prevscr,self.currscr) that I sent to you? To sum it up, in the ImageChops module, (which comes with PIL) there's a function called difference that returns a list with the different pixel values for each coordinate of the image. I would suggest the following course of action: 1) Check if the file format is the same. If it's a PNG vs a JPG vs a BMP or whatever, the compression routines will have an effect on the image, so your difference test won't work. 2) Check if the resolution is the same. If one's 640X480 and the other's 800X600, you're going to have a difference. 3) do the following ( or something equivalent): from ImageChops import difference alist = difference(image1,image2) a = [b for b in alist.getdata() if b != (0,0,0)] if len(a) != 0: print "Not the same" > > I've tried im.tostring () but that doesn't ever enter the loop either. I have no idea what 'that doesn't ever enter the loop' means. > > ******************************************************************************************* > Second question is this: > Is there a way to divide the screen so I only grab maybe the lower > right 200x200 pixels or some such? > Or possibly a way to seperate the image into a grid so I could just > take the grid I wanted? You're referring to when you're using ImageGrab.grab() I assume, but you should have said this. It's better to be explicit than implicit, after all :) Yes, it's possible to grab only part of the screen. ImageGrab.grab(), if you read the help information on it, says that it takes a bbox argument with a default value of none. so override this value with your own bounding box. I.E. ImageGrab.grab((0,0,200,200)) will grab a square from the upper-left corner of the screen. Separating the image into a grid would also be quite easy. If you have an Image instance, just use its crop method to get the area you want. example: import Image im = Image.open('test.bmp') im.crop((0,0,200,200)).save('test.bmp') Should overwrite the old image with a new one. Also, note that the code: ImageGrab.grab().crop((0,0,200,200)) is equivalent to ImageGrab.grab((0,0,200,200)) In other words, the ImageGrab always takes a screenshot of the entire working area. so if you're expecting this bounding-box to speed anything up, it won't. HTH, -Luke > Thanks! > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Thu Nov 9 00:30:05 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 Nov 2006 15:30:05 -0800 (PST) Subject: [Tutor] Questions about PIL In-Reply-To: References: Message-ID: On Wed, 8 Nov 2006, Chris Hengge wrote: > I'm trying to figure out how to compare im1 to im2 and recognize the > difference. I dont care what the difference is... > > something like > > if im1 is not im2: > print "Not same" Do not use 'is' here. It is not doing any kind of equality testing at all. We had a discussion about 'is' just a few days ago: http://mail.python.org/pipermail/tutor/2006-November/050680.html According to: http://www.pythonware.com/library/pil/handbook/image.htm the im.getdata() function looks interesting. > I've tried im.tostring() but that doesn't ever enter the loop either. This should have worked. I'm not sure if you tried comparing two strings using 'is' or not. > Second question is this: > Is there a way to divide the screen so I only grab maybe the lower right > 200x200 pixels or some such? > Or possibly a way to seperate the image into a grid so I could just take the > grid I wanted? im.transform() from the documentation link above looks relevant. Is that what you're looking for? From pyro9219 at gmail.com Thu Nov 9 00:51:02 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 8 Nov 2006 15:51:02 -0800 Subject: [Tutor] Questions about PIL In-Reply-To: <4552654F.6070300@gmail.com> References: <4552654F.6070300@gmail.com> Message-ID: Thanks for the detailed examples again Luke. Sorry I wasn't more clear with my implimentation. The loop I was refering to was the one in the start of my post but using im.tostring() instead. I saw an example to make a webcam motion detector that used tostring(), but couldn't get the program to see a difference. As for just capturing a section of the screen. I'm not looking to make faster captures, so I think your sample was on the ball. Your example however wasn't quite what I had in mind when I was thinking up the question and again I take fault for this. I was thinking more of a way to create quadrants of the screenshot. (Or any number of area's) that I could independantly interact with. I know this isn't a CPU friendly task, but just humor me please =P On 11/8/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I'm trying to figure out how to compare im1 to im2 and recognize the > > difference. I dont care what the difference is... > > > > something like > > > > if im1 is not im2: > > print "Not same" > Hey, Chris. > I'm supposing here that you are checking if the images are _visually_ > different, > not if they are different objects or files. > > Remember when we were talking about the VNC? > Specifically, the line > diff = ImageChops.difference(self.prevscr,self.currscr) > that I sent to you? > > To sum it up, in the ImageChops module, > (which comes with PIL) > there's a function called difference that returns a list with the > different pixel values for each coordinate of the image. > > I would suggest the following course of action: > 1) Check if the file format is the same. If it's a PNG vs a JPG vs a > BMP or whatever, the compression routines > will have an effect on the image, so your difference test won't work. > 2) Check if the resolution is the same. If one's 640X480 and the > other's 800X600, you're going to have a difference. > 3) do the following ( or something equivalent): > from ImageChops import difference > alist = difference(image1,image2) > a = [b for b in alist.getdata() if b != (0,0,0)] > if len(a) != 0: > print "Not the same" > > > > I've tried im.tostring () but that doesn't ever enter the loop either. > I have no idea what 'that doesn't ever enter the loop' means. > > > > > ******************************************************************************************* > > Second question is this: > > Is there a way to divide the screen so I only grab maybe the lower > > right 200x200 pixels or some such? > > Or possibly a way to seperate the image into a grid so I could just > > take the grid I wanted? > You're referring to when you're using ImageGrab.grab() I assume, > but you should have said this. It's better to be explicit than > implicit, after all :) > > Yes, it's possible to grab only part of the screen. > ImageGrab.grab(), if you read the help information on it, > says that it takes a bbox argument with a default value of none. > so override this value with your own bounding box. > I.E. ImageGrab.grab((0,0,200,200)) will grab a square from the > upper-left corner of the screen. > > Separating the image into a grid would also be quite easy. > If you have an Image instance, just use its crop method to get the area > you want. > example: > import Image > im = Image.open('test.bmp') > im.crop((0,0,200,200)).save('test.bmp') > > Should overwrite the old image with a new one. > > Also, note that the code: > ImageGrab.grab().crop((0,0,200,200)) > is equivalent to > ImageGrab.grab((0,0,200,200)) > > In other words, > the ImageGrab always takes a screenshot of the entire working area. > so if you're expecting this bounding-box to speed anything up, it won't. > > HTH, > -Luke > > > Thanks! > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/760e3e9e/attachment.htm From pyro9219 at gmail.com Thu Nov 9 01:18:58 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 8 Nov 2006 16:18:58 -0800 Subject: [Tutor] Questions about PIL In-Reply-To: References: Message-ID: I tried the .tostring again, seems to be working using != instead of is not... Thanks for that thread link, very helpful. I'll look more into im.transform and see what I can come up with. I'm not sure I fully understand what it does, but I'm reading it as I'll remove the wanted section of im and trash the rest. I'm more-so looking for a way to maybe divide an image into quantrants for individual manipulation without having to split and rebuild the image. My goal with these two features is I'd like to create a way to compare an image for changes based on an area of the image, rather then the entire image. Lets use the quadrants for example (mental code). 1,2 3,4 ^ this is how the quad appears on the image (upper left, upper right, etc...) for space in quad: if newpic[space].tostring() != oldpic[space].tostring(): oldpic[space] = newpic[space] else : # Dont really care because this [space] isn't important. On 11/8/06, Danny Yoo wrote: > > > > On Wed, 8 Nov 2006, Chris Hengge wrote: > > > I'm trying to figure out how to compare im1 to im2 and recognize the > > difference. I dont care what the difference is... > > > > something like > > > > if im1 is not im2: > > print "Not same" > > Do not use 'is' here. It is not doing any kind of equality testing at > all. We had a discussion about 'is' just a few days ago: > > http://mail.python.org/pipermail/tutor/2006-November/050680.html > > According to: > > http://www.pythonware.com/library/pil/handbook/image.htm > > the im.getdata() function looks interesting. > > > > I've tried im.tostring() but that doesn't ever enter the loop either. > > This should have worked. I'm not sure if you tried comparing > two strings using 'is' or not. > > > Second question is this: > > Is there a way to divide the screen so I only grab maybe the lower right > > 200x200 pixels or some such? > > Or possibly a way to seperate the image into a grid so I could just take > the > > grid I wanted? > > im.transform() from the documentation link above looks relevant. Is that > what you're looking for? > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/797e740f/attachment.html From kdidriksson at gmail.com Thu Nov 9 02:25:51 2006 From: kdidriksson at gmail.com (Kristinn Didriksson) Date: Wed, 8 Nov 2006 20:25:51 -0500 Subject: [Tutor] Drawing simple graphics objects Message-ID: <55B2FF94-0A9D-4FBB-BBFC-F80FA6AFCB06@gmail.com> Hello, This is one of the questions in Python Programming by Zelle. Ch 5, #1b. The problem calls for the program to create a new square at the mouse click instead of moving the square as in the previous problem. I have tried various ways to tackle the problem with no success. Any help would be greatly be appreciated. This is the code that works for the previous example and moved the square at the mouse click: ------ # Modify the example in the book to program to draw a square instead of a circle. # Interactive graphics program to draw a square from graphics import * def main(): win = GraphWin() shape = Rectangle(Point(50,50), Point(20,20)) shape.setOutline("red") shape.setFill("red") shape.draw(win) for i in range(10): p = win.getMouse() c = shape.getCenter() dx = p.getX() - c.getX() dy = p.getY() - c.getY() shape.move(dx,dy) win.close() main() #This one worked without too much trouble. All I had to do was change the object to be # drawn to a square! -------------------------- This is the mess i got myself into with the next problem. Please note that I initially tried to move the shape.draw(win) object to the beginning of the loop and I got an error that said: Traceback (most recent call last): File "/Users/krissd/Desktop/python/code_zelle/chapter5/1a.py", line 21, in main() File "/Users/krissd/Desktop/python/code_zelle/chapter5/1a.py", line 14, in main shape.draw(win) File "/Users/krissd/Desktop/python/code_zelle/chapter5/ graphics.py", line 280, in draw if self.canvas: raise GraphicsError, OBJ_ALREADY_DRAWN graphics.GraphicsError: ('O', 'b', 'j', 'e', 'c', 't', ' ', 'c', 'u', 'r', 'r', 'e', 'n', 't', 'l', 'y', ' ', 'd', 'r', 'a', 'w', 'n') 230-152:~/Desktop/python/code_zelle/chapter5 krissd$ Second program: This one draws squares, but not of the same dimensions as the first and not with the center at the mouse click. --------------------- # Modify the example in the book to program to draw a square instead of a circle. # Additionally, have a new square drawn each time the mouse is clicked. from graphics import * def main(): win = GraphWin() shape = Rectangle(Point(50,50), Point(20,20)) shape.setOutline("red") shape.setFill("red") shape.draw(win) for i in range(10): gui p = win.getMouse() c = shape.getCenter() dx = p.getX() # - c.getX() dy = p.getY() # - c.getY() shape = Rectangle(Point(dx,dx),Point(dy,dy)) shape.setOutline("red") shape.setFill("red") shape.draw(win) win.close() main() #This is turning out trickier than I thought! # I have gotten close. It redraws the square, but not with the same dimensions # at a different location determined by the mouse click. # I am barking up the wrong tree with this effort!!!! ---------------- I have attached the graphics package that is used in the program for reference. -------------- next part -------------- A non-text attachment was scrubbed... Name: graphics.py Type: text/x-python-script Size: 21426 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061108/51937d28/attachment-0001.bin -------------- next part -------------- One additional question. Zelle creates this graphics library to use to demonstrate GUI programming. I have seen discussions about tkinter and wxpython. Should I be trying to use one of them instead for these problems? Or would that be jumping ahead of the game? Regards, kristinn From pyro9219 at gmail.com Thu Nov 9 06:28:59 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 8 Nov 2006 21:28:59 -0800 Subject: [Tutor] Questions about PIL In-Reply-To: <4552654F.6070300@gmail.com> References: <4552654F.6070300@gmail.com> Message-ID: alist = difference(image1,image2) a = [b for b in alist.getdata() if b != (0,0,0)] if len(a) != 0: print "Not the same" is much slower then (9x) if im1.tostring() != im2.tostring() print "something changed!" This loop itself is fairly slow by itself though.. I'm going to try and see if there is a faster way. On 11/8/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I'm trying to figure out how to compare im1 to im2 and recognize the > > difference. I dont care what the difference is... > > > > something like > > > > if im1 is not im2: > > print "Not same" > Hey, Chris. > I'm supposing here that you are checking if the images are _visually_ > different, > not if they are different objects or files. > > Remember when we were talking about the VNC? > Specifically, the line > diff = ImageChops.difference(self.prevscr,self.currscr) > that I sent to you? > > To sum it up, in the ImageChops module, > (which comes with PIL) > there's a function called difference that returns a list with the > different pixel values for each coordinate of the image. > > I would suggest the following course of action: > 1) Check if the file format is the same. If it's a PNG vs a JPG vs a > BMP or whatever, the compression routines > will have an effect on the image, so your difference test won't work. > 2) Check if the resolution is the same. If one's 640X480 and the > other's 800X600, you're going to have a difference. > 3) do the following ( or something equivalent): > from ImageChops import difference > alist = difference(image1,image2) > a = [b for b in alist.getdata() if b != (0,0,0)] > if len(a) != 0: > print "Not the same" > > > > I've tried im.tostring () but that doesn't ever enter the loop either. > I have no idea what 'that doesn't ever enter the loop' means. > > > > > ******************************************************************************************* > > Second question is this: > > Is there a way to divide the screen so I only grab maybe the lower > > right 200x200 pixels or some such? > > Or possibly a way to seperate the image into a grid so I could just > > take the grid I wanted? > You're referring to when you're using ImageGrab.grab() I assume, > but you should have said this. It's better to be explicit than > implicit, after all :) > > Yes, it's possible to grab only part of the screen. > ImageGrab.grab(), if you read the help information on it, > says that it takes a bbox argument with a default value of none. > so override this value with your own bounding box. > I.E. ImageGrab.grab((0,0,200,200)) will grab a square from the > upper-left corner of the screen. > > Separating the image into a grid would also be quite easy. > If you have an Image instance, just use its crop method to get the area > you want. > example: > import Image > im = Image.open('test.bmp') > im.crop((0,0,200,200)).save('test.bmp') > > Should overwrite the old image with a new one. > > Also, note that the code: > ImageGrab.grab().crop((0,0,200,200)) > is equivalent to > ImageGrab.grab((0,0,200,200)) > > In other words, > the ImageGrab always takes a screenshot of the entire working area. > so if you're expecting this bounding-box to speed anything up, it won't. > > HTH, > -Luke > > > Thanks! > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061108/96e0cecd/attachment.html From rabidpoobear at gmail.com Thu Nov 9 08:31:03 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 09 Nov 2006 01:31:03 -0600 Subject: [Tutor] Questions about PIL In-Reply-To: References: <4552654F.6070300@gmail.com> Message-ID: <4552D937.9090306@gmail.com> Chris Hengge wrote: > alist = difference(image1,image2) > a = [b for b in alist.getdata() if b != (0,0,0)] > if len(a) != 0: > print "Not the same" > > is much slower then (9x) > > if im1.tostring() != im2.tostring() > print "something changed!" > > This loop itself is fairly slow by itself though.. I'm going to try > and see if there is a faster way. Chris, are you sure you know what a loop is? The only loop here is in the list comprehension. 'if' is not a loop. 'for' and 'while' are. In computer science, it's important to be clear in your use of terminology. It makes sense that my example was slow. I didn't really think to try converting them to strings. Any time you're trying to compare pixel values, it's going to take a while, cause remember, a 1024X768 image has 786,432 different pixels. I think your tostring comparison may be your best bet. From rabidpoobear at gmail.com Thu Nov 9 08:38:06 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 09 Nov 2006 01:38:06 -0600 Subject: [Tutor] Questions about PIL In-Reply-To: References: <4552654F.6070300@gmail.com> Message-ID: <4552DADE.2070907@gmail.com> Chris Hengge wrote: > Thanks for the detailed examples again Luke. Sorry I wasn't more clear > with my implimentation. The loop I was refering to was the one in the > start of my post but using im.tostring() instead. I saw an example to > make a webcam motion detector that used tostring(), but couldn't get > the program to see a difference. I'm glad the examples helped. See my other response about your use of the term 'loop.' > > As for just capturing a section of the screen. I'm not looking to make > faster captures, so I think your sample was on the ball. Your example > however wasn't quite what I had in mind when I was thinking up the > question and again I take fault for this. I was thinking more of a way > to create quadrants of the screenshot. (Or any number of area's) that > I could independantly interact with. I know this isn't a CPU friendly > task, but just humor me please =P Once again, you're not being explicit enough in explaining what you're trying to do. Specifically, your sentence "(Or any number of area's) that I could independently interact with" How are you trying to interact with them? Do you want them split into actual separate image files, into separate image objects, or what? The crop method I showed you will do any kind of splitting you want, you just have to think through what exactly you need to crop in any given situation. For example, (pseudocode) width = 1024/2 height = 768/2 image = load_image('imagename') quad1 = image.crop((0,0,width,height)) quad2 = image.crop((width,0,width,height)) quad3 = image.crop((0,height,width,height)) quad4 = image.crop((width,height,width,height)) note that width and height are the w/h of the quadrants, not of the image itself. since there are 4 quadrants (get it? quad = 4 ;) each width/height would be original_image_ * (.5) HTH, -Luke From rabidpoobear at gmail.com Thu Nov 9 09:36:44 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 09 Nov 2006 02:36:44 -0600 Subject: [Tutor] Drawing simple graphics objects In-Reply-To: <55B2FF94-0A9D-4FBB-BBFC-F80FA6AFCB06@gmail.com> References: <55B2FF94-0A9D-4FBB-BBFC-F80FA6AFCB06@gmail.com> Message-ID: <4552E89C.6070108@gmail.com> > > from graphics import * > > def main(): > > win = GraphWin() > shape = Rectangle(Point(50,50), Point(20,20)) > shape.setOutline("red") > shape.setFill("red") > shape.draw(win) > for i in range(10): gui What's this mysterious 'gui' floating out here? > p = win.getMouse() > c = shape.getCenter() > dx = p.getX() # - c.getX() > dy = p.getY() # - c.getY() > shape = Rectangle(Point(dx,dx),Point(dy,dy)) Do you understand what's happening here, and what you're trying to do? The standard way to define rectangles is topleft, and the width, and height, but this graphics library doesn't seem to do that (it uses absolute coordinates) one way to standardize this would be to define an intermediate function that will convert width, height values to absolute coordinates, so your code would look like this: # start code. from graphics import * def make_rect(topleft,size): return (Point(topleft[0],topleft[1]),Point(topleft[0]+size[0],topleft[1]+size[1])) def main(): win = GraphWin() shape = Rectangle(Point(50,50), Point(20,20)) shape.setOutline("red") shape.setFill("red") shape.draw(win) for i in range(10): p = win.getMouse() c = shape.getCenter() rect = make_rect((p.getX(),p.getY()),(30,30)) shape = Rectangle(rect[0],rect[1]) shape.setOutline("red") shape.setFill("red") shape.draw(win) win.close() main() #end code. Otherwise, you can just use the actual absolute values if you don't want to use this function... #start code from graphics import * def main(): win = GraphWin() shape = Rectangle(Point(50,50), Point(20,20)) shape.setOutline("red") shape.setFill("red") shape.draw(win) for i in range(10): p = win.getMouse() c = shape.getCenter() shape = Rectangle(Point(p.getX()+30,p.getY()+30), Point(p.getX(),p.getY())) shape.setOutline("red") shape.setFill("red") shape.draw(win) win.close() main() #end code. Note that both of these codes put the topleft of the image at the mouse cursor. If you want them to be centered, try to figure out how to do it yourself, and if you can't, of course, we're here to help :) > shape.setOutline("red") > shape.setFill("red") > shape.draw(win) > win.close() > main() > > #This is turning out trickier than I thought! > # I have gotten close. It redraws the square, but not with the same > dimensions > # at a different location determined by the mouse click. > # I am barking up the wrong tree with this effort!!!! The problem with your code was your usage of dx, dy. Look at the code I sent and see if you can see what the problem was. (I'm really tired now and I can't tell you exactly what is wrong without making an effort, and I'm saving myself for the Computer Ethics essay I have yet to write :) > ---------------- > > I have attached the graphics package that is used in the program for > reference. > ------------------------------------------------------------------------ > thanks for giving it as reference. If you could've pastebinned it or something it would've been nice cause it was quite a long file. > > ------------------------------------------------------------------------ > > > One additional question. Zelle creates this graphics library to use to > demonstrate GUI programming. I have seen discussions about tkinter and > wxpython. Should I be trying to use one of them instead for these > problems? Or would that be jumping ahead of the game? This graphics library is written in TKinter. I would be using pygame instead for these problems. The stuff I've seen so far, drawing rects, etc. has nothing to do with TKInter and wxpython. Those libraries are for making e-mail clients, web browsers, and stuff. things with lots of listboxes, scroll bars, and text. Not for playing with images. That's what pygame is for. But I think you should use the graphics library if you can, since it's what the book is written about, unless you really feel that you can dive into a new library without the book's help. HTH, -Luke From pyro9219 at gmail.com Thu Nov 9 10:32:57 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 9 Nov 2006 01:32:57 -0800 Subject: [Tutor] Questions about PIL In-Reply-To: <4552D937.9090306@gmail.com> References: <4552654F.6070300@gmail.com> <4552D937.9090306@gmail.com> Message-ID: Yes, I understand what a loop is, and there was a loop but I didn't write that code into my email because I didn't need commenting on it. Here is the code so its clear incase you really care =P from PIL import Image from PIL import ImageGrab import time capturedFrames = 100 count = 0 print "\nInitializing Engine..." newView = ImageGrab.grab() print "Engine Initilized Successfully!" raw_input("Press any key to begin...") print "\nInitializing capture cycle..." startClock = time.clock() for i in range(capturedFrames): # Here is the loop I was timing that I commented is extremely slow using the method you suggested. It does work however. oldView = newView newView = ImageGrab.grab() if oldView.tostring() != newView.tostring(): count = count + 1 endClock = time.clock() totalTime = endClock - startClock calculatedFPS = capturedFrames / totalTime horRes = str(newView.getbbox()[2]) verRes = str(newView.getbbox()[3]) print "Frame Resolution : %sx%s" % (horRes.rjust(4), verRes.rjust(4)) print "Frames Captured : %s" % str(capturedFrames).rjust(9) print "Capture Time (sec) : %s" % str(totalTime)[:4].rjust(9) print "Calculated FPS : %s" % str(calculatedFPS)[:4].rjust(9) print "Changes Registered : %s" % str(count).rjust(9) raw_input("\nPress Any Key...") On 11/8/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > alist = difference(image1,image2) > > a = [b for b in alist.getdata() if b != (0,0,0)] > > if len(a) != 0: > > print "Not the same" > > > > is much slower then (9x) > > > > if im1.tostring() != im2.tostring() > > print "something changed!" > > > > This loop itself is fairly slow by itself though.. I'm going to try > > and see if there is a faster way. > Chris, > are you sure you know what a loop is? > The only loop here is in the list comprehension. > 'if' is not a loop. > 'for' and 'while' are. > In computer science, it's important to be clear in your use of > terminology. > > It makes sense that my example was slow. > I didn't really think to try converting them to strings. > > Any time you're trying to compare pixel values, it's going to take a > while, > cause remember, a 1024X768 image has 786,432 different pixels. > I think your tostring comparison may be your best bet. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/d0798ff4/attachment.htm From pyro9219 at gmail.com Thu Nov 9 10:36:01 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 9 Nov 2006 01:36:01 -0800 Subject: [Tutor] Questions about PIL In-Reply-To: <4552DADE.2070907@gmail.com> References: <4552654F.6070300@gmail.com> <4552DADE.2070907@gmail.com> Message-ID: What I want to do with the data shouldn't really matter. I'm not completely sure what I want to do with the image data anyways, but for sake of arguement everything is happening in memory at this point, so 'objects' is correct. Images start in memory, and are being evaluated in memory, never written to disk.. On 11/8/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > Thanks for the detailed examples again Luke. Sorry I wasn't more clear > > with my implimentation. The loop I was refering to was the one in the > > start of my post but using im.tostring() instead. I saw an example to > > make a webcam motion detector that used tostring(), but couldn't get > > the program to see a difference. > I'm glad the examples helped. > See my other response about your use of the term 'loop.' > > > > As for just capturing a section of the screen. I'm not looking to make > > faster captures, so I think your sample was on the ball. Your example > > however wasn't quite what I had in mind when I was thinking up the > > question and again I take fault for this. I was thinking more of a way > > to create quadrants of the screenshot. (Or any number of area's) that > > I could independantly interact with. I know this isn't a CPU friendly > > task, but just humor me please =P > Once again, you're not being explicit enough in explaining what you're > trying to do. > Specifically, your sentence "(Or any number of area's) that I could > independently interact with" > How are you trying to interact with them? > Do you want them split into actual separate image files, into separate > image objects, or what? > The crop method I showed you will do any kind of splitting you want, > you just have to think through what exactly you need to crop in any > given situation. > For example, > (pseudocode) > > width = 1024/2 > height = 768/2 > image = load_image('imagename') > quad1 = image.crop((0,0,width,height)) > quad2 = image.crop((width,0,width,height)) > quad3 = image.crop((0,height,width,height)) > quad4 = image.crop((width,height,width,height)) > > note that width and height are the w/h of the quadrants, not of the > image itself. > since there are 4 quadrants (get it? quad = 4 ;) > each width/height would be original_image_ * (.5) > > HTH, > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/f76667e7/attachment.html From kent37 at tds.net Thu Nov 9 11:58:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Nov 2006 05:58:06 -0500 Subject: [Tutor] Questions about PIL In-Reply-To: References: <4552654F.6070300@gmail.com> Message-ID: <455309BE.9090800@tds.net> Chris Hengge wrote: > alist = difference(image1,image2) > a = [b for b in alist.getdata() if b != (0,0,0)] > if len(a) != 0: > print "Not the same" > > is much slower then (9x) > > if im1.tostring() != im2.tostring() > print "something changed!" One reason the second version will be faster is that it can stop checking for differences as soon as it finds one. The first version will look at all of alist.getdata() even if the first entry is not (0, 0, 0). If you are using Python 2.5 try if any(b != (0, 0, 0) for b in alist.getdata()): print "Not the same" This uses a generator comprehension instead of a list comprehension so it doesn't have to make the whole list, only enough to find a non-(0,0,0) value. In Python 2.4 you can write it as for b in alist.getdata(): if b != (0, 0, 0): print "Not the same" break Again the key idea is not to create the entire comparison list if it is not needed, and to abort the loop when you find a non-zero entry. Kent From dhhoa1 at student.monash.edu Thu Nov 9 03:55:23 2006 From: dhhoa1 at student.monash.edu (Hieu Hoang) Date: Thu, 09 Nov 2006 13:55:23 +1100 Subject: [Tutor] First real script Message-ID: Hi Carlos, I hope this module would help you with the binary conversion part: def tobits(inte,size = 3): """Copy an integer's bits from memory""" s='' for i in range(size): s += str((inte & (1<>i) #bits are extracted right-to-left s = s[::-1] #reverse the result string print s return list(s) >>>test = tobits(30,8) 00011110 >>>test ['0', '0', '0', '1', '1', '1', '1', '0'] Cheers, Rooy From kent37 at tds.net Thu Nov 9 12:07:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Nov 2006 06:07:33 -0500 Subject: [Tutor] Request - please join the list to post Message-ID: <45530BF5.80104@tds.net> Recently there have been a number of replies to the list from people who are not subscribed. I suppose they are from people who read the list on gmane.org or some other web archive rather than receiving it through email. Each of these replies requires a list administrator (usually me) to log on to the admin web site, review the post and approve or deny it. It's not a big deal but it does take some time and it interrupts whatever I am doing. So my request is, if you want to participate in the discussion, please join the list. It's very easy to do using the form here: http://mail.python.org/mailman/listinfo/tutor If you like you can set your preferences to not send email and you can continue to read the list on the web. Thank you, A list admin who has other things he would really rather do... Kent From ajkadri at googlemail.com Thu Nov 9 13:08:56 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 9 Nov 2006 12:08:56 +0000 Subject: [Tutor] Which is the latest version of Python for windows Message-ID: Hi Folks, Can someone tell me which is teh latest version of Python on windows platform? TIA. Best Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/b8af7307/attachment.html From simon at brunningonline.net Thu Nov 9 13:21:21 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 9 Nov 2006 12:21:21 +0000 Subject: [Tutor] Which is the latest version of Python for windows In-Reply-To: References: Message-ID: <8c7f10c60611090421u4f1b9d6buc4efbf84c51ed874@mail.gmail.com> On 11/9/06, Asrarahmed Kadri wrote: > Hi Folks, > > Can someone tell me which is teh latest version of Python on windows > platform? Version 2.5 -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From lucidmonk at gmail.com Thu Nov 9 14:57:04 2006 From: lucidmonk at gmail.com (Todd Dahl) Date: Thu, 9 Nov 2006 08:57:04 -0500 Subject: [Tutor] Windows Registry Message-ID: <44290fe50611090557j644d457aod09a96c0baf2648b@mail.gmail.com> I am currently working on a project that in a small part of it I need to find keys in the windows registry. I have found _winreg but was wondering if anyone knows of any modules that people have written as a wrapper for it. I have googled like crazy but am not finding anything. What I trying to do is search the registry for a list of known keys without knowing their specific locations and then find values of the other keys around it. Hope that makes sence. Thanks, -Todd -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/f4b10c54/attachment.html From kent37 at tds.net Thu Nov 9 15:10:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Nov 2006 09:10:46 -0500 Subject: [Tutor] Windows Registry In-Reply-To: <44290fe50611090557j644d457aod09a96c0baf2648b@mail.gmail.com> References: <44290fe50611090557j644d457aod09a96c0baf2648b@mail.gmail.com> Message-ID: <455336E6.3020308@tds.net> Todd Dahl wrote: > I am currently working on a project that in a small part of it I need to > find keys in the windows registry. I have found _winreg but was > wondering if anyone knows of any modules that people have written as a > wrapper for it. pyRegistry maybe? http://jbox.ultraemail.net:8000/~jbj1/ Kent From 3dbernard at gmail.com Thu Nov 9 16:24:01 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 9 Nov 2006 10:24:01 -0500 Subject: [Tutor] Calling instance method using a string Message-ID: <61d0e2b40611090724x52b43d6emc7731ba98feb0ea2@mail.gmail.com> Hello, Is there a way to call an instance method using a string? Let say I have the method name in the form of a string, and I want to call this method by providing the string instead of calling the name directly. Is this possible? Say I have class A: class A: def myMethod( self ): print 'foo' a = A() Then I would look to do something along the lines of: a.__call__( 'myMethod' ) or callattr( a, 'myMethod' ) Thanks Bernard From rabidpoobear at gmail.com Thu Nov 9 16:25:34 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 09 Nov 2006 09:25:34 -0600 Subject: [Tutor] Questions about PIL In-Reply-To: References: <4552654F.6070300@gmail.com> <4552D937.9090306@gmail.com> Message-ID: <4553486E.8000107@gmail.com> Chris Hengge wrote: > Yes, I understand what a loop is, and there was a loop but I didn't > write that code into my email because I didn't need commenting on it. > Here is the code so its clear incase you really care =P Just because you don't need commenting on it doesn't mean it's not relevant. Especially when you make references to it in your e-mail. From rabidpoobear at gmail.com Thu Nov 9 16:27:06 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 09 Nov 2006 09:27:06 -0600 Subject: [Tutor] Questions about PIL In-Reply-To: References: <4552654F.6070300@gmail.com> <4552DADE.2070907@gmail.com> Message-ID: <455348CA.6070709@gmail.com> Chris Hengge wrote: > What I want to do with the data shouldn't really matter. I'm not > completely sure what I want to do with the image data anyways, but for > sake of arguement everything is happening in memory at this point, so > 'objects' is correct. Images start in memory, and are being evaluated > in memory, never written to disk.. Then you shouldn't have any problem using crop to make the images. Do you have a different problem now or are you all set? :). From kent37 at tds.net Thu Nov 9 16:34:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Nov 2006 10:34:09 -0500 Subject: [Tutor] Calling instance method using a string In-Reply-To: <61d0e2b40611090724x52b43d6emc7731ba98feb0ea2@mail.gmail.com> References: <61d0e2b40611090724x52b43d6emc7731ba98feb0ea2@mail.gmail.com> Message-ID: <45534A71.6090209@tds.net> Bernard Lebel wrote: > Hello, > > Is there a way to call an instance method using a string? Let say I > have the method name in the form of a string, and I want to call this > method by providing the string instead of calling the name directly. > Is this possible? > > Say I have class A: > > class A: > def myMethod( self ): > print 'foo' > > a = A() getattr(a, 'myMethod')() The getattr() call gets the bound method, the extra parentheses at the end call it. Kent > > > Then I would look to do something along the lines of: > > a.__call__( 'myMethod' ) > or > callattr( a, 'myMethod' ) > > > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From simon at brunningonline.net Thu Nov 9 16:38:25 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 9 Nov 2006 15:38:25 +0000 Subject: [Tutor] Which is the latest version of Python for windows In-Reply-To: References: <8c7f10c60611090421u4f1b9d6buc4efbf84c51ed874@mail.gmail.com> <8c7f10c60611090515t7c7db7fet29bc5d179ff8476@mail.gmail.com> Message-ID: <8c7f10c60611090738s7fd19c85p913cf633926acc8e@mail.gmail.com> On 11/9/06, Asrarahmed Kadri wrote: > I am so sorry to disturb you. I hope u dont mind. > I cannot find the version 2.5 for Active Python. http://www.google.com/search?q=python+2.5+windows+download > Is it possible to use two versions at the same time..?? Yup. Install however many versions you want. Install the version that you want to use by default (i.e. the version that gets used when you double-click on a .py file) *last*. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From tim at johnsons-web.com Thu Nov 9 17:15:34 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 9 Nov 2006 07:15:34 -0900 Subject: [Tutor] Request - please join the list to post In-Reply-To: <45530BF5.80104@tds.net> References: <45530BF5.80104@tds.net> Message-ID: <20061109161534.GA13336@johnsons-web.com> On a related note, every time I post, I get some kind of advisory email back that is worded as if this is the first time I've posted. (I've been on this list for close to 6 years)...... Not exactly spam, but not necessary. tj -- let's see if I get one from this -- * Kent Johnson [061109 02:13]: > Recently there have been a number of replies to the list from people who > are not subscribed. I suppose they are from people who read the list on > gmane.org or some other web archive rather than receiving it through email. > > Each of these replies requires a list administrator (usually me) to log > on to the admin web site, review the post and approve or deny it. It's > not a big deal but it does take some time and it interrupts whatever I > am doing. > > So my request is, if you want to participate in the discussion, please > join the list. It's very easy to do using the form here: > http://mail.python.org/mailman/listinfo/tutor > > If you like you can set your preferences to not send email and you can > continue to read the list on the web. > > Thank you, > A list admin who has other things he would really rather do... > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From chris.arndt at web.de Thu Nov 9 17:22:55 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 09 Nov 2006 17:22:55 +0100 Subject: [Tutor] Windows Registry In-Reply-To: <44290fe50611090557j644d457aod09a96c0baf2648b@mail.gmail.com> References: <44290fe50611090557j644d457aod09a96c0baf2648b@mail.gmail.com> Message-ID: <455355DF.1000909@web.de> Todd Dahl schrieb: > I am currently working on a project that in a small part of it I need to > find keys in the windows registry. I have found _winreg but was > wondering if anyone knows of any modules that people have written as a > wrapper for it. I have googled like crazy but am not finding anything. > What I trying to do is search the registry for a list of known keys > without knowing their specific locations and then find values of the > other keys around it. Hope that makes sence. Search the Python Cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python/) for "registry" and you'll find plenty of examples and wrappers. Chris From kent37 at tds.net Thu Nov 9 17:37:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Nov 2006 11:37:01 -0500 Subject: [Tutor] Request - please join the list to post In-Reply-To: <20061109161534.GA13336@johnsons-web.com> References: <45530BF5.80104@tds.net> <20061109161534.GA13336@johnsons-web.com> Message-ID: <4553592D.3070703@tds.net> Tim Johnson wrote: > On a related note, every time I post, I get some kind of advisory > email back that is worded as if this is the first time I've posted. > (I've been on this list for close to 6 years)...... > Not exactly spam, but not necessary. > tj I think you will get one of those every 90 days, or maybe if you haven't posted for 90 days, I'm not sure. I recently got one too. I'm not a mailman expert though... Kent From tim at johnsons-web.com Thu Nov 9 17:57:12 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 9 Nov 2006 07:57:12 -0900 Subject: [Tutor] [spam-spf] Re: Request - please join the list to post In-Reply-To: <4553592D.3070703@tds.net> References: <45530BF5.80104@tds.net> <20061109161534.GA13336@johnsons-web.com> <4553592D.3070703@tds.net> Message-ID: <20061109165712.GB13336@johnsons-web.com> * Kent Johnson [061109 07:46]: > Tim Johnson wrote: > > On a related note, every time I post, I get some kind of advisory > > email back that is worded as if this is the first time I've posted. > > (I've been on this list for close to 6 years)...... > > Not exactly spam, but not necessary. > > tj > > I think you will get one of those every 90 days, or maybe if you haven't > posted for 90 days, I'm not sure. I recently got one too. Sounds about right. Not a problem tim > I'm not a mailman expert though... > > Kent -- Tim Johnson http://www.alaska-internet-solutions.com From dyoo at hkn.eecs.berkeley.edu Thu Nov 9 18:13:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Nov 2006 09:13:00 -0800 (PST) Subject: [Tutor] Calling instance method using a string In-Reply-To: <45534A71.6090209@tds.net> References: <61d0e2b40611090724x52b43d6emc7731ba98feb0ea2@mail.gmail.com> <45534A71.6090209@tds.net> Message-ID: >> Say I have class A: >> >> class A: >> def myMethod( self ): >> print 'foo' >> >> a = A() > > getattr(a, 'myMethod')() > > The getattr() call gets the bound method, the extra parentheses at the > end call it. Hi Bernard, You can also do this in a controlled manner by treating the methods as functions, and using a dispatch table. Concretely: ######################################################### class TestDispatch: def add(self, x, y): return x + y def sub(self, x, y): return x - y def dontcallme(self): return "oh no" def dispatch(self, msg, *args): table = {"add" : self.add, "sub" : self.sub} if msg in table: return table[msg](*args) print "Unrecognized message:", msg return None def test(): calc = TestDispatch() msg = None while msg != 'quit': msg = raw_input('cmd? ') print calc.dispatch(msg, 3, 4) ######################################################### Try running test(), and then enter either "add" or "sub" at the prompt. This approach differs from getattr() because we can prevent clients from calling dontcallme() by excluding it from our dispatch table, so it's more controlled. Also, it's a techinque that's pretty programming-language agnostic. However, it is a little more verbose than the equivalent getattr()-driven code. From dyoo at hkn.eecs.berkeley.edu Thu Nov 9 18:13:45 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Nov 2006 09:13:45 -0800 (PST) Subject: [Tutor] Request - please join the list to post In-Reply-To: <4553592D.3070703@tds.net> References: <45530BF5.80104@tds.net> <20061109161534.GA13336@johnsons-web.com> <4553592D.3070703@tds.net> Message-ID: On Thu, 9 Nov 2006, Kent Johnson wrote: > Tim Johnson wrote: >> On a related note, every time I post, I get some kind of advisory >> email back that is worded as if this is the first time I've posted. >> (I've been on this list for close to 6 years)...... >> Not exactly spam, but not necessary. >> tj > > I think you will get one of those every 90 days, or maybe if you haven't > posted for 90 days, I'm not sure. I recently got one too. Mailman has a bad memory. I get these too if I haven't posted in a very long time. From Barry.Carroll at psc.com Thu Nov 9 18:45:55 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 9 Nov 2006 09:45:55 -0800 Subject: [Tutor] Ruby Code Blocks vs. Python Lambdas Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A1F@eugsrv400.psc.pscnet.com> Hello, John > -----Original Message----- > From: jfouhy at gmail.com [mailto:jfouhy at gmail.com] On Behalf Of John Fouhy > Sent: Tuesday, November 07, 2006 6:56 PM > To: Carroll, Barry > Cc: tutor at python.org > Subject: Re: [Tutor] Ruby Code Blocks vs. Python Lambdas > > On 08/11/06, Carroll, Barry wrote: > > Correct indeed. But lambda functions ARE anonymous. > > > > "Python supports the creation of anonymous functions (i.e. > > functions that are not bound to a name) at runtime, using > > a construct called "lambda". > > http://www.secnetix.de/~olli/Python/lambda_functions.hawk > > > > So that principle has already been bent. Since code blocks are more > > flexible and more intuitive than lambdas, why not add them to the tool > > box? To quote some more principles: > > PEP3099 (http://www.python.org/dev/peps/pep-3099/) makes this seem > unlikely.. > > -- > John. Yes, I'd say it certainly does. It's unfortunate, IMHO, but I'm not a language designer and probably don't understand all the implications of such a change. -sigh- Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From 3dbernard at gmail.com Thu Nov 9 18:53:18 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 9 Nov 2006 12:53:18 -0500 Subject: [Tutor] Calling instance method using a string In-Reply-To: References: <61d0e2b40611090724x52b43d6emc7731ba98feb0ea2@mail.gmail.com> <45534A71.6090209@tds.net> Message-ID: <61d0e2b40611090953v25a04aeck157440e84bb2767c@mail.gmail.com> Thanks everyone for the advice. Bernard On 11/9/06, Danny Yoo wrote: > >> Say I have class A: > >> > >> class A: > >> def myMethod( self ): > >> print 'foo' > >> > >> a = A() > > > > getattr(a, 'myMethod')() > > > > The getattr() call gets the bound method, the extra parentheses at the > > end call it. > > > Hi Bernard, > > You can also do this in a controlled manner by treating the methods as > functions, and using a dispatch table. Concretely: > > ######################################################### > class TestDispatch: > def add(self, x, y): > return x + y > > def sub(self, x, y): > return x - y > > def dontcallme(self): > return "oh no" > > def dispatch(self, msg, *args): > table = {"add" : self.add, > "sub" : self.sub} > if msg in table: > return table[msg](*args) > print "Unrecognized message:", msg > return None > > def test(): > calc = TestDispatch() > msg = None > while msg != 'quit': > msg = raw_input('cmd? ') > print calc.dispatch(msg, 3, 4) > ######################################################### > > Try running test(), and then enter either "add" or "sub" at the prompt. > > This approach differs from getattr() because we can prevent clients from > calling dontcallme() by excluding it from our dispatch table, so it's more > controlled. Also, it's a techinque that's pretty programming-language > agnostic. However, it is a little more verbose than the equivalent > getattr()-driven code. > From bashu at yandex.ru Thu Nov 9 19:09:54 2006 From: bashu at yandex.ru (Basil Shubin) Date: Fri, 10 Nov 2006 00:09:54 +0600 Subject: [Tutor] Tuple and Dicts? Message-ID: <45536EF2.3080900@yandex.ru> Hi friends! Imagine the tuple that has dictionaries as it's item: >>> print data ({'id': 0, 'title': 'Linux'}, {'id': 1, 'title': 'FreeBSD'}) How I can get index of tuple item where dict's key 'id' equal to appropriate value? And can this be done without 'for' loops, just in one string? -- Basil Shubin Freelance Software Developer From ajkadri at googlemail.com Thu Nov 9 19:23:50 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 9 Nov 2006 18:23:50 +0000 Subject: [Tutor] Help with Elementtree ...how to access the attributes.. Message-ID: Hi Folks, I am trying to parse XML documents using elementtree. I have just started with it. Can somebody help me with how to select nodes with a particular atribute set to some value. For example, I have the following file. Now I want to access the founder element of the company whose attribute is set to 'ndtv'. Can somebody help me with this? sample.xml larry page sergey brin search engine Pranoy Roy Radhika Roy news Azeem Premje IT services -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/e6c324aa/attachment.htm From jason.massey at gmail.com Thu Nov 9 19:37:29 2006 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 9 Nov 2006 12:37:29 -0600 Subject: [Tutor] Tuple and Dicts? In-Reply-To: <45536EF2.3080900@yandex.ru> References: <45536EF2.3080900@yandex.ru> Message-ID: <7e3eab2c0611091037k2bb20565p9155f33219149b32@mail.gmail.com> How about something like: >>> data = ({'id': 0, 'title': 'Linux'}, {'id': 1, 'title': 'FreeBSD'}) >>> id = 0 >>> result = [x for x in data if x['id'] == id] [{'id': 0, 'title': 'Linux'}] >>> result = [x for x in data if x['id'] == id] >>> result[0] {'id': 0, 'title': 'Linux'} >>> You get the entire dict entry out of the tuple that way. On 11/9/06, Basil Shubin wrote: > > Hi friends! > > Imagine the tuple that has dictionaries as it's item: > > >>> print data > ({'id': 0, 'title': 'Linux'}, {'id': 1, 'title': 'FreeBSD'}) > > How I can get index of tuple item where dict's key 'id' equal to > appropriate value? And can this be done without 'for' loops, just in one > string? > > -- > Basil Shubin > Freelance Software Developer > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/4e676801/attachment-0001.htm From kent37 at tds.net Thu Nov 9 19:41:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Nov 2006 13:41:05 -0500 Subject: [Tutor] Tuple and Dicts? In-Reply-To: <45536EF2.3080900@yandex.ru> References: <45536EF2.3080900@yandex.ru> Message-ID: <45537641.2000401@tds.net> Basil Shubin wrote: > Hi friends! > > Imagine the tuple that has dictionaries as it's item: > >>>> print data > ({'id': 0, 'title': 'Linux'}, {'id': 1, 'title': 'FreeBSD'}) > > How I can get index of tuple item where dict's key 'id' equal to > appropriate value? And can this be done without 'for' loops, just in one > string? If you must...this will break if there is no match, and it will always enumerate the entire data list: [ i for i, d in enumerate(data) if d['id']== id_to_match ][0] For the readable version, which won't break if the id is missing, and may be faster depending on the data: for i, d in enumerate(data): if d['id'] == id_to_match: break else: i = None # or whatever you want to do to signal no match Alternately, maybe you should be storing data in a dict indexed by id instead of in a list? Kent From dyoo at hkn.eecs.berkeley.edu Thu Nov 9 19:42:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Nov 2006 10:42:09 -0800 (PST) Subject: [Tutor] Some sample code: review? Message-ID: Hi everyone, I wrote up some sample code to make a more extensible str()-like function. I'd like some comments before putting it up onto the Python Cookbook: ##################################################################### class DeepStr: """Deep stringifier.""" def __init__(self, default_str=str, recursive_str=lambda obj, dstr: "..."): """Creates a new DeepStr. Once constructed, call as if this were a function that takes objects and returns strings. default_str is the default function used on types that this does not recognize. If we hit structure that's already been traversed, uses recursive_str to represent that structure.""" self.__handlers = [] self.__default_str = default_str self.__recursive_str = recursive_str def __call__(self, obj): """Takes a datum and returns a string of that object.""" return self.__deepstr(obj, {}) def __deepstr(self, obj, _seen): if id(obj) in _seen: return self.__recursive_str(obj, self) _seen[id(obj)] = True for h in self.__handlers: result = h(obj, lambda o: self.__deepstr(o, _seen)) if result != None: return result return self.__default_str(obj) def register(self, handler): """register: (object (object -> string) -> string or None) Registers a new handler type. Handers take in the object as well as a str() function, and returns either a string if it can handle the object, or None otherwise. The second argument should be used on substructures.""" self.__handlers.append(handler) def handle_list(obj, dstr): if isinstance(obj, list): return "[" + ", ".join([dstr(x) for x in obj]) + "]" return None def handle_tuple(obj, dstr): if isinstance(obj, tuple): return "(" + ", ".join([dstr(x) for x in obj]) + ")" return None def handle_dict(obj, dstr): if isinstance(obj, dict): return ("{" + ", ".join([dstr(k) + ':' + dstr(v) for (k, v) in obj.items()]) + "}") return None dstr = DeepStr() dstr.register(handle_list) dstr.register(handle_tuple) dstr.register(handle_dict) ##################################################################### The idea is that Python's str() on lists uses repr() on internal structure, which some people might consider a little wacky. dstr(), on the other hand, will go all the way deeply through a structure, using the same stringifier. It's also open for extension so that it can handle different container types in the future. Any comments would be greatly appreciated. From john at fouhy.net Thu Nov 9 22:23:49 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 10 Nov 2006 10:23:49 +1300 Subject: [Tutor] Help with Elementtree ...how to access the attributes.. In-Reply-To: References: Message-ID: <5e58f2e40611091323n37d019d3y9a0fa12cb8e8ed79@mail.gmail.com> On 10/11/06, Asrarahmed Kadri wrote: > I am trying to parse XML documents using elementtree. > I have just started with it. Can somebody help me with how to select nodes > with a particular atribute set to some value. For example, I have the > following file. Now I want to access the founder element of the company > whose attribute is set to 'ndtv'. Can somebody help me with this? Here's some code to get you started: >>> from elementtree import ElementTree >>> tree = ElementTree.parse('sample.xml') # Make a list of all elements. >>> companies = tree.findall('company') # Make a dict, mapping the name attrib of elements to the elements themselves. >>> companiesByName = dict((c.get('name'), c) for c in companies) # Access the founder element in the ndtv company. >>> ndtvFounder = companiesByName['ndtv'].find('founder') I notice that sometimes, your element contains text, and sometimes it contains other elements ( and ). This will make extracting founder information a bit fiddly.. You might want to consider changing the structure -- perhaps: Bill Gates Steve Jobs Larry Wall That way, you could do: >>> founderElements = companiesByName['ndtv'].findall('founder') >>> founders = [f.text for f in founderElements] and that would give you the founder names in a list, regardless of whether you had one or many. HTH! -- John. From gsf at panix.com Thu Nov 9 22:27:29 2006 From: gsf at panix.com (Gabriel Farrell) Date: Thu, 9 Nov 2006 16:27:29 -0500 Subject: [Tutor] Help with Elementtree ...how to access the attributes.. In-Reply-To: References: Message-ID: <20061109212729.GB27386@panix.com> On Thu, Nov 09, 2006 at 06:23:50PM +0000, Asrarahmed Kadri wrote: > Hi Folks, > > > I am trying to parse XML documents using elementtree. > I have just started with it. Can somebody help me with how to select nodes > with a particular atribute set to some value. For example, I have the > following file. Now I want to access the founder element of the company > whose attribute is set to 'ndtv'. Can somebody help me with this? > with elementtree: from elementtree import ElementTree as et tree = et.parse('temp.xml') company_list = tree.findall('company') for company in company_list: if company.attrib['name'] == 'ndtv': for founder in company.findall('founder'): for child in founder.getchildren(): print child.tag, child.text with lxml (note the difference a full xpath implementation makes): from lxml import etree tree = etree.parse('temp.xml') ndtv_founder_list = tree.xpath('company[@name="ndtv"]/founder') for founder in ndtv_founder_list: for child in founder.getchildren(): print child.tag, child.text I'll leave the modifying of tags and the writing of new xml files up to you. A note on your sample.xml: why is it larry page sergey brin when it could just be larry page sergey brin ? That would make it easier to parse the text out. (Probably easier to produce as well.) gabe > sample.xml > > > > > larry page > sergey brin > > search engine > > > > > Pranoy Roy > Radhika Roy > > news > > > > Azeem Premje > IT services > > > > -- > To HIM you shall return. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From gsf at panix.com Thu Nov 9 22:42:00 2006 From: gsf at panix.com (Gabriel Farrell) Date: Thu, 9 Nov 2006 16:42:00 -0500 Subject: [Tutor] Help with Elementtree ...how to access the attributes.. In-Reply-To: <5e58f2e40611091323n37d019d3y9a0fa12cb8e8ed79@mail.gmail.com> References: <5e58f2e40611091323n37d019d3y9a0fa12cb8e8ed79@mail.gmail.com> Message-ID: <20061109214200.GC27386@panix.com> On Fri, Nov 10, 2006 at 10:23:49AM +1300, John Fouhy wrote: > On 10/11/06, Asrarahmed Kadri wrote: > > I am trying to parse XML documents using elementtree. > > I have just started with it. Can somebody help me with how to select nodes > > with a particular atribute set to some value. For example, I have the > > following file. Now I want to access the founder element of the company > > whose attribute is set to 'ndtv'. Can somebody help me with this? > > Here's some code to get you started: > > >>> from elementtree import ElementTree > >>> tree = ElementTree.parse('sample.xml') > > # Make a list of all elements. > >>> companies = tree.findall('company') > > # Make a dict, mapping the name attrib of elements to the > elements themselves. > >>> companiesByName = dict((c.get('name'), c) for c in companies) > > # Access the founder element in the ndtv company. > >>> ndtvFounder = companiesByName['ndtv'].find('founder') > Oops, I guess John's email and mine zipped by each other on the wires. I like his use of a dictionary to simplify things. Funny that we had nearly the same comment about the element! > I notice that sometimes, your element contains text, and > sometimes it contains other elements ( and ). This will > make extracting founder information a bit fiddly.. You might want to > consider changing the structure -- perhaps: > > > > Bill Gates > Steve Jobs > Larry Wall > > > > That way, you could do: > > >>> founderElements = companiesByName['ndtv'].findall('founder') > >>> founders = [f.text for f in founderElements] > > and that would give you the founder names in a list, regardless of > whether you had one or many. > > HTH! > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Thu Nov 9 23:49:25 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 9 Nov 2006 14:49:25 -0800 (PST) Subject: [Tutor] Which is the latest version of Python for windows In-Reply-To: <8c7f10c60611090738s7fd19c85p913cf633926acc8e@mail.gmail.com> Message-ID: On Thu, 9 Nov 2006, Simon Brunning wrote: > On 11/9/06, Asrarahmed Kadri wrote: > > I am so sorry to disturb you. I hope u dont mind. > > I cannot find the version 2.5 for Active Python. Activestate is still on 2.4.3. I'm awaiting a 2.5 version of ActivePython, myself. You can install the Windows version of Python 2.5, but you'll have to add in a lot of the stuff you're accustomed to Activestate doing for you. From carloslara at web.de Fri Nov 10 00:04:41 2006 From: carloslara at web.de (Carlos) Date: Fri, 10 Nov 2006 00:04:41 +0100 Subject: [Tutor] First realscript + Game of Life Message-ID: <4553B409.50504@web.de> Hallo to All, Hey Rooy, so its possible to copy binary numbers from memory? I had the impression that this could be done, but obviously it is too much for me. This way is going to be faster than the hack that I tried before, right? Thanks for the module : ) Now I'm tring to implement a Conway's Game of Life in Maya with CGKit. It was going well until I got this error: Traceback (most recent call last): File "", line 14, in ? File "test.py", line 31, in ? Neighbor_Value = BOX_State[i-11]+BOX_State[i-10]+BOX_State[i-9]+\ IndexError: list index out of range I know what it means, but I just can't figure out why this happens when the loop reaches 89. Can someone please tell me the reason for this? Here is my code so far: from maya.mel import * from random import * BOX_List = [] BOX_State = [] rows = 10 columns = 10 for x in range (rows): for z in range(columns): State = randint(0,1) Name = 'BOX_%i_%i'%(x,z) BOX_List.append(Name) BOX_State.append(State) if State == 1: polyCube(name = (Name)) move(z,0,x) for i in range (rows*columns): Cell_Value = BOX_State[i] Neighbor_Value = BOX_State[i-11]+BOX_State[i-10]+BOX_State[i-9]+\ BOX_State[i-1]+BOX_State[i+1]+\ BOX_State[i+11]+BOX_State[i+10]+BOX_State[i+9] Just to explain my plan a little bit: I have two lists, BOX_List and BOX_State. BOX_State is my way to sidestep the wrappping problem. I expected an exception with the last number in the list, but not 10 numbers before. As I see it, the problem comes when 'i' reaches BOX_State[i-1] Is this correct? And again if you see something that should be different please let me know, in this way I can improve a little bit every time. Since there has been some talk about the list itself, when some of you reply to my posts sometimes I get a mail straight to my account. This is very useful because it lets me see the reply before it is posted on the list and because in this way is easier to keep track of the info that is useful for me. The question is: is this a personal option from the person who replys? I would like to have all my answers this way, is it possible? Thanks a lot for your help. Happy coding, Carlos -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061110/511d41fc/attachment.htm From pyro9219 at gmail.com Fri Nov 10 00:31:04 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 9 Nov 2006 15:31:04 -0800 Subject: [Tutor] Which is the latest version of Python for windows In-Reply-To: References: <8c7f10c60611090738s7fd19c85p913cf633926acc8e@mail.gmail.com> Message-ID: I've been trying to look for a roadmap or something from them that would show estimated product release dates. Does this not exist? On 11/9/06, Terry Carroll wrote: > > On Thu, 9 Nov 2006, Simon Brunning wrote: > > > On 11/9/06, Asrarahmed Kadri wrote: > > > I am so sorry to disturb you. I hope u dont mind. > > > I cannot find the version 2.5 for Active Python. > > Activestate is still on 2.4.3. I'm awaiting a 2.5 version of > ActivePython, myself. > > You can install the Windows version of Python 2.5, but you'll have to add > in a lot of the stuff you're accustomed to Activestate doing for you. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/1773f339/attachment-0001.html From fedekiller at gmail.com Fri Nov 10 00:39:14 2006 From: fedekiller at gmail.com (federico ramirez) Date: Thu, 9 Nov 2006 20:39:14 -0300 Subject: [Tutor] pygame rpg Message-ID: <26a78a3c0611091539v5ae72a8dlf79c20185e627f6@mail.gmail.com> Hi! im trying to make a rpg game with pygame, of ocurse i will first to try make simpler games, anyways, i could not find any good tutorial, example, article, not anything about making a rpg with pygame and the documentations is pretty poor... only some tutorials Well, i was wondering is someone can give me a link or something to get started with pygame rpgs -- Best Regards. fedekiller -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/e0335020/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Nov 10 01:48:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 9 Nov 2006 16:48:30 -0800 (PST) Subject: [Tutor] Can you help me with Elementtree (fwd) Message-ID: Forwarding to tutor. Please don't email tutor questions directly to me, but do share them with the group instead. I don't want to shoulder the obligation of answering your question on my own; I'd rather share that with a support group like Tutor. See: http://catb.org/esr/faqs/smart-questions.html#noprivate (In fact, I'm now putting myself in digest mode for a while due to time constraints.) ---------- Forwarded message ---------- Date: Thu, 9 Nov 2006 20:32:28 +0000 From: Asrarahmed Kadri To: dyoo at hkn.eecs.berkeley.edu Subject: Can you help me with Elementtree Hi Danny, I hope you dont mind me mailing you personally. I am trying to learn elementtree and the problem is i cannot figure out how to use the API functions. I have learnt to create an XML document using Element () and SubElement () functions. But the getitem() and other functions are giving me pain. If you can point out some material other that effbot, that would be very helpful which has detailed examples of accessing specific node-sets ........ Please help me in this matter. Best Regards, Asrarahmed -- To HIM you shall return. From jfabiani at yolo.com Fri Nov 10 04:55:12 2006 From: jfabiani at yolo.com (johnf) Date: Thu, 9 Nov 2006 19:55:12 -0800 Subject: [Tutor] datetimetype vs datetime.datetime Message-ID: <200611091955.12475.jfabiani@yolo.com> Hi I'm working on a python interface to freetds. And freetds can access MS SQL database engines. But I'm having trouble with datatime datatypes. The python module I'm using is MSSQL.py written back in 2003. After getting it compiled access to MS SQL works if I stay with simple datatypes (int, varchar). But when the table has a datetime field the MSSQL.py module returns a 'DateTimeType' i.e. Jan 13 2006 12:00AM The question is how can I convert the 'DateTimeType' to a datetime.datetime? John From pyro9219 at gmail.com Fri Nov 10 07:33:33 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 9 Nov 2006 22:33:33 -0800 Subject: [Tutor] Looking for some constructive peer review. Message-ID: I write this little IM style client the other night based on some sample socket and threading examples I found plus a little of my own twist just to make it more interesting.. I'd like some constructive peer review just to help me make sure I'm doing this correctly / well. You can test it by connecting to localhost if you want to run the code to help with review. One thing I'd like to know how to do is fix the output to the screen. Currently it interrupts typing when a message is recieved which as I understand is because my typing a line is basically letting the client thread sleep, and recieving a message triggers the server thread while I'm typing... Maybe there is some sort of better thread management for this? Or is this just a limiting factor since I'm playing in the console world? The other issue I have is when the other person types DSC to end their session, I should be able to put the thread to sleep, or trash it or something so I dont have to close the app to use it again. It also isn't going through the entire I was hoping to actually make something more like an IRC server / client, but I'm not sure I've got this thing down well enough to try that. Thanks! from socket import * import Queue, threading, os class ServerThread ( threading.Thread ): def run ( self ): while True: client = clientPool.get() clientName = client[0].recv(1024) print '\n' + ('=' * 40) print 'Connection Established by %s...' % clientName client[0].send('Connection Established!') while True: try: data = client[0].recv(1024) except: print "Connection to %s terminated!" % clientName break if data: if 'DSC' not in data: print data else: print ('=' * 40) client[0].send('Connection Terminated...') print '\nClosed connection to %s... ' % clientName return False else: client[0].send('Closing connection.') return False client[0].close() class ClientThread ( threading.Thread ): def run ( self ): print "Type 'DSC' to disconnect..." print '=' * 40 myServer = raw_input('Server Name / IP: ') myName = os.environ.items()[1][1].title() server = socket(AF_INET, SOCK_STREAM) try: server.connect((myServer, 2000)) server.send(myName) msg = '' while True: data = server.recv(1024) print data print '=' * 40 while msg != 'DSC': msg = raw_input() server.send(myName + ': ' + msg) data = server.recv(1024) print data server.close() except: server.close() # Create our Queue: clientPool = Queue.Queue ( 0 ) # Start threads: print '=' * 40 print "Initializing Listening Device..." ServerThread().start() myPort = 2000 myIP = gethostbyname(os.environ.items()[1][1]) print "Listening for %s on port %s" % (myIP,myPort) ClientThread().start() # Set up the server: myServer = socket(AF_INET, SOCK_STREAM) myServer.bind(('', myPort)) myServer.listen(5) # Have the server serve "forever": while True: clientPool.put(myServer.accept()) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/ea1f0885/attachment.html From pyro9219 at gmail.com Fri Nov 10 07:34:46 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 9 Nov 2006 22:34:46 -0800 Subject: [Tutor] Looking for some constructive peer review. In-Reply-To: References: Message-ID: Oops... I started another sentence at the end, then ended up on the phone and forgot what I was doing and hit send.... Now I dont remember the other bug.. Oh well.. Thanks again. On 11/9/06, Chris Hengge wrote: > > I write this little IM style client the other night based on some sample > socket and threading examples I found plus a little of my own twist just to > make it more interesting.. > I'd like some constructive peer review just to help me make sure I'm doing > this correctly / well. > > You can test it by connecting to localhost if you want to run the code to > help with review. One thing I'd like to know how to do is fix the output to > the screen. Currently it interrupts typing when a message is recieved which > as I understand is because my typing a line is basically letting the client > thread sleep, and recieving a message triggers the server thread while I'm > typing... Maybe there is some sort of better thread management for this? Or > is this just a limiting factor since I'm playing in the console world? The > other issue I have is when the other person types DSC to end their session, > I should be able to put the thread to sleep, or trash it or something so I > dont have to close the app to use it again. It also isn't going through the > entire > > I was hoping to actually make something more like an IRC server / client, > but I'm not sure I've got this thing down well enough to try that. Thanks! > > from socket import * > import Queue, threading, os > > class ServerThread ( threading.Thread ): > > def run ( self ): > while True: > client = clientPool.get() > clientName = client[0].recv(1024) > print '\n' + ('=' * 40) > print 'Connection Established by %s...' % clientName > client[0].send('Connection Established!') > while True: > try: > data = client[0].recv(1024) > except: > print "Connection to %s terminated!" % clientName > break > if data: > if 'DSC' not in data: > print data > else: > print ('=' * 40) > client[0].send('Connection Terminated...') > print '\nClosed connection to %s... ' % clientName > > return False > else: > client[0].send('Closing connection.') > return False > client[0].close() > > class ClientThread ( threading.Thread ): > > def run ( self ): > print "Type 'DSC' to disconnect..." > print '=' * 40 > myServer = raw_input('Server Name / IP: ') > myName = os.environ.items ()[1][1].title() > server = socket(AF_INET, SOCK_STREAM) > > try: > server.connect((myServer, 2000)) > server.send(myName) > msg = '' > while True: > data = server.recv(1024) > print data > print '=' * 40 > while msg != 'DSC': > msg = raw_input() > server.send(myName + ': ' + msg) > data = server.recv(1024) > print data > server.close() > except: > server.close() > > # Create our Queue: > clientPool = Queue.Queue ( 0 ) > > # Start threads: > print '=' * 40 > print "Initializing Listening Device..." > ServerThread().start() > myPort = 2000 > myIP = gethostbyname(os.environ.items()[1][1]) > print "Listening for %s on port %s" % (myIP,myPort) > ClientThread().start() > > # Set up the server: > myServer = socket(AF_INET, SOCK_STREAM) > myServer.bind(('', myPort)) > myServer.listen(5) > > # Have the server serve "forever": > while True: > clientPool.put(myServer.accept()) > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/cda1d2d8/attachment-0001.htm From rabidpoobear at gmail.com Fri Nov 10 08:00:16 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 01:00:16 -0600 Subject: [Tutor] Looking for some constructive peer review. In-Reply-To: References: Message-ID: <45542380.5040607@gmail.com> Chris Hengge wrote: > I write this little IM style client the other night based on some > sample socket and threading examples I found plus a little of my own > twist just to make it more interesting.. > I'd like some constructive peer review just to help me make sure I'm > doing this correctly / well. > > You can test it by connecting to localhost if you want to run the code > to help with review. One thing I'd like to know how to do is fix the > output to the screen. Currently it interrupts typing when a message is > recieved which as I understand is because my typing a line is > basically letting the client thread sleep, and recieving a message > triggers the server thread while I'm typing... Maybe there is some > sort of better thread management for this? Or is this just a limiting > factor since I'm playing in the console world? The other issue I have > is when the other person types DSC to end their session, I should be > able to put the thread to sleep, or trash it or something so I dont > have to close the app to use it again. It also isn't going through the > entire > > I was hoping to actually make something more like an IRC server / > client, but I'm not sure I've got this thing down well enough to try > that. Thanks! Sorry, I'm too tired to read your code right now. A few things I'd like to point out... yeah, it's tough to show output and get input in the same console window. A simple TKInter gui would not be all that hard to put together. Just a textbox and an entry widget. wouldn't even need a 'send' button if you just bind 'enter' to the send command from the entry widget. Also, IRC is not as complicated as you may think. The messages are all in ascii. Basically you just say import socket sock = socket.socket() sock.connect(('irc.freenode.net',6667)) sock.send("NICK Bob\r\n") sock.send("USER Bob irc.freenode.net bla :realname\r\n") sock.send("JOIN #test\r\n") sock.send("PRIVMSG #test HELLO!\r\n") sock.send("LEAVE #test\r\n") From rabidpoobear at gmail.com Fri Nov 10 08:07:51 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 01:07:51 -0600 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <4553B409.50504@web.de> References: <4553B409.50504@web.de> Message-ID: <45542547.9050703@gmail.com> Carlos wrote: > Hallo to All, > > Hey Rooy, so its possible to copy binary numbers from memory? I had > the impression that this could be done, but obviously it is too much > for me. This way is going to be faster than the hack that I tried > before, right? Thanks for the module : ) What? I think you're talking to someone else here, cause I have no idea what you mean. Copy binary numbers from memory? You mean from any arbitrary memory location you want? That sounds a lot like C++ pointers to me. > > Now I'm tring to implement a Conway's Game of Life > in Maya with > CGKit. It was going well until I got this error: > > Traceback (most recent call last): > File "", line 14, in ? > File "test.py", line 31, in ? > Neighbor_Value = BOX_State[i-11]+BOX_State[i-10]+BOX_State[i-9]+\ > IndexError: list index out of range > > I know what it means, but I just can't figure out why this happens > when the loop reaches 89. Can someone please tell me the reason for > this? Here is my code so far: > > > Neighbor_Value = BOX_State[i-11]+BOX_State[i-10]+BOX_State[i-9]+\ > BOX_State[i-1]+BOX_State[i+1]+\ > > BOX_State[i+11]+BOX_State[i+10]+BOX_State[i+9] > > Just to explain my plan a little bit: I have two lists, BOX_List and > BOX_State. BOX_State is my way to sidestep the wrappping problem. I > expected an exception with the last number in the list, but not 10 > numbers before. As I see it, the problem comes when 'i' reaches > BOX_State[i-1] Is this correct? No, this is not correct. Your Neighbor_Value line, though it occupies 3 lines, is only one statement. Because of this, Python is showing you that you have an error in the line where the statement starts. However, the problem line is last line, where you try to access BOX_State[i+11] obviously... 89+11 = 100, which is longer than the list. Tada. :) > > And again if you see something that should be different please let me > know, in this way I can improve a little bit every time. Sorry, I only had time to look at the part that was causing the error. > > Since there has been some talk about the list itself, when some of you > reply to my posts sometimes I get a mail straight to my account. This > is very useful because it lets me see the reply before it is posted on > the list and because in this way is easier to keep track of the info > that is useful for me. The question is: is this a personal option from > the person who replys? I would like to have all my answers this way, > is it possible? You get a direct mail when people use the 'reply-all' feature. I use that exclusively. I figure if enough people are aggravated by it, they'll get the admin to add reply-munging so replies only go straight to the whole list like on Pygame. Otherwise, I use reply-all so I don't have to type in 'tutor at python.org' every time. The side effect of other people getting the e-mails is generally not too annoying, because the list is smart enough to not send you an extra copy anyway. So unless you use the Digest method, you shouldn't notice a difference at all. > > Thanks a lot for your help. Sure thing. > > Happy coding, You too. > Carlos -Luke From rabidpoobear at gmail.com Fri Nov 10 08:11:32 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 01:11:32 -0600 Subject: [Tutor] pygame rpg In-Reply-To: <26a78a3c0611091539v5ae72a8dlf79c20185e627f6@mail.gmail.com> References: <26a78a3c0611091539v5ae72a8dlf79c20185e627f6@mail.gmail.com> Message-ID: <45542624.6080507@gmail.com> federico ramirez wrote: > Hi! im trying to make a rpg game with pygame, of ocurse i will first > to try make simpler games, anyways, i could not find any good > tutorial, example, article, not anything about making a rpg with > pygame and the documentations is pretty poor... only some tutorials I do not think the documentation is poor. In fact, I love the pygame documentation. It's the most clear documentation I've ever laid eyes on. It shines like the sun. I bow before it. Okay, yeah, so it doesn't have that many tutorials. Tutorials aren't part of the documentation, though. They are a completely separate entity. The docs explain everything you need to know about using the library, just not how you should use it for a specific task. Making an RPG in pygame will have the same problems as writing one in SDL or some other language/library. Look for general RPG design help type websites. Note that RPGs have a buttload of content and soloing one is nigh impossible IMO. From rabidpoobear at gmail.com Fri Nov 10 08:12:56 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 01:12:56 -0600 Subject: [Tutor] pygame rpg In-Reply-To: <26a78a3c0611091539v5ae72a8dlf79c20185e627f6@mail.gmail.com> References: <26a78a3c0611091539v5ae72a8dlf79c20185e627f6@mail.gmail.com> Message-ID: <45542678.2080509@gmail.com> federico ramirez wrote: > Hi! im trying to make a rpg game with pygame, of ocurse i will first > to try make simpler games, anyways, i could not find any good > tutorial, example, article, not anything about making a rpg with > pygame and the documentations is pretty poor... only some tutorials > > Well, i was wondering is someone can give me a link or something to > get started with pygame rpgs > Oops, I also forgot to say you should join the pygame mailing list. If you ask the same question there you'll likely get the same answer I gave earlier, or maybe a 'google it.' but you never know, and if you must try, I can do nothing to stop you :). -Luke From pyro9219 at gmail.com Fri Nov 10 08:28:33 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 9 Nov 2006 23:28:33 -0800 Subject: [Tutor] Looking for some constructive peer review. In-Reply-To: <45542380.5040607@gmail.com> References: <45542380.5040607@gmail.com> Message-ID: Yeah, I'm trying to hold out on gui stuff at the moment. I'm trying to get a grasp on classes and threads at the moment because nothing I've made to date in python really calls for anything outside of what a console can offer. Kinda keeping it simple for now I guess... I'll probably rebuild this application with a gui in the not-so-far future though.. would make a great starter for gui's project. (I'm pretty good in C# with gui's so I might just go with IronPython so I can use the windows libs for the interface controls, well see =D ) As for the IRC style (as in I know I could just get a library, but I wouldn't really learn anything. I also know fairly well how IRC should act, so its a good model for my learning) project, I dont need to reinvent it, but basically a threaded multiuser experience would be cool... I'm also interested in programming the server (threaded project for more practice). My original trials with the code I posted for this thread where seperate client and server code, and I ran several threads so I could get multiple connections and print content to the server console from the client console, and then return fixed messages back, but I am not sure how I'd go about letting multiple users communicate to each other, or forward messages. Does this involve traversing threads? or sockets? or something else? Thanks. On 11/9/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I write this little IM style client the other night based on some > > sample socket and threading examples I found plus a little of my own > > twist just to make it more interesting.. > > I'd like some constructive peer review just to help me make sure I'm > > doing this correctly / well. > > > > You can test it by connecting to localhost if you want to run the code > > to help with review. One thing I'd like to know how to do is fix the > > output to the screen. Currently it interrupts typing when a message is > > recieved which as I understand is because my typing a line is > > basically letting the client thread sleep, and recieving a message > > triggers the server thread while I'm typing... Maybe there is some > > sort of better thread management for this? Or is this just a limiting > > factor since I'm playing in the console world? The other issue I have > > is when the other person types DSC to end their session, I should be > > able to put the thread to sleep, or trash it or something so I dont > > have to close the app to use it again. It also isn't going through the > > entire > > > > I was hoping to actually make something more like an IRC server / > > client, but I'm not sure I've got this thing down well enough to try > > that. Thanks! > Sorry, I'm too tired to read your code right now. > A few things I'd like to point out... > yeah, it's tough to show output and get input in the same console > window. A simple TKInter gui would not be all that hard to put together. > Just a textbox and an entry widget. > wouldn't even need a 'send' button if you just bind 'enter' to the send > command from the entry widget. > > Also, IRC is not as complicated as you may think. The messages are all > in ascii. > Basically you just say > > import socket > sock = socket.socket() > sock.connect(('irc.freenode.net',6667)) > sock.send("NICK Bob\r\n") > sock.send("USER Bob irc.freenode.net bla :realname\r\n") > sock.send("JOIN #test\r\n") > sock.send("PRIVMSG #test HELLO!\r\n") > sock.send("LEAVE #test\r\n") > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061109/80ff3935/attachment.htm From carloslara at web.de Fri Nov 10 08:39:46 2006 From: carloslara at web.de (Carlos) Date: Fri, 10 Nov 2006 08:39:46 +0100 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <45542547.9050703@gmail.com> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> Message-ID: <45542CC2.1080105@web.de> Hi, > What? > I think you're talking to someone else here, cause I have no idea what > you mean. > Copy binary numbers from memory? > You mean from any arbitrary memory location you want? > That sounds a lot like C++ pointers to me. That was based on this: > Hi Carlos, > I hope this module would help you with the binary conversion part: > > > def tobits(inte,size = 3): > """Copy an integer's bits from memory""" > s='' > for i in range(size): > s += str((inte & (1<>i) > #bits are extracted right-to-left > s = s[::-1] #reverse the result string > print s > return list(s) > > > > >>>> >>>test = tobits(30,8) >>>> > 00011110 > >>>> >>>test >>>> > ['0', '0', '0', '1', '1', '1', '1', '0'] > > > Cheers, > Rooy But probably (surely) my interpretation is wrong. Hehe And about: > 89+11 = 100, which is longer than the list. :-[ Thanks Luke. Carlos From rabidpoobear at gmail.com Fri Nov 10 09:12:57 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 02:12:57 -0600 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <45542CC2.1080105@web.de> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> Message-ID: <45543489.6000708@gmail.com> > But probably (surely) my interpretation is wrong. Hehe > Ah, well, it's just the terminology you were using was a bit misleading. You say ' Hey Rooy, so its possible to copy binary numbers from memory?' All his function does is converts an integer (that's in memory, yes) into a binary number. It doesn't copy the binary bit arrangement directly from memory. It uses mathematical operations on an integer in base-10, that it gets from the binary in memory, to convert it to base-2. You could do the same for 16, or 32, or 64, or base 256 numbers if you wanted to. The point I'm trying to make is that it's not extracting the actual bits from the memory location or anything like that. It's just converting bases. It doesn't matter that the number is stored as binary cause to Python it's an integer. Think of it like this. This is what's happening Memory Python Binary_function [ 0000001] -> 1 -> [0000001] It's not going from here Memory Python [0000100] -> 4 To here... Memory Python [0000100] -> [0000100] Do you see what I mean? Python still sees the memory location as an integer, so it still stores the value (within python) in base-10, not in base-2. So even though the memory location has the actual bits, we can't access them. We can only get access to the python base-10 value. But it's fairly trivial to convert this integer into a binary list. It _is_ going through 2 conversions, though, the binary isn't directly accessed, as I got the impression you thought. ' I had the impression that this could be done, but obviously it is too much for me. This way is going to be faster than the hack that I tried before, right? Thanks for the module : )' I didn't see the hack you did before, so I don't know. But what he sent was a function, not a module. A module is quite a bit more of a complicated beastie than a function is. the wikipedia definition goes something like this: 'a *module* is a software entity that groups a set of (typically cohesive ) subprograms and data structures . Modules are units that can be compiled separately, which makes them reusable and allows multiple programmers to work on different modules simultaneously. Modules also promote modularity and encapsulation (i.e. information hiding ), both of which can make complex programs easier to understand.' Not sure what exactly a module is (I get it confused with packages) in Python. Perhaps someone can help here? >> 89+11 = 100, which is longer than the list. >> > > Thanks Luke. > Sure, glad to help :-] From kent37 at tds.net Fri Nov 10 12:34:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Nov 2006 06:34:49 -0500 Subject: [Tutor] Some sample code: review? In-Reply-To: References: Message-ID: <455463D9.7020705@tds.net> Danny Yoo wrote: > Hi everyone, > > > I wrote up some sample code to make a more extensible str()-like function. > I'd like some comments before putting it up onto the Python Cookbook: Hi Danny, This looks very clean to me. It is surprisingly complex but I don't see how to make it simpler. Some of the names and comments are confusing, I've commented below. Other than that it looks good to me. Kent > > ##################################################################### > class DeepStr: > """Deep stringifier.""" > def __init__(self, default_str=str, > recursive_str=lambda obj, dstr: "..."): > """Creates a new DeepStr. Once constructed, call as if this > were a function that takes objects and returns strings. > > default_str is the default function used on types that this > does not recognize. What are the arguments to default_str? dstr is not a very explanatory name, maybe deep_str would be better. > > If we hit structure that's already been traversed, > uses recursive_str to represent that structure.""" > self.__handlers = [] > self.__default_str = default_str > self.__recursive_str = recursive_str > > def __call__(self, obj): > """Takes a datum and returns a string of that object.""" > return self.__deepstr(obj, {}) > > def __deepstr(self, obj, _seen): I would call it 'seen', it isn't an attribute so why the _ ? > if id(obj) in _seen: > return self.__recursive_str(obj, self) > _seen[id(obj)] = True > > for h in self.__handlers: > result = h(obj, lambda o: self.__deepstr(o, _seen)) > if result != None: > return result > return self.__default_str(obj) > > def register(self, handler): > """register: (object (object -> string) -> string or None) Maybe it's just me but I don't have a clue what 'object (object -> string)' is trying to convey. > Registers a new handler type. Handers take in the object > as well as a str() function, and returns either a string maybe call it a deep_str() function, that will make the analogy clearer. > if it can handle the object, or None otherwise. The second > argument should be used on substructures.""" > self.__handlers.append(handler) > > > def handle_list(obj, dstr): > if isinstance(obj, list): > return "[" + ", ".join([dstr(x) for x in obj]) + "]" > return None > > def handle_tuple(obj, dstr): > if isinstance(obj, tuple): > return "(" + ", ".join([dstr(x) for x in obj]) + ")" > return None > > def handle_dict(obj, dstr): > if isinstance(obj, dict): > return ("{" + > ", ".join([dstr(k) + ':' + dstr(v) > for (k, v) in obj.items()]) + > "}") > return None > > dstr = DeepStr() > dstr.register(handle_list) > dstr.register(handle_tuple) > dstr.register(handle_dict) > ##################################################################### > > > The idea is that Python's str() on lists uses repr() on internal > structure, which some people might consider a little wacky. dstr(), on > the other hand, will go all the way deeply through a structure, using the > same stringifier. It's also open for extension so that it can handle > different container types in the future. > > Any comments would be greatly appreciated. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Fri Nov 10 13:36:52 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 10 Nov 2006 12:36:52 -0000 Subject: [Tutor] Some sample code: review? References: <455463D9.7020705@tds.net> Message-ID: "Kent Johnson" wrote >> def register(self, handler): >> """register: (object (object -> string) -> string or None) > > Maybe it's just me but I don't have a clue what 'object (object -> > string)' is trying to convey. This might be an interesting test of the legibility but I read that as being: register takes a handler argument that should be a callable object which in turn takes a stringlike argument and returns either a string or None Thus def f(s): if s and isinstance(s,str) : return s else: return None f would be a valid value for handler. Is that what you meant Danny? Otherwise I agree with all that Kent has said. Alan G. From magoldfish at gmail.com Fri Nov 10 15:24:15 2006 From: magoldfish at gmail.com (Marcus Goldfish) Date: Fri, 10 Nov 2006 09:24:15 -0500 Subject: [Tutor] __init__.py for running a file from commandline? Message-ID: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> Hoping someone can help with this... I have a logical python namespace using a directory tree and __init__.py files. For example, PYTHONPATH points to ~pyroot, and I have the following: ~pyroot/ ~pyroot/utils/ ~pyroot/utils/commands/mygrep.py Which makes it nice to code: # some python script import utils.commands.mygrep as grep However, I have a problem when running python scripts from the command line. I would like to do this: > python utils.commands.mygrep.py but it doesn't work. Is there a trick, or something that I am missing, that will let me run scripts like that? Thanks! Marcus ps-- WinXP, python 2.4 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061110/a34b401f/attachment.html From rabidpoobear at gmail.com Fri Nov 10 15:46:37 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 08:46:37 -0600 Subject: [Tutor] __init__.py for running a file from commandline? In-Reply-To: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> References: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> Message-ID: <455490CD.2040506@gmail.com> Marcus Goldfish wrote: > Hoping someone can help with this... > > I have a logical python namespace using a directory tree and > __init__.py files. For example, PYTHONPATH points to ~pyroot, and I > have the following: > > ~pyroot/ > ~pyroot/utils/ > ~pyroot/utils/commands/mygrep.py > > Which makes it nice to code: > > # some python script > import utils.commands.mygrep as grep > > However, I have a problem when running python scripts from the command > line. I would like to do this: > > > python utils.commands.mygrep.py Well, there's no way for Python to know that you want the dots to specify subdirectories, and not part of the filename,is there? I guess you'd have to change into that directory to run the script. > > but it doesn't work. Is there a trick, or something that I am > missing, that will let me run scripts like that? > > Thanks! > Marcus > > ps-- WinXP, python 2.4 > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From picioslug at gmail.com Fri Nov 10 16:02:37 2006 From: picioslug at gmail.com (Picio) Date: Fri, 10 Nov 2006 16:02:37 +0100 Subject: [Tutor] SAX, DOM, XSLT api Message-ID: <825bef0c0611100702g185e2315oe55d97cacf17b143@mail.gmail.com> Hello, what are the equivalent Pyhton tools you suggest to handle: SAX DOM and which api for XSLT ? I know that this is a really newbie question...But I'm a true python newbie ;) ! Daniele P.s: I know I can also google-it a little bit to find those answers but your advices are better. From Mike.Hansen at atmel.com Fri Nov 10 16:21:09 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Fri, 10 Nov 2006 08:21:09 -0700 Subject: [Tutor] First realscript + Game of Life Message-ID: <57B026980605A64F9B23484C5659E32E3CA6EC@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Luke Paireepinart > Sent: Friday, November 10, 2006 12:08 AM > To: Carlos > Cc: tutor at python.org > Subject: Re: [Tutor] First realscript + Game of Life > > > > > Since there has been some talk about the list itself, when > some of you > > reply to my posts sometimes I get a mail straight to my > account. This > > is very useful because it lets me see the reply before it > is posted on > > the list and because in this way is easier to keep track of > the info > > that is useful for me. The question is: is this a personal > option from > > the person who replys? I would like to have all my answers > this way, > > is it possible? > You get a direct mail when people use the 'reply-all' feature. > I use that exclusively. > I figure if enough people are aggravated by it, they'll get > the admin to > add reply-munging so replies > only go straight to the whole list like on Pygame. > Otherwise, I use reply-all so I don't have to type in > 'tutor at python.org' > every time. > The side effect of other people getting the e-mails is > generally not too > annoying, > because the list is smart enough to not send you an extra copy anyway. > So unless you use the Digest method, you shouldn't notice a > difference > at all. > > > > Thanks a lot for your help. > Sure thing. > > > > Happy coding, > You too. > > Carlos > -Luke http://www.python.org/infogami-faq/tutor/tutor-why-do-my-replies-go-to-t he-person-who-sent-the-message-and-not-to-the-list/ Or http://tinyurl.com/uns5q -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From Mike.Hansen at atmel.com Fri Nov 10 16:26:45 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Fri, 10 Nov 2006 08:26:45 -0700 Subject: [Tutor] SAX, DOM, XSLT api Message-ID: <57B026980605A64F9B23484C5659E32E3CA6EF@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Picio > Sent: Friday, November 10, 2006 8:03 AM > To: tutor at python.org > Subject: [Tutor] SAX, DOM, XSLT api > > Hello, > what are the equivalent Pyhton tools you suggest to handle: > SAX > DOM > > and which api for XSLT ? > > I know that this is a really newbie question...But I'm a true > python newbie ;) ! > Daniele > > P.s: I know I can also google-it a little bit to find those answers > but your advices are better. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Here's a list of all the XML parsing modles that come with Python 2.5. Element Tree seems to be the more popular way of parsing XML in Python. I believe you can download Element Tree for older vesions of Python. http://docs.python.org/lib/markup.html Here's an article on XSLT tools for Python... http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/python-xslt Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From mr.ryanwilson at gmail.com Fri Nov 10 16:40:13 2006 From: mr.ryanwilson at gmail.com (Ryan Wilson) Date: Fri, 10 Nov 2006 10:40:13 -0500 Subject: [Tutor] Windows Registry Message-ID: <6fc118c60611100740y70403ec3i3723678a5d3506a@mail.gmail.com> >I am currently working on a project that in a small part of it I need to find keys in the >windows registry. I have found _winreg but was wondering if anyone knows of any modules >that people have written as a wrapper for it. I have googled like crazy but am not finding >anything. What I trying to do is search the registry for a list of known keys without knowing >their specific locations and then find values of the other keys around it. Hope that makes >sence. I also am working on a scripts that serches the registry for key terms. I have found that this works a a substitute. import codecs os.popen("reg export hklm regFile.txt") regfile = codecs.open(regFile.txt, encoding='utf_16') #Then you can do text searches in the file somthing like for item in regfile: if '[' in item print item -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061110/a1220db5/attachment.htm From ph34r_th3_d4rkn3s at hotmail.com Fri Nov 10 17:01:00 2006 From: ph34r_th3_d4rkn3s at hotmail.com (max .) Date: Fri, 10 Nov 2006 09:01:00 -0700 Subject: [Tutor] winsound mac Message-ID: i am starting a small useless program i got from the show lost but cant find a module on mac to make beeping noises i know windows has winsound *never used it but heard about it* but eather way is thair anything like winsound for mac ^_^" s33 y4 _________________________________________________________________ Add a Yahoo! contact to Windows Live Messenger for a chance to win a free trip! http://www.imagine-windowslive.com/minisites/yahoo/default.aspx?locale=en-us&hmtagline From Mike.Hansen at atmel.com Fri Nov 10 17:15:59 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Fri, 10 Nov 2006 09:15:59 -0700 Subject: [Tutor] winsound mac Message-ID: <57B026980605A64F9B23484C5659E32E3CA6FB@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of max . > Sent: Friday, November 10, 2006 9:01 AM > To: tutor at python.org > Subject: [Tutor] winsound mac > > i am starting a small useless program i got from the show > lost but cant find > a module on mac to make beeping noises i know windows has > winsound *never > used it but heard about it* but eather way is thair anything > like winsound > for mac > > > > ^_^" s33 y4 > If you don't get any answers here, you might try the Python Mac Sig. http://www.python.org/community/sigs/current/pythonmac-sig/ Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From dyoo at hkn.eecs.berkeley.edu Fri Nov 10 17:16:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Nov 2006 08:16:31 -0800 (PST) Subject: [Tutor] Some sample code: review? In-Reply-To: References: Message-ID: > Some of the names and comments are confusing, I've commented below. > Other than that it looks good to me. >> def __init__(self, default_str=str, >> recursive_str=lambda obj, dstr: "..."): > > What are the arguments to default_str? Ah, good. I should document that default_str must be able to take any object and return a string. > dstr is not a very explanatory name, maybe deep_str would be better. Ok, I'll change this. >> def __deepstr(self, obj, _seen): > > I would call it 'seen', it isn't an attribute so why the _ ? Good point. Why the heck did I do that? Thanks for catching that. >> def register(self, handler): >> """register: (object (object -> string) -> string or None) > > Maybe it's just me but I don't have a clue what 'object (object -> > string)' is trying to convey. Alan intepreted it the way I intended: > register takes a handler argument that should be a callable object which > in turn takes a stringlike argument and returns either a string or None I should, though, rephrase the signature as: register: object str_function -> string or None to be more readable. Separately, I can then define that a 'str_function' is a callable that takes anything and turns it into a string. Thanks Alan and Kent! From doug.shawhan at gmail.com Fri Nov 10 19:00:32 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 10 Nov 2006 12:00:32 -0600 Subject: [Tutor] Help with Elementtree ...how to access the attributes.. In-Reply-To: <5e58f2e40611091323n37d019d3y9a0fa12cb8e8ed79@mail.gmail.com> References: <5e58f2e40611091323n37d019d3y9a0fa12cb8e8ed79@mail.gmail.com> Message-ID: <5e1ceb8a0611101000l64347835pb6f51babe7ca3dd5@mail.gmail.com> I'm having some difficulties with elementtree as well. I'm attempting to parse a fairly sizeable xml file (it's the ebay "category tree" report. I've cached a copy at http://www.crackrabbit.com/misc/CatTree.xml). 900K or so! :-) For some reason I'm unable to read any elements from the file. I have no problems with Asraramed's example. (I'm not attempting to extract values here, just to make sure that there is actual parsing going on!) #!/usr/bin/env python2.4 from elementtree import ElementTree as et tree = et.parse("kadri.xml") companies = tree.findall('company') for c in companies: print c which gives me: Cool beans. There's something in there! Now when I attempt the same with the data found at the above link: #!/usr/bin/env python2.4 from elementtree import ElementTree as et tree = et.parse('CatTree.xml') categories = tree.findall("CategoryArray") for cat in categories: print cat I receive nothing. I've made a smaller version that I could easily get me brain around: 2006-11-07T07:45:40.908Z Success 485 e485_core_Bundled_3782281_R1 true 6000 1 eBay Motors 6000 false false false false false true which also seems to parse cleanly and appears to be similar to what Asraramed had constructed, but still does not yeild any results no matter which element I attempt to find with findall(). What am I doing wrong? Thanks! On 11/9/06, John Fouhy wrote: > > On 10/11/06, Asrarahmed Kadri wrote: > > I am trying to parse XML documents using elementtree. > > I have just started with it. Can somebody help me with how to select > nodes > > with a particular atribute set to some value. For example, I have the > > following file. Now I want to access the founder element of the company > > whose attribute is set to 'ndtv'. Can somebody help me with this? > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061110/384a5311/attachment.html From tyctor at post.cz Fri Nov 10 19:02:44 2006 From: tyctor at post.cz (=?us-ascii?Q?viktor=20vraniak?=) Date: Fri, 10 Nov 2006 19:02:44 +0100 (CET) Subject: [Tutor] TimedRotatingFileHandler donot rollover Message-ID: <1228.5634-4780-494590548-1163181762@post.cz> hallo i have (i thing) little problem with TimedRotatingFileHandler i have following code to get mylogger: def MyLogger(req, logpath, logfilename): logdir = DEFAULT_LOG_DIR backupcount = DEFAULT_LOG_BACKUPS fmt='%(asctime)s %(msecs)d %(levelname)-8s %(message)s' datefmt='%d%m%Y %H:%M:%S' path = os.path.join(logdir, logpath) if not os.path.exists(path): try: os.makedirs(path, 0775) except: exctype, value = sys.exc_info()[:2] req.log_error("%s, %s" % (str(exctype), str(value))) raise exctype, value filename = os.path.join(path, logfilename) rootLogger = logging.getLogger('MyLogger') if not rootLogger.handlers: rotatingLogger = logging.handlers.TimedRotatingFileHandler(filename, "M", 1, backupcount) formatter = logging.Formatter(fmt=fmt,datefmt=datefmt) rotatingLogger.setFormatter(formatter) rootLogger.addHandler(rotatingLogger) if rotatingLogger.shouldRollover(None): rotatingLogger.doRollover() rootLogger.setLevel(loglevel) return rootLogger but rollover never occurs. (when = 'M' , interval = 1 is for testing) i use logginng in my web application, which runs under mod_python, python 2.4 when i try to log values from inside TimedRotatingFileHandler then i found out that time is always smaller than rolloverAt i want to use logging for midnight rottating, does anyone has this problem too? thanks for help or any answer tyctor From doug.shawhan at gmail.com Fri Nov 10 19:16:51 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 10 Nov 2006 12:16:51 -0600 Subject: [Tutor] Help with Elementtree ...how to access the attributes.. In-Reply-To: <5e1ceb8a0611101000l64347835pb6f51babe7ca3dd5@mail.gmail.com> References: <5e58f2e40611091323n37d019d3y9a0fa12cb8e8ed79@mail.gmail.com> <5e1ceb8a0611101000l64347835pb6f51babe7ca3dd5@mail.gmail.com> Message-ID: <5e1ceb8a0611101016x4fb8e524re8e26a2ae9615a09@mail.gmail.com> Ah. Apparently, the string xmlns="urn:ebay:apis:eBLBaseComponents" is causing some sort of outfreakage. I'm not well versed in xml lore: is the "urn:" tag out of context here? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061110/5d30de55/attachment.html From jfabiani at yolo.com Fri Nov 10 20:43:31 2006 From: jfabiani at yolo.com (johnf) Date: Fri, 10 Nov 2006 11:43:31 -0800 Subject: [Tutor] Second attempt convert DateTimeTyep to datetime.datetime Message-ID: <200611101143.31130.jfabiani@yolo.com> Hi, I'm using FreeTDS (MS SQL database access lib) and for datetime fields it returns a type 'DateTimeType'. I need it in type 'datetime.datetime'. There is very little in the form of a tutorial that explains what I need to do. Can someone help me with this issue. John From alan.gauld at btinternet.com Fri Nov 10 20:59:53 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 10 Nov 2006 19:59:53 -0000 Subject: [Tutor] winsound mac References: Message-ID: "max ." wrote >i am starting a small useless program i got from the show lost but >cant find > a module on mac to make beeping noises I think you can make a Terminal window beep printing the standard ASCII beep character (Ctrl-G?) But the real way to control sound on the Mac is via Quicktime which is part of the whole Quartz/Cocoa framework. But I confess I've never tried using quicktime programatically either in Python or even in ObjectiveC. Try the Mac mailing list and maybe browse the Apple Applescript web pages. You can definitely call applescript from MacPython and there's boundto be a friendly Applescript command to beep Finally, does pygame exist for Macs? If so it has some sound features. HTH, Alan G. From rabidpoobear at gmail.com Fri Nov 10 21:02:56 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 14:02:56 -0600 Subject: [Tutor] Second attempt convert DateTimeTyep to datetime.datetime In-Reply-To: <200611101143.31130.jfabiani@yolo.com> References: <200611101143.31130.jfabiani@yolo.com> Message-ID: <4554DAF0.1070802@gmail.com> johnf wrote: > Hi, > > I'm using FreeTDS (MS SQL database access lib) and for datetime fields it > returns a type 'DateTimeType'. I need it in type 'datetime.datetime'. There > is very little in the form of a tutorial that explains what I need to do. > if a datetimetype object has a __str__ or __repr__ method, you can probably just use datetime.datetime's parsing system to convert it from a string into a datetime.datetime object. > Can someone help me with this issue. > > John > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rabidpoobear at gmail.com Fri Nov 10 21:06:06 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 14:06:06 -0600 Subject: [Tutor] winsound mac In-Reply-To: References: Message-ID: <4554DBAE.4030306@gmail.com> > Finally, does pygame exist for Macs? If so it has > some sound features. > yep, yep. Pygame has mac support. You can use numeric arrays to generate various different sounds. It also has support for playing midi, mp3, ogg, etc. At least in some cases it does. > HTH, > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pyro9219 at gmail.com Fri Nov 10 22:19:12 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 10 Nov 2006 13:19:12 -0800 Subject: [Tutor] Syntax when using classes question. Message-ID: is the following dummycode good practice? Or pythonic? or what? I'm just curious because there are several ways I've found to use libraries and classes... Method 1: from lib import class lib().class(param1, param2) Method 2: (C Style?) from lib import class myClass = class() myLib.class(param1, param2) Thanks for whatever clarity you can share! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061110/9a6c78e7/attachment.htm From carroll at tjc.com Sat Nov 11 00:10:00 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 10 Nov 2006 15:10:00 -0800 (PST) Subject: [Tutor] Which is the latest version of Python for windows In-Reply-To: Message-ID: On Thu, 9 Nov 2006, Chris Hengge wrote: > I've been trying to look for a roadmap or something from them that would > show estimated product release dates. Does this not exist? I sent an email to Trent Mick at Activestate and asked if they had an ETA (and ended with "you guys aren't dropping Python, are you?"). His response (posted with permission): No, definitely not dropping Python. All my time has been focussed on Komodo 4.0 development. I've started picking up ActivePython again just recently, but there is quite a bit of work there: Python 2.5 added quite a bit. My *hope* is to have something in Nov or Dec, but Komodo 4.0 final is planned for mid/late January so it is possible it'll slip. From rabidpoobear at gmail.com Sat Nov 11 01:40:25 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Nov 2006 18:40:25 -0600 Subject: [Tutor] Syntax when using classes question. In-Reply-To: References: Message-ID: <45551BF9.6000709@gmail.com> Chris Hengge wrote: > is the following dummycode good practice? Or pythonic? or what? I'm > just curious because there are several ways I've found to use > libraries and classes... > > Method 1: > from lib import class > lib().class(param1, param2) I don't know what you're doing here but I think you may not understand the 'from' syntax. It imports that into the global namespace. so from random import randint will let you call randint(0,10) but not random.randint(0,10) because you never imported random. trying to do random.randint(0,10) will give you a NameError because random is not defined in that namespace. So yes, that's not pythonic, because it's not valid syntax :) > > Method 2: (C Style?) > from lib import class > myClass = class() > myLib.class(param1, param2) I don't understand what this 'myLib.class' comes from. This example doesn't make sense either. HTH, -Luke From dyoo at hkn.eecs.berkeley.edu Sat Nov 11 05:30:49 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 10 Nov 2006 20:30:49 -0800 (PST) Subject: [Tutor] Some sample code: review? In-Reply-To: References: Message-ID: > I should, though, rephrase the signature as: > > register: object str_function -> string or None > > to be more readable. Separately, I can then define that a 'str_function' is > a callable that takes anything and turns it into a string. Ok, I made those changes. I've also fixed a very silly bug. (Basically, it's the same exact bug that the SOAPpy folks did in traversing shallow structures.) Unfortunately, it got longer and more complicated than I wanted. *sigh* Still, here it is: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498261 From rabidpoobear at gmail.com Sat Nov 11 08:34:20 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Nov 2006 01:34:20 -0600 Subject: [Tutor] Syntax when using classes question. In-Reply-To: References: <45551BF9.6000709@gmail.com> <4555369E.1060703@gmail.com> <455555DF.4090906@gmail.com> <45556462.4050608@gmail.com> Message-ID: <45557CFC.9060302@gmail.com> Chris Hengge wrote: > As for saving memory.. I'm not particularily concerned since all my > systems have 2gb... > Also, before python I was writing C# database front ends (nothing > amazing) and I'm not even going to compare python's 10mb overhead to > .net's 45mb+. I was mostly just curious if it would save the memory in > the same manner. > > As for using modules... I'm actually looking at my real code right > now.. (need to not reply to these emails while at work when I can't > really see the code) > in my pyForge module (simple script to hold my common used objects > basically) there is a class promptForge, that contains a method prompt > <-- I know this is a great name =P.... > To call it: > import pyForge # module name > promptForge.prompt() # Class.method > will tell me promptForge is undefined. > so I use: > promptForge().prompt() > will tell me promptForge is undefined Yeah, it's unidentified because it only exists in the imported module's namespace. > so I use: > pyForge.promptForge().prompt() # module.class.method So why did you use two sets of parenthesis here? Are you completely sure you understand everything that's happening here? pyForge. -> now we're working in the module's namespace. promptForge -> the class you're targeting in the pyForge namespace () -> create an instance of the class using the __init__ method. .prompt -> get the method 'prompt' from the instance of the class you just created. () -> execute this method. So why are you creating an instance of promptForge here? > this works. (I just did all this while writing this email.) Yeah, it works, but is it necessary? > When I use: > import random > random.random () #This does its thing... most modules only have > module.whateverThisIs(params) > in my code I've got module.class().method(params)... Am I not > conforming to some sort of module standard? You're just creating an instance when you probably don't mean to. > Are modules supposed to only be filled with methods, No. Then they would be called functions :) methods are functions inside classes that act upon the class' data members (I.E. variables) They're different terms so that people will know what you're talking about. > using the module file itself as the seperation layer in place of using > a class? Yeah, do that if you want just functions. Do you want just functions? I haven't seen your pyForge class, but if you're not using any OO features, like the magical 'self' or the different __repr__, __str__, __getitems__, etc. methods, then why is it in a class in the first place, and not just functions? You can have a module of functions if you want. You can have a module of variables if you want. a module is just the same as having all the stuff declared in your program, except you refer to it all by module name. #----- config.py a = 1 #----- #---- test.py import config print config.a #------ etc. > > FYI... I dont know where it happened, but these last few e-mails are > off tutor. Oops, yeah. This one is forwarded to tutor and if anyone wants to see the previous discussion you can check the reply-stuff below. HTH, -Luke > > On 11/10/06, *Luke Paireepinart* > wrote: > > Chris Hengge wrote: > > Alright, that all makes sense other then one part... > > > Okay! I'm shivering with anticipation :) > > I'm all for you saying to just use: > > import module > > module.class.method () > > I agree this code is easier on the eyes down the road... > > > > but...( And this might be old world C++ coming in and shading my > view) > > In c++ you would be specific aka from module import class so > that you > > could conserve memory by not importing the entire library. Is this > > also true for python? > Ah, well, now we step into sacred territory. > >_>. > The long and short of it is, yes, importing the whole module uses > more > memory. > It shouldn't use significantly more memory. > If you're so constrained for memory that you're considering not using > 'import class' just for this reason, > then you'll be fretting about the 10 mb of overhead (or whatever) the > Python interpreter takes up, I think :) > > In general, in Python, consider "If it makes it easier on me and the > speed impact is not noticeable, why would I make it hard on myself?" > premature optimization is the root of all evil. > In this case, I wouldn't even consider the memory usage in deciding > which syntax you like better. > > > > Final question on the topic that hopefully has a clear answer =P > Oh, let's hope. *crosses fingers* > > When writing a module, is there some special way to do it? Like, do > > they use only classes with no methods inside? Or do they only use > > methods? > > I ask because my pyForge is Class > Methods and to use it I have > to say: > > import module > > module().class().method(stuff) > Are you sure? :D > You should never have to do this. > if you import module, > then everything inside of module is accessed the same way it would > be if > it were in your program, > just with a 'module.' prepended to it. > Imagine it like this. > > #----- > #test.py > def aFunction(): > print "hello" > aFunction() > #----- > obviously outputs hello. > > Now consider these two files. > > #----- > # module.py > def aFunction(): > print "hello" > aVariable = "hi" > #------ > how would you use this in your test.py script? > > #----- > #test-version2.py > import module > module.aFunction() > print module.aVariable > #------- > You'll see > "hello > hi" > as the output for this script. > > The 'import module' syntax you can imagine as it creating a new > variable > that points to the _entire_ script 'module.py' and everything > inside of it. > > So I don't think you'd ever have to do > 'module().class().function()' > in fact, I know you would never need to do that. > A simple test: > > import random > random() > > raises a TypeError: 'module' object is not callable. > > Do not think of a module as a class, cause it's not. > it's just a separate namespace. > So the 'from module import *' just says to get rid of that extra > level > of namespaces > that isolates those module functions from overwriting or interfering > with my own functions, > and just put them all as global, and trust me not to accidentally > overwrite them later. > > > > > but when I go to use most of the "standard libraries" I can just > write > > something like > > import module > > module.method/class?(stuff) > Yeah. you should always have to have a module., never a > module()., as I > hope the above explanation clarifies. > > > > Thanks again for your patience and clear answers Luke! > Sure! It helps me to think about things like this too :) > > Also, one final thing: > You can have a class that you don't instantiate but still create > instances of inner classes. > > for example, > >>> > class foo(object): > class bar(object): > def __init__(self): > print "Initializing bar!" > > >>> foo.bar () > Initializing bar! > <__main__.bar object at 0x00B536D0> > >>> foo > > >>> foo() > <__main__.foo object at 0x00B53830> > >>> foo().bar() > Initializing bar! > <__main__.bar object at 0x00B53890> > > You see, there's really no reason to initialize this class ('foo'), > because 'foo' is just holding the 'bar' class for us. > yeah, you can initialize 'foo' if you want, but it does exactly > the same > thing uninitialized, because it has no instance methods or variables, > or, in other words, nothing with 'self' in it. > I just thought of this because of your > " > I ask because my pyForge is Class > Methods and to use it I have > to say: > import module > module().class().method(stuff) > " > comment. > Let's assume you meant > module.class().method(stuff) > since module() raises an exception :) > so if you were doing this, it would mean on each call, > you're creating an instance of the class called 'class' and calling a > method on that instance, > but you're not storing the instance anywhere, so it's just > disappearing. > remember when we were talking about that before? > It's possible that you need to instantiate it but not keep a copy > around, but it's probable that this isn't what you wanted to do, > and you just put the () cause you thought they needed to go there. > > > HTH, > -Luke > > From pyro9219 at gmail.com Sat Nov 11 09:05:56 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 11 Nov 2006 00:05:56 -0800 Subject: [Tutor] Syntax when using classes question. In-Reply-To: <45557CFC.9060302@gmail.com> References: <45551BF9.6000709@gmail.com> <4555369E.1060703@gmail.com> <455555DF.4090906@gmail.com> <45556462.4050608@gmail.com> <45557CFC.9060302@gmail.com> Message-ID: >So why did you use two sets of parenthesis here? >Are you completely sure you understand everything that's happening here? pyForge.promptForge.prompt() TypeError: unbound method prompt() must be called with promptForge instance as first argument (got nothing instead) ^ Thats why... I have to use : import pyForge pyForge.promptForge().prompt >Do you want just functions? >I haven't seen your pyForge class, but if you're not using any OO features, >like the magical 'self' or the different __repr__, __str__, >__getitems__, etc. methods, >then why is it in a class in the first place, and not just functions? Because I was trying to get a grip on classes and OOP... =P pyForge for lack of a better description is kinda like my own mini-framework. It's basically all the methods(functions?) that I've basically rewritten in each of my python files that I grouped together into classes by functionality. For example, pyForge has class fileforge which has two methods, one for writing, and one for reading files. Each takes a few different parameters but it makes an entire block of code transparent so that when I'm trying to show someone my code at work its less to look at. There is a class for a "console based splashscreen" called promptForge which has a "EULA" mode enabled by bool and takes a few parameters. I've also got zipForge which is very similar to my fileForge, but zips/unzips. I might add a few more things that I've repeated... It was mainly an attempt at learning classes, and I wanted all my re-usable code to be centralized so I didn't keep opening scripts and cutting and pasting. On 11/10/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > As for saving memory.. I'm not particularily concerned since all my > > systems have 2gb... > > Also, before python I was writing C# database front ends (nothing > > amazing) and I'm not even going to compare python's 10mb overhead to > > .net's 45mb+. I was mostly just curious if it would save the memory in > > the same manner. > > > > As for using modules... I'm actually looking at my real code right > > now.. (need to not reply to these emails while at work when I can't > > really see the code) > > in my pyForge module (simple script to hold my common used objects > > basically) there is a class promptForge, that contains a method prompt > > <-- I know this is a great name =P.... > > To call it: > > import pyForge # module name > > promptForge.prompt() # Class.method > > will tell me promptForge is undefined. > > so I use: > > promptForge().prompt() > > will tell me promptForge is undefined > Yeah, it's unidentified because it only exists in the imported module's > namespace. > > so I use: > > pyForge.promptForge().prompt() # module.class.method > So why did you use two sets of parenthesis here? > Are you completely sure you understand everything that's happening here? > > pyForge. -> now we're working in the module's namespace. > promptForge -> the class you're targeting in the pyForge namespace > () -> create an instance of the class using the __init__ method. > .prompt -> get the method 'prompt' from the instance of the class you > just created. > () -> execute this method. > > So why are you creating an instance of promptForge here? > > this works. (I just did all this while writing this email.) > Yeah, it works, but is it necessary? > > When I use: > > import random > > random.random () #This does its thing... most modules only have > > module.whateverThisIs(params) > > in my code I've got module.class().method(params)... Am I not > > conforming to some sort of module standard? > You're just creating an instance when you probably don't mean to. > > Are modules supposed to only be filled with methods, > No. > Then they would be called functions :) > methods are functions inside classes that act upon the class' data > members (I.E. variables) > They're different terms so that people will know what you're talking > about. > > using the module file itself as the seperation layer in place of using > > a class? > Yeah, do that if you want just functions. > Do you want just functions? > I haven't seen your pyForge class, but if you're not using any OO > features, > like the magical 'self' or the different __repr__, __str__, > __getitems__, etc. methods, > then why is it in a class in the first place, and not just functions? > You can have a module of functions if you want. > You can have a module of variables if you want. > a module is just the same as having all the stuff declared in your > program, except you refer to it all by module name. > > #----- config.py > a = 1 > #----- > #---- test.py > import config > print config.a > #------ > etc. > > > > FYI... I dont know where it happened, but these last few e-mails are > > off tutor. > Oops, yeah. This one is forwarded to tutor and if anyone wants to see > the previous discussion you can check the reply-stuff below. > > HTH, > -Luke > > > > On 11/10/06, *Luke Paireepinart* > > wrote: > > > > Chris Hengge wrote: > > > Alright, that all makes sense other then one part... > > > > > Okay! I'm shivering with anticipation :) > > > I'm all for you saying to just use: > > > import module > > > module.class.method () > > > I agree this code is easier on the eyes down the road... > > > > > > but...( And this might be old world C++ coming in and shading my > > view) > > > In c++ you would be specific aka from module import class so > > that you > > > could conserve memory by not importing the entire library. Is this > > > also true for python? > > Ah, well, now we step into sacred territory. > > >_>. > > The long and short of it is, yes, importing the whole module uses > > more > > memory. > > It shouldn't use significantly more memory. > > If you're so constrained for memory that you're considering not > using > > 'import class' just for this reason, > > then you'll be fretting about the 10 mb of overhead (or whatever) > the > > Python interpreter takes up, I think :) > > > > In general, in Python, consider "If it makes it easier on me and the > > speed impact is not noticeable, why would I make it hard on myself?" > > premature optimization is the root of all evil. > > In this case, I wouldn't even consider the memory usage in deciding > > which syntax you like better. > > > > > > Final question on the topic that hopefully has a clear answer =P > > Oh, let's hope. *crosses fingers* > > > When writing a module, is there some special way to do it? Like, > do > > > they use only classes with no methods inside? Or do they only use > > > methods? > > > I ask because my pyForge is Class > Methods and to use it I have > > to say: > > > import module > > > module().class().method(stuff) > > Are you sure? :D > > You should never have to do this. > > if you import module, > > then everything inside of module is accessed the same way it would > > be if > > it were in your program, > > just with a 'module.' prepended to it. > > Imagine it like this. > > > > #----- > > #test.py > > def aFunction(): > > print "hello" > > aFunction() > > #----- > > obviously outputs hello. > > > > Now consider these two files. > > > > #----- > > # module.py > > def aFunction(): > > print "hello" > > aVariable = "hi" > > #------ > > how would you use this in your test.py script? > > > > #----- > > #test-version2.py > > import module > > module.aFunction() > > print module.aVariable > > #------- > > You'll see > > "hello > > hi" > > as the output for this script. > > > > The 'import module' syntax you can imagine as it creating a new > > variable > > that points to the _entire_ script 'module.py' and everything > > inside of it. > > > > So I don't think you'd ever have to do > > 'module().class().function()' > > in fact, I know you would never need to do that. > > A simple test: > > > > import random > > random() > > > > raises a TypeError: 'module' object is not callable. > > > > Do not think of a module as a class, cause it's not. > > it's just a separate namespace. > > So the 'from module import *' just says to get rid of that extra > > level > > of namespaces > > that isolates those module functions from overwriting or interfering > > with my own functions, > > and just put them all as global, and trust me not to accidentally > > overwrite them later. > > > > > > > > but when I go to use most of the "standard libraries" I can just > > write > > > something like > > > import module > > > module.method/class?(stuff) > > Yeah. you should always have to have a module., never a > > module()., as I > > hope the above explanation clarifies. > > > > > > Thanks again for your patience and clear answers Luke! > > Sure! It helps me to think about things like this too :) > > > > Also, one final thing: > > You can have a class that you don't instantiate but still create > > instances of inner classes. > > > > for example, > > >>> > > class foo(object): > > class bar(object): > > def __init__(self): > > print "Initializing bar!" > > > > >>> foo.bar () > > Initializing bar! > > <__main__.bar object at 0x00B536D0> > > >>> foo > > > > >>> foo() > > <__main__.foo object at 0x00B53830> > > >>> foo().bar() > > Initializing bar! > > <__main__.bar object at 0x00B53890> > > > > You see, there's really no reason to initialize this class ('foo'), > > because 'foo' is just holding the 'bar' class for us. > > yeah, you can initialize 'foo' if you want, but it does exactly > > the same > > thing uninitialized, because it has no instance methods or > variables, > > or, in other words, nothing with 'self' in it. > > I just thought of this because of your > > " > > I ask because my pyForge is Class > Methods and to use it I have > > to say: > > import module > > module().class().method(stuff) > > " > > comment. > > Let's assume you meant > > module.class().method(stuff) > > since module() raises an exception :) > > so if you were doing this, it would mean on each call, > > you're creating an instance of the class called 'class' and calling > a > > method on that instance, > > but you're not storing the instance anywhere, so it's just > > disappearing. > > remember when we were talking about that before? > > It's possible that you need to instantiate it but not keep a copy > > around, but it's probable that this isn't what you wanted to do, > > and you just put the () cause you thought they needed to go there. > > > > > > HTH, > > -Luke > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061111/d2f31ee2/attachment-0001.html From pyro9219 at gmail.com Sat Nov 11 10:42:55 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 11 Nov 2006 01:42:55 -0800 Subject: [Tutor] Syntax when using classes question. In-Reply-To: References: <4555369E.1060703@gmail.com> <455555DF.4090906@gmail.com> <45556462.4050608@gmail.com> <45557CFC.9060302@gmail.com> Message-ID: Oops... should have said this... pyForge.promptForge.prompt() TypeError: unbound method prompt() must be called with promptForge instance as first argument (got nothing instead) ^ Thats why... I have to use : import pyForge pyForge.promptForge().prompt() On 11/11/06, Chris Hengge wrote: > > >So why did you use two sets of parenthesis here? > >Are you completely sure you understand everything that's happening here? > > pyForge.promptForge.prompt() > TypeError: unbound method prompt() must be called with promptForge > instance as first argument (got nothing instead) > > ^ Thats why... I have to use : > import pyForge > pyForge.promptForge().prompt > > >Do you want just functions? > >I haven't seen your pyForge class, but if you're not using any OO > features, > >like the magical 'self' or the different __repr__, __str__, > >__getitems__, etc. methods, > >then why is it in a class in the first place, and not just functions? > > Because I was trying to get a grip on classes and OOP... =P > pyForge for lack of a better description is kinda like my own > mini-framework. It's basically all the methods(functions?) that I've > basically rewritten in each of my python files that I grouped together into > classes by functionality. For example, pyForge has class fileforge which has > two methods, one for writing, and one for reading files. Each takes a few > different parameters but it makes an entire block of code transparent so > that when I'm trying to show someone my code at work its less to look at. > There is a class for a "console based splashscreen" called promptForge which > has a "EULA" mode enabled by bool and takes a few parameters. I've also got > zipForge which is very similar to my fileForge, but zips/unzips. I might add > a few more things that I've repeated... It was mainly an attempt at learning > classes, and I wanted all my re-usable code to be centralized so I didn't > keep opening scripts and cutting and pasting. > > > > On 11/10/06, Luke Paireepinart wrote: > > > > Chris Hengge wrote: > > > As for saving memory.. I'm not particularily concerned since all my > > > systems have 2gb... > > > Also, before python I was writing C# database front ends (nothing > > > amazing) and I'm not even going to compare python's 10mb overhead to > > > .net's 45mb+. I was mostly just curious if it would save the memory in > > > the same manner. > > > > > > As for using modules... I'm actually looking at my real code right > > > now.. (need to not reply to these emails while at work when I can't > > > really see the code) > > > in my pyForge module (simple script to hold my common used objects > > > basically) there is a class promptForge, that contains a method prompt > > > <-- I know this is a great name =P.... > > > To call it: > > > import pyForge # module name > > > promptForge.prompt() # Class.method > > > will tell me promptForge is undefined. > > > so I use: > > > promptForge().prompt() > > > will tell me promptForge is undefined > > Yeah, it's unidentified because it only exists in the imported module's > > namespace. > > > so I use: > > > pyForge.promptForge().prompt() # module.class.method > > So why did you use two sets of parenthesis here? > > Are you completely sure you understand everything that's happening here? > > > > pyForge. -> now we're working in the module's namespace. > > promptForge -> the class you're targeting in the pyForge namespace > > () -> create an instance of the class using the __init__ method. > > .prompt -> get the method 'prompt' from the instance of the class you > > just created. > > () -> execute this method. > > > > So why are you creating an instance of promptForge here? > > > this works. (I just did all this while writing this email.) > > Yeah, it works, but is it necessary? > > > When I use: > > > import random > > > random.random () #This does its thing... most modules only have > > > module.whateverThisIs(params) > > > in my code I've got module.class().method(params)... Am I not > > > conforming to some sort of module standard? > > You're just creating an instance when you probably don't mean to. > > > Are modules supposed to only be filled with methods, > > No. > > Then they would be called functions :) > > methods are functions inside classes that act upon the class' data > > members (I.E. variables) > > They're different terms so that people will know what you're talking > > about. > > > using the module file itself as the seperation layer in place of using > > > a class? > > Yeah, do that if you want just functions. > > Do you want just functions? > > I haven't seen your pyForge class, but if you're not using any OO > > features, > > like the magical 'self' or the different __repr__, __str__, > > __getitems__, etc. methods, > > then why is it in a class in the first place, and not just functions? > > You can have a module of functions if you want. > > You can have a module of variables if you want. > > a module is just the same as having all the stuff declared in your > > program, except you refer to it all by module name. > > > > #----- config.py > > a = 1 > > #----- > > #---- test.py > > import config > > print config.a > > #------ > > etc. > > > > > > FYI... I dont know where it happened, but these last few e-mails are > > > off tutor. > > Oops, yeah. This one is forwarded to tutor and if anyone wants to see > > the previous discussion you can check the reply-stuff below. > > > > HTH, > > -Luke > > > > > > On 11/10/06, *Luke Paireepinart* > > > wrote: > > > > > > Chris Hengge wrote: > > > > Alright, that all makes sense other then one part... > > > > > > > Okay! I'm shivering with anticipation :) > > > > I'm all for you saying to just use: > > > > import module > > > > module.class.method () > > > > I agree this code is easier on the eyes down the road... > > > > > > > > but...( And this might be old world C++ coming in and shading my > > > > > view) > > > > In c++ you would be specific aka from module import class so > > > that you > > > > could conserve memory by not importing the entire library. Is > > this > > > > also true for python? > > > Ah, well, now we step into sacred territory. > > > >_>. > > > The long and short of it is, yes, importing the whole module uses > > > more > > > memory. > > > It shouldn't use significantly more memory. > > > If you're so constrained for memory that you're considering not > > using > > > 'import class' just for this reason, > > > then you'll be fretting about the 10 mb of overhead (or whatever) > > the > > > Python interpreter takes up, I think :) > > > > > > In general, in Python, consider "If it makes it easier on me and > > the > > > speed impact is not noticeable, why would I make it hard on > > myself?" > > > premature optimization is the root of all evil. > > > In this case, I wouldn't even consider the memory usage in > > deciding > > > which syntax you like better. > > > > > > > > Final question on the topic that hopefully has a clear answer =P > > > > > Oh, let's hope. *crosses fingers* > > > > When writing a module, is there some special way to do it? Like, > > do > > > > they use only classes with no methods inside? Or do they only > > use > > > > methods? > > > > I ask because my pyForge is Class > Methods and to use it I have > > > to say: > > > > import module > > > > module().class().method(stuff) > > > Are you sure? :D > > > You should never have to do this. > > > if you import module, > > > then everything inside of module is accessed the same way it would > > > be if > > > it were in your program, > > > just with a 'module.' prepended to it. > > > Imagine it like this. > > > > > > #----- > > > #test.py > > > def aFunction(): > > > print "hello" > > > aFunction() > > > #----- > > > obviously outputs hello. > > > > > > Now consider these two files. > > > > > > #----- > > > # module.py > > > def aFunction(): > > > print "hello" > > > aVariable = "hi" > > > #------ > > > how would you use this in your test.py script? > > > > > > #----- > > > #test-version2.py > > > import module > > > module.aFunction() > > > print module.aVariable > > > #------- > > > You'll see > > > "hello > > > hi" > > > as the output for this script. > > > > > > The 'import module' syntax you can imagine as it creating a new > > > variable > > > that points to the _entire_ script 'module.py' and everything > > > inside of it. > > > > > > So I don't think you'd ever have to do > > > 'module().class().function()' > > > in fact, I know you would never need to do that. > > > A simple test: > > > > > > import random > > > random() > > > > > > raises a TypeError: 'module' object is not callable. > > > > > > Do not think of a module as a class, cause it's not. > > > it's just a separate namespace. > > > So the 'from module import *' just says to get rid of that extra > > > level > > > of namespaces > > > that isolates those module functions from overwriting or > > interfering > > > with my own functions, > > > and just put them all as global, and trust me not to accidentally > > > overwrite them later. > > > > > > > > > > > but when I go to use most of the "standard libraries" I can just > > > > > write > > > > something like > > > > import module > > > > module.method/class?(stuff) > > > Yeah. you should always have to have a module., never a > > > module()., as I > > > hope the above explanation clarifies. > > > > > > > > Thanks again for your patience and clear answers Luke! > > > Sure! It helps me to think about things like this too :) > > > > > > Also, one final thing: > > > You can have a class that you don't instantiate but still create > > > instances of inner classes. > > > > > > for example, > > > >>> > > > class foo(object): > > > class bar(object): > > > def __init__(self): > > > print "Initializing bar!" > > > > > > >>> foo.bar () > > > Initializing bar! > > > <__main__.bar object at 0x00B536D0> > > > >>> foo > > > > > > >>> foo() > > > <__main__.foo object at 0x00B53830> > > > >>> foo().bar() > > > Initializing bar! > > > <__main__.bar object at 0x00B53890> > > > > > > You see, there's really no reason to initialize this class > > ('foo'), > > > because 'foo' is just holding the 'bar' class for us. > > > yeah, you can initialize 'foo' if you want, but it does exactly > > > the same > > > thing uninitialized, because it has no instance methods or > > variables, > > > or, in other words, nothing with 'self' in it. > > > I just thought of this because of your > > > " > > > I ask because my pyForge is Class > Methods and to use it I have > > > to say: > > > import module > > > module().class().method(stuff) > > > " > > > comment. > > > Let's assume you meant > > > module.class().method(stuff) > > > since module() raises an exception :) > > > so if you were doing this, it would mean on each call, > > > you're creating an instance of the class called 'class' and > > calling a > > > method on that instance, > > > but you're not storing the instance anywhere, so it's just > > > disappearing. > > > remember when we were talking about that before? > > > It's possible that you need to instantiate it but not keep a copy > > > around, but it's probable that this isn't what you wanted to do, > > > and you just put the () cause you thought they needed to go there. > > > > > > > > > HTH, > > > -Luke > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061111/296fd8f1/attachment-0001.htm From alan.gauld at btinternet.com Sat Nov 11 12:59:48 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 11 Nov 2006 11:59:48 -0000 Subject: [Tutor] Syntax when using classes question. References: <4555369E.1060703@gmail.com><455555DF.4090906@gmail.com><45556462.4050608@gmail.com><45557CFC.9060302@gmail.com> Message-ID: Chris, > pyForge.promptForge.prompt() > TypeError: unbound method prompt() must be called with promptForge > instance > as first argument (got nothing instead) > > ^ Thats why... I have to use : > import pyForge > pyForge.promptForge().prompt() I think the real issue that Luke was raising was why you are using that style. Basically you are creating an instance of pyForge just to call the method then it gets deleted again (by garbage collection). Thats a very inefficient function call! The normal usage of classes and objects is that you create an instance and retain it, thus: myForge = pyForge.promptForge() myForge.prompt() ... # and use it again myForge.prompt() Thus the myForge instance is retained until you are finished using any of the methods. The reason for that is that the instance will hold the data used by the methods and so if you delete it you delete the data too! For examplein your case you could have promptForge hold the prompt message you want to display. That could nbe initialised in the constructor, thus you could have several promptForge instances each with a different prompt message, lie this: class promptForge: def __init__(self.,msg = "? "): self.message = msg self.value = None # stores last input value def prompt(self): print self.message, self.value = raw_input() return self.value And use it thus: yes_no = promptForge("Continue? [Y/N] ") quit = promptForge("Hit Y to quit") intValue = promptForge("Enter an integer between 0 and 9") if yes_no.prompt() in "yY": for n in range(3): x = int(intValue.prompt()) print x if quit.prompt() in "yY2: break But if you don't have any internal data, you don;t really need instances... Now it looks like you have created some classes with no shared data just functions(methods). In that case you would be better just using functions inside the module. Its easier to use and also has a lower resource usage and potentially lower call overhead (no method lookup/dispatch) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Nov 11 13:28:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Nov 2006 07:28:20 -0500 Subject: [Tutor] Help with Elementtree ...how to access the attributes.. In-Reply-To: <5e1ceb8a0611101000l64347835pb6f51babe7ca3dd5@mail.gmail.com> References: <5e58f2e40611091323n37d019d3y9a0fa12cb8e8ed79@mail.gmail.com> <5e1ceb8a0611101000l64347835pb6f51babe7ca3dd5@mail.gmail.com> Message-ID: <4555C1E4.7020609@tds.net> doug shawhan wrote: > I'm having some difficulties with elementtree as well. > > I'm attempting to parse a fairly sizeable xml file (it's the ebay > "category tree" report. I've cached a copy at > http://www.crackrabbit.com/misc/CatTree.xml). 900K or so! :-) > I've made a smaller version that I could easily get me brain around: > > > > 2006-11-07T07:45:40.908Z > Success > 485 > e485_core_Bundled_3782281_R1 > > > true > 6000 > 1 > eBay Motors > 6000 > false > false > false > false > false > true > > > > > which also seems to parse cleanly and appears to be similar to what > Asraramed had constructed, but still does not yeild any results no > matter which element I attempt to find with findall(). > > What am I doing wrong? Thanks! When an XML document is in a namespase, ET includes the name of the namespace as part of the element name and you have to include it when you use findall(). Try categories = tree.findall("{urn:ebay:apis:eBLBaseComponents}CategoryArray") http://effbot.org/zone/element.htm#xml-namespaces Kent From kent37 at tds.net Sat Nov 11 13:33:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Nov 2006 07:33:16 -0500 Subject: [Tutor] Some sample code: review? In-Reply-To: References: Message-ID: <4555C30C.1030303@tds.net> Danny Yoo wrote: >> I should, though, rephrase the signature as: >> >> register: object str_function -> string or None >> >> to be more readable. Separately, I can then define that a 'str_function' is >> a callable that takes anything and turns it into a string. > > Ok, I made those changes. I've also fixed a very silly bug. (Basically, > it's the same exact bug that the SOAPpy folks did in traversing shallow > structures.) What was the bug? Kent From kent37 at tds.net Sat Nov 11 13:44:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Nov 2006 07:44:56 -0500 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <45543489.6000708@gmail.com> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> <45543489.6000708@gmail.com> Message-ID: <4555C5C8.6060806@tds.net> Luke Paireepinart wrote: > >> But probably (surely) my interpretation is wrong. Hehe >> > Ah, well, it's just the terminology you were using was a bit misleading. > You say > ' Hey Rooy, so its possible to copy binary numbers from memory?' > All his function does is converts an integer (that's in memory, yes) > into a binary number. > It doesn't copy the binary bit arrangement directly from memory. It > uses mathematical operations on an integer in base-10, that it gets from > the binary in memory, to convert it to base-2. > You could do the same for 16, or 32, or 64, or base 256 numbers if you > wanted to. > The point I'm trying to make is that it's not extracting the actual bits > from the memory location or anything like that. > It's just converting bases. It doesn't matter that the number is stored > as binary cause to Python it's an integer. > Think of it like this. > > This is what's happening > Memory Python Binary_function > [ 0000001] -> 1 -> [0000001] > > > It's not going from here > Memory Python > [0000100] -> 4 > > To here... > > Memory Python > [0000100] -> [0000100] > > Do you see what I mean? > Python still sees the memory location as an integer, > so it still stores the value (within python) in base-10, not in base-2. > So even though the memory location has the actual bits, we can't access > them. I think you are a bit confused here. It's important to make a distinction between the way a number is actually stored in the computer and the string that is created when a number is printed. Most computers store integers as binary numbers. So the number 21 for example will be stored as the bit pattern 00010100. In order to print this number, Python converts it to a string containing the two characters '2' and '1' (which are themselves stored as the bit patterns 00110010 and 00110001) and outputs those characters to the console. So now we have two representations, the binary number stored in the computer memory and the string representation of the base 10 representation of the number. There are lots of other ways to represent the same number. What Carlos wants is the string representation of the binary representation of the number. This is confusing to talk about because the number is already stored in binary. The module he showed generates this representation. Kent > We can only get access to the python base-10 value. > But it's fairly trivial to convert this integer into a binary list. > It _is_ going through 2 conversions, though, the binary isn't directly > accessed, as I got the impression you thought. > > ' I had the impression that this could be done, but obviously it is too > much for me. This way is going to be faster than the hack that I tried > before, right? Thanks for the module : )' > I didn't see the hack you did before, so I don't know. > But what he sent was a function, not a module. > A module is quite a bit more of a complicated beastie than a function is. > the wikipedia definition goes something like this: > 'a *module* is a software entity that groups a set of (typically > cohesive ) > subprograms and data > structures . Modules are > units that can be compiled > separately, which makes them reusable and allows multiple programmers to > work on different modules simultaneously. Modules also promote > modularity > and encapsulation (i.e. information hiding > ), both of which can > make complex programs easier to understand.' > Not sure what exactly a module is (I get it confused with packages) in > Python. > Perhaps someone can help here? >>> 89+11 = 100, which is longer than the list. >>> >> Thanks Luke. >> > Sure, glad to help :-] > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sat Nov 11 13:53:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Nov 2006 07:53:36 -0500 Subject: [Tutor] datetimetype vs datetime.datetime In-Reply-To: <200611091955.12475.jfabiani@yolo.com> References: <200611091955.12475.jfabiani@yolo.com> Message-ID: <4555C7D0.5000406@tds.net> johnf wrote: > Hi > I'm working on a python interface to freetds. And freetds can access MS SQL > database engines. But I'm having trouble with datatime datatypes. > > The python module I'm using is MSSQL.py written back in 2003. After getting Why are you using such an old version? > it compiled access to MS SQL works if I stay with simple datatypes (int, > varchar). But when the table has a datetime field the MSSQL.py module > returns a 'DateTimeType' i.e. > Jan 13 2006 12:00AM > > The question is how can I convert the 'DateTimeType' to a datetime.datetime? Presumably DateTimeType is the type of mx.DateTime? If so, this is a rich data type that you might be able to use directly. It was popular before Python's datetime module was released. See http://www.egenix.com/files/python/mxDateTime.html#DateTime If you have to convert to datetime.datetime just use the DateTime attributes to extract the data: datetime.datetime(mxd.year, mxd.month, mxd.day) Kent > > John > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sat Nov 11 13:56:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Nov 2006 07:56:45 -0500 Subject: [Tutor] __init__.py for running a file from commandline? In-Reply-To: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> References: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> Message-ID: <4555C88D.3080503@tds.net> Marcus Goldfish wrote: > Hoping someone can help with this... > > I have a logical python namespace using a directory tree and __init__.py > files. For example, PYTHONPATH points to ~pyroot, and I have the following: > > ~pyroot/ > ~pyroot/utils/ > ~pyroot/utils/commands/mygrep.py > > Which makes it nice to code: > > # some python script > import utils.commands.mygrep as grep > > However, I have a problem when running python scripts from the command > line. I would like to do this: > > > python utils.commands.mygrep.py > > but it doesn't work. Is there a trick, or something that I am missing, > that will let me run scripts like that? python utils/commands/mygrep.py will work if mygrep.py doesn't import other modules from utils; not sure if it will work with imports. Kent > > Thanks! > Marcus > > ps-- WinXP, python 2.4 > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From qba_free at op.pl Sat Nov 11 03:12:08 2006 From: qba_free at op.pl (Jakub Jankiewicz) Date: Fri, 10 Nov 2006 18:12:08 -0800 (PST) Subject: [Tutor] SAX, DOM, XSLT api In-Reply-To: <825bef0c0611100702g185e2315oe55d97cacf17b143@mail.gmail.com> References: <825bef0c0611100702g185e2315oe55d97cacf17b143@mail.gmail.com> Message-ID: <7288709.post@talk.nabble.com> picio_slug wrote: > > Hello, > what are the equivalent Pyhton tools you suggest to handle: > SAX > DOM > > and which api for XSLT ? > > I know that this is a really newbie question...But I'm a true python > newbie ;) ! > Daniele > > P.s: I know I can also google-it a little bit to find those answers > but your advices are better. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > There are modules sax and dom in xml package (in Sandarad Library), and greate external package http://www.xml.com/pub/a/2002/09/25/py.html pyXML . -- View this message in context: http://www.nabble.com/SAX%2C-DOM%2C-XSLT-api-tf2608248.html#a7288709 Sent from the Python - tutor mailing list archive at Nabble.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061110/8cad21d8/attachment.htm From ajkadri at googlemail.com Sat Nov 11 15:16:44 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 11 Nov 2006 14:16:44 +0000 Subject: [Tutor] A strange problem... Message-ID: Hi Folks, I am trying to create a XML document and then writing it to a file, But the porblem is that I have to run the program twice before the contents are written to the file. Can you explain the reason for such a strange behaviour ?? The code is as below: from elementtree import ElementTree as etree info = etree.Element('info') co1 = etree.SubElement(info,'company',name='google') etree.SubElement(co1,'founder').text = 'Larry Page' etree.SubElement(co1,'founder').text = 'Sergey Brin' etree.SubElement(co1,'focus').text = 'Search Engine' co2 = etree.SubElement(info,'company',name = 'NDTV') etree.SubElement(co2,'founder').text = 'Pranoy Roy' etree.SubElement(co2,'founder').text = 'Radhika Roy' etree.SubElement(co2,'focus').text = '24/7 News Channel' co3 = etree.SubElement(info,'company',name='WIPRO') etree.SubElement(co3,'founder').text = 'Azim Premjee' etree.SubElement(co3,'focus').text = 'IT Services' fd = open('C:\\samtom.xml','w') e = etree.tostring(info) fd.write(e) -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061111/98eda53f/attachment-0001.htm From skokot at po.opole.pl Sat Nov 11 15:39:13 2006 From: skokot at po.opole.pl (Seweryn Kokot) Date: Sat, 11 Nov 2006 15:39:13 +0100 Subject: [Tutor] A strange problem... References: Message-ID: <87zmay9hf2.fsf@poczta.po.opole.pl> "Asrarahmed Kadri" writes: > > fd.write(e) > > add: fd.close() to your code I hope it helps regards, SK From skokot at po.opole.pl Sat Nov 11 15:52:17 2006 From: skokot at po.opole.pl (Seweryn Kokot) Date: Sat, 11 Nov 2006 15:52:17 +0100 Subject: [Tutor] A strange problem... References: Message-ID: <87velm9gta.fsf@poczta.po.opole.pl> "Asrarahmed Kadri" writes: > fd.write(e) fd.close() > > i hope it helps regards, SK From rabidpoobear at gmail.com Sat Nov 11 17:18:59 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Nov 2006 10:18:59 -0600 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <4555C5C8.6060806@tds.net> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> <45543489.6000708@gmail.com> <4555C5C8.6060806@tds.net> Message-ID: <4555F7F3.3070302@gmail.com> Kent Johnson wrote: > Luke Paireepinart wrote: > >> > working> > > I think you are a bit confused here. > Quite possible! > It's important to make a distinction between the way a number is > actually stored in the computer and the string that is created when a > number is printed. > > Most computers store integers as binary numbers. So the number 21 for > example will be stored as the bit pattern 00010100. In order to print > this number, Python converts it to a string containing the two > characters '2' and '1' (which are themselves stored as the bit patterns > 00110010 and 00110001) and outputs those characters to the console. So > now we have two representations, the binary number stored in the > computer memory and the string representation of the base 10 > representation of the number. > I was trying to make it clear that Python wasn't directly accessing the binary from memory with this function Carlos had. The function just mathematically converted a base-10 number into a base-2 number. The function, if you recall (from Hieu Hoang): >Hi Carlos, >I hope this module would help you with the binary conversion part: > def tobits(inte,size = 3): > """Copy an integer's bits from memory""" > s='' > for i in range(size): > s += str((inte & (1<>i) > #bits are extracted right-to-left > s = s[::-1] #reverse the result string > print s > return list(s) And what Carlos said in response to it, > Hey Rooy, so its possible to copy binary numbers from memory? I had the impression that this could be done, but obviously it is too much for me. This way is going to be faster than the hack that I tried before, right? Thanks for the module : ) I'm not sure why Carlos calls them Rooy. Anyway, I just wanted to make sure that Carlos knew that python wasn't directly copying the binary representation from memory into a list, Python was getting the base-10 integer representation out of the binary, and then the function converted this back again into base2 using binary shifts. I.E. the sentence 'copy binary numbers from memory' made me think Carlos thought the binary was directly copied into a list. I also clarified that it's not a 'module' it's a function. Am I still confused, Kent? From kent37 at tds.net Sat Nov 11 19:25:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Nov 2006 13:25:54 -0500 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <4555F7F3.3070302@gmail.com> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> <45543489.6000708@gmail.com> <4555C5C8.6060806@tds.net> <4555F7F3.3070302@gmail.com> Message-ID: <455615B2.1030207@tds.net> Luke Paireepinart wrote: > I was trying to make it clear that Python wasn't directly accessing the > binary from memory with this function Carlos had. > The function just mathematically converted a base-10 number into a > base-2 number. No. It converts a binary representation of a number into a string representation of the binary representation of the number. There is no base-10 number involved. > > Anyway, I just wanted to make sure that Carlos knew that python wasn't > directly copying the binary representation from memory into a list, > Python was getting the base-10 integer representation out of the binary, No, there is no base-10 representation anywhere in Carlos' program, at least not on any computer he is likely to be using to run the program. > and then the function converted this back again into base2 using > binary shifts. I.E. the sentence 'copy binary numbers from memory' made > me think Carlos thought the binary was directly copied into a list. > I also clarified that it's not a 'module' it's a function. > > Am I still confused, Kent? Yes. Maybe someone else can explain better than me? Kent From rabidpoobear at gmail.com Sat Nov 11 19:48:23 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Nov 2006 12:48:23 -0600 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <455615B2.1030207@tds.net> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> <45543489.6000708@gmail.com> <4555C5C8.6060806@tds.net> <4555F7F3.3070302@gmail.com> <455615B2.1030207@tds.net> Message-ID: <45561AF7.4030402@gmail.com> Kent Johnson wrote: > Luke Paireepinart wrote: >> I was trying to make it clear that Python wasn't directly accessing >> the binary from memory with this function Carlos had. >> The function just mathematically converted a base-10 number into a >> base-2 number. > > No. It converts a binary representation of a number into a string > representation of the binary representation of the number. There is no > base-10 number involved. Binary is base-2. Decimal is base-10. Integers in python are base-10. Python doesn't give him direct access to the bits in memory. It gives him a base-10 integer (a decimal number) he uses a mathematical conversion to go from a decimal integer to a list of binary bits. Do you disagree? The argument to the function is an integer. >> > >> Anyway, I just wanted to make sure that Carlos knew that python >> wasn't directly copying the binary representation from memory into a >> list, >> Python was getting the base-10 integer representation out of the binary, > > No, there is no base-10 representation anywhere in Carlos' program, at > least not on any computer he is likely to be using to run the program. > >> and then the function converted this back again into base2 using >> binary shifts. I.E. the sentence 'copy binary numbers from memory' >> made me think Carlos thought the binary was directly copied into a list. >> I also clarified that it's not a 'module' it's a function. >> >> Am I still confused, Kent? > > Yes. Maybe someone else can explain better than me? > > Kent > > From kent37 at tds.net Sat Nov 11 20:17:44 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Nov 2006 14:17:44 -0500 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <45561AF7.4030402@gmail.com> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> <45543489.6000708@gmail.com> <4555C5C8.6060806@tds.net> <4555F7F3.3070302@gmail.com> <455615B2.1030207@tds.net> <45561AF7.4030402@gmail.com> Message-ID: <455621D8.4020603@tds.net> Luke Paireepinart wrote: > Kent Johnson wrote: >> Luke Paireepinart wrote: >>> I was trying to make it clear that Python wasn't directly accessing >>> the binary from memory with this function Carlos had. >>> The function just mathematically converted a base-10 number into a >>> base-2 number. >> No. It converts a binary representation of a number into a string >> representation of the binary representation of the number. There is no >> base-10 number involved. > Binary is base-2. yes > Decimal is base-10. yes > Integers in python are base-10. no. Integers are represented in whatever form the C language implementation uses which on most modern computers is binary. When integers are printed in Python, the string representation of the integer is in base-10. The underlying integer is probably not in base 10. > Python doesn't give him direct access to the bits in memory. right > It gives him a base-10 integer (a decimal number) no. > he uses a mathematical conversion to go from a decimal integer to a list > of binary bits. no, he uses a mathematical conversion to go from a number represented in the internal format used by the C implementation (probably binary) to a list of '0' and '1' characters which represent binary bits. > Do you disagree? yes. You have to make a distinction between the bit pattern used to represent the integer value, which is binary, and the character pattern used to represent the integer. Kent > The argument to the function is an integer. >>> Anyway, I just wanted to make sure that Carlos knew that python >>> wasn't directly copying the binary representation from memory into a >>> list, >>> Python was getting the base-10 integer representation out of the binary, >> No, there is no base-10 representation anywhere in Carlos' program, at >> least not on any computer he is likely to be using to run the program. >> >>> and then the function converted this back again into base2 using >>> binary shifts. I.E. the sentence 'copy binary numbers from memory' >>> made me think Carlos thought the binary was directly copied into a list. >>> I also clarified that it's not a 'module' it's a function. >>> >>> Am I still confused, Kent? >> Yes. Maybe someone else can explain better than me? >> >> Kent >> >> > > > From rabidpoobear at gmail.com Sat Nov 11 21:38:21 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Nov 2006 14:38:21 -0600 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <455621D8.4020603@tds.net> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> <45543489.6000708@gmail.com> <4555C5C8.6060806@tds.net> <4555F7F3.3070302@gmail.com> <455615B2.1030207@tds.net> <45561AF7.4030402@gmail.com> <455621D8.4020603@tds.net> Message-ID: <455634BD.3060906@gmail.com> Okay, so let's see where we are. Integers, as well as strings, and everything else, are stored in memory as binary. This is a given, because the architecture of the computer is binary. You say 'the string representation of the integer is in base-10.' Okay, well, python's representation of any object is different from what it's stored as, which is binary. So why do we care how it's stored? >>> a = 'a' This is actually >>> ord(a) 97 a single byte that is stored in memory as 97 = 1100001. Depending on the C implementation of a character. But since it's a python string, and hence a python object, it also has methods tied to it. The actual data that represents the character 'a' is somewhere in memory still stored as '1100001'. If we want the binary representation of the character, we can't get to it directly. So we get the value of the ord function (which is an integer that is stored as binary but represented as base-10 (which we also cannot access the binary for)) and we use some mathematical tricks to convert from the base-10 representation to a binary one. I know it's not stored as base-10. This is perfectly clear to me. However, in Python this is inconsequential. I don't need to know the IEEE binary format for defining floats to know that a = '.001' will work. That number's in base-10, and it will be converted to base-2, because that's how the C implementation of float stores its floats. It may lose some precision here. What I'm trying to get at is that in python, we see the numbers represented in specific bases. a = 0x2F This is a base-16 number. It's stored as binary by the C implementation, but we don't care because that doesn't matter at all to us, and we can't access the binary anyway. Basically, everything is stored as binary, but you don't say, given the code astr = 'hello, how are you!' 'well yes, the string representation of astr is 'hello, how are you!' but it's stored in memory as binary.' I don't see why you do for integers. I hope you don't see this as disrespectful. I'm just not sure what you're getting at here. You said: >no, he uses a mathematical conversion to go from a number represented in the internal format used by the C implementation (probably binary) to a list of '0' and '1' characters which represent binary bits. No he doesn't. He uses a mathematical conversion to go from a number represented in python as a base-10 number (which is represented by the C implementation as a binary number) to a list of '0' and '1' characters that represent binary bits. He doesn't ever deal with the actual C representation of the binary number. He deals with the python representation on top of that, which is decimal. >You have to make a distinction between the bit pattern used to represent the integer value, which is binary, and the character pattern used to represent the integer. I do. The bit pattern used to represent the integer value is binary in memory. The way the integer is presented _to the programmer_ in python is decimal, which you term the 'character pattern'. This distinction was the whole point of these e-mails, because Carlos said that he could 'access the binary from memory' and put it into a list, but what was really happening was that his program was taking the python 'character pattern' representation, which is in base-10, decimal, and using mathematical tricks to manipulate it back into the base-2 bit pattern. His program doesn't deal with the internal representation of the integer as base-2, it deals with the external representation of base-10. If it could access the internal representation, the program would be much more simple. bitpattern = list(integer.bits) or something. Hopefully ;) -Luke From Joel.Levine at Dartmouth.EDU Sat Nov 11 21:40:42 2006 From: Joel.Levine at Dartmouth.EDU (Joel Levine) Date: 11 Nov 2006 15:40:42 -0500 Subject: [Tutor] numpy memory muncher Message-ID: <71933843@newdancer.Dartmouth.EDU> I'm using, perhaps misusing numpy which is eating up the memory and, eventually crashing my program. Isolating it, the following piece of code continually eats memory. Is it my program or what ...? Thanks Joel Levine Using Mac OSX 10.4.7 Not clear on versions: Appears to be 0.9.8 with py2.4 ----------------- from numpy import * a=zeros((2000,100),float) while True: for row in range(2000): for col in range(100): x=a[row,col] #if x!=0: print "?" From pyro9219 at gmail.com Sun Nov 12 00:34:16 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 11 Nov 2006 15:34:16 -0800 Subject: [Tutor] Syntax when using classes question. In-Reply-To: References: <455555DF.4090906@gmail.com> <45556462.4050608@gmail.com> <45557CFC.9060302@gmail.com> Message-ID: I guess I'm just lost as to the point of classes... Outside of using them to abstract a collection of methods that have similair roles I dont see the point.. But when I group similar methods together (promptForge is a bad example, but I've got class fileForge which has a few file writing or reading methods), people tell me its overkill (basicaly) =P On 11/11/06, Alan Gauld wrote: > > Chris, > > > pyForge.promptForge.prompt() > > TypeError: unbound method prompt() must be called with promptForge > > instance > > as first argument (got nothing instead) > > > > ^ Thats why... I have to use : > > import pyForge > > pyForge.promptForge().prompt() > > I think the real issue that Luke was raising was why you are using > that style. > Basically you are creating an instance of pyForge just to call the > method > then it gets deleted again (by garbage collection). Thats a very > inefficient > function call! > > The normal usage of classes and objects is that you create an > instance and retain it, thus: > > myForge = pyForge.promptForge() > myForge.prompt() > ... > # and use it again > myForge.prompt() > > Thus the myForge instance is retained until you are finished using > any of the methods. > > The reason for that is that the instance will hold the data used > by the methods and so if you delete it you delete the data too! > For examplein your case you could have promptForge hold the > prompt message you want to display. That could nbe initialised > in the constructor, thus you could have several promptForge > instances each with a different prompt message, lie this: > > class promptForge: > def __init__(self.,msg = "? "): > self.message = msg > self.value = None # stores last input value > def prompt(self): > print self.message, > self.value = raw_input() > return self.value > > And use it thus: > > yes_no = promptForge("Continue? [Y/N] ") > quit = promptForge("Hit Y to quit") > intValue = promptForge("Enter an integer between 0 and 9") > > if yes_no.prompt() in "yY": > for n in range(3): > x = int(intValue.prompt()) > print x > if quit.prompt() in "yY2: break > > But if you don't have any internal data, you don;t really > need instances... > > Now it looks like you have created some classes with no > shared data just functions(methods). In that case you would > be better just using functions inside the module. Its easier to > use and also has a lower resource usage and potentially > lower call overhead (no method lookup/dispatch) > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061111/5040e0e5/attachment.html From cappy2112 at gmail.com Sun Nov 12 01:26:57 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sat, 11 Nov 2006 16:26:57 -0800 Subject: [Tutor] using CVS through Python Message-ID: <8249c4ac0611111626k65de294ex82cb03262747cd2f@mail.gmail.com> I need to do some automated checkouts of CVS projects from Python scripts, and want ot be able to handle success and failure conditions. While sending the command lines to cvs isn't a problem, I could use some suggestions for how to check the cvs responses. Parsing the text returned from CVS isn't a good idea, since I don't know all of the possible combinations of strings indicating sucess of failure. I wasn't able to find any wrappers for Python by googling. Suggestions pelase.. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061111/20b975a1/attachment.htm From rabidpoobear at gmail.com Sun Nov 12 01:28:12 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Nov 2006 18:28:12 -0600 Subject: [Tutor] Syntax when using classes question. In-Reply-To: References: <455555DF.4090906@gmail.com> <45556462.4050608@gmail.com> <45557CFC.9060302@gmail.com> Message-ID: <45566A9C.2030502@gmail.com> Chris Hengge wrote: > I guess I'm just lost as to the point of classes... Outside of using > them to abstract a collection of methods that have similair roles I > dont see the point.. But when I group similar methods together > (promptForge is a bad example, but I've got class fileForge which has > a few file writing or reading methods), people tell me its overkill > (basicaly) =P Have you tried reading Alan Gauld's tutorial on classes? I'm sure he explains their purpose quite well. Classes can be used to group similar methods together, but so can modules, and that's usually what people do. the point in using classes is when you have similar functions all operating on a single set of data. that's the key. If you find yourself calling the functions and passing in arguments, you're probably doing it wrong :) Something like this #proc.py class ProcessFile(object): def input_file(self): f = file(filename) self.text = f.readlines() f.close() def __init__(self,filename): self.filename = filename input_file() def display_filename_and_contents(self): print "Filename: %s" % self.filename print "Contents:" for line in self.text: print line.strip() print "END.\n\n" def change_file(self,filename): self.filename = filename input_file() #input1.txt I am a cat. What is the plural of Syllabus? Can the penguin wear the hat, mommy, please? That walrus looks absurdly skinny. It weighs 800 pounds! That's not so much.... for a walrus. #input2.txt What... is the air-speed velocity of an unladen swallow? African or European? #<(-_- )----> and so endeth the example codeth. Now you can easily do something like this (in proc.py as well) myfile = ProcessFile('input1.txt') myfile.display_filename_and_contents() myfile.change_file('input2.txt') myfile.display_filename_and_contents() will give you an output like this: Filename: input1.txt Contents: I am a cat. What is the plural of Syllabus? Can the penguin wear the hat, mommy, please? That walrus looks absurdly skinny. It weighs 800 pounds! That's not so much.... for a walrus. END. Filename: input2.txt Contents: What... is the air-speed velocity of an unladen swallow? African or European? END. See, the main idea here is that, because these functions operate on the same dataset, you give them all equal access to the data by putting them in a class and making the data attributes of the class. For example, view the input_file function. It doesn't need you to tell it what the filename is, because it gets it from the instance variable self.filename It doesn't need to return a value because it sticks the inputted text into self.text() Now a self.text() file exists that contains the text of the file. If you weren't doing this in a class, and you wanted multiple functions to act upon the contents of a file, you'd do something like f = file('input1.txt') text = f.readlines() f.close() function1(text) function2(text) function3(text) etc. Now, if these were all in a class, you could just have an instance variable self.text that contains the data in the class, and you wouldn't have to pass this to every function. HTH, -Luke From bgailer at alum.rpi.edu Sun Nov 12 01:28:53 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 11 Nov 2006 16:28:53 -0800 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <45561AF7.4030402@gmail.com> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> <45543489.6000708@gmail.com> <4555C5C8.6060806@tds.net> <4555F7F3.3070302@gmail.com> <455615B2.1030207@tds.net> <45561AF7.4030402@gmail.com> Message-ID: <45566AC5.9080903@alum.rpi.edu> Luke Paireepinart wrote: >>> The function just mathematically converted a base-10 number into a >>> base-2 number. >>> For what its worth - we say "base 10" to mean "decimal". But 10 = decimal only when we have already agreed we are talking decimal! Consider a planet where residents have 8 fingers. They count 0 1 2 3 4 5 6 7 10 11. When referring to their number system they also say "base 10". Ditto for any other number base. So recognize there is tacit agreement that we are speaking decimal unless we say otherwise. Also if you told a "binary" person that his base was 2 he could not understand that. To him it is base 10 -- Bob Gailer 510-978-4454 From rabidpoobear at gmail.com Sun Nov 12 01:39:15 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Nov 2006 18:39:15 -0600 Subject: [Tutor] First realscript + Game of Life In-Reply-To: <45566AC5.9080903@alum.rpi.edu> References: <4553B409.50504@web.de> <45542547.9050703@gmail.com> <45542CC2.1080105@web.de> <45543489.6000708@gmail.com> <4555C5C8.6060806@tds.net> <4555F7F3.3070302@gmail.com> <455615B2.1030207@tds.net> <45561AF7.4030402@gmail.com> <45566AC5.9080903@alum.rpi.edu> Message-ID: <45566D33.9040004@gmail.com> Bob Gailer wrote: > Luke Paireepinart wrote: >>>> The function just mathematically converted a base-10 number into a >>>> base-2 number. >>>> > For what its worth - we say "base 10" to mean "decimal". But 10 = > decimal only when we have already agreed we are talking decimal! > Consider a planet where residents have 8 fingers. They count 0 1 2 3 4 > 5 6 7 10 11. When referring to their number system they also say "base > 10". Ditto for any other number base. Yeah, thanks for pointing that out. :) From alan.gauld at btinternet.com Sun Nov 12 01:40:28 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 12 Nov 2006 00:40:28 -0000 Subject: [Tutor] Syntax when using classes question. References: <455555DF.4090906@gmail.com><45556462.4050608@gmail.com><45557CFC.9060302@gmail.com> Message-ID: Chris, >I guess I'm just lost as to the point of classes... Outside of using >them to > abstract a collection of methods that have similair roles Most people get hung up on the data aspect of classes and forget that the behaviour(the methods) are actually the most important bit. However you have focused so much on the methods you haven't noticed the data. The point of classes is that they encapsulate data and the functions that operate on that data. A classs that only has functions is just a collection of functions that could sit equally well in a module. A class enables you to capture state between method calls in data that is local and unique to the instance. If there is no shared data between the methods then there is little need for a class. (There are a few exceptions to that rule but not many). You have to think of the methods of a class as being the operations on a set of shared data. Consider a string class; of what use would the strip() method be if there was no sequence of characters within the class to operate on? or the lower() method etc... Similarly for files. If there was no file object then what would you read() or write() to? > But when I group similar methods together A class is not a group of *similar* methods, it is a set of *related* methods - related through the data upon which they operate. Think of a class as an object template, a noun. Think what things you can do to such an object. A common, although not always effective, technique for identifying classes is to read (or write down if it doesn't exist) a description of your problem or program. Underline the nouns. Those are your classes. Now pick out the verbs and attach them to the nouns. Those are your methods. Finally look at the adjectives, those are likely indicators of attributes of your classes. Its simple and not always the best analysis technique but its a good way to start. > promptForge is a bad example, As I hoped I'd shown a promptForge class would be entirely appropriate if it had some data that related to the methods. It could present a standard prompt message, apply consistent error checking, do datya conersions etc etc. > people tell me its overkill OOP can often be overkill, it is frequently abused. OOP is great for bigger programs and good for aiding resuse. But functions can be just as reusable where no intermediate or shared data is involved. If your programs are short there is less likeliehood that you will find object useful. As your programs get longer objects rapidly become powerful tools. But don;t get hung up on them. They are not superior by divine right, they are just one more tool in your toolbox. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pyro9219 at gmail.com Sun Nov 12 02:43:02 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 11 Nov 2006 17:43:02 -0800 Subject: [Tutor] Syntax when using classes question. In-Reply-To: References: <45556462.4050608@gmail.com> <45557CFC.9060302@gmail.com> Message-ID: Thanks for the great feedback! I was missing the whole "methods that share the same data" aspect of a class.. Thats makes them MUCH more clear to understand. Thanks for both of you having the patience to help me figure this out =D Time for me to ditch the classes from my pyForge.py! On 11/11/06, Alan Gauld wrote: > > Chris, > > >I guess I'm just lost as to the point of classes... Outside of using > >them to > > abstract a collection of methods that have similair roles > > Most people get hung up on the data aspect of classes > and forget that the behaviour(the methods) are actually > the most important bit. However you have focused so > much on the methods you haven't noticed the data. > > The point of classes is that they encapsulate data and the > functions that operate on that data. A classs that only has > functions is just a collection of functions that could sit > equally well in a module. A class enables you to capture > state between method calls in data that is local and > unique to the instance. If there is no shared data between > the methods then there is little need for a class. (There are > a few exceptions to that rule but not many). You have to > think of the methods of a class as being the operations > on a set of shared data. > > Consider a string class; of what use would the strip() method > be if there was no sequence of characters within the class > to operate on? or the lower() method etc... Similarly for files. > If there was no file object then what would you read() or > write() to? > > > But when I group similar methods together > > A class is not a group of *similar* methods, it is a set of > *related* methods - related through the data upon which > they operate. Think of a class as an object template, a noun. > Think what things you can do to such an object. > > A common, although not always effective, technique for > identifying classes is to read (or write down if it doesn't > exist) a description of your problem or program. Underline > the nouns. Those are your classes. Now pick out the > verbs and attach them to the nouns. Those are your methods. > Finally look at the adjectives, those are likely indicators of > attributes of your classes. > > Its simple and not always the best analysis technique but > its a good way to start. > > > promptForge is a bad example, > > As I hoped I'd shown a promptForge class would be > entirely appropriate if it had some data that related to > the methods. It could present a standard prompt message, > apply consistent error checking, do datya conersions etc etc. > > > people tell me its overkill > > OOP can often be overkill, it is frequently abused. > OOP is great for bigger programs and good for aiding resuse. > But functions can be just as reusable where no intermediate > or shared data is involved. If your programs are short there > is less likeliehood that you will find object useful. As your > programs get longer objects rapidly become powerful tools. > But don;t get hung up on them. They are not superior by divine > right, they are just one more tool in your toolbox. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061111/55e3537f/attachment.html From dyoo at hkn.eecs.berkeley.edu Sun Nov 12 03:45:28 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 11 Nov 2006 18:45:28 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 33, Issue 48 In-Reply-To: References: Message-ID: >>> I should, though, rephrase the signature as: >>> >>> register: object str_function -> string or None >>> >>> to be more readable. Separately, I can then define that a 'str_function' is >>> a callable that takes anything and turns it into a string. >> >> Ok, I made those changes. I've also fixed a very silly bug. (Basically, >> it's the same exact bug that the SOAPpy folks did in traversing shallow >> structures.) > > What was the bug? If the stringifier saw two instances of the same object, it'd think that recursion was going on. Unfortunately, since the numbers between 1-100 are typically interned (as well as strings), it'd also think that if I visited "0" twice,that I was in a recursive loop too. I got around it by special casing the "shallow types": ######################################################################## def make_shallow_recursive_str(recursion_label): shallow_types = ((bool, int, float, long, complex, types.NoneType) + types.StringTypes) def f(obj, deep_str): if isinstance(obj, shallow_types): return deep_str(obj) return recursion_label return f ######################################################################## But this is a kludge, though, and I feel bad because the code now is very tricky. The real problem is design: I really should be monitoring recursive loops only when I'm visiting container types. I could rearrange the code a bit so that it limits recursion tests to just that. I'll think about it a bit more to make sure it doesn't look too ugly. From dyoo at hkn.eecs.berkeley.edu Sun Nov 12 04:41:17 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 11 Nov 2006 19:41:17 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 33, Issue 48 In-Reply-To: References: Message-ID: >> What was the bug? > > If the stringifier saw two instances of the same object, it'd think that > recursion was going on. Unfortunately, since the numbers between 1-100 > are typically interned (as well as strings), it'd also think that if I > visited "0" twice,that I was in a recursive loop too. The test cases from the bottom of: http://hashcollision.org/svn/repos/projects/misc/deepstr/deepstr.py especially testRepeatedObjects() and testNonRecursion(), failed with the older code. The way I'm doing it now is much better, even though it's still very subtle. I like the code though, just because it isolates the hard part about writing a function like this. Once we have DeepStr, the implementation of the deep_str function is simple. Of course, all of this is already implemented deep in the bowels of Python already, but I wanted to make something extensible. Anyway, thanks again for the feedback; I'm considering this a done project for now. *grin* From dyoo at hkn.eecs.berkeley.edu Sun Nov 12 05:12:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 11 Nov 2006 20:12:14 -0800 (PST) Subject: [Tutor] church numerals In-Reply-To: References: Message-ID: >>>> The function just mathematically converted a base-10 number into a >>>> base-2 number. >>>> > For what its worth - we say "base 10" to mean "decimal". But 10 = > decimal only when we have already agreed we are talking decimal! > Consider a planet where residents have 8 fingers. They count 0 1 2 3 4 5 > 6 7 10 11. When referring to their number system they also say "base > 10". Ditto for any other number base. > > So recognize there is tacit agreement that we are speaking decimal > unless we say otherwise. > > Also if you told a "binary" person that his base was 2 he could not > understand that. To him it is base 10 Just to add confusion to this issue: it sounds like we're really talking about positional number representations. http://en.wikipedia.org/wiki/Positional_notation In order to concisely talk about numbers, we resort to positional notation because we're trained to do so. But because it's the default, there might be the belief that decimal notation is the ONLY way we can talk about numbers. But if we were wacky, we could just as easily represent numbers using a different representation other than positional notation. We already know of one way: drawing lines. But here's one that may look very shocking: ############################# >>> def zero(s, z): ... return z ... >>> def one(s, z): ... return s(z) ... >>> def add1(n): ... def new_number(s, z): ... return s(n(s, z)) ... return new_number ... >>> two = add1(one) >>> three = add1(two) ############################# Believe it or not, these things actually work like numbers: ######################### >>> def iszero(n): ... def s(x): ... return False ... return n(s, True) ... >>> iszero(zero) True >>> iszero(one) False >>> iszero(two) False >>> iszero(three) False >>> >>> def add(n1, n2): ... def new_number(s, z): ... return n1(s, n2(s, z)) ... return new_number ... >>> iszero(add(zero, zero)) True >>> iszero(add(zero, one)) False >>> >>> def mul(n1, n2): ... def new_number(s, z): ... return n1(lambda z: n2(s, z), z) ... return new_number ... >>> iszero(mul(zero, zero)) True >>> iszero(mul(zero, one)) True >>> iszero(mul(zero, two)) True >>> iszero(mul(one, two)) False >>> iszero(mul(mul(one, two), zero)) True ########################## And we can even convert this crazy thing back to something familiar: ############################################################ >>> def church_numeral_to_python_number(n): ... def s(n): return n + 1 ... return n(s, 0) ... >>> church_numeral_to_python_number(add(one, mul(two, two))) 5 ############################################################ The code above is a demonstration of a representation of numbers using functions, more commonly known as "Church Numerals". Functions are very powerful. *grin* So the fundamental notation of number isn't necessarily tied down to anything except the operations we use on them. We find it very convenient to use positional notation because it takes advantage of our fingers and our eyes; just don't be fooled into thinking that there's only one way to represent number. From rabidpoobear at gmail.com Sun Nov 12 06:31:41 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Nov 2006 23:31:41 -0600 Subject: [Tutor] church numerals In-Reply-To: References: Message-ID: <4556B1BD.9060501@gmail.com> Danny Yoo wrote: > > The code above is a demonstration of a representation of numbers using > functions, more commonly known as "Church Numerals". Functions are very > powerful. *grin* > > > So the fundamental notation of number isn't necessarily tied down to > anything except the operations we use on them. We find it very convenient > to use positional notation because it takes advantage of our fingers and > our eyes; just don't be fooled into thinking that there's only one way to > represent number. > That was a really interesting link. Thanks, Danny. I never thought of our time as a base-60 number. (referring to the Sexagesimal System subsection of that link) Oh, and the church numerals were quite breathtaking :) -Luke From dyoo at hkn.eecs.berkeley.edu Sun Nov 12 20:38:05 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 12 Nov 2006 11:38:05 -0800 (PST) Subject: [Tutor] church numerals (fwd) Message-ID: [Forwarding to tutor. Asrarahmed, please learn to use the "Reply to All" feature on your email client.] ---------- Forwarded message ---------- Date: Sun, 12 Nov 2006 11:03:42 +0000 From: Asrarahmed Kadri To: Danny Yoo Subject: Re: [Tutor] church numerals > Believe it or not, these things actually work like numbers: > > ######################### >>>> def iszero(n): > ... def s(x): > ... return False > ... return n(s, True) Where is n() defined ...????? From jfabiani at yolo.com Sun Nov 12 21:29:08 2006 From: jfabiani at yolo.com (johnf) Date: Sun, 12 Nov 2006 12:29:08 -0800 Subject: [Tutor] dump class question Message-ID: <200611121229.08388.jfabiani@yolo.com> Hi, Is it possible to a single that contains two classes: Myclass.py file contains: Class one(object): def needsomething(self): Class two (object): def dosomething(self): I want Class one's methods to access Class two methods? Class one(object): def needsomething(self): return dosomething() Thanks From alan.gauld at btinternet.com Sun Nov 12 22:24:02 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 12 Nov 2006 21:24:02 -0000 Subject: [Tutor] dump class question References: <200611121229.08388.jfabiani@yolo.com> Message-ID: "johnf" wrote > Myclass.py file contains: > > Class one(object): > def needsomething(self): > Class two (object): > def dosomething(self): > > I want Class one's methods to access Class two methods? Thats pretty wierd and would suggest a problem in your class design. Can you elaborate on why you think that would be necessary? What is more common is for a method to want to access another object's methods and that is achieved by either passing the object in as an argument to the method or by having the instance stored in the class (possibly as a part of initialisation) > Class one(object): > def needsomething(self): > return dosomething() return self.aTwo.dosomething() Or def needsomething(self,aTwo): return aTwo.dosomething() Do either of those scenarions meet your needs? It is possible to access a class's methods without instantiating the class but the results would be "interesting" in this case I suspect. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Nov 12 23:19:57 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 12 Nov 2006 22:19:57 -0000 Subject: [Tutor] church numerals (fwd) References: Message-ID: > From: Asrarahmed Kadri >> ######################### >>>>> def iszero(n): >> ... def s(x): >> ... return False >> ... return n(s, True) > > > Where is n() defined ...????? n is a parameter of the function. Thus to call iszero you need to pass in another function which in turn takes a function and a boolean as its arguments. Going back to Danny's original example: >>> def zero(s, z): ... return z ... >>> def one(s, z): ... return s(z) Both of these "numbers" match the type of fuction that iszero expects. So we can do: iszero(zero) Now n takes on the vale of zero and the return line of iszero becomes: return zero(s,True) and zero returns its second argument which is True, so zero is zero, as expected. For iszero(one) the return line is return one(s,True) but inside one the return is now return s(True), but the return value of s is False. So the ultimate reurtn value of iszero(one) is False, again as expected. This is fairly mind bending the first time you come across it so don;t panic,ust work your way through a few more examples as I did above. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alain_belisle at videotron.ca Mon Nov 13 15:07:24 2006 From: alain_belisle at videotron.ca (=?iso-8859-1?Q?Alain_B=E9lisle?=) Date: Mon, 13 Nov 2006 09:07:24 -0500 Subject: [Tutor] (no subject) Message-ID: <000601c7072d$0bb9d7c0$6400a8c0@compaq27951177> Hello, my name is Alain , as you will guess, i'm new at programming python, i bought a book, Python Programming Second Edition, for the absolute beginner. In the second chapter , the Game Over program, using triple quotes strings , even after checking to see if my code was well writing from the examples, i am not able to see the big block text from the string ? Can someone tell me why , thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061113/1dac5fd4/attachment.html From ajkadri at googlemail.com Mon Nov 13 15:39:24 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 13 Nov 2006 14:39:24 +0000 Subject: [Tutor] Not able to store result between function call.. Help needed Message-ID: Hi Folks, I have a textbox and a button (in tkinter). What I want is the following functionality: The user enters a number in the text box and presses the button. The event will call a function called "adder" and when the user enters another value and presses the button, the 'adder' function is again called and the summation of both the numbers is displayed. The problem is I am not able to store the value of 'result' variable. I want to make it persistant between the function calls. TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061113/fa025fd1/attachment.htm From doug.shawhan at gmail.com Mon Nov 13 16:06:42 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Mon, 13 Nov 2006 09:06:42 -0600 Subject: [Tutor] Help with Elementtree ...how to access the attributes.. In-Reply-To: <4555C1E4.7020609@tds.net> References: <5e58f2e40611091323n37d019d3y9a0fa12cb8e8ed79@mail.gmail.com> <5e1ceb8a0611101000l64347835pb6f51babe7ca3dd5@mail.gmail.com> <4555C1E4.7020609@tds.net> Message-ID: <5e1ceb8a0611130706k1265cd35kf03a57d99679d99b@mail.gmail.com> Oho! Thanks, Kent (and everyone else.) That clears up some things. The link has some embarassment reducing info as well. :-) On 11/11/06, Kent Johnson wrote: > > doug shawhan wrote: > > I'm having some difficulties with elementtree as well. > > > > I'm attempting to parse a fairly sizeable xml file (it's the ebay > > "category tree" report. I've cached a copy at > > http://www.crackrabbit.com/misc/CatTree.xml). 900K or so! :-) > > > I've made a smaller version that I could easily get me brain around: > > > > > > > > 2006-11-07T07:45:40.908Z > > Success > > 485 > > e485_core_Bundled_3782281_R1 > > > > > > true > > 6000 > > 1 > > eBay Motors > > 6000 > > false > > false > > false > > false > > false > > true > > > > > > > > > > which also seems to parse cleanly and appears to be similar to what > > Asraramed had constructed, but still does not yeild any results no > > matter which element I attempt to find with findall(). > > > > What am I doing wrong? Thanks! > > When an XML document is in a namespase, ET includes the name of the > namespace as part of the element name and you have to include it when > you use findall(). > > Try categories = > tree.findall("{urn:ebay:apis:eBLBaseComponents}CategoryArray") > > http://effbot.org/zone/element.htm#xml-namespaces > > Kent > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061113/dc5741da/attachment.htm From kent37 at tds.net Mon Nov 13 16:12:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Nov 2006 10:12:29 -0500 Subject: [Tutor] (no subject) In-Reply-To: <000601c7072d$0bb9d7c0$6400a8c0@compaq27951177> References: <000601c7072d$0bb9d7c0$6400a8c0@compaq27951177> Message-ID: <45588B5D.1050306@tds.net> Alain B?lisle wrote: > Hello, my name is Alain , as you will guess, i'm new at programming > python, i bought a book, Python Programming Second Edition, for the > absolute beginner. > In the second chapter , the Game Over program, using triple quotes > strings , even after checking to see if my code was well writing from > the examples, i am not able to see the big block text from the string ? > Can someone tell me why , thanks We really can't tell without seeing your code. Please post your program and the complete error message, if any. Kent From matt.erasmus at gmail.com Mon Nov 13 16:13:25 2006 From: matt.erasmus at gmail.com (Matt Erasmus) Date: Mon, 13 Nov 2006 17:13:25 +0200 Subject: [Tutor] Sloppy Code ? Message-ID: Hi guys Very new to python programming but am really enjoying it. Anyway, I was just wondering if this code could be improved on in anway. ... stdin, stdout, stderr = os.popen3('/bin/hostname -f') system_name = stdout.read() stdin.close() stderr.close() stdout.close() ... report.write("System Report for: ") report.write(system_name) ... Is there a better way of doing this ? It works for what I want to do, but I would like to know if there's another way of doing things.... Thanks in advance. Matt E matt.erasmus (at) gmail (dot) com From noufal at airtelbroadband.in Mon Nov 13 16:16:14 2006 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Mon, 13 Nov 2006 20:46:14 +0530 Subject: [Tutor] Not able to store result between function call.. Help needed In-Reply-To: References: Message-ID: <45588C3E.3080501@airtelbroadband.in> Asrarahmed Kadri wrote: > > > > Hi Folks, > > > I have a textbox and a button (in tkinter). What I want is the following > functionality: The user enters a number in the text box and presses the > button. The event will call a function called "adder" and when the user > enters another value and presses the button, the 'adder' function is > again called and the summation of both the numbers is displayed. > The problem is I am not able to store the value of 'result' variable. I > want to make it persistant between the function calls. Well, you have stated your problem quite succinctly. Can you suggest what an ideal solution could be? -- ~noufal From dyoo at hkn.eecs.berkeley.edu Mon Nov 13 16:27:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 13 Nov 2006 07:27:48 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 33, Issue 52 In-Reply-To: References: Message-ID: > Is it possible to a single that contains two classes: > > Myclass.py file contains: > > Class one(object): > def needsomething(self): > Class two (object): > def dosomething(self): > > I want Class one's methods to access Class two methods? > > Class one(object): > def needsomething(self): > return dosomething() An instance of class one can talk to an instance of class two, if that's what you're trying to do. ##################################################### class Mailbox: def __init__(self): self.messages = [] def accept_message(self, msg): print 'I see a new message', msg.title self.messages.append(msg) class Message: def __init__(self, title, contents): self.title, self.contents = title, contents def insert_into_mailbox(self, mbox): mbox.accept_message(self) ##################################################### Given this, we can make a Mailbox and put a bunch of Messages into it. ############################################################### >>> my_mailbox = Mailbox() >>> message_1 = Message("hello world", "this is a test") >>> message_2 = Message("goodbye world", "thanks for watching") >>> >>> message_1.insert_into_mailbox(my_mailbox) I see a new message hello world >>> message_2.insert_into_mailbox(my_mailbox) I see a new message goodbye world ############################################################### Note that Message.insert_into_mailbox() is expecting to talk to a Mailbox. From bgailer at alum.rpi.edu Mon Nov 13 16:31:04 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 13 Nov 2006 07:31:04 -0800 Subject: [Tutor] Not able to store result between function call.. Help needed In-Reply-To: References: Message-ID: <45588FB8.8090100@alum.rpi.edu> Asrarahmed Kadri wrote: > > > > Hi Folks, > > > I have a textbox and a button (in tkinter). What I want is the > following functionality: The user enters a number in the text box and > presses the button. The event will call a function called "adder" and > when the user enters another value and presses the button, the 'adder' > function is again called and the summation of both the numbers is > displayed. > The problem is I am not able to store the value of 'result' variable. > I want to make it persistant between the function calls. There are at least 3 ways to accomplish persistent storage in Python: global variables class attributes files For your purpose the simplest is a global variable (one that may be assigned a value outside of any function, and/or may be (re)assigned within a function if declared global in the function. Simplest demonstration: def f(): global a a = 3 f() print a > > TIA. > Regards, > Asrarahmed > > -- > To HIM you shall return. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From bgailer at alum.rpi.edu Mon Nov 13 16:32:59 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 13 Nov 2006 07:32:59 -0800 Subject: [Tutor] (no subject) In-Reply-To: <000601c7072d$0bb9d7c0$6400a8c0@compaq27951177> References: <000601c7072d$0bb9d7c0$6400a8c0@compaq27951177> Message-ID: <4558902B.9020108@alum.rpi.edu> Alain B?lisle wrote: > Hello, my name is Alain , as you will guess, i'm new at programming > python, i bought a book, Python Programming Second Edition, for the > absolute beginner. > In the second chapter , the Game Over program, using triple quotes > strings , even after checking to see if my code was well writing from > the examples, i am not able to see the big block text from the string ? > Can someone tell me why , thanks Probably, if we had more information. What does "i am not able to see the big block text from the string" mean? Show us some code and tell us what you were expecting. -- Bob Gailer 510-978-4454 From albs000 at hotmail.com Mon Nov 13 16:48:24 2006 From: albs000 at hotmail.com (=?iso-8859-1?Q?Alain_B=E9lisle?=) Date: Mon, 13 Nov 2006 10:48:24 -0500 Subject: [Tutor] (no subject) Message-ID: Disreguard last message(Big Block text) on my part, bad coding , between me and my keyboard, sorry for that, thanks all for replying. _________________________________________________________________ Soyez parmi les premiers ? essayer Windows Live Mail. http://ideas.live.com/programpage.aspx?versionId=5d21c51a-b161-4314-9b0e-4911fb2b2e6d -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061113/d0301d49/attachment.htm From cbc at unc.edu Mon Nov 13 17:08:47 2006 From: cbc at unc.edu (Chris Calloway) Date: Mon, 13 Nov 2006 11:08:47 -0500 Subject: [Tutor] Houston PyCamp Message-ID: <4558988F.4010300@unc.edu> Need to learn Python quickly? http://trizpug.org/boot-camp/hpyc1/ -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From lkvam at venix.com Mon Nov 13 14:17:54 2006 From: lkvam at venix.com (Lloyd Kvam) Date: Mon, 13 Nov 2006 08:17:54 -0500 Subject: [Tutor] numpy memory muncher In-Reply-To: <71933843@newdancer.Dartmouth.EDU> References: <71933843@newdancer.Dartmouth.EDU> Message-ID: <1163423874.327.11.camel@www.venix.com> On Sat, 2006-11-11 at 15:40 -0500, Joel Levine wrote: > I'm using, perhaps misusing numpy which is eating up the memory and, > eventually crashing my program. OK. that's a small enough piece of code to figure things out. One quick suggestion, for looping variables xrange avoids creating a real list. It provides a lazy evaluation for those cases where you never need the whole range-list to exist as an entity. > > Isolating it, the following piece of code continually eats memory. Is it my program or what ...? > Thanks > Joel Levine > > Using Mac OSX 10.4.7 > Not clear on versions: Appears to be 0.9.8 with py2.4 > > ----------------- > > from numpy import * > > a=zeros((2000,100),float) > while True: > for row in range(2000): > for col in range(100): > x=a[row,col] > #if x!=0: print "?" > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 From kdidriksson at gmail.com Mon Nov 13 17:51:01 2006 From: kdidriksson at gmail.com (Kristinn Didriksson) Date: Mon, 13 Nov 2006 11:51:01 -0500 Subject: [Tutor] what does it mean? Message-ID: Hello, This is my first program calling functions :) It worked nicely except for the message above. Can anyone explain what the message means. Thanks, Kristinn Program ----------------------------- # a program that prints the lyrics for Old Mcdonal had a farm for 5 different animals. # this will have two functions: oldMac and animals # two functions will be passed: animal and sound def animals(animal, sound): # print out the lyrics calling the subroutine for aminals print "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!" print "And on the farm he had a ", animal + ", Ee-igh, Ee-igh, Oh!" print "With a", sound + ",", sound, "here and a" , sound + ",", sound + " there." print "Here a", sound + ", there a", sound + ", everyehere a", sound + ",", sound + "." print "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!" print return animals def oldMac(): print animals("cow", "moo") print animals("pig", "oink") print animals("horse", "neigh") print animals("dog", "woof") print animals("cat", "meow") oldMac() ------------------------------ Output ----------------------------- Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everyehere a moo, moo. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a pig, Ee-igh, Ee-igh, Oh! With a oink, oink here and a oink, oink there. Here a oink, there a oink, everyehere a oink, oink. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a horse, Ee-igh, Ee-igh, Oh! With a neigh, neigh here and a neigh, neigh there. Here a neigh, there a neigh, everyehere a neigh, neigh. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a dog, Ee-igh, Ee-igh, Oh! With a woof, woof here and a woof, woof there. Here a woof, there a woof, everyehere a woof, woof. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a cat, Ee-igh, Ee-igh, Oh! With a meow, meow here and a meow, meow there. Here a meow, there a meow, everyehere a meow, meow. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! ------------------------------- From amar.mehta at lehman.com Mon Nov 13 18:07:27 2006 From: amar.mehta at lehman.com (Mehta, Amar) Date: Mon, 13 Nov 2006 12:07:27 -0500 Subject: [Tutor] what does it mean? In-Reply-To: Message-ID: the function animals returns a reference to itself. the reference is printed in oldMac oldMac can be changed to remove the print statements def oldMac(): animals("cow", "moo") animals("pig", "oink") animals("horse", "neigh") animals("dog", "woof") animals("cat", "meow") you also don't need to return anything from the animals function as it stands. the function as it stands is merely for side effects (ie printing various strings). is the location of the code for the function in the computers RAM. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kristinn Didriksson Sent: Monday, November 13, 2006 11:51 AM To: tutor at python.org Subject: [Tutor] what does it mean? Hello, This is my first program calling functions :) It worked nicely except for the message above. Can anyone explain what the message means. Thanks, Kristinn Program ----------------------------- # a program that prints the lyrics for Old Mcdonal had a farm for 5 different animals. # this will have two functions: oldMac and animals # two functions will be passed: animal and sound def animals(animal, sound): # print out the lyrics calling the subroutine for aminals print "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!" print "And on the farm he had a ", animal + ", Ee-igh, Ee-igh, Oh!" print "With a", sound + ",", sound, "here and a" , sound + ",", sound + " there." print "Here a", sound + ", there a", sound + ", everyehere a", sound + ",", sound + "." print "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!" print return animals def oldMac(): print animals("cow", "moo") print animals("pig", "oink") print animals("horse", "neigh") print animals("dog", "woof") print animals("cat", "meow") oldMac() ------------------------------ Output ----------------------------- Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everyehere a moo, moo. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a pig, Ee-igh, Ee-igh, Oh! With a oink, oink here and a oink, oink there. Here a oink, there a oink, everyehere a oink, oink. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a horse, Ee-igh, Ee-igh, Oh! With a neigh, neigh here and a neigh, neigh there. Here a neigh, there a neigh, everyehere a neigh, neigh. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a dog, Ee-igh, Ee-igh, Oh! With a woof, woof here and a woof, woof there. Here a woof, there a woof, everyehere a woof, woof. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a cat, Ee-igh, Ee-igh, Oh! With a meow, meow here and a meow, meow there. Here a meow, there a meow, everyehere a meow, meow. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! ------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. From nephish at gmail.com Mon Nov 13 19:44:34 2006 From: nephish at gmail.com (shawn bright) Date: Mon, 13 Nov 2006 12:44:34 -0600 Subject: [Tutor] question about __init__ in a class Message-ID: <384c93600611131044o4722ed36m8d17c83db0776c25@mail.gmail.com> Hello there all. i have a class that i need to load some class variables depending on what is passed to the class, it would either be set up using one variable or another. The values for the class variables would be loaded from a database. But how it is looked up depends on how its called. Like this: class Sensor_Object(object): def __init__(self, id, monitor): if id: self.id = id load values from the database value1 = somevalue value2 = someOthervalue else: self.monitor = monitor get some values from database value1 = somevalue value2 = someothervalue now i could call it like this: new_monitor = sensor.Sensor('', 'XJ191') or new_monitor = sensor.Sensor('3433', '') to load based on the other variable. i think that this would work, but i was thinking that there must be a cleaner way to do it. any suggestions ? sk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061113/cc34499e/attachment.htm From klappnase at freenet.de Mon Nov 13 19:51:15 2006 From: klappnase at freenet.de (Michael Lange) Date: Mon, 13 Nov 2006 19:51:15 +0100 Subject: [Tutor] Sloppy Code ? In-Reply-To: References: Message-ID: <20061113195115.06f820f8.klappnase@freenet.de> On Mon, 13 Nov 2006 17:13:25 +0200 "Matt Erasmus" wrote: > Hi guys > > Very new to python programming but am really enjoying it. > > Anyway, I was just wondering if this code could be improved on in anway. > > ... > stdin, stdout, stderr = os.popen3('/bin/hostname -f') > system_name = stdout.read() > stdin.close() > stderr.close() > stdout.close() > ... > report.write("System Report for: ") > report.write(system_name) > ... > > Is there a better way of doing this ? It works for what I want to do, > but I would > like to know if there's another way of doing things.... > import socket print socket.gethostname() I hope this helps Michael From Mike.Hansen at atmel.com Mon Nov 13 19:55:50 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 13 Nov 2006 11:55:50 -0700 Subject: [Tutor] question about __init__ in a class Message-ID: <57B026980605A64F9B23484C5659E32E3CA7B6@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of shawn bright > Sent: Monday, November 13, 2006 11:45 AM > To: tutor-python > Subject: [Tutor] question about __init__ in a class > > Hello there all. > i have a class that i need to load some class variables > depending on what is passed to the class, it would either be > set up using one variable or another. The values for the > class variables would be loaded from a database. But how it > is looked up depends on how its called. Like this: > > class Sensor_Object(object): > def __init__(self, id, monitor): > if id: > self.id = id > load values from the database > value1 = somevalue > value2 = someOthervalue > else: > self.monitor = monitor > get some values from database > value1 = somevalue > value2 = someothervalue > > now i could call it like this: > > new_monitor = sensor.Sensor('', 'XJ191') > or > new_monitor = sensor.Sensor('3433', '') > to load based on the other variable. > > i think that this would work, but i was thinking that there > must be a cleaner way to do it. > any suggestions ? > > sk I don't know if it's cleaner, but it might be easier to read if you use default named arguments. def __init__(self, id = None, monitor = None): Calling it new_monitor = sensor.Sensor(monitor = 'XJ191') new_monitor = sensor.Sensor(id = '3433') Check to make sure one or the other arguments is supplied. Otherwise throw an exception. Maybe there'll be some better ideas from other posters. Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From matt.erasmus at gmail.com Mon Nov 13 20:10:39 2006 From: matt.erasmus at gmail.com (Matt Erasmus) Date: Mon, 13 Nov 2006 21:10:39 +0200 Subject: [Tutor] Sloppy Code ? In-Reply-To: <20061113195115.06f820f8.klappnase@freenet.de> References: <20061113195115.06f820f8.klappnase@freenet.de> Message-ID: Hi Michael Yes, that does help, although it doesn't print the FQDN which is what I'm really after. But thanks to you I now know about the socket module (is that the right terminology ?) and using the Python script in Vim I found socket.getfqdn() which prints exactly what I needed... So my code goes from: stdin, stdout, stderr = os.popen3('/bin/hostname -f') system_name = stdout.read() stdin.close() stderr.close() stdout.close() ... to report.write(socket.getfqdn()) On 13/11/06, Michael Lange wrote: > import socket > print socket.gethostname() > > I hope this helps Thanks so much Michael -Matt From nephish at gmail.com Mon Nov 13 20:12:25 2006 From: nephish at gmail.com (shawn bright) Date: Mon, 13 Nov 2006 13:12:25 -0600 Subject: [Tutor] question about __init__ in a class In-Reply-To: <57B026980605A64F9B23484C5659E32E3CA7B6@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E3CA7B6@poccso.US.ad.atmel.com> Message-ID: <384c93600611131112w2f455561v9235ce2c6a7fedbf@mail.gmail.com> Thats a lot better, thanks, will use it like that. -shawn On 11/13/06, Mike Hansen wrote: > > > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of shawn bright > > Sent: Monday, November 13, 2006 11:45 AM > > To: tutor-python > > Subject: [Tutor] question about __init__ in a class > > > > Hello there all. > > i have a class that i need to load some class variables > > depending on what is passed to the class, it would either be > > set up using one variable or another. The values for the > > class variables would be loaded from a database. But how it > > is looked up depends on how its called. Like this: > > > > class Sensor_Object(object): > > def __init__(self, id, monitor): > > if id: > > self.id = id > > load values from the database > > value1 = somevalue > > value2 = someOthervalue > > else: > > self.monitor = monitor > > get some values from database > > value1 = somevalue > > value2 = someothervalue > > > > now i could call it like this: > > > > new_monitor = sensor.Sensor('', 'XJ191') > > or > > new_monitor = sensor.Sensor('3433', '') > > to load based on the other variable. > > > > i think that this would work, but i was thinking that there > > must be a cleaner way to do it. > > any suggestions ? > > > > sk > > I don't know if it's cleaner, but it might be easier to read if you use > default named arguments. > def __init__(self, id = None, monitor = None): > > Calling it > new_monitor = sensor.Sensor(monitor = 'XJ191') > new_monitor = sensor.Sensor(id = '3433') > > Check to make sure one or the other arguments is supplied. Otherwise > throw an exception. > > Maybe there'll be some better ideas from other posters. > > Mike > > > > > > ------------- > > NOTICE: This e-mail transmission and any documents or files attached to > it contain information for the sole use of the above-identified > individual or entity. > > Its contents may be privileged, confidential, and exempt from disclosure > under the law. > Any dissemination, distribution, or copying of this communication is > strictly prohibited. > > Please notify the sender immediately if you are not the intended > recipient. > > FGNS > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061113/f3e015d3/attachment.htm From kent37 at tds.net Mon Nov 13 20:14:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Nov 2006 14:14:22 -0500 Subject: [Tutor] question about __init__ in a class In-Reply-To: <57B026980605A64F9B23484C5659E32E3CA7B6@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E3CA7B6@poccso.US.ad.atmel.com> Message-ID: <4558C40E.2040908@tds.net> Mike Hansen wrote: > > >> -----Original Message----- >> From: tutor-bounces at python.org >> [mailto:tutor-bounces at python.org] On Behalf Of shawn bright >> Sent: Monday, November 13, 2006 11:45 AM >> To: tutor-python >> Subject: [Tutor] question about __init__ in a class >> >> Hello there all. >> i have a class that i need to load some class variables >> depending on what is passed to the class, it would either be >> set up using one variable or another. > I don't know if it's cleaner, but it might be easier to read if you use > default named arguments. > def __init__(self, id = None, monitor = None): > > Calling it > new_monitor = sensor.Sensor(monitor = 'XJ191') > new_monitor = sensor.Sensor(id = '3433') > > Check to make sure one or the other arguments is supplied. Otherwise > throw an exception. > > Maybe there'll be some better ideas from other posters. That is a good solution. Another way is to make new functions that wrap the constructor. In sensor.py add: def fromId(id): return Sensor(id, None) def fromMonitor(monitor): return Sensor(None, monitor) Then client code is new_monitor = sensor.fromMonitor('XJ191') new_monitor = sensor.fromId('3433') Kent From paulino1 at sapo.pt Mon Nov 13 20:40:55 2006 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Mon, 13 Nov 2006 19:40:55 +0000 Subject: [Tutor] Please comment my script Message-ID: <1163446855.11uyuwusqjpc@w10.mail.sapo.pt> This is a script I have at work, it is running fine (gives the output I want). Any comments are very welcome. It queries a database and gives out a reportlab pdf file with a balance sheet of costs per department. In the first version there were neither functions nor classes, it worked as well, but with no reusability. A second version I defined the functions very close to the ones found here, but had lots of problems because the variables were all local to each function. So I changed direction to this final version. Maybe the matter here is not best suited for OOP. The class definition sounds more like action than object... I think the Query method is the peace of code that is more in need of improvement... Paulino ::::::::::::::::::::::::::::::::::::::::: # -*- coding: latin-1 -*- # Balancete por departamento import sys, re # Importa modulo MS SQL import pymssql con=pymssql.connect(host='gi-clsql', database='baandb',user='baan', password='baan' ) cur=con.cursor() # Importa os modulos ReportLab from reportlab.platypus import * from reportlab.lib.styles import ParagraphStyle from reportlab.lib.units import cm from reportlab.lib import colors from reportlab.platypus.flowables import Flowable def FormCGI() : """Cathes the values 'ano', 'mes' and 'dept' from an HTML form """ import cgi import cgitb; cgitb.enable() form=cgi.FieldStorage() try : ano=form["ano"].value mes=form["mes"].value dept=form["custo"].value return ano, mes, dept except KeyError : print "Content-type: text/html\n\n" print """

Balancete por centro de custo

? necess?rio preencher todos os campos

Centro de custo:
Exercicio: Periodo at?: """ sys.exit(0) class BalanceteCusto: """ Performs a query in a MS SQL database and returns a pdf file containing a report of costs per department """ def __init__(self, ano, mes, dept): self.ano = ano self.mes = mes self.dept = dept self.ppistyle = ParagraphStyle('normal', fontName='helvetica', fontSize=8 ) self.pag=( 21*cm, 29.7*cm) self.PL=self.pag[0] self.PA=self.pag[1] # Largura, altura self.meses={1:'Janeiro', 2:'Fevereiro', 3:'Marco', 4:'Abril', 5:'Maio', 6:'Junho', 7:'Julho', 8:'Agosto', 9:'Setembro', 10:'Outubro', 11:'Novembro', 12:'Dezembro', 13:'Regularizacoes'} self.titulo="BALANCETE POR CENTRO DE CUSTO" self.pdf = 'Balancetecc%s.pdf' %(self.dept) #### Defini??o dos formatos da tabela self.st=[('ALIGN', (2, 0), (-1,-1), 'RIGHT') , ('FONT', (0,1), (-1,-1), 'Helvetica', 8), ('FONT', (0,0), (-1, 0), 'Helvetica', 9), ('FONT', (0,-1), (-1, -1), 'Helvetica', 9), ('LINEBELOW', (0,0), (-1,0), 1, colors.blue), ('TOPPADDING', (0,1), (-1,-1), 1), ('BOTTOMPADDING', (0,1), (-1,-1), 1) ] self.Query() self.CriaPDF() def Formata(self,num): """Formats numbers as the local settings""" import locale locale.setlocale(locale.LC_ALL, '') if num == 0.0 : return '' else : return locale.format("%.*f", (2, num), True) def Pagina(self, canvas, doc) : """Sets the fixed content of the pages (reportlab)""" # Cabe?alho canvas.setFont('Helvetica', 13) # Titulo centrado no papel canvas.drawCentredString( self.PL / 2.0, self.PA - 2*cm, self.titulo) canvas.setFont('Helvetica', 10) #canvas.drawRightString(PL-2.3*cm, PA-3.1*cm, 'De '+dini+' a '+dfim) canvas.drawString( 3.5*cm, self.PA - 2.6*cm, self.subtit1) canvas.drawString( 3.5*cm, self.PA - 3.1*cm, self.subtit2) # Rodape - lado direito canvas.setFont('Helvetica', 8) canvas.drawRightString( self.PL-60, 0.8*cm, 'Pagina %d' %(doc.page) ) canvas.line( 60, 30, self.PL-60, 30) def Acumula(self, item, ctpai) : """Calculates grand-total and subtotals for the itermediate accounts""" tdeb = self.acum[ctpai][1] + item[1] tcred = self.acum[ctpai][2] + item[2] self.acum[ctpai] = [ self.contas[ctpai], tdeb, tcred ] def Desc(self, texto) : """Encodes text as required by reportlab""" #return Paragraph( unicode( re.sub('&', '&', texto) , 'latin-1'), style=ppistyle ) return unicode( texto, 'latin-1') def Query( self ) : cur.execute( """SELECT A.t_leac, SUM(A.t_fdam), SUM(A.t_fcam) FROM ( SELECT c.t_leac, c.t_fdam, c.t_fcam FROM ttfgld202100 c WHERE c.t_cono=100 AND c.t_ptyp=1 AND c.t_year=%s AND c.t_prno<%d AND c.t_dtyp=5 AND c.t_dimx='%s' AND c.t_leac BETWEEN '6' AND '79999') A GROUP BY A.t_leac """ % (self.ano, eval(self.mes)+1, self.dept ) ) valores=cur.fetchall() # Obtem descritivo das contas e centro de custo cur.execute("SELECT gld8.t_leac, gld8.t_desc FROM ttfgld008100 gld8 " ) self.contas={} for i in cur.fetchall() : self.contas[i[0].strip() ] = i[1].strip() cur.execute("SELECT g10.t_desc FROM ttfgld010100 g10 WHERE g10.t_dtyp=5 AND g10.t_dimx='%s'" %(self.dept) ) self.deptdesc=cur.fetchone() self.acum={} self.final=[['Conta', 'Descricao', 'Debito', 'Credito', 'Saldo']] saldo, tdeb, tcred = 0, 0, 0 for v in valores : cta = v[0].strip() saldo=saldo+v[1]-v[2] tdeb=tdeb+v[1] tcred=tcred+v[2] self.acum[cta]=[self.contas[cta], v[1], v[2] ] for n in range(1, len(cta)-1 ) : if cta[:-n] in self.contas.keys() : if cta[:-n] in self.acum.keys() : self.Acumula( v, cta[:-n]) else : self.acum[ cta[:-n] ] = [ self.contas[cta[:-n]], 0, 0 ] self.Acumula( v, cta[:-n]) ak=self.acum.keys() ak.sort() for v in ak : linpdf=[ v, self.Desc( self.acum[v][0] ), self.Formata( self.acum[v][1] ), self.Formata( self.acum[v][2] ), self.Formata( self.acum[v][1]-self.acum[v][2] ) ] self.final.append(linpdf) self.final.append( ['', 'Total', self.Formata(tdeb), self.Formata(tcred), self.Formata(tdeb - tcred) ] ) def CriaPDF(self): doc = SimpleDocTemplate(self.pdf, pagesize=self.pag, topMargin=3*cm, bottomMargin=cm, rightMargin=2.5*cm, leftMargin=2.5*cm) tab=Table( self.final, colWidths=(50, 180, 70, 70, 70), style=self.st, repeatRows=1 ) story=[tab] self.subtit1="Centro de custo: %s - %s " %(self.dept, unicode(self.deptdesc[0], 'latin-1') ) self.subtit2="Ano %s, acumulado ate ao mes de %s" % (self.ano, self.meses[eval(self.mes)] ) doc.build(story, onFirstPage=self.Pagina, onLaterPages=self.Pagina) def GeraHTML(self): print "Content-Type:text/html\n\n

%s

" %(self.titulo) print 'VISUALIZAR' %(self.pdf) print '' if __name__ == '__main__' : for dpt in ('13', '14', '15') : BalanceteCusto( '2006', '10', dpt) con.close() ___________________________________________________________________ O SAPO j? est? livre de v?rus com a Panda Software, fique voc? tamb?m! Clique em: http://antivirus.sapo.pt From uselinux34 at yahoo.co.uk Mon Nov 13 20:35:15 2006 From: uselinux34 at yahoo.co.uk (Richard Gelling) Date: Mon, 13 Nov 2006 19:35:15 -0000 Subject: [Tutor] what does it mean? In-Reply-To: Message-ID: <01b501c7075a$dc136c60$0200a8c0@joanjett> Registered Linux User : 256848 Failure isn't an option -- it comes bundled with Microsoft Windows -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kristinn Didriksson Sent: 13 November 2006 16:51 To: tutor at python.org Subject: [Tutor] what does it mean? Hello, This is my first program calling functions :) It worked nicely except for the message above. Can anyone explain what the message means. Thanks, Kristinn Program ----------------------------- # a program that prints the lyrics for Old Mcdonal had a farm for 5 different animals. # this will have two functions: oldMac and animals # two functions will be passed: animal and sound def animals(animal, sound): # print out the lyrics calling the subroutine for aminals print "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!" print "And on the farm he had a ", animal + ", Ee-igh, Ee-igh, Oh!" print "With a", sound + ",", sound, "here and a" , sound + ",", sound + " there." print "Here a", sound + ", there a", sound + ", everyehere a", sound + ",", sound + "." print "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!" print return animals def oldMac(): print animals("cow", "moo") print animals("pig", "oink") print animals("horse", "neigh") print animals("dog", "woof") print animals("cat", "meow") oldMac() ------------------------------ Output ----------------------------- Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everyehere a moo, moo. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a pig, Ee-igh, Ee-igh, Oh! With a oink, oink here and a oink, oink there. Here a oink, there a oink, everyehere a oink, oink. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a horse, Ee-igh, Ee-igh, Oh! With a neigh, neigh here and a neigh, neigh there. Here a neigh, there a neigh, everyehere a neigh, neigh. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a dog, Ee-igh, Ee-igh, Oh! With a woof, woof here and a woof, woof there. Here a woof, there a woof, everyehere a woof, woof. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on the farm he had a cat, Ee-igh, Ee-igh, Oh! With a meow, meow here and a meow, meow there. Here a meow, there a meow, everyehere a meow, meow. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! ------------------------------- I don't think you need the 'return animals' in the animals function. It is just displaying where the aniaml function is in memory. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From python at venix.com Mon Nov 13 21:05:03 2006 From: python at venix.com (Python) Date: Mon, 13 Nov 2006 15:05:03 -0500 Subject: [Tutor] numpy memory muncher In-Reply-To: <71933843@newdancer.Dartmouth.EDU> References: <71933843@newdancer.Dartmouth.EDU> Message-ID: <1163448303.327.85.camel@www.venix.com> On Sat, 2006-11-11 at 15:40 -0500, Joel Levine wrote: > I'm using, perhaps misusing numpy which is eating up the memory and, > eventually crashing my program. I can reproduce the problem on my Linux system, so it is not Mac specific. Using xrange makes no difference. Oddly enough, print a[row,col] does not cause the memory usage to grow. I guess numpy needs to allocate some memory when binding a python variable to an array element. This memory does not appear to get released when the python variable is deleted or passes out of scope. The gc (garbage collector) module did not shed any light for me. > > Isolating it, the following piece of code continually eats memory. Is it my program or what ...? > Thanks > Joel Levine > > Using Mac OSX 10.4.7 > Not clear on versions: Appears to be 0.9.8 with py2.4 > > ----------------- > > from numpy import * > > a=zeros((2000,100),float) > while True: > for row in range(2000): > for col in range(100): > x=a[row,col] > #if x!=0: print "?" > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From andreas at kostyrka.org Mon Nov 13 21:38:55 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 13 Nov 2006 21:38:55 +0100 Subject: [Tutor] question about __init__ in a class In-Reply-To: <384c93600611131044o4722ed36m8d17c83db0776c25@mail.gmail.com> References: <384c93600611131044o4722ed36m8d17c83db0776c25@mail.gmail.com> Message-ID: <20061113203854.GB8410@andi-lap.la.revver.com> * shawn bright [061113 19:46]: > Hello there all. > i have a class that i need to load some class variables depending on what is > passed to the class, it would either be set up using one variable or > another. The values for the class variables would be loaded from a database. > But how it is looked up depends on how its called. Like this: > > class Sensor_Object(object): > def __init__(self, id, monitor): > if id: > self.id = id > load values from the database > value1 = somevalue > value2 = someOthervalue > else: > self.monitor = monitor > get some values from database > value1 = somevalue > value2 = someothervalue > > now i could call it like this: > > new_monitor = sensor.Sensor('', 'XJ191') > or > new_monitor = sensor.Sensor('3433', '') > to load based on the other variable. > > i think that this would work, but i was thinking that there must be a > cleaner way to do it. Well, the code is basically ok, but I'd propose the following (it will help using the instances): class Sensor_Object(object): sensid = None monitor = None ... Basically, provide class variables shadowing your "main" instance attributes. I've also renamed id to sensid as id is an builtin function. (it's legal and ok to use id, but some tools like pylint like to complain about that style of shadowing.) The benefit is easy, in other methods, you can use code like this: if self.sensid is not None: instead of the more clumsy if hasattr(self, "sensid"): Andreas > any suggestions ? > > sk > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From nephish at gmail.com Mon Nov 13 23:26:04 2006 From: nephish at gmail.com (shawn bright) Date: Mon, 13 Nov 2006 16:26:04 -0600 Subject: [Tutor] question about __init__ in a class In-Reply-To: <20061113203854.GB8410@andi-lap.la.revver.com> References: <384c93600611131044o4722ed36m8d17c83db0776c25@mail.gmail.com> <20061113203854.GB8410@andi-lap.la.revver.com> Message-ID: <384c93600611131426o134e99fex1b7c72365891efbe@mail.gmail.com> hey thanks, did not think about the possible consequences of the use of a built in as a variable name. -sk On 11/13/06, Andreas Kostyrka wrote: > > * shawn bright [061113 19:46]: > > Hello there all. > > i have a class that i need to load some class variables depending on > what is > > passed to the class, it would either be set up using one variable or > > another. The values for the class variables would be loaded from a > database. > > But how it is looked up depends on how its called. Like this: > > > > class Sensor_Object(object): > > def __init__(self, id, monitor): > > if id: > > self.id = id > > load values from the database > > value1 = somevalue > > value2 = someOthervalue > > else: > > self.monitor = monitor > > get some values from database > > value1 = somevalue > > value2 = someothervalue > > > > now i could call it like this: > > > > new_monitor = sensor.Sensor('', 'XJ191') > > or > > new_monitor = sensor.Sensor('3433', '') > > to load based on the other variable. > > > > i think that this would work, but i was thinking that there must be a > > cleaner way to do it. > > Well, the code is basically ok, but I'd propose the following (it will > help using the instances): > > class Sensor_Object(object): > sensid = None > monitor = None > > ... > > Basically, provide class variables shadowing your "main" instance > attributes. I've also renamed id to sensid as id is an builtin > function. (it's legal and ok to use id, but some tools like pylint > like to complain about that style of shadowing.) > > The benefit is easy, in other methods, you can use code like this: > if self.sensid is not None: > instead of the more clumsy > if hasattr(self, "sensid"): > > Andreas > > > any suggestions ? > > > > sk > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061113/3e41d4aa/attachment.html From svadhri at paypal.com Tue Nov 14 00:03:15 2006 From: svadhri at paypal.com (Vadhri, Srinivas) Date: Mon, 13 Nov 2006 16:03:15 -0700 Subject: [Tutor] free IDE for Python? Message-ID: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> Hi A newbie to Python. What is the free IDE for Python development activities? ActiveState's Komodo IDE needs a license and a fee. Any recommendations? Regards, Srinivas Vadhri -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061113/5d949abc/attachment.htm From Mike.Hansen at atmel.com Tue Nov 14 00:20:20 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 13 Nov 2006 16:20:20 -0700 Subject: [Tutor] free IDE for Python? Message-ID: <57B026980605A64F9B23484C5659E32E3CA802@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Vadhri, Srinivas > Sent: Monday, November 13, 2006 4:03 PM > To: tutor at python.org > Subject: [Tutor] free IDE for Python? > > Hi > > > > A newbie to Python. What is the free IDE for Python > development activities? ActiveState's Komodo IDE needs a > license and a fee. > > > > Any recommendations? > > > > Regards, > > Srinivas Vadhri > http://www.python.org/infogami-faq/tutor/tutor-whats-the-best-editor-ide -for-python/ Or tinyurl ..http://tinyurl.com/yxjxgc I use VIM. I've been experimenting with Eclipse and Pydev. You'll get almost as many answers as there are people on this list. Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From hugonz-lists at h-lab.net Tue Nov 14 00:23:14 2006 From: hugonz-lists at h-lab.net (Hugo Gonzalez M) Date: Mon, 13 Nov 2006 17:23:14 -0600 Subject: [Tutor] free IDE for Python? In-Reply-To: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> Message-ID: <4558FE62.7070106@h-lab.net> Hi, I like SPE and IDLE, I do all development with them. Hugo From tomdrak at gmail.com Tue Nov 14 00:24:32 2006 From: tomdrak at gmail.com (tomd) Date: Tue, 14 Nov 2006 00:24:32 +0100 Subject: [Tutor] free IDE for Python? In-Reply-To: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> Message-ID: <2006111402432.468032@oem-up3sjowr2u8> Try Stani's Python editor from http://stani.be/python/spe/blog/ -- Tom, http://www.vscripts.net/ on Mon, 13 Nov 2006 16:03:15 -0700, you wrote: > A newbie to Python. What is the free IDE for Python development > activities? ActiveState?s Komodo IDE needs a license and a fee. From ajikoe at gmail.com Tue Nov 14 00:40:51 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 14 Nov 2006 06:40:51 +0700 Subject: [Tutor] free IDE for Python? In-Reply-To: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> Message-ID: Try scite: http://www.scintilla.org/SciTE.html pujo On 11/14/06, Vadhri, Srinivas wrote: > > Hi > > > > A newbie to Python. What is the free IDE for Python development > activities? ActiveState's Komodo IDE needs a license and a fee. > > > > Any recommendations? > > > > Regards, > > Srinivas Vadhri > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061114/a5a3e469/attachment.html From mrgordon at mit.edu Tue Nov 14 00:43:04 2006 From: mrgordon at mit.edu (Matthew Gordon) Date: Mon, 13 Nov 2006 18:43:04 -0500 Subject: [Tutor] free IDE for Python? In-Reply-To: <57B026980605A64F9B23484C5659E32E3CA802@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E3CA802@poccso.US.ad.atmel.com> Message-ID: <2edc23690611131543l3f3b8a0t2956e40209f0a118@mail.gmail.com> agreed. if you plan on programming in a few different languages, i would suggest picking up vim, emacs, or another multi-language environment. you can get a plugin (at least for emacs) that highlights syntax, indents, etc. - matt On 11/13/06, Mike Hansen wrote: > > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Vadhri, Srinivas > > Sent: Monday, November 13, 2006 4:03 PM > > To: tutor at python.org > > Subject: [Tutor] free IDE for Python? > > > > Hi > > > > > > > > A newbie to Python. What is the free IDE for Python > > development activities? ActiveState's Komodo IDE needs a > > license and a fee. > > > > > > > > Any recommendations? > > > > > > > > Regards, > > > > Srinivas Vadhri > > > > http://www.python.org/infogami-faq/tutor/tutor-whats-the-best-editor-ide > -for-python/ > > Or tinyurl ..http://tinyurl.com/yxjxgc > > I use VIM. I've been experimenting with Eclipse and Pydev. You'll get > almost as many answers as there are people on this list. > > Mike > > > ------------- > > NOTICE: This e-mail transmission and any documents or files attached to > it contain information for the sole use of the above-identified individual or entity. > > Its contents may be privileged, confidential, and exempt from disclosure under the law. > Any dissemination, distribution, or copying of this communication is strictly prohibited. > > Please notify the sender immediately if you are not the intended recipient. > > FGNS > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From andreas at kostyrka.org Tue Nov 14 01:15:27 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 14 Nov 2006 01:15:27 +0100 Subject: [Tutor] question about __init__ in a class In-Reply-To: <384c93600611131426o134e99fex1b7c72365891efbe@mail.gmail.com> References: <384c93600611131044o4722ed36m8d17c83db0776c25@mail.gmail.com> <20061113203854.GB8410@andi-lap.la.revver.com> <384c93600611131426o134e99fex1b7c72365891efbe@mail.gmail.com> Message-ID: <20061114001525.GJ8410@andi-lap.la.revver.com> * shawn bright [061113 23:51]: > hey thanks, did not think about the possible consequences of the use of a > built in as a variable name. Well, the consequences are minimal: a) pylint complains by default about that. b) if you paste code into your function, you might get problems, as it might use the "standard" id. Please note, that self.id is safe from that, but you probably want to name the attribute of the instance the same as the constructor arguments. Andreas From govilakanksha at yahoo.com Tue Nov 14 14:49:14 2006 From: govilakanksha at yahoo.com (Akanksha Govil) Date: Tue, 14 Nov 2006 05:49:14 -0800 (PST) Subject: [Tutor] need help for using ssl in python Message-ID: <20061114134914.94873.qmail@web36507.mail.mud.yahoo.com> Hi, I need to create an ssl socket. But i am getting the folowing error: Traceback (most recent call last): File "client-Nextone.py", line 35, in ? resp = port.editCallPlanConfig(req) File "/home/nabanita/new_soap_zsi/NexToneSubnet_services.py", line 38, in editCallPlanConfig self.binding.Send(None, None, request, soapaction="setCallPlanConfig", **kw) File "/usr/local/lib/python2.4/site-packages/ZSI/client.py", line 266, in Send self.h.connect() File "/usr/local/lib/python2.4/httplib.py", line 1073, in connect ssl = socket.ssl(sock, self.key_file, self.cert_file) AttributeError: 'module' object has no attribute 'ssl' I have installed OpenSSL/ module for python 2.4 and also openssl-0.9.7d-15.15.3 python-openssl-0.6-2.1 openssl-devel-0.9.7d-25.1 Please help. Akanksha --------------------------------- Everyone is raving about the all-new Yahoo! Mail beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061114/27f42021/attachment.htm From bashu at yandex.ru Tue Nov 14 15:14:51 2006 From: bashu at yandex.ru (Basil Shubin) Date: Tue, 14 Nov 2006 20:14:51 +0600 Subject: [Tutor] free IDE for Python? In-Reply-To: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> Message-ID: <4559CF5B.4080602@yandex.ru> Vadhri, Srinivas ?????: > Hi > > > > A newbie to Python. What is the free IDE for Python development > activities? ActiveState?s Komodo IDE needs a license and a fee. > > > > Any recommendations? You can look at GNU Emacs + python-mode or even try out ECB (Emacs Code Browser - IDE for Emacs) -- Basil Shubin Freelance Software Developer From tim at johnsons-web.com Tue Nov 14 17:44:17 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 14 Nov 2006 07:44:17 -0900 Subject: [Tutor] free IDE for Python? In-Reply-To: <2edc23690611131543l3f3b8a0t2956e40209f0a118@mail.gmail.com> References: <57B026980605A64F9B23484C5659E32E3CA802@poccso.US.ad.atmel.com> <2edc23690611131543l3f3b8a0t2956e40209f0a118@mail.gmail.com> Message-ID: <20061114164417.GD6750@johnsons-web.com> * Matthew Gordon [061113 14:54]: > agreed. if you plan on programming in a few different languages, i > would suggest picking up vim, emacs, or another multi-language > environment. you can get a plugin (at least for emacs) that highlights > syntax, indents, etc. I've used vim in the past for python and recommend it for ease of use and support. I also use emacs, which may be found harder to learn but has the advantage of being able to evaluate code directly in the editor. tim > - matt > > > On 11/13/06, Mike Hansen wrote: > > > > > > > -----Original Message----- > > > From: tutor-bounces at python.org > > > [mailto:tutor-bounces at python.org] On Behalf Of Vadhri, Srinivas > > > Sent: Monday, November 13, 2006 4:03 PM > > > To: tutor at python.org > > > Subject: [Tutor] free IDE for Python? > > > > > > Hi > > > > > > > > > > > > A newbie to Python. What is the free IDE for Python > > > development activities? ActiveState's Komodo IDE needs a > > > license and a fee. > > > > > > > > > > > > Any recommendations? > > > > > > > > > > > > Regards, > > > > > > Srinivas Vadhri > > > > > > > http://www.python.org/infogami-faq/tutor/tutor-whats-the-best-editor-ide > > -for-python/ > > > > Or tinyurl ..http://tinyurl.com/yxjxgc > > > > I use VIM. I've been experimenting with Eclipse and Pydev. You'll get > > almost as many answers as there are people on this list. > > > > Mike > > > > > > ------------- > > > > NOTICE: This e-mail transmission and any documents or files attached to > > it contain information for the sole use of the above-identified individual or entity. > > > > Its contents may be privileged, confidential, and exempt from disclosure under the law. > > Any dissemination, distribution, or copying of this communication is strictly prohibited. > > > > Please notify the sender immediately if you are not the intended recipient. > > > > FGNS > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From wescpy at gmail.com Tue Nov 14 17:59:49 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 14 Nov 2006 08:59:49 -0800 Subject: [Tutor] free IDE for Python? In-Reply-To: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> Message-ID: <78b3a9580611140859y34c4d5ev135048e08f3f6f5c@mail.gmail.com> > A newbie to Python. What is the free IDE for Python development activities? > ActiveState's Komodo IDE needs a license and a fee. lifting this list straight out of Core Python (and removing the commercial ones): Open Source =========== IDLE (comes with Python distribution) http://www.python.org/idle/ Stani's Python Editor (wxWindows-based) http://pythonide.stani.be/ PythonWin + Win32 Extensions http://starship.python.net/crew/skippy/win32/ IDE Studio (IDLE+more) http://starship.python.net/crew/mike/Idle/ Eclipse http://pydev.sourceforge.net http://www.eclipse.org/ General overall IDE list ======================== http://wiki.python.org/moin/IntegratedDevelopmentEnvironments of course, this is all in addition to vi(m) and emacs. :-) good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rfquerin at gmail.com Tue Nov 14 18:28:02 2006 From: rfquerin at gmail.com (Richard Querin) Date: Tue, 14 Nov 2006 12:28:02 -0500 Subject: [Tutor] free IDE for Python? In-Reply-To: <20061114164417.GD6750@johnsons-web.com> References: <57B026980605A64F9B23484C5659E32E3CA802@poccso.US.ad.atmel.com> <2edc23690611131543l3f3b8a0t2956e40209f0a118@mail.gmail.com> <20061114164417.GD6750@johnsons-web.com> Message-ID: <7d81675b0611140928g7d972ba7v9e65fee4d908df38@mail.gmail.com> On 11/14/06, Tim Johnson wrote: > > > I've used vim in the past for python and recommend it for ease of > use and support. I also use emacs, which may be found harder to > learn but has the advantage of being able to evaluate code directly > in the editor. > tim > I have to chuckle when you recommend Vim for ease of use. Now don't start flaming me quite yet. I'm a big fan of Vim and I'm in the midst of learning it myself. I think it's a very powerful editor and I like it a lot. But recommending it for ease of use might be a little stretch. It's like a lot of things, the higher learning curve ultimately gets you greater rewards. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061114/92a40e5f/attachment.html From jameshcunningham at gmail.com Tue Nov 14 18:47:08 2006 From: jameshcunningham at gmail.com (James Cunningham) Date: Tue, 14 Nov 2006 12:47:08 -0500 Subject: [Tutor] review of beginner's code requested Message-ID: <9a5576390611140947q3e937af0x887d2d1c7214e957@mail.gmail.com> Hello. I'm new to Python; for a project to get to know the language I wrote up an api for representing finite topologies, and for subsets of topologies for which the orbit (the number of ways to use closure, interior, and complement operators to get separate sets) is fourteen. It can be used like this: some_set = [[1, 2, 3], [1, 2], [2, 3], [1, 3], [1], [2], [3], []] a = FiniteTopology(some_set, [1, 2, 3]) ... With all attendant methods. The constructor will take a list of lists or a set of sets. orbits_of_fourteen(8) will generate all topologies on subsets of [1, 2, 3, 4, 5, 6, 7, 8], and look for subsets of those topologies whose orbits are of length fourteen. (It will also never end. I wouldn't recommend trying that; I put it in as an exercise.) One thing I'm not sure of: if the user tries to create a FiniteTopology with a collection of sets that's not a topology, I throw a NotATopologyError in the constructor. But it looks like the FiniteTopology instance is still created. Is there any way to keep the instance from being created at all? I'm also interested in tips about documentation and style. Thanks a lot! Best, James #!/usr/bin/env python class NotATopologyError(Exception): pass class FiniteTopology(object): """This represents a finite topology on a set of elements that can be represented by Python's builtin set class. Its representation is of a set of frozensets, but its constructor will take a list of lists; let it be stressed that the elements on which the topology is defined must be immutable.""" def __init__(self, topology, main_set): """Creates an instance of FiniteTopology, checking first to make sure that it *is* a topology. If it isn't, we raise a NotATopology exception.""" self.topology = set([frozenset(element) for element in topology]) self.main_set = set(main_set) if not self._is_a_topology(): raise NotATopologyError() def get_topology(self): return self.topology def _is_a_topology(self): """Checks if self.topology is a topology.""" check_one = self._check_contains_empty_main() check_two = self._check_unions() check_three = self._check_intersections() return check_one and check_two and check_three def _check_contains_empty_main(self): """A topology contains its set and the empty set.""" return self.main_set in self.topology and set([]) in self.topology def _check_unions(self): """A topology contains all unions of open sets.""" for i in xrange(1, len(self.topology) + 1): for subset in combinations(self.as_list(), i): current_union = set() for one_set in subset: current_union = current_union.union(one_set) if not current_union in self.topology: return False return True def _check_intersections(self): """A topology contains all pairwise intersections of open sets.""" for item in self.topology: for next_item in self.topology: intersect = set(item).intersection(next_item) if not intersect in self.topology: return False return True def as_list(self): """Returns a list representation of the topology.""" return [[i for i in j] for j in self.topology] def orbit(self, subset): """Calculates the maximum number of ways we can use take complements, interiors, and closures of a set to make unique sets. There are at most 14 ways to do this, and usually less.""" orbit = set() complement = self.complement closure = self.closure interior = self.interior orbit.add(frozenset(subset)) orbit.add(frozenset(complement(subset))) orbit.add(frozenset(complement(interior(subset)))) orbit.add(frozenset(complement(interior(complement(subset))))) orbit.add (frozenset(complement(interior(complement(closure(subset)))))) orbit.add(frozenset(interior(subset))) orbit.add(frozenset(interior(closure(subset)))) orbit.add(frozenset(interior(complement(subset)))) orbit.add(frozenset(interior(complement(interior(subset))))) orbit.add(frozenset(interior(closure(interior(subset))))) orbit.add (frozenset(interior(closure(interior(complement(subset)))))) orbit.add(frozenset(closure(subset))) orbit.add(frozenset(closure(interior(subset)))) orbit.add(frozenset(closure(interior(complement(subset))))) return orbit def closure(self, subset): """A limit point p of a set X is such that all open sets containing p contain another point of X not equal to p. The closure of a set is the set plus all of its limit points. This finds all of the limit points of the subset and adds them.""" subset = set(subset) set_of_lps = set() for maybe_lp in self.main_set: is_lp = True for open_set in self.topology: if maybe_lp in open_set: p = [i for i in open_set if i != maybe_lp and i in subset] if not len(p): is_lp = False if is_lp: set_of_lps.add(maybe_lp) return subset.union(set_of_lps) def interior(self, subset): """The interior of a subset X is the union of all open subsets of X.""" subsets = set() for one_set in self.topology: if set(one_set).issubset(subset): subsets = subsets.union(one_set) return subsets def complement(self, subset): """Returns the complement of a subset.""" return set(self.main_set) - set(subset) def combinations(sequence, n): """Generates all unique n-combinations of a sequence.""" if n == 0: yield [] else: for i in xrange(len(sequence) - (n - 1)): for smaller_comb in combinations(sequence[i + 1:], n - 1): yield [sequence[i]] + smaller_comb def power_set(some_set, return_as_sets=False): """This returns the power set (set of all subsets) of some set, as a list of lists or a set of sets.""" # set_list = [[i for i in j] for j in some_set] power_set = [[]] for i in xrange(1, len(some_set) + 1): for j in combinations(some_set, i): power_set.extend([j]) if return_as_sets: power_set = set([frozenset(subset) for subset in power_set]) return power_set def all_collections(some_set): """This returns all collections of subsets of a particular set, as a list of lists. Takes a list.""" the_power_set = power_set(some_set) collections = [] for i in xrange(1, len(the_power_set) + 1): for j in combinations(the_power_set, i): collections.append(j) return collections def all_topologies_on_set_of_ints(upper_index): """This will find all topologies on a set like [1, 2, ..., upper_index]. They'll be returned as a list.""" all_topologies = [] coll = all_collections(range(1, upper_index + 1)) for some_set in coll: try: curr_top = FiniteTopology(some_set, some_set[len(some_set) - 1]) except: pass else: all_topologies.append(some_set) return all_topologies def orbits_of_fourteen(upper_index): """Prints topologies and subsets for which the orbit of that subset in the topology is fourteen.""" all_t = all_topologies_on_set_of_ints(upper_index) for i in all_t: for j in xrange(1, len(i[len(i) - 1]) + 1): for comb in combinations(i[len(i) - 1], j): orb_len = len(FiniteTopology(i, i[len(i) - 1]).orbit(comb)) if orb_len == 14: print str(comb) + " " + str(all_t) def main(): possible_topology = [[1, 2, 3], [1, 2], [1, 3], [2, 3], [1], [2], [3], []] FiniteTopology(possible_topology, [1, 2, 3]) if __name__ == '__main__': main() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061114/8d804e15/attachment-0001.html From hmm at woolgathering.cx Tue Nov 14 18:55:09 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Tue, 14 Nov 2006 12:55:09 -0500 Subject: [Tutor] free IDE for Python? In-Reply-To: <7d81675b0611140928g7d972ba7v9e65fee4d908df38@mail.gmail.com> References: <57B026980605A64F9B23484C5659E32E3CA802@poccso.US.ad.atmel.com> <2edc23690611131543l3f3b8a0t2956e40209f0a118@mail.gmail.com> <20061114164417.GD6750@johnsons-web.com> <7d81675b0611140928g7d972ba7v9e65fee4d908df38@mail.gmail.com> Message-ID: <20061114175509.GA1007@sillyrabbi.dyndns.org> On Tue, Nov 14, 2006 at 12:28:02PM -0500, Richard Querin wrote: > On 11/14/06, Tim Johnson <[1]tim at johnsons-web.com> wrote: > > I've used vim in the past for python and recommend it for ease of > use and support. I also use emacs, which may be found harder to > > I have to chuckle when you recommend Vim for ease of use. Now don't start > flaming me quite yet. I'm a big fan of Vim and I'm in the midst of > learning it myself. I think it's a very powerful editor and I like it a > lot. But recommending it for ease of use might be a little stretch. It's > like a lot of things, the higher learning curve ultimately gets you > greater rewards. Using vim is like riding a bicycle - it's hard to learn, but once you get it, it becomes automatic and can make you intolerant of walking (... everything ... is taking ... so ... long ...) :-) -- yours, William From paulino1 at sapo.pt Tue Nov 14 20:05:12 2006 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Tue, 14 Nov 2006 19:05:12 +0000 Subject: [Tutor] sleep command in python? Message-ID: <1163531112.4bjz0ttttv28@w12.mail.sapo.pt> Is there a "sleep" command in python like the bash's sleep? ___________________________________________________________________ O SAPO j? est? livre de v?rus com a Panda Software, fique voc? tamb?m! Clique em: http://antivirus.sapo.pt From bgailer at alum.rpi.edu Tue Nov 14 20:17:33 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 14 Nov 2006 11:17:33 -0800 Subject: [Tutor] sleep command in python? In-Reply-To: <1163531112.4bjz0ttttv28@w12.mail.sapo.pt> References: <1163531112.4bjz0ttttv28@w12.mail.sapo.pt> Message-ID: <455A164D.2080808@alum.rpi.edu> paulino1 at sapo.pt wrote: > Is there a "sleep" command in python like the bash's sleep? import time time.sleep(secs) "Suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system." -- Bob Gailer 510-978-4454 From andreas at kostyrka.org Tue Nov 14 20:20:18 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 14 Nov 2006 20:20:18 +0100 Subject: [Tutor] sleep command in python? In-Reply-To: <1163531112.4bjz0ttttv28@w12.mail.sapo.pt> References: <1163531112.4bjz0ttttv28@w12.mail.sapo.pt> Message-ID: <20061114192018.GO8410@andi-lap.la.revver.com> * paulino1 at sapo.pt [061114 20:07]: > Is there a "sleep" command in python like the bash's sleep? import time time.sleep(0.5) Andreas From kent37 at tds.net Tue Nov 14 20:19:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Nov 2006 14:19:16 -0500 Subject: [Tutor] sleep command in python? In-Reply-To: <1163531112.4bjz0ttttv28@w12.mail.sapo.pt> References: <1163531112.4bjz0ttttv28@w12.mail.sapo.pt> Message-ID: <455A16B4.2080707@tds.net> paulino1 at sapo.pt wrote: > Is there a "sleep" command in python like the bash's sleep? time.sleep() http://docs.python.org/lib/module-time.html Kent From etrade.griffiths at dsl.pipex.com Tue Nov 14 20:25:17 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Tue, 14 Nov 2006 19:25:17 +0000 Subject: [Tutor] Alternatives to PY2EXE Message-ID: <6.1.2.0.2.20061114192122.03f16ab0@pop.dsl.pipex.com> Hi just finished developing my first app with wxPython and matplotlib and now trying to create an EXE file using PY2EXE for distribution. However, this is proving to be an extremely frustrating experience and I am making very little progress. Are there any "simple" alternatives to PY2EXE for shipping Python apps to Windows machines? Thanks Alun Griffiths From tim at johnsons-web.com Tue Nov 14 21:07:05 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 14 Nov 2006 11:07:05 -0900 Subject: [Tutor] free IDE for Python? In-Reply-To: <20061114175509.GA1007@sillyrabbi.dyndns.org> References: <57B026980605A64F9B23484C5659E32E3CA802@poccso.US.ad.atmel.com> <2edc23690611131543l3f3b8a0t2956e40209f0a118@mail.gmail.com> <20061114164417.GD6750@johnsons-web.com> <7d81675b0611140928g7d972ba7v9e65fee4d908df38@mail.gmail.com> <20061114175509.GA1007@sillyrabbi.dyndns.org> Message-ID: <20061114200705.GG6750@johnsons-web.com> * William O'Higgins Witteman [061114 09:05]: > On Tue, Nov 14, 2006 at 12:28:02PM -0500, Richard Querin wrote: > > On 11/14/06, Tim Johnson <[1]tim at johnsons-web.com> wrote: > > > > I've used vim in the past for python and recommend it for ease of > > use and support. I also use emacs, which may be found harder to > > > > I have to chuckle when you recommend Vim for ease of use. Now don't start > > flaming me quite yet. I'm a big fan of Vim and I'm in the midst of > > learning it myself. I think it's a very powerful editor and I like it a > > lot. But recommending it for ease of use might be a little stretch. It's > > like a lot of things, the higher learning curve ultimately gets you > > greater rewards. > > Using vim is like riding a bicycle - it's hard to learn, but once you > get it, it becomes automatic and can make you intolerant of walking (... > everything ... is taking ... so ... long ...) :-) I went from Boxer on windows - nice editor, CUA-style - to vim. Getting used the vim 'modal style' seemed exotic, but not 'arcane'. Once I got past that, I found vim incredibly nimble. I found emacs harder to learn than vim. I find that they both have their place. BTW: vim offers 'hooks' to compile the python editor directly into the editor. That's a feature that portends many possibilities. tim > yours, > > William > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From tomdrak at gmail.com Tue Nov 14 21:33:04 2006 From: tomdrak at gmail.com (tomd) Date: Tue, 14 Nov 2006 21:33:04 +0100 Subject: [Tutor] Alternatives to PY2EXE In-Reply-To: <6.1.2.0.2.20061114192122.03f16ab0@pop.dsl.pipex.com> Message-ID: <2006111421334.577165@oem-up3sjowr2u8> I used PyInstaller, it was simple, but the app I used it for was rather simple too. http://pyinstaller.hpcf.upr.edu/ -- Tom, http://www.vscripts.net/ on Tue, 14 Nov 2006 19:25:17 +0000, you wrote: > Are there any "simple" alternatives to PY2EXE for > shipping Python apps to Windows machines? From singingxduck at gmail.com Tue Nov 14 21:52:48 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Tue, 14 Nov 2006 15:52:48 -0500 Subject: [Tutor] removing an image from a tkinter label Message-ID: <455A2CA0.80303@gmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061114/ecde42e5/attachment.htm From singingxduck at gmail.com Wed Nov 15 05:30:36 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Tue, 14 Nov 2006 23:30:36 -0500 Subject: [Tutor] removing an image from a tkinter label In-Reply-To: <455A2CA0.80303@gmail.com> References: <455A2CA0.80303@gmail.com> Message-ID: <455A97EC.9080008@gmail.com> Orri Ganel wrote: > Hello all, > > As part of a tkinter program that displays the currently playing > track's information (including artwork) from iTunes, I have a label > with an image in it (the artwork). However, when the song played > doesn't have artwork, I'd like to remove artwork of the old song and > replace it with the text "No artwork". However, I can't seem to find > a way to do that. Short of destroying the label and creating a new > one, is there another way to accomplish this? The relevant code > appears below. > > Thanks in advance, > Orri In the end, setting lbl["image"] = "" worked (as opposed to None, which raises a TclError with the message that pyimage2 or whatever number of pictures had been put in so far didn't exist). This is a surprisingly underdocumented fact, however. Googling various combinations of Tkinter, label, image, and remove, failed to yield a fruitful result until the 4th or 5th page of the 5th or so combination. In any case, thanks for your time. Orri -------------- next part -------------- A non-text attachment was scrubbed... Name: ganel.o.vcf Type: text/x-vcard Size: 144 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061114/31d01d9f/attachment-0001.vcf From etrade.griffiths at dsl.pipex.com Wed Nov 15 15:29:20 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Wed, 15 Nov 2006 14:29:20 +0000 Subject: [Tutor] Use of dateutil.relativedata Message-ID: <6.1.2.0.2.20061115142509.03f13530@pop.dsl.pipex.com> Hi trying to use dateutil to calculate the number of months between two dates. here is the script import datetime import dateutil x=datetime.date.today() y=x+datetime.timedelta(days=366) z=y-x print x,y,z a=dateutil.relativedelta(x,y) print a and here is the output >>> 2006-11-15 2007-11-16 366 days, 0:00:00 Traceback (most recent call last): File "C:/Projects/completion_dates", line 10, in -toplevel- a=dateutil.relativedelta(x,y) AttributeError: 'module' object has no attribute 'relativedelta' >>> There's problem here that's really basic but just can't see it!!! Thanks Alun Griffiths From etrade.griffiths at dsl.pipex.com Wed Nov 15 15:35:06 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Wed, 15 Nov 2006 14:35:06 +0000 Subject: [Tutor] Use of dateutil.relativedata Message-ID: <6.1.2.0.2.20061115143354.03f0c4f0@pop.dsl.pipex.com> Sorry, problem solved import datetime import dateutil.relativedelta x=datetime.date.today() y=x+datetime.timedelta(days=366) z=y-x print x,y,z a=dateutil.relativedelta.relativedelta(x,y) print a seems to do the trick From alan.gauld at btinternet.com Thu Nov 16 00:19:46 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Nov 2006 23:19:46 -0000 Subject: [Tutor] numpy memory muncher References: <71933843@newdancer.Dartmouth.EDU> <1163448303.327.85.camel@www.venix.com> Message-ID: > I can reproduce the problem on my Linux system, so it is not Mac > specific. Using xrange makes no difference. I believe that in recent Pythons (v2.3 onwards?) xrange is just an alias for range since range was reimplementted to use generators. So the old menory issues with range no longer apply. Alan G. From alan.gauld at btinternet.com Thu Nov 16 00:28:52 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Nov 2006 23:28:52 -0000 Subject: [Tutor] Sloppy Code ? References: <20061113195115.06f820f8.klappnase@freenet.de> Message-ID: "Matt Erasmus" wrote > Yes, that does help, although it doesn't print the FQDN which is > what > I'm really after. > But thanks to you I now know about the socket module It is very rarely necessaary to use popen etc to get basic system information or to perform basic OS commanfs. There are usually direct function/modules that do the same job more efficiently. popen is good for running actual applications but if you find yourself using it for lower level tasks consider a google search for python . In this case 'python hostname' gets me the socket module docs as the first hit... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Nov 16 00:44:30 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Nov 2006 23:44:30 -0000 Subject: [Tutor] OT: Vim was: free IDE for Python? References: <57B026980605A64F9B23484C5659E32E3CA802@poccso.US.ad.atmel.com><2edc23690611131543l3f3b8a0t2956e40209f0a118@mail.gmail.com><20061114164417.GD6750@johnsons-web.com> <7d81675b0611140928g7d972ba7v9e65fee4d908df38@mail.gmail.com> Message-ID: >> I've used vim in the past for python and recommend it for ease of >> use and support. > > I have to chuckle when you recommend Vim for ease of use. Me too, and I've been a vi/elvis/viper/vim user for over 20 years(*). vi/vim could never be described as easy to learn, but... ... ease of use can mean ease of use once you have learned it. ie efficient. Now vim passes that test with flying colours. The guys who designed vi (Bill Joy the founder of Sun Microsystems was one of them) took the view that it should be easy for experts not novices since most programmers would rapidly progress beyond novice. One of the great features of vim is that once you grasp its design philosophy it is entirely consistent and you can often guess new commands without looking it up in the help. For those who want a tutorial that teaches the underlying vi philospohy as well as the basic commands I strongly recommend the vilearn package (sometimes called teachvi). It is a bash script so you need a bash shell to install it but GNU or cygwin bash will work on Windows. Its not pretty but its short and it works: http://www.houseofthud.com/vilearn.html (*) And I've been an emacs user for equally long, I like and use both for different things... Alan G. From alan.gauld at btinternet.com Thu Nov 16 00:49:18 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Nov 2006 23:49:18 -0000 Subject: [Tutor] free IDE for Python? References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> <78b3a9580611140859y34c4d5ev135048e08f3f6f5c@mail.gmail.com> Message-ID: "wesley chun" wrote > Eclipse > http://pydev.sourceforge.net > http://www.eclipse.org/ Has anyone got an idiot's guide to getting Eclipse working with python? I've tried a couple of times but ran out of patience. In fact I haven't really got vanilla Eclipse working for Java yet, it all seems a lot of work for an IDE! NetBeans was so much easier.... but my friends all laughed at me and said I should be using Eclipse... :-) Alan (the impatient) G. From alan.gauld at btinternet.com Thu Nov 16 00:56:28 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Nov 2006 23:56:28 -0000 Subject: [Tutor] removing an image from a tkinter label References: <455A2CA0.80303@gmail.com> <455A97EC.9080008@gmail.com> Message-ID: "Orri Ganel" wrote > In the end, setting lbl["image"] = "" worked Glad it worked. I was just about to suggest creating an image with the "No image" text in it. You could then just display that as the default image... Alan G. From singingxduck at gmail.com Thu Nov 16 00:59:03 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Wed, 15 Nov 2006 18:59:03 -0500 Subject: [Tutor] removing an image from a tkinter label In-Reply-To: References: <455A2CA0.80303@gmail.com> <455A97EC.9080008@gmail.com> Message-ID: <455BA9C7.5030003@gmail.com> Alan Gauld wrote: >"Orri Ganel" wrote > > > >>In the end, setting lbl["image"] = "" worked >> >> > >Glad it worked. I was just about to suggest creating an image >with the "No image" text in it. You could then just display that >as the default image... > >Alan G. > > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From what I found, it seems that one version of the documentation (perhaps the original Tcl documentation, as I found no mention of it on effbot) actually says to set it equal to an empty string to return to whatever text is in the label (images take precedence over text). I think setting it equal to another string might have the same effect as setting it equal to None - a TclError. Incidentally, if anyone's interested in the working product (I won't call it final for a while yet), let me know and I can give you a link to the code. Orri G. From alan.gauld at btinternet.com Thu Nov 16 00:53:41 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Nov 2006 23:53:41 -0000 Subject: [Tutor] Alternatives to PY2EXE References: <6.1.2.0.2.20061114192122.03f16ab0@pop.dsl.pipex.com> Message-ID: "Etrade Griffiths" wrote > just finished developing my first app with wxPython and matplotlib > and now > trying to create an EXE file using PY2EXE for distribution. > However, this > is proving to be an extremely frustrating experience and I am making > very > little progress. Are there any "simple" alternatives to PY2EXE for > shipping Python apps to Windows machines? There are a few more sophisticated tools around but py2exe is usually considered the easy option. But are you sure you really need an EXE? The size of a bundled python install, which can be optionally loaded if not alteady there, is not excessive in modern PC software terms and many environments nowadays do not use pure exe's - VB, .NET, Java Smalltalk, etc So why not just ship Python? And if you writre a lot of code installing python will use up less memory in the long term since you won't have a copy of the interpreter hiding inside every app! Alan G. From ajkadri at googlemail.com Thu Nov 16 01:20:40 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 16 Nov 2006 00:20:40 +0000 Subject: [Tutor] Help me with this problem relating to datetime Message-ID: Hi Folks, I have got a date (as string), time (as string) , number of slots ( integer) and delta ( which is in seconds). I want to create a dictionary which has got date as the key, and the value should be a tuple with two elements (start_time, end_time). I will take start_time and find the end_time using delta. This pair of start and end times have a corresponding date. The date will be used as the key for the dictionary. Once the time crosses midnight, the date will change. Can you help me to implement this functionality? TIA. Best Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/f6486023/attachment.html From rabidpoobear at gmail.com Thu Nov 16 01:31:21 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 15 Nov 2006 18:31:21 -0600 Subject: [Tutor] Help me with this problem relating to datetime In-Reply-To: References: Message-ID: <455BB159.70406@gmail.com> Asrarahmed Kadri wrote: > Hi Folks, > > > I have got a date (as string), time (as string) , number of slots ( > integer) and delta ( which is in seconds). > I want to create a dictionary which has got date as the key, and the > value should be a tuple with two elements (start_time, end_time). > > I will take start_time and find the end_time using delta. This pair of > start and end times have a corresponding date. The date will be used > as the key for the dictionary. Once the time crosses midnight, the > date will change. > > > Can you help me to implement this functionality? yes. http://catb.org/esr/faqs/smart-questions.html#prune :). -Luke > > TIA. > > Best Regards, > Asrarahmed > > > > -- > To HIM you shall return. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ajkadri at googlemail.com Thu Nov 16 01:36:33 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 16 Nov 2006 00:36:33 +0000 Subject: [Tutor] Help me with this problem relating to datetime In-Reply-To: <455BB159.70406@gmail.com> References: <455BB159.70406@gmail.com> Message-ID: SOrry for that. I was wondering if someoen can give a hint about the implementation. I am not asking for the actual code. Regards, Asrarahmed On 11/16/06, Luke Paireepinart wrote: > > Asrarahmed Kadri wrote: > > Hi Folks, > > > > > > I have got a date (as string), time (as string) , number of slots ( > > integer) and delta ( which is in seconds). > > I want to create a dictionary which has got date as the key, and the > > value should be a tuple with two elements (start_time, end_time). > > > > I will take start_time and find the end_time using delta. This pair of > > start and end times have a corresponding date. The date will be used > > as the key for the dictionary. Once the time crosses midnight, the > > date will change. > > > > > > Can you help me to implement this functionality? > yes. > http://catb.org/esr/faqs/smart-questions.html#prune > :). > -Luke > > > > TIA. > > > > Best Regards, > > Asrarahmed > > > > > > > > -- > > To HIM you shall return. > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/db44ef47/attachment.htm From kent37 at tds.net Thu Nov 16 01:37:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Nov 2006 19:37:50 -0500 Subject: [Tutor] numpy memory muncher In-Reply-To: References: <71933843@newdancer.Dartmouth.EDU> <1163448303.327.85.camel@www.venix.com> Message-ID: <455BB2DE.60906@tds.net> Alan Gauld wrote: >> I can reproduce the problem on my Linux system, so it is not Mac >> specific. Using xrange makes no difference. > > I believe that in recent Pythons (v2.3 onwards?) xrange is just > an alias for range since range was reimplementted to use > generators. So the old menory issues with range no longer > apply. No, range() still returns a list, it is not a generator. That change is for Python 3.0. Kent From john at fouhy.net Thu Nov 16 01:38:47 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 16 Nov 2006 13:38:47 +1300 Subject: [Tutor] Help me with this problem relating to datetime In-Reply-To: References: Message-ID: <5e58f2e40611151638w11de302ale565e4ea8c42e012@mail.gmail.com> On 16/11/06, Asrarahmed Kadri wrote: > Hi Folks, > > > I have got a date (as string), time (as string) , number of slots ( integer) > and delta ( which is in seconds). > I want to create a dictionary which has got date as the key, and the value > should be a tuple with two elements (start_time, end_time). > > I will take start_time and find the end_time using delta. This pair of start > and end times have a corresponding date. The date will be used as the key > for the dictionary. Once the time crosses midnight, the date will change. Which part are you having trouble with? To convert a string into a Date or Datetime object, use time.strptime(), and then build a Datetime from the resulting time_tuple. (in Python2.5, I think, the datetime module has its own strptime() function, which short-cuts this process) -- John. From jdleach04 at sbcglobal.net Thu Nov 16 01:46:03 2006 From: jdleach04 at sbcglobal.net (J. D. Leach) Date: Wed, 15 Nov 2006 19:46:03 -0500 Subject: [Tutor] SIP-4.4 Install Borked Message-ID: <200611151946.03461.jdleach04@sbcglobal.net> To All, This is, and isn't, Python related, but thought you may be of some assisstance. Running Mandriva 2006 on a 1.8Mhz Dell GX260. Also: Python 3.4.2, ERIC3 3.8.1, etc. Problem: was going to update to ERIC3 3.9.2 and downloaded SIP-4.4, PyQT, and others. Started installation with SIP, which went well. Found that due to a raft of dependency problems, the new ERIC and PyQT will not install. Oh well, I thought, I'll just upgrade the OS at my convenience or deal with the problem later. Tried to fire up ERIC, got a segmentation fault. The new SIP has also screwed some other apps. Question: I want to remove SIP and revert to old version and can not find documentation that outlines the procedure. Any suggestions? -- J. D. Leach Columbus, Indiana USA Uptime: 19:37:45 up 1 day, 7:52, 1 user, load average: 1.00, 1.28, 1.49 Linux/Open Source Computer using: Mandriva Linux release 2006.0 (Community) for i586 kernel 2.6.12-12mdk ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ---Quote of the Day--- Oh, so there you are! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From pyro9219 at gmail.com Thu Nov 16 02:40:34 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 15 Nov 2006 17:40:34 -0800 Subject: [Tutor] Alternatives to PY2EXE In-Reply-To: References: <6.1.2.0.2.20061114192122.03f16ab0@pop.dsl.pipex.com> Message-ID: Because alot of the users here at Intel dont want to admit you can write usable programs in a "scripting" language.. so when they see a .exe they feel comfy... I'm working on pushing "agile language"... I personally think its more appropriate then scripting =D On 11/15/06, Alan Gauld wrote: > > > "Etrade Griffiths" wrote > > just finished developing my first app with wxPython and matplotlib > > and now > > trying to create an EXE file using PY2EXE for distribution. > > However, this > > is proving to be an extremely frustrating experience and I am making > > very > > little progress. Are there any "simple" alternatives to PY2EXE for > > shipping Python apps to Windows machines? > > There are a few more sophisticated tools around but py2exe is > usually considered the easy option. > > But are you sure you really need an EXE? > The size of a bundled python install, which can be optionally > loaded if not alteady there, is not excessive in modern PC > software terms and many environments nowadays do not > use pure exe's - VB, .NET, Java Smalltalk, etc > > So why not just ship Python? And if you writre a lot of code > installing > python will use up less memory in the long term since you won't > have a copy of the interpreter hiding inside every app! > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061115/18f4bc12/attachment.html From pyro9219 at gmail.com Thu Nov 16 02:44:57 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 15 Nov 2006 17:44:57 -0800 Subject: [Tutor] free IDE for Python? In-Reply-To: References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> <78b3a9580611140859y34c4d5ev135048e08f3f6f5c@mail.gmail.com> Message-ID: I tried it back before I tried SPE. I remember it taking several hours and being very bloated. Have you watched the showmedo video? Thats what I used... http://showmedo.com/videos/series?name=PyDevEclipseList If I personally "had" to use something that obnoxious I'd just reinstall ironpython and use Visual Studio for everything since I already have it for C# applications. (Yes I understand it makes .net runtime code and not python code, but I can't justify using that large and resource eating a program to use a language that is supposed to be quick and easy... ) On 11/15/06, Alan Gauld wrote: > > > "wesley chun" wrote > > Eclipse > > http://pydev.sourceforge.net > > http://www.eclipse.org/ > > Has anyone got an idiot's guide to getting Eclipse working > with python? > > I've tried a couple of times but ran out of patience. In fact I > haven't really got vanilla Eclipse working for Java yet, it all > seems a lot of work for an IDE! NetBeans was so much > easier.... but my friends all laughed at me and said I should > be using Eclipse... :-) > > Alan (the impatient) G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061115/2ee47a53/attachment.htm From pyro9219 at gmail.com Thu Nov 16 02:45:54 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 15 Nov 2006 17:45:54 -0800 Subject: [Tutor] free IDE for Python? In-Reply-To: References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> <78b3a9580611140859y34c4d5ev135048e08f3f6f5c@mail.gmail.com> Message-ID: BTW... that also counts as my vouce for using SPE =D On 11/15/06, Chris Hengge wrote: > > I tried it back before I tried SPE. I remember it taking several hours and > being very bloated. Have you watched the showmedo video? Thats what I > used... > > http://showmedo.com/videos/series?name=PyDevEclipseList > > If I personally "had" to use something that obnoxious I'd just reinstall > ironpython and use Visual Studio for everything since I already have it for > C# applications. (Yes I understand it makes .net runtime code and not python > code, but I can't justify using that large and resource eating a program to > use a language that is supposed to be quick and easy... ) > > On 11/15/06, Alan Gauld wrote: > > > > > > "wesley chun" wrote > > > Eclipse > > > http://pydev.sourceforge.net > > > http://www.eclipse.org/ > > > > Has anyone got an idiot's guide to getting Eclipse working > > with python? > > > > I've tried a couple of times but ran out of patience. In fact I > > haven't really got vanilla Eclipse working for Java yet, it all > > seems a lot of work for an IDE! NetBeans was so much > > easier.... but my friends all laughed at me and said I should > > be using Eclipse... :-) > > > > Alan (the impatient) G. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061115/04b304a7/attachment.html From jdleach04 at sbcglobal.net Thu Nov 16 02:49:28 2006 From: jdleach04 at sbcglobal.net (J. D. Leach) Date: Wed, 15 Nov 2006 20:49:28 -0500 Subject: [Tutor] SIP-4.4 Install Borked In-Reply-To: <200611151946.03461.jdleach04@sbcglobal.net> References: <200611151946.03461.jdleach04@sbcglobal.net> Message-ID: <200611152049.28265.jdleach04@sbcglobal.net> No need to answer now. I had to resort to the ole' tried-and-true method of aggressive search and destroy. After savagely excising all remnants of sip-4.4, I was able to reload the previous version and get everything back up. Sorry to have troubled you all. On Wednesday 15 November 2006 07:46 pm, J. D. Leach wrote: > To All, > > This is, and isn't, Python related, but thought you may be of some > assisstance. Running Mandriva 2006 on a 1.8Mhz Dell GX260. Also: Python > 3.4.2, ERIC3 3.8.1, etc. > Problem: was going to update to ERIC3 3.9.2 and downloaded SIP-4.4, PyQT, > and others. Started installation with SIP, which went well. Found that due > to a raft of dependency problems, the new ERIC and PyQT will not install. > Oh well, I thought, I'll just upgrade the OS at my convenience or deal with > the problem later. Tried to fire up ERIC, got a segmentation fault. The new > SIP has also screwed some other apps. > Question: I want to remove SIP and revert to old version and can not find > documentation that outlines the procedure. Any suggestions? -- J. D. Leach Columbus, Indiana USA Uptime: 20:46:20 up 1 day, 9:01, 1 user, load average: 1.06, 1.92, 1.85 Linux/Open Source Computer using: Mandriva Linux release 2006.0 (Community) for i586 kernel 2.6.12-12mdk ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ---Quote of the Day--- The savior becomes the victim. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From pyro9219 at gmail.com Thu Nov 16 02:51:40 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 15 Nov 2006 17:51:40 -0800 Subject: [Tutor] Alternatives to PY2EXE In-Reply-To: References: <6.1.2.0.2.20061114192122.03f16ab0@pop.dsl.pipex.com> Message-ID: Just want to add to that... As of the day before yesturday I've been using pyInstaller rather then py2exe(which I've used the last few months) I've found some bug that I can't figure out and dont really care to put effort into fixing.. When I run a py.exe using py2exe from the start menu and the user enters any input.. program crashes without errors. When I run a py.exe directly from the command line, it runs flawless. When I run the script from either the start menu or the command line, it runs flawless. I appreciate pyInstaller giving a little more interesting icon to my .exe also... but thats just being picky and lazy. On 11/15/06, Chris Hengge wrote: > > Because alot of the users here at Intel dont want to admit you can write > usable programs in a "scripting" language.. so when they see a .exe they > feel comfy... > > I'm working on pushing "agile language"... I personally think its more > appropriate then scripting =D > > On 11/15/06, Alan Gauld wrote: > > > > > > "Etrade Griffiths" wrote > > > just finished developing my first app with wxPython and matplotlib > > > and now > > > trying to create an EXE file using PY2EXE for distribution. > > > However, this > > > is proving to be an extremely frustrating experience and I am making > > > very > > > little progress. Are there any "simple" alternatives to PY2EXE for > > > shipping Python apps to Windows machines? > > > > There are a few more sophisticated tools around but py2exe is > > usually considered the easy option. > > > > But are you sure you really need an EXE? > > The size of a bundled python install, which can be optionally > > loaded if not alteady there, is not excessive in modern PC > > software terms and many environments nowadays do not > > use pure exe's - VB, .NET, Java Smalltalk, etc > > > > So why not just ship Python? And if you writre a lot of code > > installing > > python will use up less memory in the long term since you won't > > have a copy of the interpreter hiding inside every app! > > > > Alan G. > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061115/98b594d5/attachment.htm From vinayvinay at gmail.com Thu Nov 16 04:03:31 2006 From: vinayvinay at gmail.com (Vinay Reddy) Date: Thu, 16 Nov 2006 21:03:31 +1800 Subject: [Tutor] exception problems in socket programming Message-ID: <537f59d10611151903x572d0025y164239782ccc4b29@mail.gmail.com> Hi, I'm trying to do some simple network programming in Python, but am stuck with exception problems. Here's the relevant code snippet: self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.connect((something.com, 5000)) except socket.error, (value, message): if self.s: self.s.close() print "Could not open socket: " + message sys.exit(1) I was testing for a timeout exception (which is 60 seconds by default), but after the timeout I get the following error: File "./client.py", line 54, in connect except socket.error, (value, message): ValueError: need more than 1 value to unpack I googled and found something on ValueError, but I couldn't see how it applied here. I'd appreciate any help. Thanks, Vinay From pyro9219 at gmail.com Thu Nov 16 06:49:45 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 15 Nov 2006 21:49:45 -0800 Subject: [Tutor] exception problems in socket programming In-Reply-To: <537f59d10611151903x572d0025y164239782ccc4b29@mail.gmail.com> References: <537f59d10611151903x572d0025y164239782ccc4b29@mail.gmail.com> Message-ID: I ran this code based on yours: import socket, sys s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(('something.com', 5000)) except socket.error, (value, message): if s: s.close() print "Could not open socket: " + message raw_input("\nPress any key") And I got this result: Could not open socket: getaddrinfo failed Press any key Do you need to put quotes around something.com like I did? On 11/15/06, Vinay Reddy wrote: > > Hi, > I'm trying to do some simple network programming in Python, but am > stuck with exception problems. Here's the relevant code snippet: > > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > try: > self.s.connect((something.com, 5000)) > except socket.error, (value, message): > if self.s: > self.s.close() > print "Could not open socket: " + message > sys.exit(1) > > I was testing for a timeout exception (which is 60 seconds by > default), but after the timeout I get the following error: > File "./client.py", line 54, in connect > except socket.error, (value, message): > ValueError: need more than 1 value to unpack > > I googled and found something on ValueError, but I couldn't see how it > applied here. > > I'd appreciate any help. > > Thanks, > Vinay > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061115/82717893/attachment.htm From Tim.Golden at viacom-outdoor.co.uk Thu Nov 16 09:10:06 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 16 Nov 2006 08:10:06 -0000 Subject: [Tutor] Alternatives to PY2EXE In-Reply-To: Message-ID: [Chris Hengge] | Because alot of the users here at Intel dont want to admit | you can write usable programs in a "scripting" language.. so | when they see a .exe they feel comfy... One option which could help there -- although your other considerations might outweigh it -- is Fredrik Lundh's exemaker: http://effbot.org/zone/exemaker.htm It doesn't bundle up Python in the way that py2exe does: you still need to have python on the target machine. But it does provide an .exe of your program (which, behind the scenes, loads up the Python dll in the same way that the python.exe would have done in the first place). Thst way, the .exe-comfortable user sees a .exe without the extra work of py2exe/installer etc. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kent37 at tds.net Thu Nov 16 12:05:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Nov 2006 06:05:34 -0500 Subject: [Tutor] exception problems in socket programming In-Reply-To: <537f59d10611151903x572d0025y164239782ccc4b29@mail.gmail.com> References: <537f59d10611151903x572d0025y164239782ccc4b29@mail.gmail.com> Message-ID: <455C45FE.9010207@tds.net> Vinay Reddy wrote: > Hi, > I'm trying to do some simple network programming in Python, but am > stuck with exception problems. Here's the relevant code snippet: > > self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > try: > self.s.connect((something.com, 5000)) > except socket.error, (value, message): This is equivalent to except socket.error, e: (value, message) = e in other words you are tuple-unpacking the exception. Since it is not a tuple, but a single value, you get an error. Try this: except socket.error, e: if self.s: self.s.close() print "Could not open socket: " + e.message Kent > if self.s: > self.s.close() > print "Could not open socket: " + message > sys.exit(1) > > I was testing for a timeout exception (which is 60 seconds by > default), but after the timeout I get the following error: > File "./client.py", line 54, in connect > except socket.error, (value, message): > ValueError: need more than 1 value to unpack > > I googled and found something on ValueError, but I couldn't see how it > applied here. > > I'd appreciate any help. > > Thanks, > Vinay > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pyro9219 at gmail.com Thu Nov 16 12:07:18 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 16 Nov 2006 03:07:18 -0800 Subject: [Tutor] Alternatives to PY2EXE In-Reply-To: References: Message-ID: I'm personally not to picky... I just want the tool to work, and like I said, for some reason I'm having trouble running very simple scripts from py2exe, which I dont seem to have while using pyInstaller. I've even written a drag and drop front-end for it (had one for py2exe too) to make using it stupidly easy. It really does boggle my mind how people can be so wierd when asked to run something that isn't a .exe... Guess its a side-effect of the windows generation. On 11/16/06, Tim Golden wrote: > > [Chris Hengge] > > | Because alot of the users here at Intel dont want to admit > | you can write usable programs in a "scripting" language.. so > | when they see a .exe they feel comfy... > > One option which could help there -- although your > other considerations might outweigh it -- is > Fredrik Lundh's exemaker: > > http://effbot.org/zone/exemaker.htm > > It doesn't bundle up Python in the way that py2exe > does: you still need to have python on the target > machine. But it does provide an .exe of your > program (which, behind the scenes, loads up the > Python dll in the same way that the python.exe > would have done in the first place). > > Thst way, the .exe-comfortable user sees a .exe > without the extra work of py2exe/installer etc. > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/5a3d2836/attachment.html From Tim.Golden at viacom-outdoor.co.uk Thu Nov 16 12:16:31 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 16 Nov 2006 11:16:31 -0000 Subject: [Tutor] Alternatives to PY2EXE In-Reply-To: Message-ID: [Chris Hengge] | It really does boggle my mind how people can be so wierd when | asked to run something that isn't a .exe... Guess its a | side-effect of the windows generation. I know exactly what you mean. I had to convince a project manager once to use Python (in some small, out-of-the-way aspect of the project) and ended up by saying: 'If you were using foo.exe, created by VB6 (his preferred tool, and highly unsuitable for the job in hand), you'd put foo.exe doc.in doc.out". Using Python, you're simply adding one more parameter: "python.exe foo.py doc.in doc.out"' which at least convinced him enough to let me do it! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From etrade.griffiths at dsl.pipex.com Thu Nov 16 12:44:50 2006 From: etrade.griffiths at dsl.pipex.com (etrade.griffiths at dsl.pipex.com) Date: Thu, 16 Nov 2006 11:44:50 +0000 Subject: [Tutor] Alternatives to PY2EXE In-Reply-To: References: Message-ID: <1163677490.455c4f32688ca@netmail.pipex.net> Thanks for the various advice(s) re PY2EXE alternatives. I considered installing Python on the target machines but though it would be simpler to install the EXE as I has done with C++ apps. Boy, how naive was that? Using PY2EXE is not straightforward and the documentation is fairly poor IMHO. pyInstaller sounds promising so I will check this out. From ajkadri at googlemail.com Thu Nov 16 14:21:54 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 16 Nov 2006 13:21:54 +0000 Subject: [Tutor] A strange problem--Django Message-ID: Hi , I am trying to view this URL: http://www.developeriq.com/aboutus.php3. But my browser (IE 7) is giving me the following message; It worked! Congratulations on your first Django-powered page. Of course, you haven't actually done any work yet. Here's what to do next: If you plan to use a database, edit the DATABASE_* settings in diq/settings.py. Start your first app by running python diq/manage.py startapp [appname]. You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work! What is this???? and how to rectify this thing to view the web-page. TIA. Best Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/8354afc1/attachment.htm From simon at brunningonline.net Thu Nov 16 14:31:14 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 16 Nov 2006 13:31:14 +0000 Subject: [Tutor] A strange problem--Django In-Reply-To: References: Message-ID: <8c7f10c60611160531n2b4498epba4c05658b97aa94@mail.gmail.com> On 11/16/06, Asrarahmed Kadri wrote: > I am trying to view this URL: > http://www.developeriq.com/aboutus.php3. > > But my browser (IE 7) is giving me the following message; > > > It worked! > Congratulations on your first Django-powered page. > Of course, you haven't actually done any work yet. Here's what to do next: It look like whoever is running the http://www.developeriq.com site has set up a Django site, but not yet configured it. If that "whoever" is you, check out the Django tutorial - it's excellent. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From ajkadri at googlemail.com Thu Nov 16 14:41:25 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 16 Nov 2006 13:41:25 +0000 Subject: [Tutor] A strange problem--Django In-Reply-To: <8c7f10c60611160531n2b4498epba4c05658b97aa94@mail.gmail.com> References: <8c7f10c60611160531n2b4498epba4c05658b97aa94@mail.gmail.com> Message-ID: Its not me and I dont know what is Django. :)- Asrarahmed On 11/16/06, Simon Brunning wrote: > > On 11/16/06, Asrarahmed Kadri wrote: > > I am trying to view this URL: > > http://www.developeriq.com/aboutus.php3. > > > > But my browser (IE 7) is giving me the following message; > > > > > > It worked! > > Congratulations on your first Django-powered page. > > Of course, you haven't actually done any work yet. Here's what to do > next: > > It look like whoever is running the http://www.developeriq.com site > has set up a Django site, but not yet configured it. > > If that "whoever" is you, check out the Django tutorial - it's excellent. > > -- > Cheers, > Simon B > simon at brunningonline.net > http://www.brunningonline.net/simon/blog/ > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/798414a6/attachment.html From simon at brunningonline.net Thu Nov 16 14:48:50 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 16 Nov 2006 13:48:50 +0000 Subject: [Tutor] A strange problem--Django In-Reply-To: References: <8c7f10c60611160531n2b4498epba4c05658b97aa94@mail.gmail.com> Message-ID: <8c7f10c60611160548rc2ca084v1b8bffa04b6775c7@mail.gmail.com> On 11/16/06, Asrarahmed Kadri wrote: > Its not me and I dont know what is Django. :)- Google does: . ;-) But anyway, it looks like there's a problem at developeriq's end, so you'll have to contact them to get it fixed. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From ajkadri at googlemail.com Thu Nov 16 15:35:44 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 16 Nov 2006 14:35:44 +0000 Subject: [Tutor] Help me with this problem relating to datetime In-Reply-To: <5e58f2e40611151638w11de302ale565e4ea8c42e012@mail.gmail.com> References: <5e58f2e40611151638w11de302ale565e4ea8c42e012@mail.gmail.com> Message-ID: Thanks for your reply, John. I'll get back to you if I get stuck. Regards, Asrarahmmed On 11/16/06, John Fouhy wrote: > > On 16/11/06, Asrarahmed Kadri wrote: > > Hi Folks, > > > > > > I have got a date (as string), time (as string) , number of slots ( > integer) > > and delta ( which is in seconds). > > I want to create a dictionary which has got date as the key, and the > value > > should be a tuple with two elements (start_time, end_time). > > > > I will take start_time and find the end_time using delta. This pair of > start > > and end times have a corresponding date. The date will be used as the > key > > for the dictionary. Once the time crosses midnight, the date will > change. > > Which part are you having trouble with? > > To convert a string into a Date or Datetime object, use > time.strptime(), and then build a Datetime from the resulting > time_tuple. > (in Python2.5, I think, the datetime module has its own strptime() > function, which short-cuts this process) > > -- > John. > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/403ea0d4/attachment-0001.html From doug.shawhan at gmail.com Thu Nov 16 16:15:36 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Thu, 16 Nov 2006 09:15:36 -0600 Subject: [Tutor] free IDE for Python? In-Reply-To: References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> <78b3a9580611140859y34c4d5ev135048e08f3f6f5c@mail.gmail.com> Message-ID: <5e1ceb8a0611160715y300f5289wed4d6bd52d888511@mail.gmail.com> I know it's merely a text editor, but for any non-gui stuff I use SciTE. The little execution pane is gawgeous, gawgeous, gawgeous. (Though I find it best to use at least a 19" monitor! ) On 11/15/06, Chris Hengge wrote: > > BTW... that also counts as my vouce for using SPE =D > > On 11/15/06, Chris Hengge wrote: > > > > I tried it back before I tried SPE. I remember it taking several hours > > and being very bloated. Have you watched the showmedo video? Thats what I > > used... > > > > http://showmedo.com/videos/series?name=PyDevEclipseList > > > > If I personally "had" to use something that obnoxious I'd just reinstall > > ironpython and use Visual Studio for everything since I already have it for > > C# applications. (Yes I understand it makes .net runtime code and not python > > code, but I can't justify using that large and resource eating a program to > > use a language that is supposed to be quick and easy... ) > > > > On 11/15/06, Alan Gauld < alan.gauld at btinternet.com> wrote: > > > > > > > > > "wesley chun" wrote > > > > Eclipse > > > > http://pydev.sourceforge.net > > > > http://www.eclipse.org/ > > > > > > Has anyone got an idiot's guide to getting Eclipse working > > > with python? > > > > > > I've tried a couple of times but ran out of patience. In fact I > > > haven't really got vanilla Eclipse working for Java yet, it all > > > seems a lot of work for an IDE! NetBeans was so much > > > easier.... but my friends all laughed at me and said I should > > > be using Eclipse... :-) > > > > > > Alan (the impatient) G. > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/4026dff4/attachment.htm From Mike.Hansen at atmel.com Thu Nov 16 16:36:25 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 16 Nov 2006 08:36:25 -0700 Subject: [Tutor] free IDE for Python? Message-ID: <57B026980605A64F9B23484C5659E32E3CA9DA@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld > Sent: Wednesday, November 15, 2006 4:49 PM > To: tutor at python.org > Subject: Re: [Tutor] free IDE for Python? > > > "wesley chun" wrote > > Eclipse > > http://pydev.sourceforge.net > > http://www.eclipse.org/ > > Has anyone got an idiot's guide to getting Eclipse working > with python? > > I've tried a couple of times but ran out of patience. In fact I > haven't really got vanilla Eclipse working for Java yet, it all > seems a lot of work for an IDE! NetBeans was so much > easier.... but my friends all laughed at me and said I should > be using Eclipse... :-) > > Alan (the impatient) G. > I found the getting started docs got me going with Eclipse and Pydev. http://www.fabioz.com/pydev/manual_101_root.html I still find myself using VIM more than Eclipse. I'll need to play with Eclipse some more to make a decision if I want to stick with it or just stay with VIM. Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From lucidmonk at gmail.com Thu Nov 16 17:49:55 2006 From: lucidmonk at gmail.com (Todd Dahl) Date: Thu, 16 Nov 2006 11:49:55 -0500 Subject: [Tutor] Recursive functions and the windows registry Message-ID: <44290fe50611160849o421032ci2e86a33c57d10a09@mail.gmail.com> I have been fighting with this for a couple of days and am getting frustrated with it. I am trying to figure out a way to walk through the windows registry and to capture all nodes under the HKEY_CLASSES_ROOT\CLSID key and then put it into a list. I have been trying to do it with a recursive function but am having no luck with it. I am really hoping that it's because I am new to Python and not because I am doing something stupid but it would not be the first time I missed something obvious. This script is a subset of the larger script that I am working on. Any help or feedback would be great. I'm getting to the end of my rope. By the way I don't understand why it seems to work inside the ListRegistryKeys function but it doesn't pass all the information back to the parseRegistry function. -Todd ==== #!/usr/bin/env python import _winreg # _winreg module allows you to work with the windows registry def ListRegistryKeys(path): # if its empty do nothing if not path: return key=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, path) i=0 name = [] try: while 1: name.append(path + "\\" + _winreg.EnumKey(key, i)) print name[-1] i += 1 except WindowsError: pass _winreg.CloseKey( key) for item in name: ListRegistryKeys(item) return name def parseRegistry(): guidlist = ListRegistryKeys("CLSID") for item in guidlist: print "parseRegistry: ", item def main(): parseRegistry() if __name__=="__main__": main() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/469c8294/attachment.html From ajkadri at googlemail.com Thu Nov 16 18:28:54 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 16 Nov 2006 17:28:54 +0000 Subject: [Tutor] how to extract time from datetime.date.time() Message-ID: Hi, I want to extract hh:mm:ss from below mentioned code: import datetime >>> t = datetime.datetime.now() >>> print t 2006-11-16 16:59:02.843000 How to do it? TIA. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/5f05ac43/attachment.html From Mike.Hansen at atmel.com Thu Nov 16 18:38:21 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 16 Nov 2006 10:38:21 -0700 Subject: [Tutor] how to extract time from datetime.date.time() Message-ID: <57B026980605A64F9B23484C5659E32E3CAA13@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Asrarahmed Kadri > Sent: Thursday, November 16, 2006 10:29 AM > To: tutor-python > Subject: [Tutor] how to extract time from datetime.date.time() > > Hi, > > I want to extract hh:mm:ss from below mentioned code: > > import datetime > >>> t = datetime.datetime.now() > >>> print t > 2006-11-16 16:59:02.843000 > > How to do it? > > TIA. > Regards, > Asrarahmed > > -- > To HIM you shall return. > http://docs.python.org/lib/datetime-datetime.html I believe datetime.datetime.now() returns a datetime object. You can just look at the attributes of the object. In [6]: import datetime In [7]: t = datetime.datetime.now() In [8]: t.hour Out[8]: 10 In [10]: t.minute Out[10]: 33 In [11]: t.second Out[11]: 37 -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From jason.massey at gmail.com Thu Nov 16 18:39:57 2006 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 16 Nov 2006 11:39:57 -0600 Subject: [Tutor] how to extract time from datetime.date.time() In-Reply-To: References: Message-ID: <7e3eab2c0611160939j15b8b86fvd0cdcce865f207fe@mail.gmail.com> How about two different ways: >>> import datetime >>> t = datetime.datetime.now() >>> t datetime.datetime(2006, 11, 16, 11, 28, 15, 750000) >>> t.hour 11 >>> t.minute 28 >>> t.second 15 >>> a = "%d:%d:%d" % (t.hour,t.minute,t.second) >>> a '11:28:15' >>> or, a bit more succinctly: >>> t.strftime('%H:%M:%S') '11:28:15' All of this info is readily avaliable in the python docs. http://docs.python.org/lib/module-datetime.html On 11/16/06, Asrarahmed Kadri wrote: > > Hi, > > I want to extract hh:mm:ss from below mentioned code: > > import datetime > >>> t = datetime.datetime.now() > >>> print t > 2006-11-16 16:59:02.843000 > > How to do it? > > TIA. > Regards, > Asrarahmed > > -- > To HIM you shall return. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/4b67b8b0/attachment.htm From noufal at airtelbroadband.in Thu Nov 16 18:46:15 2006 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Thu, 16 Nov 2006 23:16:15 +0530 Subject: [Tutor] how to extract time from datetime.date.time() In-Reply-To: References: Message-ID: <455CA3E7.8070001@airtelbroadband.in> Asrarahmed Kadri wrote: > Hi, > > I want to extract hh:mm:ss from below mentioned code: > > import datetime >>>> t = datetime.datetime.now() >>>> print t > 2006-11-16 16:59:02.843000 > > How to do it? Did you read the documentation and try something out before posting this question on the list? -- ~noufal From python at venix.com Thu Nov 16 18:56:59 2006 From: python at venix.com (Python) Date: Thu, 16 Nov 2006 12:56:59 -0500 Subject: [Tutor] how to extract time from datetime.date.time() In-Reply-To: References: Message-ID: <1163699819.327.190.camel@www.venix.com> On Thu, 2006-11-16 at 17:28 +0000, Asrarahmed Kadri wrote: > Hi, > > I want to extract hh:mm:ss from below mentioned code: > > import datetime > >>> t = datetime.datetime.now() > >>> print t > 2006-11-16 16:59:02.843000 > > How to do it? The python interpreter can be pretty helpful for this kind of question. >>> import datetime >>> t = datetime.datetime.now() >>> t datetime.datetime(2006, 11, 16, 12, 44, 23, 766220) >>> dir(t) ['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__str__', '__sub__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'time', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year'] >>> t.hour 12 >>> t.min datetime.datetime(1, 1, 1, 0, 0) >>> t.minute 44 >>> t.second 23 The dir function returns the contents of an object. min and minute were the likely names for the the number of minutes. Your Python installation should have included the documentation, but you can also go to the python.org web site. The module index provides links to each module's documentation. http://www.python.org/doc/ http://docs.python.org/modindex.html http://docs.python.org/lib/module-datetime.html Reading the module documentation we find that min is the minimum datetime value and has nothing to do with minutes. > > TIA. > Regards, > Asrarahmed > > -- > To HIM you shall return. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From carroll at tjc.com Thu Nov 16 20:06:12 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 16 Nov 2006 11:06:12 -0800 (PST) Subject: [Tutor] how to extract time from datetime.date.time() In-Reply-To: Message-ID: On Thu, 16 Nov 2006, Asrarahmed Kadri wrote: > I want to extract hh:mm:ss from below mentioned code: > > import datetime > >>> t = datetime.datetime.now() > >>> print t > 2006-11-16 16:59:02.843000 > > How to do it? In addition to the suggestions you've seen, now() returns a datetime object, and a datetime object has a time() method that returns a time object: >>> dt = datetime.datetime.now() >>> t = dt.time() >>> print t 10:55:06.801000 You can get this into a string easily, if you want: >>> s = str(t) >>> s '10:55:06.801000' or, if you want the ugly one-liner: >>> s = str(datetime.datetime.now().time()) >>> s '10:56:04.361000' If you don't want the fractional part of the seconds, you can use the ordinary string methods to find the dot and slice off only the part you want to keep. For example: >>> s[0:s.find('.')] '10:56:04' Digression: It is possible to combine this with the prior ugly one-liner to produce the result you want, but it would require invoking now() twice, with the result that one instance would be used to generate the string in which you search for the '.', and the other used as the string from which the hh:mm:ss is sliced, where the two instances will have different values, but identical formats, which is good enough here, but that strikes me as just inelegant, and requires a pointless second invocation of now(), and besides, the end result will be nearly as unreadable as this sentence. But, just for the hell of it: >>> s = str(datetime.datetime.now().time())[0:str(datetime.datetime.now().time()).find('.')] >>> s '11:01:32' From hmm at woolgathering.cx Thu Nov 16 20:08:17 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Thu, 16 Nov 2006 14:08:17 -0500 Subject: [Tutor] free IDE for Python? In-Reply-To: <57B026980605A64F9B23484C5659E32E3CA9DA@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E3CA9DA@poccso.US.ad.atmel.com> Message-ID: <20061116190817.GA12672@sillyrabbi.dyndns.org> On Thu, Nov 16, 2006 at 08:36:25AM -0700, Mike Hansen wrote: >I found the getting started docs got me going with Eclipse and Pydev. > >http://www.fabioz.com/pydev/manual_101_root.html > >I still find myself using VIM more than Eclipse. I'll need to play with >Eclipse some more to make a decision if I want to stick with it or just >stay with VIM. You don't have to choose, use the viPlugin for Eclipse: http://www.eclipseplugincentral.com/Web_Links-index-req-viewlink-cid-103.html -- yours, William From vinayvinay at gmail.com Thu Nov 16 20:20:38 2006 From: vinayvinay at gmail.com (Vinay Reddy) Date: Thu, 16 Nov 2006 14:20:38 -0500 Subject: [Tutor] exception problems in socket programming In-Reply-To: <455C45FE.9010207@tds.net> References: <537f59d10611151903x572d0025y164239782ccc4b29@mail.gmail.com> <455C45FE.9010207@tds.net> Message-ID: <537f59d10611161120h7b0edcd3n663a5995cf1a21d9@mail.gmail.com> > in other words you are tuple-unpacking the exception. Since it is not a > tuple, but a single value, you get an error. Try this: > except socket.error, e: > if self.s: > self.s.close() > print "Could not open socket: " + e.message Thanks a lot! I had to make a minor change to get it to work though. 'e' is a list with variable number of elements (depends on the exception). Replacing e.message with str(e) does the trick. Thanks, Vinay From kent37 at tds.net Thu Nov 16 20:25:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Nov 2006 14:25:39 -0500 Subject: [Tutor] how to extract time from datetime.date.time() In-Reply-To: References: Message-ID: <455CBB33.2060408@tds.net> Terry Carroll wrote: > If you don't want the fractional part of the seconds, you can use the > ordinary string methods to find the dot and slice off only the part you > want to keep. For example: > >>>> s[0:s.find('.')] > '10:56:04' or s.split('.')[0] which you can put into your one-liner. Kent From carroll at tjc.com Thu Nov 16 20:30:46 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 16 Nov 2006 11:30:46 -0800 (PST) Subject: [Tutor] how to extract time from datetime.date.time() In-Reply-To: <455CBB33.2060408@tds.net> Message-ID: On Thu, 16 Nov 2006, Kent Johnson wrote: > or s.split('.')[0] which you can put into your one-liner. Yes, but that would not have given me the opportunity to write that extravagantly run-on sentence. From dyoo at hkn.eecs.berkeley.edu Thu Nov 16 20:51:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Nov 2006 11:51:13 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 33, Issue 64 In-Reply-To: References: Message-ID: > I have been fighting with this for a couple of days and am getting > frustrated with it. I am trying to figure out a way to walk through the > windows registry and to capture all nodes under the > HKEY_CLASSES_ROOT\CLSID key and then put it into a list. Ok, let's do this carefully. Let's first look at the source code, and I'll make comments as we go along: > def ListRegistryKeys(path): > # if its empty do nothing > if not path: return > key=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, path) > i=0 > name = [] > try: > while 1: > name.append(path + "\\" + _winreg.EnumKey(key, i)) > print name[-1] > i += 1 > except WindowsError: > pass > _winreg.CloseKey( key) > for item in name: > ListRegistryKeys(item) > return name First, we have to say what ListRegisterKeys expects to take in and what we expect for it to return. Here, it looks like it expects to take in a path, and returns...? It looks like it's supposed to return a list of names. If that's true, take a very close look at any place where ListRegistryKeys is being used, or where it is returning values back: > # if its empty do nothing > if not path: return That's not quite right: it must return some list of things. Thankfully, it's perfectly ok to return a list of no elements: if not path: return [] Ok, let's look at another snippet: > for item in name: > ListRegistryKeys(item) What's going on here are recursive calls. From the reasoning above, we know that ListRegistryKeys() will give us back a list of names for that item. We'd better not let those results just drop onto the floor. We should collect them! subnames = [] for item in name: subnames.extend(ListRegistryKeys(item)) We collect all of the names of the inner registry keys in 'subnames'. Finally, when we return the result of the whole thing, we must combine the results of the recursive calls together with our initial set of names. return name + subnames Here's what the code looks like with all those changes, plus some variable renaming and variable shifting. ############################################################## def ListRegistryKeys(path): """ListRegistryKeys: given a path, returns a list of key names underneath that path.""" if not path: return [] names = [] key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, path) try: i = 0 while 1: names.append(path + "\\" + _winreg.EnumKey(key, i)) i += 1 except WindowsError: pass _winreg.CloseKey(key) subnames = [] for item in names: subnames.extend(ListRegistryKeys(item)) return names + subnames ############################################################## You may want to read: http://www.ibiblio.org/obp/thinkCSpy/chap04.html#auto8 ... Unfortunately, the way that that book introduces recursive functions is bad in the sense that it focuses way too much on IO, on printing things rather than on manipulating values. The meager example in the next chapter is not much better. http://www.ibiblio.org/obp/thinkCSpy/chap05.html#auto4 Ugh. The factorial function is a sad way to introduce recursion because it's irrelevant to most people. If you have time, take a look at: http://www.htdp.org/ In particular, http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-13.html#node_sec_9.4 which isn't Python, but has a good approach to teaching useful recursion. You can then bring that knowledge back into Python-space. From Mike.Hansen at atmel.com Thu Nov 16 20:56:12 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 16 Nov 2006 12:56:12 -0700 Subject: [Tutor] free IDE for Python? Message-ID: <57B026980605A64F9B23484C5659E32E3CAA4B@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of William > O'Higgins Witteman > Sent: Thursday, November 16, 2006 12:08 PM > To: tutor at python.org > Subject: Re: [Tutor] free IDE for Python? > > On Thu, Nov 16, 2006 at 08:36:25AM -0700, Mike Hansen wrote: > > >I found the getting started docs got me going with Eclipse and Pydev. > > > >http://www.fabioz.com/pydev/manual_101_root.html > > > >I still find myself using VIM more than Eclipse. I'll need > to play with > >Eclipse some more to make a decision if I want to stick with > it or just > >stay with VIM. > > You don't have to choose, use the viPlugin for Eclipse: > > http://www.eclipseplugincentral.com/Web_Links-index-req-viewli > nk-cid-103.html > -- > > yours, > > William That looks interesting. This looks better than eclim. On the surface, Eclim looked kind of strange to set up and use. Thanks, Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From nephish at gmail.com Thu Nov 16 22:07:41 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 16 Nov 2006 15:07:41 -0600 Subject: [Tutor] email content-type: text/plain Message-ID: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> hey there all, i am using the email package and the phone provider i am trying to get a text message thru has sent me an email that says that they are looking for a tag that says 'content-type text/plain' i have tried about everything i can think of to get it in there, but everything i have tried has failed. here is what i have so far: address = 'someplace at someplace.com' message = 'some text that needs to be delivered via text message' msg = MIMEText(message) msg['Subject'] = 'pivots' msg['From'] = 'l11 at xit.net' msg['To'] = address server.sendmail(msg['From'],msg['To'], msg.as_string()) any ideas ? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/e60a1765/attachment-0001.htm From pyro9219 at gmail.com Thu Nov 16 22:49:49 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 16 Nov 2006 13:49:49 -0800 Subject: [Tutor] email content-type: text/plain In-Reply-To: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> References: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> Message-ID: Not sure if I'm really helping, but I want to try for all the help I've gotten... I took this from: http://docs.python.org/lib/module-email.message.html ############################################################################## *class MIMEText*( _text[, _subtype[, _charset]]) Module: email.mime.text A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtype is the minor type and defaults to plain. _charset is the character set of the text and is passed as a parameter to the MIMENonMultipart constructor; it defaults to us-ascii. No guessing or encoding is performed on the text data. ############################################################################# Going off this, I'd say you need to change: msg = MIMEText(message) to: msg = MIMEText(message, 'someTypeThatIsn'tPlain') On 11/16/06, shawn bright wrote: > > hey there all, > i am using the email package and the phone provider i am trying to get a > text message thru has sent me an email that says that they are looking for a > tag that says 'content-type text/plain' > > i have tried about everything i can think of to get it in there, but > everything i have tried has failed. > > here is what i have so far: > address = 'someplace at someplace.com' > message = 'some text that needs to be delivered via text message' > msg = MIMEText(message) > msg['Subject'] = 'pivots' > msg['From'] = 'l11 at xit.net' > msg['To'] = address > server.sendmail(msg['From'],msg['To'], msg.as_string()) > > any ideas ? > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/4a17d365/attachment.html From pyro9219 at gmail.com Thu Nov 16 22:56:40 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 16 Nov 2006 13:56:40 -0800 Subject: [Tutor] email content-type: text/plain In-Reply-To: References: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> Message-ID: I just re-read your email, and I dont think I answered it accurately since you apparently want plain... so maybe you can still use my example for "force" the type? On 11/16/06, Chris Hengge wrote: > > Not sure if I'm really helping, but I want to try for all the help I've > gotten... > I took this from: http://docs.python.org/lib/module-email.message.html > > ############################################################################## > *class MIMEText*( _text[, _subtype[, _charset]]) Module: email.mime.text > > A subclass of MIMENonMultipart, the MIMEText class is used to create MIME > objects of major type text. _text is the string for the payload. _subtypeis the minor type and defaults to > plain. _charset is the character set of the text and is passed as a > parameter to the MIMENonMultipart constructor; it defaults to us-ascii. No > guessing or encoding is performed on the text data. > > > ############################################################################# > > Going off this, I'd say you need to change: > > msg = MIMEText(message) > > to: > > msg = MIMEText(message, 'someTypeThatIsn'tPlain') > On 11/16/06, shawn bright wrote: > > > hey there all, > > i am using the email package and the phone provider i am trying to get a > > text message thru has sent me an email that says that they are looking for a > > tag that says 'content-type text/plain' > > > > i have tried about everything i can think of to get it in there, but > > everything i have tried has failed. > > > > here is what i have so far: > > address = 'someplace at someplace.com' > > message = 'some text that needs to be delivered via text message' > > msg = MIMEText(message) > > msg['Subject'] = 'pivots' > > msg['From'] = 'l11 at xit.net' > > msg['To'] = address > > server.sendmail(msg['From'],msg['To'], msg.as_string()) > > > > any ideas ? > > thanks > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/7c1ecd92/attachment.htm From nephish at gmail.com Thu Nov 16 22:57:03 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 16 Nov 2006 15:57:03 -0600 Subject: [Tutor] email content-type: text/plain In-Reply-To: References: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> Message-ID: <384c93600611161357o6c838647o2b64892399d266ee@mail.gmail.com> use MIMEText(message, 'someTypeThatIsn'tPlain') ? but type/plain is what i am after. i am a bit confused here. It defaults to plain, but there is not anything in the message headers that say what type it is. Should i use MIMEText(message, 'text/plain') ? thanks sk On 11/16/06, Chris Hengge wrote: > > Not sure if I'm really helping, but I want to try for all the help I've > gotten... > I took this from: http://docs.python.org/lib/module-email.message.html > > ############################################################################## > *class MIMEText*( _text[, _subtype[, _charset]]) Module: email.mime.text > > A subclass of MIMENonMultipart, the MIMEText class is used to create MIME > objects of major type text. _text is the string for the payload. _subtypeis the minor type and defaults to > plain. _charset is the character set of the text and is passed as a > parameter to the MIMENonMultipart constructor; it defaults to us-ascii. No > guessing or encoding is performed on the text data. > > > ############################################################################# > > Going off this, I'd say you need to change: > > msg = MIMEText(message) > > to: > > msg = MIMEText(message, 'someTypeThatIsn'tPlain') > On 11/16/06, shawn bright wrote: > > > > hey there all, > > i am using the email package and the phone provider i am trying to get a > > text message thru has sent me an email that says that they are looking for a > > tag that says 'content-type text/plain' > > > > i have tried about everything i can think of to get it in there, but > > everything i have tried has failed. > > > > here is what i have so far: > > address = 'someplace at someplace.com' > > message = 'some text that needs to be delivered via text message' > > msg = MIMEText(message) > > msg['Subject'] = 'pivots' > > msg['From'] = 'l11 at xit.net' > > msg['To'] = address > > server.sendmail(msg['From'],msg['To'], msg.as_string()) > > > > any ideas ? > > thanks > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/eb82ab5c/attachment.html From pyro9219 at gmail.com Thu Nov 16 23:03:57 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 16 Nov 2006 14:03:57 -0800 Subject: [Tutor] email content-type: text/plain In-Reply-To: <384c93600611161357o6c838647o2b64892399d266ee@mail.gmail.com> References: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> <384c93600611161357o6c838647o2b64892399d266ee@mail.gmail.com> Message-ID: I would start by "forcing" 'text/plain'. If that doesn't work maybe take a look at: *set_type*( type[, header][, requote]) Set the main type and subtype for the Content-Type: header. type must be a string in the form maintype/subtype, otherwise a ValueError is raised. This method replaces the Content-Type: header, keeping all the parameters in place. If requote is False, this leaves the existing header's quoting as is, otherwise the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type: header is set a MIME-Version: header is also added. New in version 2.2.2. ************************************************************************************************************* Just out of curiosity, have you tested your message? msg = MIMEText(message) print get_content_type(message) or: msg = MIMEText(message, 'plain/text') print get_content_type(message) ************************************************************************************************************* I'm just tossing out idea's for things I would try. I've not actually used this module yet. On 11/16/06, shawn bright wrote: > > use MIMEText(message, 'someTypeThatIsn'tPlain') ? but type/plain is what > i am after. > i am a bit confused here. It defaults to plain, but there is not anything > in the message headers that say what type it is. Should i use > MIMEText(message, 'text/plain') ? > > thanks > sk > > On 11/16/06, Chris Hengge wrote: > > > > Not sure if I'm really helping, but I want to try for all the help I've > > gotten... > > I took this from: http://docs.python.org/lib/module-email.message.html > > > > ############################################################################## > > *class MIMEText*( _text[, _subtype[, _charset]]) Module: > > email.mime.text > > > > A subclass of MIMENonMultipart, the MIMEText class is used to create > > MIME objects of major type text. _text is the string for the payload. > > _subtype is the minor type and defaults to plain. _charset is the > > character set of the text and is passed as a parameter to the > > MIMENonMultipart constructor; it defaults to us-ascii. No guessing or > > encoding is performed on the text data. > > > > > > ############################################################################# > > > > Going off this, I'd say you need to change: > > > > msg = MIMEText(message) > > > > to: > > > > msg = MIMEText(message, 'someTypeThatIsn'tPlain') > > On 11/16/06, shawn bright wrote: > > > > > > hey there all, > > > i am using the email package and the phone provider i am trying to get > > > a text message thru has sent me an email that says that they are looking for > > > a tag that says 'content-type text/plain' > > > > > > i have tried about everything i can think of to get it in there, but > > > everything i have tried has failed. > > > > > > here is what i have so far: > > > address = 'someplace at someplace.com' > > > message = 'some text that needs to be delivered via text message' > > > msg = MIMEText(message) > > > msg['Subject'] = 'pivots' > > > msg['From'] = 'l11 at xit.net' > > > msg['To'] = address > > > server.sendmail(msg['From'],msg['To'], msg.as_string()) > > > > > > any ideas ? > > > thanks > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/db242248/attachment-0001.htm From pyro9219 at gmail.com Thu Nov 16 23:10:22 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 16 Nov 2006 14:10:22 -0800 Subject: [Tutor] email content-type: text/plain In-Reply-To: References: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> <384c93600611161357o6c838647o2b64892399d266ee@mail.gmail.com> Message-ID: Just so you can compare... >> msg = MIMEText.MIMEText("How are you!?") >> email.Message.Message.get_content_type(msg) 'text/plain' On 11/16/06, Chris Hengge wrote: > > I would start by "forcing" 'text/plain'. > If that doesn't work maybe take a look at: > * set_type*( type[, header][, requote]) Set the main type and subtype for > the Content-Type: header. type must be a string in the form > maintype/subtype, otherwise a ValueError is raised. > > This method replaces the Content-Type: header, keeping all the parameters > in place. If requote is False, this leaves the existing header's quoting > as is, otherwise the parameters will be quoted (the default). > > An alternative header can be specified in the header argument. When the > Content-Type: header is set a MIME-Version: header is also added. > > New in version 2.2.2. > > ************************************************************************************************************* > Just out of curiosity, have you tested your message? > msg = MIMEText(message) > print get_content_type(message) > > or: > > msg = MIMEText(message, 'plain/text') > print get_content_type(message) > ************************************************************************************************************* > > I'm just tossing out idea's for things I would try. I've not actually used > this module yet. > > > On 11/16/06, shawn bright < nephish at gmail.com> wrote: > > > > use MIMEText(message, 'someTypeThatIsn'tPlain') ? but type/plain is > > what i am after. > > i am a bit confused here. It defaults to plain, but there is not > > anything in the message headers that say what type it is. Should i use > > MIMEText(message, 'text/plain') ? > > > > thanks > > sk > > > > On 11/16/06, Chris Hengge < pyro9219 at gmail.com> wrote: > > > > > > Not sure if I'm really helping, but I want to try for all the help > > > I've gotten... > > > I took this from: http://docs.python.org/lib/module-email.message.html > > > > > > ############################################################################## > > > *class MIMEText*( _text[, _subtype[, _charset]]) Module: > > > email.mime.text > > > > > > A subclass of MIMENonMultipart, the MIMEText class is used to create > > > MIME objects of major type text. _text is the string for the payload. > > > _subtype is the minor type and defaults to plain. _charset is the > > > character set of the text and is passed as a parameter to the > > > MIMENonMultipart constructor; it defaults to us-ascii. No guessing or > > > encoding is performed on the text data. > > > > > > > > > ############################################################################# > > > > > > Going off this, I'd say you need to change: > > > > > > msg = MIMEText(message) > > > > > > to: > > > > > > msg = MIMEText(message, 'someTypeThatIsn'tPlain') > > > On 11/16/06, shawn bright wrote: > > > > > > > > hey there all, > > > > i am using the email package and the phone provider i am trying to > > > > get a text message thru has sent me an email that says that they are looking > > > > for a tag that says 'content-type text/plain' > > > > > > > > i have tried about everything i can think of to get it in there, but > > > > everything i have tried has failed. > > > > > > > > here is what i have so far: > > > > address = 'someplace at someplace.com' > > > > message = 'some text that needs to be delivered via text message' > > > > msg = > > > > MIMEText(message) > > > > msg['Subject'] = 'pivots' > > > > msg['From'] = 'l11 at xit.net' > > > > msg['To'] = address > > > > server.sendmail(msg['From'],msg['To'], msg.as_string()) > > > > > > > > any ideas ? > > > > thanks > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/1cba6e9a/attachment.htm From pythontut at pusspaws.net Thu Nov 16 23:14:41 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 16 Nov 2006 22:14:41 +0000 Subject: [Tutor] free IDE for Python? In-Reply-To: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> References: <79E3309F6A39ED4891677ACCD2CF6B560A8248C9@DEN-EXM-03.corp.ebay.com> Message-ID: <200611162214.42239.pythontut@pusspaws.net> On Monday 13 November 2006 23:03, Vadhri, Srinivas wrote: > Hi > > > > A newbie to Python. What is the free IDE for Python development > activities? ActiveState's Komodo IDE needs a license and a fee. > > > > Any recommendations? Eric3/4 works for me :) http://www.die-offenbachs.de/detlev/eric3-screenshots.html > > Regards, > > Srinivas Vadhri From pythontut at pusspaws.net Thu Nov 16 23:22:06 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 16 Nov 2006 22:22:06 +0000 Subject: [Tutor] .sort(key = ???) Message-ID: <200611162222.06661.pythontut@pusspaws.net> Hi, I have a bunch of lists within lists that I need to sort ref item [4], I can't access my code at the moment but I basically ... a = [[...], [...], .... ] a.sort(item4) def item4(a,b): return a[4], b[4] Having googled I think there is a better way of doing this with the key attribute a.sort(key= ?? ) I cant get a handle on how key works or how to code it for my needs. Can anyone help ? Thanks in advance Dave From python at venix.com Thu Nov 16 23:30:35 2006 From: python at venix.com (Python) Date: Thu, 16 Nov 2006 17:30:35 -0500 Subject: [Tutor] email content-type: text/plain In-Reply-To: <384c93600611161357o6c838647o2b64892399d266ee@mail.gmail.com> References: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> <384c93600611161357o6c838647o2b64892399d266ee@mail.gmail.com> Message-ID: <1163716235.327.248.camel@www.venix.com> On Thu, 2006-11-16 at 15:57 -0600, shawn bright wrote: > use MIMEText(message, 'someTypeThatIsn'tPlain') ? but type/plain is > what i am after. > i am a bit confused here. It defaults to plain, but there is not > anything in the message headers that say what type it is. Should i use > MIMEText(message, 'text/plain') ? NO. server.sendmail takes a list of recipients. So rather than specifying msg['To'] for the recipients, use [address,'youremail at someisp.net'] You'll see exactly what you are sending. My emails that get sent with Python code pretty much like yours have the proper MIME tag: Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Do you have access to the server log files? Could something else be going wrong? My (works with email to text messaging and paging services) code: import urllib, urllib2, smtplib, pprint import email.MIMEText as MIMEText (snipped the dull parts) msg = MIMEText.MIMEText(msg_text) if subject: msg['Subject'] = subject msg['From'] = from_addy # to_addy is a list of recipients msg['To'] = ','.join(to_addy) server = smtplib.SMTP( mail_server) server.sendmail( from_addy, to_addy, msg.as_string()) server.close() > > thanks > sk > > On 11/16/06, Chris Hengge wrote: > Not sure if I'm really helping, but I want to try for all the > help I've gotten... > I took this from: http://docs.python.org/lib/module- > email.message.html > ############################################################################## > class MIMEText( > _text[, _subtype[, _charset]]) > Module: email.mime.text > > A subclass of MIMENonMultipart, the MIMEText class is used to > create MIME objects of major type text. _text is the string > for the payload. _subtype is the minor type and defaults to > plain. _charset is the character set of the text and is passed > as a parameter to the MIMENonMultipart constructor; it > defaults to us-ascii. No guessing or encoding is performed on > the text data. > > ############################################################################# > > Going off this, I'd say you need to change: > > msg = MIMEText(message) > > > to: > > msg = MIMEText(message, 'someTypeThatIsn'tPlain') > > On 11/16/06, shawn bright wrote: > hey there all, > i am using the email package and the phone provider i > am trying to get a text message thru has sent me an > email that says that they are looking for a tag that > says 'content-type text/plain' > > i have tried about everything i can think of to get it > in there, but everything i have tried has failed. > > here is what i have so far: > address = 'someplace at someplace.com' > message = 'some text that needs to be delivered via > text message' > msg = MIMEText > (message) > msg['Subject'] = 'pivots' > msg['From'] = 'l11 at xit.net' > msg['To'] = address > server.sendmail(msg['From'],msg['To'], msg.as_string > ()) > > any ideas ? > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From john at fouhy.net Thu Nov 16 23:35:07 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 17 Nov 2006 11:35:07 +1300 Subject: [Tutor] .sort(key = ???) In-Reply-To: <200611162222.06661.pythontut@pusspaws.net> References: <200611162222.06661.pythontut@pusspaws.net> Message-ID: <5e58f2e40611161435y2a940a0cm50853f0105e53a64@mail.gmail.com> On 17/11/06, Dave S wrote: > Hi, > > I have a bunch of lists within lists that I need to sort ref item [4], I can't > access my code at the moment but I basically ... > [...] > > Having googled I think there is a better way of doing this with the key > attribute > > a.sort(key= ?? ) Yep, that's right. You need at least python2.4 for this, though. You need to pass the key= parameter a function that will take an element of your list, and return the comparison key. eg: def item4(elem): return elem[4] a.sort(key=item4) Since this is a common thing to do, there is a function in the operator module that you can use, instead of defining your own: import operator a.sort(key=operator.itemgetter(4)) (operator.itemgetter(4) will return a function that is basically equivalent to item4() above) HTH! -- John. From alan.gauld at btinternet.com Thu Nov 16 23:41:49 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Nov 2006 22:41:49 -0000 Subject: [Tutor] Recursive functions and the windows registry References: <44290fe50611160849o421032ci2e86a33c57d10a09@mail.gmail.com> Message-ID: "Todd Dahl" wrote > By the way I don't understand why it seems to work inside the > ListRegistryKeys function but it doesn't pass all the information > back to > the parseRegistry function. > def ListRegistryKeys(path): > ... > name = [] > > try: > while 1: > name.append(path + "\\" + _winreg.EnumKey(key, i)) > print name[-1] > i += 1 > except WindowsError: > pass I'd rewrite this with the try/except inside the loop. while True: # use the boolean value, its clearer IMHO :-) try: name.append(...) print name[-1] i += 1 except WindowsError: pass However since you should(?) only get the error when you run out of keys to iterate that shouldn't cause your problem... > for item in name: > ListRegistryKeys(item) Note that this call will create a new name list inside the recursive call. You probably need to do: name += ListRegistryKeys(item) > return name Otherwise this just returns the top level list. > def parseRegistry(): > guidlist = ListRegistryKeys("CLSID") > > for item in guidlist: > print "parseRegistry: ", item > > def main(): > parseRegistry() > > if __name__=="__main__": > main() You could just call parseRegistry directly, there is no rule to say you need to use a main() function. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Thu Nov 16 23:40:40 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 16 Nov 2006 22:40:40 +0000 Subject: [Tutor] .sort(key = ???) In-Reply-To: <5e58f2e40611161435y2a940a0cm50853f0105e53a64@mail.gmail.com> References: <200611162222.06661.pythontut@pusspaws.net> <5e58f2e40611161435y2a940a0cm50853f0105e53a64@mail.gmail.com> Message-ID: <200611162240.40237.pythontut@pusspaws.net> On Thursday 16 November 2006 22:35, John Fouhy wrote: > On 17/11/06, Dave S wrote: > > Hi, > > > > I have a bunch of lists within lists that I need to sort ref item [4], I > > can't access my code at the moment but I basically ... > > [...] > > > Having googled I think there is a better way of doing this with the key > > attribute > > > > a.sort(key= ?? ) > > Yep, that's right. You need at least python2.4 for this, though. > > You need to pass the key= parameter a function that will take an > element of your list, and return the comparison key. > > eg: > > def item4(elem): > return elem[4] > > a.sort(key=item4) > > Since this is a common thing to do, there is a function in the > operator module that you can use, instead of defining your own: > > import operator > a.sort(key=operator.itemgetter(4)) > > (operator.itemgetter(4) will return a function that is basically > equivalent to item4() above) > > HTH! Sure does - cheers Dave From alan.gauld at btinternet.com Thu Nov 16 23:50:08 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Nov 2006 22:50:08 -0000 Subject: [Tutor] .sort(key = ???) References: <200611162222.06661.pythontut@pusspaws.net> Message-ID: "Dave S" wrote > I have a bunch of lists within lists that I need to sort ref item > [4], I can't > access my code at the moment but I basically ... > > a = [[...], [...], .... ] > a.sort(item4) > > def item4(a,b): > return a[4], b[4] > > > Having googled I think there is a better way of doing this with the > key > attribute > > a.sort(key= ?? ) > > I cant get a handle on how key works or how to code it for my needs. key is a function that returns the sortable item given the list as input. Thus for your example: a.sort(key=lambda s:s[4]) Or if you don't like lambdas: def item4(aSeqence): return aSequence[4] a.sort(key=item4) You can do some more "interesting" things with key too, including returning values derived from the original list, but the use shown is the basic technique. HTH, Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Nov 16 23:55:17 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Nov 2006 14:55:17 -0800 (PST) Subject: [Tutor] Returning compound objects? In-Reply-To: References: Message-ID: On Thu, 16 Nov 2006, Chris Hengge wrote: > I didn't send this to the list because I didn't want to go off-topic. [Meta] Then let's start a new topical thread. Let's call this one "Returning compound objects?" and work from there. But please let's keep this on Tutor; I'm serious when I say that I don't have much time these days to help out on python-tutor, and I want to make sure I don't become a single point of failure. I put myself on Digest mode for a reason. It's not because I don't want to help, but because I have other timely obligations that I can't ignore anymore. See: http://catb.org/esr/faqs/smart-questions.html#noprivate --------------------------------------------------------------------- > Could you please explain how this works? > > return names + subnames > > how do you catch something like that? Normally I'd do something like > > def foo(): > #do impressive stuff > return impressive_stuff > > impressive_stuff = foo() > > I was asking someone the other day about returning multiple items and I > got some huge answer about needing to pack the items into a single item, > then unpack them on the other side. Try this at the interactive interpreter: ####################################### words = ['this', 'is', 'a', 'sentence'] w1, w2, w3, w4 = words ####################################### What do you think will happen? Can you explain what's going on? Then take a look at this: ######################################## words = ['this', 'is', 'a', 'sentence'] w1, w2 = words ######################################### What do you think will happen? And then try it. Can you say in words what happened? Try explaining it. Finally, take a look at this: ####################################### def quotient_and_remainder(x, y): return [x / y, x % y] results = quotient_and_remainder(17, 5) print results q, r = quotient_and_remainder(17, 5) print q print r ######################################## Predict what you think will show up, and then see if your mental model matches what actually happens. From john at fouhy.net Fri Nov 17 00:10:58 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 17 Nov 2006 12:10:58 +1300 Subject: [Tutor] .sort(key = ???) In-Reply-To: <5e58f2e40611161435y2a940a0cm50853f0105e53a64@mail.gmail.com> References: <200611162222.06661.pythontut@pusspaws.net> <5e58f2e40611161435y2a940a0cm50853f0105e53a64@mail.gmail.com> Message-ID: <5e58f2e40611161510o9e0da7bp292dc5d9006d5a04@mail.gmail.com> Incidentally, I was wondering what the value of using operator.itemgetter is. So I ran some tests. Morpork:~/offlode repton$ python -m timeit -s 'import math' -s 'a = [(i, math.sin(i)) for i in range(10000)]' -s 'f = lambda e: e[1]' 'sorted(a, key=f)' 10 loops, best of 3: 22.4 msec per loop Morpork:~/offlode repton$ python -m timeit -s 'import math' -s 'import operator' -s 'a = [(i, math.sin(i)) for i in range(10000)]' -s 'f = operator.itemgetter(1)' 'sorted(a, key=f)' 100 loops, best of 3: 18.7 msec per loop So, slight win for operator.itemgetter. I'm not sure exactly how much of a win, since there's all those calls to cmp in the sort operation as well.. Incidentally, here's what happens if you define your own cmp function instead (the way you had to in python <= 2.3): Morpork:~/offlode repton$ python -m timeit -s 'import math' -s 'import operator' -s 'a = [(i, math.sin(i)) for i in range(10000)]' -s 'f = lambda x, y: cmp(x[1], y[1])' 'sorted(a, cmp=f)' 10 loops, best of 3: 163 msec per loop And decorate-sort-undecorate: Morpork:~/offlode repton$ python -m timeit -s 'import math' -s 'import operator' -s 'a = [(i, math.sin(i)) for i in range(10000)]' 'b = [(e[1], e) for e in a]' 'b.sort()' '[e[1] for e in b]' 10 loops, best of 3: 33.9 msec per loop Ho hum.. -- John. From nephish at gmail.com Fri Nov 17 00:52:56 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 16 Nov 2006 17:52:56 -0600 Subject: [Tutor] email content-type: text/plain In-Reply-To: <1163716235.327.248.camel@www.venix.com> References: <384c93600611161307m3b26459fgfc4c584aa0f1ca59@mail.gmail.com> <384c93600611161357o6c838647o2b64892399d266ee@mail.gmail.com> <1163716235.327.248.camel@www.venix.com> Message-ID: <384c93600611161552j3bc857d9vb2f688e7ef5a73f8@mail.gmail.com> ok, will try this out tomorrow at work. thanks. sk On 11/16/06, Python wrote: > > On Thu, 2006-11-16 at 15:57 -0600, shawn bright wrote: > > use MIMEText(message, 'someTypeThatIsn'tPlain') ? but type/plain is > > what i am after. > > i am a bit confused here. It defaults to plain, but there is not > > anything in the message headers that say what type it is. Should i use > > MIMEText(message, 'text/plain') ? > NO. > > server.sendmail takes a list of recipients. So rather than specifying > msg['To'] for the recipients, use > [address,'youremail at someisp.net'] > > You'll see exactly what you are sending. My emails that get sent with > Python code pretty much like yours have the proper MIME tag: > > Content-Type: text/plain; charset="us-ascii" > MIME-Version: 1.0 > > Do you have access to the server log files? Could something else be > going wrong? > > > My (works with email to text messaging and paging services) code: > > import urllib, urllib2, smtplib, pprint > import email.MIMEText as MIMEText > (snipped the dull parts) > msg = MIMEText.MIMEText(msg_text) > if subject: > msg['Subject'] = subject > msg['From'] = from_addy > # to_addy is a list of recipients > msg['To'] = ','.join(to_addy) > server = smtplib.SMTP( mail_server) > server.sendmail( from_addy, to_addy, msg.as_string()) > server.close() > > > > > thanks > > sk > > > > On 11/16/06, Chris Hengge wrote: > > Not sure if I'm really helping, but I want to try for all the > > help I've gotten... > > I took this from: http://docs.python.org/lib/module- > > email.message.html > > > ############################################################################## > > class MIMEText( > > _text[, _subtype[, _charset]]) > > Module: email.mime.text > > > > A subclass of MIMENonMultipart, the MIMEText class is used to > > create MIME objects of major type text. _text is the string > > for the payload. _subtype is the minor type and defaults to > > plain. _charset is the character set of the text and is passed > > as a parameter to the MIMENonMultipart constructor; it > > defaults to us-ascii. No guessing or encoding is performed on > > the text data. > > > > > ############################################################################# > > > > Going off this, I'd say you need to change: > > > > msg = MIMEText(message) > > > > > > to: > > > > msg = MIMEText(message, 'someTypeThatIsn'tPlain') > > > > On 11/16/06, shawn bright wrote: > > hey there all, > > i am using the email package and the phone provider i > > am trying to get a text message thru has sent me an > > email that says that they are looking for a tag that > > says 'content-type text/plain' > > > > i have tried about everything i can think of to get it > > in there, but everything i have tried has failed. > > > > here is what i have so far: > > address = 'someplace at someplace.com' > > message = 'some text that needs to be delivered via > > text message' > > msg = MIMEText > > (message) > > msg['Subject'] = 'pivots' > > msg['From'] = 'l11 at xit.net' > > msg['To'] = address > > server.sendmail(msg['From'],msg['To'], msg.as_string > > ()) > > > > any ideas ? > > thanks > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061116/c39e198a/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Nov 17 02:56:01 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 16 Nov 2006 17:56:01 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 33, Issue 67 In-Reply-To: References: Message-ID: > > while True: # use the boolean value, its clearer IMHO :-) > try: > name.append(...) > print name[-1] > i += 1 > except WindowsError: pass > [some comments cut] > > Note that this call will create a new name list inside the recursive > call. You probably need to do: > > name += ListRegistryKeys(item) Mutating the list while iterating over it is possibly bad. That's why it's probably better to use a separate variable to collect the sub-results. Concretely: ################## >>> L = [1] >>> for x in L: ... L.append(x) ... ################## is an infinite loop. From Senthil_OR at Dell.com Fri Nov 17 06:32:18 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Fri, 17 Nov 2006 11:02:18 +0530 Subject: [Tutor] OT: Vim was: free IDE for Python? In-Reply-To: Message-ID: Hi Alan, Greetings. Alan Gauld wrote: >> I have to chuckle when you recommend Vim for ease of use. > > Me too, and I've been a vi/elvis/viper/vim user for over 20 years(*). > vi/vim could never be described as easy to learn, but... I too use vim for a variety of editing tasks. From xml, python to normal text editing, not a power user yet. Do you have any tips/tricks to share for python on vim. Your vimrc file or any plugins you use. How would you run the python script from vim? - !python % OR any other way? I dislike the command line window popup to execute the scripts. (and press Enter key twice). I kindda wish, that for !python % should :split the window and display the results for non-interactive run. If interactive session, the cmd.exe could stay open.. What the settings of ppl using vim for python? -- Senthil From bn.sharath at gmail.com Fri Nov 17 07:21:28 2006 From: bn.sharath at gmail.com (sharath B N) Date: Fri, 17 Nov 2006 11:51:28 +0530 Subject: [Tutor] problem with defining a global class instance Message-ID: hi, i am sort of newbie to python. I am trying to do a super Market simulation with OOP in python. I have problems with using a class instance as global... def generate (... ,....,...) " in this function i define the global variables " global stock,stockManager, manager etc. class Manager ... ... ... def create_stockManager(..) """ this is a method in class manager""" stockManager = StockManager( name) stockManager.create_Stock(..) now this gives an attribute error sayin .... stockManager has no attribute create_Stock if i create the StockManager instance in the generate func itself...then this problem doesnt come....but i need it this way for the program to make sense.. can somebody help me thnks Sharath From singingxduck at gmail.com Fri Nov 17 09:14:25 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Fri, 17 Nov 2006 03:14:25 -0500 Subject: [Tutor] registering itunes with events Message-ID: <455D6F61.9030702@gmail.com> Hello all, As I mentioned in my recent emails, I've been working on a program that will display the currently playing iTunes track (for example, when iTunes is minimized to the system tray so that you don't have to enlarge it again just to see the name of the song). Unfortunately, of the hundreds of configurations I've found online, not one seems able to properly register iTunes with events, which would allow me to do away with the infinite while loop and time.sleep(1) and instead just call the update method whenever OnPlayerPlayEvent or OnPlayerStopEvent got called. I was playing around with it and managed for a bit to get it working, but all subsequent attempts to replicate the phenomenon have been fruitless. My best guess is something along the lines of: iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application") iTunesEvents = win32com.client.WithEvents(iTunes, iTunesEventHandler) where iTunesEventHandler is a class with methods OnPlayerPlayEvent, etc. From what I can glean, it seems like I'm missing some essential step that will keep the events connection open b/c the above tends to just close after calling iTunesEventHandler.__init__() Also, pythoncom seems to play a role in some of the online scripts I've found, but none of them seem to do anything. The trend seems to be: pythoncom.CoInitialize() iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application") iTunesEvents = win32com.client.WithEvents(iTunes, iTunesEventHandler) Sometimes followed with pythoncom.PumpWaitingMessages() Right now, I'd just like to be able to keep a connection open with iTunes that will catch OnPlayerPlayEvents and call the correct method. So if anyone has any idea how to do that, I'd be grateful. Thanks, Orri From alan.gauld at btinternet.com Fri Nov 17 10:00:51 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Nov 2006 09:00:51 -0000 Subject: [Tutor] Tutor Digest, Vol 33, Issue 67 References: Message-ID: "Danny Yoo" wrote >> Note that this call will create a new name list inside the >> recursive >> call. You probably need to do: >> >> name += ListRegistryKeys(item) > > > Mutating the list while iterating over it is possibly bad. I'd go so far as to say almost certainly bad! Oops, well caught Danny, apologies to the OP.. Alan G. From alan.gauld at btinternet.com Fri Nov 17 10:27:53 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Nov 2006 09:27:53 -0000 Subject: [Tutor] problem with defining a global class instance References: Message-ID: "sharath B N" wrote > i am sort of newbie to python. I am trying to do a super Market > simulation with OOP in python. I have problems with using a class > instance as global... > def generate (... ,....,...) > > " in this function i define the global variables " > global stock,stockManager, manager etc. Please don't do this! Global variables are dangerous enough as they are but by hiding their definitions inside a function you make them even more difficult to use. The global keyword is really intended to tell your function to use an existing global variable not to create new ones (although it does do that if the variable doesn't exist, its a side-effect that should be avoided IMHO) Just declare your global variables in the outer scope of your module: stock = 0 stockManager = None manager = 'whatever' > class Manager By defining the class here the name is at a global level and you can create instances as and where you need them. > def create_stockManager(..) > """ this is a method in class manager""" > stockManager = StockManager( name) > stockManager.create_Stock(..) > now this gives an attribute error sayin .... stockManager has no > attribute create_Stock You need to define the method in your StockManager class definition. ie class StockManager: ..... .... def create_Stock(self....) ... ... > if i create the StockManager instance in the generate func > itself...then this problem doesnt come....but i need it this way for > the program to make sense.. I'm not sure what you mean by the last bit. Are you saying that if you try to call create_Stock inside the generate function you don't get an error but if you call it outside you do? The only reason I can think of for that is that you are actually defining the class inside the function: def generate(.....): class StockManager: def create_Stock(... If so that will limit the class definition to inside generate which you don't want. Simply saying "global stockManager" in generate doesn't make your class global it just creates a new name in the global namespace. Another reason not to try hiding your global data declarations inside the generate function. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Nov 17 10:32:01 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Nov 2006 09:32:01 -0000 Subject: [Tutor] registering itunes with events References: <455D6F61.9030702@gmail.com> Message-ID: "Orri Ganel" wrote > been fruitless. My best guess is something along the lines of: > > iTunes = > win32com.client.gencache.EnsureDispatch("iTunes.Application") > iTunesEvents = win32com.client.WithEvents(iTunes, > iTunesEventHandler) > > where iTunesEventHandler is a class with methods OnPlayerPlayEvent, Are you sure its a class? I haven't looked into this but from past experience with Win32 I'd expect the event handler to be a function that takes the event and then calls the appropriate handler function. But I haven't checked the Python implementation so I could be completely off track there. Alan G. From bn.sharath at gmail.com Fri Nov 17 07:12:45 2006 From: bn.sharath at gmail.com (sharath B N) Date: Fri, 17 Nov 2006 11:42:45 +0530 Subject: [Tutor] problem with defining a global class instance Message-ID: hi, i am sort of newbie to python. I am trying to do a super Market simulation with OOP in python. I have problems with using a class instance as global... def generate (... ,....,...) " in this function i define the global variables " global stock,stockManager, manager etc. class Manager ... ... ... def create_stockManager(..) """ this is a method in class manager""" stockManager = StockManager( name) stockManager.create_Stock(..) now this gives an attribute error sayin .... stockManager has no attribute create_Stock if i create the StockManager instance in the generate func itself...then this problem doesnt come....but i need it this way for the program to make sense.. can somebody help me thnks Sharath From singingxduck at gmail.com Fri Nov 17 12:52:30 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Fri, 17 Nov 2006 06:52:30 -0500 Subject: [Tutor] registering itunes with events In-Reply-To: References: <455D6F61.9030702@gmail.com> Message-ID: <455DA27E.5090504@gmail.com> Alan Gauld wrote: >"Orri Ganel" wrote > > > >>been fruitless. My best guess is something along the lines of: >> >>iTunes = >>win32com.client.gencache.EnsureDispatch("iTunes.Application") >>iTunesEvents = win32com.client.WithEvents(iTunes, >>iTunesEventHandler) >> >>where iTunesEventHandler is a class with methods OnPlayerPlayEvent, >> >> > >Are you sure its a class? I haven't looked into this but from >past experience with Win32 I'd expect the event handler to >be a function that takes the event and then calls the appropriate >handler function. But I haven't checked the Python implementation >so I could be completely off track there. > >Alan G. > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > It's a class that I have to define myself, so you're right that it doesn't come with win32com et al. From tavspam at gmail.com Fri Nov 17 14:37:02 2006 From: tavspam at gmail.com (Thomas) Date: Fri, 17 Nov 2006 13:37:02 +0000 Subject: [Tutor] Read the builtin module source, also itchy ellipses. Message-ID: <493b81e30611170537v6be55494la563cd516d85a5e@mail.gmail.com> Hi, I sometimes find it useful to read the source code of a module and for example I can type string.__file__ to find the location of the string module. However the .__file__ method is not available for the module builtin. Is it possible to read the source code for built in functions and if so how do I find them? I realise some/all may be written in C rather than python but it would still be interesting to read them. In an unrelated follow-up may I also ask: can the ellipsis (...) be used in code? I tried a googlecode search but none of the examples worked for me. Can someone post an example line of code that uses ... in it. This has been causing an itch in my brain, please reply with the scratch. Thanks in advance, Tom -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/b3dba622/attachment.htm From kent37 at tds.net Fri Nov 17 15:10:28 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Nov 2006 09:10:28 -0500 Subject: [Tutor] Read the builtin module source, also itchy ellipses. In-Reply-To: <493b81e30611170537v6be55494la563cd516d85a5e@mail.gmail.com> References: <493b81e30611170537v6be55494la563cd516d85a5e@mail.gmail.com> Message-ID: <455DC2D4.3010702@tds.net> Thomas wrote: > Hi, > > I sometimes find it useful to read the source code of a module and for > example I can type string.__file__ to find the location of the string > module. > > However the .__file__ method is not available for the module builtin. Is > it possible to read the source code for built in functions and if so how > do I find them? I realise some/all may be written in C rather than > python but it would still be interesting to read them. It's all in C, see Python\bltinmodule.c in the source distribution. > > In an unrelated follow-up may I also ask: can the ellipsis (...) be used > in code? I tried a googlecode search but none of the examples worked for > me. Can someone post an example line of code that uses ... in it. > This has been causing an itch in my brain, please reply with the scratch. Syntactically ellipsis is allowed in a slice list as shown in the syntax definition here: http://docs.python.org/ref/slicings.html As a practical matter I think the only containers that actually support this kind of slicing are the arrays in Numeric and numpy. Here is a brief example: http://numpy.scipy.org//numpydoc/numpy-6.html#pgfId-36074 You could also support this syntax in a class of your own. Here is a simple example that just captures the argument to __getitem__() to show how the mechanism works: In [4]: class Foo(object): ...: def __getitem__(self, s): ...: self.s = s ...: return None ...: In [5]: f=Foo() In [6]: f[...,1] In [7]: f.s Out[7]: (Ellipsis, 1) Kent From Mike.Hansen at atmel.com Fri Nov 17 16:20:22 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Fri, 17 Nov 2006 08:20:22 -0700 Subject: [Tutor] OT: Vim was: free IDE for Python? References: Message-ID: <57B026980605A64F9B23484C5659E32E2A82F1@poccso.US.ad.atmel.com> ________________________________ From: tutor-bounces at python.org on behalf of Senthil_OR at Dell.com Sent: Thu 11/16/2006 10:32 PM To: alan.gauld at btinternet.com Cc: tutor at python.org Subject: Re: [Tutor] OT: Vim was: free IDE for Python? Hi Alan, Greetings. Alan Gauld wrote: >> I have to chuckle when you recommend Vim for ease of use. > > Me too, and I've been a vi/elvis/viper/vim user for over 20 years(*). > vi/vim could never be described as easy to learn, but... I too use vim for a variety of editing tasks. From xml, python to normal text editing, not a power user yet. Do you have any tips/tricks to share for python on vim. Your vimrc file or any plugins you use. How would you run the python script from vim? - !python % OR any other way? I dislike the command line window popup to execute the scripts. (and press Enter key twice). I kindda wish, that for !python % should :split the window and display the results for non-interactive run. If interactive session, the cmd.exe could stay open.. What the settings of ppl using vim for python? -- Senthil _______________________________________________ Here's what I'm doing. Not sure if it's that helpful to you. I use the mini-buffer explorer plug-in and the taglist plugin. set smartindent " shuts off the annoying "#" comment in smartindent to jump to col 1 inoremap # X# autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class I've mapped a key to run pyflakes and display the results in a different buffer :new | r!pyflakes # Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/e194da41/attachment.htm -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From picioslug at gmail.com Fri Nov 17 17:04:02 2006 From: picioslug at gmail.com (Picio) Date: Fri, 17 Nov 2006 17:04:02 +0100 Subject: [Tutor] python CRM ERP Message-ID: <825bef0c0611170804x384f905ehee9872e9d805cc97@mail.gmail.com> Hello, Can you point me to some CRM and ERP software written in Python, that in your "guru" opinion is a good product? Maybe also Open Source? Thanks Picio From hmm at woolgathering.cx Fri Nov 17 18:17:22 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Fri, 17 Nov 2006 12:17:22 -0500 Subject: [Tutor] OT: Vim was: free IDE for Python? In-Reply-To: References: Message-ID: <20061117171722.GA16549@sillyrabbi.dyndns.org> On Fri, Nov 17, 2006 at 11:02:18AM +0530, Senthil_OR at Dell.com wrote: >What the settings of ppl using vim for python? A few Python-specific things that I have in my .vimrc are as follows: set autoindent set ts=2 set shiftwidth=2 set expandtab set shiftround set smarttab filetype plugin on syntax on :inoremap ( ()i :inoremap [ []i :inoremap " ""i :inoremap { {}i :inoremap < <>i autocmd BufNewFile *.py 0r ~/.vim/skel/skel.py The python skeleton file looks like this: #!/usr/bin/python import Finally, my Python filetype file looks like this (just my changes): :inoremap ' ''i abbr dd #debug set spell! " Code Macros " Define a class in Python, with docstring inoremap class class :"""""" " Define a function in Python, with docstring inoremap def def ():"""""" " This is to create blocks when coding in Python im : : That's about it. I'm just a vim novice - there are lots of things I haven't learned or don't use enough and forget. -- yours, William From chris.arndt at web.de Fri Nov 17 18:22:49 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Fri, 17 Nov 2006 18:22:49 +0100 Subject: [Tutor] python CRM ERP In-Reply-To: <825bef0c0611170804x384f905ehee9872e9d805cc97@mail.gmail.com> References: <825bef0c0611170804x384f905ehee9872e9d805cc97@mail.gmail.com> Message-ID: <455DEFE9.8000702@web.de> Picio schrieb: > Hello, > Can you point me to some CRM and ERP software written in Python, that > in your "guru" opinion is a good product? Maybe also Open Source? Have you asked Google? http://tinyerp.org/ Chris From kdidriksson at yahoo.com Fri Nov 17 19:05:02 2006 From: kdidriksson at yahoo.com (kristinn didriksson) Date: Fri, 17 Nov 2006 10:05:02 -0800 (PST) Subject: [Tutor] a question about passing values between functions Message-ID: <511243.25365.qm@web33508.mail.mud.yahoo.com> Hello, I am still wrestling with the concept of values going between functions. (just starting out)The program below works seems to work, but here is my question. In my understanding, return area in the first routine makes the value of area an instance of areaCirc and I use areaCirc in the other program to call the value for the area that was calculated in the first routine. Is that the right way to think of this program? Did I use return area correctly? This is a new vocabulary, so I hope I am making sense. Basically, I am wondering if I needed to use the return area statement. Thanks, Kristinn --------------- # this program is a redo of ex2 ch3 with a twist! 2 # use two functions--one to compute the area of a pizza, and one to 3 # to compute cost per square inch. 4 # Given are the diameter and the price. A = pi(r**2) 5 6 # define the function that computes the area 7 import math 8 def areaCirc(): 9 diameter = input("Please input the diameter of the pizza: ") 10 area = 4*(math.pi)*(diameter/2)**2 11 print "The area of the pizza is %0.2f" % (area) 12 return area 13 14 15 def unitCost(): 16 price = input("Please input the cost of the pizza per square inch: ") 17 area = areaCirc() 18 cost = area * price 19 print "The cost of the pizza is %0.2f" %(cost) 20 21 unitCost() --------------------------- ____________________________________________________________________________________ Sponsored Link Compare mortgage rates for today. Get up to 5 free quotes. Www2.nextag.com From pyro9219 at gmail.com Fri Nov 17 20:06:29 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 17 Nov 2006 11:06:29 -0800 Subject: [Tutor] Problem making '.exe' from python. Message-ID: Whether using py2exe or pyInstaller I've noticed a problem and I'm not sure how to fix it... When I create a .exe and then make a shortcut to the file and run it.. the program will crash without warning. If I run the .exe directly it runs fine. My assumption of the problem: Since it is still built on python and my variables for files or module calls are designed for "they are in the same location I run the script from" when I run the script from a shortcut it will fail finding the wanted pieces. Is this true? And if so, how do I fix it? I could write fixed paths into my code, but that is unrealistic and makes running my scripts to test them a pain. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/b327d991/attachment-0001.html From jason.massey at gmail.com Fri Nov 17 20:19:11 2006 From: jason.massey at gmail.com (Jason Massey) Date: Fri, 17 Nov 2006 13:19:11 -0600 Subject: [Tutor] Problem making '.exe' from python. In-Reply-To: References: Message-ID: <7e3eab2c0611171119y5224766bj17a40867d450674a@mail.gmail.com> Check to make sure that under the shortcut properties that you have the "Start in" field filled out with the directory the script is located. On 11/17/06, Chris Hengge wrote: > > Whether using py2exe or pyInstaller I've noticed a problem and I'm not > sure how to fix it... > > When I create a .exe and then make a shortcut to the file and run it.. the > program will crash without warning. > If I run the .exe directly it runs fine. > > My assumption of the problem: > Since it is still built on python and my variables for files or module > calls are designed for "they are in the same location I run the script from" > when I run the script from a shortcut it will fail finding the wanted > pieces. > > Is this true? And if so, how do I fix it? I could write fixed paths into > my code, but that is unrealistic and makes running my scripts to test them a > pain. > > Thanks. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/8c5769b6/attachment.html From ke7fxl at gmail.com Fri Nov 17 20:52:06 2006 From: ke7fxl at gmail.com (Tod Haren) Date: Fri, 17 Nov 2006 11:52:06 -0800 Subject: [Tutor] str() conversion of unicode? Message-ID: <6f5b2c4e0611171152h1b6721fcga18855863e90869c@mail.gmail.com> I'm trying to calculate md5's on records from a Paradox database. The problem is that apparently some of the records have non ASCII characters. I'm at a loss as to how I should handle this. This snippet is called for each row in my recordset: m = md5.new() for f in rs.fields.keys(): val = str(rs.fields[f].value) m.update(val) m = m.hexdigest() the str() convertion throws this error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in position 1: ordinal not in range(128) print u'\xbd' renders the '1/2' symbol. I would eliminate the str() but md5 barks when you pass anything but a string apparently. Is there another way to coerce the field values to a string? From Senthil_OR at Dell.com Fri Nov 17 21:04:06 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Sat, 18 Nov 2006 01:34:06 +0530 Subject: [Tutor] OT: Vim was: free IDE for Python? In-Reply-To: <20061117171722.GA16549@sillyrabbi.dyndns.org> Message-ID: William O'Higgins Witteman wrote: > On Fri, Nov 17, 2006 at 11:02:18AM +0530, Senthil_OR at Dell.com wrote: > >> What the settings of ppl using vim for python? > > A few Python-specific things that I have in my .vimrc are as follows: Thanks for sharing William. I think ppl in this list , might also be interested in this _vimrc ( I am on windows) snippet, which on pressing Alt+D over a module name will take us to its documentation. function! OnlineDoc() if &ft =~ "python" let s:urlTemplate = "http://docs.python.org/lib/module-%.html" else return endif let s:browser = "\"C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE\"" let s:wordUnderCursor = expand("") let s:url = substitute(s:urlTemplate, "%", s:wordUnderCursor, "g") let s:cmd = "silent !start " . s:browser . " " . s:url execute s:cmd endfunction " online doc search map :call OnlineDoc() - It is written with modifications from vim tips page. Thanks, -- Senthil From pyro9219 at gmail.com Fri Nov 17 21:12:19 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 17 Nov 2006 12:12:19 -0800 Subject: [Tutor] Problem making '.exe' from python. In-Reply-To: <7e3eab2c0611171119y5224766bj17a40867d450674a@mail.gmail.com> References: <7e3eab2c0611171119y5224766bj17a40867d450674a@mail.gmail.com> Message-ID: Awesome! Thank you! This has been driving me crazy for weeks. Now to figure out how to tell Inno to add that to a link, and I'm on my way! On 11/17/06, Jason Massey wrote: > > Check to make sure that under the shortcut properties that you have the > "Start in" field filled out with the directory the script is located. > > On 11/17/06, Chris Hengge wrote: > > > Whether using py2exe or pyInstaller I've noticed a problem and I'm not > > sure how to fix it... > > > > When I create a .exe and then make a shortcut to the file and run it.. > > the program will crash without warning. > > If I run the .exe directly it runs fine. > > > > My assumption of the problem: > > Since it is still built on python and my variables for files or module > > calls are designed for "they are in the same location I run the script from" > > when I run the script from a shortcut it will fail finding the wanted > > pieces. > > > > Is this true? And if so, how do I fix it? I could write fixed paths into > > my code, but that is unrealistic and makes running my scripts to test them a > > pain. > > > > Thanks. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/883d54d4/attachment.html From bgailer at alum.rpi.edu Fri Nov 17 21:14:28 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 17 Nov 2006 12:14:28 -0800 Subject: [Tutor] a question about passing values between functions In-Reply-To: <511243.25365.qm@web33508.mail.mud.yahoo.com> References: <511243.25365.qm@web33508.mail.mud.yahoo.com> Message-ID: <455E1824.6080401@alum.rpi.edu> kristinn didriksson wrote: > Hello, > I am still wrestling with the concept of values going > between functions. (just starting out)The program > below works seems to work, but here is my question. > In my understanding, return area in the first routine > makes the value of area an instance of areaCirc area = 4*( ... is what makes area a local variable (not instance). Assignment to a name in a function where the name has not been declared global makes that name local to the function. > use areaCirc in the other program to call the value > for the area that was calculated in the first routine. > Is that the right way to think of this program? Did I > use return area correctly? > Yes. > This is a new vocabulary, so I hope I am making sense. > Basically, I am wondering if I needed to use the > return area statement. > Thanks, > Kristinn > > --------------- > # this program is a redo of ex2 ch3 with a > twist! > 2 # use two functions--one to compute the area > of a pizza, and one to > 3 # to compute cost per square inch. > 4 # Given are the diameter and the price. A = > pi(r**2) > 5 > 6 # define the function that computes the area > 7 import math > 8 def areaCirc(): > 9 diameter = input("Please input the > diameter of the pizza: ") > 10 area = 4*(math.pi)*(diameter/2)**2 > 11 print "The area of the pizza is %0.2f" % > (area) > 12 return area > 13 > 14 > 15 def unitCost(): > 16 price = input("Please input the cost of > the pizza per square inch: ") > 17 area = areaCirc() > 18 cost = area * price > 19 print "The cost of the pizza is %0.2f" > %(cost) > 20 > 21 unitCost() > --------------------------- If I were working this assignment I'd structure it thus: get the diameter get the cost per square inch call a function to compute the area call a function to compute the cost -- Bob Gailer 510-978-4454 From pyro9219 at gmail.com Fri Nov 17 22:32:37 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 17 Nov 2006 13:32:37 -0800 Subject: [Tutor] Problem making '.exe' from python. In-Reply-To: References: <7e3eab2c0611171119y5224766bj17a40867d450674a@mail.gmail.com> Message-ID: Just wanted to wrap that up so nobody wastes time replying. I've fixed my Inno scripts and all my packages work now, case closed! Thanks again Jason. On 11/17/06, Chris Hengge wrote: > > Awesome! Thank you! > > This has been driving me crazy for weeks. > Now to figure out how to tell Inno to add that to a link, and I'm on my > way! > > On 11/17/06, Jason Massey wrote: > > > > Check to make sure that under the shortcut properties that you have the > > "Start in" field filled out with the directory the script is located. > > > > On 11/17/06, Chris Hengge wrote: > > > > > Whether using py2exe or pyInstaller I've noticed a problem and I'm > > > not sure how to fix it... > > > > > > When I create a .exe and then make a shortcut to the file and run it.. > > > the program will crash without warning. > > > If I run the .exe directly it runs fine. > > > > > > My assumption of the problem: > > > Since it is still built on python and my variables for files or module > > > calls are designed for "they are in the same location I run the script from" > > > when I run the script from a shortcut it will fail finding the wanted > > > pieces. > > > > > > Is this true? And if so, how do I fix it? I could write fixed paths > > > into my code, but that is unrealistic and makes running my scripts to test > > > them a pain. > > > > > > Thanks. > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/d7792e30/attachment.htm From singingxduck at gmail.com Fri Nov 17 23:52:52 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Fri, 17 Nov 2006 17:52:52 -0500 Subject: [Tutor] any win32com experts out there? Message-ID: <455E3D44.8030000@gmail.com> Hello again. As I've mentioned in the last couple of emails, I'm having trouble registering iTunes for events, and I don't know if it's a bug with iTunes or with win32com, or if there's something I'm doing wrong. So, if any win32com gurus out there know why the following doesn't work and how to change it so it does work, a tip would be much appreciated. >>> import win32com.client >>> class iTunesEvents: def __init__(self): print "starting iTunesEvents" def OnPlayerPlayEvent(self, track): print "playing" def OnPlayerStopEvent(self, track): print "stopped" def OnDatabaseChangedEvent(self, deleted, changed): print "database changed" def OnPlayerPlayingTrackChangedEvent(self, track): print "info on current track changed" def OnCOMCallsDisabledEvent(self, reason): print "com calls disabled" def OnCOMCallsEnabledEvent(self): print "com calls enabled" def OnQuittingEvent(self): print "quitting" def OnAboutToPromptUserToQuitEvent(self): print "prompting user to quit" def OnSoundVolumeChangedEvent(self, newvolume): print "volume changed" >>> iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application") >>> iTEvents = win32com.client.WithEvents(iTunes, iTunesEvents) starting iTunesEvents >>> iTunes.Play() >>> iTunes.Pause() >>> iTunes.Play() >>> iTunes.Pause() iTunes did, in fact, play and pause as expected, but as can be seen, no events were caught. Stumped, Orri From alan.gauld at btinternet.com Fri Nov 17 23:57:12 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Nov 2006 22:57:12 -0000 Subject: [Tutor] a question about passing values between functions References: <511243.25365.qm@web33508.mail.mud.yahoo.com> Message-ID: "kristinn didriksson" wrote > In my understanding, return area in the first routine > makes the value of area an instance of areaCirc No, it simply assigns the value returned by areaCirc to area within XXXX. areaCirc assigns 4*(math.pi)*(diameter/2)**2 to its local variable area then returns area. So in effect the assignment line inside XXX could simply be rewritten: area = 4*(math.pi)*(diameter/2)**2 > Is that the right way to think of this program? Did I > use return area correctly? You used return area correctly but are getting confused between objects and instances and functions. functions (as defined with a def keyword) return values, which may be instances of classes or builtin objects Classes return instances of themselves. But the syntax in both cases is thesame which is, admittedly, confusing. > Basically, I am wondering if I needed to use the > return area statement. Yes, that is how to pass data out of one function to another part of the program. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > --------------- > # this program is a redo of ex2 ch3 with a > twist! > 2 # use two functions--one to compute the area > of a pizza, and one to > 3 # to compute cost per square inch. > 4 # Given are the diameter and the price. A = > pi(r**2) > 5 > 6 # define the function that computes the area > 7 import math > 8 def areaCirc(): > 9 diameter = input("Please input the > diameter of the pizza: ") > 10 area = 4*(math.pi)*(diameter/2)**2 > 11 print "The area of the pizza is %0.2f" % > (area) > 12 return area > 13 > 14 > 15 def unitCost(): > 16 price = input("Please input the cost of > the pizza per square inch: ") > 17 area = areaCirc() > 18 cost = area * price > 19 print "The cost of the pizza is %0.2f" > %(cost) > 20 > 21 unitCost() > --------------------------- > > > > ____________________________________________________________________________________ > Sponsored Link > > Compare mortgage rates for today. > Get up to 5 free quotes. > Www2.nextag.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tavspam at gmail.com Sat Nov 18 02:03:38 2006 From: tavspam at gmail.com (Thomas) Date: Sat, 18 Nov 2006 01:03:38 +0000 Subject: [Tutor] A Million Sevens Message-ID: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> Earlier today I typed the following into my pythonwin interactive interpreter in windows xp: >>> int('7' * 10 ** 6) I expected either an error message or it to get stuck and require me to stop the process manually. I read that unlike long integers in C, longs in python are only limited by the amount of memory (and virtual memory) your system has. Can you guess what it did? I'm temped to end the post here, but I'm new to this list and its possible that people might be annoyed by me not getting to the point within my initial post, so here's what it did: It thought about it for about 2 seconds then restarted my pc! explanations welcome. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061118/5ffc48d6/attachment.htm From pyro9219 at gmail.com Sat Nov 18 02:14:51 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 17 Nov 2006 17:14:51 -0800 Subject: [Tutor] A Million Sevens In-Reply-To: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> Message-ID: Well, I dont get the point.. its not locking up my system or anything.. its just crunching away... even while I type this... I guess your point is that it should stop since a 32 bit O/S can only count to: 4,294,967,296 On 11/17/06, Thomas wrote: > > Earlier today I typed the following into my pythonwin interactive > interpreter in windows xp: > > >>> int('7' * 10 ** 6) > > I expected either an error message or it to get stuck and require me to > stop the process manually. > > I read that unlike long integers in C, longs in python are only limited > by the amount of memory (and virtual memory) your system has. > > Can you guess what it did? > > I'm temped to end the post here, but I'm new to this list and its possible > that people might be annoyed by me not getting to the point within my > initial post, so here's what it did: > > It thought about it for about 2 seconds then restarted my pc! explanations > welcome. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/adfd6fe2/attachment.html From pyro9219 at gmail.com Sat Nov 18 02:16:23 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 17 Nov 2006 17:16:23 -0800 Subject: [Tutor] A Million Sevens In-Reply-To: References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> Message-ID: I'm thinking you either have a problem with a memory leak (my memory isn't changing, just at 100% CPU), or your CPU overheated from poor cooling since it is at 100% utilization. On 11/17/06, Chris Hengge wrote: > > Well, I dont get the point.. its not locking up my system or anything.. > its just crunching away... even while I type this... > I guess your point is that it should stop since a 32 bit O/S can only > count to: > 4,294,967,296 > > On 11/17/06, Thomas wrote: > > > Earlier today I typed the following into my pythonwin interactive > > interpreter in windows xp: > > > > >>> int('7' * 10 ** 6) > > > > I expected either an error message or it to get stuck and require me to > > stop the process manually. > > > > I read that unlike long integers in C, longs in python are only limited > > by the amount of memory (and virtual memory) your system has. > > > > Can you guess what it did? > > > > I'm temped to end the post here, but I'm new to this list and its > > possible that people might be annoyed by me not getting to the point within > > my initial post, so here's what it did: > > > > It thought about it for about 2 seconds then restarted my pc! > > explanations welcome. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/9ef46c58/attachment.htm From rabidpoobear at gmail.com Sat Nov 18 02:23:56 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 17 Nov 2006 19:23:56 -0600 Subject: [Tutor] A Million Sevens In-Reply-To: References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> Message-ID: <455E60AC.10900@gmail.com> Chris Hengge wrote: > I'm thinking you either have a problem with a memory leak (my memory > isn't changing, just at 100% CPU), or your CPU overheated from poor > cooling since it is at 100% utilization. yeah I second this... there's no reason why this would reboot your computer. At Chris: It's building a string that's 1,000,000 characters long, so it should be increasing your memory usage by at least 1,000,000 characters, or 1 mb. But that's over a probably long period of time, so you just didn't notice any change. > > On 11/17/06, *Chris Hengge* > wrote: > > Well, I dont get the point.. its not locking up my system or > anything.. its just crunching away... even while I type this... > I guess your point is that it should stop since a 32 bit O/S can > only count to: > 4,294,967,296 > > On 11/17/06, *Thomas* < tavspam at gmail.com > > wrote: > > Earlier today I typed the following into my pythonwin > interactive interpreter in windows xp: > > >>> int('7' * 10 ** 6) > > I expected either an error message or it to get stuck and > require me to stop the process manually. > > I read that unlike long integers in C, longs in python are > only limited by the amount of memory (and virtual memory) your > system has. > > Can you guess what it did? > > I'm temped to end the post here, but I'm new to this list and > its possible that people might be annoyed by me not getting to > the point within my initial post, so here's what it did: > > It thought about it for about 2 seconds then restarted my pc! > explanations welcome. > From hockeyc at umich.edu Sat Nov 18 02:14:43 2006 From: hockeyc at umich.edu (Collin Hockey) Date: Fri, 17 Nov 2006 20:14:43 -0500 Subject: [Tutor] A Million Sevens In-Reply-To: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> Message-ID: <455E5E83.7050208@umich.edu> A mildly educated guess would be that python tried to access memory Windows wasn't going to allow it to have, effectively causing a BSOD and making Windows restart the system. Thomas wrote: > Earlier today I typed the following into my pythonwin interactive > interpreter in windows xp: > > >>> int('7' * 10 ** 6) > > I expected either an error message or it to get stuck and require me to > stop the process manually. > > I read that unlike long integers in C, longs in python are only limited > by the amount of memory (and virtual memory) your system has. > > Can you guess what it did? > > I'm temped to end the post here, but I'm new to this list and its > possible that people might be annoyed by me not getting to the point > within my initial post, so here's what it did: > > It thought about it for about 2 seconds then restarted my pc! > explanations welcome. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From tim.peters at gmail.com Sat Nov 18 02:33:01 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 17 Nov 2006 20:33:01 -0500 Subject: [Tutor] A Million Sevens In-Reply-To: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> Message-ID: <1f7befae0611171733p3ad47ebesb96924711abe7349@mail.gmail.com> [Thomas] > Earlier today I typed the following into my pythonwin interactive > interpreter in windows xp: > > >>> int('7' * 10 ** 6) > > I expected either an error message Unlikely, if your box has enough RAM to run WinXP :-) > or it to get stuck and require me to stop the process manually. Not that either, but it will take a long time. There are two quadratic-time base conversions going on here, one to convert the million-digit decimal string to a large binary integer, and then again in the other direction to display the result as a decimal string. In all, using Python 2.4.3 from a "DOS box" shell under WinXP on a pretty fast box, this consumed about 16 minutes of CPU time, and process memory use peaked at a relatively measly 11.3 MB. > I read that unlike long integers in C, longs in python are only limited by > the amount of memory (and virtual memory) your system has. That's right. > Can you guess what it did? Nope. > I'm temped to end the post here, but I'm new to this list and its possible > that people might be annoyed by me not getting to the point within my > initial post, /Very/ good guess :-) > so here's what it did: > > It thought about it for about 2 seconds then restarted my pc! explanations > welcome. Don't have one: as above, it worked fine when I tried it. I wasn't using PythonWin, although hard to guess why that would matter. I wouldn't be surprised to see a GUI shell die a horrid death of some kind when asked to display a million-character string, but 2 seconds is far too short a time for your attempt to have gotten that far. If you want to play, break it into two steps: >>> i = int('7' * 10 ** 6) That much does /only/ the decimal-string -> large binary integer part. Don't display i until the next step. For display, it's /enormously/ faster to convert to a power-of-2 output base (instead of to decimal), like >>> print hex(i) In more detail, >>> from time import clock as now >>> from math import log10 >>> log10(i) 999999.89085553051 >>> t = now(); ashex = hex(i); now() - t 0.0097427830685340843 That is, converting the big binary integer to a hex string took less than a hundreth of a second, instead of the minutes required to convert to a decimal string. >>> len(ashex) 830485 From alan.gauld at btinternet.com Sat Nov 18 02:40:09 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Nov 2006 01:40:09 -0000 Subject: [Tutor] any win32com experts out there? References: <455E3D44.8030000@gmail.com> Message-ID: I'm no expert but I get the same response when I tried it. I googled a bit and found this long chain of useful looking stuff: http://www.velocityreviews.com/forums/t345123-how-to-receive-events-eg-user-mouse-clicks-from-ie.html One possibility mentioned at the end is: '''' Adding win32gui.PumpWaitingMessages() to the wait loop seems to allow both event hooks to run without blocking each other. '''' But it discusses IE not iTunes so it may not be relevant... Alan G. "Orri Ganel" wrote in message news:455E3D44.8030000 at gmail.com... > Hello again. As I've mentioned in the last couple of emails, I'm > having > trouble registering iTunes for events, and I don't know if it's a > bug > with iTunes or with win32com, or if there's something I'm doing > wrong. > So, if any win32com gurus out there know why the following doesn't > work > and how to change it so it does work, a tip would be much > appreciated. > > >>> import win32com.client > >>> class iTunesEvents: > def __init__(self): > print "starting iTunesEvents" > def OnPlayerPlayEvent(self, track): > print "playing" > def OnPlayerStopEvent(self, track): > print "stopped" > def OnDatabaseChangedEvent(self, deleted, changed): > print "database changed" > def OnPlayerPlayingTrackChangedEvent(self, track): > print "info on current track changed" > def OnCOMCallsDisabledEvent(self, reason): > print "com calls disabled" > def OnCOMCallsEnabledEvent(self): > print "com calls enabled" > def OnQuittingEvent(self): > print "quitting" > def OnAboutToPromptUserToQuitEvent(self): > print "prompting user to quit" > def OnSoundVolumeChangedEvent(self, newvolume): > print "volume changed" > > > >>> iTunes = > >>> win32com.client.gencache.EnsureDispatch("iTunes.Application") > >>> iTEvents = win32com.client.WithEvents(iTunes, iTunesEvents) > starting iTunesEvents > >>> iTunes.Play() > >>> iTunes.Pause() > >>> iTunes.Play() > >>> iTunes.Pause() > > iTunes did, in fact, play and pause as expected, but as can be seen, > no > events were caught. > > Stumped, > Orri > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pyro9219 at gmail.com Sat Nov 18 02:47:03 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 17 Nov 2006 17:47:03 -0800 Subject: [Tutor] A Million Sevens In-Reply-To: <455E60AC.10900@gmail.com> References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> <455E60AC.10900@gmail.com> Message-ID: Not that it changes your reply, but just for my own sanity: int('7' * 10 ** 6) <- does this not just type-cast a char into an int? Meaning that rather then consuming 1024k as you stated, it would consume 2048k at the peak of the calculation(2bytes per char? * 1m = 2048k) then typecasting to int would drop it back down to 1k (1byte per int * 1m = 1024k So, just for sake of getting to a point since I missed the one by the original poster.. why would you not convert that 7 from a char to an int first? That calculation is almost instant, and it doesn't require the memory rollercoaster that this calculation would require.. Anyways.. back to the poster... Perhaps you wanted an error like this? print '=' * 1000000000 Traceback (most recent call last): File "", line 1, in ? MemoryError On 11/17/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I'm thinking you either have a problem with a memory leak (my memory > > isn't changing, just at 100% CPU), or your CPU overheated from poor > > cooling since it is at 100% utilization. > yeah I second this... > there's no reason why this would reboot your computer. > At Chris: It's building a string that's 1,000,000 characters long, so it > should be increasing your memory usage by at least 1,000,000 characters, > or 1 mb. But that's over a probably long period of time, so you just > didn't notice any change. > > > > On 11/17/06, *Chris Hengge* > > wrote: > > > > Well, I dont get the point.. its not locking up my system or > > anything.. its just crunching away... even while I type this... > > I guess your point is that it should stop since a 32 bit O/S can > > only count to: > > 4,294,967,296 > > > > On 11/17/06, *Thomas* < tavspam at gmail.com > > > wrote: > > > > Earlier today I typed the following into my pythonwin > > interactive interpreter in windows xp: > > > > >>> int('7' * 10 ** 6) > > > > I expected either an error message or it to get stuck and > > require me to stop the process manually. > > > > I read that unlike long integers in C, longs in python are > > only limited by the amount of memory (and virtual memory) your > > system has. > > > > Can you guess what it did? > > > > I'm temped to end the post here, but I'm new to this list and > > its possible that people might be annoyed by me not getting to > > the point within my initial post, so here's what it did: > > > > It thought about it for about 2 seconds then restarted my pc! > > explanations welcome. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061117/499f5106/attachment.html From alan.gauld at btinternet.com Sat Nov 18 02:52:43 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Nov 2006 01:52:43 -0000 Subject: [Tutor] A Million Sevens References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> <1f7befae0611171733p3ad47ebesb96924711abe7349@mail.gmail.com> Message-ID: Tim, Every now and then you pop up on the tutor list to answer "interesting" posts like this: "Tim Peters" wrote > That much does /only/ the decimal-string -> large binary integer > part. > Don't display i until the next step. For display, it's /enormously/ > faster to convert to a power-of-2 output base (instead of to > decimal), > like > >>>> print hex(i) But given the number of other groups you contribute to, I can't believe you have time to read all of them, so how do you filter out the interesting ones? Yours Curiously, Alan G. From tavspam at gmail.com Sat Nov 18 03:38:25 2006 From: tavspam at gmail.com (Thomas) Date: Sat, 18 Nov 2006 02:38:25 +0000 Subject: [Tutor] A Million Sevens In-Reply-To: References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> <455E60AC.10900@gmail.com> Message-ID: <493b81e30611171838q69b9f5afy5fd2a3fcb7a2973e@mail.gmail.com> On 18/11/06, Chris Hengge wrote: > Not that it changes your reply, but just for my own sanity: > int('7' * 10 ** 6) <- does this not just type-cast a char into an int? > > Meaning that rather then consuming 1024k as you stated, it would consume 2048k at the peak of the calculation(2bytes per char? * 1m = 2048k) then typecasting to int would drop it back down to 1k (1byte per int * 1m = 1024k > > So, just for sake of getting to a point since I missed the one by the original poster.. why would you not convert that 7 from a char to an int first? That calculation is almost instant, and it doesn't require the memory rollercoaster that this calculation would require.. > > Anyways.. back to the poster... Thanks, original poster here, I was just reading my new book, Core Python Programming (2nd Edition) and it said that there was no in-built limit to the size of a long in python (as compared to C) so I wanted to test it out. I just typed the first way of getting a massive number that came into my head. > Perhaps you wanted an error like this? > > print '=' * 1000000000 > Traceback (most recent call last): > File "", line 1, in ? > MemoryError Now that is exactly what I thought I might get. I'll try it again with some of the variations mentioned on Monday when I get back to that computer. From rabidpoobear at gmail.com Sat Nov 18 03:39:27 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 17 Nov 2006 20:39:27 -0600 Subject: [Tutor] A Million Sevens In-Reply-To: References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> <455E60AC.10900@gmail.com> Message-ID: <455E725F.70503@gmail.com> Chris Hengge wrote: > Not that it changes your reply, but just for my own sanity: > int('7' * 10 ** 6) <- does this not just type-cast a char into an int? it typecasts a 1,000,000 character long string to an integer. > > Meaning that rather then consuming 1024k as you stated, it would > consume 2048k at the peak of the calculation(2bytes per char? * 1m = > 2048k) um, I'm not sure how you came up with these numbers. Obviously there are other considerations here besides the amount of memory required to store the data (like the memory used by the string class, and the fact that strings are probably stored as a linked list, so 1 byte for the char, and 4 bytes for the char pointer). If you just considered the characters, they're only 1 byte, not 2, assuming you're using regular ascii characters (0x00 - 0xff is 255 unique bit strings, and since english and other latin-based languages only need 26*2 (lower + uppercase letters) + 10 for numbers, and various other symbols, 255 is plenty.), so it'd be 1024k of memory usage. if you considered the pointers also, it'd be 5116k. and various other things raise this memory usage more. >then typecasting to int would drop it back down to 1k (1byte per int * 1m = 1024k no, typecasting it to int won't drop it to 1k. What's happening is that, inside the function call (the 'int' type conversion) a 7-million character string, i.e. '77777777777777777777777777............7' is generated, and then the 'int()' call converts it to the equivalent integer, 777777777777777777777777.......7 Not to a million different 7 integers. Do you see this? It's only one number. and I don't know where you got 1 byte per int. Even if they were 1,000,000 individual sevens, the C library reserves the same amount of memory for an int no matter what size it is, so even though 7 is a low number, there'd still be 4 bytes of usage per int (depending on the implementation) Depending on how exactly Python stores long ints, it should use substantially less memory than the equivalent character string would. Recall that a 2 byte unsigned integer can hold all numbers less than 2**16 (65536), a 4 byte (the default long-int size) unsigned integer can hold all numbers less than 2**32 (4294967296) which is ten decimal digits long. So you see that the memory usage of the python long integer is going to be much smaller than the usage of the character string that represents it. The string's size usage grows linearly with the data it represents ('7' will take x memory, '77' will take x*2 memory, '777' will take x*3 memory) while the size of the integer grows much faster than the memory usage memory usage (0-256 takes 1 byte, 0-65536 takes 2 bytes, 0-16777216 takes 3 bytes, 0-4294967296 takes 4 bytes, any number less than 308 digits long takes 128 bytes) > > So, just for sake of getting to a point since I missed the one by the > original poster.. why would you not convert that 7 from a char to an > int first? That calculation is almost instant, and it doesn't require > the memory rollercoaster that this calculation would require.. Because, that's not what's happening. He's not converting 1,000,000 '7' chars to the integer 7, he's converting a string of 1,000,000 7s into an integer with 1,000,000 digits, all of which are 7. Consider this example: >>> '7' * 5 '77777' You see, it's a string of length 5 with the contents just the original character, '7', repeating. You can do something similar with a string rather than a character, >>> 'hello' * 3 'hellohellohello' Now consider this: >>> '7' * 2 ** 5 '77777777777777777777777777777777' In the order of operations for Python, exponents come before multiplications, so this is equivalent to '7' * 32 as evidenced by: >>> len('7' * 2 ** 5) 32 Hope that helps and makes sense, -Luke > > Anyways.. back to the poster... > > Perhaps you wanted an error like this? > > print '=' * 1000000000 > Traceback (most recent call last): > File "", line 1, in ? > MemoryError > > > On 11/17/06, *Luke Paireepinart* > wrote: > > Chris Hengge wrote: > > I'm thinking you either have a problem with a memory leak (my memory > > isn't changing, just at 100% CPU), or your CPU overheated from poor > > cooling since it is at 100% utilization. > yeah I second this... > there's no reason why this would reboot your computer. > At Chris: It's building a string that's 1,000,000 characters long, > so it > should be increasing your memory usage by at least 1,000,000 > characters, > or 1 mb. But that's over a probably long period of time, so you just > didn't notice any change. > > > > On 11/17/06, *Chris Hengge* > > >> wrote: > > > > Well, I dont get the point.. its not locking up my system or > > anything.. its just crunching away... even while I type this... > > I guess your point is that it should stop since a 32 bit O/S can > > only count to: > > 4,294,967,296 > > > > On 11/17/06, *Thomas* < tavspam at gmail.com > > > >> wrote: > > > > Earlier today I typed the following into my pythonwin > > interactive interpreter in windows xp: > > > > >>> int('7' * 10 ** 6) > > > > I expected either an error message or it to get stuck and > > require me to stop the process manually. > > > > I read that unlike long integers in C, longs in python are > > only limited by the amount of memory (and virtual > memory) your > > system has. > > > > Can you guess what it did? > > > > I'm temped to end the post here, but I'm new to this > list and > > its possible that people might be annoyed by me not > getting to > > the point within my initial post, so here's what it did: > > > > It thought about it for about 2 seconds then restarted > my pc! > > explanations welcome. > > > > From alan.gauld at btinternet.com Sat Nov 18 10:49:53 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Nov 2006 09:49:53 -0000 Subject: [Tutor] A Million Sevens References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com><455E60AC.10900@gmail.com> Message-ID: "Chris Hengge" wrote > Not that it changes your reply, but just for my own sanity: > int('7' * 10 ** 6) <- does this not just type-cast a char into an > int? Chris, I suspect you may come from a C background? Type *conversion* in Python is very differentb from type *casting* in C. type casting says take the binary data stored at x and treat it as a different type, thats pretty well instantaneous. typecasting (int)'77' in C will not give you the number 77(decimal) but will give you the hex value 0x3737 which is entirely different (actually 14135!). Now typecasting in C++ is somewhat different, especially if you use dynamic casts and that can involve converting the type rather than just treating the existing data differently... Because of this confusion over the word cast I prefer to refer to Python as doing type conversions. Type conversion says take the data entity in variable x and change its internal structure to the representation of a new type. Thats a much more complex operation. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Sat Nov 18 12:07:29 2006 From: pythontut at pusspaws.net (Dave S) Date: Sat, 18 Nov 2006 11:07:29 +0000 Subject: [Tutor] exception not raised XP file ? Message-ID: <200611181107.29627.pythontut@pusspaws.net> Due to some sloppy programming on a commercial app :) I have a problem. I have some directories on an XP machine, I need to know which of these directories (*.cab_tmp) contains a file that that is being accessed by another XP program. I set it up so that a known file (SIZES.DBF) in a known directory is being accessed by said program. If I attempt to open said file with wordpad I get the error 'the document ...SIZES.DBF... is being used by another application and cannot be accessed !' So I wrote the following code posDirNames = filter((lambda x: x[-7:] == 'cab_tmp'), os.listdir(gsrpath)) for dirName in posDirNames: print dirName for fileName in os.listdir(gsrpath + '/' + dirName): try: file = gsrpath + '/' + dirName + '/' + fileName if fileName == 'SIZES.DBF': print file, f = open(file, 'w') f.close() except: print 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', print fileName, sys.exc_info() Expecting it to raise an exception when it hits SIZES.DBF because I am opening the file to write - no exception is raised. I know it is scanning SIZES.DBF because my if statement picks it up. Any ideas ? Dave From ajkadri at googlemail.com Sat Nov 18 14:13:59 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 18 Nov 2006 13:13:59 +0000 Subject: [Tutor] A question about: Adding seconds to datetime object Message-ID: Hi , I have a question: Is it possible to add seconds to a datetime object and get the result as a new datetime object. I mean when we keep adding, for example, 3600 seconds, the date will get changed after 24 iterations. Is it possible to carry out such an operation ? TIA. Best Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061118/8a13e1d8/attachment.htm From kent37 at tds.net Sat Nov 18 15:48:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Nov 2006 09:48:27 -0500 Subject: [Tutor] A question about: Adding seconds to datetime object In-Reply-To: References: Message-ID: <455F1D3B.2040501@tds.net> Asrarahmed Kadri wrote: > Hi , > > > I have a question: > > Is it possible to add seconds to a datetime object and get the result as > a new datetime object. I mean when we keep adding, for example, 3600 > seconds, the date will get changed after 24 iterations. Is it possible > to carry out such an operation ? Sure, just add a datetime.timedelta to the datetime object: In [1]: from datetime import datetime, timedelta In [2]: d=datetime.now() In [3]: d Out[3]: datetime.datetime(2006, 11, 18, 9, 47, 31, 187000) In [4]: delta=timedelta(seconds=3600) In [5]: d+delta Out[5]: datetime.datetime(2006, 11, 18, 10, 47, 31, 187000) Kent From chris.lasher at gmail.com Sat Nov 18 16:00:54 2006 From: chris.lasher at gmail.com (Chris Lasher) Date: Sat, 18 Nov 2006 10:00:54 -0500 Subject: [Tutor] OT: Vim was: free IDE for Python? In-Reply-To: <57B026980605A64F9B23484C5659E32E2A82F1@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E2A82F1@poccso.US.ad.atmel.com> Message-ID: <128a885f0611180700s6277b63u6ce9afbb3ab2dfe6@mail.gmail.com> On 11/17/06, Mike Hansen wrote: > > Here's what I'm doing. Not sure if it's that helpful to you. > > I use the mini-buffer explorer plug-in and the taglist plugin. > > set smartindent > > " shuts off the annoying "#" comment in smartindent to jump to col 1 > inoremap # X# > > autocmd BufRead *.py set smartindent > cinwords=if,elif,else,for,while,try,except,finally,def,class > Instead of using smartindent + cinwords + the inoremap hack, simply use "filetype indent on". This was recommended to me on #Vim IRC channel. This takes care of the silly # problem with smartindent and is considered the best way for getting proper indentation in Python. Give it a try! Chris From rschroev_nospam_ml at fastmail.fm Sat Nov 18 17:08:10 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 18 Nov 2006 17:08:10 +0100 Subject: [Tutor] exception not raised XP file ? In-Reply-To: <200611181107.29627.pythontut@pusspaws.net> References: <200611181107.29627.pythontut@pusspaws.net> Message-ID: Dave S schreef: > Due to some sloppy programming on a commercial app :) I have a problem. > > I have some directories on an XP machine, I need to know which of these > directories (*.cab_tmp) contains a file that that is being accessed by > another XP program. To me the easiest solution seems to be using Process Explorer or Handle from Sysinternals (at http://www.microsoft.com/technet/sysinternals currently). At first sight your Python solution looks good to me; I don't know why it doesn't work. Another approach I have used in the past is trying to rename the directory instead of trying to open a file in that directory: Windows cannot rename the directory when some program has a file open in that directory. At least that's my experience. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From pythontut at pusspaws.net Sat Nov 18 18:22:59 2006 From: pythontut at pusspaws.net (Dave S) Date: Sat, 18 Nov 2006 17:22:59 +0000 Subject: [Tutor] exception not raised XP file ? In-Reply-To: References: <200611181107.29627.pythontut@pusspaws.net> Message-ID: <200611181722.59504.pythontut@pusspaws.net> On Saturday 18 November 2006 16:08, Roel Schroeven wrote: > Dave S schreef: > > Due to some sloppy programming on a commercial app :) I have a problem. > > > > I have some directories on an XP machine, I need to know which of these > > directories (*.cab_tmp) contains a file that that is being accessed by > > another XP program. > > To me the easiest solution seems to be using Process Explorer or Handle > from Sysinternals (at http://www.microsoft.com/technet/sysinternals > currently). > > At first sight your Python solution looks good to me; I don't know why > it doesn't work. > > Another approach I have used in the past is trying to rename the > directory instead of trying to open a file in that directory: Windows > cannot rename the directory when some program has a file open in that > directory. At least that's my experience. Thanks for the tip :) Is it just me - I seem to run into a lot of weird behaviour in windows (but then I am a Linux Junky :) Dave From ajkadri at googlemail.com Sat Nov 18 18:24:24 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 18 Nov 2006 17:24:24 +0000 Subject: [Tutor] A question about: Adding seconds to datetime object In-Reply-To: <455F1D3B.2040501@tds.net> References: <455F1D3B.2040501@tds.net> Message-ID: Thanks. It means, you take a datetime object and then using a timedelta object, perform the addition, the language takes care of changing the date if the time crosses midnight. WOW... this makes life a lot easier.. Have a brilliant evening. Best Regards, Asrarahmed Kadri On 11/18/06, Kent Johnson wrote: > > Asrarahmed Kadri wrote: > > Hi , > > > > > > I have a question: > > > > Is it possible to add seconds to a datetime object and get the result as > > a new datetime object. I mean when we keep adding, for example, 3600 > > seconds, the date will get changed after 24 iterations. Is it possible > > to carry out such an operation ? > > Sure, just add a datetime.timedelta to the datetime object: > > In [1]: from datetime import datetime, timedelta > > In [2]: d=datetime.now() > > In [3]: d > Out[3]: datetime.datetime(2006, 11, 18, 9, 47, 31, 187000) > > In [4]: delta=timedelta(seconds=3600) > > In [5]: d+delta > Out[5]: datetime.datetime(2006, 11, 18, 10, 47, 31, 187000) > > Kent > > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061118/46a28a62/attachment.html From kentdeeg at comcast.net Sat Nov 18 19:36:49 2006 From: kentdeeg at comcast.net (Kent D. Grimsley) Date: Sat, 18 Nov 2006 11:36:49 -0700 Subject: [Tutor] (no subject) Message-ID: <003d01c70b40$88a585b0$6401a8c0@kent> I am new subscriber to python and now, I'm getting e-mail from all sorts of people having to do with questions I did not ask. Please take steps to remove my address from that list and take steps to help me get e-mail only from people answering my questions. I hope this is not an unreasonable request; if it is not, please advise. Kent Dee Grimsley kentdeeg at comcast.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061118/f23f968b/attachment.html From rabidpoobear at gmail.com Sat Nov 18 20:26:14 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 18 Nov 2006 13:26:14 -0600 Subject: [Tutor] (no subject) In-Reply-To: <003d01c70b40$88a585b0$6401a8c0@kent> References: <003d01c70b40$88a585b0$6401a8c0@kent> Message-ID: <455F5E56.10700@gmail.com> Kent D. Grimsley wrote: > I am new subscriber to python and now, I'm getting e-mail from all > sorts of people having to do with questions I did not ask. Please > take steps to remove my address from that list > and take steps to help me get e-mail only from people > answering my questions. I hope this is not an unreasonable request; > if it is not, please advise. The point of a mailing list is that everyone gets e-mails from everyone else. If I did not get e-mails from all the other people, how would I help them out? The same goes for you. The list doesn't try to determine who it is that wants help and who it is that is helping other people. It wouldn't be very helpful if everyone just got the e-mails of the questions they asked, would it? SO in other words, if it's bothering you, sign up for a digest, or unsubscribe. Hope that helps, -Luke > > Kent Dee Grimsley > kentdeeg at comcast.net > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Sun Nov 19 00:00:27 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 18 Nov 2006 17:00:27 -0600 Subject: [Tutor] (no subject) In-Reply-To: <000801c70b63$4b4db480$6401a8c0@kent> References: <003d01c70b40$88a585b0$6401a8c0@kent> <455F5E56.10700@gmail.com> <000801c70b63$4b4db480$6401a8c0@kent> Message-ID: <455F908B.9070506@gmail.com> Mr. Grimsley, I hope you don't mind if I forward this reply to the mailing list at large. I believe that some other people on the list can give you some guidance on your transition from FORTRAN to Python, and make it as enjoyable as possible. I, however, know nothing of FORTRAN, so I leave it up to other members to help you in this regard. If, in the future, you want to send a private reply, it would behoove you to notify the recipient that you'd like your communique to be confidential, because it's generally assumed that all replies should go to everyone, because then the largest audience of people who may benefit from your discussion are reached. If you mean to reply to the list, the 'reply-all' button serves this purpose quite well, and should be used unless it's necessary to reply privately. Thank you for your time, and I wish you the best of luck. -Luke Kent D. Grimsley wrote: > Mr. Luke; > > Thanks for your note in reply to my (unreasonable) request. I am > looking forward to being able to chat with someone about my newness to > Python. There is so much to absorb and digest. > > I must confess to being a long term Fortran programmer ( to the > present day) and it might take me a while to adjust to the Python > environment.. From what little dabbling in and around the Python > site, it milght be that Python is the way I COULD go to solve the > genealogical problem at hand. One obstacle to my perception is being > able to transform Fortran I/O to Python---which will not probably be > simple to do. The existence in Python of "IF THEN ELSE type > constructions, I think will be very helpful due to the similarity with > Fortran. The actual code transformation, for example from > DIMENSION to whatever the Python statement might be like, at the > moment, escapes me, as an example. > > I'm assuming that while the transformation from Fortran might not be > simple, it neveertheless can be done. > > Thanks, again, > Kent Dee Grimsley > kentdeeg at comcast.net From pyro9219 at gmail.com Sun Nov 19 00:44:00 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 18 Nov 2006 15:44:00 -0800 Subject: [Tutor] A Million Sevens In-Reply-To: References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> <455E60AC.10900@gmail.com> Message-ID: That must be part of Pythons shiny ability of dynamic data types? Must be a messy operation to change data-types like that.. I think I'll just do my best to work with the right data-types the whole time ;D On 11/18/06, Alan Gauld wrote: > > "Chris Hengge" wrote > > > Not that it changes your reply, but just for my own sanity: > > int('7' * 10 ** 6) <- does this not just type-cast a char into an > > int? > > Chris, I suspect you may come from a C background? > > Type *conversion* in Python is very differentb from > type *casting* in C. > > type casting says take the binary data stored at x and treat > it as a different type, thats pretty well instantaneous. > > typecasting (int)'77' in C will not give you the number > 77(decimal) but will give you the hex value 0x3737 > which is entirely different (actually 14135!). > > Now typecasting in C++ is somewhat different, especially > if you use dynamic casts and that can involve converting > the type rather than just treating the existing data differently... > Because of this confusion over the word cast I prefer > to refer to Python as doing type conversions. > > Type conversion says take the data entity in variable x > and change its internal structure to the representation > of a new type. Thats a much more complex operation. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061118/392dea58/attachment.html From rschroev_nospam_ml at fastmail.fm Sun Nov 19 01:09:23 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 19 Nov 2006 01:09:23 +0100 Subject: [Tutor] exception not raised XP file ? In-Reply-To: <200611181722.59504.pythontut@pusspaws.net> References: <200611181107.29627.pythontut@pusspaws.net> <200611181722.59504.pythontut@pusspaws.net> Message-ID: Dave S schreef: > Is it just me - I seem to run into a lot of weird behaviour in windows (but > then I am a Linux Junky :) It's not just you. I knew Windows long before I started to know and learn Linux, and before that I knew MS-DOS. But still I have a better understanding of the concepts, philosophy and inner workings of Linux (and Unix in general) than Windows. I think there are several reasons for that. One is that I think that Unix really is more logically designed. Another is that Unix is IMO better documented: even pretty basic user guides explain the basic concepts behind for instance processes and the file system. It's very hard, in my experience, to find a clear explanation on those concepts and the reasonings behind them in Windows. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From coen at reservoir.nl Sun Nov 19 01:39:25 2006 From: coen at reservoir.nl (Coen van der Kamp) Date: Sun, 19 Nov 2006 01:39:25 +0100 Subject: [Tutor] os.popen, xp Message-ID: <455FA7BD.6040603@reservoir.nl> Hello, I've got a problem with the following code: import os, sys, string mycolors = os.popen("coloryze --monochromatic --total=6 &").read().rstrip() print mycolors This works fine on OS X, but when i tried it on XP the only result was an empty string. When I run coloryze from the promt the return is a nice list of colors. So coloryze works. What am I missing here? Coen. From rabidpoobear at gmail.com Sun Nov 19 02:00:37 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 18 Nov 2006 19:00:37 -0600 Subject: [Tutor] os.popen, xp In-Reply-To: <455FA7BD.6040603@reservoir.nl> References: <455FA7BD.6040603@reservoir.nl> Message-ID: <455FACB5.5020303@gmail.com> Coen van der Kamp wrote: > Hello, > I've got a problem with the following code: > > import os, sys, string > mycolors = os.popen("coloryze --monochromatic --total=6 &").read().rstrip() > print mycolors > > This works fine on OS X, but when i tried it on XP the only result was > an empty string. When I run coloryze from the promt when you run it from which prompt? The OS X one or the XP one? > the return is a nice > list of colors. So coloryze works. What am I missing here? > > Coen. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Sun Nov 19 03:01:05 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Nov 2006 18:01:05 -0800 (PST) Subject: [Tutor] Re A question about: Adding seconds to datetime object In-Reply-To: References: Message-ID: > Is it possible to add seconds to a datetime object and get the result as > a new datetime object. I mean when we keep adding, for example, 3600 > seconds, the date will get changed after 24 iterations. Is it possible > to carry out such an operation ? Hi Asrarahmed, I want to add that you can find more information about this in the Library Documentation: http://www.python.org/doc/lib/module-datetime.html http://www.python.org/doc/lib/datetime-timedelta.html Try reading it and see if what the documentation says makes sense, after seeing Kent's examples. The idea is that it's good to practice reading and being able to cull out the useful stuff out of the reference documentation. From dyoo at hkn.eecs.berkeley.edu Sun Nov 19 03:08:43 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 18 Nov 2006 18:08:43 -0800 (PST) Subject: [Tutor] Changing mailing list options In-Reply-To: References: Message-ID: > I am new subscriber to python and now, I'm getting e-mail from all sorts > of people having to do with questions I did not ask. Please take steps > to remove my address from that list and take steps to help me get e-mail > only from people answering my questions. I hope this is not an > unreasonable request; if it is not, please advise. Hi Kent, There's a mailing list option that you can turn off that disables message delivery. You will still be able to post to the mailing list, but you will not receive direct traffic from the mailing list. (Note to others: this is exactly why Reply-To-All is a good idea.) Please visit: http://mail.python.org/mailman/listinfo/tutor and go down to the bottom of the page where it says "To unsubscribe from Tutor, get a password reminder, or change your subscription options enter your subscription email address." Fill in your address at the form below, and you should be able to navigate to change your subscription options from that point on. If you have problems doing this, contact the mailing list administrators at 'tutor-owner at python.org', and we will be happy to make the changes for you. That being said, you may learn a few things from listening to the general chatter on the list. It's a bit busy these days, but I think there's still worthwhile conversation. There is a "digest mode" option that bundles up messages from python-tutor so that it's easier to manage. Good luck to you. From rschroev_nospam_ml at fastmail.fm Sun Nov 19 10:33:37 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 19 Nov 2006 10:33:37 +0100 Subject: [Tutor] Rotating an array? Message-ID: <456024F1.8020400@fastmail.fm> Antonio Rodriguez schreef: > I'm trying to modify some programs I've done in Java to better > understand Python. One problem I'm encountering here is Python's lack of > explicit arrays. > > Take a square array (n x n) of Java ints, only containing 0's and 1's: > int[][] twisted = [[0, 1, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, > 1]]; > // 0 1 0 0 > // 0 1 0 0 > // 1 0 0 0 > // 0 0 0 1 > > The function I had turns the array 90 degrees counterclockwise so that > the above array turns into: > > // 0 0 0 1 > // 0 0 0 0 > // 1 1 0 0 > // 0 0 1 0 > > In Java the function goes something like this: > > private int[][] twist(int[][] in) > { > // since array is square, > // size serves as both length and width > > int size = in.length; > int[][] out = new int[size][size]; > > for(int i=0; i { > for(int j=0; j { > out[i][j] = in[j][size-i-1]; > } > } > > return(out); > } > > However, I'm having a dickens of a time trying to do the same in Python, > using lists of lists One solution is to build the list of lists one step at a time: def twist1(input): output = [] # we assume that m is square, so size == width == height size = len(input) for row in range(size): newrow = [] for col in range(size): newrow.append(input[col][size - row - 1]) output.append(newrow) return output Another solution is to build the output list with the correct dimensions beforehand, after which you can fill it in with the right values the same way as you did in Java: def twist2(input): size = len(input) output = [range(size) for i in range(size)] for row in range(size): for col in range(size): output[row][col] = input[col][size - row - 1] return output Or with a nested list comprehension it can even be done in one step: def twist3(input): size = len(input) return [[input[col][size - row - 1] for col in range(size)] for row in range(size)] > and extracting the individual values to do some string > processing after the rotation. You can access the values using the same syntax as Java: >>> print twisted [[0, 0, 0, 1], [0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0]] >>> print twisted[0][3] 1 >>> print twisted[2][2] 0 -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From coen at reservoir.nl Sun Nov 19 11:54:08 2006 From: coen at reservoir.nl (Coen van der Kamp) Date: Sun, 19 Nov 2006 11:54:08 +0100 Subject: [Tutor] os.popen, xp In-Reply-To: <455FACB5.5020303@gmail.com> References: <455FA7BD.6040603@reservoir.nl> <455FACB5.5020303@gmail.com> Message-ID: <456037D0.6010700@reservoir.nl> Luke Paireepinart wrote: > Coen van der Kamp wrote: >> Hello, >> I've got a problem with the following code: >> >> import os, sys, string >> mycolors = os.popen("coloryze --monochromatic --total=6 >> &").read().rstrip() >> print mycolors >> >> This works fine on OS X, but when i tried it on XP the only result >> was an empty string. When I run coloryze from the promt > when you run it from which prompt? > The OS X one or the XP one? XP. I did set a Path to coloryze: C:\Python\Lib\coloryze.py (my computer, advanced, system variable, user variable). So i could run coloryze form the XP prompt. I now realize that it is maybe not smart to access another python program this way,... But since typing 'coloryze --monochromatic --total=6 ' running from the prompt worked, I'd think that the same should be possible from Python. Hope you can help me out! >> the return is a nice list of colors. So coloryze works. What am I >> missing here? >> >> Coen. >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > From alan.gauld at btinternet.com Sun Nov 19 16:34:03 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Nov 2006 15:34:03 -0000 Subject: [Tutor] Rotating an array? References: <456024F1.8020400@fastmail.fm> Message-ID: "Roel Schroeven" wrote > > int[][] out = new int[size][size]; > > If you just want an empty array as per Java you can use a list comprehension: out = [[0] * 4 for n in range(4)] > > for(int i=0; i > for(int j=0; j > out[i][j] = in[j][size-i-1]; > > } > > } for i in range(size): for j in range(size): out[i][j] = inp[j][size-j-1] > Or with a nested list comprehension it can even be done in one step: > > def twist3(input): > size = len(input) > return [[input[col][size - row - 1] for col in range(size)] for > row > in range(size)] Personally I'd go with Roel's list comprehension solution. This exactly the kind of thing comprehensions were designed for. Which illustrates a danger of trying to learn one language by just translating another. You wind up ewriting your old language in the syntax of the new rather than learning the new paradigms. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Sun Nov 19 20:26:50 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 19 Nov 2006 11:26:50 -0800 Subject: [Tutor] Rotating an array? In-Reply-To: References: <456024F1.8020400@fastmail.fm> Message-ID: <4560AFFA.4060901@alum.rpi.edu> The OP (whose email address I don't have) requested a 90 degree ccw roatation. transposed = zip(*twisted) # gives the 90 degree cw roatation transposed.reverse() # does the 180 degree rotation leaving us at 90 degreee ccw -- Bob Gailer 510-978-4454 From alan.gauld at btinternet.com Sun Nov 19 23:46:31 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Nov 2006 22:46:31 -0000 Subject: [Tutor] Rotating an array? References: <456024F1.8020400@fastmail.fm> Message-ID: "Alan Gauld" wrote > If you just want an empty array as per Java you can use a > list comprehension: > > out = [[0] * 4 for n in range(4)] > This isn't really empty of course, its full of zeros, the nearest to a truly empty array you can do in Python would be to use None for the value. Sory for any confusion, Alan G. From cappy2112 at gmail.com Mon Nov 20 04:22:29 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sun, 19 Nov 2006 19:22:29 -0800 Subject: [Tutor] handling timeouts, normal completion, or exceptions when interacting with CVS Message-ID: <8249c4ac0611191922h26942943o1a73416a1e51d912@mail.gmail.com> I've written a script which will checkout files from CVS, however, I don' t know how to check for normal completion, errors or exceptions. There are many people using CVS for this massive project, so we can't just switch to a source control which has better scripting abilities. We are stuck with cvs. def SendCVSCommand(self) self.__cvsCmd = "cvs update -A -C someArchiveName" try: hProcess = popen(self.__cvsCmd, "r") # will run the cvs command, and checkout this module to the current directory # HOW LONG DO WE WAIT BEFORE CONTINUING???? sleep(timeToWait) # how do we check for errors?????????? hProcess.close() except: # bad idea, but better than nothing for now self.__FatalError = True print"\nException was encountered while processing this cvs command line %s\n" % commandLine I'm using 30 seconds for the sleep time, but what I would like to do is exit this routine early, if the CVS command finishes before 30 seconds are up. I don't know how to check if the cvs command has finised normally, or with errors. Does anyone have any suggestions how to handle erros or completion in a process like this? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061119/153b05e3/attachment.html From singingxduck at gmail.com Mon Nov 20 04:42:08 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Sun, 19 Nov 2006 22:42:08 -0500 Subject: [Tutor] registering iTunes with events now *sometimes* works Message-ID: <3449428f0611191942p3fd91e3ekd06f76bcee0f7a8c@mail.gmail.com> Hello again, still on the topic of my iTunes related program and its issues with catching events. All right, so if anyone would be willing to test-drive my program and tell me if it prints "playing" and "stopped" as it should on their computer, I'd be extremely grateful. For no discernable reason, the code that worked fine 5 minutes ago now refuses to perform as it should, and I'm stumped again: from Tkinter import * import tkFont from Tkconstants import * from PIL import Image, ImageTk import win32com.client, time, os, win32ui, win32con, win32gui, pythoncom class FakeTrack: def __init__(self, artist="No", album="Track", name="Selected", track=None): self.Artist = artist self.Album = album self.Name = name self.TrackCount = 0 self.TrackNumber = 0 self.Duration = 0 self.GetITObjectIDs = lambda: None self.Artwork = lambda x: "" if track: for key in self.__dict__: self.__dict__[key] = getattr(track, key) self.track = track class Application(Frame): def createWidgets(self): self.artpic = Label(self, fg="white", bg="black") try: im = Image.open("C:\\Documents and Settings\\Cookie\\Desktop\\temp.jpeg") # im.thumbnail((600,600)) self.image = ImageTk.PhotoImage(im.resize((600,600))) except: self.image = None self.artpic["image"] = self.image self.artpic["text"] = "No Artwork" self.artpic.pack() self.trackslbl = Label(self, fg="white", bg="black") self.trackslbl["text"] = "99" self.trackslbl.place(relx=1,rely=1,x=-22,y=-55) self.timeleftlbl = Label(self, fg="white", bg="black") self.timeleftlbl["text"] = "00:00" self.timeleftlbl.place(relx=1,rely=1,x=-32,y=-37) self.skiptoendbtn = Button(self, fg="white", bg="black", font= tkFont.Font(family="Courier", size=6, weight="bold")) self.skiptoendbtn["text"] = ">|*" self.skiptoendbtn.place(relx=1,rely=1,x=-54,y=-19) self.skiptoendbtn.bind("", self.skiptoend) self.skipendalbumbtn = Button(self, fg="white", bg="black", font= tkFont.Font(family="Courier", size=6, weight="bold")) self.skipendalbumbtn["text"] = ">>|*" self.skipendalbumbtn.place(relx=1,rely=1,x=-31,y=-19) self.skipendalbumbtn.bind("", self.skipendalbum) self.skipalbumbtn = Button(self, fg="white", bg="black", font= tkFont.Font(family="Courier", size=6, weight="bold")) self.skipalbumbtn["text"] = ">>|" self.skipalbumbtn.place(relx=1,rely=1,x=-77,y=-19) self.skipalbumbtn.bind("", self.skipalbum) self.deetsFrame = Frame(self, bg="black") self.deetsFrame.pack() self.artistlbl = Label(self.deetsFrame, fg="white", bg="black") self.artistlbl["text"] = "Artist" self.artistlbl.pack() self.albumlbl = Label(self.deetsFrame, fg="white", bg="black") self.albumlbl["text"] = "Album" self.albumlbl.pack() self.namelbl = Label(self.deetsFrame, fg="white", bg="black") self.namelbl["text"] = "Name" self.namelbl.pack() def __init__(self, master=None): self.iTunes = win32com.client.gencache.EnsureDispatch(" iTunes.Application") self.iTunesEvents = win32com.client.WithEvents(self.iTunes, iTunesEvents) self.track = FakeTrack(track=self.iTunes.CurrentTrack) # polymorphic - either "No Track Selected" or wrapper for actual track self.art = self.track.Artwork(1) # either "" or actual artwork try: self.art.SaveArtworkToFile('C:\\Documents and Settings\\Owner\\Desktop\\temp.jpeg') except AttributeError: pass self.newart = True self.playing = True Frame.__init__(self, master) self.grid() self.createWidgets() self.master.title("Now Playing") self.master["bg"] = "black" self["bg"] = "black" self.updateInfo() self.waitAndSee() def updateInfo(self): if self.iTunes.PlayerState != 0: self.master.title("Now Playing") if self.art and self.newart: #print "deleting current artwork, replacing with new artwork" self.artpic.config(width=0) im = Image.open("C:\\Documents and Settings\\Owner\\Desktop\\temp.jpeg") # im.thumbnail((100,100)) #thumbnail can only decrease size; works in-place self.image = ImageTk.PhotoImage(im.resize((600,600))) self.artpic["image"] = "" self.artpic["image"] = self.image elif not self.art: #print "deleting current artwork" self.image = None self.artpic["image"] = "" self.artpic["width"] = 75 self.artistlbl["text"] = self.track.Artist if self.track.Album and self.track.Duration != 0: tracks = self.iTunes.LibraryPlaylist.Search(self.track.Album,3) tracks = sorted([tracks.Item(i) for i in range(1,len(tracks)+1)], key=lambda x: x.TrackNumber) tracks = [t for t in tracks if t.Album == self.track.Album] self.trackslbl["text"] = "%02d" % (len(tracks)-[t.Name for t in tracks].index(self.track.Name)-1) else: self.trackslbl["text"] = "??" if not (self.track.Artist == "No" and self.track.Album == "Track" and self.track.Name == "Selected"): self.timeleftlbl["text"] = self.minutes( self.track.Duration-self.iTunes.PlayerPosition) else: self.timeleftlbl["text"] = "0:00" self.timeleftlbl.place_forget() self.timeleftlbl.place(relx=1,rely=1,x=-(37-(10*(5-len( self.timeleftlbl["text"]))-4*(5-len(self.timeleftlbl["text"])))),y=-37) self.albumlbl["text"] = self.track.Album self.namelbl["text"] = self.track.Name self.master.update() def minutes(self, seconds): return "%d:%02d" % (seconds/60,seconds-(seconds/60*60)) def waitAndSee(self): while 1: win32gui.PumpWaitingMessages() if self.iTunes.PlayerState == 0: self.master.title("Paused") self.playing = True if (not self.iTunes.CurrentTrack) or self.iTunes.CurrentTrack.GetITObjectIDs() != self.track.GetITObjectIDs() or self.newart: self.track = FakeTrack(track=self.iTunes.CurrentTrack) # either fake track w/ "No Track Selected" or wrapper for actual self.iTunes.CurrentTrack self.newart = True # either empty so doesn't matter (if self.art and self.newart in updateInfo()) or new self.art = self.track.Artwork(1) # either "" or actual Artwork if self.art: #print "saving new artwork" self.art.SaveArtworkToFile('C:\\Documents and Settings\\Owner\\Desktop\\temp.jpeg') else: self.newart = False self.updateInfo() time.sleep(1) def skiptoend(self, event=None): tm = time.localtime() self.iTunes.CurrentTrack.PlayedDate = "%s/%s/%s %s:%s:%s" % (tm[1], tm[2], tm[0], tm[3], tm[4], tm[5]) self.iTunes.CurrentTrack.PlayedCount += 1 self.iTunes.NextTrack() self.newart = True def skipendalbum(self, event): while self.iTunes.CurrentTrack.Album == self.track.Album: self.skiptoend() def skipalbum(self, event): while self.iTunes.CurrentTrack.Album == self.track.Album: self.iTunes.NextTrack() self.track = self.iTunes.CurrentTrack class iTunesEvents: def __init__(self): print "starting iTunesEvents" def OnPlayerPlayEvent(self, track): print "playing" def OnPlayerStopEvent(self, track): print "stopped" def OnDatabaseChangedEvent(self, deleted, changed): print "database changed" def OnPlayerPlayingTrackChangedEvent(self, track): print "info on current track changed" def OnCOMCallsDisabledEvent(self, reason): print "com calls disabled" def OnCOMCallsEnabledEvent(self): print "com calls enabled" def OnQuittingEvent(self): print "quitting" def OnAboutToPromptUserToQuitEvent(self): print "prompting user to quit" def OnSoundVolumeChangedEvent(self, newvolume): print "volume changed" root = Tk() try: app = Application(master=root) # app.mainloop() # unnecessary b/c loop maintained in waitAndSee; incidentally blocks events when run root.destroy() except TclError: pass try: os.remove('C:\\Documents and Settings\\Owner\\Desktop\\temp.jpeg') except OSError: pass Thanks in advance, Orri -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061119/5c485861/attachment.html From alan.gauld at btinternet.com Mon Nov 20 06:17:59 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Nov 2006 05:17:59 -0000 Subject: [Tutor] handling timeouts, normal completion, or exceptions when interacting with CVS References: <8249c4ac0611191922h26942943o1a73416a1e51d912@mail.gmail.com> Message-ID: "Tony Cappellini" wrote > def SendCVSCommand(self) > > self.__cvsCmd = "cvs update -A -C someArchiveName" > > try: > hProcess = popen(self.__cvsCmd, "r") # will run the cvs > command, > and checkout this module to the current directory > # HOW LONG DO WE WAIT BEFORE CONTINUING???? > sleep(timeToWait) > > # how do we check for errors?????????? I don't think you need the sleep because the call to popen won't return untl the command has completed. And you check for errors by reading the output from stdout and stderr just as you would at a console. result = hProcess.read() and parse the string in result. You probably want to use popen2 or popen3 to separate the stdout/stderr streams. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rschroev_nospam_ml at fastmail.fm Mon Nov 20 10:10:06 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 20 Nov 2006 10:10:06 +0100 Subject: [Tutor] Rotating an array? In-Reply-To: <4560AFFA.4060901@alum.rpi.edu> References: <456024F1.8020400@fastmail.fm> <4560AFFA.4060901@alum.rpi.edu> Message-ID: Bob Gailer schreef: > The OP (whose email address I don't have) requested a 90 degree ccw > roatation. > > transposed = zip(*twisted) # gives the 90 degree cw roatation > transposed.reverse() # does the 180 degree rotation leaving us at 90 > degreee ccw Ah yes, that works too except that it gives a list of tuples instead of a list of lists. I suppose that detail is not important in many cases. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From Mike.Hansen at atmel.com Mon Nov 20 17:43:42 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 20 Nov 2006 09:43:42 -0700 Subject: [Tutor] handling timeouts, normal completion, or exceptions when interacting with CVS Message-ID: <57B026980605A64F9B23484C5659E32E3CAB8A@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Tony Cappellini > Sent: Sunday, November 19, 2006 8:22 PM > To: tutor at python.org > Subject: [Tutor] handling timeouts, normal completion,or > exceptions when interacting with CVS > > > I've written a script which will checkout files from CVS, [...] I just googled python cvs and hit this library: http://rhaptos.org/downloads/python/pycvs/ Maybe you can use it, or you can peer into it to get some ideas on how it's doing it. Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From Mike.Hansen at atmel.com Mon Nov 20 17:47:31 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 20 Nov 2006 09:47:31 -0700 Subject: [Tutor] OT: Vim was: free IDE for Python? Message-ID: <57B026980605A64F9B23484C5659E32E3CAB8C@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces+mike.hansen=atmel.com at python.org > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of Chris Lasher > Sent: Saturday, November 18, 2006 8:01 AM > To: Python Tutor > Subject: Re: [Tutor] OT: Vim was: free IDE for Python? > > On 11/17/06, Mike Hansen wrote: > > > > Here's what I'm doing. Not sure if it's that helpful to you. > > > > I use the mini-buffer explorer plug-in and the taglist plugin. > > > > set smartindent > > > > " shuts off the annoying "#" comment in smartindent to jump to col 1 > > inoremap # X# > > > > autocmd BufRead *.py set smartindent > > cinwords=if,elif,else,for,while,try,except,finally,def,class > > > > Instead of using smartindent + cinwords + the inoremap hack, simply > use "filetype indent on". This was recommended to me on #Vim IRC > channel. This takes care of the silly # problem with smartindent and > is considered the best way for getting proper indentation in Python. > Give it a try! > > Chris Doh! I'll spend my life learning all the little things in VIM. Thanks, Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From cappy2112 at gmail.com Mon Nov 20 18:26:51 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Mon, 20 Nov 2006 09:26:51 -0800 Subject: [Tutor] handling timeouts, normal completion, or Message-ID: <8249c4ac0611200926r51ed7313y112b39020f01a359@mail.gmail.com> > Message: 1 > Date: Mon, 20 Nov 2006 05:17:59 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] handling timeouts, normal completion, or > exceptions when interacting with CVS > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Tony Cappellini" wrote > > > def SendCVSCommand(self) > > > > self.__cvsCmd = "cvs update -A -C someArchiveName" > > > > try: > > hProcess = popen(self.__cvsCmd, "r") # will run the cvs > > command, > > and checkout this module to the current directory > > # HOW LONG DO WE WAIT BEFORE CONTINUING???? > > sleep(timeToWait) > > > > # how do we check for errors?????????? > > >>I don't think you need the sleep because the call to popen won't > >>return untl the command has completed. The last line was truncated- this is why the sleep call must be there hProcess.close() This cannot be called until the cvs transaction has finished, but since I don't know how long to wait, I arbitrary used 30 seconds in the argument to sleep >>And you check for errors by reading the output from stdout > >>and stderr just as you would at a console. I tried this for line in hProcess.readlines(): print line I called this every several seconds, before the sleep(3) call Nothing is returned from cvs- not one single ascii character. >>You probably want to use popen2 or popen3 to separate the > >>stdout/stderr streams. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061120/608c2ee9/attachment.html From carroll at tjc.com Mon Nov 20 19:02:44 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 20 Nov 2006 10:02:44 -0800 (PST) Subject: [Tutor] A Million Sevens In-Reply-To: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> Message-ID: On Sat, 18 Nov 2006, Thomas wrote: > >>> int('7' * 10 ** 6) > > Can you guess what it did? Just to add to the data points: on my system, it grabbed about half the CPU and ran for 19 hours. From cappy2112 at gmail.com Mon Nov 20 20:14:55 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Mon, 20 Nov 2006 11:14:55 -0800 Subject: [Tutor] handling timeouts, normal completion, or Message-ID: <8249c4ac0611201114n5a05323at1f1488b941f45048@mail.gmail.com> *Mike Hansen* Mike.Hansen at atmel.com *Mon Nov 20 17:43:42 CET 2006* >>I just googled python cvs and hit this library: >>http://rhaptos.org/downloads/python/pycvs/ Already tried this. This project doesn't do error checking on individual cvs commands, which is what I need. It only looks at network-level protocol errors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061120/e4658755/attachment.html From rajusubbanna at yahoo.com Mon Nov 20 21:06:44 2006 From: rajusubbanna at yahoo.com (Hemantharaju Subbanna) Date: Mon, 20 Nov 2006 12:06:44 -0800 (PST) Subject: [Tutor] regular expression need help In-Reply-To: <8249c4ac0611200926r51ed7313y112b39020f01a359@mail.gmail.com> Message-ID: <20061120200644.39026.qmail@web54602.mail.yahoo.com> >>>a '\\ABC' >>>b 'THIS \\ABC' I am looking for the expression that would tell me if the line has "\\" re.match('',a) tried to escape, python complains of syntax Please help with the regular expression that would check for this double slash Thank you --raju ____________________________________________________________________________________ Sponsored Link Mortgage rates near 39yr lows. $310k for $999/mo. Calculate new payment! www.LowerMyBills.com/lre From lucidmonk at gmail.com Mon Nov 20 21:22:12 2006 From: lucidmonk at gmail.com (Todd Dahl) Date: Mon, 20 Nov 2006 15:22:12 -0500 Subject: [Tutor] Code not doing what I think it's doing Message-ID: <44290fe50611201222gdc4d91bw974f8c5cd80a9026@mail.gmail.com> So I have this piece of code below from my script that I am still working on and it's not doing what my brain says it should. If I remove the whole section starting at: > for guid in guidlist: it prints correctly the primary key of each row that I queried with the line that starts with: > print "db_row: ", str(row[0]) but with the for statement line in it does not loop back to that statement anymore and it makes no sence to me why not. Shouldn't it run through the line: > print "db_row: ", str(row[0]) every single time? No matter if the for loop in there or not? Please, excuse the littering of code snippets that I have been using for trying to figure this out. Thanks, -Todd ============================== def parseRegistry(): """ Update database with entries that where found in the registry""" #First collect all main registry keys under the CLSID tree and put them into a list guidlist = ListRegistryKeys("CLSID") #Create database if it does not exist or open database if it does exist #Create a connection object connection = sqlite.connect('dcs2000.db') #Create a cursor object cursor = connection.cursor() #Loop through returned data resultSet = cursor.execute("SELECT * FROM VBGuids where comType = 'Object' ") for row in resultSet: print "db_row: ", str(row[0]) #zz = raw_input("stop at ....db row") for guid in guidlist: key2=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, guid) j=0 try: while 1: valueName, valueValue, valueType= _winreg.EnumValue(key2, j) #print guid #print "valueName", valueName #print "valueValue", valueValue #print "valueType", valueType # zz = raw_input("... :-() ...") updateSQLString = "update VBGuids set RegistrationPath='" + 'z:\lalala' + "', Name='" + 'NANA' + "' where id=" + str(row[0]) #print "SQL: ", updateSQLString #print "row: ", str(row[0]) cursor.execute(updateSQLString) connection.commit() j += 1 #print j except WindowsError, e: continue except Exception, e: print '%s: %s' % (e.__class__.__name__, e) if isinstance(e, SystemExit): raise # take the exit except: print 'Nonstandard Exception %r: %r' % __import__('sys').exc_info()[:2] sys.exit() _winreg.CloseKey( key2) # Okay we need to close the cursor and connection cursor.close() connection.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061120/4f937085/attachment-0001.htm From rajusubbanna at yahoo.com Mon Nov 20 21:28:58 2006 From: rajusubbanna at yahoo.com (Hemantharaju Subbanna) Date: Mon, 20 Nov 2006 12:28:58 -0800 (PST) Subject: [Tutor] slash slash, Must be related. Message-ID: <20061120202859.25429.qmail@web54614.mail.yahoo.com> Wondering why single and souble slash results in 2 same effect on a >>> a= '\ABC' >>> a '\\ABC' >>> a= '\\ABC' >>> a '\\ABC' ____________________________________________________________________________________ Sponsored Link Don't quit your job - take classes online www.Classesusa.com From kent37 at tds.net Mon Nov 20 21:40:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Nov 2006 15:40:53 -0500 Subject: [Tutor] Code not doing what I think it's doing In-Reply-To: <44290fe50611201222gdc4d91bw974f8c5cd80a9026@mail.gmail.com> References: <44290fe50611201222gdc4d91bw974f8c5cd80a9026@mail.gmail.com> Message-ID: <456212D5.9060809@tds.net> Todd Dahl wrote: > So I have this piece of code below from my script that I am still > working on and it's not doing what my brain says it should. > > If I remove the whole section starting at: > > for guid in guidlist: > > it prints correctly the primary key of each row that I queried with the > line that starts with: > > > print "db_row: ", str(row[0]) > > but with the for statement line in it does not loop back to that > statement anymore and it makes no sence to me why not. Shouldn't it run > through the line: > > > print "db_row: ", str(row[0]) > > every single time? No matter if the for loop in there or not? My wild guess is that the problem is that you are reusing the same cursor while you are iterating the result set. Try using a separate cursor for the nested update or read all the data from the result set into a list and iterate the list instead of the result set. Kent > > Please, excuse the littering of code snippets that I have been using for > trying to figure this out. > > Thanks, > > -Todd > > > ============================== > > > def parseRegistry(): > """ Update database with entries that where found in the registry""" > #First collect all main registry keys under the CLSID tree and put > them into a list > > guidlist = ListRegistryKeys("CLSID") > > #Create database if it does not exist or open database if it does exist > #Create a connection object > connection = sqlite.connect('dcs2000.db ') > > #Create a cursor object > cursor = connection.cursor() > > #Loop through returned data > resultSet = cursor.execute("SELECT * FROM VBGuids where comType = > 'Object' ") > for row in resultSet: > print "db_row: ", str(row[0]) > #zz = raw_input("stop at ....db row") > > for guid in guidlist: > key2=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, guid) > j=0 > > try: > while 1: > valueName, valueValue, valueType= > _winreg.EnumValue(key2, j) > #print guid > #print "valueName", valueName > #print "valueValue", valueValue > #print "valueType", valueType > # zz = raw_input("... :-() ...") > > updateSQLString = "update VBGuids set > RegistrationPath='" + 'z:\lalala' + "', Name='" + 'NANA' + "' where id=" > + str(row[0]) > #print "SQL: ", updateSQLString > #print "row: ", str(row[0]) > > cursor.execute(updateSQLString) > connection.commit() > > > j += 1 > #print j > except WindowsError, e: > continue > except Exception, e: > print '%s: %s' % (e.__class__.__name__, e) > if isinstance(e, SystemExit): raise # take the exit > except: > print 'Nonstandard Exception %r: %r' % > __import__('sys').exc_info()[:2] > sys.exit () > > _winreg.CloseKey( key2) > > > > > # Okay we need to close the cursor and connection > cursor.close() > connection.close() > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Mon Nov 20 21:45:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Nov 2006 15:45:40 -0500 Subject: [Tutor] regular expression need help In-Reply-To: <20061120200644.39026.qmail@web54602.mail.yahoo.com> References: <20061120200644.39026.qmail@web54602.mail.yahoo.com> Message-ID: <456213F4.4090509@tds.net> Hemantharaju Subbanna wrote: >>>> a > '\\ABC' >>>> b > 'THIS \\ABC' > > I am looking for the expression that would tell me if > the line has "\\" First you should be aware that neither of these strings contains a double slash. They contain a single slash which Python prints with an extra slash as an escape. This is how Python prints and interprets string literals: In [1]: a='\\' In [2]: a Out[2]: '\\' a only contains a single character, a single slash: In [3]: len(a) Out[3]: 1 If you explicitly print a, the escaping is not done and you see the plain value of the string: In [4]: print a \ If you want to know if a string contains a slash, just ask it using 'in'. : In [5]: '\\' in a Out[5]: True In [6]: '\\' in 'THIS \\ABC' Out[6]: True Kent > > re.match('',a) > > tried to escape, python complains of syntax > > Please help with the regular expression that would > check for this double slash > > Thank you > --raju > > > > > ____________________________________________________________________________________ > Sponsored Link > > Mortgage rates near 39yr lows. > $310k for $999/mo. Calculate new payment! > www.LowerMyBills.com/lre > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From carroll at tjc.com Mon Nov 20 22:22:46 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 20 Nov 2006 13:22:46 -0800 (PST) Subject: [Tutor] slash slash, Must be related. In-Reply-To: <20061120202859.25429.qmail@web54614.mail.yahoo.com> Message-ID: On Mon, 20 Nov 2006, Hemantharaju Subbanna wrote: > Wondering why single and souble slash results in 2 > same effect on a > > >>> a= '\ABC' > >>> a > '\\ABC' > >>> a= '\\ABC' > >>> a > '\\ABC' Check out the description of the backslash at http://docs.python.org/ref/strings.html ; specifically: Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. The following is a slight oversimplification, but for the string: \ABC Python sees the '\', and says, "okay, I'm at the start of an escape sequence; let's see the next character and see how to interpret this." Then it sees the 'A' and concludes, "well, I guess it wasn't an escape sequence after all. The guy actually *meant* to include that backslash." and so interprets it as for characters: '\', 'A', 'B', and 'C'. And, when it prints out the value, it properly escapes the '\' with another, as '\\', so the whole four-character string is represented as "\\ABC" . Contrast this with the string: \abc Python sees the '\', and says, "okay, I'm at the start of an escape sequence; let's see the next character and see how to interpret this." Then it sees the 'a", and says, "aha, this is a BELL character" (see the table in that web page), and treats '\a' as a single character, having a value 0x07, representing the ASCII BEL character. The resulting string is three characters long: 0x07, 'b' and 'c'. From andreas at kostyrka.org Mon Nov 20 22:37:13 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 20 Nov 2006 22:37:13 +0100 Subject: [Tutor] slash slash, Must be related. In-Reply-To: <20061120202859.25429.qmail@web54614.mail.yahoo.com> References: <20061120202859.25429.qmail@web54614.mail.yahoo.com> Message-ID: <20061120213711.GJ10062@andi-lap.la.revver.com> * Hemantharaju Subbanna [061120 21:30]: > Wondering why single and souble slash results in 2 > same effect on a > > >>> a= '\ABC' Simple: \A is not a valid escape, so it will be taken as \ and A seperatly. Try: '\abc' :) Andreas From john at fouhy.net Mon Nov 20 23:16:01 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 21 Nov 2006 11:16:01 +1300 Subject: [Tutor] Programming exercises Message-ID: <5e58f2e40611201416u7019ae24r815a8ff6d901f3e1@mail.gmail.com> List of programming exercises: http://www.spoj.pl/problems/classical/ -- John. From nperito at gmail.com Tue Nov 21 04:02:37 2006 From: nperito at gmail.com (Nicholas Perito) Date: Tue, 21 Nov 2006 12:02:37 +0900 Subject: [Tutor] How to create delay in game Message-ID: <45626C4D.4060907@gmail.com> Hello, I new to programming and this is my first post. I'm learning Python via "Python Programming for the Absolute Beginner" by Michael Dawson. I've written a pong game into which I want to insert a delay between sprite initializations. Right now, if an "Atom" sprite reaches the bottom of the screen, the next Atom sprite appears immediately. Instead, when the sprite reaches the bottom, I want the message "Two (or One) atoms left!" to appear for it's lifetime before the next Atom sprite appears. I've tried to create a delay by making it crunch numbers, but that hasn't worked well. Anyway, the code is below, and the place where I want to create a delay is marked. Oh, and constructive criticism of the code is welcome--I'm not too sensitive. Thanks a lot to anyone who can help! (It's called 'Atom Pong' because I had a cool graphic) # Atom Pong # Nic Perito 11/06 import random from livewires import games, color SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 700 THE_SCREEN = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT) life = 3 class Atom(games.Sprite): """ Atom image """ image = games.load_image("atom.jpg") def __init__(self, screen, x, y, dx, dy): """ Initialize atom object. """ self.init_sprite(screen = screen, x = x, y = y, dx = dx, dy = dy, image = Atom.image) def moved(self): """ Reverse a velocity component if edge of screen reached. """ global life dx, dy = self.get_velocity() self.rotate_by(3) if self.get_right() > SCREEN_WIDTH: self.set_right(SCREEN_WIDTH) self.set_velocity(-dx, dy) if self.get_left() < 0: self.set_left(0) self.set_velocity(-dx, dy) if self.get_top() < 0: self.set_velocity(dx, -dy) if self.get_bottom() > SCREEN_HEIGHT: self.destroy() life -= 1 if life == 0: self.game_over() if life == 2: games.Message(screen = self.screen, x = 150, y = 20, text = "Two atoms left!", size = 40, color = color.yellow, lifetime = 200) #HERE'S WHERE I WANT A DELAY Atom(self.screen, x = (SCREEN_WIDTH - 76), y = 76, dx = 6, dy = 5) if life == 1: games.Message(screen = self.screen, x = 150, y = 45, text = "One atom left!", size = 40, color = color.yellow, lifetime = 200) #HERE'S WHERE I WANT A DELAY Atom(self.screen, x = 76, y = 76, dx = 6, dy = 6) def handle_deflect(self): """ Deflect atom. """ dx, dy = self.get_velocity() self.set_velocity(dx + random.randrange(2,4), -dy) def game_over(self): """ End the game. """ # destroy all game objects except the Text object (player's score) for game_object in self.screen.all_objects(): if not isinstance(game_object, games.Text): game_object.destroy() # show 'Game Over' for 250 mainloop() cycles games.Message(screen = self.screen, x = SCREEN_WIDTH/2, y = 400, text = "Game Over", size = 90, color = color.red, lifetime = 500, after_death = self.screen.quit) class Bonus(games.Sprite): """ Atom bonus image """ image = games.load_image("bonus.jpg") def __init__(self, screen, x, y, dx, dy): """ Initialize atom object. """ self.init_sprite(screen = screen, x = x, y = y, dx = dx, dy = dy, image = Bonus.image) def moved(self): """ Reverse a velocity component if edge of screen reached. """ dx, dy = self.get_velocity() self.rotate_by(-3) if self.get_right() > SCREEN_WIDTH or self.get_left() < 0: self.set_velocity(-dx, dy) if self.get_top() < 0: self.set_velocity(dx, -dy) if self.get_bottom() > SCREEN_HEIGHT: self.destroy() def handle_deflect(self): """ Deflect atom. """ dx, dy = self.get_velocity() self.set_velocity(dx, -dy) class Paddle(games.Sprite): """ A paddle controlled by player to 'deflect' atoms. """ image = games.load_image("paddle.jpg", transparent = False) def __init__ (self, screen, x, y): """ Initialize paddle object. Create a Text object for player's score. """ self.init_sprite(screen = screen, x = x, y = y, image = Paddle.image) self.score_value = 0 self.score_text = games.Text(screen = self.screen, x = SCREEN_WIDTH/2, y = 20, text = "Score: 0", size = 25, color = color.white) def moved(self): """ Move paddle to mouse x position. """ x, y = self.get_pos() if self.screen.is_pressed(games.K_RIGHT): x += 9 if self.screen.is_pressed(games.K_LEFT): x -= 9 self.move_to(x,y) if self.get_left() < 0: self.set_left(0) if self.get_right() > SCREEN_WIDTH: self.set_right(SCREEN_WIDTH) self.check_for_impact() def check_for_impact(self): """ Check if paddle hits atoms. """ for atom in self.overlapping_objects(): self.handle_deflect() atom.handle_deflect() def handle_deflect(self): """ Increase and display score. """ bonus = [] for i in range(0, 5000, 50): bonus.append(i) self.score_value += 10 self.score_text.set_text("Score: " + str(self.score_value)) if self.score_value in bonus: Bonus(self.screen, x = random.randrange(800)+ 76, y = 76, dx = random.randrange(10)+2, dy = random.randrange(3)+ 2) games.Message(screen = self.screen, x = SCREEN_WIDTH/2, y = 300, text = "BONUS!", size = 90, color = color.red, lifetime = 50) def main(): my_screen = THE_SCREEN my_screen.mouse_visible(False) background_image = games.load_image("black.jpg", transparent = False) my_screen.set_background(background_image) Atom(screen = my_screen, x = 76, y = 76, dx = 6, dy = 5) Paddle(screen = my_screen, x = SCREEN_WIDTH/2, y = 690) my_screen.mainloop() # start program main() From mib at mibgames.co.uk Tue Nov 21 12:57:41 2006 From: mib at mibgames.co.uk (Michael Brunton-Spall) Date: Tue, 21 Nov 2006 11:57:41 +0000 Subject: [Tutor] How to create delay in game In-Reply-To: <45626C4D.4060907@gmail.com> References: <45626C4D.4060907@gmail.com> Message-ID: <200611211157.41913.mib@mibgames.co.uk> Of all the weird things, I'm currently working for Scripture Union, i never knew they had made a python package for learning python, anyway... add import time where you want to delay for a while, time.sleep(0.1) that will sleep for 0.1 seconds, (or try to). the livewires package is a wrapper around pygame, it might be worth looking at pygame.org to see the more powerful, underlying package. The livewires packages have worksheets to go with the packages, teaching games programing. Reference sheet T(Time) had this information in it. might be worth checking those out if your sticking with livewires. find them at http://www.livewires.org.uk/python/pdfsheets.html Michael Brunton-Spall On Tuesday 21 November 2006 03:02, Nicholas Perito wrote: > Hello, > > I new to programming and this is my first post. I'm learning Python via > "Python Programming for the Absolute Beginner" by Michael Dawson. I've > written a pong game into which I want to insert a delay between sprite > initializations. Right now, if an "Atom" sprite reaches the bottom of > the screen, the next Atom sprite appears immediately. Instead, when the > sprite reaches the bottom, I want the message "Two (or One) atoms left!" > to appear for it's lifetime before the next Atom sprite appears. I've > tried to create a delay by making it crunch numbers, but that hasn't > worked well. > > Anyway, the code is below, and the place where I want to create a delay > is marked. Oh, and constructive criticism of the code is welcome--I'm > not too sensitive. > > Thanks a lot to anyone who can help! > > (It's called 'Atom Pong' because I had a cool graphic) > > # Atom Pong > # Nic Perito 11/06 > > import random > from livewires import games, color > > SCREEN_WIDTH = 1000 > SCREEN_HEIGHT = 700 > THE_SCREEN = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT) > life = 3 > > class Atom(games.Sprite): > """ Atom image """ > > image = games.load_image("atom.jpg") > def __init__(self, screen, x, y, dx, dy): > """ Initialize atom object. """ > self.init_sprite(screen = screen, x = x, y = y, > dx = dx, dy = dy, image = Atom.image) > > def moved(self): > """ Reverse a velocity component if edge of screen reached. """ > global life > dx, dy = self.get_velocity() > self.rotate_by(3) > if self.get_right() > SCREEN_WIDTH: > self.set_right(SCREEN_WIDTH) > self.set_velocity(-dx, dy) > if self.get_left() < 0: > self.set_left(0) > self.set_velocity(-dx, dy) > if self.get_top() < 0: > self.set_velocity(dx, -dy) > if self.get_bottom() > SCREEN_HEIGHT: > self.destroy() > life -= 1 > if life == 0: > self.game_over() > > if life == 2: > games.Message(screen = self.screen, > x = 150, y = 20, > text = "Two atoms left!", size = 40, color = > color.yellow, > lifetime = 200) > #HERE'S WHERE I WANT A DELAY > Atom(self.screen, x = (SCREEN_WIDTH - 76), y = 76, > dx = 6, dy = 5) > > if life == 1: > games.Message(screen = self.screen, > x = 150, y = 45, > text = "One atom left!", size = 40, color = > color.yellow, > lifetime = 200) > #HERE'S WHERE I WANT A DELAY > Atom(self.screen, x = 76, y = 76, > dx = 6, dy = 6) > > def handle_deflect(self): > """ Deflect atom. """ > dx, dy = self.get_velocity() > self.set_velocity(dx + random.randrange(2,4), -dy) > > def game_over(self): > """ End the game. """ > # destroy all game objects except the Text object (player's score) > for game_object in self.screen.all_objects(): > if not isinstance(game_object, games.Text): > game_object.destroy() > > # show 'Game Over' for 250 mainloop() cycles > games.Message(screen = self.screen, > x = SCREEN_WIDTH/2, y = 400, > text = "Game Over", size = 90, color = color.red, > lifetime = 500, after_death = self.screen.quit) > > class Bonus(games.Sprite): > """ Atom bonus image """ > image = games.load_image("bonus.jpg") > def __init__(self, screen, x, y, dx, dy): > """ Initialize atom object. """ > self.init_sprite(screen = screen, x = x, y = y, > dx = dx, dy = dy, image = Bonus.image) > > def moved(self): > """ Reverse a velocity component if edge of screen reached. """ > dx, dy = self.get_velocity() > self.rotate_by(-3) > if self.get_right() > SCREEN_WIDTH or self.get_left() < 0: > self.set_velocity(-dx, dy) > if self.get_top() < 0: > self.set_velocity(dx, -dy) > if self.get_bottom() > SCREEN_HEIGHT: > self.destroy() > def handle_deflect(self): > """ Deflect atom. """ > dx, dy = self.get_velocity() > self.set_velocity(dx, -dy) > > > class Paddle(games.Sprite): > """ > A paddle controlled by player to 'deflect' atoms. > """ > image = games.load_image("paddle.jpg", transparent = False) > > def __init__ (self, screen, x, y): > """ Initialize paddle object. Create a Text object for player's > score. """ > self.init_sprite(screen = screen, x = x, y = y, image = > Paddle.image) > self.score_value = 0 > self.score_text = games.Text(screen = self.screen, x = > SCREEN_WIDTH/2, y = 20, > text = "Score: 0", size = 25, color > = color.white) > > def moved(self): > """ Move paddle to mouse x position. """ > x, y = self.get_pos() > > if self.screen.is_pressed(games.K_RIGHT): > x += 9 > > if self.screen.is_pressed(games.K_LEFT): > x -= 9 > > self.move_to(x,y) > > > if self.get_left() < 0: > self.set_left(0) > if self.get_right() > SCREEN_WIDTH: > self.set_right(SCREEN_WIDTH) > self.check_for_impact() > > def check_for_impact(self): > """ Check if paddle hits atoms. """ > for atom in self.overlapping_objects(): > self.handle_deflect() > atom.handle_deflect() > > def handle_deflect(self): > """ Increase and display score. """ > > bonus = [] > for i in range(0, 5000, 50): > bonus.append(i) > self.score_value += 10 > self.score_text.set_text("Score: " + str(self.score_value)) > if self.score_value in bonus: > Bonus(self.screen, x = random.randrange(800)+ 76, y = 76, > dx = random.randrange(10)+2, dy = random.randrange(3)+ 2) > > games.Message(screen = self.screen, > x = SCREEN_WIDTH/2, y = 300, > text = "BONUS!", size = 90, color = color.red, > lifetime = 50) > > > > > > > > def main(): > my_screen = THE_SCREEN > my_screen.mouse_visible(False) > background_image = games.load_image("black.jpg", transparent = False) > my_screen.set_background(background_image) > > > Atom(screen = my_screen, x = 76, y = 76, > dx = 6, dy = 5) > > > Paddle(screen = my_screen, x = SCREEN_WIDTH/2, y = 690) > > > my_screen.mainloop() > > # start program > main() > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From TValone at DMV.CA.gov Tue Nov 21 17:32:18 2006 From: TValone at DMV.CA.gov (Valone, Toren W.) Date: Tue, 21 Nov 2006 08:32:18 -0800 Subject: [Tutor] FW: Problem with ftplib Message-ID: <66F85FA283D3FE40988AD74B4B209C06035023B0@PRDEXCH03.ad.dmv.ca.gov> I am attempting to design a basic program to FTP files to and from a server here is the message I am getting Traceback (most recent call last): File "C:/Python24/ftpdmv.py", line 2, in -toplevel- x = FTP(host='mvs.teale.ca.gov',user='mvtwv',passwd='xxxxx') File "C:\Python24\lib\ftplib.py", line 107, in __init__ self.connect(host) File "C:\Python24\lib\ftplib.py", line 129, in connect raise socket.error, msg error: (10053, 'Software caused connection abort') Here is the code ran in IDLE IDLE 1.1.2 >>> from ftplib import * >>> x = FTP(host='mvs.teale.ca.gov',user='mvtwv',passwd='xxxxx') I traced it down to the socket.py web but could not find 10053 in the error codes. Debug stops here def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): if _sock is None: _sock = _realsocket(family, type, proto) self._sock = _sock self.send = self._sock.send self.recv = self._sock.recv self.sendto = self._sock.sendto self.recvfrom = self._sock.recvfrom <-- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061121/c4ee09da/attachment.htm From rabidpoobear at gmail.com Tue Nov 21 17:54:28 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 21 Nov 2006 10:54:28 -0600 Subject: [Tutor] FW: Problem with ftplib In-Reply-To: <66F85FA283D3FE40988AD74B4B209C06035023B0@PRDEXCH03.ad.dmv.ca.gov> References: <66F85FA283D3FE40988AD74B4B209C06035023B0@PRDEXCH03.ad.dmv.ca.gov> Message-ID: <45632F44.5070901@gmail.com> Valone, Toren W. wrote: > > > > > > > > *I am attempting to design a basic program to FTP files to and from a > server here is the message I am getting* > > * * > > > > Traceback (most recent call last): > > File "C:/Python24/ftpdmv.py", line 2, in -toplevel- > > x = FTP(host='mvs.teale.ca.gov',user='mvtwv',passwd='xxxxx') > > File "C:\Python24\lib\ftplib.py", line 107, in __init__ > > self.connect(host) > > File "C:\Python24\lib\ftplib.py", line 129, in connect > > raise socket.error, msg > > error: (10053, 'Software caused connection abort') > This sounds like the error you get when your firewall is blocking outgoing port 21. Do you have McAffee VirusScan? Even though it's not a firewall, it sometimes messes with port 21 because lots of viruses propagate through that port. Generally 'software caused connection abort' means you have something running on your computer that's blocking outgoing connections on that port, so it never even got close to talking to the host. HTH, -Luke > > > > *Here is the code ran in IDLE* > > > > IDLE 1.1.2 > > >>> from ftplib import * > > >>> x = FTP(host='mvs.teale.ca.gov',user='mvtwv',passwd='xxxxx') > > > > *I traced it down to the socket.py web but could not find 10053 in the > error codes. * > > > > Debug stops here > > def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): > > if _sock is None: > > _sock = _realsocket(family, type, proto) > > self._sock = _sock > > self.send = self._sock.send > > self.recv = self._sock.recv > > self.sendto = self._sock.sendto > > self.recvfrom = self._sock.recvfrom ? > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From TValone at DMV.CA.gov Tue Nov 21 19:23:14 2006 From: TValone at DMV.CA.gov (Valone, Toren W.) Date: Tue, 21 Nov 2006 10:23:14 -0800 Subject: [Tutor] FW: Problem with ftplib In-Reply-To: <45632F44.5070901@gmail.com> Message-ID: <66F85FA283D3FE40988AD74B4B209C06035023B5@PRDEXCH03.ad.dmv.ca.gov> Luke, you were right on, our pc's at work have Mcafee and it is blocking the application, just wondering why it doesn't block C# programs. -----Original Message----- From: Luke Paireepinart [mailto:rabidpoobear at gmail.com] Sent: Tuesday, November 21, 2006 8:54 AM To: Valone, Toren W. Cc: tutor, python list Subject: Re: [Tutor] FW: Problem with ftplib Valone, Toren W. wrote: > > > > > > > > *I am attempting to design a basic program to FTP files to and from a > server here is the message I am getting* > > * * > > > > Traceback (most recent call last): > > File "C:/Python24/ftpdmv.py", line 2, in -toplevel- > > x = FTP(host='mvs.teale.ca.gov',user='mvtwv',passwd='xxxxx') > > File "C:\Python24\lib\ftplib.py", line 107, in __init__ > > self.connect(host) > > File "C:\Python24\lib\ftplib.py", line 129, in connect > > raise socket.error, msg > > error: (10053, 'Software caused connection abort') > This sounds like the error you get when your firewall is blocking outgoing port 21. Do you have McAffee VirusScan? Even though it's not a firewall, it sometimes messes with port 21 because lots of viruses propagate through that port. Generally 'software caused connection abort' means you have something running on your computer that's blocking outgoing connections on that port, so it never even got close to talking to the host. HTH, -Luke > > > > *Here is the code ran in IDLE* > > > > IDLE 1.1.2 > > >>> from ftplib import * > > >>> x = FTP(host='mvs.teale.ca.gov',user='mvtwv',passwd='xxxxx') > > > > *I traced it down to the socket.py web but could not find 10053 in the > error codes. * > > > > Debug stops here > > def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): > > if _sock is None: > > _sock = _realsocket(family, type, proto) > > self._sock = _sock > > self.send = self._sock.send > > self.recv = self._sock.recv > > self.sendto = self._sock.sendto > > self.recvfrom = self._sock.recvfrom ? > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mrgordon at mit.edu Tue Nov 21 20:52:05 2006 From: mrgordon at mit.edu (Matthew Gordon) Date: Tue, 21 Nov 2006 14:52:05 -0500 Subject: [Tutor] lexical scoping efficiency Message-ID: <2edc23690611211152m40a2384dwf28bbfb9d22b0087@mail.gmail.com> This isn't python specific, but it seems pertinent to the interests of this list regardless. Defining functions inside of other functions seems conceptually neater than defining those functions in the global environment if they're never going to be used by anything except that one function. In terms of efficiency though, it seems terrible to lexically scope because each time the function is called it will have to reinstantiate the sub-function. Anyone have an opinion/suggestion? - Matt From kent37 at tds.net Tue Nov 21 21:02:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Nov 2006 15:02:14 -0500 Subject: [Tutor] lexical scoping efficiency In-Reply-To: <2edc23690611211152m40a2384dwf28bbfb9d22b0087@mail.gmail.com> References: <2edc23690611211152m40a2384dwf28bbfb9d22b0087@mail.gmail.com> Message-ID: <45635B46.80106@tds.net> Matthew Gordon wrote: > This isn't python specific, but it seems pertinent to the interests of > this list regardless. > > Defining functions inside of other functions seems conceptually neater > than defining those functions in the global environment if they're > never going to be used by anything except that one function. In terms > of efficiency though, it seems terrible to lexically scope because > each time the function is called it will have to reinstantiate the > sub-function. > > Anyone have an opinion/suggestion? It's actually pretty quick to create the nested function because the heavy work of compiling is just done once. According to Fredrik Lundh on c.l.py, "all that happens is that a new function object is created from prebuilt parts, and assigned to a local variable. it's not slower than, say, a method call." See http://tinyurl.com/ylh8g9 Kent From alan.gauld at btinternet.com Tue Nov 21 22:04:04 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Nov 2006 21:04:04 -0000 Subject: [Tutor] lexical scoping efficiency References: <2edc23690611211152m40a2384dwf28bbfb9d22b0087@mail.gmail.com> Message-ID: "Matthew Gordon" wrote > Defining functions inside of other functions ...In terms > of efficiency though, it seems terrible to lexically scope because > each time the function is called it will have to reinstantiate the > sub-function. I'm speaking from a position of profound ignorance however I'd be surprised if Python does that. I suspect that when Python first parses the function definition it will create a cached reference to the nested function, probably via a dictionary. Python is usually pretty good at creating cached references to things that don't change and unlike local variables the function definition will be the same for each invocation of the function (although there is a possibility of some clever closure behaviour rendering that invalid, but I don't think so) But I'm guessing, does anyone else know for sure? Alan G From alan.gauld at btinternet.com Tue Nov 21 22:05:35 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Nov 2006 21:05:35 -0000 Subject: [Tutor] lexical scoping efficiency References: <2edc23690611211152m40a2384dwf28bbfb9d22b0087@mail.gmail.com> <45635B46.80106@tds.net> Message-ID: "Kent Johnson" wrote > It's actually pretty quick to create the nested function because the > heavy work of compiling is just done once. Thanks Kent, I was too quick to post my reply, but what you say more or less confirms what I suspected. Alan G. From rschroev_nospam_ml at fastmail.fm Tue Nov 21 23:14:57 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 21 Nov 2006 23:14:57 +0100 Subject: [Tutor] lexical scoping efficiency In-Reply-To: References: <2edc23690611211152m40a2384dwf28bbfb9d22b0087@mail.gmail.com> Message-ID: Alan Gauld schreef: > "Matthew Gordon" wrote > >> Defining functions inside of other functions ...In terms >> of efficiency though, it seems terrible to lexically scope because >> each time the function is called it will have to reinstantiate the >> sub-function. > > I'm speaking from a position of profound ignorance however I'd be > surprised if Python does that. > > I suspect that when Python first parses the function definition > it will create a cached reference to the nested function, probably > via a dictionary. Python is usually pretty good at creating cached > references to things that don't change and unlike local variables > the function definition will be the same for each invocation of the > function (although there is a possibility of some clever closure > behaviour rendering that invalid, but I don't think so) > > But I'm guessing, does anyone else know for sure? In a recent thread on comp.lang.python Fredrik Lundh said (http://groups.google.com/group/comp.lang.python/msg/81462fcf73104d8c): "(yes, an inner function is *created* every time you execute the outer function. but it's created from prefabricated parts, so that's not a very expensive process)." -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From mrgordon at mit.edu Wed Nov 22 01:15:25 2006 From: mrgordon at mit.edu (Matthew Gordon) Date: Tue, 21 Nov 2006 19:15:25 -0500 Subject: [Tutor] lexical scoping efficiency In-Reply-To: References: <2edc23690611211152m40a2384dwf28bbfb9d22b0087@mail.gmail.com> Message-ID: <2edc23690611211615o60953319ve453642d2cf47ce6@mail.gmail.com> Interesting. I'll have to look a bit more into it. I thought it was a bit too simplistic to assume that Python would allow for me to mishandle resources so much. Thanks to all three of you! - Matt On 11/21/06, Roel Schroeven wrote: > > Alan Gauld schreef: > > "Matthew Gordon" wrote > > > >> Defining functions inside of other functions ...In terms > >> of efficiency though, it seems terrible to lexically scope because > >> each time the function is called it will have to reinstantiate the > >> sub-function. > > > > I'm speaking from a position of profound ignorance however I'd be > > surprised if Python does that. > > > > I suspect that when Python first parses the function definition > > it will create a cached reference to the nested function, probably > > via a dictionary. Python is usually pretty good at creating cached > > references to things that don't change and unlike local variables > > the function definition will be the same for each invocation of the > > function (although there is a possibility of some clever closure > > behaviour rendering that invalid, but I don't think so) > > > > But I'm guessing, does anyone else know for sure? > > In a recent thread on comp.lang.python Fredrik Lundh said > (http://groups.google.com/group/comp.lang.python/msg/81462fcf73104d8c): > > "(yes, an inner function is *created* every time you execute the outer > function. but it's created from prefabricated parts, so that's not a > very expensive process)." > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061121/74d97f97/attachment.html From nperito at gmail.com Wed Nov 22 02:03:07 2006 From: nperito at gmail.com (Nicholas Perito) Date: Wed, 22 Nov 2006 10:03:07 +0900 Subject: [Tutor] How to create delay in game In-Reply-To: <200611211157.41913.mib@mibgames.co.uk> References: <45626C4D.4060907@gmail.com> <200611211157.41913.mib@mibgames.co.uk> Message-ID: Well, that was easy! Thanks for the tip and the links--a lot of good info there. Cheers, Nic On 11/21/06, Michael Brunton-Spall wrote: > > Of all the weird things, I'm currently working for Scripture Union, i > never > knew they had made a python package for learning python, anyway... > > add > import time > > where you want to delay for a while, > time.sleep(0.1) > that will sleep for 0.1 seconds, (or try to). > > the livewires package is a wrapper around pygame, it might be worth > looking at > pygame.org to see the more powerful, underlying package. > > The livewires packages have worksheets to go with the packages, teaching > games > programing. Reference sheet T(Time) had this information in it. might be > worth checking those out if your sticking with livewires. find them at > http://www.livewires.org.uk/python/pdfsheets.html > > Michael Brunton-Spall > > On Tuesday 21 November 2006 03:02, Nicholas Perito wrote: > > Hello, > > > > I new to programming and this is my first post. I'm learning Python via > > "Python Programming for the Absolute Beginner" by Michael Dawson. I've > > written a pong game into which I want to insert a delay between sprite > > initializations. Right now, if an "Atom" sprite reaches the bottom of > > the screen, the next Atom sprite appears immediately. Instead, when the > > sprite reaches the bottom, I want the message "Two (or One) atoms left!" > > to appear for it's lifetime before the next Atom sprite appears. I've > > tried to create a delay by making it crunch numbers, but that hasn't > > worked well. > > > > Anyway, the code is below, and the place where I want to create a delay > > is marked. Oh, and constructive criticism of the code is welcome--I'm > > not too sensitive. > > > > Thanks a lot to anyone who can help! > > > > (It's called 'Atom Pong' because I had a cool graphic) > > > > # Atom Pong > > # Nic Perito 11/06 > > > > import random > > from livewires import games, color > > > > SCREEN_WIDTH = 1000 > > SCREEN_HEIGHT = 700 > > THE_SCREEN = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT) > > life = 3 > > > > class Atom(games.Sprite): > > """ Atom image """ > > > > image = games.load_image("atom.jpg") > > def __init__(self, screen, x, y, dx, dy): > > """ Initialize atom object. """ > > self.init_sprite(screen = screen, x = x, y = y, > > dx = dx, dy = dy, image = Atom.image) > > > > def moved(self): > > """ Reverse a velocity component if edge of screen reached. """ > > global life > > dx, dy = self.get_velocity() > > self.rotate_by(3) > > if self.get_right() > SCREEN_WIDTH: > > self.set_right(SCREEN_WIDTH) > > self.set_velocity(-dx, dy) > > if self.get_left() < 0: > > self.set_left(0) > > self.set_velocity(-dx, dy) > > if self.get_top() < 0: > > self.set_velocity(dx, -dy) > > if self.get_bottom() > SCREEN_HEIGHT: > > self.destroy() > > life -= 1 > > if life == 0: > > self.game_over() > > > > if life == 2: > > games.Message(screen = self.screen, > > x = 150, y = 20, > > text = "Two atoms left!", size = 40, color = > > color.yellow, > > lifetime = 200) > > #HERE'S WHERE I WANT A DELAY > > Atom(self.screen, x = (SCREEN_WIDTH - 76), y = 76, > > dx = 6, dy = 5) > > > > if life == 1: > > games.Message(screen = self.screen, > > x = 150, y = 45, > > text = "One atom left!", size = 40, color = > > color.yellow, > > lifetime = 200) > > #HERE'S WHERE I WANT A DELAY > > Atom(self.screen, x = 76, y = 76, > > dx = 6, dy = 6) > > > > def handle_deflect(self): > > """ Deflect atom. """ > > dx, dy = self.get_velocity() > > self.set_velocity(dx + random.randrange(2,4), -dy) > > > > def game_over(self): > > """ End the game. """ > > # destroy all game objects except the Text object (player's > score) > > for game_object in self.screen.all_objects(): > > if not isinstance(game_object, games.Text): > > game_object.destroy() > > > > # show 'Game Over' for 250 mainloop() cycles > > games.Message(screen = self.screen, > > x = SCREEN_WIDTH/2, y = 400, > > text = "Game Over", size = 90, color = color.red, > > lifetime = 500, after_death = self.screen.quit) > > > > class Bonus(games.Sprite): > > """ Atom bonus image """ > > image = games.load_image("bonus.jpg") > > def __init__(self, screen, x, y, dx, dy): > > """ Initialize atom object. """ > > self.init_sprite(screen = screen, x = x, y = y, > > dx = dx, dy = dy, image = Bonus.image) > > > > def moved(self): > > """ Reverse a velocity component if edge of screen reached. """ > > dx, dy = self.get_velocity() > > self.rotate_by(-3) > > if self.get_right() > SCREEN_WIDTH or self.get_left() < 0: > > self.set_velocity(-dx, dy) > > if self.get_top() < 0: > > self.set_velocity(dx, -dy) > > if self.get_bottom() > SCREEN_HEIGHT: > > self.destroy() > > def handle_deflect(self): > > """ Deflect atom. """ > > dx, dy = self.get_velocity() > > self.set_velocity(dx, -dy) > > > > > > class Paddle(games.Sprite): > > """ > > A paddle controlled by player to 'deflect' atoms. > > """ > > image = games.load_image("paddle.jpg", transparent = False) > > > > def __init__ (self, screen, x, y): > > """ Initialize paddle object. Create a Text object for player's > > score. """ > > self.init_sprite(screen = screen, x = x, y = y, image = > > Paddle.image) > > self.score_value = 0 > > self.score_text = games.Text(screen = self.screen, x = > > SCREEN_WIDTH/2, y = 20, > > text = "Score: 0", size = 25, color > > = color.white) > > > > def moved(self): > > """ Move paddle to mouse x position. """ > > x, y = self.get_pos() > > > > if self.screen.is_pressed(games.K_RIGHT): > > x += 9 > > > > if self.screen.is_pressed(games.K_LEFT): > > x -= 9 > > > > self.move_to(x,y) > > > > > > if self.get_left() < 0: > > self.set_left(0) > > if self.get_right() > SCREEN_WIDTH: > > self.set_right(SCREEN_WIDTH) > > self.check_for_impact() > > > > def check_for_impact(self): > > """ Check if paddle hits atoms. """ > > for atom in self.overlapping_objects(): > > self.handle_deflect() > > atom.handle_deflect() > > > > def handle_deflect(self): > > """ Increase and display score. """ > > > > bonus = [] > > for i in range(0, 5000, 50): > > bonus.append(i) > > self.score_value += 10 > > self.score_text.set_text("Score: " + str(self.score_value)) > > if self.score_value in bonus: > > Bonus(self.screen, x = random.randrange(800)+ 76, y = 76, > > dx = random.randrange(10)+2, dy = random.randrange(3)+ > 2) > > > > games.Message(screen = self.screen, > > x = SCREEN_WIDTH/2, y = 300, > > text = "BONUS!", size = 90, color = color.red, > > lifetime = 50) > > > > > > > > > > > > > > > > def main(): > > my_screen = THE_SCREEN > > my_screen.mouse_visible(False) > > background_image = games.load_image("black.jpg", transparent = > False) > > my_screen.set_background(background_image) > > > > > > Atom(screen = my_screen, x = 76, y = 76, > > dx = 6, dy = 5) > > > > > > Paddle(screen = my_screen, x = SCREEN_WIDTH/2, y = 690) > > > > > > my_screen.mainloop() > > > > # start program > > main() > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061122/3babdea9/attachment.htm From ke7fxl at gmail.com Wed Nov 22 04:43:47 2006 From: ke7fxl at gmail.com (Tod Haren) Date: Tue, 21 Nov 2006 19:43:47 -0800 Subject: [Tutor] Database Table Primary Keys Message-ID: <6f5b2c4e0611211943r60aa982ch36dc45b0dd0488e@mail.gmail.com> Using a DBAPI 2.0 module such as ADODBAPI, how can a I identify the primary key fields of a table. cursor.desctription doesn't hold this info, unless I'm missing something. I just don't see it in the documentation. Maybe there's an SQL statement I haven't found yet. Is this even possible? I'm sure I could get this info from ADOX and win32com, but that seems a little excessive at this stage. From gtnorton at earthlink.net Wed Nov 22 04:58:55 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Tue, 21 Nov 2006 21:58:55 -0600 Subject: [Tutor] Database Table Primary Keys In-Reply-To: <6f5b2c4e0611211943r60aa982ch36dc45b0dd0488e@mail.gmail.com> References: <6f5b2c4e0611211943r60aa982ch36dc45b0dd0488e@mail.gmail.com> Message-ID: <4563CAFF.1050500@earthlink.net> Tod Haren wrote: >Using a DBAPI 2.0 module such as ADODBAPI, how can a I identify the >primary key fields of a table. cursor.desctription doesn't hold this >info, unless I'm missing something. I just don't see it in the >documentation. Maybe there's an SQL statement I haven't found yet. > >Is this even possible? I'm sure I could get this info from ADOX and >win32com, but that seems a little excessive at this stage. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Hi Tod, When I need any kind of table meta data, I use "describe" cursor.execute("DESCRIBE table") I'm sure there are many different ways, but that's what I use. Good Luck, Glenn -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From ajkadri at googlemail.com Wed Nov 22 16:18:21 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 22 Nov 2006 15:18:21 +0000 Subject: [Tutor] I need SOAPpy documentation..... Message-ID: Hi folks, Can some one provide me with the SOAPpy documentation; I mean a kind of list of the functions available in the module and the details of those functions. Thanks in anticipation. Best Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061122/b311f6a2/attachment.htm From Tim.Golden at viacom-outdoor.co.uk Wed Nov 22 16:34:28 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 22 Nov 2006 15:34:28 -0000 Subject: [Tutor] I need SOAPpy documentation..... In-Reply-To: Message-ID: | Can some one provide me with the SOAPpy documentation; I mean | a kind of list of the functions available in the module and | the details of those functions. Come on, you can try harder than that. Have you downloaded SOAPpy? Where did you get it? If it came with your distro, Google and Feel Lucky. Go to that website. Look for the links labelled Documentation and API docs. If you choose the latter, you'll need to select one of the modules. Was that so hard? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ajkadri at googlemail.com Wed Nov 22 16:39:05 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 22 Nov 2006 15:39:05 +0000 Subject: [Tutor] I need SOAPpy documentation..... In-Reply-To: References: Message-ID: I installed fpconst, and soappy and its working fine. I dont remember how I managed to get those working.. Yeah, I definitely downloaded from the Internet. REgards, Asrarahmed On 11/22/06, Tim Golden wrote: > > | Can some one provide me with the SOAPpy documentation; I mean > | a kind of list of the functions available in the module and > | the details of those functions. > > Come on, you can try harder than that. Have you downloaded > SOAPpy? Where did you get it? If it came with your distro, > Google and Feel Lucky. Go to that website. Look for > the links labelled Documentation and API docs. If you choose > the latter, you'll need to select one of the modules. > > Was that so hard? > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061122/80d4cc2b/attachment.html From Tim.Golden at viacom-outdoor.co.uk Wed Nov 22 16:42:56 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 22 Nov 2006 15:42:56 -0000 Subject: [Tutor] I need SOAPpy documentation..... In-Reply-To: Message-ID: | Can some one provide me with the SOAPpy documentation; I mean | a kind of list of the functions available in the module and | the details of those functions. As a general rule, you can run your own local pydoc server, which will offer HTML docs on every module you have installed: python -m pydoc -p 9090 (obviously pick some other port if this clashes) Browse to http://localhost:9090 and pick your module. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From lucidmonk at gmail.com Wed Nov 22 20:26:49 2006 From: lucidmonk at gmail.com (Todd Dahl) Date: Wed, 22 Nov 2006 14:26:49 -0500 Subject: [Tutor] IIS and Virtual directories Message-ID: <44290fe50611221126h7bfd55b5m562d5519d32f019b@mail.gmail.com> I have been trying to figure out how to create an IIS Virtual Directory through Python but can't find anything that works. I have done it in the past with Perl with the script below but can't seem to figure out how to do it in Python. I was wondering if someone could point me in the right direction. Thank you, -Todd P.S."Hope everyone who reads this has a nice Thanksgiving!" ============= ########################################################################## # Description: Use ADSI to create IIS virtual # ########################################################################## use Win32::OLE; my $server = "localhost"; my $VirtualDir = "AIRAdmin"; mkdir("nhvrweb",0777); eval{ #Create WWW directory #Check if the directory already exsist if (! ($www = Win32::OLE->GetObject("IIS://$server/W3svc/1/Root/$VirtualDir"))) { $www = Win32::OLE->GetObject("IIS://$server/W3svc/1"); $vRoot = $www->GetObject("IIsWebVirtualDir", "Root"); $vDir = $vRoot->Create("IIsWebVirtualDir",$VirtualDir); $vDir->{AccessScript} = 1; $vDir->{Path} = "C:\\nhvr\\$VirtualDir"; $vDir->SetInfo(); $vDir->AppCreate(1); } }; #In case of error print Win32::OLE->LastError()."\n"if(Win32::OLE->LastError()); -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061122/ca5fe031/attachment.htm From jakieabraham at yahoo.com Thu Nov 23 07:31:31 2006 From: jakieabraham at yahoo.com (Jacob Abraham) Date: Wed, 22 Nov 2006 22:31:31 -0800 (PST) Subject: [Tutor] Mod python setup Message-ID: <20061123063131.58351.qmail@web54114.mail.yahoo.com> Hi All, I've been using Trac (http://trac.edgewall.org/) for some time you will be suprised to know that I use it along with a Clearcase repository. I've also written a small plugin that displays the MSN logs. Soon some of this code will be put into trac hacks with an open source license. Forgive me but I have a very silly question to ask on problems with my multisite mod python setup. I have two trac sites both of with have plugins with slightly different code (One navigates Base Cleacase while the other UCM Clearcase), but for some reason both sites use the plugins of the site I load first. I am aware that this issue comes from my mod python setup. Please help me with the same. I'm not too sure if this is the right forum to ask this question. My current mod python setup looks like this. LoadModule python_module modules/mod_python.so LoadModule sspi_auth_module modules/mod_auth_sspi.so SetHandler mod_python PythonHandler trac.web.modpython_frontend PythonPath "['C:\\devutil\\lib\\\tracprod'] + sys.path" PythonOption TracEnv C:\\devutil\trac\tracprod PythonOption TracUriRoot /trac AuthName "A Protected Place" AuthType SSPI SSPIAuth On SSPIAuthoritative On SSPIOfferBasic On SSPIBasicPreferred On # SSPIUsernameCase lower require valid-user SetHandler mod_python PythonHandler trac.web.modpython_frontend PythonPath "['C:\\devutil\\lib\\\tracdev'] + sys.path" PythonOption TracEnv C:\\devutil\trac\tracdev PythonOption TracUriRoot /tracdev AuthName "A Protected Place" AuthType SSPI SSPIAuth On SSPIAuthoritative On SSPIOfferBasic On SSPIBasicPreferred On # SSPIUsernameCase lower require valid-user Thanking You. Regards, Jacob Abraham From bashu at yandex.ru Thu Nov 23 07:01:43 2006 From: bashu at yandex.ru (Basil Shubin) Date: Thu, 23 Nov 2006 12:01:43 +0600 Subject: [Tutor] Python and ODS Message-ID: <45653947.7030706@yandex.ru> Hi friends! Is there any extension or library to create/write data in OpenDocument Spreadsheet? I found pyExcelerator, but it's working only with xls format. -- Basil Shubin Freelance Software Developer From Tim.Golden at viacom-outdoor.co.uk Thu Nov 23 09:17:04 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Nov 2006 08:17:04 -0000 Subject: [Tutor] IIS and Virtual directories In-Reply-To: <44290fe50611221126h7bfd55b5m562d5519d32f019b@mail.gmail.com> Message-ID: | I have been trying to figure out how to create an IIS Virtual | Directory through Python but can't find anything that works. | I have done it in the past with Perl with the script below | but can't seem to figure out how to do it in Python. I was | wondering if someone could point me in the right direction. | | Thank you, | -Todd | | P.S."Hope everyone who reads this has a nice Thanksgiving!" Caveat: I don't run IIS myself, so I'm working on paper here. Couple of starting points. Basically everything you're doing there looks like it could be handled by the win32com.client module of the pywin32 extensions. (Looks like an almost literal translation). Vague code example: from win32com.client import GetObject virtual_dir = GetObject ("IIS://blah/blah") virtual_dir.DoStuff ("param1", "param2") As an alternative, you might be able to use WMI (altho' I'm not sure why you'd want to if you could use the technique above). Still, for completeness, here's a reference. http://tgolden.sc.sabren.com/python/wmi_cookbook.html#create_iis_site TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From rdm at rcblue.com Thu Nov 23 11:07:17 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 23 Nov 2006 02:07:17 -0800 Subject: [Tutor] help with Tkinter, please Message-ID: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> I think I see how to make a simple GUI with Tkinter, but I still don't see how to use one with even a simple, previously non-GUI Python script. I'm wondering if someone could create an example for me, using the 2 functions fact() and printFact() at . I'm thinking of something really plain and simple. A frame widget, an entry widget, and a text widget. The user enters an integer n (which can be very large), and the text widget shows n! in 2 formats, as the output of a modified printFact(). Maybe a button is also necessary? Thanks very much, Dick Moores From chris.arndt at web.de Thu Nov 23 14:09:27 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 23 Nov 2006 14:09:27 +0100 Subject: [Tutor] Python and ODS In-Reply-To: <45653947.7030706@yandex.ru> References: <45653947.7030706@yandex.ru> Message-ID: <45659D87.3050505@web.de> (sorry, did only send this to the OP first, now re-sending to list) Basil Shubin schrieb: > Hi friends! > > Is there any extension or library to create/write data in OpenDocument > Spreadsheet? I found pyExcelerator, but it's working only with xls format. How about pyUno? http://udk.openoffice.org/python/python-bridge.html Chris From ajkadri at googlemail.com Thu Nov 23 15:14:59 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 23 Nov 2006 14:14:59 +0000 Subject: [Tutor] How to make the label left justified in a frame Message-ID: Hi Folks, I am using grid manager inside a frame to arrange 4 label widgets, one beneath the other. What I want is that all teh labels should be placed in the left of the frame... There is no effect of using sticky = W. Please help ; is it possible to do it with anchor..??? I have the follwng code: frame3 = Frame(root,relief='sunken',bd=2) frame3.pack(fill='x') label_st_date = Label(frame3,text='Start Date:',font=font_object2) label_st_date.grid(row=0) label_ed_date = Label(frame3,text='End Date:') label_ed_date.grid(row=1,sticky=W) label_st_time = Label(frame3,text='Start Time:') label_st_time.grid(row=3,sticky=W) label_ed_time = Label(frame3,text='End Time:') label_ed_time.grid(row=4) Best Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061123/b339a7df/attachment.htm From klappnase at freenet.de Thu Nov 23 17:01:35 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 23 Nov 2006 17:01:35 +0100 Subject: [Tutor] help with Tkinter, please In-Reply-To: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> Message-ID: <20061123170135.3bf74dff.klappnase@freenet.de> On Thu, 23 Nov 2006 02:07:17 -0800 Dick Moores wrote: > I think I see how to make a simple GUI with Tkinter, but I still > don't see how to use one with even a simple, previously non-GUI > Python script. I'm wondering if someone could create an example for > me, using the 2 functions fact() and printFact() at > . I'm thinking of something > really plain and simple. A frame widget, an entry widget, and a text > widget. The user enters an integer n (which can be very large), and > the text widget shows n! in 2 formats, as the output of a modified > printFact(). Maybe a button is also necessary? > Hi Dick, assuming the functions you want to use are in a separate module "fact.py", a simple (and dirty) solution might look like from Tkinter import * import fact root = Tk() entry = Entry(root) entry.pack(side='top') text = Text(root) text.pack(side='top') # now you need a callback that calls fact() and inserts the result into the text widget def compute_fact(): value = int(entry_get()) result = fact.fact(value) newtext = 'Result: %d\n' % result# change this to the output format you wish text.insert('end', result) button = Button(root, text="Compute fact", command=compute_fact) button.pack(side='top') root.mainloop() In case you do not want an extra button, you can bind the compute_fact() callback to Key-Return events for the entry: entry.bind('', compute_fact) however you will have to change the callback's constructor to accept an event object as argument: def compute_fact(event): (...) or : def compute_fact(event=None): (...) which allows both. In case you want the output formatting done in the fact module, change the printFact() function, so that it *returns* a string instead of printing it to stdout, so you can use a callback like: def compute_fact(event=None): text.insert('end', fact.printFact(int(entry.get()))) I hope this helps Michael From klappnase at freenet.de Thu Nov 23 17:15:10 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 23 Nov 2006 17:15:10 +0100 Subject: [Tutor] How to make the label left justified in a frame In-Reply-To: References: Message-ID: <20061123171510.1bb3df9b.klappnase@freenet.de> On Thu, 23 Nov 2006 14:14:59 +0000 "Asrarahmed Kadri" wrote: > Hi Folks, > > I am using grid manager inside a frame to arrange 4 label widgets, one > beneath the other. > > What I want is that all teh labels should be placed in the left of the > frame... > > There is no effect of using sticky = W. > > Please help ; is it possible to do it with anchor..??? > > I have the follwng code: > > > frame3 = Frame(root,relief='sunken',bd=2) > frame3.pack(fill='x') > label_st_date = Label(frame3,text='Start Date:',font=font_object2) > label_st_date.grid(row=0) > label_ed_date = Label(frame3,text='End Date:') > label_ed_date.grid(row=1,sticky=W) > > label_st_time = Label(frame3,text='Start Time:') > label_st_time.grid(row=3,sticky=W) > label_ed_time = Label(frame3,text='End Time:') > label_ed_time.grid(row=4) Hi Asrarahmed, sticky=W does put the labels to the frame's left side; the problem is that the frame's grid column does not expand beyond the requested size of the labels. To fix this, you need to call: frame3.grid_columnconfigure(0, weight=1) (similar to pack(fill=X, expand=True)). I hope this helps Michael From dyoo at hkn.eecs.berkeley.edu Thu Nov 23 18:33:24 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 Nov 2006 09:33:24 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 33, Issue 84 In-Reply-To: References: Message-ID: > I think I see how to make a simple GUI with Tkinter, but I still > don't see how to use one with even a simple, previously non-GUI > Python script. I'm wondering if someone could create an example for > me, using the 2 functions fact() and printFact() at > . Hi Dick, I wrote a tutorial that may help, but unfortunately, at the moment, it's not in Python, but rather uses PLT Scheme's MrEd framework. http://hkn.eecs.berkeley.edu/~dyoo/plt/mr-ed-notes.txt The concepts should translate somewhat, though. When I have time, I'll adapt the core content to use Python and Tkinter for you. It gives a brief, simple example, followed by a more slightly interesting calculator example, both using a Model-View-Controller technique to organize the code. From rdm at rcblue.com Thu Nov 23 22:08:40 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 23 Nov 2006 13:08:40 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: <20061123170135.3bf74dff.klappnase@freenet.de> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> Message-ID: <7.0.1.0.2.20061123130300.01f41170@rcblue.com> At 08:01 AM 11/23/2006, Michael Lange wrote: >On Thu, 23 Nov 2006 02:07:17 -0800 >Dick Moores wrote: > > > I think I see how to make a simple GUI with Tkinter, but I still > > don't see how to use one with even a simple, previously non-GUI > > Python script. I'm wondering if someone could create an example for > > me, using the 2 functions fact() and printFact() at > > . I'm thinking of something > > really plain and simple. A frame widget, an entry widget, and a text > > widget. The user enters an integer n (which can be very large), and > > the text widget shows n! in 2 formats, as the output of a modified > > printFact(). Maybe a button is also necessary? > > > >Hi Dick, > >assuming the functions you want to use are in a separate module "fact.py", >a simple (and dirty) solution might look like > >from Tkinter import * >import fact > >root = Tk() >entry = Entry(root) >entry.pack(side='top') >text = Text(root) >text.pack(side='top') > ># now you need a callback that calls fact() and inserts the result >into the text widget >def compute_fact(): > value = int(entry_get()) > result = fact.fact(value) > newtext = 'Result: %d\n' % result# change this to the output > format you wish > text.insert('end', result) > >button = Button(root, text="Compute fact", command=compute_fact) >button.pack(side='top') >root.mainloop() > >In case you do not want an extra button, you can bind the >compute_fact() callback >to Key-Return events for the entry: > >entry.bind('', compute_fact) > >however you will have to change the callback's constructor to accept >an event object >as argument: > >def compute_fact(event): > (...) > >or : > >def compute_fact(event=None): > (...) > >which allows both. > >In case you want the output formatting done in the fact module, >change the printFact() function, >so that it *returns* a string instead of printing it to stdout, so >you can use a callback like: > >def compute_fact(event=None): > text.insert('end', fact.printFact(int(entry.get()))) Thanks very much, Michael. OK, here's my attempt, using my fact(), but not printFact(): ============================================ from Tkinter import * def fact(n): """ compute n! This is faster than the often-seen factorial function using recursion """ product = 1 while n > 1: product *= n n -= 1 return product root = Tk() entry = Entry(root) entry.pack(side='top') text = Text(root) text.pack(side='top') # now you need a callback that calls fact() and inserts the result into the text widget def compute_fact(): value = int(entry_get()) result = fact(value) newtext = 'Result: %d\n' % result# change this to the output format you wish text.insert('end', result) button = Button(root, text="Compute fact", command=compute_fact) button.pack(side='top') root.mainloop() ===================================================== I entered an integer, pressed the button "Compute fact", and got the error, E:\Python25\dev\Tkinter>python factTk1-a.py Exception in Tkinter callback Traceback (most recent call last): File "E:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "factTk1-a.py", line 22, in compute_fact value = int(entry_get()) NameError: global name 'entry_get' is not defined I'm so dumb I don't see how to define it. Dick From alan.gauld at btinternet.com Thu Nov 23 22:37:02 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Nov 2006 21:37:02 -0000 Subject: [Tutor] help with Tkinter, please References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com><20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> Message-ID: "Dick Moores" wrote > def compute_fact(): > value = int(entry_get()) > File "factTk1-a.py", line 22, in compute_fact > value = int(entry_get()) > NameError: global name 'entry_get' is not defined > > I'm so dumb I don't see how to define it. get is a method of the Entry widget. So the syntax is entry.get() not entry_get. HTH, Alan G. From ajkadri at googlemail.com Thu Nov 23 22:40:39 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 23 Nov 2006 21:40:39 +0000 Subject: [Tutor] Help with the following code.. Message-ID: Hi all, Trying to draw a simple bar chart on canvas of Tkinter. Here is code: from Tkinter import * root = Tk() frame = Frame(root) frame.pack() canvas = Canvas(frame,height=400,width=400) canvas.create_line(50,350,350,350,width=2) # draws the X-axis canvas.create_line(50,350,50,50,width=2) # draws teh Y-axis canvas.create_rectangle(50,340,250,330) # this is the first HORIZONTAL BAR canvas.pack() root.mainloop() I am not able to understand why two pairs of co-ordinates are supplied?? The rectangle requires 4 co-ordinate pairs, Isnt it?? Also help me how to figure out the co-ordinate pairs of next bar ?? TIA. BEst Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061123/fb58570e/attachment.htm From john at fouhy.net Thu Nov 23 23:01:57 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 24 Nov 2006 11:01:57 +1300 Subject: [Tutor] Help with the following code.. In-Reply-To: References: Message-ID: <5e58f2e40611231401s598f5f03j5f0e2e93396075bc@mail.gmail.com> On 24/11/06, Asrarahmed Kadri wrote: > canvas.create_rectangle(50,340,250,330) # this is the first HORIZONTAL BAR > canvas.pack () > > root.mainloop() > I am not able to understand why two pairs of co-ordinates are supplied?? The > rectangle requires 4 co-ordinate pairs, Isnt it?? Hmm, I was going to refer you to Fredrik Lundh's docs, but they're a bit thin on the ground (http://www.pythonware.com/library/tkinter/introduction/canvas.htm). I can think of two possibilities: 1. The arguments represent the top-left and bottom-right corners of the rectangle. eg, if you call create_rectangle(x0, y0, x1, y1) then the corners will be: (x0, y0) (x1, y0) (x1, y1) (x0, y1) 2. The arguments represent the top-left corner and the width and height. eg, if you call create_rectangle(x0, y0, w, h) then the corners will be: (x0, y0) (x0+w, y0) (x0+w, y0+h) (x0, y0+h) I suggest experimenting to figure out which... -- John. From bgailer at alum.rpi.edu Thu Nov 23 23:29:26 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 23 Nov 2006 14:29:26 -0800 Subject: [Tutor] Help with the following code.. In-Reply-To: References: Message-ID: <456620C6.2010808@alum.rpi.edu> Asrarahmed Kadri wrote: > > Hi all, > > > Trying to draw a simple bar chart on canvas of Tkinter. > > Here is code: > > > from Tkinter import * > > root = Tk() > > frame = Frame(root) > frame.pack() > > canvas = Canvas(frame,height=400,width=400) > > canvas.create_line(50,350,350,350,width=2) # draws the X-axis > canvas.create_line(50,350,50,50,width=2) # draws teh Y-axis > canvas.create_rectangle(50,340,250,330) # this is the first > HORIZONTAL BAR > canvas.pack () > > root.mainloop() > > I am not able to understand why two pairs of co-ordinates are > supplied?? The rectangle requires 4 co-ordinate pairs, Isnt it?? Don't you have any Tkinter documentation? One reference I have says: "6.9. The canvas rectangle object - Each rectangle is specified as two points: (x0, y0) is the top left corner, and (x1, y1) is the bottom right corner." I highly advise you get a reference. The Tkinter module document under the Python Manuals - Global Module Index lists several. BTW how can you write code without a reference? Are you copying examples? -- Bob Gailer 510-978-4454 From alan.gauld at btinternet.com Fri Nov 24 00:06:20 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Nov 2006 23:06:20 -0000 Subject: [Tutor] Help with the following code.. References: <456620C6.2010808@alum.rpi.edu> Message-ID: "Bob Gailer" wrote > Asrarahmed Kadri wrote: >> I am not able to understand why two pairs of co-ordinates are >> supplied?? The rectangle requires 4 co-ordinate pairs, Isnt it?? > "6.9. The canvas rectangle object - Each rectangle is specified as > two > points: (x0, y0) is the top left corner, and (x1, y1) is the bottom > right > corner." As Bob says it only needs 2 points because by definition a rectangle has the same x value for the two left corners and the same y values for the two top corners so only 4 values are required not 4 points. And the 4 values can be achieved by specifying a pair of opposite corner coordinates. So if Top Left is x1,y1 and Bottom Right is x2,y2 then Top Right must be x2,y1 and Bottom Left will be x1,y2 So from two corners Tkinter can derive the rest > I highly advise you get a reference. The Tkinter module document > under > the Python Manuals - Global Module Index lists several. BTW how can > you > write code without a reference? Are you copying examples? I think he has a reference but just couldn't see how you could draw a 4 cornered shape with only two corners specified. At least, that's how I read his post. Alan G. From bgailer at alum.rpi.edu Fri Nov 24 04:01:21 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 23 Nov 2006 19:01:21 -0800 Subject: [Tutor] Help with the following code.. In-Reply-To: References: <456620C6.2010808@alum.rpi.edu> Message-ID: <45666081.7050405@alum.rpi.edu> Alan Gauld wrote: > I think he has a reference but just couldn't see how you could draw > a 4 cornered shape with only two corners specified. > And I assumed no reference, since references usually spell out the meaning of parameters. -- Bob Gailer 510-978-4454 From Dean.Gardner at barco.com Fri Nov 24 10:39:32 2006 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Fri, 24 Nov 2006 09:39:32 -0000 Subject: [Tutor] (no subject) Message-ID: Hi I was wondering if anyone knew how to control the desktop resolution via python. I have investigated pygame which seems to allow you acces to video settings but it appears to only influence a window rather than the system (I may be totally wrong about this though) What I ideally need is a small app that will swap resolution between 1600*1200 and 1280*1024 Thanks Dean Gardner Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com dean.gardner at barco.com DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061124/9ae16a36/attachment.htm From arildna at stud.ntnu.no Fri Nov 24 10:29:35 2006 From: arildna at stud.ntnu.no (arildna at stud.ntnu.no) Date: Fri, 24 Nov 2006 10:29:35 +0100 Subject: [Tutor] a question about indentation Message-ID: <4566BB7F.304@stud.ntnu.no> Hi, I'm fairly new to python, and trying to get used to the indentation. I just encountered my first problem with it. I wrote the following code: for ord in f_ord: if not ordliste.has_key(ord) : ordliste[ord] = {} for word in e_ord: if ordliste[ord].has_key(word) : ordliste[ord][word] += 1 else : ordliste[ord][word] = 1 and then later realized I had to put in one more if-test at the beginning of the loop. In most languages I've used, this would be simple -- I would simply enclose lines 2-8 in curly braces and put the if-test in front. When I try do it in python, however, it seems I have to do the indentation all over. If I just put in the if-test, and try to indent all of the lines one step inwards, I get the following result: for ord in f_ord: if not ord in tegn: if not ordliste.has_key(ord) : ordliste[ord] = {} for word in e_ord: if ordliste[ord].has_key(word) : ordliste[ord][word] += 1 else : ordliste[ord][word] = 1 which is of course not what I'm after. I want to preserve the expression in the outer for-loop, and just put an if-test in front. This isn't really a problem in this case, as the expression is quite small, and I can quickly check the indentation line by line. But I can't begin to imagine what a hassle that would be if my expression was 70 lines and not 7. I suppose there is a good way to do indent whole blocks like this, but I haven't found out what it is. Could anybody help me out? Thanks, Arild N?ss From Tim.Golden at viacom-outdoor.co.uk Fri Nov 24 11:04:45 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 24 Nov 2006 10:04:45 -0000 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: [Gardner, Dean] | I was wondering if anyone knew how to control the desktop | resolution via python. I have investigated pygame which seems | to allow you acces to video settings but it appears to only | influence a window rather than the system (I may be totally | wrong about this though) | | What I ideally need is a small app that will swap resolution | between 1600*1200 and 1280*1024 I haven't tried it, but a bit of poking around suggests that you want to look at the ChangeDisplaySettingsEx API call, exposed by pywin32 (or via ctypes if you prefer). That in turn will probably mean learning the all-embracing DEVMODE structure, and things like Display Devices. Should be possible with a bit of experimentation, for which I'm afraid I don't have time at the moment. With this kind of question, it's almost always worth looking around the MS newgroups and Delphi forums. Someone's bound to have asked the question already; it's just a question of translating the answer into Python! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From antonioskatsikadamos at yahoo.com Fri Nov 24 11:09:11 2006 From: antonioskatsikadamos at yahoo.com (Antonios Katsikadamos) Date: Fri, 24 Nov 2006 02:09:11 -0800 (PST) Subject: [Tutor] cursor.description Message-ID: <20061124100911.67225.qmail@web58103.mail.re3.yahoo.com> Hi all. I am new to python and i am trying to execute queries from postgres db. I have a question. What is exactly the operation of cursor.description? Kind regards, Antonios --------------------------------- Sponsored Link Mortgage rates near 39yr lows. $420,000 Mortgage for $1,399/mo - Calculate new house payment -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061124/8a6423b5/attachment.htm From aymchaos at yahoo.com Fri Nov 24 11:49:38 2006 From: aymchaos at yahoo.com (Mihai Iacob) Date: Fri, 24 Nov 2006 02:49:38 -0800 (PST) Subject: [Tutor] Having trouble with " table % listTable.values() " line Message-ID: <310525.14120.qm@web32701.mail.mud.yahoo.com> Hello, This is my first post so if i make any kind of mistakes take it easy on me :). I don't know how to explain clearly what is the problem but i'll try. table = """ %s |%s |%s ----------- %s |%s |%s ----------- %s |%s |%s """ listTable is a dictionary. listTable = {0 :'X', 1 :' ' , 2 :' ', 3 :'O', 4 :' ', 5 :' ', 6 :'O', 7 :' ', 8 :'X',} I am trying to take the values from the dictionary listTable.values() and print them in the table. The problem is that listTable.values() returns a list " ['X', ' ', ' ', 'O', ' ', ' ', 'O', ' ', 'X'] " and python won't assign the values of the dictionary in the table. " table % listTable.values() " This error message appears: Traceback (most recent call last): File "", line 1, in table % listTable.values() TypeError: not enough arguments for format string So instead of the list " ['X', ' ', ' ', 'O', ' ', ' ', 'O', ' ', 'X'] " which won't let me assign strings in the table, i want to get ('X', ' ', ' ', 'O', ' ', ' ', 'O', ' ', 'X') from listTable.values() I know i can make it work using: table % (listTable[0],listTable[1], listTable[2],listTable[3],listTable[4], listTable[5],listTable[6],listTable[7],listTable[8]) but it's kinda long. If somebody can tell me how to convert the []list into () i'll make him a little shrine and worship him for 5 seconds :P I'm trying to make a OXO game, so don't give me any hints even if you spot mistakes (i hope i can make it alone) ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com From klappnase at freenet.de Fri Nov 24 12:56:47 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 24 Nov 2006 12:56:47 +0100 Subject: [Tutor] How to make the label left justified in a frame In-Reply-To: References: <20061123171510.1bb3df9b.klappnase@freenet.de> Message-ID: <20061124125647.091f059b.klappnase@freenet.de> -- Forwarded to tutor list -- On Thu, 23 Nov 2006 16:25:41 +0000 "Asrarahmed Kadri" wrote: > Sorry to bother you, > But can u please explain what does grid_columnconfigure() do.. > > The best place for questions like this are usually the Tk man pages :) Once you get used to them it is easy to figure out how to "translate" them into Python. >From the grid manpage: grid columnconfigure master index ?-option value...? (...) The -weight option (an integer value) sets the relative weight for apportioning any extra spaces among columns. A weight of zero (0) indicates the column will not deviate from its requested size. A column whose weight is two will grow at twice the rate as a column of weight one when extra space is allocated to the layout. (...) So if you have a Frame f and do: f.grid_columnconfigure(0, weight=0) f.grid_columnconfigure(1, weight=2) f.grid_columnconfigure(2, weight=1) column 0 will not expand at all when the frame is stretched horizontally, column 2 will expand and column 1 will expand even more. I hope this helps Michael From klappnase at freenet.de Fri Nov 24 12:59:18 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 24 Nov 2006 12:59:18 +0100 Subject: [Tutor] help with Tkinter, please In-Reply-To: <7.0.1.0.2.20061123130300.01f41170@rcblue.com> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> Message-ID: <20061124125918.2b2d9f43.klappnase@freenet.de> On Thu, 23 Nov 2006 13:08:40 -0800 Dick Moores wrote: > >def compute_fact(): > > value = int(entry_get()) Ooops, sorry for the typo, of course it is entry.get() not entry_get() Michael From chris.arndt at web.de Fri Nov 24 13:59:25 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Fri, 24 Nov 2006 13:59:25 +0100 Subject: [Tutor] a question about indentation In-Reply-To: <4566BB7F.304@stud.ntnu.no> References: <4566BB7F.304@stud.ntnu.no> Message-ID: <4566ECAD.80606@web.de> arildna at stud.ntnu.no schrieb: > I suppose there is a good way to do indent whole blocks like this, but I > haven't found out what it is. Could anybody help me out? Yes, get a good source code editor that has the ability to (de)indent whole blocks of code with one keystroke. This is a must-have for writing Python code! But every decent editor or IDE should have this capability. I, for example, use SciTE (http://scintilla.org/SciTE.html), where you can use the TAB key to indent and Shift-TAB to de-indent. Chris From arildna at stud.ntnu.no Fri Nov 24 14:30:33 2006 From: arildna at stud.ntnu.no (arildna at stud.ntnu.no) Date: Fri, 24 Nov 2006 14:30:33 +0100 Subject: [Tutor] a question about indentation In-Reply-To: <4566ECAD.80606@web.de> References: <4566BB7F.304@stud.ntnu.no> <4566ECAD.80606@web.de> Message-ID: <4566F3F9.8020000@stud.ntnu.no> Christopher Arndt wrote: > arildna at stud.ntnu.no schrieb: > >> I suppose there is a good way to do indent whole blocks like this, but I >> haven't found out what it is. Could anybody help me out? >> > > Yes, get a good source code editor that has the ability to (de)indent whole > blocks of code with one keystroke. This is a must-have for writing Python code! > But every decent editor or IDE should have this capability. > Thanks. I use emacs, and now I found the ability (it helps knowing what to look for). It takes a couple of keystrokes, but it works. regards, Arild N?ss From jason.massey at gmail.com Fri Nov 24 15:04:40 2006 From: jason.massey at gmail.com (Jason Massey) Date: Fri, 24 Nov 2006 08:04:40 -0600 Subject: [Tutor] Having trouble with " table % listTable.values() " line In-Reply-To: <310525.14120.qm@web32701.mail.mud.yahoo.com> References: <310525.14120.qm@web32701.mail.mud.yahoo.com> Message-ID: <7e3eab2c0611240604t59c66b07p3003eca92687162b@mail.gmail.com> So you want to convert a list into a tuple. Here ya go, using your example of the table setup: >>> raw_table =""" %s | %s | %s -------------- %s | %s | %s -------------- %s | %s | %s """ >>> from random import choice >>> x_o = [choice(['x','o']) for i in range(9)] >>> x_o ['x', 'x', 'x', 'x', 'o', 'o', 'o', 'x', 'x'] >>> filled_table = raw_table % tuple(x_o) >>> print filled_table x | x | x -------------- x | o | o -------------- o | x | x >>> On 11/24/06, Mihai Iacob wrote: > > Hello, > > This is my first post so if i make any kind of > mistakes take it easy on me :). > > I don't know how to explain clearly what is the > problem but i'll try. > table = """ > %s |%s |%s > ----------- > %s |%s |%s > ----------- > %s |%s |%s > """ > > listTable is a dictionary. > > listTable = {0 :'X', 1 :' ' , 2 :' ', 3 :'O', 4 :' ', > 5 :' ', 6 :'O', 7 :' ', 8 :'X',} > > I am trying to take the values from the dictionary > listTable.values() and print them in the table. > > The problem is that listTable.values() returns a list > " ['X', ' ', ' ', 'O', ' ', ' ', 'O', ' ', 'X'] " > and python won't assign the values of the dictionary > in the table. " table % listTable.values() " > > This error message appears: > > Traceback (most recent call last): > File "", line 1, in > table % listTable.values() > TypeError: not enough arguments for format string > > > So instead of the list " ['X', ' ', ' ', 'O', ' ', ' > ', 'O', ' ', 'X'] " which won't let me assign strings > in the table, i want to get ('X', ' ', ' ', 'O', ' ', > ' ', 'O', ' ', 'X') from listTable.values() > > I know i can make it work using: > table % (listTable[0],listTable[1], > listTable[2],listTable[3],listTable[4], > listTable[5],listTable[6],listTable[7],listTable[8]) > > but it's kinda long. > > > If somebody can tell me how to convert the []list into > () i'll make him a little shrine and worship him for 5 > seconds :P > > I'm trying to make a OXO game, so don't give me any > hints even if you spot mistakes (i hope i can make it > alone) > > > > > > > ____________________________________________________________________________________ > Do you Yahoo!? > Everyone is raving about the all-new Yahoo! Mail beta. > http://new.mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061124/d3cbb8b3/attachment.html From Tim.Golden at viacom-outdoor.co.uk Fri Nov 24 15:49:57 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 24 Nov 2006 14:49:57 -0000 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: [Gardner, Dean] | I was wondering if anyone knew how to control the desktop | resolution via python. | | What I ideally need is a small app that will swap resolution | between 1600*1200 and 1280*1024 OK. Had a bit of time to look into this. The following code snippet is (hopefully) fairly self-explanatory, the only exception being the mild shenanigans one has to go through to pick a display mode. Let's assume your two "keys" are: Depth: 32 Freq: 70 Width: 1600 <-> 1280 Height: 1200 <-> 1024 First, find your display modes: import os, sys import win32api import win32con import pywintypes display_modes = {} n = 0 while True: try: devmode = win32api.EnumDisplaySettings (None, n) except pywintypes.error: break else: key = ( devmode.BitsPerPel, devmode.PelsWidth, devmode.PelsHeight, devmode.DisplayFrequency ) display_modes[key] = devmode n += 1 You now have a dictionary [display_modes], keyed on the height, width and depth needed. All you have to do to switch is something like this: mode_required = (32, 1600, 1280, 70) devmode = display_modes[mode_required] win32api.ChangeDisplaySettings (devmode, 0) # # ... time passes # mode_required = (32, 1280, 1024, 70) devmode = display_modes[mode_required] win32api.ChangeDisplaySettings (devmode, 0) and so on. Obviously, this is *very* bare bones, (and untested) but it should get you started. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ajkadri at googlemail.com Fri Nov 24 17:03:45 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 24 Nov 2006 16:03:45 +0000 Subject: [Tutor] One question...... Message-ID: Hi Folks, I am constructing a bar-chart using Tkinter. The function takes a list 'data' and draws horizontal bar for each value. Now what I want is the the canvas widget should be able to handle variable number of data-items. I cannot figure out how to do that, because I have hard coded the lengths of X and Y axes. I want to make the entire function a lot more flexible so that it determines the length of both the axes on the basis of data supplied to it. Do you know how can I get around with this issue. The code for bar-chart is as under: from Tkinter import * import tkFont def draw_rect(canvas,data,x1,y1,x2,y2): f_obj = tkFont.Font(family='Arial',size=7,slant='italic') l = len(data) for i in data: y1 = y1 - 30 x2 = x1 + (3 * i) y2 = y2 - 30 canvas.create_rectangle(x1,y1,x2,y2) canvas.create_text(x2+5,y2,text=i,font=f_obj,anchor=NW) canvas.create_text(105,y1,text='21-11 at 12:00:00',font=f_obj) data = [10,20,100,0,50,40,30,79] root = Tk() frame = Frame(root) frame.pack() canvas = Canvas(frame,height=500,width=500) canvas.create_line(150,350,450,350,width=2) # X-axis canvas.create_line(150,350,150,50,width=2) # Y-axis canvas.pack() draw_rect(canvas,data,x1=150,y1=340,x2=250,y2=330) root.mainloop() Thanks a lot. Best Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061124/43566afb/attachment.html From Tim.Golden at viacom-outdoor.co.uk Fri Nov 24 17:18:47 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 24 Nov 2006 16:18:47 -0000 Subject: [Tutor] cursor.description In-Reply-To: <20061124100911.67225.qmail@web58103.mail.re3.yahoo.com> Message-ID: [Antonios Katsikadamos] | Hi all. I am new to python and i am trying to execute queries | from postgres db. I have a question. | | What is exactly the operation of cursor.description? Ultimately, the doc you want to look at is this: http://www.python.org/dev/peps/pep-0249/ Here's the relevant bit: """ .description This read-only attribute is a sequence of 7-item sequences. Each of these sequences contains information describing one result column: (name, type_code, display_size, internal_size, precision, scale, null_ok). The first two items (name and type_code) are mandatory, the other five are optional and must be set to None if meaningfull values are not provided. This attribute will be None for operations that do not return rows or if the cursor has not had an operation invoked via the executeXXX() method yet. The type_code can be interpreted by comparing it to the Type Objects specified in the section below. """ In practise, this means that, once a cursor's executed, you can read the names/types of columns returned from the description tuple. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From dyoo at hkn.eecs.berkeley.edu Fri Nov 24 20:20:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 Nov 2006 11:20:31 -0800 (PST) Subject: [Tutor] a question about indentation In-Reply-To: References: Message-ID: > I'm fairly new to python, and trying to get used to the indentation. I > just encountered my first problem with it. I wrote the following code: > > for ord in f_ord: > if not ordliste.has_key(ord) : > ordliste[ord] = {} > for word in e_ord: > if ordliste[ord].has_key(word) : > ordliste[ord][word] += 1 > else : > ordliste[ord][word] = 1 > > and then later realized I had to put in one more if-test at the > beginning of the loop. In most languages I've used, this would be simple > -- I would simply enclose lines 2-8 in curly braces and put the if-test > in front. Hi Arild, Try using functions more. Well-written functions can help to support the kind of rapid changes that you're making to your program, and to reduce the nesting that you're seeing. Concretely, there's a block in the code that updates the dictionary data structure. > if not ordliste.has_key(ord) : > ordliste[ord] = {} > for word in e_ord: > if ordliste[ord].has_key(word) : > ordliste[ord][word] += 1 > else : > ordliste[ord][word] = 1 We can turn that block into a full-fledged function: ################################################ def update_ordliste(ordliste, ord, words): if not ordliste.has_key(ord): ordliste[ord] = {} for word in words: if ordliste[ord].has_key(word) : ordliste[ord][word] += 1 else: ordliste[ord][word] = 1 ################################################ (There is actually a nicer way to write update_ordliste, but I'll leave that for another time.) Once we have this, we can revisit the original code, and turn: > for ord in f_ord: > if not ordliste.has_key(ord) : > ordliste[ord] = {} > for word in e_ord: > if ordliste[ord].has_key(word) : > ordliste[ord][word] += 1 > else : > ordliste[ord][word] = 1 into: ######################################### for ord in f_ord: update_ordliste(ordliste, ord, e_ord) ######################################### This code is in a form that should be easier to change more rapidly, since the block is itself not too nested or long. The general idea is that, when we have a for loop on a fairly long and substantial block, there's often a name we can give to the concept that it's doing. "update_ordliste" is not such a good, descriptive name, though: if you can think of a better name, please feel free to change it. *grin* > When I try do it in python, however, it seems I have to do the > indentation all over. With the refactored code above, we can support this kind of change with very little work: ############################################# for ord in f_ord: if not ord in tegn: update_ordliste(ordliste, ord, e_ord) ############################################# > This isn't really a problem in this case, as the expression is quite > small, and I can quickly check the indentation line by line. But I can't > begin to imagine what a hassle that would be if my expression was 70 > lines and not 7. Text editors for Python often support indenting whole blocks. If you're using Emacs, for example, "C-c >" should indent a block forward. I'm sure that other Python-aware text editors provide similar tools. What IDE are you using? You bring up a good point that it's a hassle to adjust long blocks of code. One way to attack this problem is to avoid it altogether: it's often very possible to refactor the code to make code blocks smaller or simpler. From rabidpoobear at gmail.com Fri Nov 24 22:03:04 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 24 Nov 2006 15:03:04 -0600 Subject: [Tutor] One question...... In-Reply-To: References: Message-ID: <45675E08.1080908@gmail.com> Asrarahmed Kadri wrote: > > > Hi Folks, > > I am constructing a bar-chart using Tkinter. The function takes a list > 'data' and draws horizontal bar for each value. > Now what I want is the the canvas widget should be able to handle > variable number of data-items. I cannot figure out how to do that, > because I have hard coded the lengths of X and Y axes. I want to make > the entire function a lot more flexible so that it determines the > length of both the axes on the basis of data supplied to it. #disclaimer Note: I didn't realize you said horizontal bar charts. This does vertical bar charts. It should be trivial to change this. Sorry for not reading your post more carefully to begin with. #for width >>> data = [1,5,6,7,8,3,2,9] >>>target_width = 600 >>>padding = 10 >>>num_of_data_items = len(data) >>>individual_width =( target_width-(padding*(num_of_data_items-1)))/num_of_data_items >>>individual_width 66 >>>individual_width*num_of_data_items 528 >>>padding* (len(data)-1) 70 >>>528 + 70 598 #for height >>>target_height = 600 >>> maxval = max(yvals) >>> for item in yvals: print int((float(item)/maxval) * target_height) 66 333 400 466 533 200 133 600 Did you honestly try to think this through before posting? It's a very simple concept. Not trying to be mean, just frank. I think you could've done this on your own if you had tried. Good luck with your bar charts. :) When you ask a question such as this "I cannot figure out how to do that, because I have hard coded the lengths of X and Y axes. I want to make the entire function a lot more flexible so that it determines the length of both the axes on the basis of data supplied to it." The way you should be reasoning is this: I have hardcoded the lengths of the x and y axes. I need to change this for my function to operate how I want it to. How do I change it? 1) I have the data set already, so how do i figure out the width? (or height, if you're doing horizontal bar graphs) Well, I can make the following distinctions: - I have a target width (the width of the canvas) that they must all fit within. - all bars will be the same width - there should be some distance between each bar. - this distance should be the same no matter how many data elements there are, IE fixed. - so if I have a fixed width between variable amounts of data, how would I design an algorithm to perform this for me on any arbitrary data set? 2) How do I figure out the height of the data sets? (or width, if you're doing horizontal bar graphs) The following distinctions can be made: - I have a target height that they all must fit within (the height of the canvas) - Only the maximum value should be the full height of the canvas. - the others should be less than this height, depending NOT on their ratio to the height of the maximum bar, but on their ratio to the data that generated this. -- what do we use for ratios? Fractions! HTH, -Luke From andreas at kostyrka.org Fri Nov 24 23:20:46 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 24 Nov 2006 23:20:46 +0100 Subject: [Tutor] A Million Sevens In-Reply-To: References: <493b81e30611171703v7785cbc2w6adf49452b84ae7e@mail.gmail.com> <455E60AC.10900@gmail.com> Message-ID: <20061124222046.GC29019@andi-lap.la.revver.com> * Chris Hengge [061119 00:44]: > That must be part of Pythons shiny ability of dynamic data types? Must be a > messy operation to change data-types like that.. I think I'll just do my > best to work with the right data-types the whole time ;D Well, huge miss understanding: a = b + c => a gets a reference to a newly created object containing the sum of b and c. a += b => a again gets a reference to a new object. So there is not much point in trying to apply performance experiences from other languages like C++ or Java. Andreas From engnarasimha at gmail.com Sat Nov 25 02:02:04 2006 From: engnarasimha at gmail.com (Narasimha) Date: Sat, 25 Nov 2006 06:32:04 +0530 Subject: [Tutor] Please suggest a python book Message-ID: <45679627.36188e98.0441.ffff86d6@mx.google.com> Hi! Friends, I am new to python. I have a vacation of 15 days. Please suggest me a python book (or a website). I already know C language. I have heard much about Python. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061125/d9b9bd5d/attachment.htm From hacktavist at cox.net Sat Nov 25 02:48:51 2006 From: hacktavist at cox.net (hacktavist at cox.net) Date: Fri, 24 Nov 2006 18:48:51 -0700 (MST) Subject: [Tutor] Please suggest a python book In-Reply-To: <45679627.36188e98.0441.ffff86d6@mx.google.com> References: <45679627.36188e98.0441.ffff86d6@mx.google.com> Message-ID: you could look into www.diveintopython.com it is an online book for people who are already versed in a prior language. Ray On Sat, 25 Nov 2006, Narasimha wrote: > Hi! Friends, > > I am new to python. I have a vacation of 15 days. Please suggest me a python > book (or a website). > > I already know C language. I have heard much about Python. > > From engnarasimha at gmail.com Sat Nov 25 05:33:00 2006 From: engnarasimha at gmail.com (Narasimha) Date: Sat, 25 Nov 2006 10:03:00 +0530 Subject: [Tutor] (no subject) Message-ID: <4567c790.38dee0a0.1e82.1fe9@mx.google.com> Is it possible to create stand-alone programs(like exe files in dos and a.out files in UNIX) with Python? If possible please tell me how to make them. I am planning to distribute my python code to friends. They don't have python interpreters nor they know how to use them. Please suggest a solution. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061125/a77305bd/attachment.htm From jalilsan at gmail.com Sat Nov 25 05:40:48 2006 From: jalilsan at gmail.com (Jalil) Date: Fri, 24 Nov 2006 20:40:48 -0800 Subject: [Tutor] Please suggest a python book In-Reply-To: <45679627.36188e98.0441.ffff86d6@mx.google.com> References: <45679627.36188e98.0441.ffff86d6@mx.google.com> Message-ID: <5850ed90611242040o7bbd6939o5deade89943cfe59@mail.gmail.com> If you already know C you should be fine with python ref book. *Python Essential Reference (2nd Edition)* On 11/24/06, Narasimha wrote: > > Hi! Friends, > > I am new to python. I have a vacation of 15 days. Please suggest me a > python book (or a website). > > I already know C language. I have heard much about Python. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061124/8ab9aae9/attachment.html From anilmrn at yahoo.com Sat Nov 25 06:44:40 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 24 Nov 2006 21:44:40 -0800 (PST) Subject: [Tutor] Auto-hyperlinking ignoring html tags Message-ID: <20061125054440.23446.qmail@web55215.mail.re4.yahoo.com> Hey I m trying to auto-hyperlink urls, i found libcia.web.Regextransform.py but the problem is it applies auto hyperlink on html tags for eg < img src = " http://www.google.com/a.gif " > becomes *gta* img src=" < a href= "http://www.google.com/a.gif " *lt is there any way to auto-hyperlink on text, ignoring whatever is in html tags ie within < > http://www.google.com/codesearch?q=auto-hyperlink+lang%3Apython&hl=en&btnG=Search+Code http://www.google.com/codesearch?hl=en&q=+lang:python+auto-hyperlink+show:uryY9epTPhc:stWj4z9lV24:urqZ0U7CNig&sa=N&cd=1&ct=rc&cs_p=http://svn.navi.cx/misc/trunk&cs_f=cia/LibCIA/Web/RegexTransform.py#a0 Thanks for pointers ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061124/1f773e63/attachment.htm From rabidpoobear at gmail.com Sat Nov 25 07:10:39 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 25 Nov 2006 00:10:39 -0600 Subject: [Tutor] (no subject) In-Reply-To: <4567c790.38dee0a0.1e82.1fe9@mx.google.com> References: <4567c790.38dee0a0.1e82.1fe9@mx.google.com> Message-ID: <4567DE5F.6020302@gmail.com> Narasimha wrote: > > Is it possible to create stand-alone programs(like exe files in dos > and a.out files in UNIX) with Python? > > If possible please tell me how to make them. > > I am planning to distribute my python code to friends. > > They don?t have python interpreters nor they know how to use them. > > Please suggest a solution. > Depends how you want to distribute it. It's not unreasonable for you to just include the whole python interpreter, along with a batch file that will run the script using the included interpreter, on a CD. IF you're going to make it available for download, though, you want to minimize the packages that are included. A tool like py2exe does this. In addition to reducing the included packages to the bare minimum, it also generates a nice .exe. But really, you could get the same functionality with a simple batch script, and then it would work on Linux too. Not the batch script, obviously, but the rest of your program. Although I'm prettty sure most modern linux distros come with Python already installed, so you don't need to be concerned about those linux folk. Except, I find that it's more trouble for linuxers to get packages for their python scripts, because they have to make-install etc. whereas windows people have a nice friendly, fuzzy little GUI installer for the majority of python packages. So including an interpreter on the CD With your program that has all of the dependencies built in may not be a bad idea. On the other hand (assuming we have more than 2 hands by now) you could also just teach them how to install files, and pat them gently on the back and say "congratulations!" I mean, really, it's not any harder to install a python distribution than it is to install, say, Battlefield 2 or Microsoft Office. Once it's installed, they just double-click the file the same as they would with any other program. So their argument that they 'wouldn't know how to use it' doesn't really apply. If they want to make their own programs, they can learn how to use it. If they want to run your programs, it doesn't matter whether they understand it or not. Just tell them not to look at the source code and they can go on thinking that all programs are made by magical programming fairies while we sleep, or by little elves. Oh, and to address your original question: I don't think it's possible to have a single .exe with all your program's functionality contained within. But you can have a .exe as well as a file directory that has all of your materials. In this case, why not just have a batch and a python installation? Just remember that very few programs come in completely enclosed .exes. Examples include Anim8or, and.... Hmm. I can't think of any others. Anyway, that's enough out of me. Time for you to get on with your pythoneering! Hope I helped, -Luke > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From andreas at kostyrka.org Sat Nov 25 11:44:04 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 25 Nov 2006 11:44:04 +0100 Subject: [Tutor] (no subject) In-Reply-To: <4567DE5F.6020302@gmail.com> References: <4567c790.38dee0a0.1e82.1fe9@mx.google.com> <4567DE5F.6020302@gmail.com> Message-ID: <20061125104403.GE29019@andi-lap.la.revver.com> * Luke Paireepinart [061125 07:11]: > Not the batch script, obviously, but the rest of your program. > Although I'm prettty sure most modern linux distros come with Python > already installed, so you don't need to be concerned about those linux folk. > Except, I find that it's more trouble for linuxers to get packages for I beg to differ here. Most Python packages (well, there are some Windows-only packages that are a mess, but wonder why that is so), are trivial to build and install: python setup.py install For most packages, even fetching the package is automated via ez_install. Even further, with eggs you probably could automatically fetch (and potentially build and install) a package from inside an app, but that is considered bad tone (security wise, and automatism might break). And to make it even funnier all of this is trival scriptable, while all these nice GUI installers take my time. The point is easy: Building a custom Python with a set of crazy dependencies takes some hours on my Linux laptop. Setting up the same crazy dependencies with GUI dependencies on Windows XP took me almost a week. I admit, my sympathies lie with the "type a command, go to lunch, come back and have dozens servers installed and configured" crowd, and not the "uhh, no time for lunch today, I have to wait when the GUI installer will prompt me some stupid question" crowd :) > their python scripts, because they have to make-install etc. whereas > windows people have a nice friendly, > fuzzy little GUI installer for the majority of python packages. > So including an interpreter on the CD With your program that has all of > the dependencies built in may not be a bad idea. > Oh, and to address your original question: > I don't think it's possible to have a single .exe with all your > program's functionality contained within. It is. But it is usually not worth the pain. Hints: * one can build almost all modules statically into the binary. * one can zip all Python code into one zip file. * and to make it even funnier, zip files are "appendable" onto almost all binaries. * there are a number of tools that google will show you that automate this process more or less painfully. Andreas From rdm at rcblue.com Sat Nov 25 13:32:33 2006 From: rdm at rcblue.com (Dick Moores) Date: Sat, 25 Nov 2006 04:32:33 -0800 Subject: [Tutor] Please suggest a python book In-Reply-To: <5850ed90611242040o7bbd6939o5deade89943cfe59@mail.gmail.com > References: <45679627.36188e98.0441.ffff86d6@mx.google.com> <5850ed90611242040o7bbd6939o5deade89943cfe59@mail.gmail.com> Message-ID: <7.0.1.0.2.20061125043125.07e094d0@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061125/2a1f2ae2/attachment.html From arildna at stud.ntnu.no Sat Nov 25 14:16:32 2006 From: arildna at stud.ntnu.no (=?ISO-8859-1?Q? Arild_B._N=E6ss ?=) Date: Sat, 25 Nov 2006 14:16:32 +0100 Subject: [Tutor] Please suggest a python book In-Reply-To: <7.0.1.0.2.20061125043125.07e094d0@rcblue.com> References: <45679627.36188e98.0441.ffff86d6@mx.google.com> <5850ed90611242040o7bbd6939o5deade89943cfe59@mail.gmail.com> <7.0.1.0.2.20061125043125.07e094d0@rcblue.com> Message-ID: Den 25. nov. 2006 kl. 13.32 skrev Dick Moores: > At 08:40 PM 11/24/2006, Jalil wrote: >> If you already know C you should be fine with python ref book. >> >> Python Essential Reference (2nd Edition) > > The 3rd ed. came out Feb 2006. > http://tinyurl.com/yjvn6o > I have also been wondering about a second book to get. I've already got "Beginning Python" from Apress, which is good, but very basic. I'm weighing "Python in a Nutshell" against "Python Essential Reference". In one of the customer reviews on the amazon-page (linked to above), someone claims: "The Nutshell book documents each function of a module with an explanation of how to use it and what to watch out for. It often provides a useful example. Beazley, on the other hand, has mostly restated the web docs, which are free." Any opinions on this? (BTW: When I try to visit diveintopython.com, that someone just mentioned in this thread, I get up a web page that has little if anything to do with python.) Arild N?ss -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061125/aa6e1330/attachment.html From python at venix.com Sat Nov 25 14:46:13 2006 From: python at venix.com (Python) Date: Sat, 25 Nov 2006 08:46:13 -0500 Subject: [Tutor] (no subject) In-Reply-To: <4567DE5F.6020302@gmail.com> References: <4567c790.38dee0a0.1e82.1fe9@mx.google.com> <4567DE5F.6020302@gmail.com> Message-ID: <1164462373.19530.353.camel@www.venix.com> On Sat, 2006-11-25 at 00:10 -0600, Luke Paireepinart wrote: > Although I'm prettty sure most modern linux distros come with Python > already installed, so you don't need to be concerned about those linux > folk. I think Windows is the only major OS distribution that still omits Python. > Except, I find that it's more trouble for linuxers to get packages > for > their python scripts, because they have to make-install etc. whereas > windows people have a nice friendly, > fuzzy little GUI installer for the majority of python packages. The belief that all Linux software must be compiled and installed manually is a common misconception. The major Linux distributions all have servers with thousands of packages that install easily, either from a command line or a GUI interface. For my Fedora laptop: yum install python-kid checks for any dependencies (e.g. python-elementtree) and installs all needed packages. (There is no need for the package to have been written in Python. I just used a Python example since this is a Python list.) Most Linux packages have available source code and you *can* install from source, but that is not forced on you. If a Python package is not available through yum, installation from the Cheese Shop is still quite simple, and certainly no more difficult than on Windows. -- Lloyd Kvam Venix Corp From kent37 at tds.net Sat Nov 25 15:12:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Nov 2006 09:12:13 -0500 Subject: [Tutor] Please suggest a python book In-Reply-To: References: <45679627.36188e98.0441.ffff86d6@mx.google.com> <5850ed90611242040o7bbd6939o5deade89943cfe59@mail.gmail.com> <7.0.1.0.2.20061125043125.07e094d0@rcblue.com> Message-ID: <45684F3D.3050208@tds.net> Arild B. N?ss wrote: > > Den 25. nov. 2006 kl. 13.32 skrev Dick Moores: > >> At 08:40 PM 11/24/2006, Jalil wrote: >>> If you already know C you should be fine with python ref book. >>> >>> *Python Essential Reference (2nd Edition)* >> >> The 3rd ed. came out Feb 2006. >> http://tinyurl.com/yjvn6o >> > > I have also been wondering about a second book to get. I've already got > "Beginning Python" from Apress, which is good, but very basic. > > I'm weighing "Python in a Nutshell" against "Python Essential > Reference". In one of the customer reviews on the amazon-page (linked to > above), someone claims: "The Nutshell book documents each function of a > module with an explanation of how to use it and what to watch out for. > It often provides a useful example. Beazley, on the other hand, has > mostly restated the web docs, which are free." > > Any opinions on this? Python in a Nutshell does give good concise explanations of the modules. The version of Beazley that I have, which is pretty old (2000), doesn't seem to add much to the docs. But personally I prefer the online docs to either. I think a good intermediate Python book is the Python Cookbook. This gives a lot of examples of using Python and the standard library in ways you might not have thought of. It is a good collection of idiomatic Python. > > (BTW: When I try to visit diveintopython.com, that someone just > mentioned in this thread, I get up a web page that has little if > anything to do with python.) Try diveintopython.org Kent > > Arild N?ss > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sat Nov 25 15:12:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Nov 2006 09:12:48 -0500 Subject: [Tutor] Please suggest a python book In-Reply-To: <45679627.36188e98.0441.ffff86d6@mx.google.com> References: <45679627.36188e98.0441.ffff86d6@mx.google.com> Message-ID: <45684F60.7010501@tds.net> Narasimha wrote: > Hi! Friends, > > I am new to python. I have a vacation of 15 days. Please suggest me a > python book (or a website). > > I already know C language. I have heard much about Python. I think Learning Python is a good book if you already have some programming experience. Kent From rdm at rcblue.com Sat Nov 25 15:13:49 2006 From: rdm at rcblue.com (Dick Moores) Date: Sat, 25 Nov 2006 06:13:49 -0800 Subject: [Tutor] PLEASE assign a (meaningful) subject to your posts Message-ID: <7.0.1.0.2.20061125061130.0661b9d0@rcblue.com> Pretty please. Posts without subject headers irritate the hell out of Eudora. Dick Moores From ajkadri at googlemail.com Sat Nov 25 15:34:43 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 25 Nov 2006 14:34:43 +0000 Subject: [Tutor] Question about HORIZONTAL BAR CHART..... Message-ID: As far as I understand, I need to design an algorithm which computes the padding between each bar (space between each bar) and the length of each bar ( remember that this is a HORIZONTAL BAR CHART). I am trying to understand your email. ( Please bear with my slow comprehension ) Regards, Asrarahmed Kadri On 11/24/06, Luke Paireepinart wrote: > > Asrarahmed Kadri wrote: > > > > > > Hi Folks, > > > > I am constructing a bar-chart using Tkinter. The function takes a list > > 'data' and draws horizontal bar for each value. > > Now what I want is the the canvas widget should be able to handle > > variable number of data-items. I cannot figure out how to do that, > > because I have hard coded the lengths of X and Y axes. I want to make > > the entire function a lot more flexible so that it determines the > > length of both the axes on the basis of data supplied to it. > #disclaimer > Note: I didn't realize you said horizontal bar charts. > This does vertical bar charts. > It should be trivial to change this. > Sorry for not reading your post more carefully to begin with. > > > #for width > >>> data = [1,5,6,7,8,3,2,9] > >>>target_width = 600 > >>>padding = 10 > >>>num_of_data_items = len(data) > >>>individual_width =( > target_width-(padding*(num_of_data_items-1)))/num_of_data_items > >>>individual_width > 66 > >>>individual_width*num_of_data_items > 528 > >>>padding* (len(data)-1) > 70 > >>>528 + 70 > 598 > > #for height > >>>target_height = 600 > >>> maxval = max(yvals) > >>> for item in yvals: > print int((float(item)/maxval) * target_height) > > 66 > 333 > 400 > 466 > 533 > 200 > 133 > 600 > > Did you honestly try to think this through before posting? > It's a very simple concept. > Not trying to be mean, just frank. > I think you could've done this on your own if you had tried. > Good luck with your bar charts. :) > > When you ask a question such as this > "I cannot figure out how to do that, because I have hard coded the > lengths of X and Y axes. I want to make the entire function a lot more > flexible so that it determines the length of both the axes on the basis > of data supplied to it." > The way you should be reasoning is this: > I have hardcoded the lengths of the x and y axes. > I need to change this for my function to operate how I want it to. > How do I change it? > 1) I have the data set already, so how do i figure out the width? (or > height, if you're doing horizontal bar graphs) > Well, I can make the following distinctions: > - I have a target width (the width of the canvas) that they must all fit > within. > - all bars will be the same width > - there should be some distance between each bar. > - this distance should be the same no matter how many data elements > there are, IE fixed. > - so if I have a fixed width between variable amounts of data, how would > I design an algorithm to perform this for me on any arbitrary data set? > > 2) How do I figure out the height of the data sets? (or width, if you're > doing horizontal bar graphs) > The following distinctions can be made: > - I have a target height that they all must fit within (the height of > the canvas) > - Only the maximum value should be the full height of the canvas. > - the others should be less than this height, depending NOT on their > ratio to the height of the maximum bar, but on their ratio to the data > that generated this. > -- what do we use for ratios? Fractions! > > HTH, > -Luke > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061125/7b4fb1f4/attachment.htm From andreas at kostyrka.org Sat Nov 25 22:25:42 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 25 Nov 2006 22:25:42 +0100 Subject: [Tutor] (no subject) In-Reply-To: <1164462373.19530.353.camel@www.venix.com> References: <4567c790.38dee0a0.1e82.1fe9@mx.google.com> <4567DE5F.6020302@gmail.com> <1164462373.19530.353.camel@www.venix.com> Message-ID: <20061125212541.GI29019@andi-lap.la.revver.com> * Python [061125 14:47]: > On Sat, 2006-11-25 at 00:10 -0600, Luke Paireepinart wrote: > > Although I'm prettty sure most modern linux distros come with Python > > already installed, so you don't need to be concerned about those linux > > folk. > > I think Windows is the only major OS distribution that still omits > Python. > > > Except, I find that it's more trouble for linuxers to get packages > > for > > their python scripts, because they have to make-install etc. whereas > > windows people have a nice friendly, > > fuzzy little GUI installer for the majority of python packages. > > The belief that all Linux software must be compiled and installed > manually is a common misconception. The major Linux distributions all Even worse is the common misconception that this is even a problem. One big benefit of this is, that package authors are forced to consider the built and install environment. As a cynic, and this is only a rule of thumb, the following points usually means force built/install automation: a) commercial software => usually smaller user population (and well, Windows does usually come preinstalled, so the population that does Windows installations is extremly small). b) closed source software => it does not matter how ugly it is, as nobody sees it. And providing a sensible environment is often not considered relevant by management. (E.g. I once did revamp the build system of a commercial closed source application, but I had to hide the work hours in a "paid-for" project) c) Windows => Windows has no systematic filesystem layout, is still having problems with filesystem permissions, and lacks a standard compilation environment. These are additative, IMHO ;) Yeah, I know there are exceptions, but over a decade these points have been validated in many, many cases. > have servers with thousands of packages that install easily, either from > a command line or a GUI interface. For my Fedora laptop: > yum install python-kid > checks for any dependencies (e.g. python-elementtree) and installs all > needed packages. (There is no need for the package to have been written > in Python. I just used a Python example since this is a Python list.) > Most Linux packages have available source code and you *can* install > from source, but that is not forced on you. Basically software installation on Linux (and to a lesser degree on commercial Unixes) is way less flashy than on Windows, but at the same time more advanced. Automatic fetching and dependency resolution have been standard features for Linux distribution for years now. E.g. Installing package B that breaks package A is considered a bug on Debian. Installing package B on Windows that replaces common DLLs and breaks half of the system is "state of the art". > > If a Python package is not available through yum, installation from the > Cheese Shop is still quite simple, and certainly no more difficult than > on Windows. As noted above if there a no distribution specific packages, we can fallback on a number of Python specific ways to build packages: a) easyinstall. Autofetching, building and installing, including dependencies. b) eggs. binary and system-independant prepackaged Python packages. Including version management of a given package. c) distutils setup.py => no autofetching of dependencies. automatic build + install. Btw, these are also available ob Windows, as these are Python specific ways to handle packages. OTOH they are hindered on Windows by the fact that there is no standard compiler environment (see above) that is always available. Getting a VS NET 7.1 license in the office (a big international company *g*) takes days. It's a pain, but it's easier to patch the installed python config to compile via mingw. And if I think about that one, yes, the private closed source packages that are Windows specific have the worst buildsystem. Aka a README where one can copy & paste CL.EXE invocation from. Cool, not. Andreas From chiselchip at earthlink.net Sat Nov 25 22:34:32 2006 From: chiselchip at earthlink.net (LandSurveyor) Date: Sat, 25 Nov 2006 16:34:32 -0500 (GMT-05:00) Subject: [Tutor] Please suggest a Python Book Message-ID: <14653257.1164490473018.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> "Python Programming for the absolute beginner" auth: Michael Dawson Although touted as, and directed toward, a new programmer, the book is an excellent 'sing along' tome that illustrates good examples with a good structure of creating small working scripts, and gets very well into some heavy subjects, including OOP, GUI programming. A well written, well thought out effort. From agilfoy at frontiernet.net Sun Nov 26 01:27:58 2006 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sun, 26 Nov 2006 00:27:58 +0000 Subject: [Tutor] program spontaneously closes... Message-ID: <20061126002758.q29lcb9k0h34sgks@webmail.frontiernet.net> Hello All. I've been concocting some simple programs based on an online tutorial, and I, of course, save a program as a .py file. When running my program via IDLE, once I've cleaned out the bugs, it works as I expect it to. But I noticed something else: Clicking directly on the file's icon has the program open in the Windows command line program as a .exe file. The command line program seems to work through my program OK, but the command line program shuts down immediately after the program has run through, as opposed to staying open in order to display the result. [I noticed that if the command line program is not waiting for a resposne to a prompt, it stays open.] Relevant code block: #rectangle stuff length = int(raw_input("Please enter the length of your rectangle, as a whole number : ")) #lets user input a number width = int(raw_input("Please enter the width of your rectangle, as a whole number : ")) #lets user input a number area = length * width print " " print " " print " " print "the length is" print length print " " print "the width is" print width print " " print "So the area is" print area print " " end = (raw_input("Type something, and press Enter, and the program should shut down.")) #workaround From nephish at gmail.com Sun Nov 26 02:02:56 2006 From: nephish at gmail.com (shawn bright) Date: Sat, 25 Nov 2006 19:02:56 -0600 Subject: [Tutor] shebang question Message-ID: <384c93600611251702j437abfc5ub7c1b464e557c944@mail.gmail.com> Hey there all, what is the difference between #!/usr/bin/python and #!/usr/bin/env python ? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061125/e36f99d1/attachment.html From rdm at rcblue.com Sun Nov 26 02:23:39 2006 From: rdm at rcblue.com (Dick Moores) Date: Sat, 25 Nov 2006 17:23:39 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> Message-ID: <7.0.1.0.2.20061125170157.06489650@rcblue.com> At 01:37 PM 11/23/2006, Alan Gauld wrote: >"Dick Moores" wrote > > > def compute_fact(): > > value = int(entry_get()) > > > File "factTk1-a.py", line 22, in compute_fact > > value = int(entry_get()) > > NameError: global name 'entry_get' is not defined > > > > I'm so dumb I don't see how to define it. > >get is a method of the Entry widget. >So the syntax is entry.get() not entry_get. > >HTH, Sure did, Alan. Some time has passed and I've made some progress. My question now is about the placement of buttons. Here's part of my code: ===================================================== root = Tk() fram = Frame(root, bg = "black").pack() Label(fram, text = "Enter a positive integer, n",).pack() entry = Entry(fram, fg = "red", width = 30) entry.focus_set() entry.pack(side='top') Button(fram, text="Compute n!", command=compute_fact).pack(side='top') Button(fram, text="Compute n-cubed", command=compute_cube).pack(side="top") Button(fram, text="Compute factors of n", command=compute_factors).pack(side="top") Button(fram, text="Exit", command=sys.exit).pack(side="top") #text = ScrolledText(fram) text = ScrolledText(fram, bg = "cyan", fg = "red") text.insert(END, "n-factorial or n-cubed will appear here.\n\n") text.insert(END, 'And again, with commas inserted.\n\n') text.insert(END, "And yet again, in scientific notation.") text.pack(side="top", expand = 1, fill = "both") mainloop() ============================================= I've done a lot of fiddling around with setting "side=left", and trying to put all the buttons inside a second Frame inside the first one, but I can't get the layout I want, which is the Label on top of the Entry, then a row of the first 3 buttons (which respectively trigger 3 different computations on the integer the user enters). Then below that, the Exit button, with the Text widget at the bottom. How to do this? Is it impossible with the pack() method? Thanks, Dick Moores >Alan G. > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From jayeola at gmail.com Sun Nov 26 02:34:28 2006 From: jayeola at gmail.com (john maclean) Date: Sun, 26 Nov 2006 01:34:28 +0000 Subject: [Tutor] shebang question In-Reply-To: <384c93600611251702j437abfc5ub7c1b464e557c944@mail.gmail.com> References: <384c93600611251702j437abfc5ub7c1b464e557c944@mail.gmail.com> Message-ID: <4170c1720611251734p6ff56b44g10463643658d2522@mail.gmail.com> >From what I can tell/remember, the first works in the *nix environment if python is in your $PATH, the latter will find python "somehere" on your system by looking at wher the executables should be. On 26/11/06, shawn bright wrote: > Hey there all, > what is the difference between > #!/usr/bin/python > and > #!/usr/bin/env python > ? > > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- John Maclean - 07739 171 531 MSc (DIC) From hacktavist at cox.net Sun Nov 26 05:51:06 2006 From: hacktavist at cox.net (hacktavist at cox.net) Date: Sat, 25 Nov 2006 21:51:06 -0700 (MST) Subject: [Tutor] Please suggest a python book In-Reply-To: References: <45679627.36188e98.0441.ffff86d6@mx.google.com> <5850ed90611242040o7bbd6939o5deade89943cfe59@mail.gmail.com> <7.0.1.0.2.20061125043125.07e094d0@rcblue.com> Message-ID: Sorry, it is www.diveintopython.org , not .com On Sat, 25 Nov 2006, =?ISO-8859-1?Q? Arild_B._N=E6ss ?= wrote: > > Den 25. nov. 2006 kl. 13.32 skrev Dick Moores: > >> At 08:40 PM 11/24/2006, Jalil wrote: >>> If you already know C you should be fine with python ref book. >>> >>> Python Essential Reference (2nd Edition) >> >> The 3rd ed. came out Feb 2006. >> http://tinyurl.com/yjvn6o >> > > I have also been wondering about a second book to get. I've already got > "Beginning Python" from Apress, which is good, but very basic. > > I'm weighing "Python in a Nutshell" against "Python Essential Reference". In > one of the customer reviews on the amazon-page (linked to above), someone > claims: "The Nutshell book documents each function of a module with an > explanation of how to use it and what to watch out for. It often provides a > useful example. Beazley, on the other hand, has mostly restated the web docs, > which are free." > > Any opinions on this? > > (BTW: When I try to visit diveintopython.com, that someone just mentioned in > this thread, I get up a web page that has little if anything to do with > python.) > > Arild N?ss From bgailer at alum.rpi.edu Sun Nov 26 07:42:07 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 25 Nov 2006 22:42:07 -0800 Subject: [Tutor] program spontaneously closes... In-Reply-To: <20061126002758.q29lcb9k0h34sgks@webmail.frontiernet.net> References: <20061126002758.q29lcb9k0h34sgks@webmail.frontiernet.net> Message-ID: <4569373F.8010509@alum.rpi.edu> Alan Gilfoy wrote: > Hello All. > I've been concocting some simple programs based on an online tutorial, > and I, of course, save a program as a .py file. > > When running my program via IDLE, once I've cleaned out the bugs, it > works as I expect it to. > > But I noticed something else: > > Clicking directly on the file's icon has the program open in the > Windows command line program as a .exe file. > > The command line program seems to work through my program OK, but the > command line program shuts down immediately after the program has run > through, as opposed to staying open in order to display the result. This is true of any executable on almost any system. If there is no deliberate pause-before-terminating, then the program will terminate and the window will close. This has been asked so many times on these lists I am almost weary of reading & responding. Putting raw_input() at the end is not a workaround. It is the solution. Unless you want to redesign the operating system. [I > noticed that if the command line program is not waiting for a resposne > to a prompt, it stays open.] > > Relevant code block: > > #rectangle stuff > length = int(raw_input("Please enter the length of your rectangle, as > a whole number : ")) #lets user input a number > width = int(raw_input("Please enter the width of your rectangle, as a > whole number : ")) #lets user input a number > area = length * width > print " " > print " " > print " " > print "the length is" > print length > print " " > print "the width is" > print width > print " " > print "So the area is" > print area > print " " > > end = (raw_input("Type something, and press Enter, and the program > should shut down.")) > #workaround > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From rabidpoobear at gmail.com Sun Nov 26 09:10:21 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 26 Nov 2006 02:10:21 -0600 Subject: [Tutor] Question about HORIZONTAL BAR CHART..... In-Reply-To: References: Message-ID: <45694BED.5020009@gmail.com> Asrarahmed Kadri wrote: > As far as I understand, I need to design an algorithm which computes > the padding between each bar (space between each bar) and the length > of each bar ( remember that this is a HORIZONTAL BAR CHART). I think what you want to design is an algorithm that computes the HEIGHT of each bar (as it's a HORIZONTAL bar chart) because the vertical padding, (The space between each bar) is a fixed number, like 20 pixels. At least that's what i would do. This height is dependent upon the number of data sets you have. For the width of the bars (remember this is a horizontal bar chart, so the heights of the bars will all be the same, but the widths will be different) you will want to set it up so that the largest data value is set to the widest bar, and the rest are percentages of this width. I hope that helps. -Luke From rabidpoobear at gmail.com Sun Nov 26 09:25:06 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 26 Nov 2006 02:25:06 -0600 Subject: [Tutor] program spontaneously closes... In-Reply-To: <20061126002758.q29lcb9k0h34sgks@webmail.frontiernet.net> References: <20061126002758.q29lcb9k0h34sgks@webmail.frontiernet.net> Message-ID: <45694F62.1070309@gmail.com> Bob has answered your original question, but I'd like to make some observations. Alan Gilfoy wrote: > Hello All. > I've been concocting some simple programs based on an online tutorial, > and I, of course, save a program as a .py file. > > When running my program via IDLE, once I've cleaned out the bugs, it > works as I expect it to. > Perhaps the way you expect it to work is not the way it should work :) > But I noticed something else: > > Clicking directly on the file's icon has the program open in the > Windows command line program as a .exe file. > I'm not really sure why you say 'as a .exe file.' Nowhere along the line is your python script compiled into an exe file. Yes, Python itself is an executable, but your script is not, unless you explicitly make it one. > The command line program seems to work through my program OK, but the > command line program shuts down immediately after the program has run > through, as opposed to staying open in order to display the result. [I > noticed that if the command line program is not waiting for a resposne > to a prompt, it stays open.] > I think you mean 'if the command line program IS waiting for a response to a prompt, it stays open.' And what's all of this 'command-line' business? Your python script is the same when run by double-clicking as it is when run from idle: it's interpreted by Python. IDLE happens to have a wrapper for the interpreter that captures all the output, so that it can display the tracebacks in nice pretty red colors, and things like that. But it is still the same as when you run it by double-clicking the script. > Relevant code block: > > #rectangle stuff > length = int(raw_input("Please enter the length of your rectangle, as > a whole number : ")) #lets user input a number > width = int(raw_input("Please enter the width of your rectangle, as a > whole number : ")) #lets user input a number > area = length * width > print " " > print " " > print " " > If you're trying to make blank lines, you don't need to print a blank space. This could just as well be print "" or even print but a better way, in my opinion, to do this is to add newlines! eg. print "\n"*3 or print "\n\n\n" > print "the length is" > print length > print " " > print "the width is" > print width > print " " > print "So the area is" > print area > print " " > and all of this could be shortened to: print "The length is " + length + ",\nand the width is" + width + ".\nThe Area, therefore, is " + area + ".\n" or even print "Length: %s, Width: %s, Area: %s." % (length, width, area) But of course you don't have to listen to my suggestions, particularly if their functionality doesn't make sense. No reason to copy-pasta. It's more important that you know what the crap is going on with your code :) On a final note, consider if the Python interpreter didn't automatically exit whenever it was done executing code: So we've been doing console IO for a few days, and we're moving on to a GUI app. So we make an app that edits MP3 version 1 tags, say. Now, whenever someone messes with the tag and exits our program, there's this crazy dos box that just sits there saying 'press any key to exit!' or something, and otherwise it's completely blank. Is that what you want to happen? Just remember that Python is used for many things besides console IO, and it makes everything much simpler if Python just requires you to put a sleep(10) at the end of your program, or a raw_input, if you want to view the results. Eventually you'll get into scripts that have a menu, that's displayed in a loop, and then you'll have a 'quit' option to exit out of the loop. Otherwise, the loop just runs through again and you can look back at your previous data if you want. SO in this case you could see the previously calculated rectangle values while it's asking you for the new data. HTH, -_-Luke From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?= Sun Nov 26 09:01:55 2006 From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?=) Date: Sun, 26 Nov 2006 11:01:55 +0300 Subject: [Tutor] shebang question In-Reply-To: <4170c1720611251734p6ff56b44g10463643658d2522@mail.gmail.com> References: <384c93600611251702j437abfc5ub7c1b464e557c944@mail.gmail.com> <4170c1720611251734p6ff56b44g10463643658d2522@mail.gmail.com> Message-ID: <20061126110155.0ee699fb@arch.zamb.pc> "john maclean" On Sun, 26 Nov 2006 01:34:28 +0000 wrote: > From what I can tell/remember, the first works in the *nix environment > if python is in your $PATH, ... Actually, no. The first will try to feed the script to the executable "/usr/bin/python". If that doesn't exist (or is not executable) it'll fail. > ...the latter will find python "somehere" on your system by looking at > wher the executables should be. True, assuming there's "/usr/bin/env" on your system (and is executable) and that "python" is found in your "$PATH" (and is executable). The problem is that Python is not installed in the same place on all OSes! Some will install it under "/usr/local", others under "/opt". The idea of "/usr/bin/env" is that it's always installed there (or it should be!). So, you don't need to figure out where is python (or perl, ruby, make, sed, awk, or any other executable that "feeds" on scripts/text files) installed as long as it's in your "$PATH". (Of course, "env" have other uses. As long as I can tell, this is not the intended use of "env". See "info env" for more information, or if you don't have "info" see the manual.) Ziyad. From kent37 at tds.net Sun Nov 26 13:14:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 26 Nov 2006 07:14:36 -0500 Subject: [Tutor] Auto-hyperlinking ignoring html tags In-Reply-To: <20061125054440.23446.qmail@web55215.mail.re4.yahoo.com> References: <20061125054440.23446.qmail@web55215.mail.re4.yahoo.com> Message-ID: <4569852C.1050609@tds.net> anil maran wrote: > Hey > > I m trying to auto-hyperlink urls, > i found libcia.web.Regextransform.py > but the problem is it applies auto hyperlink on html tags > for eg < img src = " http://www.google.com/a.gif " > > > becomes > *gta* img src=" < a href= "http://www.google.com/a.gif " *lt > > is there any way to auto-hyperlink on text, ignoring whatever is in html > tags ie within < > I'm not sure I understand what you want. I think you have some HTML and you want to find URLs that are in the text of the HTML and convert them to hyperlinks. To do this you have to parse the HTML, for example using Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ Then you can walk through the parsed tags and modify the text of the tags to include the hyperlinks. Kent From Eike.Welk at post.rwth-aachen.de Sat Nov 25 15:34:36 2006 From: Eike.Welk at post.rwth-aachen.de (Eike Welk) Date: Sat, 25 Nov 2006 15:34:36 +0100 Subject: [Tutor] Please suggest a python book In-Reply-To: <45679627.36188e98.0441.ffff86d6@mx.google.com> References: <45679627.36188e98.0441.ffff86d6@mx.google.com> Message-ID: <200611251534.36479.eike.welk@post.rwth-aachen.de> If you are a natural scientist or an engineer you should look at: Hans P. Langtangen Python Scripting for Computational Science It's an introduction to Python and to topical libs, for people who want to do numerical computations. Eike From john.corry at ntlworld.com Sun Nov 26 13:11:47 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 26 Nov 2006 12:11:47 -0000 Subject: [Tutor] adjust key bindings Message-ID: <000601c71154$105cc9f0$523ea8c0@JOHNC> Hi All, I have been trying to bind the "z" key to the "Down" key using Python 2.4, Glade 2 and Pygtk. I have posted this problem on the Pygtk list but have had no response. I was hoping somebody on the tutor list could help. I think that I am close. I can capture the "z" key press and assign a "Down" key press but I can't get the "Down" key press to register on the Treeview in the GUI. Any thoughts greatly appreciated. Thanks, John. -----Original Message----- From: pygtk-bounces at daa.com.au [mailto:pygtk-bounces at daa.com.au] On Behalf Of John CORRY Sent: 25 November 2006 17:23 To: 'Fabian Braennstroem'; pygtk at daa.com.au Subject: RE: [pygtk] Re: adjust key bindings Fabian, I have had a go at binding the "z" key to the down cursor key. I can block the Z key press and assign the "down" cursor key press and print out the "down" key press but I can't redirect the signal back to the widget. I have enclosed the code below, maybe someone else on the list can finish off the code. The code below assumes that you have a window in Glade with one treeview widget. Both widgets have the "key_press_event" assigned in glade. import shutil import pygtk import findgtk import gtk import gtk.glade import gobject import os import sys class Shopcard: def __init__(self): self.wTree = gtk.glade.XML ("project12.glade", "window1") dic={"on_window1_delete_event" : self.quit100, } self.wTree.signal_autoconnect (dic) tree1 = self.wTree.get_widget("treeview1") windy = self.wTree.get_widget("window1") tree1.connect("key_press_event",self.callback3000,tree1,windy) model = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING) self.hostmodel = model host_inter=self.insert_row(model,None,"test",'Test') host_inter=self.insert_row(model,None,"test1",'Test') host_inter=self.insert_row(model,None,"test2",'Test') host_inter=self.insert_row(model,None,"test3",'Test') host_inter=self.insert_row(model,None,"test4",'Test') tree1.set_model(model) renderer=gtk.CellRendererText() column=gtk.TreeViewColumn("Col1",renderer,text=0) column.set_resizable(True) tree1.append_column(column) renderer=gtk.CellRendererText() column=gtk.TreeViewColumn("Col2",renderer,text=1) column.set_resizable(True) tree1.append_column(column) def insert_row(self,model,parent,firstcolumn,secondcolumn, thirdcolumn=None): myiter=model.insert_after(parent,None) model.set_value(myiter,0,firstcolumn) model.set_value(myiter,1,secondcolumn) if thirdcolumn !=None: model.set_value(myiter,2,thirdcolumn) return myiter def callback3000(self,widget,event,tree1,windy): import re """prevents the possibility of inputting wrong chars""" ## fixme: missing comma, and cut&paste key = gtk.gdk.keyval_name (event.keyval) ONLYDIGITS="([0-9.,z]|BackSpace|Left|Right|F1|period|Tab|Up|Down)" if not re.match (ONLYDIGITS, key): print "True" return True else: if key == "z": tree1.emit_stop_by_name("key_press_event") # This blocks the signal from the key press event = gtk.gdk.Event(gtk.gdk.KEY_PRESS) event.keyval = 65364 # This is the code for the down key event.state = gtk.gdk.CONTROL_MASK event.time = 0 # assign current time print gtk.gdk.keyval_name(event.keyval) tree1.emit('key_press_event', event) tree1.connect("key_press_event",self.callback3001) else: print event.keyval print "else" return False def callback3001(self,widget,event): import re """prevents the possibility of inputting wrong chars""" ## fixme: missing comma, and cut&paste key = gtk.gdk.keyval_name (event.keyval) print key print "made it" ONLYDIGITS="([0-9.,z]|BackSpace|Left|Right|F1|period|Tab|Up|Down)" if not re.match (ONLYDIGITS, key): print "True2" return True def quit(self,obj): gtk.main_quit() sys.exit(1) def quit100(self,obj,wind): gtk.main_quit() sys.exit(1) if __name__ == '__main__': Shopcard() try: gtk.threads_init() except: print "No threading was enabled when you compiled pyGTK!" import sys sys.exit(1) gtk.threads_enter() gtk.main() gtk.threads_leave() The code outputs the following: When you hit the down cursor it prints: 65364 else and when you hit the "z" key it prints: Down 65364 else Regards, John. -----Original Message----- From: pygtk-bounces at daa.com.au [mailto:pygtk-bounces at daa.com.au] On Behalf Of Fabian Braennstroem Sent: 18 November 2006 19:14 To: pygtk at daa.com.au Subject: [pygtk] Re: adjust key bindings Hi, sorry, is that question to stupid or does nobody has a hint? * On 14 Nov 2006 * Fabian Braennstroem wrote: > Hi, > > I just start to use pygtk ... so it is just my first > question :-) > > I would like to create a small file manager based on 'lfm' > (curses based file manager). I used glade for the gui and I > am able to display the existing files and directories using > two treeview widgets. > Now, at the beginning I am kind of stuck with the key bindings. In 'lfm' > it was pretty easy to define special key bindings: > > > keytable = { > # movement > ord('p'): 'cursor_up', > ord('k'): 'cursor_up', > ord('K'): 'cursor_up2', > ord('P'): 'cursor_up', > curses.KEY_UP: 'cursor_up', > ord('n'): 'cursor_down', > ord('j'): 'cursor_down', > ord('J'): 'cursor_down2', > ord('N'): 'cursor_down', > curses.KEY_DOWN: 'cursor_down', > curses.KEY_PPAGE: 'page_previous', > curses.KEY_BACKSPACE: 'page_previous', > 0x08: 'page_previous', # BackSpace > 0x10: 'page_previous', # Ctrl-P > curses.KEY_NPAGE: 'page_next', > ord(' '): 'page_next', > 0x0E: 'page_next', # Ctrl-N > curses.KEY_HOME: 'home', > 0x16A: 'home', > ord('H'): 'home', > 0x001: 'home', > curses.KEY_END: 'end', > ord('G'): 'end', > 0x181: 'end', > 0x005: 'end', > ord('h'): 'cursor_left', > ord('l'): 'cursor_right', > curses.KEY_LEFT: 'cursor_left', > curses.KEY_RIGHT: 'cursor_right', > ord('g'): 'goto_dir', > 0x13: 'goto_file', # Ctrl-S > 0x14: 'tree', # Ctrl-T > ord('0'): 'bookmark_0', > ord('1'): 'bookmark_1', > ... > > > with such a keytable I am able to bind different 'def's to > every existing key. As you can see, I like it a lot to use > 'vim-like' keys for moving around; 'j' and 'k' to move a row > up and down. In glade I found those 'accelerators', but it > is just for certain functions. > Does anyone have an idea about using such a keybinding in > pygtk? Would be nice! > Greetings! Fabian _______________________________________________ pygtk mailing list pygtk at daa.com.au http://www.daa.com.au/mailman/listinfo/pygtk Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/ _______________________________________________ pygtk mailing list pygtk at daa.com.au http://www.daa.com.au/mailman/listinfo/pygtk Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/ From rdm at rcblue.com Sun Nov 26 14:49:37 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 26 Nov 2006 05:49:37 -0800 Subject: [Tutor] Please suggest a python book In-Reply-To: <200611251534.36479.eike.welk@post.rwth-aachen.de> References: <45679627.36188e98.0441.ffff86d6@mx.google.com> <200611251534.36479.eike.welk@post.rwth-aachen.de> Message-ID: <7.0.1.0.2.20061126054732.08907820@rcblue.com> At 06:34 AM 11/25/2006, Eike Welk wrote: >If you are a natural scientist or an engineer you should look at: > >Hans P. Langtangen >Python Scripting for Computational Science > >It's an introduction to Python and to topical libs, for people who >want to do numerical computations. Thanks for this! BTW Amazon lets us look inside: Dick Moores From nephish at gmail.com Sun Nov 26 15:09:33 2006 From: nephish at gmail.com (shawn bright) Date: Sun, 26 Nov 2006 08:09:33 -0600 Subject: [Tutor] shebang question In-Reply-To: <20061126110155.0ee699fb@arch.zamb.pc> References: <384c93600611251702j437abfc5ub7c1b464e557c944@mail.gmail.com> <4170c1720611251734p6ff56b44g10463643658d2522@mail.gmail.com> <20061126110155.0ee699fb@arch.zamb.pc> Message-ID: <384c93600611260609s5430fa86w4acc94ac248c52a5@mail.gmail.com> well thanks for all the info, gents, i appreciate it a lot ! sk On 11/26/06, ???? ?? ????????? ??????? wrote: > > "john maclean" On Sun, 26 Nov 2006 01:34:28 +0000 > wrote: > > From what I can tell/remember, the first works in the *nix environment > > if python is in your $PATH, ... > Actually, no. The first will try to feed the script to the executable > "/usr/bin/python". If that doesn't exist (or is not executable) it'll > fail. > > > ...the latter will find python "somehere" on your system by looking at > > wher the executables should be. > True, assuming there's "/usr/bin/env" on your system (and is executable) > and that "python" is found in your "$PATH" (and is executable). > > > The problem is that Python is not installed in the same place on all > OSes! Some will install it under "/usr/local", others under "/opt". > > The idea of "/usr/bin/env" is that it's always installed there (or it > should be!). So, you don't need to figure out where is python (or perl, > ruby, make, sed, awk, or any other executable that "feeds" on > scripts/text files) installed as long as it's in your "$PATH". > > (Of course, "env" have other uses. As long as I can tell, this is not > the intended use of "env". See "info env" for more information, or > if you don't have "info" see the manual.) > > Ziyad. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061126/d947ba22/attachment.html From agilfoy at frontiernet.net Sun Nov 26 15:15:06 2006 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sun, 26 Nov 2006 14:15:06 +0000 Subject: [Tutor] my program problem! Message-ID: <20061126141506.46ie72bhgnnookow@webmail.frontiernet.net> Hey! Glad to hear that using raw_input() at the end is the actual solution, not just a jury-rigged workaround. :) So sleep(10) would simply be a shorter snippet of code for that purpose? The \n thing might be handy if I was short on space, but I don't mind separate 'print' lines, I find that my code seems easier to read that way. (at least to me) I understand that having highly readable code is a ratehr desirable quality...:) -- "Blind faith in bad leadership is not patriotism." "One of the most horrible features of war is that all the war-propaganda, all the screaming and lies and hatred, comes invariably from people who are not fighting."-George Orwell, _Homage to Catalonia_ From ajkadri at googlemail.com Sun Nov 26 16:14:42 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sun, 26 Nov 2006 15:14:42 +0000 Subject: [Tutor] What are the issues in running Python script on another machine (developed on Windows but will be using on Linux) Message-ID: Hi folks, I have a couple of programs that I want to test on a different machine.. I have developed these on Win-XP platform, but I want to test them on my college's machine, which is running Linux. Are there any issues involved or i just need to take my files on a USB memory stick, and copy paste and that is it..? thanks for the help. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061126/76b5fcc8/attachment-0001.htm From klappnase at freenet.de Sun Nov 26 17:59:20 2006 From: klappnase at freenet.de (Michael Lange) Date: Sun, 26 Nov 2006 17:59:20 +0100 Subject: [Tutor] help with Tkinter, please In-Reply-To: <7.0.1.0.2.20061125170157.06489650@rcblue.com> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> Message-ID: <20061126175920.042f1dcc.klappnase@freenet.de> On Sat, 25 Nov 2006 17:23:39 -0800 Dick Moores wrote: > I've done a lot of fiddling around with setting "side=left", and > trying to put all the buttons inside a second Frame inside the first > one, but I can't get the layout I want, which is the Label on top of > the Entry, then a row of the first 3 buttons (which respectively > trigger 3 different computations on the integer the user enters). > Then below that, the Exit button, with the Text widget at the bottom. > How to do this? Is it impossible with the pack() method? > It is certainly not impossible, as long as you do not mind creating a bunch of extra Frames, however to me this really sound like a job for grid() . You could simply use grid(row= , column=0, columnspan=2) for the widgets that should use the whole window's width and grid the 3 buttons into columns 0, 1 and 2 . Michael From jfabiani at yolo.com Sun Nov 26 18:25:39 2006 From: jfabiani at yolo.com (johnf) Date: Sun, 26 Nov 2006 09:25:39 -0800 Subject: [Tutor] python exceptions Message-ID: <200611260925.39404.jfabiani@yolo.com> My debugger comes up with lots of exceptions (builtin with my IDE wing) when I run code I have obtained from others. This is not a formating error - but real unhandled exceptions. But the when the program/programs is/are run from the command line they work as expected. So does this mean that the code has some sort of exception handler not part of the python code? Or could mean that Python ignores certain exceptions. BTW this comes mostly from GUI programs. -- John Fabiani From rdm at rcblue.com Sun Nov 26 18:37:39 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 26 Nov 2006 09:37:39 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: <20061126175920.042f1dcc.klappnase@freenet.de> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> <20061126175920.042f1dcc.klappnase@freenet.de> Message-ID: <7.0.1.0.2.20061126093650.088ed790@rcblue.com> At 08:59 AM 11/26/2006, Michael Lange wrote: >On Sat, 25 Nov 2006 17:23:39 -0800 >Dick Moores wrote: > > > I've done a lot of fiddling around with setting "side=left", and > > trying to put all the buttons inside a second Frame inside the first > > one, but I can't get the layout I want, which is the Label on top of > > the Entry, then a row of the first 3 buttons (which respectively > > trigger 3 different computations on the integer the user enters). > > Then below that, the Exit button, with the Text widget at the bottom. > > How to do this? Is it impossible with the pack() method? > > > >It is certainly not impossible, as long as you do not mind creating >a bunch of extra Frames, however to me this really sound like a >job for grid() . >You could simply use grid(row= , column=0, columnspan=2) >for the widgets that should use the whole window's width and grid >the 3 buttons into columns 0, 1 and 2 . Thanks. I'll give grid() a try. Dick From andreas at kostyrka.org Sun Nov 26 19:20:42 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 26 Nov 2006 19:20:42 +0100 Subject: [Tutor] What are the issues in running Python script on another machine (developed on Windows but will be using on Linux) In-Reply-To: References: Message-ID: <20061126182042.GJ29019@andi-lap.la.revver.com> * Asrarahmed Kadri [061126 16:15]: > Hi folks, > > I have a couple of programs that I want to test on a different machine.. > > I have developed these on Win-XP platform, but I want to test them on my > college's machine, which is running Linux. > > Are there any issues involved or i just need to take my files on a USB > memory stick, and copy paste and that is it..? Well, you can try that. Details certainly depend upon if your scripts depend upon third party extensions, and if these are available on Linux. Andreas From arcege at gmail.com Sun Nov 26 19:33:04 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Sun, 26 Nov 2006 13:33:04 -0500 Subject: [Tutor] shebang question In-Reply-To: <20061126110155.0ee699fb@arch.zamb.pc> References: <384c93600611251702j437abfc5ub7c1b464e557c944@mail.gmail.com> <4170c1720611251734p6ff56b44g10463643658d2522@mail.gmail.com> <20061126110155.0ee699fb@arch.zamb.pc> Message-ID: <7e5ba9220611261033o323e9deer3fcae3a2042996c5@mail.gmail.com> Very true about Python being installed in different places. In fact, for system compatibility reasons, it is sometime required that two or three very different releases of Python need to exist on the same system. If more than one happen to be in your path, then the use of "env python" becomes a craps-shoot. Env is not to be used in shebang unless you specifically using it for the purpose it was designed for, and then make sure it is used properly - "#!/usr/bin/env python" is not proper use. FYI, most all good UNIX products for the last number of decades ship scripts with fully qualified pathnames in the shebang lines. As part of the installation, if required, the line will be rewriten to the proper value. -Arcege On 11/26/06, ???? ?? ????????? ??????? wrote: > > "john maclean" On Sun, 26 Nov 2006 01:34:28 +0000 > wrote: > > From what I can tell/remember, the first works in the *nix environment > > if python is in your $PATH, ... > Actually, no. The first will try to feed the script to the executable > "/usr/bin/python". If that doesn't exist (or is not executable) it'll > fail. > > > ...the latter will find python "somehere" on your system by looking at > > wher the executables should be. > True, assuming there's "/usr/bin/env" on your system (and is executable) > and that "python" is found in your "$PATH" (and is executable). > > > The problem is that Python is not installed in the same place on all > OSes! Some will install it under "/usr/local", others under "/opt". > > The idea of "/usr/bin/env" is that it's always installed there (or it > should be!). So, you don't need to figure out where is python (or perl, > ruby, make, sed, awk, or any other executable that "feeds" on > scripts/text files) installed as long as it's in your "$PATH". > > (Of course, "env" have other uses. As long as I can tell, this is not > the intended use of "env". See "info env" for more information, or > if you don't have "info" see the manual.) > > Ziyad. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061126/d140ac6e/attachment.html From kloosterjunkie at hotmail.com Sun Nov 26 20:42:59 2006 From: kloosterjunkie at hotmail.com (Moedeloos Overste) Date: Sun, 26 Nov 2006 20:42:59 +0100 Subject: [Tutor] Newbie string & File I/O questions...... Message-ID: Hi everybody, I am new to python and trying to write a lottery program for a schoolproject. The program is supposed to draw the lottery any entered(user input) number of times, then store the drawing results in a file. After drawings the user should see (if he wants to) how many times each of the possible numbers was picked by the computer and which were the six most succesful numbers. These data must be calculated from the data stored in the file! This is what I've been able to come up with so far: # Lottery chances. # Programs ask how many times you want to have the lottery drawn by the # computer. Then stores these draws and then shows the 6 numbers most drawn # by the computer. # Importing for making the program nicer later on... import os, sys import time import random vDraws = input("How many times do you want to draw the lottery? :>") # Draw lottery numbers & writing them to file while vDraws > 0: List_LotNumbers = random.sample(range(0,46), 6) #random numbers from range into list output_string = str(List_LotNumbers) #converting list to string to store it. fout = open("draw__output.dat", "a") fout.write(output_string) #writing string to file fout.close() vDraws = vDraws - 1 # Printing all numbers drawn vView = raw_input("Do want to see the results? y/n :>") if vView == "y" or vView == "Y": fout = open("draw__output.dat", "r") Print_list = fout.readline() print Print_list #end of program so far My question is: how do I write the output of each lottery drawing on a separate line second question: how do i print the lottery drawings to the screen without the brackets[] third:can somebody point me in the right direction as to how do I make the program read from the file and count how many times a number has been drawn. Any help or pointers would greatly be appreciated. thanks, Robert (forgive me my english, I am Dutch) _________________________________________________________________ Windows Live Mail: Kies je eigen kleur, indeling en contacten! http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl From ajkadri at googlemail.com Sun Nov 26 21:05:35 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sun, 26 Nov 2006 20:05:35 +0000 Subject: [Tutor] Newbie string & File I/O questions..... In-Reply-To: References: Message-ID: You can use, '\n' with each value, that u are writing to the file. eg. outstring = outstring + '\n' \n stands for new line character. I couldnt get the second question. Regarding the third question, you can do this: done = 0 fd = open(filename,'r') while not done: line = fd.readline() if line == '': done = 1 else: for i in line: dict[i] = int(dict[i]) + 1 # dict is a dictionary containing numbers as the keys and initial value 0 for each key HTH, Regards, Asrarahmed Kadri On 11/26/06, Moedeloos Overste wrote: > > Hi everybody, > > I am new to python and trying to write a lottery program for a > schoolproject. > > The program is supposed to draw the lottery any entered(user input) number > of times, then store the drawing results in a file. After drawings the > user > should see (if he wants to) how many times each of the possible numbers > was > picked by the computer and which were the six most succesful numbers. > These > data must be calculated from the data stored in the file! > > This is what I've been able to come up with so far: > > # Lottery chances. > # Programs ask how many times you want to have the lottery drawn by the > # computer. Then stores these draws and then shows the 6 numbers most > drawn > # by the computer. > > # Importing for making the program nicer later on... > import os, sys > import time > import random > > > vDraws = input("How many times do you want to draw the lottery? :>") > > # Draw lottery numbers & writing them to file > > while vDraws > 0: > List_LotNumbers = random.sample(range(0,46), 6) #random numbers from > range into list > output_string = str(List_LotNumbers) #converting list to string to > store > it. > fout = open("draw__output.dat", "a") > fout.write(output_string) #writing string to file > fout.close() > vDraws = vDraws - 1 > > > # Printing all numbers drawn > > vView = raw_input("Do want to see the results? y/n :>") > > if vView == "y" or vView == "Y": > fout = open("draw__output.dat", "r") > Print_list = fout.readline() > print Print_list > > #end of program so far > > My question is: how do I write the output of each lottery drawing on a > separate line > > second question: how do i print the lottery drawings to the screen without > the brackets[] > > third:can somebody point me in the right direction as to how do I make the > program read from the file and count how many times a number has been > drawn. > > Any help or pointers would greatly be appreciated. > > thanks, > > Robert (forgive me my english, I am Dutch) > > _________________________________________________________________ > Windows Live Mail: Kies je eigen kleur, indeling en contacten! > http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061126/bd720ffd/attachment.htm From kent37 at tds.net Sun Nov 26 23:23:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 26 Nov 2006 17:23:00 -0500 Subject: [Tutor] help with Tkinter, please In-Reply-To: <7.0.1.0.2.20061126093650.088ed790@rcblue.com> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> <20061126175920.042f1dcc.klappnase@freenet.de> <7.0.1.0.2.20061126093650.088ed790@rcblue.com> Message-ID: <456A13C4.30006@tds.net> Dick Moores wrote: > At 08:59 AM 11/26/2006, Michael Lange wrote: >> On Sat, 25 Nov 2006 17:23:39 -0800 >> Dick Moores wrote: >> >>> I've done a lot of fiddling around with setting "side=left", and >>> trying to put all the buttons inside a second Frame inside the first >>> one, but I can't get the layout I want, which is the Label on top of >>> the Entry, then a row of the first 3 buttons (which respectively >>> trigger 3 different computations on the integer the user enters). >>> Then below that, the Exit button, with the Text widget at the bottom. >>> How to do this? Is it impossible with the pack() method? >>> >> It is certainly not impossible, as long as you do not mind creating >> a bunch of extra Frames, however to me this really sound like a >> job for grid() . >> You could simply use grid(row= , column=0, columnspan=2) >> for the widgets that should use the whole window's width and grid >> the 3 buttons into columns 0, 1 and 2 . > > Thanks. I'll give grid() a try. It's pretty common to use nested Frames (or the equivalent in other GUI toolkits) to get the layout you want. If you can't do what you need with a single grid layout don't be shy about nesting layouts. Kent From alan.gauld at btinternet.com Mon Nov 27 00:09:56 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Nov 2006 23:09:56 -0000 Subject: [Tutor] help with Tkinter, please References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com><20061123170135.3bf74dff.klappnase@freenet.de><7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> Message-ID: "Dick Moores" wrote > Some time has passed and I've made some progress. My question now is > about the placement of buttons. ... > one, but I can't get the layout I want, which is the Label on top of > the Entry, then a row of the first 3 buttons (which respectively > trigger 3 different computations on the integer the user enters). > Then below that, the Exit button, with the Text widget at the > bottom. Sounds like 4 frames to me: 1 Frame for the outer 'skin', packed with fill for both X and Y. 1 frame for the label/entry combo, using pack to position the widgets inside the frame, then pack the frame inside the outer frame 1 frame for the row of buttons and I'd use grid to position the buttons insdide the frame and then pack the frame into the outer frame (I tend to use grid where I'm positioning things horizontally and pack when i'm doing it vertiacally. So I divide my GUI into horizontal layers and then use grid inside teach layer for horizontally laid out widgets) 1 frame for the bottom exit button and pack it into the outer. > How to do this? Is it impossible with the pack() method? Horizontal layouts are possible using pack, take a look at the GUI topic and the GUI section of the Case Study topic in my tutor for examples of using pure pack. But IMHO grid is easier for horizontal sets. Mixing layout styles in a GUI is fine provided you keep each layout in a frame to itself. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Nov 27 00:20:55 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Nov 2006 23:20:55 -0000 Subject: [Tutor] Please suggest a python book References: <45679627.36188e98.0441.ffff86d6@mx.google.com> Message-ID: "Narasimha" wrote in message news:45679627.36188e98.0441.ffff86d6 at mx.google.com... > Hi! Friends, > > I am new to python. I have a vacation of 15 days. Please suggest me > a python > book (or a website). > > I already know C language. I have heard much about Python. If you know C then the best place to start is the official tutorial on the Python web site (or in the documentation download). You can then proceed either to one of the Special Interest areas or Topic Guides or for more general info DiveIntoPython as already suggested. Personally I'd suggest that you'll learn more by doing the official tutor(2 days max!) and then just writing some code... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Nov 27 00:29:58 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Nov 2006 23:29:58 -0000 Subject: [Tutor] program spontaneously closes... References: <20061126002758.q29lcb9k0h34sgks@webmail.frontiernet.net> Message-ID: "Alan Gilfoy" wrote > The command line program seems to work through my program OK, but > the > command line program shuts down immediately after the program has > run Yes this is normal behaviour. There are several ways around it, one of which is the raw_input trick you have used. Another is to change the Python startup behaviour to include the /i parameter to python which causes the interpreter not to exit - handy for debugging faulty scripts. These options are discussed near the end of the Style topic in my tutor -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Nov 27 00:36:14 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Nov 2006 23:36:14 -0000 Subject: [Tutor] program spontaneously closes... References: <20061126002758.q29lcb9k0h34sgks@webmail.frontiernet.net> <45694F62.1070309@gmail.com> Message-ID: "Luke Paireepinart" wrote > And what's all of this 'command-line' business? Your python script > is > the same when run by double-clicking as it is when run from idle: I'll have to disdagree with you here Luke. IDLE changes script behaviour in quite a number of subtle ways that can lead to strange anomolies. Exceptions which cause programs to crash and burn are caught in IDLE. In particular this causes things like CTRL-C and CTRL-Z to behave differently. Also notoriously, Tkinter code will behave in rather unpredictable ways. The difference is small but big enough that it can confuse beginners. I always recommend that if folks are encountering strange behaviour in IDLE that they try running from a DOS prompt to see what happens. Alan G. From alan.gauld at btinternet.com Mon Nov 27 00:41:45 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Nov 2006 23:41:45 -0000 Subject: [Tutor] my program problem! References: <20061126141506.46ie72bhgnnookow@webmail.frontiernet.net> Message-ID: "Alan Gilfoy" wrote > So sleep(10) would simply be a shorter snippet of code for that > purpose? sleep just gices a long pause before quitting, usually enough to read the output. > The \n thing might be handy if I was short on space, but I don't > mind > separate 'print' lines, I find that my code seems easier to read > that > way. (at least to me) Consider triple quoted strings too. String formatting works with these too: print """ This is a long text message, It includes new lines. It also shows the result of some interpolated values here: The sum of %d and % d is %d """ % (4,5,4+5) I find that more readable than lots of \ns or lots of print statements. Alan G. From alan.gauld at btinternet.com Mon Nov 27 00:43:07 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Nov 2006 23:43:07 -0000 Subject: [Tutor] python exceptions References: <200611260925.39404.jfabiani@yolo.com> Message-ID: "johnf" wrote > My debugger comes up with lots of exceptions (builtin with my IDE > wing) when I > run code I have obtained from others. This is not a formating > error - but > real unhandled exceptions. But the when the program/programs is/are > run from > the command line they work as expected. Can you show us a short example? Show the code and the errors from Wing Alan G. From alan.gauld at btinternet.com Mon Nov 27 00:52:39 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Nov 2006 23:52:39 -0000 Subject: [Tutor] Newbie string & File I/O questions...... References: Message-ID: "Moedeloos Overste" wrote > This is what I've been able to come up with so far: > > vDraws = input("How many times do you want to draw the lottery? :>") input is considered a damngerous function because a user could input malicious python code. Its better to use raw_input and convert to an integer or float etc. > while vDraws > 0: > List_LotNumbers = random.sample(range(0,46), 6) #random numbers > from > range into list > output_string = str(List_LotNumbers) #converting list to string > to store You probably want to use the join string method here rather than str(). str just produces a string representation of your list, which includes the []. Join will produce a string from the members of a list Try >>> help(''.join) > vView = raw_input("Do want to see the results? y/n :>") > > if vView == "y" or vView == "Y": You might prefer to use 'in' here: if vView[0] in 'yY' will work for y, Y, yes, Yes (and yesterday too in case thats a problem!) > My question is: how do I write the output of each lottery drawing on > a > separate line Previous poster answered that > second question: how do i print the lottery drawings to the screen > without > the brackets[] Use join instead of str > third:can somebody point me in the right direction as to how do I > make the > program read from the file and count how many times a number has > been drawn. Try using a dictionary with each number drawn as a key and the corresponding value being the count. Alan G. From jfabiani at yolo.com Mon Nov 27 01:00:34 2006 From: jfabiani at yolo.com (johnf) Date: Sun, 26 Nov 2006 16:00:34 -0800 Subject: [Tutor] python exceptions In-Reply-To: References: <200611260925.39404.jfabiani@yolo.com> Message-ID: <200611261600.34738.jfabiani@yolo.com> On Sunday 26 November 2006 15:43, Alan Gauld wrote: > "johnf" wrote > > > My debugger comes up with lots of exceptions (builtin with my IDE > > wing) when I > > run code I have obtained from others. This is not a formating > > error - but > > real unhandled exceptions. But the when the program/programs is/are > > run from > > the command line they work as expected. > > Can you show us a short example? > Show the code and the errors from Wing > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I can but it's not the issue - I think? I want to know how it works - exceptions not handled by python that is. Are there exception handled outside of python when using modules such as wxPython and pyQT? Or are some exceptions not handled when running from the command line. i.e.: python SomeApp. Has exceptions but because it's running from the command line exceptions are passed??? Or something else is happening? -- John Fabiani From john at fouhy.net Mon Nov 27 01:17:57 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Nov 2006 13:17:57 +1300 Subject: [Tutor] python exceptions In-Reply-To: <200611261600.34738.jfabiani@yolo.com> References: <200611260925.39404.jfabiani@yolo.com> <200611261600.34738.jfabiani@yolo.com> Message-ID: <5e58f2e40611261617s1d12b556s8ec610fc14b84f43@mail.gmail.com> On 27/11/06, johnf wrote: > I can but it's not the issue - I think? I want to know how it works - > exceptions not handled by python that is. Are there exception handled > outside of python when using modules such as wxPython and pyQT? Or are some > exceptions not handled when running from the command line. If your GUI callbacks raise exceptions, the program may still function correctly. eg, basic Tkinter example (my Tkinter is a little rusty, so forgive errors): ##### e = Entry(parent) e.pack() def clear(): e.delete(0, END) raise ValueError b = Button(parent, label='Clear', command=clear) b.pack() ##### The button will (I think) work correctly, and the program won't crash. But you should see the exception printed to the command line (if you run this program from a shell). I don't know for sure, but I imagine the Tkinter mainloop() does something like: try: callback() except: # print trace to stderr This is the only possibility I can think of at the moment. But there could be other things going on, which is why we'd like to see an example. -- John. From edkjv at yahoo.com Mon Nov 27 01:25:57 2006 From: edkjv at yahoo.com (ED PENNELL) Date: Sun, 26 Nov 2006 16:25:57 -0800 (PST) Subject: [Tutor] to learn Message-ID: <617551.39626.qm@web35709.mail.mud.yahoo.com> my name is ED PENNELL, i am using MAC TIGER want to learn python and use it on emacs,i down loaded 2.5 python,i will start with IDLE, DO I NEED PORTS FOR MY MAC and need tutor with MAC.a very fresh starter. THANKS ED ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com From rabidpoobear at gmail.com Mon Nov 27 02:29:31 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 26 Nov 2006 19:29:31 -0600 Subject: [Tutor] adjust key bindings In-Reply-To: <000601c71154$105cc9f0$523ea8c0@JOHNC> References: <000601c71154$105cc9f0$523ea8c0@JOHNC> Message-ID: <456A3F7B.9080309@gmail.com> John CORRY wrote: > Hi All, > > I have been trying to bind the "z" key to the "Down" key using Python > 2.4, Glade 2 and Pygtk. I have posted this problem on the Pygtk list > but have had no response. I was hoping somebody on the tutor list could > help. I think that I am close. I can capture the "z" key press and > assign a "Down" key press but I can't get the "Down" key press to > register on the Treeview in the GUI. > > Any thoughts greatly appreciated. > > Thanks, > > John. I highly doubt that what you want to do when someone hits a 'z' is to generate a 'down' keypress. What if the user assigned the down key to z? then you'd have a z -> down -> z -> down -> .... infinite loop. What I expect you want is that each key, z and down, perform the same action. In other words, they both call the same function. So basically what you'd want is something like this (non-pyGTK specific code) def aFunc(): print "Hello, World!" bindKey = {'down':aFunc} keypress = raw_input("What keypress do you want to perform?") bindKey[keypress]()#this will call the 'aFunc' function if they type 'down', otherwise, it'll probably crash. bindKey['z'] = aFunc bindKey['z']()# now performs the same function as bindkey['down']()#this does. If you really do want to generate 'down' keypresses when someone hits 'z', please explain why, and I will try to the best of my abilities to help you in that regard! Good Luck! -Luke > > From rabidpoobear at gmail.com Mon Nov 27 02:32:36 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 26 Nov 2006 19:32:36 -0600 Subject: [Tutor] to learn In-Reply-To: <617551.39626.qm@web35709.mail.mud.yahoo.com> References: <617551.39626.qm@web35709.mail.mud.yahoo.com> Message-ID: <456A4034.4070707@gmail.com> ED PENNELL wrote: > my name is ED PENNELL, i am using MAC TIGER want > to learn python and use it on emacs,i down loaded 2.5 > python,i will start with IDLE, DO I NEED PORTS FOR MY > MAC You had me up till here and then you lost me. What do you mean, ports? network ports? software ports (as in Linux -> OSx) or what? > and need tutor with MAC. We don't offer private tutors here. If you have questions about Python or you run into problems you can't solve, we help you with them. Did you mean you need a tutorial? If so, you can use any Python tutorial. There's no need for you to look for a MAC specific one because Python is largely the same on any OS you use it on. > a very fresh starter. > THANKS ED > > Glad to hear from ya, ed! -Luke From jfabiani at yolo.com Mon Nov 27 02:50:46 2006 From: jfabiani at yolo.com (johnf) Date: Sun, 26 Nov 2006 17:50:46 -0800 Subject: [Tutor] python exceptions In-Reply-To: <5e58f2e40611261617s1d12b556s8ec610fc14b84f43@mail.gmail.com> References: <200611260925.39404.jfabiani@yolo.com> <200611261600.34738.jfabiani@yolo.com> <5e58f2e40611261617s1d12b556s8ec610fc14b84f43@mail.gmail.com> Message-ID: <200611261750.46857.jfabiani@yolo.com> On Sunday 26 November 2006 16:17, John Fouhy wrote: > On 27/11/06, johnf wrote: > > I can but it's not the issue - I think? I want to know how it works - > > exceptions not handled by python that is. Are there exception handled > > outside of python when using modules such as wxPython and pyQT? Or are > > some exceptions not handled when running from the command line. > > If your GUI callbacks raise exceptions, the program may still function > correctly. > > eg, basic Tkinter example (my Tkinter is a little rusty, so forgive > errors): > > ##### > e = Entry(parent) > e.pack() > > def clear(): > e.delete(0, END) > raise ValueError > > b = Button(parent, label='Clear', command=clear) > b.pack() > ##### > > The button will (I think) work correctly, and the program won't crash. > But you should see the exception printed to the command line (if you > run this program from a shell). I don't know for sure, but I imagine > the Tkinter mainloop() does something like: > > try: > callback() > except: > # print trace to stderr > > This is the only possibility I can think of at the moment. But there > could be other things going on, which is why we'd like to see an > example. So there are outside exception handlers? OK. thanks for the answer. For now that all I needed to understand. -- John Fabiani From rdm at rcblue.com Mon Nov 27 03:37:29 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 26 Nov 2006 18:37:29 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: <20061126175920.042f1dcc.klappnase@freenet.de> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> <20061126175920.042f1dcc.klappnase@freenet.de> Message-ID: <7.0.1.0.2.20061126182558.088f8448@rcblue.com> At 08:59 AM 11/26/2006, Michael Lange wrote: >On Sat, 25 Nov 2006 17:23:39 -0800 >Dick Moores wrote: > > > I've done a lot of fiddling around with setting "side=left", and > > trying to put all the buttons inside a second Frame inside the first > > one, but I can't get the layout I want, which is the Label on top of > > the Entry, then a row of the first 3 buttons (which respectively > > trigger 3 different computations on the integer the user enters). > > Then below that, the Exit button, with the Text widget at the bottom. > > How to do this? Is it impossible with the pack() method? > > > >It is certainly not impossible, as long as you do not mind creating >a bunch of extra Frames, however to me this really sound like a >job for grid() . >You could simply use grid(row= , column=0, columnspan=2) >for the widgets that should use the whole window's width and grid >the 3 buttons into columns 0, 1 and 2 . Well, I'm having a terrible time with grid(). I do have the 6 buttons in the same row, but they're a real mess. Someone please run this and tell me how to get them looking better. When I use pack(), the buttons are nicely centered, but lined up vertically, one above the other. Maybe I can live with that. But I'd still like to learn how to use grid() well. Dick ============================================================ from Tkinter import * root = Tk() root.option_add('*font', ('verdana', 11)) root.title("Fun with integers") fram = Frame(root).grid() Label(fram, text="Enter a positive integer, n", fg="#996666").grid(row=0,column=3) entry = Entry(fram, fg="red", bg="#DCDCDC", width = 30) entry.focus_set() entry.grid(row=2,column=3, padx=5, pady=5) b1=Button(fram, text="Compute n!", bg="black", fg="white", width = 19,command=compute_fact) b1.grid(row=4,column=0,columnspan=2,sticky=W) b2=Button(fram, text="Partially spell n", fg="black", bg="white", width = 19,command=integer_spell) b2.grid(row=4,column=1,columnspan=2,sticky=W) b3=Button(fram, text="Compute factors of n", bg="#D3D3D3", fg="yellow", width = 19,command=compute_factors) b3.grid(row=4,column=2,columnspan=2,sticky=W) b4=Button(fram, text="Find primes in [n, n+99]", bg="yellow", fg="red", width = 19,command=primes_in_interval) b4.grid(row=4,column=3,columnspan=2,sticky=W) long_text = "See the largest number that can be spelled" b5=Button(fram, text=long_text, fg="green", bg="#BF6AF5", width = 19,command=largest_number) b5.grid(row=4,column=4,columnspan=2,sticky=W) b6=Button(fram, text="EXIT", fg="white", bg="red", width = 19,command=sys.exit) b6.grid(row=4,column=5,columnspan=2,sticky=W) text = ScrolledText(fram, bg = "cyan", fg = "#330000", height=18) #text = Text(fram) text.insert(END, "n-factorial or n-cubed will appear here.\n\n") text.insert(END, 'And again, with commas inserted.\n\n') text.insert(END, "And yet again, in scientific notation.") text.grid(row=5,columnspan=7,sticky=S) mainloop() ================================================================== From john at fouhy.net Mon Nov 27 03:42:41 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Nov 2006 15:42:41 +1300 Subject: [Tutor] python exceptions In-Reply-To: <200611261750.46857.jfabiani@yolo.com> References: <200611260925.39404.jfabiani@yolo.com> <200611261600.34738.jfabiani@yolo.com> <5e58f2e40611261617s1d12b556s8ec610fc14b84f43@mail.gmail.com> <200611261750.46857.jfabiani@yolo.com> Message-ID: <5e58f2e40611261842l6f1448b4yc7f79fad0602630d@mail.gmail.com> On 27/11/06, johnf wrote: > So there are outside exception handlers? OK. thanks for the answer. For now > that all I needed to understand. I'm not sure that "outside" is quite the right word .. If you write Tkinter code, you will (at some point) call mainloop(). mainloop(), in turn, will call your functions, as the user does stuff. If your code raises an exception, mainloop() will "handle" that exception, in that it will print some stuff out, and then go back to looking for events. But it's still part of your program (as opposed to, say, part of the interpreter), it's just not code that you've written yourself. Different GUIs might do things differently.. -- John. From john at fouhy.net Mon Nov 27 03:54:50 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Nov 2006 15:54:50 +1300 Subject: [Tutor] help with Tkinter, please In-Reply-To: <7.0.1.0.2.20061126182558.088f8448@rcblue.com> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> <20061126175920.042f1dcc.klappnase@freenet.de> <7.0.1.0.2.20061126182558.088f8448@rcblue.com> Message-ID: <5e58f2e40611261854g1e43766cn5e05ca8857427b60@mail.gmail.com> On 27/11/06, Dick Moores wrote: > Well, I'm having a terrible time with grid(). I do have the 6 buttons > in the same row, but they're a real mess. Someone please run this and > tell me how to get them looking better. I'm not certain exactly what layout you want, but have a look at this to see if it looks any better: I think you were a bit confused about the role of columnspan. If you say .grid(row=R, column=C, columnspan=2) then the widget you are gridding will occupy (row R, column C) _and_ (row R, column C+1) (ie: it spans two columns). from Tkinter import * root = Tk() root.option_add('*font', ('verdana', 11)) root.title("Fun with integers") fram = Frame(root).grid() Label(fram, text="Enter a positive integer, n", fg="#996666").grid(row=0,column=1,sticky=W) entry = Entry(fram, fg="red", bg="#DCDCDC", width = 30) entry.focus_set() entry.grid(row=1,column=1, padx=5, pady=5,sticky=E+W) b1=Button(fram, text="Compute n!", bg="black", fg="white", width = 19) b1.grid(row=2,column=0,sticky=W) b2=Button(fram, text="Partially spell n", fg="black", bg="white", width = 19) b2.grid(row=2,column=1,sticky=W) b3=Button(fram, text="Compute factors of n", bg="#D3D3D3", fg="yellow", width = 19) b3.grid(row=2,column=2,sticky=W) b4=Button(fram, text="Find primes in [n, n+99]", bg="yellow", fg="red", width = 19) b4.grid(row=2,column=3,sticky=W) long_text = "See the largest number that can be spelled" b5=Button(fram, text=long_text, fg="green", bg="#BF6AF5", width = 19) b5.grid(row=3,column=0,columnspan=3,sticky=E+W) b6=Button(fram, text="EXIT", fg="white", bg="red", width = 19,command=sys.exit) b6.grid(row=3,column=3,sticky=W) #text = ScrolledText(fram, bg = "cyan", fg = "#330000", height=18) text = Text(fram) text.insert(END, "n-factorial or n-cubed will appear here.\n\n") text.insert(END, 'And again, with commas inserted.\n\n') text.insert(END, "And yet again, in scientific notation.") text.grid(row=4,column=0,columnspan=4,sticky=N+S+E+W) mainloop() From rdm at rcblue.com Mon Nov 27 03:53:58 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 26 Nov 2006 18:53:58 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> Message-ID: <7.0.1.0.2.20061126184906.08913550@rcblue.com> At 03:09 PM 11/26/2006, Alan Gauld wrote: >"Dick Moores" wrote > > > Some time has passed and I've made some progress. My question now is > > about the placement of buttons. >... > > one, but I can't get the layout I want, which is the Label on top of > > the Entry, then a row of the first 3 buttons (which respectively > > trigger 3 different computations on the integer the user enters). > > Then below that, the Exit button, with the Text widget at the > > bottom. > >Sounds like 4 frames to me: >1 Frame for the outer 'skin', packed with fill for both X and Y. > >1 frame for the label/entry combo, using pack to position the widgets >inside the frame, then pack the frame inside the outer frame > >1 frame for the row of buttons and I'd use grid to position the >buttons insdide the frame and then pack the frame into the >outer frame (I tend to use grid where I'm positioning things >horizontally and pack when i'm doing it vertiacally. So I >divide my GUI into horizontal layers and then use grid >inside teach layer for horizontally laid out widgets) > >1 frame for the bottom exit button and pack it into the >outer. > > > How to do this? Is it impossible with the pack() method? > >Horizontal layouts are possible using pack, take a look at >the GUI topic and the GUI section of the Case Study topic >in my tutor for examples of using pure pack. But IMHO grid >is easier for horizontal sets. > >Mixing layout styles in a GUI is fine provided you keep each >layout in a frame to itself. Thanks very much, Alan and Kent. For some reason I didn't see your replies before posting my wail of frustration with grid(). Please ignore it. I had tried using extra frames, but hadn't thought to use frames inside of frames. And then a grid inside of one of the inner frames. I'll give that a try right now. And check out the Case Study. Dick From john at fouhy.net Mon Nov 27 03:59:52 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Nov 2006 15:59:52 +1300 Subject: [Tutor] to learn In-Reply-To: <617551.39626.qm@web35709.mail.mud.yahoo.com> References: <617551.39626.qm@web35709.mail.mud.yahoo.com> Message-ID: <5e58f2e40611261859s47244226jdd108f4817cef2ed@mail.gmail.com> On 27/11/06, ED PENNELL wrote: > my name is ED PENNELL, i am using MAC TIGER want > to learn python and use it on emacs,i down loaded 2.5 > python,i will start with IDLE, DO I NEED PORTS FOR MY > MAC and need tutor with MAC.a very fresh starter. > THANKS ED Hi Ed, If you download python from here: http://www.python.org/download/ you get a build with some mac-specific features. You must use this build if you want to use wxWidgets (which is a framework you can use to make graphical user interfaces). You can use macports to install python as well, but it will lack the mac-specific features. macports will make installing some modules easy, though. For what it's worth, I am using python on a mac and I am not using the macports version. Hope this helps. -- John. From rdm at rcblue.com Mon Nov 27 05:17:57 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 26 Nov 2006 20:17:57 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: <5e58f2e40611261854g1e43766cn5e05ca8857427b60@mail.gmail.co m> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> <20061126175920.042f1dcc.klappnase@freenet.de> <7.0.1.0.2.20061126182558.088f8448@rcblue.com> <5e58f2e40611261854g1e43766cn5e05ca8857427b60@mail.gmail.com> Message-ID: <7.0.1.0.2.20061126195210.08abccd0@rcblue.com> At 06:54 PM 11/26/2006, John Fouhy wrote: >On 27/11/06, Dick Moores wrote: > > Well, I'm having a terrible time with grid(). I do have the 6 buttons > > in the same row, but they're a real mess. Someone please run this and > > tell me how to get them looking better. > >I'm not certain exactly what layout you want, but have a look at this >to see if it looks any better: A lot better! And now that I understand columnspan, I was able to move the buttons around and configure them a bit more. I'm quite satisfied now. For this program it seems I won't be needing to employ the nested frames suggested by Alan and Kent. But of course I'll try those anyway, just to learn about them. I have a question about the "EXIT" button's command, command=sys.exit. It fails to quit the program when I've entered too large an integer for factoring, or for prime testing, and I don't want to wait any more for the result. When I'm running the program from my Win XP console, I can quit with a simple Ctrl+C, but this won't be available to the friend I may send the executable to. Is it possible to build in a way to smoothly interrupt, say, a factoring process that's taking too long? Thanks very much, John. Dick >I think you were a bit confused about the role of columnspan. If you >say .grid(row=R, column=C, columnspan=2) then the widget you are >gridding will occupy (row R, column C) _and_ (row R, column C+1) (ie: >it spans two columns). > >from Tkinter import * > >root = Tk() >root.option_add('*font', ('verdana', 11)) >root.title("Fun with integers") >fram = Frame(root).grid() > >Label(fram, text="Enter a positive integer, n", > fg="#996666").grid(row=0,column=1,sticky=W) > >entry = Entry(fram, fg="red", bg="#DCDCDC", width = 30) >entry.focus_set() >entry.grid(row=1,column=1, padx=5, pady=5,sticky=E+W) > > >b1=Button(fram, text="Compute n!", bg="black", fg="white", width = 19) >b1.grid(row=2,column=0,sticky=W) > >b2=Button(fram, text="Partially spell n", fg="black", bg="white", > width = 19) >b2.grid(row=2,column=1,sticky=W) > >b3=Button(fram, text="Compute factors of n", bg="#D3D3D3", > fg="yellow", width = 19) >b3.grid(row=2,column=2,sticky=W) > >b4=Button(fram, text="Find primes in [n, n+99]", bg="yellow", >fg="red", width = 19) >b4.grid(row=2,column=3,sticky=W) > >long_text = "See the largest number that can be spelled" >b5=Button(fram, text=long_text, fg="green", bg="#BF6AF5", width = 19) >b5.grid(row=3,column=0,columnspan=3,sticky=E+W) > >b6=Button(fram, text="EXIT", fg="white", bg="red", width = >19,command=sys.exit) >b6.grid(row=3,column=3,sticky=W) > >#text = ScrolledText(fram, bg = "cyan", fg = "#330000", height=18) >text = Text(fram) >text.insert(END, "n-factorial or n-cubed will appear here.\n\n") >text.insert(END, 'And again, with commas inserted.\n\n') >text.insert(END, "And yet again, in scientific notation.") >text.grid(row=4,column=0,columnspan=4,sticky=N+S+E+W) > >mainloop() >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From cappy2112 at gmail.com Mon Nov 27 04:41:54 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sun, 26 Nov 2006 19:41:54 -0800 Subject: [Tutor] moving from pack to grid in tkinter Message-ID: <8249c4ac0611261941ma790bf5g222d38c437e9c50b@mail.gmail.com> I've got a main window which is 640 * 400. self.root.geometry("600x400") self.label.pack(side=BOTTOM, fill=X) This line would put the label at the bottom of the window, and extend to both left and right edges of the window. I want to change to grid geometry because I have several more widgets to put in the main window. self.label.grid(row=5, column=2, column=0) This put the label at row 5, in the center of the window, but the label didn't extend to the window edges. After reading this http://effbot.org/tkinterbook/grid.htm I tried playing around with other options, but can't get the label to move any lower in the main window self.label.grid(row=10, column=2, column=0) didn't move the label any lower than row 5 My main window isn't constructed using pack(), so I'm not mixing grid and pack in this program. Although, the main window isn't calling grid explicitly either- that's a bit confusing, because I thought all widgets had to call grid or pack to be displayed... What args do I need to move the label to the bottom of the window, and centered so it extends to both left and right edges? I don't like to hard-code a row number, I'd rather make the label dynamically be assigned to the bootm ros of the window, in case the window grows or shrinks. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061126/865c8f41/attachment.html From john at fouhy.net Mon Nov 27 05:55:26 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Nov 2006 17:55:26 +1300 Subject: [Tutor] help with Tkinter, please In-Reply-To: <7.0.1.0.2.20061126195210.08abccd0@rcblue.com> References: <7.0.1.0.2.20061123014854.00bfccf0@rcblue.com> <20061123170135.3bf74dff.klappnase@freenet.de> <7.0.1.0.2.20061123130300.01f41170@rcblue.com> <7.0.1.0.2.20061125170157.06489650@rcblue.com> <20061126175920.042f1dcc.klappnase@freenet.de> <7.0.1.0.2.20061126182558.088f8448@rcblue.com> <5e58f2e40611261854g1e43766cn5e05ca8857427b60@mail.gmail.com> <7.0.1.0.2.20061126195210.08abccd0@rcblue.com> Message-ID: <5e58f2e40611262055p14aae7d3v7380750f26f0de4e@mail.gmail.com> On 27/11/06, Dick Moores wrote: > I have a question about the "EXIT" button's command, > command=sys.exit. It fails to quit the program when I've entered too > large an integer for factoring, or for prime testing, and I don't > want to wait any more for the result. When I'm running the program > from my Win XP console, I can quit with a simple Ctrl+C, but this > won't be available to the friend I may send the executable to. Is it > possible to build in a way to smoothly interrupt, say, a factoring > process that's taking too long? Well, as you may know, the "core" of Tkinter (or most GUIs, I think) is the event loop. The event loop basically does this: 1. Look for events (mouse clicks, keypresses, etc.) 2. Process events (update widgets, call callbacks) 3. GOTO 1. So, in this specific case, the event loop is doing this: 1. Look for events ==> user clicks on "factorise" button. 2. Process events ==> call "factorise" button callback. 3. Callback runs... 4. ...callback completes. 5. Look for events ==> user clicks on "exit" button. 6. Process events ==> call "exit" button callback. 7. Python exits. So, you can see why clicking your exit button won't interrupt the calculation in progress. The only way you can do that is if you can get the event loop to start looking for events again before the callback finishes. And that means THREADS. HTH :-) -- John. From john at fouhy.net Mon Nov 27 06:07:33 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Nov 2006 18:07:33 +1300 Subject: [Tutor] moving from pack to grid in tkinter In-Reply-To: <8249c4ac0611261941ma790bf5g222d38c437e9c50b@mail.gmail.com> References: <8249c4ac0611261941ma790bf5g222d38c437e9c50b@mail.gmail.com> Message-ID: <5e58f2e40611262107j2a55cdw32da4359d38c40a@mail.gmail.com> On 27/11/06, Tony Cappellini wrote: > I've got a main window which is 640 * 400. > self.root.geometry("600x400") > > self.label.pack(side=BOTTOM, fill=X) > This line would put the label at the bottom of the window, and extend to > both left and right edges of the window. So, something like a status bar? Using pack() is really the easiest way to do this. Here's what I'd do: self.label = Label(root) # etc self.label.pack(side=BOTTOM, fill=X) self.interior = Frame(root) self.interior.pack(SIDE=TOP, fill=BOTH, expand=True) ...and then create all your other widgets as children of self.interior. > I want to change to grid geometry because I have several more widgets to put > in the main window. > self.label.grid(row=5, column=2, column=0) Not sure why you have two column= options here.. One of them should be columnspan, maybe? > This put the label at row 5, in the center of the window, but the label > didn't extend to the window edges. Using grid geometry, widgets will take their natural size and sit in the middle of the cell you place them in. If you want to override this, you need to specify which edge or edges you want the widget to stick to. In this case, you want the widget to stick to both the left and right edges, so that it is stretched across the width of the screen. You can do this by saying: self.label.grid(row=5, column=0, columnspan=2, sticky=E+W) E+W means "east and west". > self.label.grid(row=10, column=2, column=0) didn't move the label any lower > than row 5 If there is nothing in a row, the row will have a height of zero. So row 5 and row 10 are equivalent, if rows 6..9 are empty and there are no other widgets in 5 or 10. There's no way to say "put this in the last row", but you could put it in row 999 or something. > Although, the main window isn't calling grid explicitly either- that's a bit > confusing, because I thought all widgets had to call grid or pack to be > displayed... The root window Tk(), and any windows you create using Toplevel(), will display themselves. Other widgets need to be put inside a frame and pack()ed or grid()ded (or place()d). HTH! -- John. From ajkadri at googlemail.com Mon Nov 27 13:06:54 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 27 Nov 2006 12:06:54 +0000 Subject: [Tutor] How to generate permutations of a given string Message-ID: Hello folks, Can someone help me with a simple algorithm to generate permutations of a given string: Input string:---->> 'abc' Output:------->> ['abc','acb','bac','bca','cab','cba'] Thanks. Regards, Asrarahmed Kadri - To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061127/9fbb395b/attachment.htm From kloosterjunkie at hotmail.com Mon Nov 27 13:20:41 2006 From: kloosterjunkie at hotmail.com (Moedeloos Overste) Date: Mon, 27 Nov 2006 13:20:41 +0100 Subject: [Tutor] Newbie question: join() string method Message-ID: Hi, I'm trying to use the join() method on a list to be able to store the contents of that list in a file. Basically I want the contents of the list stored without the []. I've tried numerous ways of using the join() method, but they all return errors. I've tried using the tutorial and documentation on this one but still can't work it out. errors: TypeError: sequence item 0: expected string, int found code: LotNumbers = random.sample(range(1,45), 6) #random numbers from range into list) ','.join() #?what's the correct syntax? fout = open("draw__output.dat", "a") fout.write(LotNumbers) #writing string to file fout.close() vDraws = vDraws - 1 Can someone show me the correct way to use the join() method in this case? Many thanks, Robert _________________________________________________________________ De makers van Hotmail hebben groot nieuws! Meer weten? Klik hier! http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl From andreas at kostyrka.org Mon Nov 27 13:32:59 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 27 Nov 2006 13:32:59 +0100 Subject: [Tutor] Newbie question: join() string method Message-ID: ",".join(str(x) for x in intList) Andreas _____ Urspr?ngliche Mitteilung _____ Betreff: [Tutor] Newbie question: join() string method Autor: "Moedeloos Overste" Datum: 27. November 2006 13:20:41 Hi, I'm trying to use the join() method on a list to be able to store the contents of that list in a file. Basically I want the contents of the list stored without the []. I've tried numerous ways of using the join() method, but they all return errors. I've tried using the tutorial and documentation on this one but still can't work it out. errors: TypeError: sequence item 0: expected string, int found code: LotNumbers = random.sample(range(1,45), 6) #random numbers from range into list) ','.join() #?what's the correct syntax? fout = open("draw__output.dat", "a") fout.write(LotNumbers) #writing string to file fout.close() vDraws = vDraws - 1 Can someone show me the correct way to use the join() method in this case? Many thanks, Robert _________________________________________________________________ De makers van Hotmail hebben groot nieuws! Meer weten? Klik hier! http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061127/065d2022/attachment.html From jhlaks at gmail.com Mon Nov 27 14:40:55 2006 From: jhlaks at gmail.com (jhl) Date: Mon, 27 Nov 2006 06:40:55 -0700 Subject: [Tutor] Newbie question: join() string method In-Reply-To: References: Message-ID: <63f2a80c0611270540g5d5c49fau11b884c19af90de9@mail.gmail.com> Hi, I am not sure what 'random' does (what package is it from?), but list=['1','2','3'] slist=','.join(list) works, while list=[1,2,3] slist=','.join(list) does not. It appears 'join' only works on lists (and maybe tuples?) of string objects and the list must be passed in as an argument. Try translating your list into a list of string representation of numbers and then using join. Hope this is a useful clue, -Jason On 11/27/06, Moedeloos Overste wrote: > > Hi, > > I'm trying to use the join() method on a list to be able to store the > contents of that list in a file. Basically I want the contents of the list > stored without the []. I've tried numerous ways of using the join() > method, > but they all return errors. I've tried using the tutorial and > documentation > on this one but still can't work it out. > > errors: TypeError: sequence item 0: expected string, int found > > > > code: > LotNumbers = random.sample(range(1,45), 6) #random numbers from range into > list) > ','.join() #?what's > the > correct syntax? > fout = open("draw__output.dat", "a") > fout.write(LotNumbers) #writing string to > file > fout.close() > vDraws = vDraws - 1 > > Can someone show me the correct way to use the join() method in this case? > > Many thanks, > > Robert > > _________________________________________________________________ > De makers van Hotmail hebben groot nieuws! Meer weten? Klik hier! > http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061127/da758267/attachment.htm From python at venix.com Mon Nov 27 15:09:56 2006 From: python at venix.com (Python) Date: Mon, 27 Nov 2006 09:09:56 -0500 Subject: [Tutor] What are the issues in running Python script on another machine (developed on Windows but will be using on Linux) In-Reply-To: References: Message-ID: <1164636596.19530.405.camel@www.venix.com> On Sun, 2006-11-26 at 15:14 +0000, Asrarahmed Kadri wrote: > > > Hi folks, > > I have a couple of programs that I want to test on a different > machine.. > > I have developed these on Win-XP platform, but I want to test them on > my college's machine, which is running Linux. > > Are there any issues involved or i just need to take my files on a USB > memory stick, and copy paste and that is it..? > You may need to use dos2unix to convert the DOS/Windows line endings (\r\n) to Unix/Linux/BSD endings (\n) Example usage is: dos2unix myscript.py It's a simple thing to try if you get mysterious errors. > thanks for the help. > > Regards, > Asrarahmed > > -- > To HIM you shall return. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From kent37 at tds.net Mon Nov 27 15:52:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Nov 2006 09:52:01 -0500 Subject: [Tutor] What are the issues in running Python script on another machine (developed on Windows but will be using on Linux) In-Reply-To: <1164636596.19530.405.camel@www.venix.com> References: <1164636596.19530.405.camel@www.venix.com> Message-ID: <456AFB91.2070503@tds.net> Python wrote: > On Sun, 2006-11-26 at 15:14 +0000, Asrarahmed Kadri wrote: >> >> >> Hi folks, >> >> I have a couple of programs that I want to test on a different >> machine.. >> >> I have developed these on Win-XP platform, but I want to test them on >> my college's machine, which is running Linux. >> >> Are there any issues involved or i just need to take my files on a USB >> memory stick, and copy paste and that is it..? >> > > You may need to use dos2unix to convert the DOS/Windows line endings > (\r\n) > to Unix/Linux/BSD endings > (\n) > > Example usage is: > dos2unix myscript.py > > It's a simple thing to try if you get mysterious errors. Since Python 2.3, script files are opened with universal newline support: http://www.python.org/doc/2.3.5/whatsnew/node7.html It is a good idea in portable code to use os.path.join() to create file paths, rather than hard-coding the path separator (/ or \). Or you can just use / as a file separator which works on Windows and Linux. You could conceivably have issues with text file encoding if you are working with text data that includes characters outside the ASCII set. Kent From kloosterjunkie at hotmail.com Mon Nov 27 16:30:01 2006 From: kloosterjunkie at hotmail.com (Moedeloos Overste) Date: Mon, 27 Nov 2006 16:30:01 +0100 Subject: [Tutor] Newbie question: join() string method Message-ID: Ha! Thanx for all the input everybody. I finally got it to work. The contents of the list is now stored in the file without the []. The solution is in the code below. Next step in my learning process is reading the file contents and storing it in a dictionary. One question: When I run the program from IDLE it writes the data to file but when I run it from the command prompt(win32) it doesn't. why is this? code: vDraws = input("How many times do you want to draw the lottery? :>") # Draw lottery numbers & writing them to file while vDraws > 0: LotNumbers = random.sample(range(1,45), 6) #random numbers from range into list) strgOutput=",".join(str(i) for i in LotNumbers) #??????converting list to string to store it. fout = open("draw__output.dat", "a") fout.write(strgOutput + "\n") #writing string to file fout.close() vDraws = vDraws - 1 >From: "Andreas Kostyrka" >Reply-To: "Andreas Kostyrka" >To: "Moedeloos Overste" >CC: tutor at python.org >Subject: Re: [Tutor] Newbie question: join() string method >Date: Mon, 27 Nov 2006 13:32:59 +0100 > >",".join(str(x) for x in intList) > >Andreas > >_____ Urspr??ngliche Mitteilung _____ >Betreff: [Tutor] Newbie question: join() string method >Autor: "Moedeloos Overste" >Datum: 27. November 2006 13:20:41 > >Hi, > >I'm trying to use the join() method on a list to be able to store the >contents of that list in a file. Basically I want the contents of the list >stored without the []. I've tried numerous ways of using the join() method, >but they all return errors. I've tried using the tutorial and documentation >on this one but still can't work it out. > >errors: TypeError: sequence item 0: expected string, int found > > > >code: >LotNumbers = random.sample(range(1,45), 6) #random numbers from range into >list) > ','.join() #?what's >the >correct syntax? > fout = open("draw__output.dat", "a") > fout.write(LotNumbers) #writing string to >file > fout.close() > vDraws = vDraws - 1 > >Can someone show me the correct way to use the join() method in this case? > >Many thanks, > >Robert > >_________________________________________________________________ >De makers van Hotmail hebben groot nieuws! Meer weten? Klik hier! >http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Windows Live Mail: Slim, Persoonlijk, Betrouwbaar en het blijft natuurlijk gratis! http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl From alan.gauld at btinternet.com Mon Nov 27 16:43:35 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Nov 2006 15:43:35 -0000 Subject: [Tutor] How to generate permutations of a given string References: Message-ID: "Asrarahmed Kadri" wrote > Can someone help me with a simple algorithm to generate permutations > of a > given string: Try Googling for python string permutation. Several approaches came up including a cookbook page entry. Alan G. From magoldfish at gmail.com Mon Nov 27 18:16:48 2006 From: magoldfish at gmail.com (Marcus Goldfish) Date: Mon, 27 Nov 2006 12:16:48 -0500 Subject: [Tutor] __init__.py for running a file from commandline? In-Reply-To: <4555C88D.3080503@tds.net> References: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> <4555C88D.3080503@tds.net> Message-ID: <5e183f3d0611270916p1c14c3b3s4837f6118d7f557d@mail.gmail.com> On 11/11/06, Kent Johnson wrote: > > Marcus Goldfish wrote: > > Hoping someone can help with this... > > > > I have a logical python namespace using a directory tree and __init__.py > > files. For example, PYTHONPATH points to ~pyroot, and I have the > following: > > > > ~pyroot/ > > ~pyroot/utils/ > > ~pyroot/utils/commands/mygrep.py > > > > Which makes it nice to code: > > > > # some python script > > import utils.commands.mygrep as grep > > > > However, I have a problem when running python scripts from the command > > line. I would like to do this: > > > > > python utils.commands.mygrep.py > > > > but it doesn't work. Is there a trick, or something that I am missing, > > that will let me run scripts like that? > > python utils/commands/mygrep.py > will work if mygrep.py doesn't import other modules from utils; not sure > if it will work with imports. > > Kent Kent, Hmmm... I tried this on my WinXP box-- didn't work nor with backslashing). I checked my environment variables in my shell, and PYTHONPATH points to ~pyroot. Am I missing something? Could this be a 'nix thing? Marcus -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061127/fddd99c6/attachment.htm From cappy2112 at gmail.com Mon Nov 27 18:32:54 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Mon, 27 Nov 2006 09:32:54 -0800 Subject: [Tutor] e: moving from pack to grid in tkinter Message-ID: <8249c4ac0611270932q389fbd89kbae32c134fefa911@mail.gmail.com> Date: Mon, 27 Nov 2006 18:07:33 +1300 From: "John Fouhy" Subject: Re: [Tutor] moving from pack to grid in tkinter To: tutor-python Message-ID: <5e58f2e40611262107j2a55cdw32da4359d38c40a at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 27/11/06, Tony Cappellini wrote: > I've got a main window which is 640 * 400. > self.root.geometry("600x400") > > self.label.pack(side=BOTTOM, fill=X) > This line would put the label at the bottom of the window, and extend to > both left and right edges of the window. >>So, something like a status bar? Yes exactly. I started with pack- and the status bar was ok. Then I read the pdf at Effbot.org. I need to add several widgets to the main frame, so I figured I would use grid for all of them. Using pack() is really the easiest way to do this. Here's what I'd do: >> But i'm trying to get away from pack() and use grid() >>Not sure why you have two column= options here.. One of them should be >>columnspan, maybe? Just a typi- I originally had columnspan, to see how it affected the widget- it didnt'. I was in the middle of an edit when I decided to post the message- but I had tried cloumn with and without columnspan, no effect. >>Using grid geometry, widgets will take their natural size and sit in >>the middle of the cell you place them in. If you want to override >>this, you need to specify which edge or edges you want the widget to >>stick to. >>self.label.grid(row=5, column=0, columnspan=2, sticky=E+W) I tried sticky E+W- again no effect on the edges of the label:( >>f there is nothing in a row, the row will have a height of zero. So So how does one place a label (or any other widget) at the bottom row of a screen using grid()? It worked fine using pack- but the turoail pdf recommended grid() is easier when working with several widgets in a common container widget >>HTH! Well thanks anyway. The pdf has really confused me. Is there an official tkinter.org doc reference or something? -- John. ------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061127/cc8a5ec1/attachment.html From kent37 at tds.net Mon Nov 27 18:38:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Nov 2006 12:38:59 -0500 Subject: [Tutor] __init__.py for running a file from commandline? In-Reply-To: <5e183f3d0611270916p1c14c3b3s4837f6118d7f557d@mail.gmail.com> References: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> <4555C88D.3080503@tds.net> <5e183f3d0611270916p1c14c3b3s4837f6118d7f557d@mail.gmail.com> Message-ID: <456B22B3.4070207@tds.net> Marcus Goldfish wrote: > > > On 11/11/06, *Kent Johnson* > wrote: > > Marcus Goldfish wrote: > > Hoping someone can help with this... > > > > I have a logical python namespace using a directory tree and > __init__.py > > files. For example, PYTHONPATH points to ~pyroot, and I have the > following: > > > > ~pyroot/ > > ~pyroot/utils/ > > ~pyroot/utils/commands/mygrep.py > > > > Which makes it nice to code: > > > > # some python script > > import utils.commands.mygrep as grep > > > > However, I have a problem when running python scripts from the > command > > line. I would like to do this: > > > > > python utils.commands.mygrep.py > > > > but it doesn't work. Is there a trick, or something that I am > missing, > > that will let me run scripts like that? > > python utils/commands/mygrep.py > will work if mygrep.py doesn't import other modules from utils; not > sure > if it will work with imports. > > Kent > > > Kent, > > Hmmm... I tried this on my WinXP box-- didn't work nor with > backslashing). I checked my environment variables in my shell, and > PYTHONPATH points to ~pyroot. Am I missing something? Could this be a > 'nix thing? It works for me on WinXP to run a simple script with no dependencies, with forward or back slashes. I don't have PYTHONPATH set at all. How does it fail for you? Kent From arcege at gmail.com Mon Nov 27 18:40:26 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Mon, 27 Nov 2006 12:40:26 -0500 Subject: [Tutor] __init__.py for running a file from commandline? In-Reply-To: <5e183f3d0611270916p1c14c3b3s4837f6118d7f557d@mail.gmail.com> References: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> <4555C88D.3080503@tds.net> <5e183f3d0611270916p1c14c3b3s4837f6118d7f557d@mail.gmail.com> Message-ID: <7e5ba9220611270940g2689faeased0bd28b5972c6b3@mail.gmail.com> Marcus, When you type something from the command-line, you are at the whims of the WinXP command shell. You have to follow its rules, not Python's. It would need to have "python" in %PATH%, and then it would need to have to run "python C:\path\to\pyroot\utils\commands\mygrep.py". The arguments are determined before Python is even started, and they are parsed by the WinXP DOS-a-like shell. (Also why you cannot have ".", only Python understands dots). Kent mentioned issues with importing modules, and those would still hold true since those are after Python starts. Also, the WinXP shell, does handle forward slashs, but you were probably not in the proper directory for the shell to find the file using "utils/commands/mygrep.py" pathname. HTH, -Arcege On 11/27/06, Marcus Goldfish wrote: > > > > On 11/11/06, Kent Johnson wrote: > > > > Marcus Goldfish wrote: > > > Hoping someone can help with this... > > > > > > I have a logical python namespace using a directory tree and > > __init__.py > > > files. For example, PYTHONPATH points to ~pyroot, and I have the > > following: > > > > > > ~pyroot/ > > > ~pyroot/utils/ > > > ~pyroot/utils/commands/mygrep.py > > > > > > Which makes it nice to code: > > > > > > # some python script > > > import utils.commands.mygrep as grep > > > > > > However, I have a problem when running python scripts from the command > > > line. I would like to do this: > > > > > > > python utils.commands.mygrep.py > > > > > > but it doesn't work. Is there a trick, or something that I am > > missing, > > > that will let me run scripts like that? > > > > python utils/commands/mygrep.py > > will work if mygrep.py doesn't import other modules from utils; not sure > > > > if it will work with imports. > > > > Kent > > > Kent, > > Hmmm... I tried this on my WinXP box-- didn't work nor with > backslashing). I checked my environment variables in my shell, and > PYTHONPATH points to ~pyroot. Am I missing something? Could this be a 'nix > thing? > > Marcus > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061127/dddc4772/attachment.htm From alan.gauld at btinternet.com Mon Nov 27 19:46:04 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Nov 2006 18:46:04 -0000 Subject: [Tutor] Newbie question: join() string method References: Message-ID: "Moedeloos Overste" wrote > One question: When I run the program from IDLE it writes the data to > file > but when I run it from the command prompt(win32) it doesn't. why is > this? How do you know? Have you searched for the file? Or are you looking in the same file that IDLE produced? I would expect the code to create a new file in the current directory - wherever you started the program. Did you look there? ----------------------- while vDraws > 0: LotNumbers = random.sample(range(1,45), 6) #random numbers from range into list) strgOutput=",".join(str(i) for i in LotNumbers) #??????converting list to string to store it. fout = open("draw__output.dat", "a") fout.write(strgOutput + "\n") #writing string to file fout.close() -------------------------- It's probably better to put the open/close outside the loop fout = open(...,'w') while vDraws > 0 ... fout.write(strgOutput + '\n') vDraws -= 1 fout.close() That way you can use 'w' to write the file(unless you really want the previous runs to be in there too.) Also this will save the program opening and closing the file for each line which is quite a slow process. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Nov 27 19:55:02 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Nov 2006 18:55:02 -0000 Subject: [Tutor] moving from pack to grid in tkinter References: <8249c4ac0611270932q389fbd89kbae32c134fefa911@mail.gmail.com> Message-ID: "Tony Cappellini" wrote >>> > But i'm trying to get away from pack() and use grid() There's no good reason not to use pack where it makes sense. You can mix n match provided you keep it consistent within a single container(usually a frame) Grid is best where the controls conform to a grid, typically when laid out across the Frame. Pack is a natural where you want to stack things on top of each other. Typically I use pack for the frames in the main window and grid for the widgets inside each frame. A status bar is most naturally expressed as a frame at the bottom of your window containing a label widget so I'd use pack for it. You can force it wirth grid by picking a very large number but its a bit of a kluge in my view. >>>f there is nothing in a row, the row will have a height of zero. >>>So > So how does one place a label (or any other widget) at the bottom > row of a > screen using grid()? Are you using grid on your top window or on a frame within that? It sounds like maybe the former. Try creating a frame and gridding it into the main window. Then grid your widgets inside the Frame. (I haven't tried this but it sounds like a possibility!) That way the window should shrink to fit the frame... . > Well thanks anyway. The pdf has really confused me. > Is there an official tkinter.org doc reference or something? Have you checked the Tkinter page in the Python.org web site? Also the Tcl/Tk documentation gives a fairly definitive description of how things work, albeit expressed in Tcl speak HTH, Alan G. From ktroell at mac.com Mon Nov 27 20:31:43 2006 From: ktroell at mac.com (Keith Troell) Date: Mon, 27 Nov 2006 13:31:43 -0600 Subject: [Tutor] AttributeError: 'list' object has no attribute 'copy' Message-ID: <0D7D9C75-5BA4-4E93-8160-03CF98CF6913@mac.com> I'm a rank beginner. I am running Python 2.3.5 on the Terminal of Mac OSX. The Tutorial (5.1) mentions list.copy as a list method. When I run scores = [1, 2, 3] copy = scores.copy () I get: AttributeError: 'list' object has no attribute 'copy' However, I am able to use .copy for dictionaries without any problem. >>> scores = {} >>> copy = scores.copy () >>> copy {} >>> Do I need to import a module to use list.copy? What am I missing? TIA, Keith A++ G++ PKR+ !PEG B- TB ADB-- M+++ CHOW++ http://zbigniew.pyrzqxgl.com/bargegeek.html From kent37 at tds.net Mon Nov 27 20:55:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Nov 2006 14:55:48 -0500 Subject: [Tutor] AttributeError: 'list' object has no attribute 'copy' In-Reply-To: <0D7D9C75-5BA4-4E93-8160-03CF98CF6913@mac.com> References: <0D7D9C75-5BA4-4E93-8160-03CF98CF6913@mac.com> Message-ID: <456B42C4.8000700@tds.net> Keith Troell wrote: > I'm a rank beginner. I am running Python 2.3.5 on the Terminal of Mac > OSX. > > The Tutorial (5.1) mentions list.copy as a list method. When I run Are you sure? I don't see it here: http://www.python.org/doc/2.3.5/tut/node7.html#SECTION007100000000000000000 > > scores = [1, 2, 3] > copy = scores.copy () > > I get: AttributeError: 'list' object has no attribute 'copy' You can copy a list with the list() function or by slicing: copy = list(scores) or copy = scores[:] Kent From kloosterjunkie at hotmail.com Mon Nov 27 21:32:05 2006 From: kloosterjunkie at hotmail.com (Moedeloos Overste) Date: Mon, 27 Nov 2006 21:32:05 +0100 Subject: [Tutor] ashamed In-Reply-To: Message-ID: I shamefully bowe my head. How stupid of me not to think of that. I assumed that as the script is in a certain directory the output would also be in that directory. A very humbling learning experience.... Thank you for the pointer on file open/close outside of the loop. That should speed things up Right now I'm kept busy by dictionaries. I've created a dictionary containing all possible keys(lottery numbers) with their values set to zero. Now I want read the file and for each time a key is in the file i want it's value to go up +1. Like a counter. So far I've not been succesfull:-) see code. d={1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0, 13:0, 14:0, 15:0, 16:0, 17:0, 18:0, 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, 27:0, 28:0, 29:0, 30:0, 31:0, 32:0, 33:0, 34:0, 35:0, 36:0, 37:0, 38:0, 39:0, 40:0, 41:0, 42:0, 43:0, 44:0, 45:0} done=0 fd = open("draw__output.txt",'r') while not done: line = fd.readline() if line == '': done = 1 else: for i in line: d[i] = int(d[i])+ 1 >From: "Alan Gauld" >To: tutor at python.org >Subject: Re: [Tutor] Newbie question: join() string method >Date: Mon, 27 Nov 2006 18:46:04 -0000 > >"Moedeloos Overste" wrote > > > One question: When I run the program from IDLE it writes the data to > > file > > but when I run it from the command prompt(win32) it doesn't. why is > > this? > >How do you know? Have you searched for the file? >Or are you looking in the same file that IDLE produced? >I would expect the code to create a new file in the current >directory - wherever you started the program. Did you look >there? > >----------------------- >while vDraws > 0: > LotNumbers = random.sample(range(1,45), 6) #random numbers from >range >into list) > strgOutput=",".join(str(i) for i in LotNumbers) >#??????converting list >to string to store it. > fout = open("draw__output.dat", "a") > fout.write(strgOutput + "\n") #writing string to file > fout.close() >-------------------------- > >It's probably better to put the open/close outside the loop > >fout = open(...,'w') >while vDraws > 0 > ... > fout.write(strgOutput + '\n') > vDraws -= 1 >fout.close() > >That way you can use 'w' to write the file(unless you really want the >previous runs to be in there too.) Also this will save the program >opening and closing the file for each line which is quite a slow >process. > >HTH, > > >-- >Alan Gauld >Author of the Learn to Program web site >http://www.freenetpages.co.uk/hp/alan.gauld > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Windows Live Mail: Slim, Persoonlijk, Betrouwbaar en het blijft natuurlijk gratis! http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl From john.corry at ntlworld.com Mon Nov 27 21:31:37 2006 From: john.corry at ntlworld.com (John CORRY) Date: Mon, 27 Nov 2006 20:31:37 -0000 Subject: [Tutor] adjust key bindings In-Reply-To: <456A3F7B.9080309@gmail.com> Message-ID: <003501c71263$0eefb040$523ea8c0@JOHNC> Luke, Thanks for the response. I am trying to help someone out on the Pygtk list. I forgot to enclose his reasons for wanting to assign the key press. They are below: It looks like he likes his keys set out in a certain way. I am happy with mine the way they are! I used "z" in isolation just to get the logic right. I know I can assign a function to Z and make the Treeview move down one row and select the row below but I don't want to have to do this for all the different buttons. I am trying to do it without having to assign and call a whole load of different functions. > I just start to use pygtk ... so it is just my first > question :-) > > I would like to create a small file manager based on 'lfm' (curses > based file manager). I used glade for the gui and I am able to display > the existing files and directories using two treeview widgets. > Now, at the beginning I am kind of stuck with the key bindings. In 'lfm' > it was pretty easy to define special key bindings: > > > keytable = { > # movement > ord('p'): 'cursor_up', > ord('k'): 'cursor_up', > ord('K'): 'cursor_up2', > ord('P'): 'cursor_up', > curses.KEY_UP: 'cursor_up', > ord('n'): 'cursor_down', > ord('j'): 'cursor_down', > ord('J'): 'cursor_down2', > ord('N'): 'cursor_down', > curses.KEY_DOWN: 'cursor_down', > curses.KEY_PPAGE: 'page_previous', > curses.KEY_BACKSPACE: 'page_previous', > 0x08: 'page_previous', # BackSpace > 0x10: 'page_previous', # Ctrl-P > curses.KEY_NPAGE: 'page_next', > ord(' '): 'page_next', > 0x0E: 'page_next', # Ctrl-N > curses.KEY_HOME: 'home', > 0x16A: 'home', > ord('H'): 'home', > 0x001: 'home', > curses.KEY_END: 'end', > ord('G'): 'end', > 0x181: 'end', > 0x005: 'end', > ord('h'): 'cursor_left', > ord('l'): 'cursor_right', > curses.KEY_LEFT: 'cursor_left', > curses.KEY_RIGHT: 'cursor_right', > ord('g'): 'goto_dir', > 0x13: 'goto_file', # Ctrl-S > 0x14: 'tree', # Ctrl-T > ord('0'): 'bookmark_0', > ord('1'): 'bookmark_1', > ... > > > with such a keytable I am able to bind different 'def's to every > existing key. As you can see, I like it a lot to use 'vim-like' keys > for moving around; 'j' and 'k' to move a row up and down. In glade I > found those 'accelerators', but it is just for certain functions. > Does anyone have an idea about using such a keybinding in > pygtk? Would be nice! > I have attempted to answer his question but I am not sure I am on the right track. Is there a better way to do it? Regards, John. -----Original Message----- From: Luke Paireepinart [mailto:rabidpoobear at gmail.com] Sent: 27 November 2006 01:30 To: john.corry at ntlworld.com Cc: tutor at python.org Subject: Re: [Tutor] adjust key bindings John CORRY wrote: > Hi All, > > I have been trying to bind the "z" key to the "Down" key using Python > 2.4, Glade 2 and Pygtk. I have posted this problem on the Pygtk list > but have had no response. I was hoping somebody on the tutor list could > help. I think that I am close. I can capture the "z" key press and > assign a "Down" key press but I can't get the "Down" key press to > register on the Treeview in the GUI. > > Any thoughts greatly appreciated. > > Thanks, > > John. I highly doubt that what you want to do when someone hits a 'z' is to generate a 'down' keypress. What if the user assigned the down key to z? then you'd have a z -> down -> z -> down -> .... infinite loop. What I expect you want is that each key, z and down, perform the same action. In other words, they both call the same function. So basically what you'd want is something like this (non-pyGTK specific code) def aFunc(): print "Hello, World!" bindKey = {'down':aFunc} keypress = raw_input("What keypress do you want to perform?") bindKey[keypress]()#this will call the 'aFunc' function if they type 'down', otherwise, it'll probably crash. bindKey['z'] = aFunc bindKey['z']()# now performs the same function as bindkey['down']()#this does. If you really do want to generate 'down' keypresses when someone hits 'z', please explain why, and I will try to the best of my abilities to help you in that regard! Good Luck! -Luke > > From john at fouhy.net Mon Nov 27 22:09:26 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 28 Nov 2006 10:09:26 +1300 Subject: [Tutor] e: moving from pack to grid in tkinter In-Reply-To: <8249c4ac0611270932q389fbd89kbae32c134fefa911@mail.gmail.com> References: <8249c4ac0611270932q389fbd89kbae32c134fefa911@mail.gmail.com> Message-ID: <5e58f2e40611271309y5c285ea6q885baedbbc7917fe@mail.gmail.com> On 28/11/06, Tony Cappellini wrote: > But i'm trying to get away from pack() and use grid() Why? Sometimes pack() is the right option. You can do things with pack that you can't do with grid. You can use both in your program -- just don't use both in the same frame. > Well thanks anyway. The pdf has really confused me. > Is there an official tkinter.org doc reference or something? Um, not really. There are official Tk docs (at http://tcl.tk), and a few sites around with Tkinter docs (effbot, New Mexico Tech), but nothing "official". -- John. From wescpy at gmail.com Mon Nov 27 23:28:44 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 27 Nov 2006 14:28:44 -0800 Subject: [Tutor] Newbie question: join() string method In-Reply-To: References: Message-ID: <78b3a9580611271428j20b61a25s15c8517edda59b0c@mail.gmail.com> > strgOutput=",".join(str(i) for i in LotNumbers) #??????converting list > to string to store it. note that here, you are *not* converting the list to a string to store it. you are converting each list member to a string and creating a new "list" (actually generator [expression]) for the string.join() method to takes its contents (now strings) and concatenate them together into one large string delimited by ','s. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ktroell at mac.com Mon Nov 27 23:29:54 2006 From: ktroell at mac.com (Keith Troell) Date: Mon, 27 Nov 2006 16:29:54 -0600 Subject: [Tutor] AttributeError: 'list' object has no attribute 'copy' In-Reply-To: <456B42C4.8000700@tds.net> References: <0D7D9C75-5BA4-4E93-8160-03CF98CF6913@mac.com> <456B42C4.8000700@tds.net> Message-ID: On Nov 27, 2006, at 1:55 PM, Kent Johnson wrote: > Keith Troell wrote: >> I'm a rank beginner. I am running Python 2.3.5 on the Terminal of >> Mac OSX. >> The Tutorial (5.1) mentions list.copy as a list method. When I run > > Are you sure? I don't see it here: > http://www.python.org/doc/2.3.5/tut/ > node7.html#SECTION007100000000000000000 Nope, it's not there. Must have had a brain spasm... > >> scores = [1, 2, 3] >> copy = scores.copy () >> I get: AttributeError: 'list' object has no attribute 'copy' > > You can copy a list with the list() function or by slicing: > copy = list(scores) > or > copy = scores[:] > That'll work. Thanks Keith From Barry.Carroll at psc.com Mon Nov 27 21:39:25 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 27 Nov 2006 12:39:25 -0800 Subject: [Tutor] How to generate permutations of a given string Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A37@eugsrv400.psc.pscnet.com> Hello, Asrarahmed > -----Original Message----- > Date: Mon, 27 Nov 2006 12:06:54 +0000 > From: "Asrarahmed Kadri" > Subject: [Tutor] How to generate permutations of a given string > To: tutor-python > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Hello folks, > > > Can someone help me with a simple algorithm to generate permutations of a > given string: > > Input string:---->> 'abc' > > Output:------->> ['abc','acb','bac','bca','cab','cba'] > > Thanks. > Regards, > Asrarahmed Kadri > - > To HIM you shall return. I'm not sure these qualify as "simple", but they work. This was one of my very first projects in Python, so it may be more complicated than necessary. ########## def permute (word): """ Accepts a string. Returns a list of all permutations of the string using all characters. """ retList=[] if len(word) == 1: # There is only one possible permutation retList.append(word) else: # Return a list of all permutations using all characters for pos in range(len(word)): # Get the permutations of the rest of the word permuteList=permute2(word[0:pos]+word[pos+1:len(word)]) # Now, tack the first char onto each word in the list # and add it to the output for item in permuteList: retList.append(word[pos]+item) return retList ########## Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From shitizb at yahoo.com Mon Nov 27 23:36:34 2006 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon, 27 Nov 2006 14:36:34 -0800 (PST) Subject: [Tutor] Convert string to file handle In-Reply-To: Message-ID: <20061127223634.36894.qmail@web53809.mail.yahoo.com> Hi, i have a string abc. i need a file handle f pointing to a file which contains this string. is there any way i can achieve this without actually writing the contents to a file and then opening it? for performance reasons i want to run this entire process within the physical memory! Thanks, Shitiz __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061127/d196c817/attachment.html From john at fouhy.net Mon Nov 27 23:49:12 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 28 Nov 2006 11:49:12 +1300 Subject: [Tutor] How to generate permutations of a given string In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A37@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A37@eugsrv400.psc.pscnet.com> Message-ID: <5e58f2e40611271449k9bcc61ex3d1233ae32f0a3d6@mail.gmail.com> On 28/11/06, Carroll, Barry wrote: > I'm not sure these qualify as "simple", but they work. This was one of > my very first projects in Python, so it may be more complicated than > necessary. This is an alternative approach: http://mail.python.org/pipermail/tutor/2005-May/038059.html -- John. From john at fouhy.net Mon Nov 27 23:50:28 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 28 Nov 2006 11:50:28 +1300 Subject: [Tutor] Convert string to file handle In-Reply-To: <20061127223634.36894.qmail@web53809.mail.yahoo.com> References: <20061127223634.36894.qmail@web53809.mail.yahoo.com> Message-ID: <5e58f2e40611271450j3f38ff7csb5a6b615e86f28d1@mail.gmail.com> On 28/11/06, Shitiz Bansal wrote: > Hi, > i have a string abc. > i need a file handle f pointing to a file which contains this string. > is there any way i can achieve this without actually writing the contents to > a file and then opening it? for performance reasons i want to run this > entire process within the physical memory! Have a look at the StringIO module: http://www.python.org/doc/current/lib/module-StringIO.html -- John. From bgailer at alum.rpi.edu Tue Nov 28 00:00:56 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 27 Nov 2006 15:00:56 -0800 Subject: [Tutor] Convert string to file handle In-Reply-To: <20061127223634.36894.qmail@web53809.mail.yahoo.com> References: <20061127223634.36894.qmail@web53809.mail.yahoo.com> Message-ID: <456B6E28.1070306@alum.rpi.edu> Shitiz Bansal wrote: > Hi, > i have a string abc. > i need a file handle f pointing to a file which contains this string. For what? > is there any way i can achieve this without actually writing the > contents to a file and then opening it? for performance reasons i want > to run this entire process within the physical memory! Depends on what for. -- Bob Gailer 510-978-4454 From dyoo at hkn.eecs.berkeley.edu Tue Nov 28 00:29:28 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 Nov 2006 15:29:28 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 33, Issue 100 In-Reply-To: References: Message-ID: > done=0 > fd = open("draw__output.txt",'r') > while not done: > line = fd.readline() > if line == '': > done = 1 > else: > for i in line: > d[i] = int(d[i])+ 1 Code simplification: you can do a loop directly across files. Files provide an "iterator" that allow us to march line by line across it. The above code can be transformed into: ################################# fd = open("draw__output.txt",'r') for line in fd: for i in line: d[i] = int(d[i])+ 1 ################################# For more information about iterators, see: http://www.python.org/dev/peps/pep-0234/ In particular, skip down to the Dictionary Iterators and File Iterators sections: they should help show how to use the standard iterators types in Python. Good luck! From alan.gauld at btinternet.com Tue Nov 28 01:12:30 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Nov 2006 00:12:30 -0000 Subject: [Tutor] ashamed References: Message-ID: "Moedeloos Overste" wrote > d={1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0, > 13:0, > 14:0, 15:0, > 16:0, 17:0, 18:0, 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, > 27:0, > 28:0, > 29:0, 30:0, 31:0, 32:0, 33:0, 34:0, 35:0, 36:0, 37:0, 38:0, 39:0, > 40:0, > 41:0, 42:0, > 43:0, 44:0, 45:0} You probably don't need to initialise all the values, just test to see if its already set (either by catching any KeyError exceptions) or use get() method to return zero as a default as you go (see my code below). > done=0 > fd = open("draw__output.txt",'r') > while not done: > line = fd.readline() > if line == '': > done = 1 You can replace all of that with a Python for loop: for line in open("draw_output.txt"): > for i in line: > d[i] = d.get(i,0)+ 1 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tim at johnsons-web.com Tue Nov 28 03:21:40 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 27 Nov 2006 17:21:40 -0900 Subject: [Tutor] How to Automatically generate a synopsis for a Module Message-ID: <20061128022140.GG1762@johnsons-web.com> Hello: If I start the python interpreter, then import a file, and type help(module_name_here) Documentation about the module is displayed in detail. I would like to write a python script that Searches for all python scripts in a directory, and extracts (initially) the description for each script as a string so that I can print to stdout. IOWS: I want to extract what help(module) would display in the python interpreter. Any ideas? :-) TIA tim -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Tue Nov 28 03:30:22 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 27 Nov 2006 17:30:22 -0900 Subject: [Tutor] How to Automatically generate a synopsis for a Module In-Reply-To: <20061128022140.GG1762@johnsons-web.com> References: <20061128022140.GG1762@johnsons-web.com> Message-ID: <20061128023022.GH1762@johnsons-web.com> Amazing what google can do I think pydoc does it all... pydoc -p 1234 sets up the server what what I need. Never mind! :-) tim * Tim Johnson [061127 17:24]: > Hello: > If I start the python interpreter, then import a file, and > type > help(module_name_here) > Documentation about the module is displayed in detail. > > I would like to write a python script that > Searches for all python scripts in a directory, and > extracts (initially) the description for each script as > a string so that I can print to stdout. > > IOWS: > I want to extract what help(module) would display in > the python interpreter. > > Any ideas? :-) > TIA > tim > > -- > Tim Johnson > http://www.alaska-internet-solutions.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From rdm at rcblue.com Tue Nov 28 05:09:58 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 27 Nov 2006 20:09:58 -0800 Subject: [Tutor] help with Tkinter, please Message-ID: <7.0.1.0.2.20061127200947.08383488@rcblue.com> At 08:55 PM 11/26/2006, you wrote: >On 27/11/06, Dick Moores wrote: >>I have a question about the "EXIT" button's command, >>command=sys.exit. It fails to quit the program when I've entered too >>large an integer for factoring, or for prime testing, and I don't >>want to wait any more for the result. When I'm running the program >>from my Win XP console, I can quit with a simple Ctrl+C, but this >>won't be available to the friend I may send the executable to. Is it >>possible to build in a way to smoothly interrupt, say, a factoring >>process that's taking too long? > >Well, as you may know, the "core" of Tkinter (or most GUIs, I think) >is the event loop. The event loop basically does this: >1. Look for events (mouse clicks, keypresses, etc.) >2. Process events (update widgets, call callbacks) >3. GOTO 1. > >So, in this specific case, the event loop is doing this: > >1. Look for events ==> user clicks on "factorise" button. >2. Process events ==> call "factorise" button callback. >3. Callback runs... >4. ...callback completes. >5. Look for events ==> user clicks on "exit" button. >6. Process events ==> call "exit" button callback. >7. Python exits. > >So, you can see why clicking your exit button won't interrupt the >calculation in progress. The only way you can do that is if you can >get the event loop to start looking for events again before the >callback finishes. And that means THREADS. Thanks, John. I know nothing about threading. I see that Chun's _Core Python Programming_, 2nd ed. has a 30-page chapter on it. A good place to start? Dick From rdm at rcblue.com Tue Nov 28 08:19:28 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 27 Nov 2006 23:19:28 -0800 Subject: [Tutor] Rounding a float to n significant digits Message-ID: <7.0.1.0.2.20061127231658.083d26f0@rcblue.com> I just dug this Tim Smith creation out of the Tutor archive. def round_to_n(x, n): """ Rounds float x to n significant digits, in scientific notation. Written by Tim Peters. See his Tutor list post of 7/3/04 at http://mail.python.org/pipermail/tutor/2004-July/030324.html """ if n < 1: raise ValueError("number of significant digits must be >= 1") return "%.*e" % (n-1, x) Thought others might find it of use. Dick Moores From wescpy at gmail.com Tue Nov 28 08:20:39 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 27 Nov 2006 23:20:39 -0800 Subject: [Tutor] Please suggest a python book In-Reply-To: <45679627.36188e98.0441.ffff86d6@mx.google.com> References: <45679627.36188e98.0441.ffff86d6@mx.google.com> Message-ID: <78b3a9580611272320v73e78620h1b37154f315b41eb@mail.gmail.com> > I am new to python. I have a vacation of 15 days. Please suggest me a python > book (or a website). > > I already know C language. I have heard much about Python. there was a long thread about this in the main newsgroup several months ago... i suppose these threads show up annually. anyway, it was an in-depth back-n-forth, and hopefully you will be able to find something to your liking. some discussion on my book, core python programming, appears in the final couple of theads. http://groups.google.com/group/comp.lang.python/browse_thread/thread/4a9e9a76c623e451 http://groups.google.com/group/comp.lang.python/browse_thread/thread/a3157bfacca26a3 http://groups.google.com/group/comp.lang.python/browse_thread/thread/839a4afb79b7c258 hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Tue Nov 28 08:32:55 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 27 Nov 2006 23:32:55 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: <7.0.1.0.2.20061127200947.08383488@rcblue.com> References: <7.0.1.0.2.20061127200947.08383488@rcblue.com> Message-ID: <78b3a9580611272332m40e1e8c3m59b09a5612080c47@mail.gmail.com> > >>I have a question about the "EXIT" button's command, > >>command=sys.exit. It fails to quit the program when I've entered too > >>large an integer for factoring, or for prime testing, and I don't > >>want to wait any more for the result. > > > >So, you can see why clicking your exit button won't interrupt the > >calculation in progress. The only way you can do that is if you can > >get the event loop to start looking for events again before the > >callback finishes. And that means THREADS. > > Thanks, John. I know nothing about threading. I see that Chun's _Core > Python Programming_, 2nd ed. has a 30-page chapter on it. A good > place to start? it is a good place to start, but there isn't a combination GUI+threading example in the book... perhaps 3rd edition.... in order to make your app "do what you want," you need to have the main thread running the GUI, e.g., mainloop(), and fire off threads to do the calculations. if your operating system supports daemon threads, set your unimportant threads as daemon threads -- from the docs: "The entire Python program exits when no active non-daemon threads are left." http://docs.python.org/lib/thread-objects.html if your OS threads don't support this, then you have to manage a shared "QUIT" variable which you can set in your quit routine which calls root.quit() if root is your main Tk window (sys.exit() is a little rough), and have your worker threads continually check the status of such a flag during execution. when the user quits, this flag can be set, telling the workers to put down their shovels and go home. :-) hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Tue Nov 28 10:16:23 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Nov 2006 09:16:23 -0000 Subject: [Tutor] help with Tkinter, please References: <7.0.1.0.2.20061127200947.08383488@rcblue.com> <78b3a9580611272332m40e1e8c3m59b09a5612080c47@mail.gmail.com> Message-ID: "wesley chun" wrote > do the calculations. if your operating system supports daemon > threads, set your unimportant threads as daemon threads -- from the > docs: > > "The entire Python program exits when no active non-daemon threads > are left." Wes, why do you recommend the use of daemons here? Wouldn't that just leave a load of silently running daemon threads eating up resources after the main program finishes? I don't see the logic of that one? I'd have thought you wanted to be sure all application threads died when the app died? What am I missing? Alan G. From wescpy at gmail.com Tue Nov 28 11:16:42 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 28 Nov 2006 02:16:42 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: References: <7.0.1.0.2.20061127200947.08383488@rcblue.com> <78b3a9580611272332m40e1e8c3m59b09a5612080c47@mail.gmail.com> Message-ID: <78b3a9580611280216q300b92b4xcccb754eacddb73e@mail.gmail.com> > > "The entire Python program exits when no active non-daemon threads > > are left." > > why do you recommend the use of daemons here? > Wouldn't that just leave a load of silently running daemon > threads eating up resources after the main program finishes? > I don't see the logic of that one? I'd have thought you wanted > to be sure all application threads died when the app died? > > What am I missing? are you missing something? :-) i think there is a distinction bewteen a daemon/server process and daemon threads. i don't think that daemon threads are spawned to a different process, save perhaps the ones started from C. i believe that as soon as there are only daemon threads left (a complementary statement to the doc line above for Thread objects), the Python interpreter will exit, killing them all. i think Python threads are very similar to Java threads, but i'll let the thread experts chime in here. in the meantime, i googled for some references and found some good (but perhaps long) reading: http://www.quepublishing.com/articles/article.asp?p=26044&seqNum=8&rl=1 http://groups.google.com/group/comp.lang.python/browse_thread/thread/3da7545c655bd769 http://groups.google.com/group/comp.lang.python/browse_thread/thread/e8551fad6e06421f http://groups.google.com/group/comp.lang.python/browse_thread/thread/ffa4edeca2a4fd60 http://mail.python.org/pipermail/python-list/2003-May/202288.html http://groups.google.com/group/comp.lang.python/browse_thread/thread/8262b6e68481f1f9 hope this helps! -- wes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ajkadri at googlemail.com Tue Nov 28 11:35:02 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 28 Nov 2006 10:35:02 +0000 Subject: [Tutor] How to connect to the SOAP server and make a request.......... Message-ID: Hi folks, I am using SOAPpy module to make SOAP requests. Can someone point me documentation that has list of functions that can be used for carrying out various tasks. Thanks in anticipation. Best Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061128/d2fa301e/attachment.html From simon at brunningonline.net Tue Nov 28 11:55:55 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 28 Nov 2006 10:55:55 +0000 Subject: [Tutor] How to connect to the SOAP server and make a request.......... In-Reply-To: References: Message-ID: <8c7f10c60611280255t69d3cb9fsecf164ee041f744a@mail.gmail.com> On 11/28/06, Asrarahmed Kadri wrote: > I am using SOAPpy module to make SOAP requests. > > Can someone point me documentation that has list of functions that can be > used for carrying out various tasks. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From kent37 at tds.net Tue Nov 28 12:05:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Nov 2006 06:05:01 -0500 Subject: [Tutor] help with Tkinter, please In-Reply-To: <78b3a9580611272332m40e1e8c3m59b09a5612080c47@mail.gmail.com> References: <7.0.1.0.2.20061127200947.08383488@rcblue.com> <78b3a9580611272332m40e1e8c3m59b09a5612080c47@mail.gmail.com> Message-ID: <456C17DD.3070904@tds.net> wesley chun wrote: > if your operating system supports daemon > threads, set your unimportant threads as daemon threads -- from the > docs: > > "The entire Python program exits when no active non-daemon threads are left." > > http://docs.python.org/lib/thread-objects.html AFAIK daemon threads are supported on all OSes that have Python thread support; the docs don't mention it being OS-specific and the threading module is written in Python so it should work wherever threads are supported. Kent From rdm at rcblue.com Tue Nov 28 12:07:26 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 28 Nov 2006 03:07:26 -0800 Subject: [Tutor] Does Fredrik Lundh's console module work on Win XP? Message-ID: <7.0.1.0.2.20061128025458.0844cbe8@rcblue.com> This seems it might be very useful. I just downloaded and thought I'd installed "console-1.1a1-20011229.win32-py2.5.exe" in Python 2.5 in Win XP, but I can't get it to appear. My attempts: ======================================= E:\Python25\Lib\site-packages>Console.py Traceback (most recent call last): File "E:\Python25\Lib\site-packages\Console.py", line 34, in ? raise ImportError, "installation error: cannot find a console driver" ImportError: installation error: cannot find a console driver E:\Python25\Lib\site-packages>python Console.py (silence) ========================================== Lundh says on http://effbot.org/zone/console-handbook.htm : "The Console module provides a simple console interface, which provides cursor-addressable text output, plus support for keyboard and mouse input. "The Console module is currently only available for Windows 95, 98, NT, and 2000. It probably works under Windows XP, but it hasn't been tested on that platform." So DOES it work under Win XP? Or have I screwed something up? Thanks, Dick Moores From kent37 at tds.net Tue Nov 28 12:10:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Nov 2006 06:10:21 -0500 Subject: [Tutor] help with Tkinter, please In-Reply-To: <78b3a9580611280216q300b92b4xcccb754eacddb73e@mail.gmail.com> References: <7.0.1.0.2.20061127200947.08383488@rcblue.com> <78b3a9580611272332m40e1e8c3m59b09a5612080c47@mail.gmail.com> <78b3a9580611280216q300b92b4xcccb754eacddb73e@mail.gmail.com> Message-ID: <456C191D.1000109@tds.net> wesley chun wrote: >>> "The entire Python program exits when no active non-daemon threads >>> are left." >> why do you recommend the use of daemons here? >> Wouldn't that just leave a load of silently running daemon >> threads eating up resources after the main program finishes? >> I don't see the logic of that one? I'd have thought you wanted >> to be sure all application threads died when the app died? >> >> What am I missing? > > > are you missing something? :-) i think there is a distinction bewteen > a daemon/server process and daemon threads. i don't think that daemon > threads are spawned to a different process, save perhaps the ones > started from C. > > i believe that as soon as there are only daemon threads left (a > complementary statement to the doc line above for Thread objects), the > Python interpreter will exit, killing them all. i think Python threads > are very similar to Java threads, but i'll let the thread experts > chime in here. Yes, that is correct. Daemon threads won't block the program from exiting. They will be stopped when the program exits - they are not separate processes. However for the OP's application which is running calculations in the background in a GUI application, the threads will probably be created as needed and will end when the calculation is done. Unless the calculation is long enough that you want to be able to exit the app before the calculation completes, the thread doesn't really need to be a daemon. Kent From Tim.Golden at viacom-outdoor.co.uk Tue Nov 28 12:31:40 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 28 Nov 2006 11:31:40 -0000 Subject: [Tutor] Does Fredrik Lundh's console module work on Win XP? In-Reply-To: <7.0.1.0.2.20061128025458.0844cbe8@rcblue.com> Message-ID: [Dick Moores] | This seems it might be very useful. I just downloaded and thought I'd | installed "console-1.1a1-20011229.win32-py2.5.exe" in Python 2.5 in | Win XP, but I can't get it to appear. | | My attempts: | ======================================= | E:\Python25\Lib\site-packages>Console.py | Traceback (most recent call last): | File "E:\Python25\Lib\site-packages\Console.py", line 34, in ? | raise ImportError, "installation error: cannot find a | console driver" | ImportError: installation error: cannot find a console driver Most likely bet here is that you don't have Python25 linked to .py files. What does: ftype python.file show? | | E:\Python25\Lib\site-packages>python Console.py | (silence) | ========================================== Do you mean it hung: didn't come back to the command prompt? Or merely started, finished, and did nothing? If the latter, then that's what I'd expect, since the module does nothing except import things for you to use from your own code. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ajkadri at googlemail.com Tue Nov 28 12:45:57 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 28 Nov 2006 11:45:57 +0000 Subject: [Tutor] What is the meaning of using single underscore in front of variable name Message-ID: Hi folks, What does this mean? _url = 'http://api.google.com/search/beta2' _namespace = 'urn:GoogleSearch' Single underscore as a prefix in variable naming...?? whats it for?? Any idea.. Regards, Asrarahmed -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061128/c118c673/attachment.htm From simon at brunningonline.net Tue Nov 28 12:50:48 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 28 Nov 2006 11:50:48 +0000 Subject: [Tutor] What is the meaning of using single underscore in front of variable name In-Reply-To: References: Message-ID: <8c7f10c60611280350wd11efacy51c49ab2c01f0443@mail.gmail.com> On 11/28/06, Asrarahmed Kadri wrote: > What does this mean? > > _url = 'http://api.google.com/search/beta2' > _namespace = 'urn:GoogleSearch' > > Single underscore as a prefix in variable naming...?? whats it for?? It means "private by convention" - see . -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From ajkadri at googlemail.com Tue Nov 28 15:18:14 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 28 Nov 2006 14:18:14 +0000 Subject: [Tutor] WHy use SOAPpy if we can do the things using httplib moduleRe: How to connect to the SOAP server and make a request.......... Message-ID: I read the URL suggested by Simon, In that URL, it is given how to create the SOAP ENVELOPE using httplib, so why bother about using SOAPpy...?? Any comments...???? Best Regards, Asrarahmed Kadri On 11/28/06, Simon Brunning wrote: > > On 11/28/06, Asrarahmed Kadri wrote: > > I am using SOAPpy module to make SOAP requests. > > > > Can someone point me documentation that has list of functions that can > be > > used for carrying out various tasks. > > > > -- > Cheers, > Simon B > simon at brunningonline.net > http://www.brunningonline.net/simon/blog/ > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061128/97898e1f/attachment.html From kent37 at tds.net Tue Nov 28 16:10:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Nov 2006 10:10:01 -0500 Subject: [Tutor] Does Fredrik Lundh's console module work on Win XP? In-Reply-To: <7.0.1.0.2.20061128025458.0844cbe8@rcblue.com> References: <7.0.1.0.2.20061128025458.0844cbe8@rcblue.com> Message-ID: <456C5149.2080905@tds.net> Dick Moores wrote: > This seems it might be very useful. I just downloaded and thought I'd > installed "console-1.1a1-20011229.win32-py2.5.exe" in Python 2.5 in > Win XP, but I can't get it to appear. It seems to work for me. Try this program, based on the example in the docs: import Console c = Console.getconsole() c.title("Console Example") c.text(0, 0, "here's some white text on white background", 0x1f) c.text(10, 5, "line five, column ten") c.text(1, 6, "press a key to exit") c.getchar() Kent From simon at brunningonline.net Tue Nov 28 16:13:53 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 28 Nov 2006 15:13:53 +0000 Subject: [Tutor] WHy use SOAPpy if we can do the things using httplib moduleRe: How to connect to the SOAP server and make a request.......... In-Reply-To: References: Message-ID: <8c7f10c60611280713u1db0ae58geb8ca55f4725e082@mail.gmail.com> On 11/28/06, Asrarahmed Kadri wrote: > > I read the URL suggested by Simon, In that URL, it is given how to create > the SOAP ENVELOPE using > httplib, so why bother about using SOAPpy...?? The article discusses two ways of doing SOAP; by hand, and using SOAPpy. Building the SOAP message by hand is part of the first section, using SOAPpy is the second. There's also a number of other article in the series: -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From arbaro at gmail.com Tue Nov 28 16:25:05 2006 From: arbaro at gmail.com (arbaro arbaro) Date: Tue, 28 Nov 2006 16:25:05 +0100 Subject: [Tutor] timeout a routine Message-ID: <802dc1e0611280725m3236c5b8h932ef42c9a89b381@mail.gmail.com> Hello, I have a small problem with accessing a directory that may or may not exist. - The program runs from a Linux OS. (though this shouldn't matter) - A mountpoint /mnt/server may have been made to a windows server with samba. I would like to find out if a folder on the server is reachable (eg. /mnt/server/folderOnServer). When I try to find out if dir exists with os.path.isdir("/mnt/server/folderOnServer"), python hangs for a very long time. Is there a way to run the command os.path.isdir("/mnt/server/folderOnServer"), and kill the attempt if it tries for longer then 5 seconds? Where/what can I use to accomplish something like this? Thanks, Arbaro From engnarasimha at gmail.com Tue Nov 28 16:46:43 2006 From: engnarasimha at gmail.com (Kopalle Narasimha) Date: Tue, 28 Nov 2006 21:16:43 +0530 Subject: [Tutor] (no subject) Message-ID: Hello, Everyone. I have a strange problem with floating point numbers. Please help me. I tried the following at the python prompt: Case 1: >>> 4.5/2.0 #Gives quotient Answer: 2.25 Case 2: >>> 4.5%2.0 #Gives Remainder Answer: 0.5 How could a floating point division give a remainder??? I think the remainder must always be zero since the quotient would be a floating point number. When a similar program is written in C language(i.e. to get remainder of two floating point numbers), I received an error supporting my idea. From noufal at airtelbroadband.in Tue Nov 28 17:30:51 2006 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Tue, 28 Nov 2006 22:00:51 +0530 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <456C643B.60403@airtelbroadband.in> Kopalle Narasimha wrote: > Hello, Everyone. > > I have a strange problem with floating point numbers. Please help me. > I tried the following at the python prompt: > > Case 1: >>>> 4.5/2.0 #Gives quotient > Answer: 2.25 > > Case 2: >>>> 4.5%2.0 #Gives Remainder > Answer: 0.5 > I don't think it's defined that way. When you say x%y, you are looking for the remainder after when x is divided by y. The fractional part is a remainder. eg. a%b = c 4.5%2.0 = 0.5 because 2.0 * 2 + 0.5 = 4.5 (b * quotient) + c = a where quotient is not a fractional number. It's discussed a little here http://docs.python.org/ref/binary.html -- ~noufal From rdm at rcblue.com Tue Nov 28 19:06:22 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 28 Nov 2006 10:06:22 -0800 Subject: [Tutor] Does Fredrik Lundh's console module work on Win XP? Message-ID: <7.0.1.0.2.20061128100611.06266158@rcblue.com> At 07:10 AM 11/28/2006, you wrote: >Dick Moores wrote: >>This seems it might be very useful. I just downloaded and thought >>I'd installed "console-1.1a1-20011229.win32-py2.5.exe" in Python >>2.5 in Win XP, but I can't get it to appear. > >It seems to work for me. Try this program, based on the example in the docs: > >import Console > >c = Console.getconsole() > >c.title("Console Example") > >c.text(0, 0, "here's some white text on white background", 0x1f) >c.text(10, 5, "line five, column ten") >c.text(1, 6, "press a key to exit") > >c.getchar() Yes, that works. I added styles to the 2nd 2 texts, and also added a rectangle with a style and a character. Everything works. But what's the point? How is this console useful? In games or animation? Dick From vladeli at gmail.com Tue Nov 28 19:27:10 2006 From: vladeli at gmail.com (vladeli@googlemail.com) Date: Tue, 28 Nov 2006 19:27:10 +0100 Subject: [Tutor] Python for Kids Message-ID: <03DB3ADD-61CE-4410-AAF7-140FAE1C02CC@googlemail.com> Hello, I bought the book "Python for Kids". started to read it, but can not find where I have to install xturlte? I use macintosh... Have python 2.5. If someone knows where I have to copy the xturtle and other files (for xturle) on macintosh, will be happy for help:) Thank You in advance, Vladlena From arbaro at gmail.com Tue Nov 28 19:35:17 2006 From: arbaro at gmail.com (arbaro arbaro) Date: Tue, 28 Nov 2006 19:35:17 +0100 Subject: [Tutor] timeout a routine In-Reply-To: <456C786A.2030301@gmail.com> References: <802dc1e0611280725m3236c5b8h932ef42c9a89b381@mail.gmail.com> <456C786A.2030301@gmail.com> Message-ID: <802dc1e0611281035y4d18c02ax1ef053eb8edf1958@mail.gmail.com> Thanks a lot Jordan, I have no experience with classes at all yet, so your example will give me a really nice startting point. On 11/28/06, Jordan Greenberg wrote: > arbaro arbaro wrote: > > Hello, > > > Is there a way to run the command > > os.path.isdir("/mnt/server/folderOnServer"), and kill the attempt if > > it tries for longer then 5 seconds? > > Where/what can I use to accomplish something like this? > > > > > > Thanks, > > Arbaro > > Hi Arbaro! > The only way I can think of is with threads. > Its not too hard to use one thread to control another, and stop it after > a certain amount of time. Something like this: > > #threadexample.py > > from threading import Thread > import time > > MyThread(Thread): > def __init__(self, message): > self.message=message > Thread.__init__(self) > def run(self): > while True: > print "MyThread: "+self.message > > class Controller(Thread): > def __init__(self, runner,time): > self.runner=runner > self.delta=time > Thread.__init__(self) > > def run(self): > self.start=time.time() > self.runner.start() > self.done=False > while not self.done: > if time.time() > (self.start+self.delta): > print "Controller: Stopping MyThread." > self.runner._Thread__stop() > return > > mythread=MyThread("hello") > control=Controller(mythread, 2) > control.start() > > #end of threadexample.py > > I'm still just learning threading, so there is probably a better way to > do this, though this seems to work pretty well. > > > Hope this helps, > Jordan Greenberg > From bgailer at alum.rpi.edu Tue Nov 28 19:44:49 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 28 Nov 2006 10:44:49 -0800 Subject: [Tutor] Modulo operator (was no subject) In-Reply-To: <456C643B.60403@airtelbroadband.in> References: <456C643B.60403@airtelbroadband.in> Message-ID: <456C83A1.4000800@alum.rpi.edu> Please always provide a subject line. Otherwise it is very hard to follow threads. Noufal Ibrahim wrote: > Kopalle Narasimha wrote: > >> Hello, Everyone. >> >> I have a strange problem with floating point numbers. Please help me. >> I tried the following at the python prompt: >> >> Case 1: >> >>>>> 4.5/2.0 #Gives quotient >>>>> >> Answer: 2.25 >> >> Case 2: >> >>>>> 4.5%2.0 #Gives Remainder >>>>> Despite what the documentation says, the modulo operator does not return a remainder! Notice: >>> [x % 3 for x in range(-5,5)] [1, 2, 0, 1, 2, 0, 1, 2, 0, 1] For negative values of the left argument the result is NOT the remainder. The literature seems very confused about this, using "remainder" when it is NOT the case. What's worse, in some languages the mod operator DOES return the remainder. [snip] -- Bob Gailer 510-978-4454 From alan.gauld at btinternet.com Tue Nov 28 19:51:40 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Nov 2006 18:51:40 -0000 Subject: [Tutor] What is the meaning of using single underscore in front ofvariable name References: Message-ID: "Asrarahmed Kadri" wrote > Single underscore as a prefix in variable naming...?? whats it for?? > > Any idea.. Its a convention to indicate that this variable is not for general use. It is part of the internal implementation of the class or module. But it is only a convention and Python will not stop you from accessing it. It is similar to the convention of using all uppercase letters to indicate a constant value that should not be changed by users of the code. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Tue Nov 28 19:48:43 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 28 Nov 2006 10:48:43 -0800 Subject: [Tutor] Modulo operator (was no subject) In-Reply-To: <456C643B.60403@airtelbroadband.in> References: <456C643B.60403@airtelbroadband.in> Message-ID: <456C848B.30701@alum.rpi.edu> See http://en.wikipedia.org/wiki/Modular_arithmetic for a comprehensive discussion. Especially the paragraph title Remainders. Often people ask "what's the practical use of modular arithmetic?" Consider how we tell time... -- Bob Gailer 510-978-4454 From alan.gauld at btinternet.com Tue Nov 28 19:54:39 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Nov 2006 18:54:39 -0000 Subject: [Tutor] WHy use SOAPpy if we can do the things using httplibmoduleRe: How to connect to the SOAP server and make arequest.......... References: Message-ID: "Asrarahmed Kadri" wrote in message >I read the URL suggested by Simon, In that URL, it is given how to >create > the SOAP ENVELOPE using > httplib, so why bother about using SOAPpy...?? You can also read web pages using http POST and GET messages to a socket using the socket library, but most folks find it easier to use urllib. For that matter you can display output to sys.stdout, so why bother with print? The library functions make things easier and more consistent. Somebody else has debugged the code so you don't have to... Alan G. From jordangreenberg at gmail.com Tue Nov 28 20:02:38 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Tue, 28 Nov 2006 14:02:38 -0500 Subject: [Tutor] Test Message-ID: <39cae8480611281102y223bc925tc739ae771e4372b4@mail.gmail.com> Hey, my messages don't seem to be showing up on the list... So if this one works, sorry for the test message, everybody! My school just decided not to allow any outgoing email to any SMTP server but their own *grumble* So I've been sending my tutor messages through that server but with this address munged into the headers. Seems to send messages through fine, but I guess the list doesn't like it for some reason. If this message works, it'll be proof of that (since this is from the gmail web interface) and I'll re-subscribe to the list from my other address (greenbergj at wit.edu) so my messages will come from there from now on. Sorry again for the test, Jordan Greenberg From alan.gauld at btinternet.com Tue Nov 28 20:02:24 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Nov 2006 19:02:24 -0000 Subject: [Tutor] help with Tkinter, please References: <7.0.1.0.2.20061127200947.08383488@rcblue.com><78b3a9580611272332m40e1e8c3m59b09a5612080c47@mail.gmail.com> <78b3a9580611280216q300b92b4xcccb754eacddb73e@mail.gmail.com> Message-ID: "wesley chun" wrote >> why do you recommend the use of daemons here? >> Wouldn't that just leave a load of silently running daemon >> threads eating up resources > > are you missing something? :-) i think there is a distinction > bewteen > a daemon/server process and daemon threads. i don't think that > daemon > threads are spawned to a different process Aha! That's what I was missing. I assumed that daemon threads ran under the OS main thread rather than the application main thread. What exactly is the advantage of a daemon thread over a normal one in that case - other than that the application will end while daemons are still running? In fact that might be the advantage. But in that case daemons would only be useful for endless loop type threads? So I still don't see why the OP should should them? > are very similar to Java threads, but i'll let the thread experts > chime in here. Java threads, like so much of Java are things I try to avoid! :-) Thanks for the pointers. Alan G. From samrobertsmith at gmail.com Tue Nov 28 20:19:09 2006 From: samrobertsmith at gmail.com (linda.s) Date: Tue, 28 Nov 2006 11:19:09 -0800 Subject: [Tutor] draw 3D using Tkinter? Message-ID: <1d987df30611281119yae9a0beo738deebb1651dd1b@mail.gmail.com> Is there any sample code to draw 3D using Tkinter? Thanks, Linda From m_hafeji88 at talktalk.net Tue Nov 28 20:56:21 2006 From: m_hafeji88 at talktalk.net (Mohammed H. Hafeji) Date: Tue, 28 Nov 2006 19:56:21 -0000 Subject: [Tutor] Help Message-ID: <000601c71327$49084700$0b93f159@HafejiHousehold> Need some help in python. How do i make the user choose wheter or not to pick it up? (i can do picking up an item from a list): objectsCarried = [] inventory = ['bat'] lengthOfInventory =len(inventory) print 'The room holds:' for item in range(lengthOfInventory): print item, inventory[item] numberChosen = int(raw_input('use the number to pick up an item ')) objectChosen = inventory[numberChosen] objectsCarried.append(objectChosen) inventory.remove(objectChosen) print 'you are carrying ' for item in objectsCarried: print item print print 'The room now holds:' for item in inventory: print item But i cant do when u have a choice to pick up or not. Also if not too much trouble then how can i do: IF the user picks the bat up then when he comes across the vampire then he kills it, but if he hasnt pickd up the bat then he dies? Thanks in advance P.S. Could u plz email sum code -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061128/38360c96/attachment.html From wescpy at gmail.com Tue Nov 28 21:15:21 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 28 Nov 2006 12:15:21 -0800 Subject: [Tutor] help with Tkinter, please In-Reply-To: References: <7.0.1.0.2.20061127200947.08383488@rcblue.com> <78b3a9580611272332m40e1e8c3m59b09a5612080c47@mail.gmail.com> <78b3a9580611280216q300b92b4xcccb754eacddb73e@mail.gmail.com> Message-ID: <78b3a9580611281215n1b83582emfec235b6c1dd0ba9@mail.gmail.com> > What exactly is the advantage of a daemon thread over a normal > one in that case - other than that the application will end while > daemons are still running? In fact that might be the advantage. > But in that case daemons would only be useful for endless > loop type threads? for example, they can be worker threads, those that take some service request, perform some work, produces results, then goes back to wait for more work -- your endless loop scenario. if the main thread is taking user input and pawning off service requests to worker threads, then exits, meaning no more possible work for the worker threads, they should then be killed off along with the main thread. here's a snippet from the 1st link i sent: "Daemon threads are designed as low-level background threads that perform useful work. However, it is not essential that they be allowed to complete before an application terminates. One example of a daemon thread is the garbage collector thread." if the main (and other non-daemon) threads exit, there is no more code allocating memory (thus no longer a need to GC memory... IOW, there's no more work to be done), so there really isn't a reason for them (daemon threads) to stay up and running. the bottom line is that they can do work when work is available, but other than that, are pretty useless without some non-daemon threads providing that work for them; thus it's relatively harmless to kill them off. FWIW, when i first learned about daemon threads, i was also confused at the naming and their relationship (if any) with daemon/server processes even though they do similar things. i guess that's what makes it easy to reboot your *nix servers... you shutdown and/or reboot without explicitly killing each server right? it sure would take a long time... can you imagine how many "/etc/init.d/XXX stop" calls you'd have to make in your shell? :-) HTH, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Tue Nov 28 21:21:42 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 28 Nov 2006 12:21:42 -0800 Subject: [Tutor] WHy use SOAPpy if we can do the things using httplibmoduleRe: How to connect to the SOAP server and make arequest.......... In-Reply-To: References: Message-ID: <78b3a9580611281221l529c3518x1b02c702414663fb@mail.gmail.com> > it is given how to > >create > > the SOAP ENVELOPE using > > httplib, so why bother about using SOAPpy...?? > > You can also read web pages using http POST and GET messages > to a socket using the socket library, but most folks find it easier > to use urllib. > > For that matter you can display output to sys.stdout, so > why bother with print? > > The library functions make things easier and more consistent. > Somebody else has debugged the code so you don't have to... to further the analogy, you could say why bother with urllib and use httplib instead, or forget all those and use TCP sockets, or drop TCP in favor of UDP, or protocols? who needs protocols? just use raw sockets! (i'll stop here... you get the picture.) :-) you're basically using high-level libraries as an abstraction layer (to make developing apps easier) to hide the messiness of the lower-level implementation and details which may not be applicable to your work. i mean, why use Python when you can do it in C? -- wesley From andreas at kostyrka.org Tue Nov 28 21:38:07 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 28 Nov 2006 21:38:07 +0100 Subject: [Tutor] WHy use SOAPpy if we can do the things using httplibmoduleRe: How to connect to the SOAP server and make arequest.......... In-Reply-To: <78b3a9580611281221l529c3518x1b02c702414663fb@mail.gmail.com> References: <78b3a9580611281221l529c3518x1b02c702414663fb@mail.gmail.com> Message-ID: <20061128203807.GA21210@andi-lap.la.revver.com> > you're basically using high-level libraries as an abstraction layer > (to make developing apps easier) to hide the messiness of the > lower-level implementation and details which may not be applicable to > your work. i mean, why use Python when you can do it in C? Wimp! You can do it in binary machine code. (Assemblers are weakminded compilers only) And you can even have the joy multiple times, porting your app to half a dozen architectures that might be relevant :) Andreas From bgailer at alum.rpi.edu Tue Nov 28 21:40:52 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 28 Nov 2006 12:40:52 -0800 Subject: [Tutor] Game programming - inventory management (was Help) In-Reply-To: <000601c71327$49084700$0b93f159@HafejiHousehold> References: <000601c71327$49084700$0b93f159@HafejiHousehold> Message-ID: <456C9ED4.2040908@alum.rpi.edu> Please use a meaningful subject line. Many of us try to follow "threads", and "help" does not help. I have provided one for this case. Mohammed H. Hafeji wrote: > Need some help in python. > > How do i make the user choose wheter or not to pick it up? (i can do > picking up an item from a list): > // > /*objectsCarried = []*/ > /**/ > /*inventory = ['bat'] > lengthOfInventory =len(inventory)*/ > /**/ > /*print 'The room holds:'*/ > /**/ > /*for item in range(lengthOfInventory): > print item, inventory[item]*/ > /**/ > > /*numberChosen = int(raw_input('use the number to pick up an item '))*/ > /**/ > /*objectChosen = inventory[numberChosen]*/ > /**/ > /*objectsCarried.append(objectChosen) > inventory.remove(objectChosen)*/ > /**/ > /*print 'you are carrying ' > for item in objectsCarried: > print item*/ > /**/ > /*print*/ > /**/ > /*print 'The room now holds:'*/ > /**/ > /*for item in inventory: > print item*/ > > But i cant do when u have a choice to pick up or not. > > Also if not too much trouble then how can i do: > > IF the user picks the bat up then when he comes across the vampire > then he kills it, but if he hasnt pickd up the bat then he dies? > > Thanks in advance > > P.S. Could u plz email sum code > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From rdm at rcblue.com Tue Nov 28 21:57:51 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 28 Nov 2006 12:57:51 -0800 Subject: [Tutor] How to generate permutations of a given string In-Reply-To: <5e58f2e40611271449k9bcc61ex3d1233ae32f0a3d6@mail.gmail.com > References: <2BBAEE949D384D40A2B851287ADB6A4304595A37@eugsrv400.psc.pscnet.com> <5e58f2e40611271449k9bcc61ex3d1233ae32f0a3d6@mail.gmail.com> Message-ID: <7.0.1.0.2.20061128122720.075e9cc8@rcblue.com> At 02:49 PM 11/27/2006, John Fouhy wrote: >On 28/11/06, Carroll, Barry wrote: > > I'm not sure these qualify as "simple", but they work. This was one of > > my very first projects in Python, so it may be more complicated than > > necessary. > >This is an alternative approach: >http://mail.python.org/pipermail/tutor/2005-May/038059.html However, this is not what someone looking for an anagram algorithm would find useful, it seems to me. Barry Carroll offering does the job, if the last line is revised as shown below: def permute(word): """ By Barry Carrol on Tutor list, revised (last line) by me. """ retList=[] if len(word) == 1: # There is only one possible permutation retList.append(word) else: # Return a list of all permutations using all characters for pos in range(len(word)): # Get the permutations of the rest of the word permuteList=permute(word[0:pos]+word[pos+1:len(word)]) # Now, tack the first char onto each word in the list # and add it to the output for item in permuteList: retList.append(word[pos]+item) #return retList return list(set(retList)) # make elements of retList unique (The line in the code in Barry's post, "permuteList=permute2(word[0:pos]+word[pos+1:len(word)])", was corrected to "permuteList=permute(word[0:pos]+word[pos+1:len(word)])" in an email from him to me.) (i.e., permute2 changed to permute) Dick Moores From alan.gauld at btinternet.com Tue Nov 28 22:13:07 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Nov 2006 21:13:07 -0000 Subject: [Tutor] draw 3D using Tkinter? References: <1d987df30611281119yae9a0beo738deebb1651dd1b@mail.gmail.com> Message-ID: "linda.s" wrote > Is there any sample code to draw 3D using Tkinter? I don't think so, native Tkinter isn't really the ideal graphics environment. Its not what it was designed for. However there are almost certainly libraries around for 3D stuff that can use Tkinter, although I don't know of any myself. Some of the plotting libraries might do it. I think pyGame does 3D graphics but it uses wxPython not Tkinter. Visual python (?) does 3D stuff too, but again I've never used it. Alan G. From sanelson at gmail.com Tue Nov 28 22:31:30 2006 From: sanelson at gmail.com (Steve Nelson) Date: Tue, 28 Nov 2006 21:31:30 +0000 Subject: [Tutor] Extract from Word Doc Message-ID: Hello, Is there a way to pull "strings" out of a word document? Not unlike the way the UNIX command "strings" does? I want this to be OS-portable, so shelling out is not an option. I tried opening the word doc and then looking at it using the object's methods, but it is all binary info, and can't be parsed. Any suggestions? S. From john at fouhy.net Tue Nov 28 22:54:15 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 29 Nov 2006 10:54:15 +1300 Subject: [Tutor] Extract from Word Doc In-Reply-To: References: Message-ID: <5e58f2e40611281354y4a306114ka99227400635498e@mail.gmail.com> On 29/11/06, Steve Nelson wrote: > Hello, > > Is there a way to pull "strings" out of a word document? Not unlike > the way the UNIX command "strings" does? Here's a crude attempt: >>> import string >>> s = file('myworddoc.doc').read() >>> t = ''.join(c for c in s if c in string.letters+string.digits+string.punctuation+string.whitespace) -- John. From carloslara at web.de Tue Nov 28 22:59:06 2006 From: carloslara at web.de (Carlos) Date: Tue, 28 Nov 2006 22:59:06 +0100 Subject: [Tutor] Angles Message-ID: <456CB12A.9050207@web.de> Hello to All: I'm trying to write a sun positioning system with the help of python. The idea is that you give the program a location, date and hour and it returns the position of the sun. I found a webpage that details the math behind this (http://www.usc.edu/dept/architecture/mbs/tools/vrsolar/Help/solar_concepts.html) , it was fairly trivial to translate this to python until I got to the azimuth equation. It looks like this: x_azm = sin(hour_R) * cos(decl_R) y_azm = (-(cos(hour_R))*cos(decl_R)*sin(lat_R))+(cos(lat_R)* sin(decl_R)) azimuth = atan(x_azm/y_azm)*TODEGREE where: Alt = Altitude Azm = Azimuth Decl = Declination HAngle = Hour angle alt_R = Altitude in radians azm_R = Azimuth in radians lat_R = Latitude in radians hour_R = Hour angle in radians x_azm = x component of azimuth y_azm = y component of azimuth TODEGREE = Constant equal to 180/p My python code for this particular equation: from math import * def Az(Lat, Dec, H_Ang): lat_r = radians(Lat) decl_r = radians(Dec) hour_r = radians(H_Ang) x_azm = sin(hour_r) * cos(decl_r) y_azm = (-(cos(hour_r)) * cos(decl_r) * sin(lat_r)) + (cos(lat_r) * sin(decl_r)) Azimuth = degrees(atan(x_azm/y_azm)) Azimuth = Azimuth *(-1) return Azimuth I was never very good at trigonometry, but looks like my translation of the equation is ok and the problem is some kind of python behavior, because whenever the results exceed 100? (deg) Python returns the complementary angle, it is possible to avoid this? Or I'm overlooking somethig? You can check this by yourself: If you use Az(34, -21.67, -150) you will get 72.79, the result in the webpage tool will be 107.21. And 72.79 + 107.21 = 180 but if you use Az(34, -21.67, -150) you will get 54.88 in both, my script and the webpage tool. If you want to take a look at the webpage tool this is the link: http://www.usc.edu/dept/architecture/mbs/tools/vrsolar/frameset.html Thanks in advance for your help, Carlos From rdm at rcblue.com Wed Nov 29 00:45:14 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 28 Nov 2006 15:45:14 -0800 Subject: [Tutor] Why can't I import this? Message-ID: <7.0.1.0.2.20061128152828.0760f498@rcblue.com> I just discovered something for Tkinter that I want to use. It's a Tooltip class, at . I've copied it to a file I named toolTipDemo.py and put it with a couple of other files I use as modules. They're in E:\Python25\Lib\site-packages\mine. One file there is intSpell.py, and I can import it by from mine.intSpell import intSpell With no problem: >>> from mine.intSpell import intSpell >>> However, the same method of importing doesn't work with toolTipDemo: >>> from mine.toolTipDemo import toolTipDemo Traceback (most recent call last): File "", line 1, in ImportError: cannot import name toolTipDemo I've tried various things, such as remarking out the whole demo at the bottom, but leaving if __name__ == '__main__': #demo() pass Any ideas on what I've done wrong? BTW, toolTipDemo.py runs fine at the command line. I.e., the demo shows up nicely, with 2 tooltips. Thanks, Dick Moores From Barry.Carroll at psc.com Wed Nov 29 00:55:08 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 28 Nov 2006 15:55:08 -0800 Subject: [Tutor] How to generate permutations of a given string Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A3D@eugsrv400.psc.pscnet.com> Dick, et al: > -----Original Message----- > Date: Tue, 28 Nov 2006 12:57:51 -0800 > From: Dick Moores > Subject: Re: [Tutor] How to generate permutations of a given string > To: Python Tutor List > Message-ID: <7.0.1.0.2.20061128122720.075e9cc8 at rcblue.com> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > At 02:49 PM 11/27/2006, John Fouhy wrote: > >On 28/11/06, Carroll, Barry wrote: > > > I'm not sure these qualify as "simple", but they work. This was one > of > > > my very first projects in Python, so it may be more complicated than > > > necessary. > > > >This is an alternative approach: > >http://mail.python.org/pipermail/tutor/2005-May/038059.html > > However, this is not what someone looking for an anagram algorithm > would find useful, it seems to me. > > Barry Carroll offering does the job, if the last line is revised as > shown below: > > def permute(word): > """ > By Barry Carrol > on Tutor list, revised (last line) by me. > """ > retList=[] > if len(word) == 1: > # There is only one possible permutation > retList.append(word) > else: > # Return a list of all permutations using all characters > for pos in range(len(word)): > # Get the permutations of the rest of the word > > permuteList=permute(word[0:pos]+word[pos+1:len(word)]) > # Now, tack the first char onto each word in the > list > # and add it to the output > for item in permuteList: > retList.append(word[pos]+item) > #return retList > return list(set(retList)) # make elements of retList unique > > (The line in the code in Barry's post, > "permuteList=permute2(word[0:pos]+word[pos+1:len(word)])", was > corrected to "permuteList=permute(word[0:pos]+word[pos+1:len(word)])" > in an email from him to me.) > (i.e., permute2 changed to permute) > > Dick Moores In the intrest of reusability, I would recommend leaving permute as it is and calling it from another function: ##### >>>>> def permuteset(word): >>>>> return list(set(permute(word))) >>>>> permute("121") >>>>> ['121', '112', '211', '211', '112', '121'] >>>>> permuteset("121") >>>>> ['121', '211', '112'] ##### If you're sure you will never want to use the permute function in any other way, then it doesn't matter, of course. Otherwise, it's nice to have the original function intact, in case you ever want a list of all the combinations that ARE duplicates, for example ;*) FWIW. Regards, Barry From amadeo.bellotti at gmail.com Wed Nov 29 01:24:25 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Tue, 28 Nov 2006 19:24:25 -0500 Subject: [Tutor] OT What's next Message-ID: I've recently wanted to learn more about my hardware and i figured what better way then programming at the base level. I no it sounds stupid but i would like to learn to manage my own memory. so i was wondering if anyone has dipped there toe in either C or Assembly. If you have please tell me which one you prefer and were a good site is -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061128/6abd0184/attachment.html From carroll at tjc.com Wed Nov 29 02:53:45 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 28 Nov 2006 17:53:45 -0800 (PST) Subject: [Tutor] Angles In-Reply-To: <456CB12A.9050207@web.de> Message-ID: On Tue, 28 Nov 2006, Carlos wrote: > I was never very good at trigonometry, but looks like my translation of > the equation is ok and the problem is some kind of python behavior, > because whenever the results exceed 100? (deg) Python returns the > complementary angle, it is possible to avoid this? Or I'm overlooking > somethig? Carlos, I'm not so good at trigonometry myself, but I suspect that the trouble is that for some trig functions, both an angle and that angle's complement map to the same value. For example: >>> angle1 = radians(45) # 45 degrees >>> angle2 = pi-angle1 # 135 degrees >>> print degrees(angle1), degrees(angle2) 45.0 135.0 >>> sin(angle1), sin(angle2) (0.70710678118654746, 0.70710678118654757) >>> angle1 = radians(30) >>> angle2 = pi-angle1 >>> print degrees(angle1), degrees(angle2) 30.0 150.0 >>> sin(angle1), sin(angle2) (0.49999999999999994, 0.49999999999999994) So basically, once you take a sine in your early steps, you're getting the same sine result regardless of whether it's in the first quadrant (0-90 degrees) or second quadrant (90-180 degrees). When you subsequently use that sine and try to eventually get an angle out of it, it's going to give you a first-quadrant result. I think you'll need to track the range of your input angle and adjust your output angle accordingly. The algorithm you got may only be valid for 0-90 degrees. From kent37 at tds.net Wed Nov 29 04:20:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Nov 2006 22:20:05 -0500 Subject: [Tutor] Why can't I import this? In-Reply-To: <7.0.1.0.2.20061128152828.0760f498@rcblue.com> References: <7.0.1.0.2.20061128152828.0760f498@rcblue.com> Message-ID: <456CFC65.5040409@tds.net> Dick Moores wrote: > I just discovered something for Tkinter that I want to use. It's a > Tooltip class, at . > > I've copied it to a file I named toolTipDemo.py and put it with a > couple of other files I use as modules. They're in > E:\Python25\Lib\site-packages\mine. One file there is intSpell.py, > and I can import it by > > from mine.intSpell import intSpell > > With no problem: > >>> from mine.intSpell import intSpell > >>> > However, the same method of importing doesn't work with toolTipDemo: > >>> from mine.toolTipDemo import toolTipDemo > Traceback (most recent call last): > File "", line 1, in > ImportError: cannot import name toolTipDemo Try from mine.toolTipDemo import demo mine.toolTipDemo points to the module, then you need to reference a name defined in the module. (You must have something called intSpell in intSpell.py.) Kent From rdm at rcblue.com Wed Nov 29 04:32:54 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 28 Nov 2006 19:32:54 -0800 Subject: [Tutor] Why can't I import this? In-Reply-To: <456CFC65.5040409@tds.net> References: <7.0.1.0.2.20061128152828.0760f498@rcblue.com> <456CFC65.5040409@tds.net> Message-ID: <7.0.1.0.2.20061128192256.07ade2b8@rcblue.com> At 07:20 PM 11/28/2006, Kent Johnson wrote: >Dick Moores wrote: > > I just discovered something for Tkinter that I want to use. It's a > > Tooltip class, at . > > > > I've copied it to a file I named toolTipDemo.py and put it with a > > couple of other files I use as modules. They're in > > E:\Python25\Lib\site-packages\mine. One file there is intSpell.py, > > and I can import it by > > > > from mine.intSpell import intSpell > > > > With no problem: > > >>> from mine.intSpell import intSpell > > >>> > > However, the same method of importing doesn't work with toolTipDemo: > > >>> from mine.toolTipDemo import toolTipDemo > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: cannot import name toolTipDemo > >Try >from mine.toolTipDemo import demo > >mine.toolTipDemo points to the module, then you need to reference a name >defined in the module. (You must have something called intSpell in >intSpell.py.) Interestingly (or not) it just hit me that I should try that, and it worked. So I suppose that if I want to use tooltips in a Tkinter program, I can just use "from mine.toolTipDemo import *" and use what I need. (Haven't tried that yet, however.) Thanks, Kent. Dick From amadeo.bellotti at gmail.com Wed Nov 29 04:45:29 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Tue, 28 Nov 2006 22:45:29 -0500 Subject: [Tutor] Python Linux Distro Anyone Message-ID: I was thinking it would be really nice if i could make a Pocket Linux distro that of course fits on one or two floppies (outdated I no but still are amazing) thats just the Linux kernel, bash, and python. with of course a lot of tiny scripts to do daily business and/or recovery. We could have a mail client, a text reader/editor, text based web browser, all in python. Of Course this will be a lot of work and it would be neat if the whole user group pitched in. so what I'm basically asking is that if you are interested email me and ill give you some detail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061128/41d168b1/attachment.html From kent37 at tds.net Wed Nov 29 04:48:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Nov 2006 22:48:50 -0500 Subject: [Tutor] Why can't I import this? In-Reply-To: <7.0.1.0.2.20061128192256.07ade2b8@rcblue.com> References: <7.0.1.0.2.20061128152828.0760f498@rcblue.com> <456CFC65.5040409@tds.net> <7.0.1.0.2.20061128192256.07ade2b8@rcblue.com> Message-ID: <456D0322.5020805@tds.net> Dick Moores wrote: > At 07:20 PM 11/28/2006, Kent Johnson wrote: >> Try >>from mine.toolTipDemo import demo >> mine.toolTipDemo points to the module, then you need to reference a name >> defined in the module. (You must have something called intSpell in >> intSpell.py.) > > Interestingly (or not) it just hit me that I should try that, and it > worked. So I suppose that if I want to use tooltips in a Tkinter > program, I can just use "from mine.toolTipDemo import *" and use > what I need. (Haven't tried that yet, however.) Yes, you can do that but in general that style is not recommended. It makes it hard to figure out where names are defined and you can import more than you really want. Better is to just import what you want, e.g. from mine.toolTipDemo import A, b, CC or import the module with an alias: import mine.toolTipDemo as TTD then refer to e.g. TTD.demo() Kent From dkuhlman at rexx.com Wed Nov 29 05:17:29 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 28 Nov 2006 20:17:29 -0800 Subject: [Tutor] Python Linux Distro Anyone In-Reply-To: References: Message-ID: <20061129041729.GA24287@cutter.rexx.com> On Tue, Nov 28, 2006 at 10:45:29PM -0500, Amadeo Bellotti wrote: > I was thinking it would be really nice if i could make a Pocket Linux distro > that of course fits on one or two floppies (outdated I no but still are > amazing) thats just the Linux kernel, bash, and python. with of course a lot > of tiny scripts to do daily business and/or recovery. We could have a mail > client, a text reader/editor, text based web browser, all in python. Of > Course this will be a lot of work and it would be neat if the whole user > group pitched in. so what I'm basically asking is that if you are interested > email me and ill give you some detail. What about the following? http://www.rpath.org/rbuilder/project/lamp/ http://wiki.rpath.com/wiki/Appliance:LAMP_Appliance Not a floppy. But, I believe that you would be able to boot from a CD. LAMP is more than Python, but Python is an important part of it. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Wed Nov 29 06:23:30 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 29 Nov 2006 05:23:30 -0000 Subject: [Tutor] OT What's next References: Message-ID: "Amadeo Bellotti" wrote > I've recently wanted to learn more about my hardware and i figured > what > better way then programming at the base level. I no it sounds stupid > but i > would like to learn to manage my own memory. so i was wondering if > anyone > has dipped there toe in either C or Assembly. If you have please > tell me > which one you prefer and were a good site is Never mind my toes getting wet, I was thrown in bodily! :-) C is the way to go, although you may need to dip into assembler, but that can be done most easily by using the 'inline' or 'asm' features of most PC C compilers. Pure assembler on a PC involves a huge amount of work for even the most trivial task. But for the Python programmer I'd consider Borland Delphi, based on Pascal. Pascal is much more readable and Pythonic than C and allows the same level of access to the underlying hardware (and assembler when needed). OTOH Python is written in C so learning C can help with understanding Python too! HTH, Alan G. From rdm at rcblue.com Wed Nov 29 07:44:43 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 28 Nov 2006 22:44:43 -0800 Subject: [Tutor] Why can't I import this? In-Reply-To: <456D0322.5020805@tds.net> References: <7.0.1.0.2.20061128152828.0760f498@rcblue.com> <456CFC65.5040409@tds.net> <7.0.1.0.2.20061128192256.07ade2b8@rcblue.com> <456D0322.5020805@tds.net> Message-ID: <7.0.1.0.2.20061128223738.07b4fca0@rcblue.com> At 07:48 PM 11/28/2006, Kent Johnson wrote: >Dick Moores wrote: > > At 07:20 PM 11/28/2006, Kent Johnson wrote: > >> Try > >>from mine.toolTipDemo import demo > >> mine.toolTipDemo points to the module, then you need to reference a name > >> defined in the module. (You must have something called intSpell in > >> intSpell.py.) > > > > Interestingly (or not) it just hit me that I should try that, and it > > worked. So I suppose that if I want to use tooltips in a Tkinter > > program, I can just use "from mine.toolTipDemo import *" and use > > what I need. (Haven't tried that yet, however.) > >Yes, you can do that but in general that style is not recommended. It >makes it hard to figure out where names are defined and you can import >more than you really want. Better is to just import what you want, e.g. >from mine.toolTipDemo import A, b, CC Thanks, Kent. Turns out all I needed was the class, ToolTip. So just from mine.toolTipDemo import ToolTip will do it. >or import the module with an alias: >import mine.toolTipDemo as TTD > >then refer to e.g. >TTD.demo() A good trick. Thanks very much, Kent. Dick From rabidpoobear at gmail.com Wed Nov 29 07:50:33 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 29 Nov 2006 00:50:33 -0600 Subject: [Tutor] Game programming - inventory management (was Help) In-Reply-To: <456C9ED4.2040908@alum.rpi.edu> References: <000601c71327$49084700$0b93f159@HafejiHousehold> <456C9ED4.2040908@alum.rpi.edu> Message-ID: <456D2DB9.9050701@gmail.com> Bob Gailer wrote: > Please use a meaningful subject line. Many of us try to follow > "threads", and "help" does not help. > I have provided one for this case. > > Mohammed H. Hafeji wrote: > >> Need some help in python. >> >> How do i make the user choose wheter or not to pick it up? (i can do >> picking up an item from a list): >> [snip bolded python code] >> Please also don't format your code to look different from the rest of the e-mail. I know what Python code looks like without seeing it bolded, italicized or colorized. >> >> But i cant do when u have a choice to pick up or not. >> It is helpful if you tell us what you have tried. 'I can't do x' doesn't help. 'I did x, but it didn't work out right. I think x is working this way, but I meant for it to work that way.' would be very helpful. >> >> Also if not too much trouble then how can i do: >> >> IF the user picks the bat up then when he comes across the vampire >> then he kills it, but if he hasnt pickd up the bat then he dies? >> What have you tried for this? What do you think you might do? >> >> Thanks in advance >> >> P.S. Could u plz email sum code >> We're not here to provide code for you. It's a tutor list, meant to help you learn Python. Giving you the code you want is most likely not going to help you nearly as much as if you had to make it yourself. >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > From simon at brunningonline.net Wed Nov 29 10:08:58 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 29 Nov 2006 09:08:58 +0000 Subject: [Tutor] WHy use SOAPpy if we can do the things using httplibmoduleRe: How to connect to the SOAP server and make arequest.......... In-Reply-To: <20061128203807.GA21210@andi-lap.la.revver.com> References: <78b3a9580611281221l529c3518x1b02c702414663fb@mail.gmail.com> <20061128203807.GA21210@andi-lap.la.revver.com> Message-ID: <8c7f10c60611290108u3adaafc6uc448d48b3f9024e2@mail.gmail.com> On 11/28/06, Andreas Kostyrka wrote: > Wimp! You can do it in binary machine code. Binary? You need ones *and* zeros? Loser. ;-) -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From rschroev_nospam_ml at fastmail.fm Wed Nov 29 10:47:59 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 29 Nov 2006 10:47:59 +0100 Subject: [Tutor] Angles In-Reply-To: <456CB12A.9050207@web.de> References: <456CB12A.9050207@web.de> Message-ID: Carlos schreef: > I found a webpage that details the math behind this > (http://www.usc.edu/dept/architecture/mbs/tools/vrsolar/Help/solar_concepts.html) > , it was fairly trivial to translate this to python until I got to the > azimuth equation. It looks like this: > > x_azm = sin(hour_R) * cos(decl_R) > y_azm = (-(cos(hour_R))*cos(decl_R)*sin(lat_R))+(cos(lat_R)* sin(decl_R)) > azimuth = atan(x_azm/y_azm)*TODEGREE > > My python code for this particular equation: > > from math import * > > def Az(Lat, Dec, H_Ang): > > lat_r = radians(Lat) > decl_r = radians(Dec) > hour_r = radians(H_Ang) > > x_azm = sin(hour_r) * cos(decl_r) > y_azm = (-(cos(hour_r)) * cos(decl_r) * sin(lat_r)) + > (cos(lat_r) * sin(decl_r)) > > Azimuth = degrees(atan(x_azm/y_azm)) > Azimuth = Azimuth *(-1) > return Azimuth > > I was never very good at trigonometry, but looks like my translation of > the equation is ok and the problem is some kind of python behavior, > because whenever the results exceed 100? (deg) Python returns the > complementary angle, it is possible to avoid this? Or I'm overlooking > somethig? I think the problem is with the atan() function: you divide x_azm by y_azm, which makes you lose the signs. There is an alternative, the atan2() function, which takes two parameters. Therefore it can use the signs of both x_azm and y_azm to work out the correct quadrant. So I'd try: Azimuth = degrees(atan2(x_azm, y_azm)) -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From anders.u.persson at telia.com Wed Nov 29 14:25:31 2006 From: anders.u.persson at telia.com (Anders Persson) Date: Wed, 29 Nov 2006 14:25:31 +0100 Subject: [Tutor] Use Python to learn kids (9 yr) to program Message-ID: <456D8A4B.7040207@telia.com> Hi! I have looked around for som language to use to learn my 9 year son programming. There is a KPL - Kids Programming Language but my son diden't grasp the OO, GUI and everyting around this, maby becurse English is not his spoken language, and for a beginner i think the inviroment was to complex. So my plan is to use Python, has anyone try to learn kids this way, and could giv som ide how-to. I witch way to introduce every part of the language,,, best regards Anders From andre.roberge at gmail.com Wed Nov 29 15:56:18 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 29 Nov 2006 10:56:18 -0400 Subject: [Tutor] Use Python to learn kids (9 yr) to program In-Reply-To: <456D8A4B.7040207@telia.com> References: <456D8A4B.7040207@telia.com> Message-ID: <7528bcdd0611290656i4d2491c2o684d7c4f40992807@mail.gmail.com> HI- I think Python is a great choice. You may want to have a look, as a first step, at rur-ple. Then, as a next step (although it might be a bit steep), you may want to have a look at livewires . This will provide a good introduction to pygame . Andr? On 11/29/06, Anders Persson wrote: > > Hi! > > I have looked around for som language to use to learn my 9 year son > programming. > > There is a KPL - Kids Programming Language but my son diden't grasp the > OO, GUI and everyting around this, maby becurse English is not his spoken > language, and for a beginner i think the inviroment was to complex. > > So my plan is to use Python, has anyone try to learn kids this way, and > could > giv som ide how-to. > I witch way to introduce every part of the language,,, > > best regards > Anders > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061129/e358a3dc/attachment.html From python at venix.com Wed Nov 29 17:21:26 2006 From: python at venix.com (Python) Date: Wed, 29 Nov 2006 11:21:26 -0500 Subject: [Tutor] Python Linux Distro Anyone In-Reply-To: References: Message-ID: <1164817286.19530.550.camel@www.venix.com> On Tue, 2006-11-28 at 22:45 -0500, Amadeo Bellotti wrote: > I was thinking it would be really nice if i could make a Pocket Linux > distro that of course fits on one or two floppies (outdated I no but > still are amazing) thats just the Linux kernel, bash, and python. with > of course a lot of tiny scripts to do daily business and/or recovery. You might want to look at puppyOS. http://www.puppyos.net/ It is designed to boot from USB memory and provides a small footprint OS. http://www.puppyos.net/pfs/ Describes how to build puppy from scratch (pfs) which would allow you to build your own tiny version. > We could have a mail client, a text reader/editor, text based web > browser, all in python. Of Course this will be a lot of work and it > would be neat if the whole user group pitched in. so what I'm > basically asking is that if you are interested email me and ill give > you some detail. Shooting for a floppy disk based distribution is too much pain with too little gain for me. The puppy approach of a bootable OS that you can carry in your pocket is pretty slick. I'm using a 1 GB USB flash which is, for me, reasonably low cost and far better than carrying floppy disks. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From carloslara at web.de Wed Nov 29 17:41:22 2006 From: carloslara at web.de (Carlos) Date: Wed, 29 Nov 2006 17:41:22 +0100 Subject: [Tutor] Angles In-Reply-To: References: Message-ID: <456DB832.6000204@web.de> Thanks Terry and Roel, I got it working now, the problem was a sign situation. I fixed it this way: from math import * def Az(Lat, Dec, H_Ang): lat_R = radians(Lat) decl_R = radians(Dec) hour_R = radians(H_Ang) x_azm = sin(hour_R) * cos(decl_R) y_azm = (-(cos(hour_R))*cos(decl_R)*sin(lat_R))+(cos(lat_R)* sin(decl_R)) if Lat > 0: y_azm = y_azm * -1 Azimuth = degrees(atan2(x_azm, y_azm)) return Azimuth The if conditional tells the system wether the sun is east or west. Looks like this fixes it. Cheers From Senthil_OR at Dell.com Wed Nov 29 19:31:04 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Thu, 30 Nov 2006 00:01:04 +0530 Subject: [Tutor] Use Python to learn kids (9 yr) to program In-Reply-To: <7528bcdd0611290656i4d2491c2o684d7c4f40992807@mail.gmail.com> Message-ID: Hi, Playing with Guido Van Robot http://gvr.sf.net is another good option to teach programming to young ones. Rurple is just another graphic representation of the gvr. -- Senthil ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Andre Roberge Sent: Wednesday, November 29, 2006 8:26 PM To: anders.u.persson at telia.com Cc: bp Subject: Re: [Tutor] Use Python to learn kids (9 yr) to program HI- I think Python is a great choice. You may want to have a look, as a first step, at rur-ple . Then, as a next step (although it might be a bit steep), you may want to have a look at livewires . This will provide a good introduction to pygame . Andr? On 11/29/06, Anders Persson wrote: Hi! I have looked around for som language to use to learn my 9 year son programming. There is a KPL - Kids Programming Language but my son diden't grasp the OO, GUI and everyting around this, maby becurse English is not his spoken language, and for a beginner i think the inviroment was to complex. So my plan is to use Python, has anyone try to learn kids this way, and could giv som ide how-to. I witch way to introduce every part of the language,,, best regards Anders _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061130/04e1aed8/attachment.html From carloslara at web.de Wed Nov 29 19:38:32 2006 From: carloslara at web.de (Carlos) Date: Wed, 29 Nov 2006 19:38:32 +0100 Subject: [Tutor] Sun Location System Message-ID: <456DD3A8.4050401@web.de> Hi Again, I have been working in a sun location system and it seems like is working now. But I have two issues that I hope you can help me solve. I have a number of functions in this script and I would like to know which is the best way to pass values among them? Here is the script so far: ##################################################################### from math import * # I would like to substitute Lat for the location name def Sol_Pos (Lat, Month, Day, Hour): month_index = Month -1 date_index = Day -1 def J_Day(month_index,date_index): j_day=0 date_val=date_index+1 if (month_index==0): j_day = 0+date_val elif (month_index==1): j_day=31+date_val elif (month_index==2): j_day=59+date_val elif (month_index==3): j_day=90+date_val elif (month_index==4): j_day=120+date_val elif (month_index==5): j_day=151+date_val elif (month_index==6): j_day=181+date_val elif (month_index==7): j_day=212+date_val elif (month_index==8): j_day=243+date_val elif (month_index==9): j_day=273+date_val elif (month_index==10): j_day=304+date_val elif (month_index==11): j_day=334+date_val return j_day def Dec(J_Day): Dec = 23.45 * sin(radians(( j_day + 284.0) * 360/365)) return Dec def H_Ang(Hour): Hour_Angle = 15*(12-Hour) return Hour_Angle def Alt(Lat, Dec, H_Ang): lat_r = radians(Lat) decl_r = radians(Dec) hour_r = radians(H_Ang) sin_alt_r = cos(lat_r)*cos(decl_r)*cos(hour_r)+sin(lat_r)*sin(decl_r) sin2alt = sin_alt_r * sin_alt_r cos_alt_r = sqrt(1 - sin2alt) Alt = degrees(atan(sin_alt_r / cos_alt_r)) return Sol_Alt def Az(Lat, Dec, H_Ang): lat_R = radians(Lat) decl_R = radians(Dec) hour_R = radians(H_Ang) x_azm = sin(hour_R) * cos(decl_R) y_azm = (-(cos(hour_R))*cos(decl_R)*sin(lat_R))+(cos(lat_R)* sin(decl_R)) if Lat > 0: y_azm = y_azm * -1 Azimuth = degrees(atan2(x_azm, y_azm)) return Azimuth #################################################################### And my idea is to give the script a location name, date and hour and it will return the sun position relative to that info. So how can I work with info of this type? 30.30 48.20 Abadan, Iran 45.40 -98.40 Aberdeen Ap, South Dakota - USA 57.10 -2.10 Aberdeen, Scotland 46.90 -123.80 Aberdeen, Washington - USA 5.30 -4.00 Abidjan, Ivory Coasti 32.40 -99.60 Abilene Ap, Texas - USA 5.50 -0.20 Accra, Ghana I know that a dictionary probably is a solution, but as you can imagine formatting this data is going to take a long time, there are too many locations. Is there a solution for this problem? Thanks for your help, Carlos From carroll at tjc.com Wed Nov 29 20:25:53 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 29 Nov 2006 11:25:53 -0800 (PST) Subject: [Tutor] OT What's next In-Reply-To: Message-ID: On Wed, 29 Nov 2006, Alan Gauld wrote: > But for the Python programmer I'd consider Borland Delphi, based > on Pascal. Pascal is much more readable and Pythonic than C > and allows the same level of access to the underlying hardware > (and assembler when needed). I'm going to apologize for taking this even further off-topic, but, if the OP is looking at Delphi, he should know that Borland provides a version of Delphi, called Turbo Delphi Explorer, that you can download and use for free. We also offer a priced "Professional" version, but for the OP's interests, the Explorer edition will probably work just fine. http://www.turboexplorer.com/ http://www.borland.com/downloads/download_turbo.html Full disclosure: I say "we" above, because I *am* affiliated with Borland: I'm Borland's in-house attorney for intellectual property and product matters. (What's an attorney doing on a Python list? I was a developer before I was an attorney, and still play around a little bit here and there, and I usually use Python when I do.) From shitizb at yahoo.com Wed Nov 29 20:35:53 2006 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed, 29 Nov 2006 11:35:53 -0800 (PST) Subject: [Tutor] Beautiful Soup In-Reply-To: Message-ID: <504807.68633.qm@web53807.mail.yahoo.com> Hi, I am using beautiful soup for extracting links from a web page. Most pages use relative links in their pages which is causing a problem. Is there any library to extract complete links or do i have to parse this myself? Thanks, Shitiz Terry Carroll wrote: On Wed, 29 Nov 2006, Alan Gauld wrote: > But for the Python programmer I'd consider Borland Delphi, based > on Pascal. Pascal is much more readable and Pythonic than C > and allows the same level of access to the underlying hardware > (and assembler when needed). I'm going to apologize for taking this even further off-topic, but, if the OP is looking at Delphi, he should know that Borland provides a version of Delphi, called Turbo Delphi Explorer, that you can download and use for free. We also offer a priced "Professional" version, but for the OP's interests, the Explorer edition will probably work just fine. http://www.turboexplorer.com/ http://www.borland.com/downloads/download_turbo.html Full disclosure: I say "we" above, because I *am* affiliated with Borland: I'm Borland's in-house attorney for intellectual property and product matters. (What's an attorney doing on a Python list? I was a developer before I was an attorney, and still play around a little bit here and there, and I usually use Python when I do.) _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Cheap Talk? Check out Yahoo! Messenger's low PC-to-Phone call rates. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061129/519c3d96/attachment-0001.htm From akashmahajan at gmail.com Wed Nov 29 20:53:39 2006 From: akashmahajan at gmail.com (Akash) Date: Thu, 30 Nov 2006 01:23:39 +0530 Subject: [Tutor] Beautiful Soup In-Reply-To: <504807.68633.qm@web53807.mail.yahoo.com> References: <504807.68633.qm@web53807.mail.yahoo.com> Message-ID: <868b524f0611291153l29351452p30db75c7a3e9388@mail.gmail.com> On 11/30/06, Shitiz Bansal wrote: > I am using beautiful soup for extracting links from a web page. > Most pages use relative links in their pages which is causing a problem. Is > there any library to extract complete links or do i have to parse this > myself? > Beautiful Soup can also extract text which is present on the page. If there are no complete links no library can do that for you. But since you are reaching a certain web page to extract you already have that URL information with you. All you have to do then is to prefix it to each extracted URL. HTH akash From andreas at kostyrka.org Wed Nov 29 21:07:15 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 29 Nov 2006 21:07:15 +0100 Subject: [Tutor] Beautiful Soup In-Reply-To: <868b524f0611291153l29351452p30db75c7a3e9388@mail.gmail.com> References: <504807.68633.qm@web53807.mail.yahoo.com> <868b524f0611291153l29351452p30db75c7a3e9388@mail.gmail.com> Message-ID: <20061129200712.GI5201@andi-lap.la.revver.com> * Akash [061129 20:54]: > On 11/30/06, Shitiz Bansal wrote: > > I am using beautiful soup for extracting links from a web page. > > Most pages use relative links in their pages which is causing a problem. Is > > there any library to extract complete links or do i have to parse this > > myself? > > > > Beautiful Soup can also extract text which is present on the page. If > there are no complete links no library can do that for you. But since > you are reaching a certain web page to extract you already have that > URL information with you. All you have to do then is to prefix it to > each extracted URL. Take a look at urlparse.urljoin from the standard library. Andreas From andre.roberge at gmail.com Wed Nov 29 21:33:39 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 29 Nov 2006 16:33:39 -0400 Subject: [Tutor] Use Python to learn kids (9 yr) to program In-Reply-To: References: <7528bcdd0611290656i4d2491c2o684d7c4f40992807@mail.gmail.com> Message-ID: <7528bcdd0611291233q6856a5e8l9ccb8d72e894fa5d@mail.gmail.com> On 11/29/06, Senthil_OR at dell.com wrote: > > Hi, > Playing with Guido Van Robot http://gvr.sf.net is another good option > to teach programming to young ones. Rurple is just another graphic > representation of the gvr. > Not quite. GvR uses a Python-like notation and has no OOP support. Rur-ple uses standard Python and has OOP support. Andr? -- > Senthil > > > ------------------------------ > *From:* tutor-bounces at python.org [mailto:tutor-bounces at python.org] *On > Behalf Of *Andre Roberge > *Sent:* Wednesday, November 29, 2006 8:26 PM > *To:* anders.u.persson at telia.com > *Cc:* bp > *Subject:* Re: [Tutor] Use Python to learn kids (9 yr) to program > > HI- > > I think Python is a great choice. > > You may want to have a look, as a first step, at rur-ple. > Then, as a next step (although it might be a bit steep), you may want to > have a look at livewires . This > will provide a good introduction to pygame . > > Andr? > > On 11/29/06, Anders Persson wrote: > > > > Hi! > > > > I have looked around for som language to use to learn my 9 year son > > programming. > > > > There is a KPL - Kids Programming Language but my son diden't grasp the > > OO, GUI and everyting around this, maby becurse English is not his > > spoken > > language, and for a beginner i think the inviroment was to complex. > > > > So my plan is to use Python, has anyone try to learn kids this way, and > > could > > giv som ide how-to. > > I witch way to introduce every part of the language,,, > > > > best regards > > Anders > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061129/a3b73073/attachment.html From shitizb at yahoo.com Wed Nov 29 21:42:29 2006 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed, 29 Nov 2006 12:42:29 -0800 (PST) Subject: [Tutor] Beautiful Soup In-Reply-To: <20061129200712.GI5201@andi-lap.la.revver.com> Message-ID: <935447.78711.qm@web53810.mail.yahoo.com> Thanks, urlparse.urljoin did the trick. Akash- the problem with directly prefixing url to the link is that the url most of the times contains not just the page address but also parameters and fragments. Andreas Kostyrka wrote: * Akash [061129 20:54]: > On 11/30/06, Shitiz Bansal wrote: > > I am using beautiful soup for extracting links from a web page. > > Most pages use relative links in their pages which is causing a problem. Is > > there any library to extract complete links or do i have to parse this > > myself? > > > > Beautiful Soup can also extract text which is present on the page. If > there are no complete links no library can do that for you. But since > you are reaching a certain web page to extract you already have that > URL information with you. All you have to do then is to prefix it to > each extracted URL. Take a look at urlparse.urljoin from the standard library. Andreas --------------------------------- Access over 1 million songs - Yahoo! Music Unlimited. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061129/68e071d6/attachment.html From amonroe at columbus.rr.com Thu Nov 30 01:32:57 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 29 Nov 2006 19:32:57 -0500 Subject: [Tutor] OT What's next In-Reply-To: References: Message-ID: <163301647446.20061129193257@columbus.rr.com> > Pure assembler on a PC involves a huge amount of work for even > the most trivial task. Some useful assembly tips here: http://www.grc.com/smgassembly.htm Alan From amonroe at columbus.rr.com Thu Nov 30 01:47:55 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 29 Nov 2006 19:47:55 -0500 Subject: [Tutor] Use Python to learn kids (9 yr) to program In-Reply-To: <456D8A4B.7040207@telia.com> References: <456D8A4B.7040207@telia.com> Message-ID: <88302544606.20061129194755@columbus.rr.com> > So my plan is to use Python, has anyone try to learn kids this way, and > could > giv som ide how-to. > I witch way to introduce every part of the language,,, http://davidbau.com/archives/2005/07/29/haaarg_world.html Alan From carroll at tjc.com Thu Nov 30 02:29:19 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 29 Nov 2006 17:29:19 -0800 (PST) Subject: [Tutor] OT What's next In-Reply-To: <163301647446.20061129193257@columbus.rr.com> Message-ID: On Wed, 29 Nov 2006, R. Alan Monroe wrote: > > Pure assembler on a PC involves a huge amount of work for even > > the most trivial task. > > Some useful assembly tips here: > http://www.grc.com/smgassembly.htm I never wanted to actually program assembly on the PC, but I did want to understand it (actually, I wanted to understand the Intel x86 architecture, and there's no better way of doing that than learning the assembly language for a machine). I read Jeff Duntemann's "Assembly language Step-by-Step," http://duntemann.com/assembly.htm , and found it very useful, although I didn't actually try any programming. I'm an old mainframe assembler language hack from way back in the IBM System/370 days (although in my last development job, I wrote more in machine code than in actual assembler), so I didn't really need or desire to do the practical aspects of actually writing x86 code; but I felt that would have been a good book to get me there, had that been what I wanted. A couple of years ago, I took a course in which I built a rudimentary computer around an Intel 8031 chip; and when I say "built," I mean built. It was a couple dozen components on a breadboard, with about only about 2Kbytes of memory, if I recall; I soldered or wire-wrapped every connection. You really learn an architecture when you do that. not that I remember much of it anymore, two years later. Not a route I recommend. I needed a few credits to fill an obscure educational requirement, though, and this was a fun way to do it. From amonroe at columbus.rr.com Thu Nov 30 02:34:49 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 29 Nov 2006 20:34:49 -0500 Subject: [Tutor] OT What's next In-Reply-To: References: Message-ID: <141305359493.20061129203449@columbus.rr.com> > A couple of years ago, I took a course in which I built a rudimentary > computer around an Intel 8031 chip; and when I say "built," I mean built. > It was a couple dozen components on a breadboard, with about only about > 2Kbytes of memory, if I recall; I soldered or wire-wrapped every > connection. You really learn an architecture when you do that. not that > I remember much of it anymore, two years later. Not a route I recommend. > I needed a few credits to fill an obscure educational requirement, though, > and this was a fun way to do it. Have you seen http://www.xgamestation.com/ ? Alan From amadeo.bellotti at gmail.com Thu Nov 30 02:39:18 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Wed, 29 Nov 2006 20:39:18 -0500 Subject: [Tutor] OT What's next In-Reply-To: References: <163301647446.20061129193257@columbus.rr.com> Message-ID: thank you to all I think I'm going to take on C maybe after i learn that take it to python and implement both at the same time. so step one choosing what language - done step two sites to learn anyone know where i can look up c programming for linux? On 11/29/06, Terry Carroll wrote: > > On Wed, 29 Nov 2006, R. Alan Monroe wrote: > > > > Pure assembler on a PC involves a huge amount of work for even > > > the most trivial task. > > > > Some useful assembly tips here: > > http://www.grc.com/smgassembly.htm > > I never wanted to actually program assembly on the PC, but I did want to > understand it (actually, I wanted to understand the Intel x86 > architecture, and there's no better way of doing that than learning the > assembly language for a machine). I read Jeff Duntemann's "Assembly > language Step-by-Step," http://duntemann.com/assembly.htm , and found it > very useful, although I didn't actually try any programming. > > I'm an old mainframe assembler language hack from way back in the IBM > System/370 days (although in my last development job, I wrote more in > machine code than in actual assembler), so I didn't really need or desire > to do the practical aspects of actually writing x86 code; but I felt that > would have been a good book to get me there, had that been what I wanted. > > A couple of years ago, I took a course in which I built a rudimentary > computer around an Intel 8031 chip; and when I say "built," I mean built. > It was a couple dozen components on a breadboard, with about only about > 2Kbytes of memory, if I recall; I soldered or wire-wrapped every > connection. You really learn an architecture when you do that. not that > I remember much of it anymore, two years later. Not a route I recommend. > I needed a few credits to fill an obscure educational requirement, though, > and this was a fun way to do it. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061129/c1ec8c3c/attachment.htm From amadeo.bellotti at gmail.com Thu Nov 30 02:57:35 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Wed, 29 Nov 2006 20:57:35 -0500 Subject: [Tutor] Python Linux Distro Anyone In-Reply-To: <1164817286.19530.550.camel@www.venix.com> References: <1164817286.19530.550.camel@www.venix.com> Message-ID: Dave I looked at LAMP it really didn't have everything I need well more like want. I was thinking instead of Vi or emacs have a text editor written in python which would save a lot of space. Instead of lynx have one in python. On 11/29/06, Python wrote: > > On Tue, 2006-11-28 at 22:45 -0500, Amadeo Bellotti wrote: > > I was thinking it would be really nice if i could make a Pocket Linux > > distro that of course fits on one or two floppies (outdated I no but > > still are amazing) thats just the Linux kernel, bash, and python. with > > of course a lot of tiny scripts to do daily business and/or recovery. > > You might want to look at puppyOS. > http://www.puppyos.net/ > It is designed to boot from USB memory and provides a small footprint > OS. > > http://www.puppyos.net/pfs/ > Describes how to build puppy from scratch (pfs) which would allow you to > build your own tiny version. > > > We could have a mail client, a text reader/editor, text based web > > browser, all in python. Of Course this will be a lot of work and it > > would be neat if the whole user group pitched in. so what I'm > > basically asking is that if you are interested email me and ill give > > you some detail. > > Shooting for a floppy disk based distribution is too much pain with too > little gain for me. The puppy approach of a bootable OS that you can > carry in your pocket is pretty slick. I'm using a 1 GB USB flash which > is, for me, reasonably low cost and far better than carrying floppy > disks. > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061129/af6004c3/attachment.html From Senthil_OR at Dell.com Thu Nov 30 07:25:17 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Thu, 30 Nov 2006 11:55:17 +0530 Subject: [Tutor] Use Python to learn kids (9 yr) to program In-Reply-To: <7528bcdd0611291233q6856a5e8l9ccb8d72e894fa5d@mail.gmail.com> Message-ID: Andre Roberge wrote: > On 11/29/06, Senthil_OR at dell.com wrote: > Hi, > Playing with Guido Van Robot http://gvr.sf.net is another good > option to teach programming to young ones. Rurple is just another > graphic representation of the gvr. > > > > Not quite. GvR uses a Python-like notation and has no OOP support. > Rur-ple uses standard Python and has OOP support. > Andr? Thanks for clarifying Andre. Infact, myself and my young friends started with GVR, after completing it. I analyzed rur-ple. On the surface, I found it similar (if not the same). We were more interested with programming than python. For the purpose of introduction to programming to young ppl, does GVR or Rurple really make a difference? We are trying to play with squeak now, but little progress so far. You might like to know about my friend Avi, we tried gvr and trying squeak and trying to understand freeciv: http://puggy.symonds.net/~senthil/Phoenix/Avi_Quiz.ppt -- Senthil From roka100 at gmail.com Thu Nov 30 09:13:36 2006 From: roka100 at gmail.com (Jia Lu) Date: Thu, 30 Nov 2006 17:13:36 +0900 Subject: [Tutor] Why SelectAll() cannot work well ? Message-ID: <9a1e512f0611300013t519df62bic9108640fec980b6@mail.gmail.com> Hi all I am using wx Py with FC6. I ran the program below but I found the method SelectAll() cannot work well.(The last letter didnot be selected.!!) ------------------ import wx ComboList = ['Akari', 'Aika', 'Alice'] class MyApp(wx.App): def OnInit(self): frame = wx.Frame(None, -1, "ARIA", size=(250, 100)) frame.Show() self.CBox = wx.ComboBox(frame, -1, "Alicia", pos=(20, 20), size=(100,30), choices=ComboList) self.Text = wx.StaticText(frame, -1, "ARIA", pos=(20,50)) # Note: EVT self.CBox.Bind(wx.EVT_COMBOBOX, self.OnSelect) self.CBox.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) #self.CBox.SetSelection(2) return 1 def OnSelect(self, event): Text = self.CBox.GetStringSelection() self.Text.SetLabel(Text) def OnEnter(self, event): Text = self.CBox.GetValue() self.Text.SetLabel(Text) self.CBox.SetFocus() self.CBox.SelectAll() app = MyApp() app.MainLoop() -- -- Jia LU Registered Linux user #434792 python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '001akor at liamg.moc'.split('@')])" -- \ "Unix is an operating system, OS/2 is half an operating system, | `\ Windows is a shell, and DOS is a boot partition virus." -- | _o__) Peter H. Coffin | -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061130/1489a6f4/attachment.htm From jason.massey at gmail.com Thu Nov 30 17:01:41 2006 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 30 Nov 2006 10:01:41 -0600 Subject: [Tutor] Why SelectAll() cannot work well ? In-Reply-To: <9a1e512f0611300013t519df62bic9108640fec980b6@mail.gmail.com> References: <9a1e512f0611300013t519df62bic9108640fec980b6@mail.gmail.com> Message-ID: <7e3eab2c0611300801g77ddad67q9e5113c8fb247c3c@mail.gmail.com> I'm running WinXP and the entire text is selected when you enter a new choice. In fact, on XP at least, you don't have to use SelectAll, SetFocus selected the entire text. On 11/30/06, Jia Lu wrote: > > Hi all > > I am using wx Py with FC6. I ran the program below but I found the method > SelectAll() cannot work well.(The last letter didnot be selected.!!) > ------------------ > import wx > > ComboList = ['Akari', 'Aika', 'Alice'] > > class MyApp(wx.App): > def OnInit(self): > frame = wx.Frame(None, -1, "ARIA", size=(250, 100)) > frame.Show() > > self.CBox = wx.ComboBox(frame, -1, "Alicia", pos=(20, 20), > size=(100,30), choices=ComboList) > self.Text = wx.StaticText(frame, -1, "ARIA", pos=(20,50)) > # Note: EVT > self.CBox.Bind(wx.EVT_COMBOBOX, self.OnSelect) > self.CBox.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) > #self.CBox.SetSelection(2) > return 1 > > def OnSelect(self, event): > Text = self.CBox.GetStringSelection() > self.Text.SetLabel(Text) > > def OnEnter(self, event): > Text = self.CBox.GetValue() > self.Text.SetLabel(Text) > self.CBox.SetFocus() > self.CBox.SelectAll() > > app = MyApp() > app.MainLoop() > > > > -- > -- Jia LU > < http://www.lujia.us> > Registered Linux user #434792 > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p > in '001akor at liamg.moc'.split('@')])" > -- > \ "Unix is an operating system, OS/2 is half an operating system, | > `\ Windows is a shell, and DOS is a boot partition virus." -- | > _o__) Peter H. Coffin | > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061130/2ab7b27a/attachment.html From jfabiani at yolo.com Thu Nov 30 18:17:44 2006 From: jfabiani at yolo.com (johnf) Date: Thu, 30 Nov 2006 09:17:44 -0800 Subject: [Tutor] Why SelectAll() cannot work well ? In-Reply-To: <9a1e512f0611300013t519df62bic9108640fec980b6@mail.gmail.com> References: <9a1e512f0611300013t519df62bic9108640fec980b6@mail.gmail.com> Message-ID: <200611300917.44132.jfabiani@yolo.com> On Thursday 30 November 2006 00:13, Jia Lu wrote: > Hi all > > I am using wx Py with FC6. I ran the program below but I found the method > SelectAll() cannot work well.(The last letter didnot be selected.!!) > ------------------ > import wx > > ComboList = ['Akari', 'Aika', 'Alice'] > > class MyApp(wx.App): > def OnInit(self): > frame = wx.Frame(None, -1, "ARIA", size=(250, 100)) > frame.Show() > > self.CBox = wx.ComboBox(frame, -1, "Alicia", pos=(20, 20), > size=(100,30), choices=ComboList) > self.Text = wx.StaticText(frame, -1, "ARIA", pos=(20,50)) > # Note: EVT > self.CBox.Bind(wx.EVT_COMBOBOX, self.OnSelect) > self.CBox.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) > #self.CBox.SetSelection(2) > return 1 > > def OnSelect(self, event): > Text = self.CBox.GetStringSelection() > self.Text.SetLabel(Text) > > def OnEnter(self, event): > Text = self.CBox.GetValue() > self.Text.SetLabel(Text) > self.CBox.SetFocus() > self.CBox.SelectAll() > > app = MyApp() > app.MainLoop() I spoke to soon. I can confirm SelectAll() does not highlight all the text. The last letter is not selected..... -- John Fabiani From jfabiani at yolo.com Thu Nov 30 18:13:22 2006 From: jfabiani at yolo.com (johnf) Date: Thu, 30 Nov 2006 09:13:22 -0800 Subject: [Tutor] Why SelectAll() cannot work well ? In-Reply-To: <9a1e512f0611300013t519df62bic9108640fec980b6@mail.gmail.com> References: <9a1e512f0611300013t519df62bic9108640fec980b6@mail.gmail.com> Message-ID: <200611300913.22763.jfabiani@yolo.com> On Thursday 30 November 2006 00:13, Jia Lu wrote: > import wx > > ComboList = ['Akari', 'Aika', 'Alice'] > > class MyApp(wx.App): > ? ? def OnInit(self): > ? ? ? ? frame = wx.Frame(None, -1, "ARIA", size=(250, 100)) > ? ? ? ? frame.Show() > > ? ? ? ? self.CBox = wx.ComboBox(frame, -1, "Alicia", pos=(20, 20), > size=(100,30), choices=ComboList) > ? ? ? ? self.Text = wx.StaticText(frame, -1, "ARIA", pos=(20,50)) > ? ? ? ? # Note: EVT > ? ? ? ? self.CBox.Bind(wx.EVT_COMBOBOX, self.OnSelect) > ? ? ? ? self.CBox.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) > ? ? ? ? #self.CBox.SetSelection(2) > ? ? ? ? return 1 > > ? ? def OnSelect(self, event): > ? ? ? ? Text = self.CBox.GetStringSelection() > ? ? ? ? self.Text.SetLabel(Text) > > ? ? def OnEnter(self, event): > ? ? ? ? Text = self.CBox.GetValue() > ? ? ? ? self.Text.SetLabel(Text) > ? ? ? ? self.CBox.SetFocus() > ? ? ? ? self.CBox.SelectAll() > > app = MyApp() > app.MainLoop() SUSE 10.1 python 2.4.3 wxPython 2.6.? works for me -- John Fabiani From rdm at rcblue.com Thu Nov 30 20:25:46 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 30 Nov 2006 11:25:46 -0800 Subject: [Tutor] How to get Python to find tk/tcl? Message-ID: <7.0.1.0.2.20061130111820.05c4e2f0@rcblue.com> I'd like to use TableListWrapper (). I ran it as TableList.py, and got this error: E:\Python25\dev\Tkinter>python TableList.py Traceback (most recent call last): File "TableList.py", line 1142, in tabletest() File "TableList.py", line 1061, in tabletest stretch = "all" File "TableList.py", line 50, in __init__ _loadtablelist(master) File "TableList.py", line 1039, in _loadtablelist parent.tk.call("package", "require", "tablelist") _tkinter.TclError: can't find package tablelist I have tcl in E:\Python25\tcl. It came with Python 2.5? Is the above error caused by Python not being able to find tk/pcl? If so, what do I do? And if not, what do I do? Thanks, Dick Moores From kent37 at tds.net Thu Nov 30 20:44:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Nov 2006 14:44:46 -0500 Subject: [Tutor] How to get Python to find tk/tcl? In-Reply-To: <7.0.1.0.2.20061130111820.05c4e2f0@rcblue.com> References: <7.0.1.0.2.20061130111820.05c4e2f0@rcblue.com> Message-ID: <456F34AE.8090606@tds.net> Dick Moores wrote: > I'd like to use TableListWrapper > (). I ran it as > TableList.py, and got this error: > > E:\Python25\dev\Tkinter>python TableList.py > Traceback (most recent call last): > File "TableList.py", line 1142, in > tabletest() > File "TableList.py", line 1061, in tabletest > stretch = "all" > File "TableList.py", line 50, in __init__ > _loadtablelist(master) > File "TableList.py", line 1039, in _loadtablelist > parent.tk.call("package", "require", "tablelist") > _tkinter.TclError: can't find package tablelist > > I have tcl in E:\Python25\tcl. It came with Python 2.5? Is the above > error caused by Python not being able to find tk/pcl? If so, what do > I do? And if not, what do I do? My guess is that you need the actual tcl tablelist widget from http://www.nemethi.de/ stored somewhere where tcl will find it, maybe in E:\Python25\tcl\tk8.4. Kent From alan.gauld at btinternet.com Thu Nov 30 21:25:58 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Nov 2006 20:25:58 -0000 Subject: [Tutor] OT What's next References: <163301647446.20061129193257@columbus.rr.com> Message-ID: "Amadeo Bellotti" wrote > step two sites to learn anyone know where i can look > up c programming for linux? Ah! Now, if you'd said you were talking about a Linux PC then there would be no question. C is the only way to go. The Linux documentation project has loads of stuff about programming for Linux, but you need to learn C first. My personal choices for books are: 1) The original C Language book by Kernighan & Ritchie One of the finest programming tutorials ever written, great for core C but useless for the library functions. 2) C The Complete Reference by Schildt. A very good tutorial that also makes a good (albeit DOS oriented) reference manual. Online I haven't seen anything outstanding for C but then I haven't really looked at beginners tutorials because I could already program C before the web was invented! One thing - Don;t get sidetracked into C++. Its a whole different ballgame, much more complex and unnecessary if you want to go low level. HTH, Alan G. > > On 11/29/06, Terry Carroll wrote: >> >> On Wed, 29 Nov 2006, R. Alan Monroe wrote: >> >> > > Pure assembler on a PC involves a huge amount of work for even >> > > the most trivial task. >> > >> > Some useful assembly tips here: >> > http://www.grc.com/smgassembly.htm >> >> I never wanted to actually program assembly on the PC, but I did >> want to >> understand it (actually, I wanted to understand the Intel x86 >> architecture, and there's no better way of doing that than learning >> the >> assembly language for a machine). I read Jeff Duntemann's >> "Assembly >> language Step-by-Step," http://duntemann.com/assembly.htm , and >> found it >> very useful, although I didn't actually try any programming. >> >> I'm an old mainframe assembler language hack from way back in the >> IBM >> System/370 days (although in my last development job, I wrote more >> in >> machine code than in actual assembler), so I didn't really need or >> desire >> to do the practical aspects of actually writing x86 code; but I >> felt that >> would have been a good book to get me there, had that been what I >> wanted. >> >> A couple of years ago, I took a course in which I built a >> rudimentary >> computer around an Intel 8031 chip; and when I say "built," I mean >> built. >> It was a couple dozen components on a breadboard, with about only >> about >> 2Kbytes of memory, if I recall; I soldered or wire-wrapped every >> connection. You really learn an architecture when you do that. >> not that >> I remember much of it anymore, two years later. Not a route I >> recommend. >> I needed a few credits to fill an obscure educational requirement, >> though, >> and this was a fun way to do it. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Thu Nov 30 21:31:13 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Nov 2006 20:31:13 -0000 Subject: [Tutor] Use Python to learn kids (9 yr) to program References: <456D8A4B.7040207@telia.com> Message-ID: "Anders Persson" wrote > So my plan is to use Python, has anyone try to learn kids this way, > and > could giv som ide how-to. I have had an 11 year old complete my tutorial with no help from adults (apart from a few emails to me) and a 10 year old complete it with the aid of his father. I've also had a 10 year old girl go through my book(the paper edition) with her father and succeed. They are the youngest I know of. The Python Edu SIG would be worth asking about this. Also Gregor lingl(sp?) had a book/version of Python specifically for teaching kids. I think it was in English as well as Gregor's native German. Gregor, are you still on tutor list? The other language with a very good repoutation for teaching children is Logo, it has quite a good community for this purpose too. And there are Windows versions with reasonable IDE too. HTH, Alan G. From alan.gauld at btinternet.com Thu Nov 30 21:33:02 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Nov 2006 20:33:02 -0000 Subject: [Tutor] Use Python to learn kids (9 yr) to program References: <456D8A4B.7040207@telia.com> Message-ID: "Anders Persson" wrote > So my plan is to use Python, has anyone try to learn kids this way, > and > could giv som ide how-to. I meant to mention that SmallTalk also has a good reputation as a teaching language with kids in the 10-15 age group. I've never tried it, but personally found Smalltalk quite "challenging" to learn... But then, I was an adult who could already program in more conventional languages... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Thu Nov 30 21:39:51 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 30 Nov 2006 20:39:51 +0000 Subject: [Tutor] finding AcroRd32.exe - a better way ? Message-ID: <200611302039.51237.pythontut@pusspaws.net> My app generates an on the fly PDF manual by using reportlab, once generated I would like it to be automatically opened and displayed by XP adobe reader. Here's where I get stuck. ... os.execv('E:\Program Files\Adobe\Acrobat 7.0\Reader\AcroRd32.exe', ('/n', '/s', 'user.pdf')) Does what I need and works great but I manualy searched around to find the path to AcroRd32.exe. Short of writting some code to scan any adobe dirs for this exe is there a more elegant way for me to ensure my app will work on any windows machine ? Any pointers would be greatly appreciated Dave From rdm at rcblue.com Thu Nov 30 21:49:42 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 30 Nov 2006 12:49:42 -0800 Subject: [Tutor] How to get Python to find tk/tcl? In-Reply-To: <456F34AE.8090606@tds.net> References: <7.0.1.0.2.20061130111820.05c4e2f0@rcblue.com> <456F34AE.8090606@tds.net> Message-ID: <7.0.1.0.2.20061130124716.062e3620@rcblue.com> At 11:44 AM 11/30/2006, you wrote: >Dick Moores wrote: > > I'd like to use TableListWrapper > > (). I ran it as > > TableList.py, and got this error: > > > > E:\Python25\dev\Tkinter>python TableList.py > > Traceback (most recent call last): > > File "TableList.py", line 1142, in > > tabletest() > > File "TableList.py", line 1061, in tabletest > > stretch = "all" > > File "TableList.py", line 50, in __init__ > > _loadtablelist(master) > > File "TableList.py", line 1039, in _loadtablelist > > parent.tk.call("package", "require", "tablelist") > > _tkinter.TclError: can't find package tablelist > > > > I have tcl in E:\Python25\tcl. It came with Python 2.5? Is the above > > error caused by Python not being able to find tk/pcl? If so, what do > > I do? And if not, what do I do? > >My guess is that you need the actual tcl tablelist widget from >http://www.nemethi.de/ stored somewhere where tcl will find it, maybe in >E:\Python25\tcl\tk8.4. Thanks, Kent. That did it. Dick From carroll at tjc.com Thu Nov 30 21:50:45 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 30 Nov 2006 12:50:45 -0800 (PST) Subject: [Tutor] finding AcroRd32.exe - a better way ? In-Reply-To: <200611302039.51237.pythontut@pusspaws.net> Message-ID: On Thu, 30 Nov 2006, Dave S wrote: > My app generates an on the fly PDF manual by using reportlab, once generated I > would like it to be automatically opened and displayed by XP adobe reader. > > Here's where I get stuck. ... > > os.execv('E:\Program Files\Adobe\Acrobat 7.0\Reader\AcroRd32.exe', > ('/n', '/s', 'user.pdf')) > > Does what I need and works great but I manualy searched around to find the > path to AcroRd32.exe. Short of writting some code to scan any adobe dirs for > this exe is there a more elegant way for me to ensure my app will work on any > windows machine ? try this: os.startfile('user.pdf') From pyro9219 at gmail.com Thu Nov 30 21:51:02 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 30 Nov 2006 12:51:02 -0800 Subject: [Tutor] Best Known Method for Filtering redundant list items. Message-ID: Anyone point me to something more efficient then for item in list1: if item not in list2: list2.append() This just seems to take a bit a time when there are thousands or dozens of thousands of records just to filter out the dozen or so copies.. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061130/f57489e4/attachment.html From rdm at rcblue.com Thu Nov 30 21:52:32 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 30 Nov 2006 12:52:32 -0800 Subject: [Tutor] Rounding a float to n significant digits In-Reply-To: <7.0.1.0.2.20061127231658.083d26f0@rcblue.com> References: <7.0.1.0.2.20061127231658.083d26f0@rcblue.com> Message-ID: <7.0.1.0.2.20061130113350.05e83588@rcblue.com> At 11:19 PM 11/27/2006, Dick Moores wrote: >I just dug this Tim Smith creation out of the Tutor archive. > >def round_to_n(x, n): > """ > Rounds float x to n significant digits, in scientific notation. > Written by Tim Peters. See his Tutor list post of 7/3/04 at > http://mail.python.org/pipermail/tutor/2004-July/030324.html > """ > if n < 1: > raise ValueError("number of significant digits must be >= 1") > return "%.*e" % (n-1, x) > >Thought others might find it of use. > >Dick Moores I've run into the limitation on the size of an int that can be converted to a float. Out of curiosity I've tried to close in on what that limit is: >>> round_to_n(2*10**308,4) Traceback (most recent call last): File "E:\Program Files\Wing IDE Personal 2.1\src\debug\server\_sandbox.py", line 1, in # Used internally for debug sandbox under external interpreter File "e:\Python25\Lib\site-packages\mine\mycalc.py", line 35, in round_to_n return "%.*e" % (n-1, x) TypeError: float argument required >>> round_to_n(1.75*10**308,4) '1.750e+308' >>> round_to_n(1.2*10**308,4) '1.200e+308' >>> round_to_n(1.87*10**308,4) '1.#IOe+000' >>> round_to_n(1.81*10**308,4) '1.#IOe+000' >>> round_to_n(1.78*10**308,4) '1.780e+308' So I've run across the curious '1.#IOe+000'. What is that? And what is the exact limit? I suppose it's some power of 2? But 2**1023 is too low; 2**1024 is too high; so is 2**1024-1. Dick Moores From alan.gauld at btinternet.com Thu Nov 30 21:57:12 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Nov 2006 20:57:12 -0000 Subject: [Tutor] Use Python to learn kids (9 yr) to program References: <456D8A4B.7040207@telia.com> <88302544606.20061129194755@columbus.rr.com> Message-ID: "R. Alan Monroe" wrote > http://davidbau.com/archives/2005/07/29/haaarg_world.html > Loved it Alan! Thanks for posting, I'd never have stumbled across that one. :-) Alan G. From python at venix.com Thu Nov 30 22:01:45 2006 From: python at venix.com (Python) Date: Thu, 30 Nov 2006 16:01:45 -0500 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: References: Message-ID: <1164920505.19530.699.camel@www.venix.com> On Thu, 2006-11-30 at 12:51 -0800, Chris Hengge wrote: > Anyone point me to something more efficient then > list2 = list(set(list1)) Older Pythons will force you to import sets and use sets.Set > for item in list1: > if item not in list2: > list2.append() > > This just seems to take a bit a time when there are thousands or > dozens of thousands of records just to filter out the dozen or so > copies.. > > Thanks. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From pythontut at pusspaws.net Thu Nov 30 22:03:05 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 30 Nov 2006 21:03:05 +0000 Subject: [Tutor] finding AcroRd32.exe - a better way ? In-Reply-To: References: Message-ID: <200611302103.05058.pythontut@pusspaws.net> On Thursday 30 November 2006 20:50, Terry Carroll wrote: > On Thu, 30 Nov 2006, Dave S wrote: > > My app generates an on the fly PDF manual by using reportlab, once > > generated I would like it to be automatically opened and displayed by XP > > adobe reader. > > > > Here's where I get stuck. ... > > > > os.execv('E:\Program Files\Adobe\Acrobat 7.0\Reader\AcroRd32.exe', > > ('/n', '/s', 'user.pdf')) > > > > Does what I need and works great but I manualy searched around to find > > the path to AcroRd32.exe. Short of writting some code to scan any adobe > > dirs for this exe is there a more elegant way for me to ensure my app > > will work on any windows machine ? > > try this: > > os.startfile('user.pdf') Neat, cool & 100% what I was looking for :):):) Cheers Dave PS I would offer to buy you a pint - but you probably don't live near Bedford England ! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From greenbergj at wit.edu Thu Nov 30 22:11:48 2006 From: greenbergj at wit.edu (Jordan Greenberg) Date: Thu, 30 Nov 2006 16:11:48 -0500 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: References: Message-ID: <456F4914.1020304@wit.edu> Chris Hengge wrote: > Anyone point me to something more efficient then > > for item in list1: > if item not in list2: > list2.append() > > This just seems to take a bit a time when there are thousands or dozens of > thousands of records just to filter out the dozen or so copies.. > > Thanks. somewhat unsurprisingly, the first thing google lists for "python list duplicates" is a quite good ASPN recipe to do just what you want. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 From pyro9219 at gmail.com Thu Nov 30 22:13:33 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 30 Nov 2006 13:13:33 -0800 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: <1164920505.19530.699.camel@www.venix.com> References: <1164920505.19530.699.camel@www.venix.com> Message-ID: Nice! Thank you. Curious as to why this happens though... >>> list1 = ['1','1','2','3','4'] >>> list2 = list(set(list1)) >>> list2 ['1', '3', '2', '4'] <-- here the order has changed. This doesn't matter for my program, its just for a script that takes excel columns and posts them into a given SQL db column... On 11/30/06, Python wrote: > > On Thu, 2006-11-30 at 12:51 -0800, Chris Hengge wrote: > > Anyone point me to something more efficient then > > > list2 = list(set(list1)) > > Older Pythons will force you to import sets and use sets.Set > > > for item in list1: > > if item not in list2: > > list2.append() > > > > This just seems to take a bit a time when there are thousands or > > dozens of thousands of records just to filter out the dozen or so > > copies.. > > > > Thanks. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061130/fe7ac3c4/attachment.htm From tomwebb at ctel.net Thu Nov 30 22:09:47 2006 From: tomwebb at ctel.net (TomW) Date: Thu, 30 Nov 2006 16:09:47 -0500 Subject: [Tutor] Use Python to learn kids (9 yr) to program In-Reply-To: <456D8A4B.7040207@telia.com> References: <456D8A4B.7040207@telia.com> Message-ID: <456F489B.1040508@ctel.net> Anders Persson wrote: > Hi! > > I have looked around for som language to use to learn my 9 year son > programming. > > There is a KPL - Kids Programming Language but my son diden't grasp the > OO, GUI and everyting around this, maby becurse English is not his spoken > language, and for a beginner i think the inviroment was to complex. > > So my plan is to use Python, has anyone try to learn kids this way, and > could > giv som ide how-to. > I witch way to introduce every part of the language,,, > > best regards > Anders > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Another interesting way to learn to program the OO way is a from Carnegie Mellon University at http://alice.org/. It is a graphical approach. I just stumbled upon this software last week. Tom From pyro9219 at gmail.com Thu Nov 30 22:22:02 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 30 Nov 2006 13:22:02 -0800 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: <1164921431.19530.705.camel@www.venix.com> References: <1164920505.19530.699.camel@www.venix.com> <1164921431.19530.705.camel@www.venix.com> Message-ID: No problem at all, as I said, this doesn't matter for my needs since I'm just posting values into a DB. Just curious why it jumbles it all up :) On 11/30/06, Lloyd Kvam wrote: > > There is a fly in the ointment that hit me after I sent the email. > Using set does not preserve the order. If you care about the order of > elements in list1, my suggestion will not work. > > > On Thu, 2006-11-30 at 16:01 -0500, Python wrote: > > On Thu, 2006-11-30 at 12:51 -0800, Chris Hengge wrote: > > > Anyone point me to something more efficient then > > > > > list2 = list(set(list1)) > > > > Older Pythons will force you to import sets and use sets.Set > > > > > for item in list1: > > > if item not in list2: > > > list2.append() > > > > > > This just seems to take a bit a time when there are thousands or > > > dozens of thousands of records just to filter out the dozen or so > > > copies.. > > > > > > Thanks. > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp. > 1 Court Street, Suite 378 > Lebanon, NH 03766-1358 > > voice: 603-653-8139 > fax: 320-210-3409 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061130/db3bdc23/attachment.html From python at venix.com Thu Nov 30 22:23:25 2006 From: python at venix.com (Python) Date: Thu, 30 Nov 2006 16:23:25 -0500 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: <1164920505.19530.699.camel@www.venix.com> References: <1164920505.19530.699.camel@www.venix.com> Message-ID: <1164921805.19530.709.camel@www.venix.com> Right after hitting send I realized I fail to preserver order. If preserving order is important, we're back to using more complex code. On Thu, 2006-11-30 at 16:01 -0500, Python wrote: > On Thu, 2006-11-30 at 12:51 -0800, Chris Hengge wrote: > > Anyone point me to something more efficient then > > > list2 = list(set(list1)) > > Older Pythons will force you to import sets and use sets.Set > > > for item in list1: > > if item not in list2: > > list2.append() > > > > This just seems to take a bit a time when there are thousands or > > dozens of thousands of records just to filter out the dozen or so > > copies.. > > > > Thanks. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From john at fouhy.net Thu Nov 30 22:56:19 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 1 Dec 2006 10:56:19 +1300 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: References: <1164920505.19530.699.camel@www.venix.com> Message-ID: <5e58f2e40611301356s21cf67devdcd3437065596c69@mail.gmail.com> On 01/12/06, Chris Hengge wrote: > Nice! Thank you. > > Curious as to why this happens though... > > >>> list1 = ['1','1','2','3','4'] > >>> list2 = list(set(list1)) > >>> list2 > ['1', '3', '2', '4'] <-- here the order has changed. For the same reason that dictionaries don't preserve order. Basically, sets are (I think) implemented using a hash table. You can read about hash tables on wikipedia (or many other places), but one of the components of a hash table is a function mapping keys to integers in a particular range. To produce an efficient hash table, you want this function to spread the input out evenly across the range, which means you want random behaviour. Hence you lose the order of strings :-) In fact, you can think of a set as a dictionary where the values are always True (or something), and you only care about the keys. eg: >>> import itertools >>> list1 = ['1', '1', '2', '3', '4'] >>> list2 = dict(zip(list1, itertools.repeat(True))).keys() >>> list2 ['1', '3', '2', '4'] -- John. From kmaheshw at science.uva.nl Thu Nov 30 22:53:15 2006 From: kmaheshw at science.uva.nl (Ketan Maheshwari) Date: Thu, 30 Nov 2006 22:53:15 +0100 Subject: [Tutor] how to save wxpython output Message-ID: <456F52CB.90807@science.uva.nl> Hi *: How do I save the output of a wxpython program as a jpg or png image from within the program? Thanks, k. From amadeo.bellotti at gmail.com Thu Nov 30 23:34:36 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 30 Nov 2006 17:34:36 -0500 Subject: [Tutor] OT What's next In-Reply-To: References: <163301647446.20061129193257@columbus.rr.com> Message-ID: thank you soo much Alan i have Sams teach yourself C in 21 days fr starters is that any good? On 11/30/06, Alan Gauld wrote: > > > "Amadeo Bellotti" wrote > > > step two sites to learn anyone know where i can look > > up c programming for linux? > > Ah! Now, if you'd said you were talking about a > Linux PC then there would be no question. C is > the only way to go. > > The Linux documentation project has loads of stuff about > programming for Linux, but you need to learn C first. > > My personal choices for books are: > 1) The original C Language book by Kernighan & Ritchie > One of the finest programming tutorials ever written, great > for core C but useless for the library functions. > 2) C The Complete Reference by Schildt. A very good tutorial > that also makes a good (albeit DOS oriented) reference manual. > > Online I haven't seen anything outstanding for C but > then I haven't really looked at beginners tutorials because I > could already program C before the web was invented! > > One thing - Don;t get sidetracked into C++. Its a whole > different ballgame, much more complex and unnecessary > if you want to go low level. > > HTH, > > Alan G. > > > > > > On 11/29/06, Terry Carroll wrote: > >> > >> On Wed, 29 Nov 2006, R. Alan Monroe wrote: > >> > >> > > Pure assembler on a PC involves a huge amount of work for even > >> > > the most trivial task. > >> > > >> > Some useful assembly tips here: > >> > http://www.grc.com/smgassembly.htm > >> > >> I never wanted to actually program assembly on the PC, but I did > >> want to > >> understand it (actually, I wanted to understand the Intel x86 > >> architecture, and there's no better way of doing that than learning > >> the > >> assembly language for a machine). I read Jeff Duntemann's > >> "Assembly > >> language Step-by-Step," http://duntemann.com/assembly.htm , and > >> found it > >> very useful, although I didn't actually try any programming. > >> > >> I'm an old mainframe assembler language hack from way back in the > >> IBM > >> System/370 days (although in my last development job, I wrote more > >> in > >> machine code than in actual assembler), so I didn't really need or > >> desire > >> to do the practical aspects of actually writing x86 code; but I > >> felt that > >> would have been a good book to get me there, had that been what I > >> wanted. > >> > >> A couple of years ago, I took a course in which I built a > >> rudimentary > >> computer around an Intel 8031 chip; and when I say "built," I mean > >> built. > >> It was a couple dozen components on a breadboard, with about only > >> about > >> 2Kbytes of memory, if I recall; I soldered or wire-wrapped every > >> connection. You really learn an architecture when you do that. > >> not that > >> I remember much of it anymore, two years later. Not a route I > >> recommend. > >> I needed a few credits to fill an obscure educational requirement, > >> though, > >> and this was a fun way to do it. > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > -------------------------------------------------------------------------------- > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061130/5f9504a1/attachment.htm From alan.gauld at btinternet.com Thu Nov 30 23:42:57 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Nov 2006 22:42:57 -0000 Subject: [Tutor] OT What's next References: <163301647446.20061129193257@columbus.rr.com> Message-ID: "Amadeo Bellotti" wrote > i have Sams teach yourself C in 21 days fr starters > is that any good? I haven't seen it but given you already know at least the basics of programming through Python I'm pretty sure it will be good enough to get you up and started in C. C is a very simple language with only about 20-3-0 reserved words. Like Python most of the power is in its library of functions. So learning the core language is easy, learning the functions can take a long time! But like Python you only need to learn as much as you need at any given time! Have fun, Alan G From wescpy at gmail.com Thu Nov 30 23:57:54 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 30 Nov 2006 14:57:54 -0800 Subject: [Tutor] Rounding a float to n significant digits In-Reply-To: <7.0.1.0.2.20061130113350.05e83588@rcblue.com> References: <7.0.1.0.2.20061127231658.083d26f0@rcblue.com> <7.0.1.0.2.20061130113350.05e83588@rcblue.com> Message-ID: <78b3a9580611301457oe052b75i8559a37b3d0d195@mail.gmail.com> i think on a 32-bit platform, C doubles (IEEE754) are limited to 10 ** 308.25 which is pretty close to 2 ** 1024 -wesley