From tim at johnsons-web.com Thu Dec 1 03:46:05 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 30 Nov 2005 17:46:05 -0900 Subject: [Tutor] Class Inheritance -> NameError Message-ID: <20051201024605.GD1806@johnsons-web.com> The following code snippet is meant to test inheritance: class test: def __init__(self,v): self.__val = v def val(self): print self.__val class sub(test): def __init__(self): val() The following console session has an error: >>> T = mylib.test('hello') >>> s = mylib.sub() Traceback (most recent call last): File "", line 1, in ? File "mylib.py", line 1612, in __init__ val() NameError: global name 'val' is not defined ## what do I need to do to make the 'test method visible ## class 'sub? thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From chris.arndt at web.de Thu Dec 1 04:09:55 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 01 Dec 2005 03:09:55 +0000 Subject: [Tutor] Class Inheritance -> NameError In-Reply-To: <20051201024605.GD1806@johnsons-web.com> References: <20051201024605.GD1806@johnsons-web.com> Message-ID: <438E6983.5030107@web.de> Tim Johnson schrieb: > The following code snippet is meant to test inheritance: > class test: > def __init__(self,v): > self.__val = v > def val(self): > print self.__val > class sub(test): > def __init__(self): > val() > The following console session has an error: > Beware test.__val is a 'private' attribute. See http://www.python.org/doc/current/tut/node11.html#SECTION0011600000000000000000 for an explanation. >>>>T = mylib.test('hello') >>>>s = mylib.sub() > > Traceback (most recent call last): > File "", line 1, in ? > File "mylib.py", line 1612, in __init__ > val() > NameError: global name 'val' is not defined > > ## what do I need to do to make the 'test method visible > ## class 'sub? Surely you mean the 'val' method (see the traceback)? it lives in the namespace of the class 'test'. So if you want to call it as a class method: >>> test.val(instance) if you want to call it as an instance method: >>> instance = sub() >>> instance.val() resp. in the class and sub-classes itself: >>> self.val() HTH, Chris From Liam.Clarke-Hutchinson at business.govt.nz Thu Dec 1 04:18:33 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Thu, 1 Dec 2005 16:18:33 +1300 Subject: [Tutor] Class Inheritance -> NameError Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B14F3@chbnt01.alpha.wd.govt.nz> Hi Tim, Either - class test: def __init__(self,v): self.__val = v def val(self): print self.__val class sub(test): def __init__(self, v): test.__init__(v) self.val() or - class sub(test): def __init__(self, v): test.__init__(v) test.val() That will resolve your calling the method problem, but self.__val won't inherit (I think). I don't recommend using double underscored variables unless there's a really good reason, C# et al be damned. Oh, and if self.__val / val is set by the superclasses __init__ method, then you'll need to call it specifically, or otherwise you'll get a UnboundLocalError, because self.__val/val won't exist. Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Tim Johnson Sent: Thursday, 1 December 2005 3:46 p.m. To: tutor at python.org Subject: [Tutor] Class Inheritance -> NameError The following code snippet is meant to test inheritance: class test: def __init__(self,v): self.__val = v def val(self): print self.__val class sub(test): def __init__(self): val() The following console session has an error: >>> T = mylib.test('hello') >>> s = mylib.sub() Traceback (most recent call last): File "", line 1, in ? File "mylib.py", line 1612, in __init__ val() NameError: global name 'val' is not defined ## what do I need to do to make the 'test method visible ## class 'sub? thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From tim at johnsons-web.com Thu Dec 1 04:56:32 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 30 Nov 2005 18:56:32 -0900 Subject: [Tutor] Class Inheritance -> NameError In-Reply-To: <438E6983.5030107@web.de> References: <20051201024605.GD1806@johnsons-web.com> <438E6983.5030107@web.de> Message-ID: <20051201035632.GE1806@johnsons-web.com> My thanks to Christopher and Liam. I've revisited this with the following: class test: def __init__(self): self.s = ' there' def val(self,V): print '%s%s' % (V,self.s) class sub(test): def __init__(self): pass The following console session: >>> T = mylib.test() >>> S = mylib.sub() >>> S.val('hello') Traceback (most recent call last): File "", line 1, in ? File "mylib.py", line 1609, in val print '%s%s' % (V,self.s) AttributeError: sub instance has no attribute 's' Removing references to self.s as in class test: def __init__(self): pass def val(self,V): print V class sub(test): def __init__(self): pass gives a console session without the AttributeError ---------------------------------------------------------- | Do I understand that classes inherit methods, but not | | variable attributes? | ---------------------------------------------------------- Thanks: I've use inherited classes before but haven't tried anything with variables. tim -- Tim Johnson http://www.alaska-internet-solutions.com From john at fouhy.net Thu Dec 1 05:11:12 2005 From: john at fouhy.net (John Fouhy) Date: Thu, 1 Dec 2005 17:11:12 +1300 Subject: [Tutor] Class Inheritance -> NameError In-Reply-To: <20051201035632.GE1806@johnsons-web.com> References: <20051201024605.GD1806@johnsons-web.com> <438E6983.5030107@web.de> <20051201035632.GE1806@johnsons-web.com> Message-ID: <5e58f2e40511302011w77c18709n@mail.gmail.com> On 01/12/05, Tim Johnson wrote: > My thanks to Christopher and Liam. I've revisited this > with the following: > class test: > def __init__(self): > self.s = ' there' > def val(self,V): > print '%s%s' % (V,self.s) > class sub(test): > def __init__(self): > pass > The following console session: > >>> T = mylib.test() > >>> S = mylib.sub() > >>> S.val('hello') > Traceback (most recent call last): > File "", line 1, in ? > File "mylib.py", line 1609, in val > print '%s%s' % (V,self.s) > AttributeError: sub instance has no attribute 's' Hi Tim, When you create an instance of a class, python calls the __init__ method of the class you just created, but it _doesn't_ call the __init__ method of any superclasses. There are several good reasons for this --- it doesn't know what parameters you want to pass to the superclass __init__ methods, or when you want to call them. So, it is up to you to make that call. You can do that like this: class sub(test): def __init__(self): test.__init__(self) Because self.s is only created in test.__init__, you have to call the __init__ method to get access to it. HTH! -- John. From tim at johnsons-web.com Thu Dec 1 05:48:53 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 30 Nov 2005 19:48:53 -0900 Subject: [Tutor] Class Inheritance -> NameError In-Reply-To: <5e58f2e40511302011w77c18709n@mail.gmail.com> References: <20051201024605.GD1806@johnsons-web.com> <438E6983.5030107@web.de> <20051201035632.GE1806@johnsons-web.com> <5e58f2e40511302011w77c18709n@mail.gmail.com> Message-ID: <20051201044853.GF1806@johnsons-web.com> * John Fouhy [051130 19:21]: <..snip...> > On 01/12/05, Tim Johnson wrote: > superclass __init__ methods, or when you want to call them. So, it is > up to you to make that call. > > You can do that like this: > > class sub(test): > def __init__(self): > test.__init__(self) > > Because self.s is only created in test.__init__, you have to call the > __init__ method to get access to it. > > HTH! :-) It does indeed! thanks everybody tim -- Tim Johnson http://www.alaska-internet-solutions.com From falcon3166 at hotmail.com Thu Dec 1 07:11:37 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 30 Nov 2005 23:11:37 -0700 Subject: [Tutor] How does pickle save files? Message-ID: Hey all, In what format does pickle save files as? I mean it is .txt, .dat, or some other way? Thanks Nathan Pinno, Owner/operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/ MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051130/209d6e18/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051130/209d6e18/attachment.gif From dyoo at hkn.eecs.berkeley.edu Thu Dec 1 08:19:48 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 30 Nov 2005 23:19:48 -0800 (PST) Subject: [Tutor] How does pickle save files? In-Reply-To: Message-ID: On Wed, 30 Nov 2005, Nathan Pinno wrote: > In what format does pickle save files as? I mean it is .txt, .dat, or > some other way? Hi Nathan, pickle actually has three formats: there's a textual format that looks weird, and two binary formats that looks even weirder. *grin* You should probably consider them all as ".dat", as the only consumer of pickles is supposed to be the pickle module: the output is not human-friendly. There's some introductory information on the three formats here: http://www.python.org/doc/lib/node64.html Protocol zero is textual, and the other two are binary. None of them are really meant to be read by humans, although Protocol 0's output is somewhat comprehendable by looking at it. ###### >>> pickle.dumps(['hello', ('world',)], protocol=0) "(lp0\nS'hello'\np1\na(S'world'\np2\ntp3\na." >>> print pickle.dumps(['hello', ('world',)], protocol=0) (lp0 S'hello' p1 a(S'world' p2 tp3 a. ###### Protocols one and two are less easy to read; we can't really print them out since they don't fit ASCII, although we can see their byte representation: ###### >>> pickle.dumps(['hello', ('world',)], protocol=1) ']q\x00(U\x05helloq\x01(U\x05worldq\x02tq\x03e.' >>> pickle.dumps(['hello', ('world',)], protocol=2) '\x80\x02]q\x00(U\x05helloq\x01U\x05worldq\x02\x85q\x03e.' ###### All three protocols can be inspected through the 'pickletools' module and its disassembly function 'dis()': http://www.python.org/doc/lib/module-pickletools.html We can learn about the gory details of pickle's format by studying the the source code in 'pickletools.py': http://svn.python.org/projects/python/trunk/Lib/pickletools.py That being said, pickle's format is a very low-level detail, and understanding it also requires a bit of knowledge on virtual machines; I'm not sure how well the details will make sense to you. You probably don't need to worry how Pickle writes its output unless you are very curious. Best of wishes to you! From ajikoe at gmail.com Thu Dec 1 10:06:30 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 1 Dec 2005 10:06:30 +0100 Subject: [Tutor] python swig problem Message-ID: Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c */ #include double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char *get_time() { time_t ltime; time(<ime); return ctime(<ime); } ------------------------- /* example.i */ %module example %{ /* Put header files here or function declarations like below */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); ------------------------------------------------------------ I write this in my dos console: swig -python example.i # this is ok bcc32 -c example.c example_wrap.c # this has error I found this error: Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland example.c: example_wrap.c: Warning W8004 example_wrap.c 428: 'uu' is assigned a value that is never used in function SWIG_UnpackData Warning W8004 example_wrap.c 669: 'flags' is assigned a value that is never used in function PySwigObject_print Error E2063 example_wrap.c 791: Illegal initialization in function PySwigObject_type Warning W8057 example_wrap.c 1660: Parameter 'self' is never used in function _wrap_fact Warning W8057 example_wrap.c 1688: Parameter 'self' is never used in function _wrap_my_mod Warning W8065 example_wrap.c 1696: Call to function 'get_time' with no prototype in function _wrap_get_time Warning W8057 example_wrap.c 1702: Parameter 'self' is never used in function _wrap_get_time Warning W8060 example_wrap.c 2106: Possibly incorrect assignment in function SWIG_Python_FixMethods *** 1 errors in Compile *** How can I solve the problem. Thanks in advance. pujo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051201/22134b6f/attachment-0001.html From python at kapitalisten.no Thu Dec 1 10:32:01 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Thu, 1 Dec 2005 10:32:01 +0100 (CET) Subject: [Tutor] Unicode trouble Message-ID: <10989.193.71.38.142.1133429521.squirrel@mail.sporck.net> Michael Lange wrote: >> I haven't read all of this thread, but maybe you are trying to pass a >> non-utf8 string to the utf8 codec? >Yes, I guess that much is pretty clear - there is some data in the source >file that is not valid utf-8. I tried the error='replace' as you suggested and the program made it thru the list. However, here are some results: the gjenoppl???et gjenoppl??? from the gjenoppl?st det gjenoppl?ste kan v??? konsentrert from kan v?re konsentrert I did check the site http://www.columbia.edu/kermit/utf8.html and the letters that is the problem here are a part of the utf-8. Is there anything else I could try? Thanks in advance -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Thu Dec 1 11:48:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 01 Dec 2005 05:48:53 -0500 Subject: [Tutor] Unicode trouble In-Reply-To: <10989.193.71.38.142.1133429521.squirrel@mail.sporck.net> References: <10989.193.71.38.142.1133429521.squirrel@mail.sporck.net> Message-ID: <438ED515.50206@tds.net> ?yvind wrote: > I tried the error='replace' as you suggested and the program made it thru > the list. However, here are some results: > > the gjenoppl???et gjenoppl??? > from > the gjenoppl?st det gjenoppl?ste > > kan v??? konsentrert > from > kan v?re konsentrert It seems pretty clear that you are using the wrong encoding somewhere. > > I did check the site http://www.columbia.edu/kermit/utf8.html and the > letters that is the problem here are a part of the utf-8. That doesn't mean anything. Pretty much every letter used in every natural language of the world is part of unicode, that's the point of it. utf-8 is just a way to encode unicode so it includes all unicode characters. The important question is, what is actual encoding of your source data? > > Is there anything else I could try? Understand why the above question is important, then answer it. Until you do you are just thrashing around in the dark. Do you know what a character encoding is? Do you understand the difference between utf-8 and latin-1? Kent -- http://www.kentsjohnson.com From kent37 at tds.net Thu Dec 1 12:08:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 01 Dec 2005 06:08:56 -0500 Subject: [Tutor] Beautiful Soup, inserting a node? In-Reply-To: References: Message-ID: <438ED9C8.2090005@tds.net> Bob Tanner wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Is there a way to insert a node with Beautiful Soup? BS doesn't really seem to be set up to support this. The Tags in a soup are kept in a linked list by their next attribute so you will have to find the right Tag, break the chain of 'next' and insert your new Tag. You will have to look at the source; start with the unknown_starttag() method. Good luck, Kent -- http://www.kentsjohnson.com From python at kapitalisten.no Thu Dec 1 12:25:11 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Thu, 1 Dec 2005 12:25:11 +0100 (CET) Subject: [Tutor] Unicode trouble Message-ID: <56319.193.71.38.142.1133436311.squirrel@mail.sporck.net> >The important question is, what is actual encoding of your source data? >> >> Is there anything else I could try? >Understand why the above question is important, then answer it. Until you do >you are just thrashing around in the dark. The source is a text-document that as far as I know only contains English and Norwegian letters. It can be opened with Notepad and Excel. I tried to run thru it in Python by: f = open('c://file.txt') for i in f: print f and that doesn't seem to give any problem. It prints all characters without any trouble. How would I find what encoding the document is in? All I can find is by opening Notepad, selecting Font/Script and it says 'Western'. Might the problem only be related to Win32com, not Python since Python prints it without trouble? >Do you know what a character encoding is? Do you understand the difference >between utf-8 and latin-1? Earlier characters had values 1-255. (Ascii). Now, you have a wider choice. In our part of the world we can use an extended version which contains a lot more, latin-1. UTF-8 is a part of Unicode and contains a lot more characters than Ascii. My knowledge about character encoding doesn't go much farther than this. Simply said, I understand that the document that I want to read includes characters beyond Ascii, and therefore I need to use UTF-8 or Latin-1. Why I should use one instead of the other, I have no idea. -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Thu Dec 1 14:29:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 01 Dec 2005 08:29:23 -0500 Subject: [Tutor] Unicode trouble In-Reply-To: <56319.193.71.38.142.1133436311.squirrel@mail.sporck.net> References: <56319.193.71.38.142.1133436311.squirrel@mail.sporck.net> Message-ID: <438EFAB3.8010609@tds.net> ?yvind wrote: >>The important question is, what is actual encoding of your source data? >> >>>Is there anything else I could try? > > >>Understand why the above question is important, then answer it. Until you > > do >you are just thrashing around in the dark. > > The source is a text-document that as far as I know only contains English > and Norwegian letters. It can be opened with Notepad and Excel. I tried to > run thru it in Python by: > > f = open('c://file.txt') > > for i in f: > print f > > and that doesn't seem to give any problem. It prints all characters > without any trouble. That doesn't narrow it down much though it does point towards latin-1 (or cp1252). > How would I find what encoding the document is in? All I can find is by > opening Notepad, selecting Font/Script and it says 'Western'. That doesn't really mean anything about the doc. Try opening the file in your browser. Most browsers have an encoding menu (View / Character Encoding in Firefox, View / Encoding in IE). Find the selection in this menu that makes the text display correctly; that's the encoding of the file. > Might the problem only be related to Win32com, not Python since Python > prints it without trouble? That's another issue. First you need to know what you are starting with. > >>Do you know what a character encoding is? Do you understand the difference >between utf-8 and latin-1? > > Earlier characters had values 1-255. (Ascii). Now, you have a wider > choice. In our part of the world we can use an extended version which > contains a lot more, latin-1. UTF-8 is a part of Unicode and contains a > lot more characters than Ascii. > > My knowledge about character encoding doesn't go much farther than this. > Simply said, I understand that the document that I want to read includes > characters beyond Ascii, and therefore I need to use UTF-8 or Latin-1. Why > I should use one instead of the other, I have no idea. You really should read this: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) http://www.joelonsoftware.com/articles/Unicode.html Kent -- http://www.kentsjohnson.com From paul.hendrick at gmail.com Thu Dec 1 22:24:16 2005 From: paul.hendrick at gmail.com (Paul Hendrick) Date: Thu, 01 Dec 2005 21:24:16 +0000 Subject: [Tutor] problem detecting files Message-ID: <1133472256.8527.6.camel@localhost.localdomain> Hi there, I've got a problem with getting the difference between 2 directories, but only recognising directories and not files. I'm trying to find directories in /home/svn that aren't in /usr/local/trac/projects. The list returned by listdir in /home/svn is: ['.bash_logout', '.bash_profile', '.bashrc', '.emacs', 'dir1', 'dir2'] the problem is I can't get the script to detect that .bash_profile and .emacs aren't directories, it always comes back in my list of directories. I'll include my code below - any help would be greatly appreciated. http://pastebin.ca/32033 Cheers, Paul From dyoo at hkn.eecs.berkeley.edu Fri Dec 2 00:43:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 1 Dec 2005 15:43:04 -0800 (PST) Subject: [Tutor] Scientific Notation + 18 Digit Pecision In-Reply-To: <000d01c5f5ca$48167f40$6401a8c0@hfsys3> Message-ID: > Methods for turning on true division? > > A. Install the new Python, when it is available. > > When will this be available? Hi Hubert, Not certain. It's not clear if this will be adopted as the default in the immediate future; you might not want to wait for this. > B. from__future__import division > > This will work properly in an IDLE Python Shell, if I type it in, but > not when it is present in .py modules. I see that it was read from the > .py file by the python shell, but the behaviour in the shell still is > not changed from integer division to normal division. (I put the > statement at the beginning of my .py modules.) That directive only affects its enclosing module --- it doesn't affect things globally. > C. -Qnew > > I did not understand how to get and install Qnew, so I searched on the > information below, and got a lot of results (1100), that confused me > further. I'm not on Windows, so I can't point out exactly what you'd need to change to make IDLE and Python use the -Qnew argument flag. > This approach might be the best, but before I consider it, I must get > the two affected fuunctions working. I saved the function modules that > you refactored for me, into separate files, but should probably put them > all into one file later. > > 1. Extract Equation > 2. EvaluateEquation > 3. PrintEquationAndValue > 4. DisplayPyFile > and my > 5. Calling Program Module > > When I ran the caling module, (and got the indentation right in the > function modues) all modules appeared to work except for the > PrintEquationAnd Value Function which gives a syntax error for "if > value:" with an arrow pointing to value. Next time, can you show us the exact error message? Please give verbatim error messages: they often help us figure out what exactly Python is having an issue with. > ############################################ > def PrintEquationAndValue(equation, value): > """Prints out the equation and its value.""" > if value: > name, assignment, comment = equation > print "%10s = %18.15e (%s)\t[%s]" % (name, value, assignment, comment) > else: > print "%s not defined. %s" % (name, assignment) > ############################################ The code you've sent us implies that the function body hasn't been indented properly. Can you check this? I see that you're bouncing between indenting a function body with one, two, or four spaces. I'd recommend to stick with four, for consistency's sake. Good luck! From dyoo at hkn.eecs.berkeley.edu Fri Dec 2 00:44:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 1 Dec 2005 15:44:15 -0800 (PST) Subject: [Tutor] FW: files - strings - lists (fwd) Message-ID: [Hi Paul; redirecting to tutor. Try reposting to tutor next time; we may need to see if there's some mailing list issue there.] ---------- Forwarded message ---------- Date: Thu, 1 Dec 2005 16:42:32 -0600 From: Paul McGuire To: smiles at worksmail.net, dyoo at hkn.eecs.berkeley.edu Subject: FW: [Tutor] files - strings - lists (Sorry for the direct e-mail, tutor-list rejected my post. -- Paul) -----Original Message----- From: Paul McGuire [mailto:paul at alanweberassociates.com] Sent: Thursday, December 01, 2005 11:07 AM To: 'tutor at python.org' Subject: [Tutor] files - strings - lists Chris, Danny, et al. - Sorry I didn't chime in earlier on this thread. Here is a pyparsing sample that goes beyond just tokenizing, and uses the structure of the input text to organize the tokens into records with named attributes. Enjoy! -- Paul # from earlier post data = """1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 """ from pyparsing import * real = Combine(Word(nums) + '.' + Word(nums)) integer = Combine(Optional("-") + Word(nums)) # while we're parsing, might as well convert # integer strings to ints def makeInt(st,loc,tokens): return int(tokens[0]) integer.setParseAction( makeInt ) # we could get tricky and force names to start # only with capitals, followed by all lower case, # but let's keep it simple name = Word(alphas) # "26 wrzesnia 2005" looks suspiciously date-like date = integer + name + integer header = Group( integer + restOfLine + LineEnd() + date + LineEnd() + integer + integer + integer + integer + integer + LineEnd() + integer + integer + integer ) dataline = Group(real + integer.setResultsName("start") + integer.setResultsName("end") + integer + LineEnd() ) entry = Group( name.setResultsName("fromName") + "-" + name.setResultsName("toName") + LineEnd() + integer.setResultsName("recnum") + LineEnd() + OneOrMore( dataline ).setResultsName("data") ) # define the overal grammar definition grammar = header.setResultsName("header") + \ ZeroOrMore(entry).setResultsName("records") # parse the input data string results = grammar.parseString( data ) # print how many records found print len(results.records) # iterate over the returned records, and access # named data fields like object attributes for rec in results.records: print rec.recnum, rec.fromName, "->", rec.toName for d in rec.data: print "-",d.start,d.end print """ Prints out: 2 1 Bohossian -> Kolinski - 9 13 - 2 4 - 10 8 - 8 6 2 Szadkowska -> Szczurek - 11 16 - 1 -4 - 3 -7 - 10 13 """ From chris.arndt at web.de Fri Dec 2 00:58:11 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 01 Dec 2005 23:58:11 +0000 Subject: [Tutor] problem detecting files In-Reply-To: <1133472256.8527.6.camel@localhost.localdomain> References: <1133472256.8527.6.camel@localhost.localdomain> Message-ID: <438F8E13.2020106@web.de> Paul Hendrick schrieb: > Hi there, > I've got a problem with getting the difference between 2 directories, > but only recognising directories and not files. > I'm trying to find directories in /home/svn that aren't > in /usr/local/trac/projects. > > The list returned by listdir in /home/svn is: > ['.bash_logout', '.bash_profile', '.bashrc', '.emacs', 'dir1', 'dir2'] > > the problem is I can't get the script to detect that .bash_profile > and .emacs aren't directories, it always comes back in my list of > directories. os.listdir() always returns a list of all files in a directory. If you want just the directories, you have to filter them out yourself: >>> from os.path import join, isdir >>> files = os.listdir('mydir') >>> dirs = [f for f in files if isdir(join('mydir', f))] Have you looked at the popular 'path' module (http://www.jorendorff.com/articles/python/path/)? It eases common tasks when handling filesystems very nicely. Chris From simplebob at gmail.com Fri Dec 2 01:47:57 2005 From: simplebob at gmail.com (Daniel McQuay) Date: Thu, 1 Dec 2005 19:47:57 -0500 Subject: [Tutor] problem with IDLE Message-ID: <6d87ecf40512011647s6ba89712yde9392f669012d4b@mail.gmail.com> Hello list, I just got a Windows box up and running. When I go to use IDLE I get an error saying something along the lines of, "IDLE was unable to start you may need to shut off the firewall". Now when I shut the firewall off it starts up fine. So my question is, does IDLE try to access a port? if so, what port? I would like to be able to make rule so that I can keep the firewall running and have no problem starting IDLE. Thank you in advance, -- Daniel McQuay 814.825.0847 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051201/8870f22d/attachment.html From Liam.Clarke-Hutchinson at business.govt.nz Fri Dec 2 01:50:44 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 2 Dec 2005 13:50:44 +1300 Subject: [Tutor] problem with IDLE Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1507@chbnt01.alpha.wd.govt.nz> IDLE uses localhost (a loopback port 127.0.0.1) to communicate with running scripts (so interrupt keys and debugging calls get passed etc.) It's a nice cross platform method of interprocess communication. So yeah, 127.0.0.1 is the one. Regards, Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Daniel McQuay Sent: Friday, 2 December 2005 1:48 p.m. To: Tutor at python.org Subject: [Tutor] problem with IDLE Hello list, I just got a Windows box up and running. When I go to use IDLE I get an error saying something along the lines of, "IDLE was unable to start you may need to shut off the firewall". Now when I shut the firewall off it starts up fine. So my question is, does IDLE try to access a port? if so, what port? I would like to be able to make rule so that I can keep the firewall running and have no problem starting IDLE. Thank you in advance, -- Daniel McQuay 814.825.0847 A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051202/5e137e59/attachment-0001.htm From simplebob at gmail.com Fri Dec 2 02:03:15 2005 From: simplebob at gmail.com (Daniel McQuay) Date: Thu, 1 Dec 2005 20:03:15 -0500 Subject: [Tutor] problem with IDLE In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1507@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1507@chbnt01.alpha.wd.govt.nz> Message-ID: <6d87ecf40512011703hef9ce54r21355248b51cac99@mail.gmail.com> Not to be sound ignorant, but what port on local host would that be? On 12/1/05, Liam Clarke-Hutchinson wrote: > > IDLE uses localhost (a loopback port 127.0.0.1) to communicate with > running scripts (so interrupt keys and debugging calls get passed etc.) It's > a nice cross platform method of interprocess communication. > > So yeah, 127.0.0.1 is the one. > > Regards, > > *Liam Clarke-Hutchinson*| Contact Centre Advisor|* Ministry of Economic > Development * > DDI +64 3 962 2639 | Fax +64 3 962 6220 > ***www.med.govt.nz*** **** > > -----Original Message----- > *From:* tutor-bounces at python.org [mailto:tutor-bounces at python.org] *On > Behalf Of *Daniel McQuay > *Sent:* Friday, 2 December 2005 1:48 p.m. > *To:* Tutor at python.org > *Subject:* [Tutor] problem with IDLE > > Hello list, > > I just got a Windows box up and running. When I go to use IDLE I get an > error saying something along the lines of, "IDLE was unable to start you may > need to shut off the firewall". Now when I shut the firewall off it starts > up fine. So my question is, does IDLE try to access a port? if so, what > port? I would like to be able to make rule so that I can keep the firewall > running and have no problem starting IDLE. > > Thank you in advance, > > -- > Daniel McQuay > 814.825.0847 > > > > *A new monthly electronic newsletter covering all aspects of MED's work is > now available. Subscribers can choose to receive news from any or all of > seven categories, free of charge: Growth and Innovation, Strategic > Directions, Energy and Resources, Business News, ICT, Consumer Issues and > Tourism. See **http://news.business.govt.nz* > * for more details.* > > ** > > > > > > govt.nz - connecting you to New Zealand central & > local government services > > ------------------------------ > Any opinions expressed in this message are not necessarily those of the > Ministry of Economic Development. This message and any files transmitted > with it are confidential and solely for the use of the intended recipient. > If you are not the intended recipient or the person responsible for delivery > to the intended recipient, be advised that you have received this message in > error and that any use is strictly prohibited. Please contact the sender and > delete the message and any attachment from your computer. > ------------------------------ > > -- Daniel McQuay 814.825.0847 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051201/63794d0b/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Dec 2 04:01:48 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 1 Dec 2005 19:01:48 -0800 (PST) Subject: [Tutor] problem with IDLE In-Reply-To: <6d87ecf40512011703hef9ce54r21355248b51cac99@mail.gmail.com> Message-ID: On Thu, 1 Dec 2005, Daniel McQuay wrote: > Not to be sound ignorant, but what port on local host would that be? Hi Daniel, I believe it's port 8833, at least according to the source code in: http://svn.python.org/projects/python/trunk/Lib/idlelib/PyShell.py One of the error methods has the content: ####################################################################### def display_port_binding_error(self): tkMessageBox.showerror( "Port Binding Error", "IDLE can't bind TCP/IP port 8833, which is necessary to " "communicate with its Python execution server. Either " "no networking is installed on this computer or another " "process (another IDLE?) is using the port. Run IDLE with the -n " "command line switch to start without a subprocess and refer to " "Help/IDLE Help 'Running without a subprocess' for further " "details.", ######################################################################## Hope this helps! From tanner at real-time.com Fri Dec 2 09:09:52 2005 From: tanner at real-time.com (Bob Tanner) Date: Fri, 02 Dec 2005 02:09:52 -0600 Subject: [Tutor] Beautiful Soup, inserting a node? References: <438ED9C8.2090005@tds.net> Message-ID: Kent Johnson wrote: >> Is there a way to insert a node with Beautiful Soup? > > BS doesn't really seem to be set up to support this. The Tags in a soup > are kept in a linked What would the appropriate technology to use? I tried the xml modules, but they fail on the parsing of the html. -- Bob Tanner | Phone : (952)943-8700 http://www.real-time.com, Minnesota, Linux | Fax : (952)943-8500 Key fingerprint = AB15 0BDF BCDE 4369 5B42 1973 7CF1 A709 2CC1 B288 From kent37 at tds.net Fri Dec 2 11:55:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 02 Dec 2005 05:55:23 -0500 Subject: [Tutor] Beautiful Soup, inserting a node? In-Reply-To: References: <438ED9C8.2090005@tds.net> Message-ID: <4390281B.5000601@tds.net> Bob Tanner wrote: > Kent Johnson wrote: > > >>>Is there a way to insert a node with Beautiful Soup? >> >>BS doesn't really seem to be set up to support this. The Tags in a soup >>are kept in a linked > > > What would the appropriate technology to use? Fredrik Lundh's elementtidy uses the Tidy library to read (and clean up) HTML into an ElementTree representation which you can then modify and write. Here is a recipe that claims to be useful for modifying HTML pages: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286269 These articles have more suggestions: http://www.xml.com/pub/a/2004/09/08/pyxml.html http://www.boddie.org.uk/python/HTML.html Note that any process you use to convert HTML to an XML representation and then write out will not in general preserve the exact text of the original HTML - it will convert it to XHTML. This may or may not be desirable. If exact fidelity to the original document is important probably the cookbook recipe is the only one of these that will work. Depending on what kind of modifications you are making a simple regex-based text processing approach might work also - don't parse the text as HTML, just look for the part you need to change and make the change directly. Kent -- http://www.kentsjohnson.com From lists at janeden.org Fri Dec 2 14:50:17 2005 From: lists at janeden.org (Jan Eden) Date: Fri, 2 Dec 2005 14:50:17 +0100 Subject: [Tutor] Malformed CSV Message-ID: Hi, I need to parse a CSV file using the csv module: "hotel","9,463","95","1.00" "hotels","7,033","73","1.04" "hotels hamburg","2,312","73","3.16" "hotel hamburg","2,708","42","1.55" "Hotels","2,854","41","1.44" "hotel berlin","2,614","31","1.19" The idea is to use each single keyword (field 1) as a dictionary key and sum up the clicks (field 2) and transactions (field 3): try: keywords[keyword]['clicks'] += clicks keywords[keyword]['transactions'] += transactions # if the keyword has not been found yet... except KeyError: keywords[keyword] = { 'clicks' : clicks, 'transactions' : transactions } Unfortunately, the quote characters are not properly escaped within fields: ""hotel,hamburg"","1","0","0" ""hotel,billig, in berlin tegel"","1","0","0" ""hotel+wien"","1","0","0" ""hotel+n?rnberg"","1","0","0" ""hotel+london"","1","0","0" ""hotel" "budapest" "billig"","1","0","0" which leads to the following output (example): hotel 9,463hamburg""billig 951 in berlin tegel"" As you can see, Python added 'hamburg""' and 'billig' to the first 'hotel' row's click value (9,463), and '1' as well as ' in berlin tegel' to the transactions (95). I am aware that I need to convert real clicks/transactions to integers before adding them, but I first wanted to sort out the parsing problem. Is there a way to deal with the incorrect quoting automatically? Thanks, Jan -- I was gratified to be able to answer promptly, and I did. I said I didn't know. - Mark Twain From kent37 at tds.net Fri Dec 2 15:29:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 02 Dec 2005 09:29:42 -0500 Subject: [Tutor] Malformed CSV In-Reply-To: References: Message-ID: <43905A56.80600@tds.net> Jan Eden wrote: > Hi, > > I need to parse a CSV file using the csv module: > > "hotel","9,463","95","1.00" > "hotels","7,033","73","1.04" > "hotels hamburg","2,312","73","3.16" > "hotel hamburg","2,708","42","1.55" > "Hotels","2,854","41","1.44" > "hotel berlin","2,614","31","1.19" > > Unfortunately, the quote characters are not properly escaped within fields: > > ""hotel,hamburg"","1","0","0" > ""hotel,billig, in berlin tegel"","1","0","0" > ""hotel+wien"","1","0","0" > ""hotel+n?rnberg"","1","0","0" > ""hotel+london"","1","0","0" > ""hotel" "budapest" "billig"","1","0","0" > > Is there a way to deal with the incorrect quoting automatically? I'm not entirely sure how you want to interpret the data above. One possibility is to just change the double "" to single " before processing with csv. For example: # data is the raw data from the whole file data = '''""hotel,hamburg"","1","0","0" ""hotel,billig, in berlin tegel"","1","0","0" ""hotel+wien"","1","0","0" ""hotel+nurnberg"","1","0","0" ""hotel+london"","1","0","0" ""hotel" "budapest" "billig"","1","0","0"''' data = data.replace('""', '"') data = data.splitlines() import csv for line in csv.reader(data): print line Output is ['hotel,hamburg', '1', '0', '0'] ['hotel,billig, in berlin tegel', '1', '0', '0'] ['hotel+wien', '1', '0', '0'] ['hotel+nurnberg', '1', '0', '0'] ['hotel+london', '1', '0', '0'] ['hotel "budapest" "billig"', '1', '0', '0'] which looks pretty reasonable except for the last line, and I don't really know what you would consider correct there. Kent -- http://www.kentsjohnson.com From lists at janeden.org Fri Dec 2 16:26:33 2005 From: lists at janeden.org (Jan Eden) Date: Fri, 2 Dec 2005 16:26:33 +0100 Subject: [Tutor] Malformed CSV In-Reply-To: <43905A56.80600@tds.net> Message-ID: Kent Johnson wrote on 02.12.2005: >I'm not entirely sure how you want to interpret the data above. One >possibility is to just change the double "" to single " before >processing with csv. For example: > ># data is the raw data from the whole file >data = '''""hotel,hamburg"","1","0","0" >""hotel,billig, in berlin tegel"","1","0","0" >""hotel+wien"","1","0","0" >""hotel+nurnberg"","1","0","0" >""hotel+london"","1","0","0" >""hotel" "budapest" "billig"","1","0","0"''' > >data = data.replace('""', '"') >data = data.splitlines() > >import csv > >for line in csv.reader(data): > print line > >Output is >['hotel,hamburg', '1', '0', '0'] >['hotel,billig, in berlin tegel', '1', '0', '0'] >['hotel+wien', '1', '0', '0'] >['hotel+nurnberg', '1', '0', '0'] >['hotel+london', '1', '0', '0'] >['hotel "budapest" "billig"', '1', '0', '0'] > >which looks pretty reasonable except for the last line, and I don't >really know what you would consider correct there. > Exactly, the last line is the problem. With correct (Excel-style) quoting, it would look like this """hotel"" ""budapest"" ""billig""","1","0","0" i.e. each quote within a field would be doubled, and the output would be ['"hotel" "budapest" "billig"', '1', '0', '0'] i.e. the quoting of the original search string "hotel" "budapest" "billig" would be preserved (and this is important). I guess I need to notify the engineer responsible for the CSV output and have the quoting corrected. Thanks, Jan -- Any sufficiently advanced technology is indistinguishable from a Perl script. - Programming Perl From kent37 at tds.net Fri Dec 2 16:46:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 02 Dec 2005 10:46:11 -0500 Subject: [Tutor] Malformed CSV In-Reply-To: References: Message-ID: <43906C43.70307@tds.net> Jan Eden wrote: > I guess I need to notify the engineer responsible for the CSV output > and have the quoting corrected. If that is possible it is a much better solution. I hate to hack around bad data - much better to correct the source of the data if possible. In fact you may have little choice if you want to use the CSV module - for example what if the first field has commas and quotes? Could you have a line like this? ""hotel", "budapest", "billig"","1","0","0" Alternately you could just write your own parser, if the data is very regular this may not be hard: for line in data.splitlines(): fields = line.rsplit(',', 3) fields = [ field[1:-1] for field in fields ] print fields BTW do you really have doubled quotes in all the hotel fields, or just the one with quotes? The data in your original post is inconsistent. Kent -- http://www.kentsjohnson.com From lists at janeden.org Fri Dec 2 16:55:58 2005 From: lists at janeden.org (Jan Eden) Date: Fri, 2 Dec 2005 16:55:58 +0100 Subject: [Tutor] Malformed CSV In-Reply-To: <43906C43.70307@tds.net> Message-ID: Kent Johnson wrote on 02.12.2005: >Jan Eden wrote: >>I guess I need to notify the engineer responsible for the CSV >>output and have the quoting corrected. > >If that is possible it is a much better solution. I hate to hack >around bad data - much better to correct the source of the data if >possible. > Right. >In fact you may have little choice if you want to use the CSV module >- for example what if the first field has commas and quotes? Could >you have a line like this? ""hotel", "budapest", >"billig"","1","0","0" [...] > >BTW do you really have doubled quotes in all the hotel fields, or >just the one with quotes? The data in your original post is >inconsistent. > Yes, and that's the source of my problem: The data is based on user input to Google, which tends to be extremely inconsistent. Users seem to use any kind of absurd quoting, like hotel" "miami" "miami","hotel Thanks again, Jan -- Life's unfair - but root password helps! From kent37 at tds.net Fri Dec 2 16:59:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 02 Dec 2005 10:59:20 -0500 Subject: [Tutor] Beautiful Soup, inserting a node? In-Reply-To: References: <438ED9C8.2090005@tds.net> Message-ID: <43906F58.5030606@tds.net> Bob Tanner wrote: > Kent Johnson wrote: > > >>>Is there a way to insert a node with Beautiful Soup? >> >>BS doesn't really seem to be set up to support this. The Tags in a soup >>are kept in a linked > > > What would the appropriate technology to use? You might also email the author of BS and see if he has a suggestion. Kent -- http://www.kentsjohnson.com From din22 at earthlink.net Fri Dec 2 18:51:33 2005 From: din22 at earthlink.net (david) Date: Fri, 2 Dec 2005 11:51:33 -0600 Subject: [Tutor] my text adventure Message-ID: <000601c5f769$09020040$0201a8c0@d71bh5mhis9p7o> i am attempting to write a dig function that will create rooms. i have succeeded only in getting a headache :) any suggestions on where i am going wrong would be super helpful. thanks, david world = {} class Room: def __init__(self,name,coords): self.contents = [] self.name = name self.coords = coords world[tuple(coords)] = self def nextdoor(self,direction): if direction == 'n': nextdoor = (self.coords[0], self.coords[1] + 1) print nextdoor elif direction == 's': nextdoor = (self.coords[0], self.coords[1] - 1) print nextdoor elif direction == 'e': nextdoor = (self.coords[0] +1, self.coords[1]) print nextdoor elif direction == 'w': nextdoor = (self.coords[0] -1, self.coords[1]) print nextdoor def dig(self,direction): target = self.nextdoor(direction) print target if world.has_key(target): print 'already a room there' else: print "someday we'll make a room here" world[target]=Room('newroom',target) room1 = Room('startroom',[0,0]) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051202/70d44d5d/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Dec 2 22:23:32 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 2 Dec 2005 13:23:32 -0800 (PST) Subject: [Tutor] my text adventure In-Reply-To: <000601c5f769$09020040$0201a8c0@d71bh5mhis9p7o> Message-ID: > i am attempting to write a dig function that will create rooms. > i have succeeded only in getting a headache :) > any suggestions on where i am going wrong would > be super helpful. Hi David, You may want to write a unit test to make sure that all the methods of your class are doing the right thing. The issue with programs is that, when something goes wrong, any component might be responsible: unit tests allow us to get more confidence that all components are working. (And actually, they is something wrong with one of your helper functions; that's why I'm encouraging writing the proper test cases. *grin*) Here's one that will help point out a problem: #################################################### import unittest class TestRoom(unittest.TestCase): def testNorthFromOrigin(self): room1 = Room('startroom',[0,0]) self.assertEqual([0, 1], room1.nextdoor('n')) def testSouthFromOrigin(self): room1 = Room('startroom',[0,0]) self.assertEqual([0, -1], room1.nextdoor('s')) def testEastFromOrigin(self): room1 = Room('startroom',[0,0]) self.assertEqual([1, 0], room1.nextdoor('e')) def testWestFromOrigin(self): room1 = Room('startroom',[0,0]) self.assertEqual([-1, 0], room1.nextdoor('w')) if __name__ == '__main__': unittest.main() #################################################### Do these tests make sense? It's just making sure that nextdoor is doing something reasonable and returning the proper coordinates that we expect. Try testing your code, and you should see something. For a more comprehensive example of unit testing, you might want to look at: http://diveintopython.org/unit_testing/ which has a good long-running example of Python's unittest module. Hope this helps! From narm at go.com.jo Fri Dec 2 22:53:41 2005 From: narm at go.com.jo (Basem Narmok) Date: Fri, 02 Dec 2005 23:53:41 +0200 Subject: [Tutor] Request For Suggestions Message-ID: <4390C265.1040202@go.com.jo> Hi all, I am planning to make a Python CD for advocating Python, and I need your suggestions about this, the objective is to build a CD that contains the basic material for Python beginner (e.g. Python 2.4.2 for different platforms) with some advocating material (e.g. videos), and here is what comes to my mind to present on the CD: Software: - Python 2.4.2 for different platforms. - ironPython 0.9.5 - wxPython 2.6 - SPE 0.7.5 Media: - Introducing Python (video) - TurboGears (videos) - ironPython (videos) - maybe some video from URU and CIV IV games The CD is intended to be given to Python beginners in a free course, any comments or suggestions are welcome. Thanks Basem From falcon3166 at hotmail.com Fri Dec 2 23:20:43 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 2 Dec 2005 15:20:43 -0700 Subject: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? In-Reply-To: Message-ID: I like the Toolkit, is there anywhere where there is a how to use it? Thanks, Nathan Pinno, Co-owner/co-operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/ MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 _____ From: Adam [mailto:adam.jtm30 at gmail.com] Sent: November 28, 2005 3:44 PM To: Nathan Pinno Cc: Albertito Troiano; Tutor Mailing List Subject: Re: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? Hello Nathan, glad to see you're still working on this. I don't think I can improve on Danny's info on the GUI but I'll add this. You might want to try the Python Cryptography Toolkit to encrypt the password files and maybe encrypting the file as a binary pickle will add a little bit more security too. One last thing, I think you might want to use "a" here def save_file(pw): store = open('passcard.txt',"w") so that new username/passwords are appended to the file rather than overwriting any previous ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051202/1e4f92d7/attachment.htm From SNelson at midwaygames.com Fri Dec 2 23:20:55 2005 From: SNelson at midwaygames.com (Nelson, Scott) Date: Fri, 2 Dec 2005 16:20:55 -0600 Subject: [Tutor] Request For Suggestions Message-ID: <64F7B8E2954C73499806C1E59A848C1D078448C3@CHICAGO-EX1.chicago.midway.com> You could include the Pygame module. If this CD is for beginners, nothing like writing a game to provide a little bit of motivation! Plus, Pygame provides a lot of multimedia features all in one place (graphics, sound, keyboard, mouse, joystick, CD, mixer) http://www.pygame.org/ I'm sure everyone could suggest their favorite module be included, but Pygame might be the kind of thing that would catch some beginner's fancy. How many of us wrote a game as one of our first programs? :) -Scott -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Basem Narmok Sent: Friday, December 02, 2005 3:54 PM To: tutor at python.org Subject: [Tutor] Request For Suggestions Hi all, I am planning to make a Python CD for advocating Python, and I need your suggestions about this, the objective is to build a CD that contains the basic material for Python beginner (e.g. Python 2.4.2 for different platforms) with some advocating material (e.g. videos), and here is what comes to my mind to present on the CD: Software: - Python 2.4.2 for different platforms. - ironPython 0.9.5 - wxPython 2.6 - SPE 0.7.5 Media: - Introducing Python (video) - TurboGears (videos) - ironPython (videos) - maybe some video from URU and CIV IV games The CD is intended to be given to Python beginners in a free course, any comments or suggestions are welcome. Thanks Basem From narm at go.com.jo Fri Dec 2 23:25:35 2005 From: narm at go.com.jo (Basem Narmok) Date: Sat, 03 Dec 2005 00:25:35 +0200 Subject: [Tutor] Request For Suggestions In-Reply-To: References: <4390C265.1040202@go.com.jo> Message-ID: <4390C9DF.9070203@go.com.jo> Murtog wrote: >PyGame and videos about it would be good too. > > cool I will do it :) >2005/12/2, Basem Narmok : > > >>Hi all, >> >>I am planning to make a Python CD for advocating Python, and I need your >>suggestions about this, the objective is to build a CD that contains the >>basic material for Python beginner (e.g. Python 2.4.2 for different >>platforms) with some advocating material (e.g. videos), and here is what >>comes to my mind to present on the CD: >> >>Software: >>- Python 2.4.2 for different platforms. >>- ironPython 0.9.5 >>- wxPython 2.6 >>- SPE 0.7.5 >> >>Media: >>- Introducing Python (video) >>- TurboGears (videos) >>- ironPython (videos) >>- maybe some video from URU and CIV IV games >> >>The CD is intended to be given to Python beginners in a free course, any >>comments or suggestions are welcome. >> >>Thanks >>Basem >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > >-- >Abra??o, >Murtog [ http://murtog.blogspot.com ] > > From falcon3166 at hotmail.com Sat Dec 3 00:10:15 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 2 Dec 2005 16:10:15 -0700 Subject: [Tutor] Does anyone have any experience with ezPyCrypto? Message-ID: Does anyone have any experience with ezPyCrypto? If so, can you please tell me whether or not I can use it to encrypt dictionaries (i.e. user:password or site:username password for examples)? Thanks, Nathan Pinno, Co-owner/co-operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/ MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051202/45ecb6ea/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051202/45ecb6ea/attachment.gif From chris.arndt at web.de Sat Dec 3 00:51:09 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Fri, 02 Dec 2005 23:51:09 +0000 Subject: [Tutor] Request For Suggestions In-Reply-To: <4390C265.1040202@go.com.jo> References: <4390C265.1040202@go.com.jo> Message-ID: <4390DDED.6040701@web.de> Basem Narmok schrieb: > Hi all, > > I am planning to make a Python CD for advocating Python, and I need your > suggestions about this, the objective is to build a CD that contains the > basic material for Python beginner (e.g. Python 2.4.2 for different > platforms) with some advocating material (e.g. videos), and here is what > comes to my mind to present on the CD: > > Software: > - Python 2.4.2 for different platforms. > - ironPython 0.9.5 > - wxPython 2.6 > - SPE 0.7.5 > > Media: > - Introducing Python (video) > - TurboGears (videos) > - ironPython (videos) > - maybe some video from URU and CIV IV games > > The CD is intended to be given to Python beginners in a free course, any > comments or suggestions are welcome. Great idea! Here some brainstorming: Documentation, documentation, documentation! For example: - Official Python docs - List of beginners tutorials from the wiki, possible with copies of these on the CD - Dive into Python - How to think like a computer scientist - ... - Quick Reference Guides - Coding Style guide - The Zen of Python (import this) (maybe as a nicely formatted HTML page) Of course, you have to check licences of these. Would be cool to include a PDF with a nice cover for the CD, so people can distribute new copies. - Cool Python graphics (I have a PDF with a trainspotting-look-alike ad, but I don't know where I got it from) - Interviews with the BDFL (might be a bit of work to get the permissions for these) - A page with testimonials (Google, IL&M, whatever) - Flying Circus scripts ;-) Chris From lordvader at gmail.com Sat Dec 3 01:58:26 2005 From: lordvader at gmail.com (Fred Lionetti) Date: Fri, 2 Dec 2005 16:58:26 -0800 Subject: [Tutor] tkFileDialog bug on windows Message-ID: <434140620512021658h52dffb0drcbf739c9e120120b@mail.gmail.com> Hi everyone, I may have found a strange bug with tkFileDialog, and I'm wondering if anyone has a workaround for the problem. It happens when you have a button (or any other clickable widget) directly behind the askopenfilename dialog box and double click on a file. The button (behind the open file dialog) gets clicked, when it shouldn't. It occurs with the code below (but only under windows). ---------------------------------- from Tkinter import * import tkFileDialog def cmd(): print "button was pressed" parent = Tk() Button(parent, text = "hello", command = cmd, width=30, height = 10).pack() tkFileDialog.askopenfilename(parent=parent, title = "Double click on a file with the 'hello' button directly behind") parent.mainloop() --------------------------------- Any ideas? Thanks! Fred From dyoo at hkn.eecs.berkeley.edu Sat Dec 3 02:41:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 2 Dec 2005 17:41:22 -0800 (PST) Subject: [Tutor] Request For Suggestions In-Reply-To: <4390DDED.6040701@web.de> Message-ID: > > I am planning to make a Python CD for advocating Python, and I need > > your suggestions about this, the objective is to build a CD that > > contains the basic material for Python beginner (e.g. Python 2.4.2 for > > different platforms) with some advocating material (e.g. videos), and > > here is what comes to my mind to present on the CD: Hi Basem, You might also want to give a ping out to the folks on the edu-sig list and see what ideas they have. My memory is rusty, but I remember that the educators there had some ideas a while back about their own CD distribution of beginner Python resources. They might be able to give you a few more pointers. 'edu-sig' can be found on: http://mail.python.org/mailman/listinfo/edu-sig Good luck! From din22 at earthlink.net Sat Dec 3 04:42:00 2005 From: din22 at earthlink.net (david) Date: Fri, 2 Dec 2005 21:42:00 -0600 Subject: [Tutor] my text adventure Message-ID: <000c01c5f7bb$84ddca80$0201a8c0@d71bh5mhis9p7o> well i have got some things to work, thanks for the help. at this point i am just making things worse so thats it for tonight. any comments, suggestions, bug fixes, improvements, or ideas on how my program can add to the quality of all our lives are, as always, most greatly appreciated. import sys import string world = {} class Room: def __init__(self,coords): self.contents = [] self.name = '' self.coords = coords world[tuple(coords)] = self self.exits = {} def nextdoor(self,direction): if direction == 'n': nextdoor = (self.coords[0], self.coords[1] + 1) return list(nextdoor) elif direction == 's': nextdoor = list((self.coords[0], self.coords[1] - 1)) return nextdoor elif direction == 'e': nextdoor = list((self.coords[0] +1, self.coords[1])) return nextdoor elif direction == 'w': nextdoor = (self.coords[0] -1, self.coords[1]) return list(nextdoor) class Player: def __init__(self,name): self.name = name self.location = None self.inventory = [] self.wielded = None def look(self): print self.location.name def move(self,direction): if self.location.exits.has_key(direction): self.location = self.location.exits[direction] def wield(self,what): self.wielded = what def wear(self,what): pass def take(self,what): pass def drop(self,what): pass def dig(self,direction): target = tuple(self.location.nextdoor(direction)) print target if self.location.exits.has_key(target): print 'there is already an exit to that room' elif world.has_key(target): print 'already a room there, attempt to make exits' self.location.exits[direction] = Room(target) else: world[target]=Room(target) self.location.exits[direction] = Room(target) def do(self): cmd = string.split(raw_input('>')) verb = cmd[0] if len(cmd) > 1: target = cmd[1] if verb == 'l': self.look() elif verb in ['n','s','e','w']: self.move(cmd) elif verb == 'quit': sys.exit() elif verb == 'i': for a in self.inventory: print a.name elif verb == 'dig': self.dig(target) else: print 'what?' class Thing: def __init__(self,name): self.name = name p = Player('david') room1 = Room([0,0]) room1.name = 'startroom' p.location = room1 sword = Thing('sword') hat = Thing('hat') p.inventory.append(sword) p.inventory.append(hat) while 1: p.do() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051202/3624af3b/attachment.html From din22 at earthlink.net Sat Dec 3 05:20:34 2005 From: din22 at earthlink.net (david) Date: Fri, 2 Dec 2005 22:20:34 -0600 Subject: [Tutor] spam, eggs, and my text adventure Message-ID: <001c01c5f7c0$e80d62a0$0201a8c0@d71bh5mhis9p7o> hello :) i have some questions that are more about programming in general than python specifically. suppose, for whatever reason, you had a burning desire to write a simple text adventure. how would you start? would you just start writing some code? i knew i wanted a room structure or object and that i wanted to be able to create the rooms from within the game. so i thought i will keep track of rooms in a dictionary and use xy coordinates as keys and rooms as values. and rooms can keep track of their exits in a dictionary too. then all i would have to do is write some code to create rooms and move through them. anyway i am stuck so please find a question in there somewhere. hello :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051202/2952a065/attachment.htm From ismaelgf at adinet.com.uy Sat Dec 3 16:01:15 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sat, 03 Dec 2005 13:01:15 -0200 Subject: [Tutor] Request For Suggestions In-Reply-To: <4390C265.1040202@go.com.jo> References: <4390C265.1040202@go.com.jo> Message-ID: <4391B33B.2090502@adinet.com.uy> Basem Narmok wrote: >Hi all, > >I am planning to make a Python CD for advocating Python, and I need your >suggestions about this, the objective is to build a CD that contains the >basic material for Python beginner (e.g. Python 2.4.2 for different >platforms) with some advocating material (e.g. videos), and here is what >comes to my mind to present on the CD: > >Software: >- Python 2.4.2 for different platforms. >- ironPython 0.9.5 >- wxPython 2.6 >- SPE 0.7.5 > > SPE is now at 0.8.0 You should include some tutorials, too. Perhaps the modules noted on UsefulModules could be included, too? (With their respective docs/tutorials) http://wiki.python.org/moin/UsefulModules Take a look at the edu-sig page, too: http://www.python.org/sigs/edu-sig/ HTH Ismael From klappnase at freenet.de Sat Dec 3 23:19:38 2005 From: klappnase at freenet.de (Michael Lange) Date: Sat, 3 Dec 2005 23:19:38 +0100 Subject: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? In-Reply-To: References: Message-ID: <20051203231938.3fd24676.klappnase@freenet.de> On Fri, 2 Dec 2005 15:20:43 -0700 "Nathan Pinno" wrote: > I like the Toolkit, is there anywhere where there is a how to use it? > A good place to look for Tkinter resources is the wiki: There is a number of links to Tkinter documentation there: And still the best resource on Tkinter programming is John Grayson's "Python and Tkinter programming": Regards Michael From klappnase at freenet.de Sat Dec 3 23:34:01 2005 From: klappnase at freenet.de (Michael Lange) Date: Sat, 3 Dec 2005 23:34:01 +0100 Subject: [Tutor] tkFileDialog bug on windows In-Reply-To: <434140620512021658h52dffb0drcbf739c9e120120b@mail.gmail.com> References: <434140620512021658h52dffb0drcbf739c9e120120b@mail.gmail.com> Message-ID: <20051203233401.68c743ff.klappnase@freenet.de> On Fri, 2 Dec 2005 16:58:26 -0800 Fred Lionetti wrote: > Hi everyone, > > I may have found a strange bug with tkFileDialog, and I'm wondering if > anyone has a workaround for the problem. It happens when you have a > button (or any other clickable widget) directly behind the > askopenfilename dialog box and double click on a file. The button > (behind the open file dialog) gets clicked, when it shouldn't. It > occurs with the code below (but only under windows). > > ---------------------------------- > from Tkinter import * > import tkFileDialog > > def cmd(): > print "button was pressed" > > parent = Tk() > Button(parent, text = "hello", command = cmd, width=30, height = 10).pack() > tkFileDialog.askopenfilename(parent=parent, title = "Double click on a > file with the 'hello' button directly behind") > > parent.mainloop() > --------------------------------- Hi Fred, I don't have a windows box here to try it, so I can just guess. On my linux box the list in the dialog responds to ButtonRelease events, but I think on windows tk uses native dialogs, and maybe these respond to ButtonPress events; if this is the case, it may happen that the ButtonRelease occurs *after* the dialog window has been destroyed, so the event gets delivered to the button in the parent window. Regards Michael From srini_iyyer_bio at yahoo.com Sun Dec 4 00:55:03 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Sat, 3 Dec 2005 15:55:03 -0800 (PST) Subject: [Tutor] Printing regular expression match In-Reply-To: <4391B33B.2090502@adinet.com.uy> Message-ID: <20051203235503.99251.qmail@web31615.mail.mud.yahoo.com> Dear group, I have two lists: >>> a ['apple', 'boy', 'boy', 'apple'] >>> b ['Apple', 'BOY', 'APPLE-231'] >>> for i in a: pat = re.compile(i,re.IGNORECASE) for m in b: if pat.match(m): print m Apple APPLE-231 BOY BOY Apple APPLE-231 >>> Here I tried to match element in list a to element in list b and asked to ignore the case. It did work. However, I do not know how to make it print only m What I want : Apple BOY APPLE-231 I do not want python to print both elenents from lists a and b. I just want only the elements in the list B. how can i do that.. Please help me. thank you. srini __________________________________________ Yahoo! DSL ? Something to write home about. Just $16.99/mo. or less. dsl.yahoo.com From dndfan at hotpop.com Sun Dec 4 01:28:39 2005 From: dndfan at hotpop.com (Vlad Popescu) Date: Sun, 04 Dec 2005 02:28:39 +0200 Subject: [Tutor] Command line arguments passing Message-ID: <1133656119.2498.7.camel@localhost.localdomain> Hi there, everyone; first time poster! Sorry if this isn't very closely related to Python, but I have encountered the issue while trying to learn Python, so I guess I can just ask here. My question is: when invoking a program with, let's say, a filename containing spaces as a parameter: myprog -file "Long name" What does sys.argv hold in this case? I am specifically interested in whether argv[2]=="\"Long" or argv[2]=="Long name", that is, if the shell does the processing or I need to do it in the program. Also, I need to know if most environments do the same (I wouldn't want to be caught pants down while porting this to Windows). Many thanks in advance for your valuable suggestions and apologies if I have misposted, Vlad From chris.arndt at web.de Sun Dec 4 01:44:27 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Sun, 04 Dec 2005 00:44:27 +0000 Subject: [Tutor] Command line arguments passing In-Reply-To: <1133656119.2498.7.camel@localhost.localdomain> References: <1133656119.2498.7.camel@localhost.localdomain> Message-ID: <43923BEB.7030806@web.de> Vlad Popescu schrieb: > Hi there, everyone; first time poster! Sorry if this isn't very closely > related to Python, but I have encountered the issue while trying to > learn Python, so I guess I can just ask here. > > My question is: when invoking a program with, let's say, a filename > containing spaces as a parameter: > > myprog -file "Long name" > > What does sys.argv hold in this case? I am specifically interested in > whether argv[2]=="\"Long" or argv[2]=="Long name", Why don't you just try it out? $ python - -f "Long file" Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.argv[1] -f >>> print sys.argv[2] ... I think you can do the rest. Chris From dyoo at hkn.eecs.berkeley.edu Sun Dec 4 01:51:00 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 3 Dec 2005 16:51:00 -0800 (PST) Subject: [Tutor] Printing regular expression match In-Reply-To: <20051203235503.99251.qmail@web31615.mail.mud.yahoo.com> Message-ID: On Sat, 3 Dec 2005, Srinivas Iyyer wrote: > >>> a > ['apple', 'boy', 'boy', 'apple'] > > >>> b > ['Apple', 'BOY', 'APPLE-231'] > > >>> for i in a: > pat = re.compile(i,re.IGNORECASE) > for m in b: > if pat.match(m): > print m Hi Srinivas, We may want to change the problem so that it's less focused on "print"ing results directly. We can rephrase the question as a list "filtering" operation: we want to keep the elements of b that satisfy a certain criteron. Let's give a name to that criterion now: ###### def doesNameMatchSomePrefix(word, prefixes): """Returns True if the input word is matched by some prefix in the input list of prefixes. Otherwise, returns False.""" # ... fill me in ###### Can you write doesNameMatchSomePrefix()? In fact, you might not even need regexes to write an initial version of it. If you can write that function, then what you're asking: > I do not want python to print both elenents from lists a and b. I just > want only the elements in the list B. should not be so difficult: it'll be a straightforward loop across b, using that helper function. (Optimization can be done to make doesNameMatchSomePrefix() fast, but you probably should concentrate on correctness first. If you're interested in doing something like this for a large number of prefixes, you might be interested in: http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ which has more details and references to specialized modules that attack the problem you've shown us so far.) Good luck! From dyoo at hkn.eecs.berkeley.edu Sun Dec 4 02:23:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 3 Dec 2005 17:23:37 -0800 (PST) Subject: [Tutor] Command line arguments passing In-Reply-To: <43923BEB.7030806@web.de> Message-ID: > > My question is: when invoking a program with, let's say, a filename > > containing spaces as a parameter: > > > > myprog -file "Long name" > > > > What does sys.argv hold in this case? I am specifically interested in > > whether argv[2]=="\"Long" or argv[2]=="Long name", Hi Vlad, What you're asking is a platform-specific thing. I believe it should do what you're expecting --- "Long name" should be a pulled together as a single argument in sys.argv. But it's not Python that's pulling "Long name" together: it's your operating system's command line shell that's doing this. For example, on Windows, the following pages: http://www.microsoft.com/technet/community/columns/scripts/sg0704.mspx http://www.microsoft.com/technet/archive/winntas/deploy/shellscr.mspx talk about how Windows does command line argument parsing. (Search those pages for the word "quote", and you'll see a mention of this.) And the details on the role of quoting arguments is simliar for Unix shells like 'bash' or 'tcsh'. For example, for the bash shell: http://www.gnu.org/software/bash/manual/bashref.html#SEC8 So all Python knows is that it's getting an array of strings: it doesn't even see the original line that the user typed at the command line prompt; it instead gets something that has already been partially digested by your command line shell. Hope this helps! From srini_iyyer_bio at yahoo.com Sun Dec 4 02:28:23 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Sat, 3 Dec 2005 17:28:23 -0800 (PST) Subject: [Tutor] Printing regular expression match In-Reply-To: Message-ID: <20051204012823.95495.qmail@web31611.mail.mud.yahoo.com> Hi Danny, thanks for your email. In the example I've shown, there are no odd elements except for character case. In the real case I have a list of 100 gene names for Humans. The human gene names are conventioanlly represented in higher cases (eg.DDX3X). However, NCBI's gene_info dataset the gene names are reported in lowercase (eg. ddx3x). I want to extract the rest of the information for DDX3X that I have from NCBI's file (given that dataset is in tab delim format). my approach was if i can define DDX3X is identical ddx3x then I want to print that line from the other list (NCBI's gene_info dataset). I guess, I understood your suggestion wrongly. In such case, why do I have to drop something from list b (which is over 150 K lines). If I can create a sublist of all elements in b (a small list of 100) then it is more easy. this is my opinion. -srini --- Danny Yoo wrote: > > > On Sat, 3 Dec 2005, Srinivas Iyyer wrote: > > >>> a > > ['apple', 'boy', 'boy', 'apple'] > > > > >>> b > > ['Apple', 'BOY', 'APPLE-231'] > > > > >>> for i in a: > > pat = re.compile(i,re.IGNORECASE) > > for m in b: > > if pat.match(m): > > print m > > > Hi Srinivas, > > We may want to change the problem so that it's less > focused on "print"ing > results directly. We can rephrase the question as a > list "filtering" > operation: we want to keep the elements of b that > satisfy a certain > criteron. > > > Let's give a name to that criterion now: > > ###### > def doesNameMatchSomePrefix(word, prefixes): > """Returns True if the input word is matched by > some prefix in > the input list of prefixes. Otherwise, returns > False.""" > # ... fill me in > > ###### > > > Can you write doesNameMatchSomePrefix()? In fact, > you might not even need > regexes to write an initial version of it. > > > > If you can write that function, then what you're > asking: > > > I do not want python to print both elenents from > lists a and b. I just > > want only the elements in the list B. > > should not be so difficult: it'll be a > straightforward loop across b, > using that helper function. > > > > (Optimization can be done to make > doesNameMatchSomePrefix() fast, but you > probably should concentrate on correctness first. > If you're interested in > doing something like this for a large number of > prefixes, you might be > interested in: > > > http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ > > which has more details and references to specialized > modules that attack > the problem you've shown us so far.) > > > Good luck! > > __________________________________________ Yahoo! DSL ? Something to write home about. Just $16.99/mo. or less. dsl.yahoo.com From din22 at earthlink.net Sun Dec 4 03:36:10 2005 From: din22 at earthlink.net (david) Date: Sat, 3 Dec 2005 20:36:10 -0600 Subject: [Tutor] (no subject) Message-ID: <000601c5f87b$7d660130$0201a8c0@d71bh5mhis9p7o> hello again. i think my dig function is working correctly now. any input on how to save and restore all the rooms and descriptions? thanks for helping. import sys import string world = {} class Room: def __init__(self,coords): self.contents = [] self.description = '' self.coords = coords world[tuple(coords)] = self self.exits = {} def nextdoor(self,direction): if direction == 'n': nextdoor = (self.coords[0], self.coords[1] + 1) return list(nextdoor) elif direction == 's': nextdoor = list((self.coords[0], self.coords[1] - 1)) return nextdoor elif direction == 'e': nextdoor = list((self.coords[0] +1, self.coords[1])) return nextdoor elif direction == 'w': nextdoor = (self.coords[0] -1, self.coords[1]) return list(nextdoor) class Player: def __init__(self,name): self.name = name self.location = None self.inventory = [] self.wielded = None def look(self): print self.location.coords print self.location.description def move(self,direction): type(direction) if self.location.exits.has_key(direction): self.location = self.location.exits[direction] else: print 'alas, you cannot go that way' def wield(self,what): self.wielded = what def wear(self,what): pass def take(self,what): pass def drop(self,what): pass def dig(self,direction): target = tuple(self.location.nextdoor(direction)) print target if self.location.exits.has_key(target): print 'there is already an exit to that room' elif world.has_key(target): print 'already a room there, attempt to make exits' self.location.exits[direction] = Room(target) world[target].exits[opdir(direction)] = self.location else: world[target]=Room(target) self.location.exits[direction] = Room(target) world[target].exits[opdir(direction)] = self.location def describeroom(self): self.location.description = raw_input('>>') def do(self): cmd = string.split(raw_input('>')) verb = cmd[0] if len(cmd) > 1: target = cmd[1] if verb == 'l': self.look() elif verb in ['n','s','e','w']: self.move(verb) elif verb == 'quit': sys.exit() elif verb == 'i': for a in self.inventory: print a.name elif verb == 'dig': self.dig(target) elif verb == 'dr': self.describeroom() else: print 'what?' class Thing: def __init__(self,name): self.name = name def opdir(direction): if direction == 'n': return 's' if direction == 's': return 'n' if direction == 'e': return 'w' if direction == 'w': return 'e' p = Player('david') room1 = Room([0,0]) p.location = room1 sword = Thing('sword') hat = Thing('hat') p.inventory.append(sword) p.inventory.append(hat) while 1: p.do() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051203/34f0f2c9/attachment.htm From din22 at earthlink.net Sun Dec 4 03:40:05 2005 From: din22 at earthlink.net (david) Date: Sat, 3 Dec 2005 20:40:05 -0600 Subject: [Tutor] my text adventure References: <000601c5f87b$7d660130$0201a8c0@d71bh5mhis9p7o> Message-ID: <001201c5f87c$09330960$0201a8c0@d71bh5mhis9p7o> sorry i forgot a subject line. i have looked at the pickle module and was able to pickle world. but i can't figure how to restore everything. ----- Original Message ----- From: david To: tutor at python.org Sent: Saturday, December 03, 2005 8:36 PM Subject: [Tutor] (no subject) hello again. i think my dig function is working correctly now. any input on how to save and restore all the rooms and descriptions? thanks for helping. import sys import string world = {} class Room: def __init__(self,coords): self.contents = [] self.description = '' self.coords = coords world[tuple(coords)] = self self.exits = {} def nextdoor(self,direction): if direction == 'n': nextdoor = (self.coords[0], self.coords[1] + 1) return list(nextdoor) elif direction == 's': nextdoor = list((self.coords[0], self.coords[1] - 1)) return nextdoor elif direction == 'e': nextdoor = list((self.coords[0] +1, self.coords[1])) return nextdoor elif direction == 'w': nextdoor = (self.coords[0] -1, self.coords[1]) return list(nextdoor) class Player: def __init__(self,name): self.name = name self.location = None self.inventory = [] self.wielded = None def look(self): print self.location.coords print self.location.description def move(self,direction): type(direction) if self.location.exits.has_key(direction): self.location = self.location.exits[direction] else: print 'alas, you cannot go that way' def wield(self,what): self.wielded = what def wear(self,what): pass def take(self,what): pass def drop(self,what): pass def dig(self,direction): target = tuple(self.location.nextdoor(direction)) print target if self.location.exits.has_key(target): print 'there is already an exit to that room' elif world.has_key(target): print 'already a room there, attempt to make exits' self.location.exits[direction] = Room(target) world[target].exits[opdir(direction)] = self.location else: world[target]=Room(target) self.location.exits[direction] = Room(target) world[target].exits[opdir(direction)] = self.location def describeroom(self): self.location.description = raw_input('>>') def do(self): cmd = string.split(raw_input('>')) verb = cmd[0] if len(cmd) > 1: target = cmd[1] if verb == 'l': self.look() elif verb in ['n','s','e','w']: self.move(verb) elif verb == 'quit': sys.exit() elif verb == 'i': for a in self.inventory: print a.name elif verb == 'dig': self.dig(target) elif verb == 'dr': self.describeroom() else: print 'what?' class Thing: def __init__(self,name): self.name = name def opdir(direction): if direction == 'n': return 's' if direction == 's': return 'n' if direction == 'e': return 'w' if direction == 'w': return 'e' p = Player('david') room1 = Room([0,0]) p.location = room1 sword = Thing('sword') hat = Thing('hat') p.inventory.append(sword) p.inventory.append(hat) while 1: p.do() ------------------------------------------------------------------------------ _______________________________________________ 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/20051203/c55777e9/attachment.html From dan at tangledhelix.com Sun Dec 4 08:24:26 2005 From: dan at tangledhelix.com (Dan Lowe) Date: Sun, 4 Dec 2005 02:24:26 -0500 Subject: [Tutor] my text adventure In-Reply-To: <001201c5f87c$09330960$0201a8c0@d71bh5mhis9p7o> References: <000601c5f87b$7d660130$0201a8c0@d71bh5mhis9p7o> <001201c5f87c$09330960$0201a8c0@d71bh5mhis9p7o> Message-ID: On Dec 3, 2005, at 9:40 PM, david wrote: > sorry i forgot a subject line. i have looked at the pickle module > and was able to pickle world. > but i can't figure how to restore everything. import pickle def save_game(state, filename): file = open(filename, 'w') pickle.dump(state, file) file.close() def load_game(filename): file = open(filename, 'r') state = pickle.load(file) file.close() return state save_game(world, 'mygame') world = load_game('mygame') -- logic (n.): the art of being wrong with confidence. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051204/a3075ed0/attachment.htm From ml.cyresse at gmail.com Sun Dec 4 09:44:50 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 4 Dec 2005 21:44:50 +1300 Subject: [Tutor] Search theory for luddites? Message-ID: Hi all, Going to build a repository for my code snippets (and I know that pre-existing solutions exist, but I like to roll my own to see what I can learn.), and just wondering on how to best store it and search it. My current planned approach is to have each file added read and keywords extracted (i.e. variable names, libraries imported etc.) and used as keys in a dictionary, and each key points to a list of files containing it (files will be stored in a zip or similar). i.e. words = { "imaplib": ["X.py"], "smtplib": ["X.py", "Y.py"] } And if I do a search for "smtplib" or "imaplib" it'll return X.py first, as it contains both, and Y.py second. Is there a more efficient approach? I don't think a relational DB really suits this sort of task at present, but I'm wondering about search times. I've googled for search theory, and hit c2's wiki up, but I'm having no luck at finding applicable, understandable theory... a lot of stuff about trees and nodes and paths through graphs, but I can't correlate that to my problem. (I can see how graph pathfinding could relat e to routing a connection over a network, though.) Can anyone recommend a good introduction to the theory of searching? I really need to take some Computer Science courses. Regards, Liam Clarke From alan.gauld at freenet.co.uk Sun Dec 4 10:00:13 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 4 Dec 2005 09:00:13 -0000 Subject: [Tutor] Command line arguments passing References: <1133656119.2498.7.camel@localhost.localdomain> Message-ID: <00c101c5f8b1$23af5480$0a01a8c0@xp> > My question is: when invoking a program with, let's say, a filename > containing spaces as a parameter: > > myprog -file "Long name" > > What does sys.argv hold in this case? What did you get when you tried it? I ran: #######test.py ###### import sys print sys.argv ################### python test.py foo "long name" bar and got ['testargv.py', 'foo', 'long name', 'bar'] What did you get? Since its much less typing to try it than to ask the question I assume you must have had a problem with it? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld and got I am specifically interested in > whether argv[2]=="\"Long" or argv[2]=="Long name", that is, if the shell > does the processing or I need to do it in the program. Also, I need to > know if most environments do the same (I wouldn't want to be caught > pants down while porting this to Windows). > > Many thanks in advance for your valuable suggestions and apologies if I > have misposted, > > Vlad > > > > From dndfan at hotpop.com Sun Dec 4 11:04:00 2005 From: dndfan at hotpop.com (Vlad Popescu) Date: Sun, 04 Dec 2005 12:04:00 +0200 Subject: [Tutor] Command line arguments passing In-Reply-To: References: Message-ID: <1133690641.2500.3.camel@localhost.localdomain> On Sat, 2005-12-03 at 17:23 -0800, Danny Yoo wrote: > > > > My question is: when invoking a program with, let's say, a filename > > > containing spaces as a parameter: > > > > > > myprog -file "Long name" > > > > > > What does sys.argv hold in this case? I am specifically interested in > > > whether argv[2]=="\"Long" or argv[2]=="Long name", > > > Hi Vlad, > > What you're asking is a platform-specific thing. I believe it should do > what you're expecting --- "Long name" should be a pulled together as a > single argument in sys.argv. But it's not Python that's pulling "Long > name" together: it's your operating system's command line shell that's > doing this. > > For example, on Windows, the following pages: > > http://www.microsoft.com/technet/community/columns/scripts/sg0704.mspx > http://www.microsoft.com/technet/archive/winntas/deploy/shellscr.mspx > > talk about how Windows does command line argument parsing. (Search those > pages for the word "quote", and you'll see a mention of this.) And the > details on the role of quoting arguments is simliar for Unix shells like > 'bash' or 'tcsh'. For example, for the bash shell: > > http://www.gnu.org/software/bash/manual/bashref.html#SEC8 > > > So all Python knows is that it's getting an array of strings: it doesn't > even see the original line that the user typed at the command line prompt; > it instead gets something that has already been partially digested by your > command line shell. > > > Hope this helps! > Thanks, that's what I was looking for -- a multiplatform reference, since I can't test scripts on Windows just yet. From alan.gauld at freenet.co.uk Sun Dec 4 11:05:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 4 Dec 2005 10:05:22 -0000 Subject: [Tutor] Search theory for luddites? References: Message-ID: <00db01c5f8ba$3d648310$0a01a8c0@xp> > Is there a more efficient approach? I don't think a relational DB > really suits this sort of task at present, Why not? If its a big data set then a proper database will be more effective. The advantages are that you can define many more parameters for searching - author, date, number of accesses, version, etc Also it allows easy use of wildcards and ranges in your searches. And search times will be more close to constant for large volumes. It will also make generating stats for your own use easier. If you keep the structure simple and only store paths/filenames rather than trying to store the files then a relational database seems perfectly reasonable. Another approach to consider would be an LDAP Directory, but I'd go with a database for this one if volumes are to grow to more than a few hundred items. Alan G From dndfan at hotpop.com Sun Dec 4 11:08:34 2005 From: dndfan at hotpop.com (Vlad Popescu) Date: Sun, 04 Dec 2005 12:08:34 +0200 Subject: [Tutor] Command line arguments passing In-Reply-To: <00c101c5f8b1$23af5480$0a01a8c0@xp> References: <1133656119.2498.7.camel@localhost.localdomain> <00c101c5f8b1$23af5480$0a01a8c0@xp> Message-ID: <1133690914.2500.6.camel@localhost.localdomain> I don't have Python on Windows and didn't want to make any assumptions about the way the Windows shell passes parameters. Sorry again for being trivial. On Sun, 2005-12-04 at 09:00 +0000, Alan Gauld wrote: > > My question is: when invoking a program with, let's say, a filename > > containing spaces as a parameter: > > > > myprog -file "Long name" > > > > What does sys.argv hold in this case? > > What did you get when you tried it? > > I ran: > > #######test.py ###### > import sys > print sys.argv > > ################### > > python test.py foo "long name" bar > > and got > ['testargv.py', 'foo', 'long name', 'bar'] > > What did you get? Since its much less typing to try it than to ask > the question I assume you must have had a problem with it? > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > and got > > I am specifically interested in > > whether argv[2]=="\"Long" or argv[2]=="Long name", that is, if the shell > > does the processing or I need to do it in the program. Also, I need to > > know if most environments do the same (I wouldn't want to be caught > > pants down while porting this to Windows). > > > > Many thanks in advance for your valuable suggestions and apologies if I > > have misposted, > > > > Vlad > > > > > > > > From python at kapitalisten.no Sun Dec 4 13:15:58 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Sun, 4 Dec 2005 13:15:58 +0100 (CET) Subject: [Tutor] Unicode trouble Message-ID: <3130.193.71.156.231.1133698558.squirrel@mail.sporck.net> >> Might the problem only be related to Win32com, not Python since Python >> prints it without trouble? >That's another issue. First you need to know what you are starting with. >You really should read this: >The Absolute Minimum Every Software Developer Absolutely, Positively Must >Know About Unicode and Character Sets (No Excuses!) >http://www.joelonsoftware.com/articles/Unicode.html >Kent Thanks a lot for your help. I did actually get it to work. It didn't have to do with the characters, but the flags that I set for Word. But, I did learn a few things about characters in the process as well.... -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From din22 at earthlink.net Sun Dec 4 14:28:36 2005 From: din22 at earthlink.net (david) Date: Sun, 4 Dec 2005 07:28:36 -0600 Subject: [Tutor] my text adventure References: <000601c5f87b$7d660130$0201a8c0@d71bh5mhis9p7o> <001201c5f87c$09330960$0201a8c0@d71bh5mhis9p7o> Message-ID: <001b01c5f8d6$a1e11620$0201a8c0@d71bh5mhis9p7o> thanks. i had actually coded this almost exactly the same. i'll try to make my questions more specific. i am able to pickle and restore world. which is a dictionary of coordinates : room objects. when i look at the savefile that pickle generates i can see all my descriptions and exits. however when i reload my world gets back all the rooms that were created with dig. but the rooms don't have their exits or descriptions. is pickle the right tool for this? can i pickle.dump more than one thing to the same savefile? or how could i go about creating a structure that holds room, coords, descriptions and exits? and then pickle and unpickle that. or would it be better to write my own functions to write everything to a file and not use pickle at all? eventually my program will have many more things to keep track of and i am thinking that the saving and restoring of a programs state (is that correct usage?) could be important in many different programs. ----- Original Message ----- From: Dan Lowe To: david Cc: tutor at python.org Sent: Sunday, December 04, 2005 1:24 AM Subject: Re: [Tutor] my text adventure On Dec 3, 2005, at 9:40 PM, david wrote: sorry i forgot a subject line. i have looked at the pickle module and was able to pickle world. but i can't figure how to restore everything. import pickle def save_game(state, filename): file = open(filename, 'w') pickle.dump(state, file) file.close() def load_game(filename): file = open(filename, 'r') state = pickle.load(file) file.close() return state save_game(world, 'mygame') world = load_game('mygame') -- logic (n.): the art of being wrong with confidence. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051204/683cfbf2/attachment.htm From kent37 at tds.net Sun Dec 4 15:07:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 04 Dec 2005 09:07:49 -0500 Subject: [Tutor] spam, eggs, and my text adventure In-Reply-To: <001c01c5f7c0$e80d62a0$0201a8c0@d71bh5mhis9p7o> References: <001c01c5f7c0$e80d62a0$0201a8c0@d71bh5mhis9p7o> Message-ID: <4392F835.1030203@tds.net> david wrote: > hello :) > i have some questions that are more about programming in general than > python specifically. > suppose, for whatever reason, you had a burning desire to write a > simple text adventure. > how would you start? would you just start writing some code? Alan G and I had a brief discussion about this recently - see the thread that starts here: http://mail.python.org/pipermail/tutor/2005-November/043602.html > i knew i wanted a room structure or object and that i wanted to be > able to create the rooms > from within the game. so i thought i will keep track of rooms in a > dictionary and use xy coordinates > as keys and rooms as values. and rooms can keep track of their exits > in a dictionary too. > then all i would have to do is write some code to create rooms and > move through them. > anyway i am stuck so please find a question in there somewhere. So actually you didn't just start writing code, you thought about the objects and data structures you might need to use to solve the problem before you started writing code. That's pretty much what I do too. For simple scripts incremental development can work well - just write a little code, run it to see if it works, repeat. This works well if - running the script provides immediate feedback so you know whether it is working or not (this is not true of your adventure game) - the script is not likely to get big enough to require significant refactoring (reorganization) in its lifetime (this is hard to know when you start but generally it applies to one-off scripts and very simple utilities) For any other kind of program, I find a test-driven approach works very well, especially when I don't have a good understanding of the problem or how to solve it. I think of a small part of the problem that I understand, write a test for the code that will solve it, and run the test. Of course the test fails, I haven't written the code yet! So I write the code to make the test pass. Frequently reassess whether the code I have written is the best code I could write to solve the problem *as I currently understand it* as expressed in the current tests. Repeat until done. James Shore recently described this process well in his blog: http://www.jamesshore.com/Blog/Red-Green-Refactor.html (though I think Michael Feather's guidelines are too strict) By the way, for anyone reading who hasn't tried TDD (test-driven development), I really recommend you do. For me it was a profound shift to a way of working that is productive and satisfying. The constant feedback of working tests is a clear indication that I have accomplished something. At the end of a coding session I have great confidence that I have created working code - I have tested every part of it many times. At the end of a project, when I deliver to QA, I have great confidence that I have created working code - I have tested every part of it many times! And it's fun - the constant feedback of "yes, it works...yes, it works" is like having someone constantly saying, "that's good". Being able to refactor without fear is priceless. Until I tried TDD I didn't realize how much I was programming in fear of breaking something. Without automated tests, it is easy to break something. Whenever I wanted to refactor something I had to weigh the benefits of the refactoring against the chance of breaking something. Now I just make the change and run the tests to see if I broke anything, then go and fix it. Uncle Bob Martin has a great article that describes some of the benefits: http://www.butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd Kent From din22 at earthlink.net Sun Dec 4 17:06:09 2005 From: din22 at earthlink.net (david) Date: Sun, 4 Dec 2005 10:06:09 -0600 Subject: [Tutor] (no subject) Message-ID: <000601c5f8ec$a482c110$0201a8c0@d71bh5mhis9p7o> i added a list of rooms and rooms.append(self) to the Room initialization. then i run my program and create one room. there should now be two rooms. when i look at rooms i have three rooms! where did this other room come from? anyway, thanks for taking time to look at my code. import sys import string import pickle import os.path world = {} rooms = [] class Room: def __init__(self,coords): self.contents = [] self.description = '' self.coords = coords world[tuple(coords)] = self rooms.append(self) self.exits = {} def nextdoor(self,direction): if direction == 'n': nextdoor = (self.coords[0], self.coords[1] + 1) return list(nextdoor) elif direction == 's': nextdoor = list((self.coords[0], self.coords[1] - 1)) return nextdoor elif direction == 'e': nextdoor = list((self.coords[0] +1, self.coords[1])) return nextdoor elif direction == 'w': nextdoor = (self.coords[0] -1, self.coords[1]) return list(nextdoor) class Player: def __init__(self,name): self.name = name self.location = None self.inventory = [] self.wielded = None def look(self): print self.location.coords print self.location.description def move(self,direction): type(direction) if self.location.exits.has_key(direction): self.location = self.location.exits[direction] else: print 'alas, you cannot go that way' def wield(self,what): self.wielded = what def wear(self,what): pass def take(self,what): pass def drop(self,what): pass def dig(self,direction): target = tuple(self.location.nextdoor(direction)) print target if self.location.exits.has_key(target): print 'there is already an exit to that room' elif world.has_key(target): print 'already a room there, attempt to make exits' self.location.exits[direction] = Room(target) world[target].exits[opdir(direction)] = self.location else: world[target]=Room(target) self.location.exits[direction] = Room(target) world[target].exits[opdir(direction)] = self.location def describeroom(self): self.location.description = raw_input('>>') def save(self): f = open('savefile', 'w') pickle.dump(world,f) f.close() def do(self): cmd = string.split(raw_input('>')) verb = cmd[0] if len(cmd) > 1: target = cmd[1] if verb == 'l': self.look() elif verb in ['n','s','e','w']: self.move(verb) elif verb == 'quit': sys.exit() elif verb == 'i': for a in self.inventory: print a.name elif verb == 'dig': self.dig(target) elif verb == 'dr': self.describeroom() elif verb == 'save': self.save() else: print 'what?' class Thing: def __init__(self,name): self.name = name def opdir(direction): if direction == 'n': return 's' if direction == 's': return 'n' if direction == 'e': return 'w' if direction == 'w': return 'e' p = Player('david') room1 = Room([0,0]) p.location = room1 sword = Thing('sword') hat = Thing('hat') p.inventory.append(sword) p.inventory.append(hat) if os.path.isfile('savefile'): f = open('savefile','r') world = pickle.load(f) f.close() while 1: p.do() else: while 1: p.do() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051204/084b70c1/attachment-0001.htm From python at kapitalisten.no Sun Dec 4 17:19:55 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Sun, 4 Dec 2005 17:19:55 +0100 (CET) Subject: [Tutor] Socket connection Message-ID: <3619.193.71.156.231.1133713195.squirrel@mail.sporck.net> Hello. I need to get some whois-info from whois.ripe.net. I have been able to connect and get the info that I need, but I would like to know what is the most 'polite' way of doing so. I need to do quite a few whois lookups (from my server logs) and don't want to risk creating more hassle for their server than necessary. So, what I would like to know, is what is the best way of doing lots of requests? This works like a dream: >>> from socket import * >>> import socket >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.connect(('whois.ripe.net', 43)) >>> s.send("%s \n\n" % 'vg.no') 14 >>> data = s.recv(8196) But if I thereafter do this: >>> s.send("%s \n\n" % 'dagbladet.no') 11 >>> data = s.recv(8196) Traceback (most recent call last): File "", line 1, in ? error: (10053, 'Software caused connection abort') It doesn't go quite as well. I saw on http://www.amk.ca/python/howto/sockets/ that the socket is supposed to get destroyed after one use. But, if I try to connect again: >>> s.connect(('whois.ripe.net', 43)) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in connect error: (10056, 'Socket is already connected') It is already connected. So it seems like I have to start again at the beginning: >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.connect(('whois.ripe.net', 43)) ...... But, I have 300 requests. Should I do this 300 times? And thereafter end with: >>> s.shutdown(1) >>> s.close() Or should I do this each time? Or is there some other way to keep it open so that I can ask 300 times? Thanks in advance -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From din22 at earthlink.net Sun Dec 4 18:15:22 2005 From: din22 at earthlink.net (david) Date: Sun, 4 Dec 2005 11:15:22 -0600 Subject: [Tutor] my text adventure References: <000601c5f8ec$a482c110$0201a8c0@d71bh5mhis9p7o> Message-ID: <001001c5f8f6$4fc08ef0$0201a8c0@d71bh5mhis9p7o> i fixed this myself ! i think i can get everything working now so please disregard previous messages. if you haven't already. :) ----- Original Message ----- From: david To: tutor at python.org Sent: Sunday, December 04, 2005 10:06 AM Subject: [Tutor] (no subject) i added a list of rooms and rooms.append(self) to the Room initialization. then i run my program and create one room. there should now be two rooms. when i look at rooms i have three rooms! where did this other room come from? anyway, thanks for taking time to look at my code. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051204/e72a6b3e/attachment.htm From alan.gauld at freenet.co.uk Sun Dec 4 18:24:08 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 4 Dec 2005 17:24:08 -0000 Subject: [Tutor] (no subject) References: <000601c5f8ec$a482c110$0201a8c0@d71bh5mhis9p7o> Message-ID: <011e01c5f8f7$89027f60$0a01a8c0@xp> > then i run my program and create one room. there should now be two rooms. > when i look at rooms i have three rooms! where did this other room come > from? Dunno but have uyou tried asking it about itself using the debugger? Call the description methjod or look at the coordinates... One wee observation: rooms = [] class Room: def __init__(self,coords): self.contents = [] self.description = '' self.coords = coords world[tuple(coords)] = self rooms.append(self) self.exits = {} I'd either make rooms a class variable which can be accessed from outside the class with Room.rooms or I'd make the append operation a responsibility of the calling client. Otherwise every time you try to use the Room class in another program you will need to create a rooms global variable. Since the purpose of rooms is to keep a register of all the rooms in existence I'd argue it should be a class variable. Just a matter of style it doesn't really affect the operation here. And certainly doesn't fix your extra room problem! Alan G. From dyoo at hkn.eecs.berkeley.edu Mon Dec 5 01:45:20 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 4 Dec 2005 16:45:20 -0800 (PST) Subject: [Tutor] Search theory for luddites? In-Reply-To: Message-ID: > My current planned approach is to have each file added read and keywords > extracted (i.e. variable names, libraries imported etc.) and used as > keys in a dictionary, and each key points to a list of files containing > it (files will be stored in a zip or similar). > > i.e. > > words = { > > "imaplib": ["X.py"], > "smtplib": ["X.py", "Y.py"] > > } > > And if I do a search for "smtplib" or "imaplib" it'll return X.py > first, as it contains both, and Y.py second. > > Is there a more efficient approach? I don't think a relational DB really > suits this sort of task at present, but I'm wondering about search > times. Hi Liam, That sounds fine, and it's a popular approach. What you have there is known as an "inverted index": http://www.nist.gov/dads/HTML/invertedIndex.html and it's the way that many search engines know how to link up keywords to their respective documents. > I've googled for search theory, and hit c2's wiki up, but I'm having no > luck at finding applicable, understandable theory... a lot of stuff > about trees and nodes and paths through graphs, but I can't correlate > that to my problem. There's a really short-and-sweet book called "Understanding Search Engines: Mathematical Modeling and Text Retrieval" that covers some core ideas: http://www.cs.utk.edu/~berry/usebook/ I'd heartily recommend that one; they do talk about the theory, but from a practitioner's point of view, so it's quite readable. And it is very thin and easy to carry. *grin* From dyoo at hkn.eecs.berkeley.edu Mon Dec 5 01:53:16 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 4 Dec 2005 16:53:16 -0800 (PST) Subject: [Tutor] my text adventure In-Reply-To: <001001c5f8f6$4fc08ef0$0201a8c0@d71bh5mhis9p7o> Message-ID: On Sun, 4 Dec 2005, david wrote: > i fixed this myself ! i think i can get everything working now so > please disregard previous messages. if you haven't already. :) That's great! By the way, you asked a while back if trying to write a text-adventure game was a good way to learn how to program: I think you're finding the answer to be: "Yes". *grin* From dyoo at hkn.eecs.berkeley.edu Mon Dec 5 02:03:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 4 Dec 2005 17:03:13 -0800 (PST) Subject: [Tutor] Socket connection In-Reply-To: <3619.193.71.156.231.1133713195.squirrel@mail.sporck.net> Message-ID: > I need to get some whois-info from whois.ripe.net. I have been able to > connect and get the info that I need, but I would like to know what is > the most 'polite' way of doing so. I need to do quite a few whois > lookups (from my server logs) and don't want to risk creating more > hassle for their server than necessary. So, what I would like to know, > is what is the best way of doing lots of requests? Hello, It's really specific to the protocol: a protocol will define if it's ok or not to send multiple requests per connection. According to RFC 3912: http://www.rfc-editor.org/rfc/rfc3912.txt here is their high-level overview of the WHOIS protocol: """ 2. Protocol Specification A WHOIS server listens on TCP port 43 for requests from WHOIS clients. The WHOIS client makes a text request to the WHOIS server, then the WHOIS server replies with text content. All requests are terminated with ASCII CR and then ASCII LF. The response might contain more than one line of text, so the presence of ASCII CR or ASCII LF characters does not indicate the end of the response. The WHOIS server closes its connection as soon as the output is finished. The closed TCP connection is the indication to the client that the response has been received. """ So unfortunately it does look like you'll have to reestablish the connection after each request: the whois protocol as defined here doesn't appear to allow multiple requests per connection. Hope this helps! From din22 at earthlink.net Mon Dec 5 02:09:37 2005 From: din22 at earthlink.net (david) Date: Sun, 4 Dec 2005 19:09:37 -0600 Subject: [Tutor] my text adventure, saving and restoring Message-ID: <000a01c5f938$9046a1c0$0201a8c0@d71bh5mhis9p7o> when i restore from the pickle i can see my exits and descriptions are still there. but look won't see the description and move can't move to the next room. i am stumped. what is going on here? how can i fix it? please help? IDLE 1.1.2 ==== No Subprocess ==== >>> >rooms [<__main__.Room instance at 0x00E08EB8>] {} >world {(0, 0): <__main__.Room instance at 0x00E08EB8>} >dr >>startroom >l [0, 0] startroom >dig n (0, 1) >n >dr >>nextroom >rooms [<__main__.Room instance at 0x00E08EB8>, <__main__.Room instance at 0x00E7BFD0>] startroom {'n': <__main__.Room instance at 0x00E7BFD0>} nextroom {'s': <__main__.Room instance at 0x00E08EB8>} >world {(0, 1): <__main__.Room instance at 0x00E7BFD0>, (0, 0): <__main__.Room instance at 0x00E08EB8>} >save >quit Traceback (most recent call last): File "C:\Documents and Settings\david\Desktop\t.py", line 150, in ? p.do() File "C:\Documents and Settings\david\Desktop\t.py", line 93, in do sys.exit() SystemExit >>> >rooms [<__main__.Room instance at 0x00E13F30>, <__main__.Room instance at 0x00E13698>] startroom {'n': <__main__.Room instance at 0x00E13698>} nextroom {'s': <__main__.Room instance at 0x00E13F30>} >world {(0, 1): <__main__.Room instance at 0x00E13FA8>, (0, 0): <__main__.Room instance at 0x00E132B0>} >n alas, you cannot go that way >l [0, 0] > import sys import string import pickle import os.path world = {} rooms = [] class Room: def __init__(self,coords): self.contents = [] self.description = '' self.coords = coords world[tuple(coords)] = self rooms.append(self) self.exits = {} def nextdoor(self,direction): if direction == 'n': nextdoor = (self.coords[0], self.coords[1] + 1) return list(nextdoor) elif direction == 's': nextdoor = list((self.coords[0], self.coords[1] - 1)) return nextdoor elif direction == 'e': nextdoor = list((self.coords[0] +1, self.coords[1])) return nextdoor elif direction == 'w': nextdoor = (self.coords[0] -1, self.coords[1]) return list(nextdoor) class Player: def __init__(self,name): self.name = name self.location = None self.inventory = [] self.wielded = None def look(self): print self.location.coords print self.location.description def move(self,direction): type(direction) if self.location.exits.has_key(direction): self.location = self.location.exits[direction] else: print 'alas, you cannot go that way' def wield(self,what): self.wielded = what def wear(self,what): pass def take(self,what): pass def drop(self,what): pass def dig(self,direction): target = tuple(self.location.nextdoor(direction)) print target if self.location.exits.has_key(target): print 'there is already an exit to that room' elif world.has_key(target): print 'already a room there, attempt to make exits' self.location.exits[direction] = world[target] world[target].exits[opdir(direction)] = self.location else: world[target]=Room(target) self.location.exits[direction] = world[target] world[target].exits[opdir(direction)] = self.location def describeroom(self): self.location.description = raw_input('>>') def save(self): f = open('savefile', 'w') pickle.dump(world,f) pickle.dump(rooms,f) for i in rooms: pickle.dump(i,f) f.close() def do(self): cmd = string.split(raw_input('>')) verb = cmd[0] if len(cmd) > 1: target = cmd[1] if verb == 'l': self.look() elif verb in ['n','s','e','w']: self.move(verb) elif verb == 'quit': sys.exit() elif verb == 'i': for a in self.inventory: print a.name elif verb == 'dig': self.dig(target) elif verb == 'dr': self.describeroom() elif verb == 'save': self.save() elif verb == 'world': print world elif verb == 'rooms': print rooms for i in rooms: print i.description print i.exits else: print 'what?' class Thing: def __init__(self,name): self.name = name def opdir(direction): if direction == 'n': return 's' if direction == 's': return 'n' if direction == 'e': return 'w' if direction == 'w': return 'e' p = Player('david') room1 = Room([0,0]) p.location = room1 sword = Thing('sword') hat = Thing('hat') p.inventory.append(sword) p.inventory.append(hat) if os.path.isfile('savefile'): f = open('savefile','r') world = pickle.load(f) rooms = pickle.load(f) for i in rooms: i = pickle.load(f) f.close() while 1: p.do() else: while 1: p.do() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051204/d7ab05d1/attachment-0001.htm From Ashwini.Mishra at umassmed.edu Mon Dec 5 02:13:12 2005 From: Ashwini.Mishra at umassmed.edu (Mishra, Ashwini) Date: Sun, 4 Dec 2005 20:13:12 -0500 Subject: [Tutor] script run problem Message-ID: <1A42F1E1A1E73A4F8C6048789F34A32F3957E5@edunivmail02.ad.umassmed.edu> Hi everyone, I am not able to run any script in python ver2.4.2. under window xp.I get the following error message------------python.exe has encountered a problem and needs to be closed. Though path for python.exe is correct.Error meeasge generated by MS office is ?xml version="1.0" encoding="UTF-16"?> I would apppreciate any help. Thanks Ashwini ----------------------------------------------- Dr.AShwini Mishra Univ. of Massachusetts Medical school Two biotech ,suite119 373 Plantation st,Worcester MaA01605 Tel:508-856-1087 From srini_iyyer_bio at yahoo.com Mon Dec 5 02:29:42 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Sun, 4 Dec 2005 17:29:42 -0800 (PST) Subject: [Tutor] Words alignment tool In-Reply-To: Message-ID: <20051205012942.36455.qmail@web31603.mail.mud.yahoo.com> Dear Expert programmers, I aplogise if this mail is out of context here. I have a list of elements like these: Contr1 SPR-10 SPR-101 SPR-125 SPR-137 SPR-139 SPR-143 contr2 SPR-1 SPR-15 SPR-126 SPR-128 SPR-141 SPR-148 contr3 SPR-106 SPR-130 SPR-135 SPR-138 SPR-139 SPR-145 contr4 SPR-124 SPR-125 SPR-130 SPR-139 SPR-144 SPR-148 There are several common elements prefixed with SPR-. Although these elements are sorted in asecending order row wise, the common elements are difficult to spot. One has to look for common elements by eyeballing. It would be wonderful if these elements are aligned properly by inserting gaps. In bioinformatics world, this is 100% identical to Protein or DNA alignment. Example: If there are 3 sequences DNA1,2 and 3 with their sequences: DNA1: ATAAAATTAA DNA2: AAAAATAT DNA3: TAATAATAA DNA1 ATAAAATTAA DNA2 A AAAA TA T DNA3 TA AtAAT AA These 3 sequences are aligned by introducing gaps. However, in DNA and protein sequence alignments more complex algorithms and treatment is done so as to make a better scoring alignment. However, unfortunately I cannot apply these algorithms/programs to my data, because these programs are made for DNA and protein sequences. I googled for some word matchers. There are programs available however, they align them without itroducing gaps. So ultimately I cannot see the common items clearly lined up (I guess I may be wrong here, it might be better also). My question to the community is, are there any such programs that would generate a multiple alignments on user defined data. I am sure that the idea of multiple algorithms might have been extended to other areas of science, economics or LINGUISTICS. Could any one help me if I can align my data. I have a total of 50 unique words (SPR-1, SPR-2, SPR-3 likewise but no exactly the order and digit). For some Control elements I have 120 such words in a row (consider this of a sequence with 120 words). So if I have to do this in excel I will spend the rest of my happy life doing that :-) However, to show I tried to do that and pasted it below ( derailed completely). So, dear respected members do you have any suggestions of any such programs that I can use in this world of CS. Thank you. S Contr1 SPR-10 SPR-15 SPR-101 SPR-106 SPR-138 SPR-139 SPR-140 SPR-144 SPR-148 contr2 SPR-1 SPR-10 SPR-101 SPR-130 SPR-138 SPR-139 SPR-142 SPR-144 SPR-148 contr3 SPR-15 SPR-16 SPR-17 SPR-106 SPR-130 SPR-135 SPR-139 SPR-144 SPR-181 __________________________________ Start your day with Yahoo! - Make it your home page! http://www.yahoo.com/r/hs From john at fouhy.net Mon Dec 5 02:41:52 2005 From: john at fouhy.net (John Fouhy) Date: Mon, 5 Dec 2005 14:41:52 +1300 Subject: [Tutor] my text adventure, saving and restoring In-Reply-To: <000a01c5f938$9046a1c0$0201a8c0@d71bh5mhis9p7o> References: <000a01c5f938$9046a1c0$0201a8c0@d71bh5mhis9p7o> Message-ID: <5e58f2e40512041741i4537d1b3n@mail.gmail.com> On 05/12/05, david wrote: > when i restore from the pickle i can see my exits and descriptions are still > there. > def save(self): > f = open('savefile', 'w') > pickle.dump(world,f) > pickle.dump(rooms,f) > for i in rooms: > pickle.dump(i,f) > f.close() Hi David, You appear to be saving your information multiple times. 'world' is a dictionary with Room instances as its values. Those same Room instances occur in 'rooms'. So, when you run your save method, python does this: 1. Write information to the pickle file telling python to construct a dictionary. This includes telling python how to construct the Room instances. 2. Write information to the pickle file telling python to construct a list. This includes telling python how to construct the Room instances. 3. For each Room instance, write information to the pickle file telling python how to construct it. Now, when you unpickle the information, python does this: 1. Build a dictionary to be the world. Build all the Rooms (because the Rooms were the values of this dictionary). 2. Build a list of Rooms. Build all the Rooms (because the Rooms were the contents of this list). 3. Build all the Rooms again, and do nothing with them. Initially, your Room isntances in world were the same as the Rooms in rooms. But after unpickling, python builds the Rooms separately for each data structure, and so they end up different. Let me try some ASCII art: [view this in a monospaced font, eg, by cutting-and-pasting to Notepad] Before: world: (0,0) |-> Room0; (0,1) |-> Room1; (1,1) |-> Room2 /------/ /-------/ /--/ / / / /------\ /------\ /------\ | Room | | Room | | Room | |object| |object| |object| \------/ \------/ \------/ /----/ /-------/ /------/ rooms: [ RoomA, RoomB, RoomC ] After: world: (0,0) |-> Room0; (0,1) |-> Room1; (1,1) |-> Room2 /------/ /-------/ /--/ / / / /------\ /------\ /------\ | Room | | Room | | Room | |object| |object| |object| \------/ \------/ \------/ rooms: [ RoomA, RoomB, RoomC ] \----\ \-------\ \------\ /------\ /------\ /------\ | Room | | Room | | Room | |object| |object| |object| \------/ \------/ \------/ You could make your save() method a lot simpler; something like this: def save(self): f = open('savefile', 'w') pickle.dump(world,f) f.close() This is all you need, because 'world' contains all the information about your world. Then, when you load the data back, you will need to figure out some way of building your 'rooms' data structure from 'world'. Does this help? -- John. From din22 at earthlink.net Mon Dec 5 03:04:22 2005 From: din22 at earthlink.net (david) Date: Sun, 4 Dec 2005 20:04:22 -0600 Subject: [Tutor] my text adventure, saving and restoring References: <000a01c5f938$9046a1c0$0201a8c0@d71bh5mhis9p7o> <5e58f2e40512041741i4537d1b3n@mail.gmail.com> Message-ID: <000b01c5f940$3617cdc0$0201a8c0@d71bh5mhis9p7o> thanks that was very helpful. i added all that stuff because i was trying to figure out some way of getting at the descriptions and exits. that is the part i'm stuck on. but knowing that world is all i need is good because i can focus my efforts better. thanks. > You could make your save() method a lot simpler; something like this: > > def save(self): > f = open('savefile', 'w') > pickle.dump(world,f) > f.close() > > This is all you need, because 'world' contains all the information > about your world. Then, when you load the data back, you will need to > figure out some way of building your 'rooms' data structure from > 'world'. > > Does this help? > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Mon Dec 5 04:17:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 04 Dec 2005 22:17:21 -0500 Subject: [Tutor] Words alignment tool In-Reply-To: <20051205012942.36455.qmail@web31603.mail.mud.yahoo.com> References: <20051205012942.36455.qmail@web31603.mail.mud.yahoo.com> Message-ID: <4393B141.8050207@tds.net> Srinivas Iyyer wrote: >Dear Expert programmers, > >I aplogise if this mail is out of context here. > >I have a list of elements like these: > >Contr1 SPR-10 SPR-101 SPR-125 SPR-137 SPR-139 SPR-143 >contr2 SPR-1 SPR-15 SPR-126 SPR-128 SPR-141 SPR-148 >contr3 SPR-106 SPR-130 SPR-135 SPR-138 SPR-139 SPR-145 >contr4 SPR-124 SPR-125 SPR-130 SPR-139 SPR-144 SPR-148 > > >There are several common elements prefixed with SPR-. >Although these elements are sorted in asecending order >row wise, the common elements are difficult to spot. >One has to look for common elements by eyeballing. >It would be wonderful if these elements are aligned >properly by inserting gaps. > > I think this is much easier than the bioinformatics problem because your sequence elements are unique and sorted, and you don't have very much data. One approach is to create pairs that look like ('SPR-10', 'Contr1') for all the data. These pairs can be put into one big list and sorted, then grouped by the first element to get what you want. Python 2.4 has the groupby() function which makes it easy to do the grouping. For example: data = '''Contr1 SPR-10 SPR-101 SPR-125 SPR-137 SPR-139 SPR-143 contr2 SPR-1 SPR-15 SPR-126 SPR-128 SPR-141 SPR-148 contr3 SPR-106 SPR-130 SPR-135 SPR-138 SPR-139 SPR-145 contr4 SPR-124 SPR-125 SPR-130 SPR-139 SPR-144 SPR-148'''.splitlines() import itertools, operator pairs = [] # This will be a list of all the pairs like ('SPR-10', 'Contr1') for line in data: items = line.split() name, items = items[0], items[1:] # now name is the first item on the line, items is a list of all the rest # add the pairs for this line to the main list pairs.extend( (item, name) for item in items) pairs.sort() # Sort the list to bring the first items together # groupby() will return a sequence of key, group pairs where the key is the # first element of the group for k, g in itertools.groupby(pairs, operator.itemgetter(0)): print k, [ name for item, name in g ] The output of this program is SPR-1 ['contr2'] SPR-10 ['Contr1'] SPR-101 ['Contr1'] SPR-106 ['contr3'] SPR-124 ['contr4'] SPR-125 ['Contr1', 'contr4'] SPR-126 ['contr2'] SPR-128 ['contr2'] SPR-130 ['contr3', 'contr4'] SPR-135 ['contr3'] SPR-137 ['Contr1'] SPR-138 ['contr3'] SPR-139 ['Contr1', 'contr3', 'contr4'] SPR-141 ['contr2'] SPR-143 ['Contr1'] SPR-144 ['contr4'] SPR-145 ['contr3'] SPR-148 ['contr2', 'contr4'] SPR-15 ['contr2'] Converting this to a horizontal display is still a little tricky but I'll leave that for you. I should probably explain more about groupby() and itemgetter() but not tonight... Kent From din22 at earthlink.net Mon Dec 5 04:56:53 2005 From: din22 at earthlink.net (david) Date: Sun, 4 Dec 2005 21:56:53 -0600 Subject: [Tutor] my text adventure Message-ID: <000601c5f94f$ee96ccc0$0201a8c0@d71bh5mhis9p7o> i have finally got save and restoring to work. here is my code for posterity. :) i was (i think) putting the player in a room that wasnt the room from the pickle. but somehow the same room. anyway comments welcome. import sys import string import pickle import os.path world = {} rooms = [] class Room: def __init__(self,coords): self.contents = [] self.description = '' self.coords = coords world[tuple(coords)] = self rooms.append(self) self.exits = {} def nextdoor(self,direction): if direction == 'n': nextdoor = (self.coords[0], self.coords[1] + 1) return list(nextdoor) elif direction == 's': nextdoor = list((self.coords[0], self.coords[1] - 1)) return nextdoor elif direction == 'e': nextdoor = list((self.coords[0] +1, self.coords[1])) return nextdoor elif direction == 'w': nextdoor = (self.coords[0] -1, self.coords[1]) return list(nextdoor) class Player: def __init__(self,name): self.name = name self.location = None self.inventory = [] self.wielded = None def look(self): print self.location.coords print self.location.description def move(self,direction): type(direction) if self.location.exits.has_key(direction): self.location = self.location.exits[direction] else: print 'alas, you cannot go that way' def wield(self,what): self.wielded = what def wear(self,what): pass def take(self,what): pass def drop(self,what): pass def dig(self,direction): target = tuple(self.location.nextdoor(direction)) print target if self.location.exits.has_key(target): print 'there is already an exit to that room' elif world.has_key(target): print 'already a room there, attempt to make exits' self.location.exits[direction] = world[target] world[target].exits[opdir(direction)] = self.location else: world[target]=Room(target) self.location.exits[direction] = world[target] world[target].exits[opdir(direction)] = self.location def describeroom(self): self.location.description = raw_input('>>') def save(self): f = open('savefile', 'w') pickle.dump(world,f) f.close() def do(self): cmd = string.split(raw_input('>')) verb = cmd[0] if len(cmd) > 1: target = cmd[1] if verb == 'l': self.look() elif verb in ['n','s','e','w']: self.move(verb) elif verb == 'quit': sys.exit() elif verb == 'i': for a in self.inventory: print a.name elif verb == 'dig': self.dig(target) elif verb == 'dr': self.describeroom() elif verb == 'save': self.save() elif verb == 'world': print world elif verb == 'rooms': print rooms for i in rooms: print i.description print i.exits else: print 'what?' class Thing: def __init__(self,name): self.name = name def opdir(direction): if direction == 'n': return 's' if direction == 's': return 'n' if direction == 'e': return 'w' if direction == 'w': return 'e' p = Player('david') sword = Thing('sword') hat = Thing('hat') p.inventory.append(sword) p.inventory.append(hat) if os.path.isfile('savefile'): f = open('savefile','r') world = pickle.load(f) f.close() p.location = world[0,0] while 1: p.do() else: room1 = Room([0,0]) p.location = room1 while 1: p.do() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051204/d07f21c6/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Dec 5 05:26:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 4 Dec 2005 20:26:35 -0800 (PST) Subject: [Tutor] Words alignment tool In-Reply-To: <20051205012942.36455.qmail@web31603.mail.mud.yahoo.com> Message-ID: On Sun, 4 Dec 2005, Srinivas Iyyer wrote: > Contr1 SPR-10 SPR-101 SPR-125 SPR-137 SPR-139 SPR-143 > contr2 SPR-1 SPR-15 SPR-126 SPR-128 SPR-141 SPR-148 > contr3 SPR-106 SPR-130 SPR-135 SPR-138 SPR-139 SPR-145 > contr4 SPR-124 SPR-125 SPR-130 SPR-139 SPR-144 SPR-148 Hi Srinivas, I'd strongly recommend changing the data representation from a line-oriented to a more structured view. Each line in your data above appears to describe a conceptual set of tuples: (control_number, spr_number) For example, we can think of the line: Contr1 SPR-10 SPR-101 SPR-125 SPR-137 SPR-139 SPR-143 as an encoding for the set of tuples written below (The notation I use below is mathematical and not meant to be interpreted as Python.): { (Contr1, SPR-10), (Contr1, SPR-101), (Contr1, SPR-125), (Contr1, SPR-137), (Contr1, SPR-139), (Contr1, SPR-143) } I'm not sure if I'm seeing everything, but from what I can tell so far, your data cries out to be held in a relational database. I agree with Kent: you do not need to "align" anything. If, within your sequence, each element has to be unique in that sequence, then your "alignment" problem transforms into a simpler table lookup problem. That is, if all your data looks like: 1: A B D E 2: A C F 3: A B C D where no line can have repeated characters, then that data can be transformed into a simple tablular representation, conceptually as: A B C D E F 1 | x | x | | x | x | | 2 | x | | x | | | x | 3 | x | x | x | x | | | So unless there's something here that you're not telling us, there's no need for any complicated alignment algorithms: we just start off with an empty table, and then for each tuple, check the corresponding entry in the table. Then when we need to look for common elements, we just scan across a row or column of the table. BLAST is cool, but, like regular expressions, it's not the answer to every string problem. If you want to implement code to do the above, it's not difficult, but you really should use an SQL database to do this. As a bioinformatician, it would be in your best interest to know SQL, because otherwise, you'll end up trying to reinvent tools that have already been written for you. A good book on introductory relational database usage is "The Practical SQL Handbook: Using Structured Query Language" by Judith Bowman, Sandra Emerson, and Marcy Darnovsky. Good luck to you. From JYAGY1 at pride.hofstra.edu Mon Dec 5 06:18:02 2005 From: JYAGY1 at pride.hofstra.edu (Josh Yagy) Date: Mon, 05 Dec 2005 00:18:02 -0500 Subject: [Tutor] Problems padding a string with 0's while deconcatonating Message-ID: <1133759882.745ff7e0JYAGY1@pride.hofstra.edu> Hello everyone, this is my first time using the tutor e-mail, so if I mess up any common format or something just let me know :). Alright, for a little background, I'm in the process of writing a merkle-hellman cryptosystem for my CS15 class. I'm doing fine till I get to the decatonation of the long binary string into n-strings which will then be used to match up to the public key. I have the following code: def binaryString(b, n): s=[] j=0 while j < len(b): temp = b[j:j+n] s = s + [ temp ] j = j + n return s which works for all intents and purposes, but I can't figure out a way to get it to pad the left of the string with zeros so that each of the subsets is n bits long. As is, it will deconcatonate a given string into n-substrings, but not all of the substrings are n bits long. Any help would be greatly appreciated and sorry again if I didn't include anything I should. -Josh From din22 at earthlink.net Mon Dec 5 14:42:34 2005 From: din22 at earthlink.net (david) Date: Mon, 5 Dec 2005 07:42:34 -0600 Subject: [Tutor] (no subject) Message-ID: <000701c5f9a1$c003c2d0$0201a8c0@d71bh5mhis9p7o> hello everyone, and thanks for your help and guidance so far. amazingly enough, something i thought would be simple has turned out to be not simple. i have a sword that i want to wield. as i have it here, i think i am wielding whatever string i type as argument to wield. so i guess i need to pass wield an object somehow instead of a string. can anyone point in the right direction? class Player: def __init__(self,name): self.name = name self.location = None self.inventory = [] self.wielded = None self.headwear = None def wield(self,what): print type(what) print 'you wield',what self.wielded = what def do(self): cmd = string.split(raw_input('>')) verb = cmd[0] if len(cmd) > 1: target = cmd[1] if verb == 'l': self.look() elif verb in ['n','s','e','w']: self.move(verb) elif verb == 'quit': sys.exit() elif verb == 'i': print 'wielded',self.wielded print 'on head', self.headwear for a in self.inventory: print a.name elif verb == 'wield': self.wield(target) else: print 'what?' class Thing: def __init__(self,name): self.name = name self.uponwield = '' p = Player('david') sord = Thing('sword') sord.uponwield = 'the sword glows ' hat = Thing('hat') p.inventory.append(sword) p.inventory.append(hat) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051205/517ef96e/attachment.html From AKolinski at nriindustries.com Mon Dec 5 15:26:37 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Mon, 5 Dec 2005 09:26:37 -0500 Subject: [Tutor] files - strings - lists (continued) In-Reply-To: <43866B99.1030704@tds.net> Message-ID: I used Kent's hints and suggestions but now I'm facing a problem of how to calculate final results from the retrieved data. My script, at this stage, opens _all_ game results files, gets an individual player's name, calculates his score and keeps the number of boards played. It does it per _each_ _game_ _individually_. What I would like to do is to calculate his ranking as a: (sum of all scores)/(sum of all boards). I have no clue how to combine results from, let's say, 3 games and use it for the above calculations. Below are: the copy of the script (under construction) and the sample of the data available: ################################# import glob, string resultsFileName = 'butler.txt' resultsFile = open(resultsFileName,"w") resultsFile.write('----------------------------------\nImie i Nazwisko\t\tBUTLER\n---------------------------------\n') for f in glob.glob("*.sbk"): # Get all text files and loop over them try: filecontents = open(f,'r') filecontents.next() filecontents.next() header = filecontents.next().split() hands = int(header[2]) rounds = int(header[3]) boards = hands*rounds filecontents.next() except IOError: # If something went wrong, ignore this file continue allScores = {} try: # you don't say how you know the end of the names, I just run to the end of data while True: names = filecontents.next().strip().split() player1 = names[0] player2 = names[2] filecontents.next() # skip line after name scores = [ int(filecontents.next().split()[2]) for i in range(rounds) ] tScores = 0 for i in scores: iScore = float(i) tScores = float(sum(scores)) allScores.setdefault(player1, []).append((tScores, boards)) allScores.setdefault(player2, []).append((tScores, boards)) except: # no more lines if filecontents.next() == '1,1': pass for player1, tScores in allScores.items(): print player1, tScores score = tScores[0][0] played = tScores[0][1] butler = score/played #print ("%1.4f") %butler line = "%s\t\t%1.4f" %(player1, butler) #print line resultsFile.write(line + '\n') filecontents.close() resultsFile.close() #################################################### Chrabalowski [(21.0, 24)] Kowalski [(-8.0, 24)] Kolinski [(31.0, 24)] ......................... Chrabalowski [(45.0, 25)] Orlicka [(-27.0, 25)] KempaM [(5.0, 25)] ........................ Chrabalowski [(-23.0, 25)] Lukasik [(-24.0, 25)] Szczerbowski [(31.0, 25)] As you can see Chrabalowski played in all three games. His current score should be calculated like this: finalButler = (21.0 + 45.0 -23.0)/(24 + 25 + 25), which is 0.5811 by the way. Is the individual db appropriate for this or I should be looking for a dictionary type format. I am lost. _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski Kent Johnson Sent by: tutor-bounces at python.org 24/11/2005 08:40 PM To cc tutor at python.org Subject Re: [Tutor] files - strings - lists Andrzej Kolinski wrote: > > OK, I made some progress I think. I added a few lines to Kent's script > to get closer what I really am after: Congratulations! See some notes below. > > ========================================== > lines = open('liga050926.sbk') # to get the data from a real file > > #lines = iter(data) # getting data from a string, you don't need this > when reading a file > > lines.next() # skip two headers > lines.next() > > header = lines.next().split() > hands = int(header[2]) > rounds = int(header[3]) > boards = hands*rounds > > lines.next() > > > allScores = {} # accumulate scores into a dictionary whose key is the name > > # Now we can process the names and scores in a loop > try: # you don't say how you know the end of the names, I just run to > the end of data > while True: > names = lines.next().strip() > player1 = names.split()[0] > player2 = names.split()[2] This could be names = lines.next().strip().split() player1 = names[0] player2 = names[2] or even player1, player2 = lines.next().strip().split(' - ') > > lines.next() # skip line after name > scores = [ int(lines.next().split()[2]) for i in range(rounds) ] > tScores = 0 > for i in scores: > iScore = float(i) > tScores = tScores + iScore This could be tScores = float(sum(scores)) > > allScores[player1] = tScores/boards > allScores[player2] = tScores/boards > > except: # no more lines > if lines.next() == '1,1': > pass I'm not sure what the two lines above are doing? It looks like you don't have a good way to detect the end of the data and you just catch some exception...you should figure out a clean way to exit the loop. Maybe when you read the names line you can look for '1,1' and break out of the loop, if that is what always follows the data you care about. > > for player1, tScores in allScores.items(): > print player1, tScores > ============================================= > 1. I singled out the players names. > 2. I added the players scores and divided by the number of boards > played. > 3. The output contents is what I wanted: > > Chrabalowski 0.875 > Kowalski -0.333333333333 > Kolinski 1.29166666667 > Bohossian 1.29166666667 > Stankiewicz -1.16666666667 > Cwir -0.708333333333 ... > > 4. The next step for me would be to read the data from more, > similar files (from 2 to 10) representing different games and generate > an average score for each participating player (a player does not > necessary plays each game and I would eventually like to calculate > averages of best six out of maximum ten games). Tough! How should I > start this next step? (I would like to keep both options open: > final ranking = (all tScores)/all boards), or > final ranking = average(RScores/boards, RScores/boards, > RScores/boards, ...) > game1 > game2 game3) I would save more data for each player. Instead of just keeping the average for the player, I would keep a list of pairs of (tScore, boards) for each game. Instead of allScores[player1] = tScores/boards you could say playerScores = allScores.get(player1, []) playerScores.append( (tScores, boards) ) allScores[player1] = playerScores all of which can be written more tersely (and obscurely) as allScores.setdefault(player1, []).append( (tScores, boards) ) Of course you need a loop to read all the files and you will initialize allScores before the loop. Then when you finish with the files you can retrieve the players' stats and process them either way you want. BTW what game is this? It seems odd that both players get the same score. > > Thanks Kent, Chris and Danny. After many, many months of using or > modifying (and using) existing scripts, with your invaluable help I feel > I can write script that is original and extremely useful to me! Glad to hear it! Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051205/1387f949/attachment.html From ajikoe at gmail.com Mon Dec 5 16:40:28 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 5 Dec 2005 16:40:28 +0100 Subject: [Tutor] distutils python 2.4.2 winxp, microsoft visual studio 2005 problem Message-ID: Hello, I try to call setup build and found this problem: running build running build_ext *** Failed: error: The .NET Framework SDK needs to be installed before building extensions for Python. I have .NET Framework SDK already. Is there anyone experiance this problem ? I also found some information about this : http://www.vrplumber.com/programming/mstoolkit But I think this is only for .NetFramework 1.1 and visual studio 7 I have Visual studio express 2005 which use .NetFramework 2.0 Can anybody helps? Thanks pujo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051205/5d01887a/attachment.htm From ARoberts at ambac.com Mon Dec 5 16:55:04 2005 From: ARoberts at ambac.com (Roberts, Alice) Date: Mon, 5 Dec 2005 10:55:04 -0500 Subject: [Tutor] (no subject) Message-ID: <30CB82E83CB76D4584C5D7CEE3A4013E04ED47B7@THEARCHITECT.ambac.abklan.net> Good morning, Does anyone know of something that will copy a directory tree, but only for files with a specific extension? I found copytree( src, dst[, symlinks]) , but I wasn't sure how to assign the src to the string, ie) \\server\share\*.xls. Thanks, Alice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051205/3437a691/attachment.html From kent37 at tds.net Mon Dec 5 17:16:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 05 Dec 2005 11:16:02 -0500 Subject: [Tutor] (no subject) In-Reply-To: <30CB82E83CB76D4584C5D7CEE3A4013E04ED47B7@THEARCHITECT.ambac.abklan.net> References: <30CB82E83CB76D4584C5D7CEE3A4013E04ED47B7@THEARCHITECT.ambac.abklan.net> Message-ID: <439467C2.3060003@tds.net> Roberts, Alice wrote: > Good morning, > > Does anyone know of something that will copy a directory tree, but > only for files with a specific extension? I found > > *copytree*( > > > > /src, dst/[/, symlinks/]) > > , but I wasn?t sure how to assign the src to the string, ie) > \\server\share\*.xls. > Alice, shutil.copytree() won't do what you want, but you might consider making a modified copy for your own use. It is a pretty simple function and the comments even encourage using it as an example to do what you want. You can find the source in the Lib directory of your Python installation. Kent From kent37 at tds.net Mon Dec 5 19:05:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 05 Dec 2005 13:05:46 -0500 Subject: [Tutor] Problems padding a string with 0's while deconcatonating In-Reply-To: <1133759882.745ff7e0JYAGY1@pride.hofstra.edu> References: <1133759882.745ff7e0JYAGY1@pride.hofstra.edu> Message-ID: <4394817A.5050108@tds.net> Josh Yagy wrote: >I have the following code: > >def binaryString(b, n): > s=[] > j=0 > while j < len(b): > temp = b[j:j+n] > s = s + [ temp ] > j = j + n > return s > >which works for all intents and purposes, but I can't figure out a way to get it to pad the left of the string with zeros so that each of the subsets is n bits long. As is, it will deconcatonate a given string into n-substrings, but not all of the substrings are n bits long. Any help would be greatly appreciated and sorry again if I didn't include anything I should. > Josh, I don't think I understand the problem. When I try your function I get b= '0101001100011100001111' print binaryString(b, 4) -> ['0101', '0011', '0001', '1100', '0011', '11'] How does this differ from what you want? I am not losing any leading zeros, just the last substring is short. BTW your function can be written much more compactly. I'll show you how in a few steps. First, notice that the sequence of values in j can be generated with the range() function, e.g. >>> range(0, len(b), 4) [0, 4, 8, 12, 16, 20] This lets you replace the calculation of j with a simple for statement: def binaryString2(b, n): s=[] for j in range(0, len(b), n): temp = b[j:j+n] s = s + [ temp ] return s Next, use list.append() to add to s and get rid of temp: def binaryString3(b, n): s=[] for j in range(0, len(b), n): s.append(b[j:j+n]) return s Now this can be easily replaced with a single list comprehension: def binaryString4(b, n): return [b[j:j+n] for j in range(0, len(b), n)] (This version appears in the Python Cookbook at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044) Kent From dyoo at hkn.eecs.berkeley.edu Mon Dec 5 20:52:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 5 Dec 2005 11:52:21 -0800 (PST) Subject: [Tutor] RPG wielding In-Reply-To: <000701c5f9a1$c003c2d0$0201a8c0@d71bh5mhis9p7o> Message-ID: > hello everyone, and thanks for your help and guidance so far. amazingly > enough, something i thought would be simple has turned out to be not > simple. i have a sword that i want to wield. as i have it here, i think > i am wielding whatever string i type as argument to wield. so i guess i > need to pass wield an object somehow instead of a string. can anyone > point in the right direction? Your player's inventory is a list of items. One way to make wield() work right is to hunt through your inventory to see what item matches the 'what'. Good luck! From alan.gauld at freenet.co.uk Mon Dec 5 22:16:29 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 5 Dec 2005 21:16:29 -0000 Subject: [Tutor] (no subject) References: <000701c5f9a1$c003c2d0$0201a8c0@d71bh5mhis9p7o> Message-ID: <019401c5f9e1$5a9aa810$0a01a8c0@xp> > i guess i need to pass wield an object somehow instead of a string. > can anyone point in the right direction? AS ever converting strings to objects is a job for a doictionary. And remember that classe3s are objects too. So simply register each class you define in a dictionary of classes against their name classes = {'Room':Room, 'Player': Player, 'Sword':Sword,...} class Player: def wield(self,what): print type(what) print 'you wield',what self.wielded = classes[what]() # an instance of what... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Dec 5 22:17:52 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 5 Dec 2005 21:17:52 -0000 Subject: [Tutor] script run problem References: <1A42F1E1A1E73A4F8C6048789F34A32F3957E5@edunivmail02.ad.umassmed.edu> Message-ID: <019501c5f9e1$5b0ec6a0$0a01a8c0@xp> Hi Kishra, In the words of the old joke(*) why not just 'get out and get back in' and see if that fixes it? In other words I'd try a reinstall of Python, it looks like something has gone missing or got corrupted... Alan G. (*)Three guys are in a car that breaks down. The first says "I'm an Electrical Engineer, I bet it's the electrics", jumps out and starts checking the wiring. The second guy says "I'm a mechanical engineer, it's probably the engine" and gets out to check the gaskets. The third guy says "I'm a software engineer, why don't we just get out of the car then get back in and see if that fixes it?" From JYAGY1 at pride.hofstra.edu Tue Dec 6 00:49:34 2005 From: JYAGY1 at pride.hofstra.edu (Josh Yagy) Date: Mon, 05 Dec 2005 18:49:34 -0500 Subject: [Tutor] Problems padding a string with 0's while deconcatonating Message-ID: <1133826574.79c60b20JYAGY1@pride.hofstra.edu> Wow, that code is much more compact, thanks for the help! But as far as the original question goes, I think I worded my problem wrong. The output you got with your binary string is almost what I Want, but not quite. I need each subset of binary strings to be n bits long (in the dummy problem you ran, 4 bits). The last subset is two bits short, but for the sake of the cryptosystem, I can't pad it with zeros at the right, I need to pad it to the left. for instance: Your output was: print binaryString(b, 4) -> ['0101', '0011', '0001', '1100', '0011', '11'] What I'm looking for is for the output to be: print binaryString(b, 4) -> ['0001', '0100', '1100', '0111', '0000', '1111'] notice that my desired output is the same as yours, only all the bits are moved back two places to fill up the last subset, and the extra space is filled with 0's in the first subset. Thanks again for the help -----Original Message----- From: Kent Johnson Date: Mon, 05 Dec 2005 13:05:46 -0500 Subject: Re: [Tutor] Problems padding a string with 0's while deconcatonating Josh Yagy wrote: >I have the following code: > >def binaryString(b, n): > s=[] > j=0 > while j < len(b): > temp = b[j:j+n] > s = s + [ temp ] > j = j + n > return s > >which works for all intents and purposes, but I can't figure out a way to get it to pad the left of the string with zeros so that each of the subsets is n bits long. As is, it will deconcatonate a given string into n-substrings, but not all of the substrings are n bits long. Any help would be greatly appreciated and sorry again if I didn't include anything I should. > Josh, I don't think I understand the problem. When I try your function I get b= '0101001100011100001111' print binaryString(b, 4) -> ['0101', '0011', '0001', '1100', '0011', '11'] How does this differ from what you want? I am not losing any leading zeros, just the last substring is short. BTW your function can be written much more compactly. I'll show you how in a few steps. First, notice that the sequence of values in j can be generated with the range() function, e.g. >>> range(0, len(b), 4) [0, 4, 8, 12, 16, 20] This lets you replace the calculation of j with a simple for statement: def binaryString2(b, n): s=[] for j in range(0, len(b), n): temp = b[j:j+n] s = s + [ temp ] return s Next, use list.append() to add to s and get rid of temp: def binaryString3(b, n): s=[] for j in range(0, len(b), n): s.append(b[j:j+n]) return s Now this can be easily replaced with a single list comprehension: def binaryString4(b, n): return [b[j:j+n] for j in range(0, len(b), n)] (This version appears in the Python Cookbook at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044) Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From john at fouhy.net Tue Dec 6 01:02:24 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 6 Dec 2005 13:02:24 +1300 Subject: [Tutor] Problems padding a string with 0's while deconcatonating In-Reply-To: <1133826574.79c60b20JYAGY1@pride.hofstra.edu> References: <1133826574.79c60b20JYAGY1@pride.hofstra.edu> Message-ID: <5e58f2e40512051602h7efe1725s@mail.gmail.com> On 06/12/05, Josh Yagy wrote: > Wow, that code is much more compact, thanks for the help! But as far as the original > question goes, I think I worded my problem wrong. The output you got with your binary string > is almost what I Want, but not quite. I need each subset of binary strings to be n bits long (in > the dummy problem you ran, 4 bits). The last subset is two bits short, but for the sake of the > cryptosystem, I can't pad it with zeros at the right, I need to pad it to the left. for instance: Perhaps you could pad the original string! How much do we pad it by? Well, if n is the word size, we're not interested in how many complete chunks of n bits there are. We're only interested in how many are left over, once we cast out all complete pieces. This is equivalent to asking for the remainder, after dividing the length by n. eg: >>> b = '01010011010110101101101' >>> len(b) 23 >>> len(b)//4 # The // means we want integer division, not real division. 5 >>> len(b)-4*(len(b)//4) 3 So, if we split b into 4 bit pieces, there will be 5 of them, and 3 bits left over. But there's an easier way to do that calculation --- the modulo operator: >>> len(b) % 4 3 That's how many extra bits we have, so we can subtract that from n to get the number of '0's we need to pad with. Does that help? -- John. From ismaelgf at adinet.com.uy Tue Dec 6 01:04:20 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Mon, 05 Dec 2005 22:04:20 -0200 Subject: [Tutor] Problems padding a string with 0's while deconcatonating In-Reply-To: <1133826574.79c60b20JYAGY1@pride.hofstra.edu> References: <1133826574.79c60b20JYAGY1@pride.hofstra.edu> Message-ID: <4394D584.7000602@adinet.com.uy> Josh Yagy wrote: >Wow, that code is much more compact, thanks for the help! But as far as the original question goes, I think I worded my problem wrong. The output you got with your binary string is almost what I Want, but not quite. I need each subset of binary strings to be n bits long (in the dummy problem you ran, 4 bits). The last subset is two bits short, but for the sake of the cryptosystem, I can't pad it with zeros at the right, I need to pad it to the left. for instance: >Your output was: > print binaryString(b, 4) -> ['0101', '0011', '0001', '1100', '0011', '11'] >What I'm looking for is for the output to be: >print binaryString(b, 4) -> ['0001', '0100', '1100', '0111', '0000', '1111'] > >notice that my desired output is the same as yours, only all the bits are moved back two places to fill up the last subset, and the extra space is filled with 0's in the first subset. > >Thanks again for the help > Why don't you pad it before processing? def padleft(b, bits): bitsshort = len(b)%bits if bitsshort: #so that if len(b) == bits you don't get extra 0s amount = bits - bitsshort return "0"*amount + b return b >>> padleft("10011", 5) '10011' >>> padleft("101101", 4) '00101101' >>> padleft("1010101", 6) '000001010101' HTH! Ismael From Hans.Dushanthakumar at navman.com Tue Dec 6 01:36:07 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 6 Dec 2005 13:36:07 +1300 Subject: [Tutor] How to Pass lists by value Message-ID: <5667508E43F1B740BCFA57FF46E3530002A626CA@nav-akl-exch-c.newton.navman.com> Hi folks, How do I pass a list by value to a function. The foll: snippet of code produces the output as shown: Code: ----- def junk(x): x.append("20") return x a = ["10"] b = junk(a) print b print a Output: ------- >>> b = ['10', '20'] a = ['10', '20'] This indicates that the variable "a" was passed by reference because the function alters its value in the main script. However, the following code produces a slightly diff output: Code: ----- def junk(x): x = "30" return x a = ["10"] b = junk(a) print "b = ", b print "a = ", a Output: ------- >>> b = 30 a = ['10'] In this case, "a" seems to be passed by value, because the value is unchanged even after the call to the function. Question is, in the 1st scenario, how do I forcefully pass the variable by value rather than reference. Why is there a difference between the two scenarios? Cheers Hans From Hans.Dushanthakumar at navman.com Tue Dec 6 02:04:10 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 6 Dec 2005 14:04:10 +1300 Subject: [Tutor] How to Pass lists by value Message-ID: <5667508E43F1B740BCFA57FF46E3530002A62761@nav-akl-exch-c.newton.navman.com> Thanks guys Yes either of the foll solves the problem: b = junk(copy.copy(a)) OR b = junk(a[:]) Why is there a difference between the way the two lines (x.append("20") and x = "30") are handled within a function? ________________________________ From: Adam [mailto:adam.jtm30 at gmail.com] Sent: Tuesday, 6 December 2005 1:49 p.m. To: Hans Dushanthakumar Subject: Re: [Tutor] How to Pass lists by value On 06/12/05, Hans Dushanthakumar wrote: Hi folks, How do I pass a list by value to a function. The foll: snippet of code produces the output as shown: Code: ----- def junk(x): x.append("20") return x a = ["10"] b = junk(a) print b print a Output: ------- >>> b = ['10', '20'] a = ['10', '20'] This indicates that the variable "a" was passed by reference because the function alters its value in the main script. However, the following code produces a slightly diff output: Code: ----- def junk(x): x = "30" return x a = ["10"] b = junk(a) print "b = ", b print "a = ", a Output: ------- >>> b = 30 a = ['10'] In this case, "a" seems to be passed by value, because the value is unchanged even after the call to the function. Question is, in the 1st scenario, how do I forcefully pass the variable by value rather than reference. Why is there a difference between the two scenarios? Cheers Hans _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor def junk(x): x.append("20") return x a = ["10"] b = junk(a[:]) That should give you what you're looking for a[:] will pass the values of a. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051206/c3bf2a2d/attachment.html From john at fouhy.net Tue Dec 6 02:58:10 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 6 Dec 2005 14:58:10 +1300 Subject: [Tutor] How to Pass lists by value In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002A62761@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002A62761@nav-akl-exch-c.newton.navman.com> Message-ID: <5e58f2e40512051758k500616d3r@mail.gmail.com> On 06/12/05, Hans Dushanthakumar wrote: > > Thanks guys > > Yes either of the foll solves the problem: > > b = junk(copy.copy(a)) > > OR > > b = junk(a[:]) One thing you should be aware of --- these will both do a "shallow copy". Example: >>> lists = [[], [], [], []] >>> lists2 = lists[:] >>> lists.append('foo') >>> lists, lists2 # This shows that lists and lists2 are different. ([[], [], [], [], 'foo'], [[], [], [], []]) >>> lists[0].append(13) >>> lists, lists2 # Oops, but lists[0] and lists2[0] are the same! ([[13], [], [], [], 'foo'], [[13], [], [], []]) > Why is there a difference between the way the two lines (x.append("20") and > x = "30") are handled within a function? x = '30' will create a new (local) variable x and give it the value '30'. x.append('20') will call the .append() method on x. Calling this method has the side effect of changing the list x points to. -- John. From kent37 at tds.net Tue Dec 6 03:05:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 05 Dec 2005 21:05:11 -0500 Subject: [Tutor] How to Pass lists by value In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002A62761@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002A62761@nav-akl-exch-c.newton.navman.com> Message-ID: <4394F1D7.6010702@tds.net> Hans Dushanthakumar wrote: > Thanks guys > > Yes either of the foll solves the problem: > > b = junk(copy.copy(a)) > OR > > b = junk(a[:]) These work because they make a copy of a and pass (a reference to) the copy to the function. > Why is there a difference between the way the two lines > (x.append("20") and x = "30") are handled within a function? Because they are doing different things. x.append("20") calls a method on the object bound to the name x. The method mutates the object, so it now has a new value. x = "30" binds the name x to a new object, the string "30". This binding happens in the local namespace so it doesn't affect the value seen by the caller. You have to change how you think about variables. In Python, a variable is not a storage location into which values are put, it is a reference to an object - a name given to an object. Assignment binds a name to a value. When you call a function, the names of the formal parameters are bound to the values passed in to the function. Parameters are *always* passed by reference. The names inside the function are bound to the same objects as the names outside the function, so if you call a mutating method on the object, like list.append(), the change will be seen externally. If you rebind the name inside the function, this has no effect on the bindings external to the function. I hope this helps. There is a fundamental shift in the way you think about names that is needed to grok Python. Once you get it much will become clearer - The Zen of Python says, "Namespaces are one honking great idea -- let's do more of those!" so it's important to understand namespaces :-) This may help: http://effbot.org/zone/python-objects.htm Kent > > > ------------------------------------------------------------------------ > *From:* Adam [mailto:adam.jtm30 at gmail.com] > *Sent:* Tuesday, 6 December 2005 1:49 p.m. > *To:* Hans Dushanthakumar > *Subject:* Re: [Tutor] How to Pass lists by value > > On 06/12/05, *Hans Dushanthakumar* > wrote: > > > Hi folks, > How do I pass a list by value to a function. > > The foll: snippet of code produces the output as shown: > > Code: > ----- > def junk(x): > x.append("20") > return x > > a = ["10"] > b = junk(a) > > print b > print a > > > Output: > ------- >>>> > b = ['10', '20'] > a = ['10', '20'] > > This indicates that the variable "a" was passed by reference > because the > function alters its value in the main script. > > However, the following code produces a slightly diff output: > > Code: > ----- > > def junk(x): > x = "30" > return x > > a = ["10"] > b = junk(a) > > print "b = ", b > print "a = ", a > > Output: > ------- >>>> > b = 30 > a = ['10'] > > In this case, "a" seems to be passed by value, because the value is > unchanged even after the call to the function. > > > Question is, in the 1st scenario, how do I forcefully pass the > variable > by value rather than reference. Why is there a difference between the > two scenarios? > > Cheers > Hans > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > def junk(x): > x.append("20") > return x > > a = ["10"] > b = junk(a[:]) > > That should give you what you're looking for a[:] will pass the values > of a. > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > From din22 at earthlink.net Tue Dec 6 05:00:38 2005 From: din22 at earthlink.net (david) Date: Mon, 5 Dec 2005 22:00:38 -0600 Subject: [Tutor] terminology Message-ID: <001401c5fa19$9e7373e0$0201a8c0@d71bh5mhis9p7o> suppose you have a list of words and you want to unambiguously identify each word in the list with the shortest number of characters. for instance a list like : kill, kiss, take i would want to get take just by typing t. but you would have to type kil or kis to get kill or kiss. where should i start googling? is this a matter of sorting? i was thinking of trees for some reason. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051205/df4e6ceb/attachment.html From john at fouhy.net Tue Dec 6 05:04:57 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 6 Dec 2005 17:04:57 +1300 Subject: [Tutor] terminology In-Reply-To: <001401c5fa19$9e7373e0$0201a8c0@d71bh5mhis9p7o> References: <001401c5fa19$9e7373e0$0201a8c0@d71bh5mhis9p7o> Message-ID: <5e58f2e40512052004m18543e8dy@mail.gmail.com> On 06/12/05, david wrote: > suppose you have a list of words and you want to unambiguously identify > each word in the list with the shortest number of characters. > for instance a list like : kill, kiss, take > i would want to get take just by typing t. > but you would have to type kil or kis to get kill or kiss. > where should i start googling? is this a matter of sorting? > i was thinking of trees for some reason. Look for tries :-) http://en.wikipedia.org/wiki/Trie or http://www.nist.gov/dads/HTML/trie.html I think there's a couple of good python implementations around that you could google for.. -- John. From dyoo at hkn.eecs.berkeley.edu Tue Dec 6 08:16:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 5 Dec 2005 23:16:39 -0800 (PST) Subject: [Tutor] terminology In-Reply-To: <5e58f2e40512052004m18543e8dy@mail.gmail.com> Message-ID: > > suppose you have a list of words and you want to unambiguously identify > > each word in the list with the shortest number of characters. > > for instance a list like : kill, kiss, take > > i would want to get take just by typing t. > > but you would have to type kil or kis to get kill or kiss. > > where should i start googling? is this a matter of sorting? > > i was thinking of trees for some reason. > > Look for tries :-) http://en.wikipedia.org/wiki/Trie or > http://www.nist.gov/dads/HTML/trie.html > > I think there's a couple of good python implementations around that you > could google for.. Hi David, Alternatively, the 'bisect' module might be "good enough". http://www.python.org/doc/lib/module-bisect.html bisect_left() will get us quickly to the right leftmost position (or the leftmost right position? *grin*), if we assuming the list of words is sorted. For example: ####### >>> import bisect >>> words = [x.strip() for x in open('/usr/share/dict/words').readlines()] >>> words.sort() >>> bisect.bisect_left(words, 'kiss') 114279 >>> words[114280] 'kissability' >>> words[114281] 'kissable' >>> words[114282] 'kissableness' ####### The idea is that we can just continue marching across our sorted list of words till we stop finding candidates, once we find our starting position. From gregor at mail.uajy.ac.id Tue Dec 6 06:57:05 2005 From: gregor at mail.uajy.ac.id (Gregorius Gede Wiranarada) Date: Tue, 06 Dec 2005 12:57:05 +0700 Subject: [Tutor] MS ODBC Message-ID: <20051206055705.13678.qmail@mail.uajy.ac.id> hello, how can i connect python to read data from ms access or ms foxpro? regards, Gregor _______________________________________________________________________ Dibuka pendaftaran Program Magister dan Double Degree Pascasarjana UAJY (MM - MTF atau sebaliknya; M.Hum - MTF; M.Hum - MM; MTS. - MM). Penerimaan mahasiswa setiap Mei, September dan Januari. From wescpy at gmail.com Tue Dec 6 09:11:06 2005 From: wescpy at gmail.com (w chun) Date: Tue, 6 Dec 2005 00:11:06 -0800 Subject: [Tutor] How to Pass lists by value In-Reply-To: <4394F1D7.6010702@tds.net> References: <5667508E43F1B740BCFA57FF46E3530002A62761@nav-akl-exch-c.newton.navman.com> <4394F1D7.6010702@tds.net> Message-ID: <78b3a9580512060011xc5b324dw216d8725c04f3c5a@mail.gmail.com> On 12/5/05, Kent Johnson wrote: > > You have to change how you think about variables. In Python, a variable > is not a storage location into which values are put, it is a reference > to an object - a name given to an object. Assignment binds a name to a > value. > > When you call a function, the names of the formal parameters are bound > to the values passed in to the function. Parameters are *always* passed > by reference. hans, kent makes some good points here that you need to master. to further elaborate, here are three things to keep in mind: 1) in Python, everything is an object, and all names are just references or aliases to those objects. 2) managing these objects is based on how many references exist that point to an object -- this is called a "reference count." objects are "deallocated" when an object's reference count goes to zero. 3) there are both mutable (can be changed) and immutable (cannot be changed without creating a new one) objects. lists and dictionaries are mutable while numbers, strings, and tuples are not. in your example, you passed in a list by reference. that list had a reference count of 1 when you created it; when you passed it to the function, a new reference, local to the called function, is created for that object, incrementing its reference count by 1, and now it totals 2. (a side note here: that only mutable objects have methods.) you then called a method [[].append()] which alters that object, which it did. in the function, you only had access to the 2nd alias to the list, but it doesn't matter whether you used this one, or called the list's method from the global code using the original reference as either would affect the list the way it did. note that when the function concluded, the local variable went away, decrementing the list object's reference count back down to 1. in your second example, you almost did the exact same thing. you *did* pass the list in as an argument, creating another reference to the list object, incrementing its reference count to 2. but in this case, you immediately "wiped" access to that object by reassigning that variable name to point to something else, an integer. all you did here was to decrement the reference count to the list object by one (back to 1). the outer print gave the expected output because you just passed that integer object back to the calling function. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Tue Dec 6 12:07:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Dec 2005 06:07:59 -0500 Subject: [Tutor] MS ODBC In-Reply-To: <20051206055705.13678.qmail@mail.uajy.ac.id> References: <20051206055705.13678.qmail@mail.uajy.ac.id> Message-ID: <4395710F.8020406@tds.net> Gregorius Gede Wiranarada wrote: >hello, >how can i connect python to read data from ms access or ms foxpro? > I don't know about FoxPro. You can connect to MS Access from a Windows client using adodbapi (free) http://adodbapi.sourceforge.net/ eGenix mxODBC (commercial) http://www.egenix.com/files/python/mxODBC.html Search comp.lang.python for more ideas. Kent From din22 at earthlink.net Tue Dec 6 13:50:58 2005 From: din22 at earthlink.net (david) Date: Tue, 6 Dec 2005 06:50:58 -0600 Subject: [Tutor] terminology References: <001401c5fa19$9e7373e0$0201a8c0@d71bh5mhis9p7o> Message-ID: <000d01c5fa63$b4ad4dd0$0201a8c0@d71bh5mhis9p7o> thanks for tries and bisect. this led me to the wikipedia article http://en.wikipedia.org/wiki/Search_algorithm which was where i was looking to start. so, i think the simplest approach to search through a short list would be a brute force algorithm. like so : get a letter and compare it to every item in the list if there is only one match: we're done if there is more than one: get another letter rinse and repeat this is usually how i figure out how to code stuff. anyway, i am thinking there could be other brute-force algorithms that would accomplish the same thing. please correct me if i use any terminology incorrectly. so a trie would be a data structure for holding your list in. and bisect would be an algorithm for searching through a list. and determining which data structures and which algorithms to use would be depending on the nature of the list and what you wanted to do with it. have i got this right? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051206/2ed8f297/attachment.htm From cpu.crazy at gmail.com Tue Dec 6 15:57:50 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 6 Dec 2005 08:57:50 -0600 Subject: [Tutor] Timer Message-ID: <66ca60fc0512060657q46e0789avfc75303e7a374e75@mail.gmail.com> I'd like to make a 30 minute timer. How an I do that? With time? Thanks, Joe -- There are 10 different types of people in the world. Those who understand binary and those who don't. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051206/fe6aef4c/attachment.htm From ajikoe at gmail.com Tue Dec 6 16:12:35 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 6 Dec 2005 16:12:35 +0100 Subject: [Tutor] Timer In-Reply-To: <66ca60fc0512060657q46e0789avfc75303e7a374e75@mail.gmail.com> References: <66ca60fc0512060657q46e0789avfc75303e7a374e75@mail.gmail.com> Message-ID: Probably the simplest thing is to make the computer sleep in a specific time. Example: def main(): time.sleep(2) # sleeping 2 second print 'finish' Cheers, pujo On 12/6/05, Joseph Quigley wrote: > > I'd like to make a 30 minute timer. How an I do that? With time? > Thanks, > Joe > > -- > There are 10 different types of people in the world. > Those who understand binary and those who don't. > > _______________________________________________ > 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/20051206/5268b4ca/attachment.html From kent37 at tds.net Tue Dec 6 16:24:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Dec 2005 10:24:38 -0500 Subject: [Tutor] Timer In-Reply-To: <66ca60fc0512060657q46e0789avfc75303e7a374e75@mail.gmail.com> References: <66ca60fc0512060657q46e0789avfc75303e7a374e75@mail.gmail.com> Message-ID: <4395AD36.6090400@tds.net> Joseph Quigley wrote: > I'd like to make a 30 minute timer. How an I do that? With time? A little context would be helpful. If you are writing a standalone app that just needs to wait 30 minutes, then do something, use time.sleep(). If the program needs to be able to do something else at the same time as the timer is running, you will have to put the sleep() call in a separate thread. threading.Timer will do this for you, see this recipe for an example of its use: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440476 If you are running in a GUI app, the GUI toolkit may have a timer you can use, for example in Tkinter widgets have an after() method that schedules a callback for a future time; wxPython has wx.FutureCall. http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm http://www.wxpython.org/docs/api/wx.FutureCall-class.html Kent From cpu.crazy at gmail.com Tue Dec 6 16:28:40 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 6 Dec 2005 09:28:40 -0600 Subject: [Tutor] Timer In-Reply-To: References: <66ca60fc0512060657q46e0789avfc75303e7a374e75@mail.gmail.com> Message-ID: <66ca60fc0512060728t351f2fcs661175f61ffb1755@mail.gmail.com> thanks. I'm also trying time.time() I hope one works. One disadvantage though, now that i think of it is that time.sleep() freezes everything and I don't think I want that but I'll try it anyway. On 12/6/05, Pujo Aji wrote: > > Probably the simplest thing is to make the computer sleep in a specific > time. > > Example: > def main(): > time.sleep(2) # sleeping 2 second > print 'finish' > > Cheers, > pujo > > On 12/6/05, Joseph Quigley wrote: > > > I'd like to make a 30 minute timer. How an I do that? With time? > > Thanks, > > Joe > > > > -- > > There are 10 different types of people in the world. > > Those who understand binary and those who don't. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- There are 10 different types of people in the world. Those who understand binary and those who don't. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051206/568f70da/attachment.htm From lists at janeden.org Tue Dec 6 16:29:59 2005 From: lists at janeden.org (Jan Eden) Date: Tue, 6 Dec 2005 16:29:59 +0100 Subject: [Tutor] Exception repeated in a loop Message-ID: Hi, I use the following loop to parse some HTML code: for record in data: try: parser.feed(record['content']) except HTMLParseError, (msg): print "!!!Parsing error in", record['page_id'], ": ", msg Now after HTMLParser encounters a parse error in one record, it repeats to execute the except statement for all following records - why is that? !!!Parsing error in 8832 : bad end tag: '', at line 56568, column 1647999 !!!Parsing error in 8833 : bad end tag: '', at line 56568, column 1651394 !!!Parsing error in 8834 : bad end tag: '', at line 56568, column 1654789 !!!Parsing error in 8835 : bad end tag: '', at line 56568, column 1658184 Thanks. Jan -- Hanlon's Razor: Never attribute to malice that which can be adequately explained by stupidity. From bgailer at alum.rpi.edu Tue Dec 6 16:45:28 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 06 Dec 2005 07:45:28 -0800 Subject: [Tutor] MS ODBC In-Reply-To: <20051206055705.13678.qmail@mail.uajy.ac.id> References: <20051206055705.13678.qmail@mail.uajy.ac.id> Message-ID: <7.0.0.16.0.20051206073310.01d2db08@alum.rpi.edu> At 09:57 PM 12/5/2005, Gregorius Gede Wiranarada wrote: >hello, >how can i connect python to read data from ms access or ms foxpro? foxpro: Install (if you have not) Mark Hammond's pywin32 to get the odbc module http://sourceforge.net/project/showfiles.php?group_id=78018 Create a Data Source (if you don't already have one) for the Visual FoxPro Driver. Call it VFP (or whatever). If you don't know what this means, ask. import odbc vfpconn = odbc.odbc(VFP) vfpcursor = vfpconn.cursor() vfpcursor.execute(sql) # this can be more complex, involving substitution parameters rows = vfp..cursor.fetchall() Also see http://www.python.org/windows/win32/odbc.html From Pawel_Kraszewski at wp.pl Tue Dec 6 16:47:34 2005 From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Tue, 6 Dec 2005 16:47:34 +0100 Subject: [Tutor] Exception repeated in a loop In-Reply-To: References: Message-ID: <200512061647.34780.Pawel_Kraszewski@wp.pl> Dnia wtorek, 6 grudnia 2005 16:29, Jan Eden napisa?: > Hi, > > I use the following loop to parse some HTML code: > > for record in data: > try: > parser.feed(record['content']) > except HTMLParseError, (msg): > print "!!!Parsing error in", record['page_id'], ": ", msg > > Now after HTMLParser encounters a parse error in one record, it repeats to > execute the except statement for all following records - why is that? Short answer: because you told Python to do so... Long answer: My hint for students having such problems is to execute their code with a pencil on a hardcopy. They read aloud what the program currently does - usually they spot the error during the first "reading". Your code being "read loud" 1. begin loop 2. attempt to execute parser.feed 3. abort attempt if it fails, showing the error 4. take next loop So - you take next loop regardless of the failure or not. There are two ways out of here. I wrote them "aloud", to transcribe into python as an excersize: (Notice the difference between this and your original) I) 1. attempt to 2. begin loop 3. abort attempt if it fails, showing the error 4. take next loop II) 1. begin loop 2. attempt to execute parser.feed 3. abort attempt if it fails, showing the error AND breaking the loop 4. take next loop Hope this helps, -- Pawel Kraszewski From lists at janeden.org Tue Dec 6 17:24:21 2005 From: lists at janeden.org (Jan Eden) Date: Tue, 6 Dec 2005 17:24:21 +0100 Subject: [Tutor] Exception repeated in a loop In-Reply-To: <200512061647.34780.Pawel_Kraszewski@wp.pl> Message-ID: Hi Pawel, Pawel Kraszewski wrote on 06.12.2005: >Dnia wtorek, 6 grudnia 2005 16:29, Jan Eden napisa?: >> Hi, >> >> I use the following loop to parse some HTML code: >> >> for record in data: >> try: >> parser.feed(record['content']) >> except HTMLParseError, (msg): >> print "!!!Parsing error in", record['page_id'], ": ", msg >> >> Now after HTMLParser encounters a parse error in one record, it repeats to >> execute the except statement for all following records - why is that? > >Short answer: because you told Python to do so... > >Long answer: > >My hint for students having such problems is to execute their code with a >pencil on a hardcopy. They read aloud what the program currently does - >usually they spot the error during the first "reading". > >Your code being "read loud" > >1. begin loop >2. attempt to execute parser.feed >3. abort attempt if it fails, showing the error >4. take next loop > >So - you take next loop regardless of the failure or not. There are two ways >out of here. I wrote them "aloud", to transcribe into python as an excersize: > >(Notice the difference between this and your original) > >I) > >1. attempt to >2. begin loop >3. abort attempt if it fails, showing the error >4. take next loop > >II) >1. begin loop >2. attempt to execute parser.feed >3. abort attempt if it fails, showing the error AND breaking the loop >4. take next loop > Thanks, I tested your suggestion, which works fine. But I don't understand the problem with my original code. If the parser raises an exception for a certain record, it should print the error message and move on to the next record in the loop. Why would I need the break statement? What's more - if the break statement is executed, all following records will never be parsed. I still don't understand why failure of a single record affects the other records. Thanks, Jan -- There's no place like ~/ From cpu.crazy at gmail.com Tue Dec 6 17:34:45 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 6 Dec 2005 10:34:45 -0600 Subject: [Tutor] Timer Message-ID: <66ca60fc0512060834s5e8d3e8dn360efa421d4064c1@mail.gmail.com> Sorry, this is a little console project to tell me when there new headlines on slashdot.org using their rss file. All it does is see if there's something different and if there is it will tell you. Here's my timer: while True: if count > 1800: break time.sleep(1) count += 1 Or should I just do: time.sleep(1800)? > A little context would be helpful. If you are writing a standalone app > that just needs to wait 30 minutes, then do something, use time.sleep(). > > If the program needs to be able to do something else at the same time as > the timer is running, you will have to put the sleep() call in a > separate thread. threading.Timer will do this for you, see this recipe > for an example of its use: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440476 > > If you are running in a GUI app, the GUI toolkit may have a timer you > can use, for example in Tkinter widgets have an after() method that > schedules a callback for a future time; wxPython has wx.FutureCall. > > http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm > http://www.wxpython.org/docs/api/wx.FutureCall-class.html > > Kent > > > -- There are 10 different types of people in the world. Those who understand binary and those who don't. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051206/24516f22/attachment.htm From SNelson at midwaygames.com Tue Dec 6 17:36:22 2005 From: SNelson at midwaygames.com (Nelson, Scott) Date: Tue, 6 Dec 2005 10:36:22 -0600 Subject: [Tutor] Exception repeated in a loop Message-ID: <64F7B8E2954C73499806C1E59A848C1D078EFA72@CHICAGO-EX1.chicago.midway.com> An unhandled exception immediately stops the execution of your code. A handled exception (try/except) does not stop code execution (unless you explicitly tell it to). This shows how a handled exception does not stop code execution: try: raise Exception except: print 'caught exception' print 'fell through' Hope this helps... -Scott -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Jan Eden Sent: Tuesday, December 06, 2005 10:24 AM To: Pawel Kraszewski; tutor at python.org Subject: Re: [Tutor] Exception repeated in a loop Hi Pawel, Pawel Kraszewski wrote on 06.12.2005: >Dnia wtorek, 6 grudnia 2005 16:29, Jan Eden napisa?: >> Hi, >> >> I use the following loop to parse some HTML code: >> >> for record in data: >> try: >> parser.feed(record['content']) >> except HTMLParseError, (msg): >> print "!!!Parsing error in", record['page_id'], ": ", msg >> >> Now after HTMLParser encounters a parse error in one record, it repeats to >> execute the except statement for all following records - why is that? > >Short answer: because you told Python to do so... > >Long answer: > >My hint for students having such problems is to execute their code with a >pencil on a hardcopy. They read aloud what the program currently does - >usually they spot the error during the first "reading". > >Your code being "read loud" > >1. begin loop >2. attempt to execute parser.feed >3. abort attempt if it fails, showing the error >4. take next loop > >So - you take next loop regardless of the failure or not. There are two ways >out of here. I wrote them "aloud", to transcribe into python as an excersize: > >(Notice the difference between this and your original) > >I) > >1. attempt to >2. begin loop >3. abort attempt if it fails, showing the error >4. take next loop > >II) >1. begin loop >2. attempt to execute parser.feed >3. abort attempt if it fails, showing the error AND breaking the loop >4. take next loop > Thanks, I tested your suggestion, which works fine. But I don't understand the problem with my original code. If the parser raises an exception for a certain record, it should print the error message and move on to the next record in the loop. Why would I need the break statement? What's more - if the break statement is executed, all following records will never be parsed. I still don't understand why failure of a single record affects the other records. Thanks, Jan -- There's no place like ~/ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From p.atmatzidis at gmail.com Tue Dec 6 17:48:46 2005 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Tue, 6 Dec 2005 18:48:46 +0200 Subject: [Tutor] Python Script Problem. Simple sql problem & py problems. Message-ID: Hello, I wrote my first script (ever) in Python. It's an interface for handling the proftpd virtual users. I wrote the script after reading the howto. You can see the browse[1] the code anytime. These are my first steps in programming in general so.. the problems that this script has until now, are two: One is that MySQL's autoincrement works only the first time, I can't add users after I exit the program the first time. This version or the script is a re-write. The first one, had no problem with that. The users were getting the respective key in auto every time I was about to add a user. The second one is more python specific I guess. The programs prints the "Exiting" string on exit one time for every action I do. Which means that if I add 4 users, I'll see 4 time exiting printed. If I add 2 users and delete 1 user, I'll see 3 exiting prints and so on. Any idea why does this happen? Best Regards, Panagiotis Atmatzidis [1] http://beast.merseine.nu/files/other/vuhandle.html ps. This script comes with a specific proftpd configuration file, it does not make sense without it. If someone wants to test this please drop a mail and I'll upload the proftpd conf file. From kent37 at tds.net Tue Dec 6 18:00:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Dec 2005 12:00:10 -0500 Subject: [Tutor] Exception repeated in a loop In-Reply-To: References: Message-ID: <4395C39A.5000807@tds.net> Jan Eden wrote: >Hi, > >I use the following loop to parse some HTML code: > >for record in data: > try: > parser.feed(record['content']) > except HTMLParseError, (msg): > print "!!!Parsing error in", record['page_id'], ": ", msg > >Now after HTMLParser encounters a parse error in one record, it repeats to execute the except statement for all following records - why is that? > >!!!Parsing error in 8832 : bad end tag: '', at line 56568, column 1647999 >!!!Parsing error in 8833 : bad end tag: '', at line 56568, column 1651394 >!!!Parsing error in 8834 : bad end tag: '', at line 56568, column 1654789 >!!!Parsing error in 8835 : bad end tag: '', at line 56568, column 1658184 > The parser processes up to the error. It never recovers from the error. HTMLParser has an internal buffer and buffer pointer that is never advanced when an error is detected; each time you call feed() it tries to parse the remaining data and gets the same error again. Take a look at HTMLParser.goahead() in Lib/HTMLParser.py if you are interested in the details. IIRC HTMLParser is not noted for handling badly formed HTML. Beautiful Soup, ElementTidy, or HTML Scraper might be a better choice depending on what you are trying to do. Kent From lists at janeden.org Tue Dec 6 18:02:41 2005 From: lists at janeden.org (Jan Eden) Date: Tue, 6 Dec 2005 18:02:41 +0100 Subject: [Tutor] Exception repeated in a loop In-Reply-To: <64F7B8E2954C73499806C1E59A848C1D078EFA72@CHICAGO-EX1.chicago.midway.com> Message-ID: Hi, Nelson, Scott wrote on 06.12.2005: >An unhandled exception immediately stops the execution of your code. > >A handled exception (try/except) does not stop code execution (unless >you explicitly tell it to). > >This shows how a handled exception does not stop code execution: > >try: > raise Exception >except: > print 'caught exception' >print 'fell through' This is exactly what I need Python to do: Raise the exception for a certain record and go on with the following records. I just do not see why the same loop is raised over and over again - obviously because of the same malformed HTML tag. Adding a break statement causes Python to skip all following records, which is not what I need. Thanks, Jan -- There are two major products that come out of Berkeley: LSD and UNIX. We don't believe this to be a coincidence. - Jeremy S. Anderson From lists at janeden.org Tue Dec 6 18:05:22 2005 From: lists at janeden.org (Jan Eden) Date: Tue, 6 Dec 2005 18:05:22 +0100 Subject: [Tutor] Exception repeated in a loop In-Reply-To: <4395C39A.5000807@tds.net> Message-ID: Kent Johnson wrote on 06.12.2005: >The parser processes up to the error. It never recovers from the >error. HTMLParser has an internal buffer and buffer pointer that is >never advanced when an error is detected; each time you call feed() >it tries to parse the remaining data and gets the same error again. >Take a look at HTMLParser.goahead() in Lib/HTMLParser.py if you are >interested in the details. > Aha! That's what I needed to know. Thanks to all who answered. - Jan -- I'd never join any club that would have the likes of me as a member. - Groucho Marx From kjzz.webmaster at riomail.maricopa.edu Tue Dec 6 18:09:00 2005 From: kjzz.webmaster at riomail.maricopa.edu (KJZZ Webmaster) Date: Tue, 6 Dec 2005 10:09:00 -0700 Subject: [Tutor] Displaying Separate Tables for Specific Dictionary Keys References: Message-ID: <008001c5fa87$c21c9830$2300a8c0@RADIOWORLD.RIO.MARICOPA.EDU> I have a list of dictionaries. Each dictionary has a key named "program". I can display a html table for the entire list of dictionaries, however... I would like to display distinct html tables for each program while also displaying the playlist for the day in chronological order (the list has already been sorted according to time). One note: If a program starts at midnight and ends at 3am. Then starts again at 11pm and goes to midnight, it should be displayed in two tables at both the start and the end of the playlist for the day. To view the table as it is currently displayed, see: http://playlists.deserttalk.org/playlists/displayTableByHourQuestion To view the slightly modified code, see: http://playlists.deserttalk.org/playlists/displayTableByHourQuestion.txt Thanks kindly, John T. From SNelson at midwaygames.com Tue Dec 6 18:16:13 2005 From: SNelson at midwaygames.com (Nelson, Scott) Date: Tue, 6 Dec 2005 11:16:13 -0600 Subject: [Tutor] Auto package install? Message-ID: <64F7B8E2954C73499806C1E59A848C1D078EFB56@CHICAGO-EX1.chicago.midway.com> The Zen of Python (http://www.python.org/doc/Humor.html#zen) states: "There should be one-- and preferably only one --obvious way to do it." I'm searching for the obvious Pythonic way to achieve automated package installation (I believe Perl's CPAN can be used to accomplish this in Perl?). I'd like to have a way where a Python script can automatically download/install/update the versions of packages it needs to run. I'm looking to avoid requiring the users of my scripts to manually download and install a pile of packages (with potential for user error) just to run my scripts. I use mostly common packages such as wxPython. My scripts may eventually get out to > 100 people over 3 states so I want to minimize administration and potential for user error. I'm aware of the very handy CheeseShop (http://www.python.org/pypi), but this doesn't automate the installation process. I've done some googling and found ciphon (http://sourceforge.net/projects/pythonsiphon) and pypan (http://starship.python.net/crew/theller/pypan/), but both seem somewhat abandoned and incomplete. EasyInstall (http://peak.telecommunity.com/DevCenter/EasyInstall) seems new and I'm willing to hear any experiences with it. I also glanced thru c.l.p and most of the discussions seem a few years old and bordered on holy wars with no real obvious resolution... So, what is the obvious way to accomplish this? If no such solution exists currently, what do people consider "best practices" when releasing scripts dependent on other packages to a number of users? Thanks for the help. I'm relatively new to the group and it has been great so far! -Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051206/017d1650/attachment-0001.html From nephish at xit.net Tue Dec 6 18:22:02 2005 From: nephish at xit.net (nephish) Date: Tue, 06 Dec 2005 17:22:02 +0000 Subject: [Tutor] whats the best command to end a program Message-ID: <1133889722.11128.2.camel@localhost.localdomain> Hey there, what would be the best command to end a program with. i have an app that i want to start every day at 6am from cron but i want it to shutdown at 4pm i was going to check by time on every loop if int(time.strftime(%H)) > 4: some end the program command else: continue what would be best used here ? From kent37 at tds.net Tue Dec 6 18:48:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Dec 2005 12:48:44 -0500 Subject: [Tutor] Displaying Separate Tables for Specific Dictionary Keys In-Reply-To: <008001c5fa87$c21c9830$2300a8c0@RADIOWORLD.RIO.MARICOPA.EDU> References: <008001c5fa87$c21c9830$2300a8c0@RADIOWORLD.RIO.MARICOPA.EDU> Message-ID: <4395CEFC.2040704@tds.net> KJZZ Webmaster wrote: > I have a list of dictionaries. Each dictionary has a key named "program". > > I can display a html table for the entire list of dictionaries, however... > > I would like to display distinct html tables for each program while also > displaying the playlist for the day in chronological order (the list has > already been sorted according to time). > > One note: If a program starts at midnight and ends at 3am. Then starts > again at 11pm and goes to midnight, it should be displayed in two tables at > both the start and the end of the playlist for the day. You need to make two changes - put the table generation in a loop, and group the records by program. The looping part is pretty simple, the grouping can be done by itertools.groupby(). I owe the list an explanation of groupby() so let me try it. Suppose you have a list of dicts containing the names of cities and states, and you want to print them out with headings by state: >>> cities = [ ... { 'city' : 'Harford', 'state' : 'Connecticut' }, ... { 'city' : 'Boston', 'state' : 'Massachusetts' }, ... { 'city' : 'Worcester', 'state' : 'Massachusetts' }, ... { 'city' : 'Albany', 'state' : 'New York' }, ... { 'city' : 'New York City', 'state' : 'New York' }, ... { 'city' : 'Yonkers', 'state' : 'New York' }, ... ] First let me explain operator.itemgetter(). This function is a factory for new functions. It creates functions that access items using a key. In this case I will use it to create a function to access the 'state' item of each record: >>> from operator import itemgetter >>> getState = itemgetter('state') >>> getState >>> getState(cities[0]) 'Connecticut' >>> [ getState(record) for record in cities ] ['Connecticut', 'Massachusetts', 'Massachusetts', 'New York', 'New York', 'New York'] So itemgetter('state') is a function that accepts a dict as an argument and returns the 'state' item of the dict. Calling getState(d) is the same as writing d['state']. What does this have to do with groupby? >>> from itertools import groupby >>> help(groupby) Help on class groupby in module itertools: class groupby(__builtin__.object) | groupby(iterable[, keyfunc]) -> create an iterator which returns | (key, sub-iterator) grouped by each value of key(value). groupby() takes an optional second argument which is a function to extract keys from the data. getState() is just the function we need. >>> groups = groupby(cities, getState) >>> groups Hmm. That's a bit opaque. groupby() returns an iterator. Each item in the iterator is a pair of (key, group). Let's take a look: >>> for key, group in groups: ... print key, group ... Connecticut Massachusetts New York Hmm. Still a bit opaque :-) The 'key' part is clear - that's the state, extracted with the itemgetter getState - but the group is _another_ iterator. One way to look at it's contents is to use a nested loop. Note that I have to call groupby again, the old iterator was consumed by the last loop: >>> for key, group in groupby(cities, getState): ... print key ... for record in group: ... print record ... Connecticut {'city': 'Harford', 'state': 'Connecticut'} Massachusetts {'city': 'Boston', 'state': 'Massachusetts'} {'city': 'Worcester', 'state': 'Massachusetts'} New York {'city': 'Albany', 'state': 'New York'} {'city': 'New York City', 'state': 'New York'} {'city': 'Yonkers', 'state': 'New York'} Well that makes more sense! And it's not too far from the original requirement, we just need to pretty up the output a bit. How about this: >>> for key, group in groupby(cities, getState): ... print 'State:', key ... for record in group: ... print ' ', record['city'] ... State: Connecticut Harford State: Massachusetts Boston Worcester State: New York Albany New York City Yonkers Other than misspelling Hartford (sheesh, and I grew up in Connecticut!) that's not too bad! In your case, the output is more complex so you probably want to make some functions to break it into smaller pieces, but the overall idea should work for you. Kent From Hans.Dushanthakumar at navman.com Tue Dec 6 21:24:28 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Wed, 7 Dec 2005 09:24:28 +1300 Subject: [Tutor] How to Pass lists by value Message-ID: <5667508E43F1B740BCFA57FF46E3530002A62F59@nav-akl-exch-c.newton.navman.com> Thanks for your valuable feedback guys. Cheers Hans -----Original Message----- From: w chun [mailto:wescpy at gmail.com] Sent: Tuesday, 6 December 2005 9:11 p.m. To: Hans Dushanthakumar Cc: tutor at python.org Subject: Re: How to Pass lists by value On 12/5/05, Kent Johnson wrote: > > You have to change how you think about variables. In Python, a > variable is not a storage location into which values are put, it is a > reference to an object - a name given to an object. Assignment binds a > name to a value. > > When you call a function, the names of the formal parameters are bound > to the values passed in to the function. Parameters are *always* > passed by reference. hans, kent makes some good points here that you need to master. to further elaborate, here are three things to keep in mind: 1) in Python, everything is an object, and all names are just references or aliases to those objects. 2) managing these objects is based on how many references exist that point to an object -- this is called a "reference count." objects are "deallocated" when an object's reference count goes to zero. 3) there are both mutable (can be changed) and immutable (cannot be changed without creating a new one) objects. lists and dictionaries are mutable while numbers, strings, and tuples are not. in your example, you passed in a list by reference. that list had a reference count of 1 when you created it; when you passed it to the function, a new reference, local to the called function, is created for that object, incrementing its reference count by 1, and now it totals 2. (a side note here: that only mutable objects have methods.) you then called a method [[].append()] which alters that object, which it did. in the function, you only had access to the 2nd alias to the list, but it doesn't matter whether you used this one, or called the list's method from the global code using the original reference as either would affect the list the way it did. note that when the function concluded, the local variable went away, decrementing the list object's reference count back down to 1. in your second example, you almost did the exact same thing. you *did* pass the list in as an argument, creating another reference to the list object, incrementing its reference count to 2. but in this case, you immediately "wiped" access to that object by reassigning that variable name to point to something else, an integer. all you did here was to decrement the reference count to the list object by one (back to 1). the outer print gave the expected output because you just passed that integer object back to the calling function. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From python-tutor at toddmaynard.com Tue Dec 6 21:28:37 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Tue, 6 Dec 2005 15:28:37 -0500 Subject: [Tutor] Auto package install? In-Reply-To: <64F7B8E2954C73499806C1E59A848C1D078EFB56@CHICAGO-EX1.chicago.midway.com> References: <64F7B8E2954C73499806C1E59A848C1D078EFB56@CHICAGO-EX1.chicago.midway.com> Message-ID: <200512061528.37391.python-tutor@toddmaynard.com> Scott, Take a look at setuptools: http://peak.telecommunity.com/DevCenter/setuptools It should handle everything you are looking for with ease. Turbogears ( http://turbogears.org )is a real world project that uses it. So far it seems to be flexible and reliabe for me. Good Luck, --Todd Maynard On Tuesday 06 December 2005 12:16, Nelson, Scott wrote: > The Zen of Python (http://www.python.org/doc/Humor.html#zen) states: > > "There should be one-- and preferably only one --obvious way to do it." > > > > I'm searching for the obvious Pythonic way to achieve automated package > installation (I believe Perl's CPAN can be used to accomplish this in > Perl?). I'd like to have a way where a Python script can automatically > download/install/update the versions of packages it needs to run. I'm > looking to avoid requiring the users of my scripts to manually download > and install a pile of packages (with potential for user error) just to > run my scripts. I use mostly common packages such as wxPython. My > scripts may eventually get out to > 100 people over 3 states so I want > to minimize administration and potential for user error. > > > > I'm aware of the very handy CheeseShop (http://www.python.org/pypi), but > this doesn't automate the installation process. I've done some googling > and found ciphon (http://sourceforge.net/projects/pythonsiphon) and > pypan (http://starship.python.net/crew/theller/pypan/), but both seem > somewhat abandoned and incomplete. EasyInstall > (http://peak.telecommunity.com/DevCenter/EasyInstall) seems new and I'm > willing to hear any experiences with it. > > > > I also glanced thru c.l.p and most of the discussions seem a few years > old and bordered on holy wars with no real obvious resolution... > > > > So, what is the obvious way to accomplish this? If no such solution > exists currently, what do people consider "best practices" when > releasing scripts dependent on other packages to a number of users? > > > > Thanks for the help. I'm relatively new to the group and it has been > great so far! > > > > -Scott From alan.gauld at freenet.co.uk Tue Dec 6 21:35:37 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 6 Dec 2005 20:35:37 -0000 Subject: [Tutor] How to Pass lists by value References: <5667508E43F1B740BCFA57FF46E3530002A62761@nav-akl-exch-c.newton.navman.com><4394F1D7.6010702@tds.net> <78b3a9580512060011xc5b324dw216d8725c04f3c5a@mail.gmail.com> Message-ID: <000a01c5faa4$9dbd8130$0a01a8c0@xp> Lots of good stuff from Wes snipped... > (a side note here: that only mutable objects have methods.) But this is not quite true. Strings are immutable and have lots of methods and even tuples and plain integers have methods (albeit Pythons magic operator methods) which can be subclassed and overridden. But to be honest that minor detail really makes no difference to the basic point of Wes' message, that everuything is an object, but only some objects are mutable Alan G. From pythontut at pusspaws.net Tue Dec 6 21:40:43 2005 From: pythontut at pusspaws.net (dave s) Date: Tue, 6 Dec 2005 20:40:43 +0000 Subject: [Tutor] smtplib mail header problem Message-ID: <200512062040.46277.pythontut@pusspaws.net> Hi all, I have a python script that works out & emails my employer with parts that I have used. It has been great for 11ish months, now all my mail is classed as spam & junked :( Apparently the reason for it being junked is ... 'No subject' and 'No Sender' I set up a small test script to isolate the problem using the core of the email code ... #!/usr/bin/env python # -*- coding: iso8859_1 -*- from smtplib import SMTP from time import sleep, strftime from datetime import datetime import sys email_SMTP = 'mail.pusspaws.net' email_addr = 'jk at pusspaws.net' def email_test(): for trys in xrange(10): try: mail_server = SMTP(email_SMTP) mail_server.login('XXXX', 'XXXX') subject = 'Test Email' from_ = 'Dave Selby' to = email_addr return_path = email_addr blog="""Hi,\n\nThis is just a test""" msg = mail_headers(subject, from_, to, return_path) +'\r\n\r\n'+blog mail_server.sendmail(subject , email_addr, msg) mail_server.quit() # If we get to here, all is well, drop out of the loop break except: print 'Mailing error ... Re-trying ... '+str(trys+1)+' of 10\n' sleep(300) if trys==9: raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) def mail_headers(subject, from_, to, return_path): """ Generate a formatted mail header string """ header = 'Return-Path: ' + return_path header = header + '\r\nFrom: ' + from_ header = header + '\r\nReply-To: ' + return_path header = header + '\r\nTo: ' + to header = header + '\r\nSubject: '+subject now=datetime.now() day = now.strftime('%a') date = now.strftime('%d %b %Y %X') header = header + '\r\nDate : ' + day + ', ' + date + ' -0000\r\n' return (header) email_test() From this I receive the following .... Return-Path: Delivered-To: jk at pusspaws.user Received: (qmail 21696 invoked by uid 503); 6 Dec 2005 20:35:48 -0000 Received: from unknown (HELO localhost.localdomain) (chubb at 86.130.36.111) by host201.com with SMTP; 6 Dec 2005 20:35:48 -0000 Return-Path: jk at pusspaws.net From: Dave Selby Reply-To: jk at pusspaws.net To: jk at pusspaws.net Subject: Test Email Date: Tue, 06 Dec 2005 20:35:47 -0000 X-Bogosity: Ham, tests=bogofilter, spamicity=0.288675, version=0.95.2 X-UID: Status: R X-Status: NGC X-KMail-EncryptionState: X-KMail-SignatureState: X-KMail-MDN-Sent: Hi, This is just a test I cannot seem to set the top 'Return-path' correctly, any ideas how I do this ? also I have a sender so I am unsure why the spam filter picked this out. Any suggestions Cheers dave From Liam.Clarke-Hutchinson at business.govt.nz Tue Dec 6 22:13:40 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 7 Dec 2005 10:13:40 +1300 Subject: [Tutor] smtplib mail header problem Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1547@chbnt01.alpha.wd.govt.nz> Hi Dave, IIRC The first argument to sendmail() is the name of the account that's sending... So when you include your subject there, it seems your ISP is somewhat forgiving. Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of dave s Sent: Wednesday, 7 December 2005 9:41 a.m. To: Python Tutor Subject: [Tutor] smtplib mail header problem Hi all, I have a python script that works out & emails my employer with parts that I have used. It has been great for 11ish months, now all my mail is classed as spam & junked :( Apparently the reason for it being junked is ... 'No subject' and 'No Sender' I set up a small test script to isolate the problem using the core of the email code ... #!/usr/bin/env python # -*- coding: iso8859_1 -*- from smtplib import SMTP from time import sleep, strftime from datetime import datetime import sys email_SMTP = 'mail.pusspaws.net' email_addr = 'jk at pusspaws.net' def email_test(): for trys in xrange(10): try: mail_server = SMTP(email_SMTP) mail_server.login('XXXX', 'XXXX') subject = 'Test Email' from_ = 'Dave Selby' to = email_addr return_path = email_addr blog="""Hi,\n\nThis is just a test""" msg = mail_headers(subject, from_, to, return_path) +'\r\n\r\n'+blog mail_server.sendmail(subject , email_addr, msg) mail_server.quit() # If we get to here, all is well, drop out of the loop break except: print 'Mailing error ... Re-trying ... '+str(trys+1)+' of 10\n' sleep(300) if trys==9: raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) def mail_headers(subject, from_, to, return_path): """ Generate a formatted mail header string """ header = 'Return-Path: ' + return_path header = header + '\r\nFrom: ' + from_ header = header + '\r\nReply-To: ' + return_path header = header + '\r\nTo: ' + to header = header + '\r\nSubject: '+subject now=datetime.now() day = now.strftime('%a') date = now.strftime('%d %b %Y %X') header = header + '\r\nDate : ' + day + ', ' + date + ' -0000\r\n' return (header) email_test() >From this I receive the following .... Return-Path: Delivered-To: jk at pusspaws.user Received: (qmail 21696 invoked by uid 503); 6 Dec 2005 20:35:48 -0000 Received: from unknown (HELO localhost.localdomain) (chubb at 86.130.36.111) by host201.com with SMTP; 6 Dec 2005 20:35:48 -0000 Return-Path: jk at pusspaws.net From: Dave Selby Reply-To: jk at pusspaws.net To: jk at pusspaws.net Subject: Test Email Date: Tue, 06 Dec 2005 20:35:47 -0000 X-Bogosity: Ham, tests=bogofilter, spamicity=0.288675, version=0.95.2 X-UID: Status: R X-Status: NGC X-KMail-EncryptionState: X-KMail-SignatureState: X-KMail-MDN-Sent: Hi, This is just a test I cannot seem to set the top 'Return-path' correctly, any ideas how I do this ? also I have a sender so I am unsure why the spam filter picked this out. Any suggestions Cheers dave _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From wescpy at gmail.com Tue Dec 6 22:24:34 2005 From: wescpy at gmail.com (w chun) Date: Tue, 6 Dec 2005 13:24:34 -0800 Subject: [Tutor] How to Pass lists by value In-Reply-To: <000a01c5faa4$9dbd8130$0a01a8c0@xp> References: <5667508E43F1B740BCFA57FF46E3530002A62761@nav-akl-exch-c.newton.navman.com> <4394F1D7.6010702@tds.net> <78b3a9580512060011xc5b324dw216d8725c04f3c5a@mail.gmail.com> <000a01c5faa4$9dbd8130$0a01a8c0@xp> Message-ID: <78b3a9580512061324u712fb788jf7d23ed776d5a74b@mail.gmail.com> On 12/6/05, Alan Gauld wrote: > Lots of good stuff from Wes snipped... > > (a side note here: that only mutable objects have methods.) > > But this is not quite true. Strings are immutable and have lots > of methods and even tuples and plain integers have methods oh POO. i *knew* i shouldn't have been replying in the middle of the nite. yes, they all really do. string methods are even available "to the public," i.e. by default already defined, unlike those where you have to override them to "make them work." what i really wanted to say was that because objects are passed in by reference, any mutable object's methods that modify it will (obviously) propagate those changes regardless of where you reference that object. i think the main point was altering a mutable object vs. reassigning the reference to another object. thanks for keeping me on my toes alan! -- wesley ps. i'd like to encourage folks to attend the next PyCon this Feb in Dallas -- the registration fees have been kept low for one purpose: to get you to come even if your company is not footing the bill. it's great fun, you'll learn a lot, and i hope to meet some of you there! more info at http://us.pycon.org ... earlybird reg ends Dec 31! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at freenet.co.uk Tue Dec 6 22:49:36 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 6 Dec 2005 21:49:36 -0000 Subject: [Tutor] whats the best command to end a program References: <1133889722.11128.2.camel@localhost.localdomain> Message-ID: <004d01c5faae$f3ae7f40$0a01a8c0@xp> > what would be the best command to end a program with. If its Tkinter (or another GuI) there will be a quit command somewhere. Call that to ensure that the GUI framework gets tidied up properly. For normal programs import sys; sys.exit() You can pass an exit code to the outdside world as a parameter to exit too. or just raise SystemExit will work. > i have an app that i want to start every day at 6am from cron > but i want it to shutdown at 4pm OK, here you probably want system.exit(n) with a proper error code so that cron can tell if it worked or not... BTW strftime('%H') returns the hour in 24 hour format so you will want to check for 16 not 4... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Tue Dec 6 23:08:19 2005 From: pythontut at pusspaws.net (dave s) Date: Tue, 6 Dec 2005 22:08:19 +0000 Subject: [Tutor] smtplib mail header problem In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1547@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1547@chbnt01.alpha.wd.govt.nz> Message-ID: <200512062208.21489.pythontut@pusspaws.net> On Tuesday 06 December 2005 21:13, Liam Clarke-Hutchinson wrote: > Hi Dave, > > IIRC The first argument to sendmail() is the name of the account that's > sending... So when you include your subject there, it seems your ISP is > somewhat forgiving. > > Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic > Development > DDI +64 3 962 2639 | Fax +64 3 962 6220 > www.med.govt.nz Thanks for that heads up, I will amend the code & try to re-send it ... Dave From nephish at xit.net Tue Dec 6 23:17:57 2005 From: nephish at xit.net (nephish) Date: Tue, 06 Dec 2005 16:17:57 -0600 Subject: [Tutor] whats the best command to end a program In-Reply-To: <004d01c5faae$f3ae7f40$0a01a8c0@xp> References: <1133889722.11128.2.camel@localhost.localdomain> <004d01c5faae$f3ae7f40$0a01a8c0@xp> Message-ID: <1133907477.23759.1.camel@localhost.localdomain> right, greater > 16 was what i ment. he he it is not a gui. is raise SystemExit built in ? thanks gents sk On Tue, 2005-12-06 at 21:49 +0000, Alan Gauld wrote: > > what would be the best command to end a program with. > > If its Tkinter (or another GuI) there will be a quit command > somewhere. Call that to ensure that the GUI framework gets > tidied up properly. > > For normal programs > > import sys; sys.exit() > > You can pass an exit code to the outdside world as > a parameter to exit too. > > or just > > raise SystemExit > > will work. > > > i have an app that i want to start every day at 6am from cron > > but i want it to shutdown at 4pm > > OK, here you probably want system.exit(n) with a proper error > code so that cron can tell if it worked or not... > > BTW strftime('%H') returns the hour in 24 hour format so you > will want to check for 16 not 4... > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From cpu.crazy at gmail.com Tue Dec 6 23:16:49 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 6 Dec 2005 16:16:49 -0600 Subject: [Tutor] whats the best command to end a program Message-ID: <66ca60fc0512061416x17f89bfw3fa4c2a00d12a40a@mail.gmail.com> if int(time.strftime(%H)) > 4: > some end the program command > else: > continue > > what would be best used here ? > > I would use raise SystemExit But another possibility is: import sys then to exit sys.exit() -- There are 10 different types of people in the world. Those who understand binary and those who don't. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051206/b84dfee3/attachment.html From Liam.Clarke-Hutchinson at business.govt.nz Tue Dec 6 23:23:41 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 7 Dec 2005 11:23:41 +1300 Subject: [Tutor] smtplib mail header problem Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B154C@chbnt01.alpha.wd.govt.nz> Okay, just checked the docs - "sendmail( from_addr, to_addrs, msg[, mail_options, rcpt_options]) Note: The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents. The SMTP does not modify the message headers in any way." So my guess is that the spam agent is checking that from_addr, and getting an invalid email address and spitting the dummy. Most ISPs won't allow an invalid from_addr, although mine does.. Regards, Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of dave s Sent: Wednesday, 7 December 2005 11:08 a.m. To: Python Tutor Subject: Re: [Tutor] smtplib mail header problem On Tuesday 06 December 2005 21:13, Liam Clarke-Hutchinson wrote: > Hi Dave, > > IIRC The first argument to sendmail() is the name of the account > that's sending... So when you include your subject there, it seems > your ISP is somewhat forgiving. > > Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic > Development DDI +64 3 962 2639 | Fax +64 3 962 6220 > www.med.govt.nz Thanks for that heads up, I will amend the code & try to re-send it ... Dave _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From wescpy at gmail.com Tue Dec 6 23:47:52 2005 From: wescpy at gmail.com (w chun) Date: Tue, 6 Dec 2005 14:47:52 -0800 Subject: [Tutor] Python Script Problem. Simple sql problem & py problems. In-Reply-To: References: Message-ID: <78b3a9580512061447t1f1fc02aq4b657fd93418bf3c@mail.gmail.com> > I wrote my first script (ever) in Python. > : > The second one is more python specific I guess. The programs prints > the "Exiting" string on exit one time for every action I do. Which > means that if I add 4 users, I'll see 4 time exiting printed. If I add > 2 users and delete 1 user, I'll see 3 exiting prints and so on. Any > idea why does this happen? hi, and welcome to Python! for your 1st script, it looks pretty good. as far as the 2nd problem is concerned, it's all in the cheers() function. first of all, your code won't compile due to indentation issues. i assume that your if stmts are lined up like this: if choc == '1': sql_adduser(sql_host, sql_user, sql_pass, sql_dtbs, groupid) cheers() ... rather than how they're formatted online. more importantly, it appears that you are calling cheers() in a recursive way, for functionality that doesn't require it. it is because you call cheers() again and again recursively that lead you to seeing "Exiting" for each user you enter (or for any action). what you should do is to put things in a while loop to do the desired repeat until the single exit: def cheers(): while True: print "Type [1] to add a user" print "Type [2] to delete a user" print "Type [3] to list the dbase" print "Type [99] to install (default installation, see README)" print "Type anything else to exit" choc = raw_input("Choose [1, 2, 3]: ") if choc == '1': sql_adduser(sql_host, sql_user, sql_pass, sql_dtbs, groupid) elif choc == '2': sql_deluser(sql_host, sql_user, sql_pass, sql_dtbs) elif choc == '3': sql_listusers(sql_host, sql_user, sql_pass, sql_dtbs) elif choc == '99': sql_install(sql_host, sql_user, sql_pass, sql_dtbs) else: break print "Exiting" cheers() hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From cpu.crazy at gmail.com Tue Dec 6 23:54:11 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 6 Dec 2005 16:54:11 -0600 Subject: [Tutor] Read XML Message-ID: <66ca60fc0512061454r3337ec9fh3facd90aab923a3f@mail.gmail.com> How do I read xml? The python documentation doesn't help me. Or, how can I remove the (tags?) ? thanks, Joe -- There are 10 different types of people in the world. Those who understand binary and those who don't. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051206/49290a9e/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Dec 7 00:31:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 6 Dec 2005 15:31:37 -0800 (PST) Subject: [Tutor] Read XML In-Reply-To: <66ca60fc0512061454r3337ec9fh3facd90aab923a3f@mail.gmail.com> Message-ID: On Tue, 6 Dec 2005, Joseph Quigley wrote: > How do I read xml? The python documentation doesn't help me. Or, how can > I remove the (tags?) ? Hi Joseph, The modules in the standard library for XML reading should be functional. For example, here is some 'xml.dom.minidom' example code to show how we can parse and extract stuff out of XML text: ###### >>> import xml.dom.minidom >>> xml.dom.minidom.parseString >>> >>> tree = xml.dom.minidom.parseString("test") >>> tree >>> >>> >>> tree.getElementsByTagName('world') [] >>> worldNode = tree.getElementsByTagName('world')[0] >>> worldNode >>> >>> worldNode.firstChild >>> worldNode.firstChild.data u'test' ###### There's a larger example of minidom here: http://www.python.org/doc/lib/dom-example.html But to tell the truth; I don't like minidom too much these days. *grin* The code above is a bit verbose, and the usage of the standard Python XML parsers is a little less than obvious because much of the design was borrowed from Java's SAX and DOM parsers. You might want to take a look at some third-party modules like ElementTree or Amara instead. http://effbot.org/zone/element-index.htm http://uche.ogbuji.net/uche.ogbuji.net/tech/4suite/amara/ I don't have too much experience with Amara, and I hope someone else can give an example with it. With ElementTree, the code to grab the 'test' text looks like this: ###### >>> from elementtree import ElementTree >>> tree = ElementTree.fromstring("test") >>> tree.findtext('world') 'test' ###### Good luck! From bgailer at alum.rpi.edu Wed Dec 7 03:58:49 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 06 Dec 2005 18:58:49 -0800 Subject: [Tutor] Timer In-Reply-To: <66ca60fc0512060657q46e0789avfc75303e7a374e75@mail.gmail.co m> References: <66ca60fc0512060657q46e0789avfc75303e7a374e75@mail.gmail.com> Message-ID: <7.0.0.16.0.20051206185826.02222d90@alum.rpi.edu> At 06:57 AM 12/6/2005, Joseph Quigley wrote: >I'd like to make a 30 minute timer. How an I do that? With time? import time time.sleep(30) From Liam.Clarke-Hutchinson at business.govt.nz Wed Dec 7 04:18:46 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 7 Dec 2005 16:18:46 +1300 Subject: [Tutor] Timer Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1554@chbnt01.alpha.wd.govt.nz> Hi, time.sleep() takes an argument as seconds. Regards, Liam Clarke -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of bob Sent: Wednesday, 7 December 2005 3:59 p.m. To: Joseph Quigley; tutor at python.org Subject: Re: [Tutor] Timer At 06:57 AM 12/6/2005, Joseph Quigley wrote: >I'd like to make a 30 minute timer. How an I do that? With time? import time time.sleep(30) _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From kent37 at tds.net Wed Dec 7 04:22:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 06 Dec 2005 22:22:50 -0500 Subject: [Tutor] Read XML In-Reply-To: <66ca60fc0512061454r3337ec9fh3facd90aab923a3f@mail.gmail.com> References: <66ca60fc0512061454r3337ec9fh3facd90aab923a3f@mail.gmail.com> Message-ID: <4396558A.40509@tds.net> Joseph Quigley wrote: > How do I read xml? The python documentation doesn't help me. > Or, how can I remove the (tags?) ? If you want to strip out all the tags and just leave the text, Strip-o-Gram might do it. http://www.zope.org/Members/chrisw/StripOGram There was a thread here recently about other tools for stripping text out of HTML but I can't find it. Kent From wkranec at gmail.com Wed Dec 7 06:22:20 2005 From: wkranec at gmail.com (wkranec@gmail.com) Date: Wed, 7 Dec 2005 00:22:20 -0500 Subject: [Tutor] Exceptions vs. Status Codes Message-ID: <32b77d5a0512062122o4bdcf935q4098740997e2d065@mail.gmail.com> Hi, I have a general question regarding programming style which may or may not have an answer. Is it a better practice to have a function raise an exception on error, so that the error can be caught; or return a status code indicating that the function was unsuccessful? Like I said, I don't expect an answer that works in general, but some guidelines about when one approach is more appropriate would be appreciated. Thanks, Bill From wescpy at gmail.com Wed Dec 7 09:29:15 2005 From: wescpy at gmail.com (w chun) Date: Wed, 7 Dec 2005 00:29:15 -0800 Subject: [Tutor] smtplib mail header problem In-Reply-To: <200512062040.46277.pythontut@pusspaws.net> References: <200512062040.46277.pythontut@pusspaws.net> Message-ID: <78b3a9580512070029n20c494f6g87b5a1290dba6ac5@mail.gmail.com> > It has been great for 11ish months, now all my mail is classed as > spam & junked :( dave, i'm a little surprised by this. if your code has been working for almost a year and suddently breaks, that can only be explained by 1 or 2 things: 1. your code was modified 2. the server was modified (or both). things just don't all of a sudden break. do you know what changed in the system? > Apparently the reason for it being junked is ... > 'No subject' and 'No Sender' > : > from_ = 'Dave Selby' from just observing your From line, it looks like you need a space between your name and the '<' that begins the e-mail address. i don't think that without the space, it's a valid RFC2822 e-mail address. i don't know if this is the entire problem, but it can't hurt to remedy it and see if it helps. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at freenet.co.uk Wed Dec 7 13:00:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 7 Dec 2005 12:00:39 -0000 Subject: [Tutor] Exceptions vs. Status Codes References: <32b77d5a0512062122o4bdcf935q4098740997e2d065@mail.gmail.com> Message-ID: <007501c5fb25$d7824e10$0a01a8c0@xp> > not have an answer. Is it a better practice to have a function raise > an exception on error, so that the error can be caught; or return a > status code indicating that the function was unsuccessful? Exceptions are nearly always better. For some of the reasons why, see my tutorial topic on Error Handling Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Dec 7 14:01:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 07 Dec 2005 08:01:54 -0500 Subject: [Tutor] Exceptions vs. Status Codes In-Reply-To: <32b77d5a0512062122o4bdcf935q4098740997e2d065@mail.gmail.com> References: <32b77d5a0512062122o4bdcf935q4098740997e2d065@mail.gmail.com> Message-ID: <4396DD42.7040003@tds.net> wkranec at gmail.com wrote: > Hi, > > I have a general question regarding programming style which may or may > not have an answer. Is it a better practice to have a function raise > an exception on error, so that the error can be caught; or return a > status code indicating that the function was unsuccessful? Hmm, this is a harder question than I thought :-) My first response was to say, in general using exceptions to indicate errors is more useful. But after a little reflection I realized that I use status codes of a sort quite a bit as well. Long ago and far away I programmed for Mac OS 9. This OS was meticulous about returning status codes from every system call. Well-written client code had to be equally meticulous about checking the codes and returning them back to callers. As a result, any function that used the OS would return an error code; actual return values would be returned by reference in a parameter to the function. Client code ended up looking like this: int errno; if (errno=doSomethingImportant() != noError) return errno; int param; if (errno=getParameter(¶m) != noError) return errno; if (errno=doSomethingWithParam(param) != noError) return errno; etc. As you can see, the code is dominated by the error handling, even though all it does is return the error codes to the caller, it doesn't actually handle any errors. The same code written using exceptions would be stripped of all the error handling code, like this: doSomethingImportant(); int param = getParameter(); doSomethingWithParam(param); This is *far* more readable and much easier to write. Also consider the consequences of forgetting to check an error code. Suppose that due to ignorance or lazinesss the first code had been written like the second, ignoring the error codes. If an error does occur, it won't be recognized until some secondary failure occurs; maybe doSomethingWithParam() will crash catastrophically because doSomethingImportant() didn't suceed. The second code doesn't have to do anything special to handle exceptions; at some higher level in the code it can catch exceptions and deal with them. If there is no exception handler an uncaught exception will terminate the program with a stack trace showing the location of the error. On the other hand, when a function is returning a value and there is a reasonable sentinal value for failure (such as None) and the caller can't reasonably proceed without the returned value, I will sometimes return None to signify failure instead of raising an exception. For example, suppose our program needs to load a Foo resource that may be found in one of two places. We have functions getFooFromA() and getFooFromB() that return either a Foo or None. Client code is simple: foo = getFooFromA() if foo is None: foo = getFooFromB() if foo is None: raise FooNotFoundError If the getFooFromX() functions raised FooNotFoundError themselves, the client code would be try: foo = getFooFromA() except FooNotFoundError: foo = getFooFromB() Hmm, not a very convincing example! Maybe I should be using exceptions more :-) Kent From ps_python3 at yahoo.co.in Wed Dec 7 15:01:10 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Wed, 7 Dec 2005 14:01:10 +0000 (GMT) Subject: [Tutor] regular expressions Message-ID: <20051207140110.67988.qmail@web8404.mail.in.yahoo.com> hi, I am a new python learner. i am trying to parse a file using regular expressions. LOCUS NM_005417 4145 bp mRNA linear PRI 04-DEC-2005 DEFINITION Homo sapiens v-src sarcoma (Schmidt-Ruppin A-2) viral oncogene homolog (avian) (SRC), transcript variant 1, mRNA. ACCESSION NM_005417 VERSION NM_005417.3 GI:38202215 CDS 450..2060 /gene="SRC" /EC_number="2.7.1.112" /note="v-src avian sarcoma (Schmidt-Ruppin A-2) viral oncogene homolog; protooncogene SRC, Rous sarcoma; tyrosine-protein kinase SRC-1; tyrosine kinase pp60c-src; go_component: ubiquitin ligase complex [goid 0000151] [evidence NAS] [pmid 14976165]; go_function: ATP binding [goid 0005524] [evidence IEA]; go_function: nucleotide binding [goid 0000166] [evidence IEA]; go_function: protein binding [goid 0005515] [evidence IPI] [pmid 15546919]; go_function: protein binding [goid 0005515] [evidence IPI] [pmid 15749833]; go_function: transferase activity [goid 0016740] [evidence IEA]; go_function: SH3/SH2 adaptor activity [goid 0005070] [evidence TAS] [pmid 9020193]; go_function: protein-tyrosine kinase activity [goid 0004713] [evidence IEA]; go_function: protein-tyrosine kinase activity [goid 0004713] [evidence TAS] [pmid 9020193]; go_process: protein kinase cascade [goid 0007243] [evidence TAS] [pmid 9020193]; go_process: signal complex formation [goid 0007172] [evidence TAS] [pmid 9924018]; go_process: protein amino acid phosphorylation [goid 0006468] [evidence IEA]" /codon_start=1 /product="proto-oncogene tyrosine-protein kinase SRC" I want to pullout LOCUS, go_process, go_function, go_compartment into columns so that i can fill my postgres tables. although i know well to some extenet sql stuff, i am finding it difficult to get these elements from this raw text. an idea that might have worked however, due to incompetence it did not work. i seek help of this forum. import re f1 = open('this_raw_text','r') dat = f1.readlines() pat1 = re.compile('LOCUS') pat2 = re.compile('go_component') pat3 = re.compile('go_process') pat4 = re.compile('go_function') for line in dat: a = pat1.match(line) b = pat2.match(line) c = pat3.match(line) d = pat4.match(line) loc = a.group(1) comp =b.group(1) proc = c. group(1) func = d. group(1) print loc+'\t'+func print loc+'\t'+comp print loc+'\t'+func print loc+'\t'+proc Traceback (most recent call last): File "", line 6, in ? loc = a.group(1) IndexError: no such group In the second attempt: >>>for line in dat: a = pat1.match(line) b = pat2.match(line) c = pat3.match(line) d = pat4.match(line) print a, b, c, d <_sre.SRE_Match object at 0x00D53330> None None None rest all lines are NONE. However, b,c,d are there in the file. I do not know if this is the correct procedure. Can any one help me please. thanks a lot. M __________________________________________________________ Yahoo! India Matrimony: Find your partner now. Go to http://yahoo.shaadi.com From work at infomaniak.ch Wed Dec 7 15:15:54 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Wed, 07 Dec 2005 15:15:54 +0100 Subject: [Tutor] cas and python Message-ID: <20051207141554.GB2016@obs.unige.ch> hi, does one of you knows if there is a python module which implements CAS(Central Authentication Service): https://clearinghouse.ja-sig.org/wiki/display/CAS/Home thanks in advance Ced. -- Cedric BRINER Geneva - Switzerland From cpu.crazy at gmail.com Wed Dec 7 16:13:52 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 7 Dec 2005 09:13:52 -0600 Subject: [Tutor] Read XML Message-ID: <66ca60fc0512070713x7d5df8abqf45abdd63c0009c7@mail.gmail.com> > > > Joseph Quigley wrote: > > How do I read xml? The python documentation doesn't help me. > > Or, how can I remove the (tags?) ? > > If you want to strip out all the tags and just leave the text, > Strip-o-Gram might do it. > http://www.zope.org/Members/chrisw/StripOGram > > There was a thread here recently about other tools for stripping text > out of HTML but I can't find it. > > Kent Thanks. This looks like it will do the trick. -- There are 10 different types of people in the world. Those who understand binary and those who don't. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051207/aa920d76/attachment.html From AKolinski at nriindustries.com Wed Dec 7 15:51:16 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Wed, 7 Dec 2005 09:51:16 -0500 Subject: [Tutor] to process data from several dictionaries In-Reply-To: <000601c5f8ec$a482c110$0201a8c0@d71bh5mhis9p7o> Message-ID: Let's forget for the time being my previous topic (files - strings - lists). As a result of (not only) my efforts I arrived to the point that I have data I need but I do not know how to process them. Form each (game) file a dictionary is created containing player names (key) and the scores + boards played (tuple), ex.: from file 1 - {'Chrabalowski': [(21.0, 24)], 'Stankiewicz': [(-28.0, 24)], ... more ...} from file 2 - {'Chrabalowski': [(45.0, 25)], 'Orlicka': [(-27.0, 25)], ... more ...} from file 3 - {'Chrabalowski': [(-23.0, 25)], 'Stankiewicz': [(20.0, 25)], ... more ...}, etc. Eventually I will have 10 files to process. I need help how to calculate a final ranking for each player using individual data. Many names will be repeated but there will be some that appear only once or twice. So for "Chrabalowski" we'll have: (21.0 + 45.0 - 23.0)/(24 + 25 + 25), and for "Stankiewicz: (- 28.0 + 20.0)/(24 + 25) I have no clue how to do it. Maybe dictionaries are not good for that, maybe I should be using lists of lists? Please help. _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051207/e2aa2fcf/attachment.html From kent37 at tds.net Wed Dec 7 17:03:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 07 Dec 2005 11:03:54 -0500 Subject: [Tutor] to process data from several dictionaries In-Reply-To: References: Message-ID: <439707EA.1080806@tds.net> Andrzej Kolinski wrote: > > Let's forget for the time being my previous topic (files - strings - > lists). As a result of (not only) my efforts I arrived to the point that > I have data I need but I do not know how to process them. Form each > (game) file a dictionary is created containing player names (key) and > the scores + boards played (tuple), ex.: > from file 1 - > {'Chrabalowski': [(21.0, 24)], 'Stankiewicz': [(-28.0, 24)], ... more ...} > from file 2 - > {'Chrabalowski': [(45.0, 25)], 'Orlicka': [(-27.0, 25)], ... more ...} > from file 3 - > {'Chrabalowski': [(-23.0, 25)], 'Stankiewicz': [(20.0, 25)], ... more > ...}, etc. > > Eventually I will have 10 files to process. I need help how to calculate > a final ranking for each player using individual data. Many names will > be repeated but there will be some that appear only once or twice. So > for "Chrabalowski" we'll have: > (21.0 + 45.0 - 23.0)/(24 + 25 + 25), > and for "Stankiewicz: > (- 28.0 + 20.0)/(24 + 25) I think you would be better off creating a single dictionary whose keys are the player names and values are a list of tuples of game data. In your example the dict would be {'Chrabalowski': [(21.0, 24),(45.0, 25),(-23.0, 25)], 'Stankiewicz': [(-28.0, 24)(20.0, 25)], 'Orlicka': [(-27.0, 25)], ... more ...} Then it will be much simpler to process each player because all his data will be in one place. There is a compact idiom for creating a dict where the values are accumulated in lists. Imagine you have a dict, key and value d, k, v and you want to append v to the list associated with k. A simple approach might be something like this: lst = d.get(k) if lst is None: lst = [] d[k] = lst lst.append(v) Note there is no need to assign d[k] = lst in the case where d[k] is already defined, because the list returned by get() is still in the dict and will be modified by the append(). (See the recent thread "How to Pass lists by value" if you don't understand this part.) dicts actually have a (confusingly named) method which already does most of the above - dict.setdefault(). Using setdefault() the above code can be written as lst = d.setdefault(k, []) lst.append(v) or even simpler: d.setdefault(k, []).append(v) Kent From ps_python3 at yahoo.co.in Wed Dec 7 17:58:20 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Wed, 7 Dec 2005 16:58:20 +0000 (GMT) Subject: [Tutor] regular expressions Message-ID: <20051207165820.8429.qmail@web8403.mail.in.yahoo.com> sorry for repost. awaiting to hear from some members. a scientist suggested me to try biopython. This point is not just with genbank sequences. what will i do if i have to parse a paragraph for some expression. thanks again. hi, I am a new python learner. i am trying to parse a file using regular expressions. LOCUS NM_005417 4145 bp mRNA linear PRI 04-DEC-2005 DEFINITION Homo sapiens v-src sarcoma (Schmidt-Ruppin A-2) viral oncogene homolog (avian) (SRC), transcript variant 1, mRNA. ACCESSION NM_005417 VERSION NM_005417.3 GI:38202215 CDS 450..2060 /gene="SRC" /EC_number="2.7.1.112" /note="v-src avian sarcoma (Schmidt-Ruppin A-2) viral oncogene homolog; protooncogene SRC, Rous sarcoma; tyrosine-protein kinase SRC-1; tyrosine kinase pp60c-src; go_component: ubiquitin ligase complex [goid 0000151] [evidence NAS] [pmid 14976165]; go_function: ATP binding [goid 0005524] [evidence IEA]; go_function: nucleotide binding [goid 0000166] [evidence IEA]; go_function: protein binding [goid 0005515] [evidence IPI] [pmid 15546919]; go_function: protein binding [goid 0005515] [evidence IPI] [pmid 15749833]; go_function: transferase activity [goid 0016740] [evidence IEA]; go_function: SH3/SH2 adaptor activity [goid 0005070] [evidence TAS] [pmid 9020193]; go_function: protein-tyrosine kinase activity [goid 0004713] [evidence IEA]; go_function: protein-tyrosine kinase activity [goid 0004713] [evidence TAS] [pmid 9020193]; go_process: protein kinase cascade [goid 0007243] [evidence TAS] [pmid 9020193]; go_process: signal complex formation [goid 0007172] [evidence TAS] [pmid 9924018]; go_process: protein amino acid phosphorylation [goid 0006468] [evidence IEA]" /codon_start=1 /product="proto-oncogene tyrosine-protein kinase SRC" I want to pullout LOCUS, go_process, go_function, go_compartment into columns so that i can fill my postgres tables. although i know well to some extenet sql stuff, i am finding it difficult to get these elements from this raw text. an idea that might have worked however, due to incompetence it did not work. i seek help of this forum. import re f1 = open('this_raw_text','r') dat = f1.readlines() pat1 = re.compile('LOCUS') pat2 = re.compile('go_component') pat3 = re.compile('go_process') pat4 = re.compile('go_function') for line in dat: a = pat1.match(line) b = pat2.match(line) c = pat3.match(line) d = pat4.match(line) loc = a.group(1) comp =b.group(1) proc = c. group(1) func = d. group(1) print loc+'\t'+func print loc+'\t'+comp print loc+'\t'+func print loc+'\t'+proc Traceback (most recent call last): File "", line 6, in ? loc = a.group(1) IndexError: no such group In the second attempt: >>>for line in dat: a = pat1.match(line) b = pat2.match(line) c = pat3.match(line) d = pat4.match(line) print a, b, c, d <_sre.SRE_Match object at 0x00D53330> None None None rest all lines are NONE. However, b,c,d are there in the file. I do not know if this is the correct procedure. Can any one help me please. thanks a lot. M ____________________________________________________ Yahoo! India Matrimony: Find your partner now. Go to http://yahoo.shaadi.com From dyoo at hkn.eecs.berkeley.edu Wed Dec 7 18:22:00 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 7 Dec 2005 09:22:00 -0800 (PST) Subject: [Tutor] regular expressions In-Reply-To: <20051207140110.67988.qmail@web8404.mail.in.yahoo.com> Message-ID: On Wed, 7 Dec 2005, ps python wrote: > I am a new python learner. i am trying to parse a file using regular > expressions. Hello, Just as an aside: parsing Genbank flat files like this is not such a good idea, because you can get the Genbank XML files instead. For example, your locus NM_005417 has a perfectly good XML representation (using the GBSeq XML format): http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&qty=1&c_start=1&list_uids=38202215&dopt=gbx&dispmax=5&sendto= This format contains the same content as the human-readable text report, but structured in a way that makes it easier to extract elements if we use an XML parser like ElementTree. http://effbot.org/zone/element-index.htm And even if that weren't avaliable, we might also consider using the parsers that come with the BioPython project: http://www2.warwick.ac.uk/fac/sci/moac/currentstudents/peter_cock/python/genbank/ http://www.biopython.org/docs/tutorial/Tutorial004.html#toc13 I guess I'm trying to say: you might not want to reinvent the wheel: it's been done several times already. *grin* If you're doing this to learn regular expressions, that's fine too. Just be aware that those other modules are out there. Let's look at the code. > for line in dat: > a = pat1.match(line) > b = pat2.match(line) > c = pat3.match(line) > d = pat4.match(line) Use the search() method, not the match() method. match() always assumes that the match must start at the very beginning of the line, and it'll miss things if your pattern is in the middle somewhere. There's a discussion about this in the Regex HOWTO: http://www.amk.ca/python/howto/regex/ http://www.amk.ca/python/howto/regex/regex.html#SECTION000720000000000000000 If you have more questions, please feel free to ask. From broek at cc.umanitoba.ca Wed Dec 7 17:01:25 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 07 Dec 2005 10:01:25 -0600 Subject: [Tutor] (no subject) In-Reply-To: <000601c5f87b$7d660130$0201a8c0@d71bh5mhis9p7o> References: <000601c5f87b$7d660130$0201a8c0@d71bh5mhis9p7o> Message-ID: <43970755.5000509@cc.umanitoba.ca> david said unto the world upon 2005-12-03 20:36: > hello again. i think my dig function is working correctly now. > any input on how to save and restore all the rooms and descriptions? > thanks for helping. Hi David, I'm catching up on mail backlog, so I'm a bit late, but I've a suggestion or two about other aspects of your code. > class Room: > def __init__(self,coords): # sniped code > def nextdoor(self,direction): > if direction == 'n': > nextdoor = (self.coords[0], self.coords[1] + 1) > return list(nextdoor) > elif direction == 's': > nextdoor = list((self.coords[0], self.coords[1] - 1)) > return nextdoor > elif direction == 'e': > nextdoor = list((self.coords[0] +1, self.coords[1])) > return nextdoor > elif direction == 'w': > nextdoor = (self.coords[0] -1, self.coords[1]) > return list(nextdoor) This looks a bit ugly to me :-) First, I think it's a bad thing that some of your if clauses convert the value to a list in the nextdoor assignment, and others in the return. It is easier to grok what is going on if the like operations are effected in the same way. Further, why not just return list((self.coords[0], self.coords[1] - 1)) and so forth, dispensing with the nextdoor assignment? (I get that the name has documentation value, but I think it'd be better to do without and put the documentation in a docstring.) If that is changed, then all four clauses are almost identical. That is often a sign that there is a better way. I'd suggest: def nextdoor(self,direction): '''direction -> list of co-ordinates for next location (Perhaps more description here.) ''' xy_difs = {'n':(0, 1), 's':(0, -1), 'e':(1, 0), 'w':(-1, 0)} x_dif, y_dif = xy_difs[direction] return list(self.coords[0] + x_dif, self.coords[1] + y_dif) Once you get used to it, this style is often easier to understand quickly than is a list of if tests. Perhaps best of all, this way makes it much easier to add other directions like 'nw'. Likewise, where you have: > def opdir(direction): > if direction == 'n': > return 's' > if direction == 's': > return 'n' > if direction == 'e': > return 'w' > if direction == 'w': > return 'e' I'd suggest def opdir(direction): return {'n':'s', 's':'n', 'e':'w', 'w':'e'}[direction] Since that has dropped it down to a single line, it might even be better to dispense with the function entirely. But, I'd likely leave it, as the function provides a good place to document just what the point of the code is. A further advantage with what I've given over yours is what occurs if an unexpected value is passed to opdir(). Your version will return None (i.e. fail silently). Mine will raise an exception immediately. >>> {'n':'s', 's':'n', 'e':'w', 'w':'e'}['bad'] Traceback (most recent call last): File "", line 1, in -toplevel- {'n':'s', 's':'n', 'e':'w', 'w':'e'}['bad'] KeyError: 'bad' >>> It often helps track down bugs if you try to arrange things so that the problem surfaces as soon as possible. HTH, Brian vdB From dyoo at hkn.eecs.berkeley.edu Wed Dec 7 18:08:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 7 Dec 2005 09:08:23 -0800 (PST) Subject: [Tutor] cas and python In-Reply-To: <20051207141554.GB2016@obs.unige.ch> Message-ID: On Wed, 7 Dec 2005, Cedric BRINER wrote: > does one of you knows if there is a python module which implements > CAS(Central Authentication Service): > https://clearinghouse.ja-sig.org/wiki/display/CAS/Home Hi Cedric, Not certain, but most likely. See: http://www.zope.org/Members/mrlex/ACUF which appears to be an implementation of a CAS client for Zope. It might be possible to extract their CAS client out of that package. The protocol's documentation in: https://clearinghouse.ja-sig.org/wiki/display/CAS/CAS+2.0+Architecture also looks fairly straightforward, at least at a casual glance. *grin* From dyoo at hkn.eecs.berkeley.edu Wed Dec 7 18:39:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 7 Dec 2005 09:39:47 -0800 (PST) Subject: [Tutor] regular expressions In-Reply-To: <20051207165820.8429.qmail@web8403.mail.in.yahoo.com> Message-ID: On Wed, 7 Dec 2005, ps python wrote: > sorry for repost. awaiting to hear from some members. a scientist > suggested me to try biopython. This point is not just with genbank > sequences. what will i do if i have to parse a paragraph for some > expression. thanks again. Hello, I just want to clarify: we're a volunteer group, so getting answers within two hours is not a guarantee, nor should that level of response be expected. We'll do what we can to help, but some answers take some careful consideration and research. We don't want to spit out the first thing that comes into our heads; otherwise, that could encourage some rude responses like RTFW, and that would be a terrible way to mess the atmosphere here. The page "How to Ask Questions the Smart Way" talks about this in less diplomatic language: http://www.catb.org/~esr/faqs/smart-questions.html#urgent But the idea is: we see your question. At least one of us here on Tutor will reply when we have the time to contribute. If no one responds in some time, we'll say that we don't think we can help you, but we'll try to point you to people who can. Just try not hurry people to answer your questions here. Some of us have day jobs, and others haven't gotten out of their classrooms yet! *grin* Good luck to you. From alan.gauld at freenet.co.uk Wed Dec 7 19:50:45 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 7 Dec 2005 18:50:45 -0000 Subject: [Tutor] regular expressions References: <20051207165820.8429.qmail@web8403.mail.in.yahoo.com> Message-ID: <008f01c5fb5f$21cb1770$0a01a8c0@xp> > a scientist suggested me to try biopython. This point > is not just with genbank sequences. what will i do if > i have to parse a paragraph for some expression. One thing to watch is that re.match() only checks if the pattern is at the beginning of the line. You should maybe consider using re.search()? But I haven't looked in detail so that nay be way off beam... Alan G. From ewalker at micron.com Wed Dec 7 20:06:35 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 7 Dec 2005 12:06:35 -0700 Subject: [Tutor] file permissions Message-ID: <200512071206.35437.ewalker@micron.com> Looking for easiest way to get a files permissions in linux. Thanks From dyoo at hkn.eecs.berkeley.edu Wed Dec 7 20:52:20 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 7 Dec 2005 11:52:20 -0800 (PST) Subject: [Tutor] file permissions In-Reply-To: <200512071206.35437.ewalker@micron.com> Message-ID: On Wed, 7 Dec 2005, Eric Walker wrote: > Looking for easiest way to get a files permissions in linux. Hi Eric, What have you looked at so far? One of the first hits to the Google query "file permission python" comes up with some good information: http://www.faqts.com/knowledge_base/view.phtml/aid/5707/fid/552 Forgive me: I'm giving you a hard time only because it didn't look like you did anything yourself yet. Next time you ask a question, also try to show what you've tried so far to find an answer, so that we know we're not following avenues that you've already pursued. We want to make sure you know how to look for answers. If the existing documentation sucks (and some of Python's documentation does need more work!), then we want to know that too so that we can help improve it by sending comments to the Documentation team. In summary, there's file permission stuff we can extract using the 'stat()' function in the 'os' module: http://www.python.org/doc/lib/os-file-dir.html#l2h-1629 The values we get back from os.stat() are a little obscure, but we can interpret the results using the 'stat' module: http://www.python.org/doc/lib/module-stat.html I'm not sure if there's nicer interface to the permission bits; most material I see on it looks fairly low-level. If you have more questions, please feel free to ask. (But please show what work you've tried so far; that way, we have a better idea of your context.) Good luck! From yann.ledu at noos.fr Wed Dec 7 20:34:49 2005 From: yann.ledu at noos.fr (Yann Le Du) Date: Wed, 7 Dec 2005 20:34:49 +0100 (CET) Subject: [Tutor] Run script automatically in IDLE shell Message-ID: Hello, I'd like to have some scripts run directly inside the IDLE shell when I double click on some properly built shortcut, and not inside the DOS window. I've managed to do that under win98, but failed in win2000 and winXP. I dont' want to have to "run module" inside the idle editor, just direct execution when double clicking on some shortcut. In win98 my shortcut is : C:\Python22\pythonw.exe "C:\PYTHON24\Tools\idle\idle.py" "prog.py" and this opens an IDLE shell window in which my script is executed. Anyone knows how to do that in win2000 and winXP, with python24 ? P.S. I do all this to have accentuated characters (French) correctly displayed, and this is done in the IDLE Shell, but fails inside the DOS window. So this is why I want to have my scripts run directly inside the IDLE shell... -- Yann Le Du http://yledu.free.fr From gsf at panix.com Wed Dec 7 21:42:56 2005 From: gsf at panix.com (Gabriel Farrell) Date: Wed, 7 Dec 2005 15:42:56 -0500 Subject: [Tutor] file permissions In-Reply-To: References: <200512071206.35437.ewalker@micron.com> Message-ID: <20051207204256.GA23611@panix.com> On Wed, Dec 07, 2005 at 11:52:20AM -0800, Danny Yoo wrote: > On Wed, 7 Dec 2005, Eric Walker wrote: > > > Looking for easiest way to get a files permissions in linux. > > Hi Eric, > > What have you looked at so far? I agree with Danny, the question lacks any evidence of prior investigation on the part of the poster, and that makes it a lousy candidate for the helpful guidance of the python tutor list. The documentation on this aspect of python, however, is pretty sparse, and the answer's not exactly intuitive, so I thought I'd mention the effbot's page about the os module as a good place to look, in addition to the documentation Danny listed. http://effbot.org/librarybook/os.htm What he's written there should be able to answer your question. If I may hijack the thread, does anyone more knowledgeable than me know why os.stat and stat are so low-level and esoteric? Am I crazy for wanting to replace oct(stat.S_IMODE(os.stat(thefile)[stat.ST_MODE])) with, say, stat.getmode(os.stat(thefile)) or even os.getmode(thefile) ? From ewalker at micron.com Wed Dec 7 22:51:55 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 7 Dec 2005 14:51:55 -0700 Subject: [Tutor] file permissions In-Reply-To: <20051207204256.GA23611@panix.com> References: <200512071206.35437.ewalker@micron.com> <20051207204256.GA23611@panix.com> Message-ID: <200512071451.55927.ewalker@micron.com> Sorry for the bad question. I did google and found the same pages that Danny mentioned. Just couldn't get the stuff to work, or understand what modules needed to be imported to get them to work. I typically use the tutor list as a last resort. After 4+ hours of playing around with this I made the futile post..... On Wednesday 07 December 2005 01:42 pm, Gabriel Farrell wrote: > On Wed, Dec 07, 2005 at 11:52:20AM -0800, Danny Yoo wrote: > > On Wed, 7 Dec 2005, Eric Walker wrote: > > > Looking for easiest way to get a files permissions in linux. > > > > Hi Eric, > > > > What have you looked at so far? > > I agree with Danny, the question lacks any evidence of prior > investigation on the part of the poster, and that makes it a lousy > candidate for the helpful guidance of the python tutor list. The > documentation on this aspect of python, however, is pretty sparse, and > the answer's not exactly intuitive, so I thought I'd mention the > effbot's page about the os module as a good place to look, in addition > to the documentation Danny listed. > > http://effbot.org/librarybook/os.htm > > What he's written there should be able to answer your question. > > If I may hijack the thread, does anyone more knowledgeable than me > know why os.stat and stat are so low-level and esoteric? Am I crazy > for wanting to replace > > oct(stat.S_IMODE(os.stat(thefile)[stat.ST_MODE])) > > with, say, > > stat.getmode(os.stat(thefile)) > > or even > > os.getmode(thefile) > > ? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From gsf at panix.com Wed Dec 7 22:59:29 2005 From: gsf at panix.com (Gabriel Farrell) Date: Wed, 7 Dec 2005 16:59:29 -0500 Subject: [Tutor] file permissions In-Reply-To: <200512071451.55927.ewalker@micron.com> References: <200512071206.35437.ewalker@micron.com> <20051207204256.GA23611@panix.com> <200512071451.55927.ewalker@micron.com> Message-ID: <20051207215929.GB11312@panix.com> On Wed, Dec 07, 2005 at 02:51:55PM -0700, Eric Walker wrote: > After 4+ hours > of playing around with this I made the futile post..... Don't let the post be futile! Post what you've tried so far and you'll get help. gsf From pythontut at pusspaws.net Wed Dec 7 23:36:00 2005 From: pythontut at pusspaws.net (dave s) Date: Wed, 7 Dec 2005 22:36:00 +0000 Subject: [Tutor] smtplib mail header problem In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B154C@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B154C@chbnt01.alpha.wd.govt.nz> Message-ID: <200512072236.02435.pythontut@pusspaws.net> On Tuesday 06 December 2005 22:23, Liam Clarke-Hutchinson wrote: > Okay, just checked the docs - > > "sendmail( from_addr, to_addrs, msg[, mail_options, rcpt_options]) > > Note: The from_addr and to_addrs parameters are used to construct the > message envelope used by the transport agents. The SMTP does not modify the > message headers in any way." > > So my guess is that the spam agent is checking that from_addr, and getting > an invalid email address and spitting the dummy. > Most ISPs won't allow an invalid from_addr, although mine does.. > > Regards, > > Liam Clarke-Hutchinson > Thanks for that I 'pydoc smtplib' but got somewhat confused :) Dave From dyoo at hkn.eecs.berkeley.edu Wed Dec 7 23:57:27 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 7 Dec 2005 14:57:27 -0800 (PST) Subject: [Tutor] file permissions In-Reply-To: <200512071451.55927.ewalker@micron.com> Message-ID: > > I agree with Danny, the question lacks any evidence of prior > > investigation on the part of the poster, and that makes it a lousy > > candidate for the helpful guidance of the python tutor list. Hi Eric, It there's something I want to avoid, it's the impression that we're looking at each question and saying "That's not worthy of our attention." That's not the real motivation behind asking for more details. The issue is similar to what typically happens in grade school when students learn arithmetic. If I see something like: 1 2 - 1 5 ----- 7 then obviously the student is thinking of something, and doing some sort of operation in their head. And even if that operation isn't quite right, at least we can try to figure out why the student's doing addition in some places, and subtraction in another. Contrast that transparent situation to another. Imagine seeing a student's worksheet: 1 2 - 1 5 ----- WRONG WRONG WRONG where we don't get any information at all about what the student was trying to do. That silliness is what I'd like to avoid, because that's not how things work in the real world. We all have partial knowledge, and we know how to do some things: it's not a binary thing, even if we're dealing with computer programming. > I did google and found the same pages that Danny mentioned. Just > couldn't get the stuff to work, or understand what modules needed to be > imported to get them to work. That's information that would have been useful; we'd then concentrate more on how to filter out the documentation to stuff that's useful to you. For the programs that was written that didn't work, we'd like to see why they didn't work: perhaps it might be a misdesign in the module itself, and perhaps that misdesign can be corrected. (I know, for example, that Tkinter should do more early error trapping on its input. For example: ###### >>> Tkinter.Message('hello world') Traceback (most recent call last): File "", line 1, in ? File "/export/home/dyoo/local/python-2.4//lib/python2.4/lib-tk/Tkinter.py", line 2634, in __init__ Widget.__init__(self, master, 'message', cnf, kw) File "/export/home/dyoo/local/python-2.4//lib/python2.4/lib-tk/Tkinter.py", line 1856, in __init__ BaseWidget._setup(self, master, cnf) File "/export/home/dyoo/local/python-2.4//lib/python2.4/lib-tk/Tkinter.py", line 1834, in _setup self.tk = master.tk AttributeError: 'str' object has no attribute 'tk' ###### There's an error message, but it doesn't really say up front what the real issue is. It's complaining that 'str' doesn't have the 'tk' attribute, which is technically true, but what it really should be saying is that the first argument to Tkinter.Message() has to be a master widget. But that's something that has a technical fix --- we can modify the Tkinter.py library to check for that attribute early, and give a good error message if it see's something wrong. I'm planning to send some patches later through SF because I know people on Tutor occassionally run into these bad error messages.) > > If I may hijack the thread, does anyone more knowledgeable than me > > know why os.stat and stat are so low-level and esoteric? Am I crazy > > for wanting to replace > > > > oct(stat.S_IMODE(os.stat(thefile)[stat.ST_MODE])) > > > > with, say, > > > > stat.getmode(os.stat(thefile)) > > > > or even > > > > os.getmode(thefile) It's possible that no one has considered it a problem yet! *grin* The design is closely mimicing the interface that C provides us. There's a case for making it less obscure, but no one has gone through the effort to make it better yet. It might make a good project for someone to make grabbing file permissions a bit nicer. From alan.gauld at freenet.co.uk Thu Dec 8 00:28:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 7 Dec 2005 23:28:32 -0000 Subject: [Tutor] file permissions References: <200512071206.35437.ewalker@micron.com> Message-ID: <00ab01c5fb85$f06cc710$0a01a8c0@xp> > Looking for easiest way to get a files permissions in linux. > look at the os.stat function. I'm in the middle of documenting its use but you might like to peruse the later sections of the following draft topic http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Dec 8 00:34:48 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 7 Dec 2005 23:34:48 -0000 Subject: [Tutor] Run script automatically in IDLE shell References: Message-ID: <00b701c5fb86$d097b5c0$0a01a8c0@xp> The IDLE documentation (run idle -h) says that idle -r file.py runs the commands in the file. Is that what you are doing? It looks different to your Win98 version. > P.S. I do all this to have accentuated characters (French) correctly > displayed, and this is done in the IDLE Shell, but fails inside the DOS > window. So this is why I want to have my scripts run directly inside the > IDLE shell... Do you have the correct language and locale settings set up in your DOS environment? It should be able to display French characters (and any other Western alphabet - not sure about unicode stuff though) just fine. Alan G. From sweetdaddysiki at hotmail.com Thu Dec 8 05:09:20 2005 From: sweetdaddysiki at hotmail.com (Trent Rigsbee) Date: Thu, 08 Dec 2005 04:09:20 +0000 Subject: [Tutor] My First Program Message-ID: Hi! My first "ever" program that I've created is a simple game called "State Capitals". It's straight forward; 5 simple questions about state capitals in a non-GUI format. Can someone look over my code and offer tips, suggestions, criticism? Also, I'd like to be able to end the program if the user misses 3 questions (i.e., kick them out after the 3rd wrong answer). How can I do this? Thanks! print "\nState Capitals! Answer a or b to the following questions.\n" question = raw_input("Question 1 - What is the capital of NC, a: Raleigh or b: Atlanta? ") if question == "a": print "Yes\n" else: print "WRONG\n" question = raw_input("Question 2 - What is the capital of SC, a: Greenville or b: Columbia? ") if question == "b": print "Yes\n" else: print "WRONG\n" question = raw_input("Question 3 - What is the capital of NY, a: Albany or b: Buffalo?") if question == "a": print "Yes\n" else: print "WRONG\n" question = raw_input("Question 4 - What is the capital of OH, a: Cleveland or b: Columbus? ") if question == "b": print "Yes\n" else: print "WRONG\n" question = raw_input("Question 5 - What is the capital of TX, a: Houston or b: Austin? ") if question == "b": print "Yes\n" else: print "WRONG\n" From tim at johnsons-web.com Thu Dec 8 02:50:46 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 7 Dec 2005 16:50:46 -0900 Subject: [Tutor] Escaping double quotes In-Reply-To: <20051208005622.GD1806@johnsons-web.com> References: <00b701c5fb86$d097b5c0$0a01a8c0@xp> <20051208005622.GD1806@johnsons-web.com> Message-ID: <20051208015046.GE1806@johnsons-web.com> * Tim Johnson [051207 15:56]: > I must be having a Senior Moment here, but the following > baffles me: > >>> label = 'this is "quoted"' > >>> label.replace('"','\"') > 'this is "quoted"' > ## This works > >>> label.replace('"','\'') > "this is 'quoted'" What I should have been using is label.replace('"','\\"') :-) Nevermind. tj > What am I missing here? > thanks > tim > > -- > Tim Johnson > http://www.alaska-internet-solutions.com -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Thu Dec 8 01:56:22 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 7 Dec 2005 15:56:22 -0900 Subject: [Tutor] Escaping double quotes In-Reply-To: <00b701c5fb86$d097b5c0$0a01a8c0@xp> References: <00b701c5fb86$d097b5c0$0a01a8c0@xp> Message-ID: <20051208005622.GD1806@johnsons-web.com> I must be having a Senior Moment here, but the following baffles me: >>> label = 'this is "quoted"' >>> label.replace('"','\"') 'this is "quoted"' ## This works >>> label.replace('"','\'') "this is 'quoted'" What am I missing here? thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From wescpy at gmail.com Thu Dec 8 08:08:56 2005 From: wescpy at gmail.com (w chun) Date: Wed, 7 Dec 2005 23:08:56 -0800 Subject: [Tutor] Escaping double quotes In-Reply-To: <20051208015046.GE1806@johnsons-web.com> References: <00b701c5fb86$d097b5c0$0a01a8c0@xp> <20051208005622.GD1806@johnsons-web.com> <20051208015046.GE1806@johnsons-web.com> Message-ID: <78b3a9580512072308h4ea3cc04u829d73c780f902c6@mail.gmail.com> > > >>> label = 'this is "quoted"' > > >>> label.replace('"','\"') > > 'this is "quoted"' > > ## This works > > >>> label.replace('"','\'') > > "this is 'quoted'" > > > What I should have been using is label.replace('"','\\"') > :-) Nevermind. hold on a second pardner! :-) what were you trying to do, provide escaped quotes? because if it was something else, like replacing the double quotes with singles, you had it correct. otherwise your solution can also be done with raw strings: >>> label.replace('"','\\"') 'this is \\"quoted\\"' >>> label.replace('"',r'\"') 'this is \\"quoted\\"' ok, i'll stop thinking about it now. ;-) cheers, -wesley From wescpy at gmail.com Thu Dec 8 08:19:40 2005 From: wescpy at gmail.com (w chun) Date: Wed, 7 Dec 2005 23:19:40 -0800 Subject: [Tutor] My First Program In-Reply-To: References: Message-ID: <78b3a9580512072319g18e1b952x80d86e4edd6375b6@mail.gmail.com> looks good for your 1st program. some improvements that i can think of: 1. notice how you repeat blocks of code? specifically, i mean: (ask a question, get the answer, validate the answer). since this is all similar code, it's a great place for you to learn what a loop is. that way, you only have one copy of that code. 2. in order to pull of #1, you need to learn about Python's data structures (like shopping bags for data) so that you can save the set of questions along with their corresponding answers. then your loop will just cycle through the Q&A, and you'll only have one place to debug! my suggestion would be a tuple of (Q,A) tuple pairs. and you will have to play a minor game to get your quiz to start with question 1 rather than 0. if you want, post your progress as you change your code, and we can take a look at it. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Thu Dec 8 08:39:22 2005 From: wescpy at gmail.com (w chun) Date: Wed, 7 Dec 2005 23:39:22 -0800 Subject: [Tutor] whats the best command to end a program In-Reply-To: <1133889722.11128.2.camel@localhost.localdomain> References: <1133889722.11128.2.camel@localhost.localdomain> Message-ID: <78b3a9580512072339y4b98caa9ia7120ee91b8a6e07@mail.gmail.com> > what would be the best command to end a program with. > i have an app that i want to start every day at 6am from cron > but i want it to shutdown at 4pm > > i was going to check by time on every loop > > if int(time.strftime(%H)) > 4: > some end the program command > else: > continue > > what would be best used here ? i think using int(), strftime(), takes too much computation. what's wrong with just if time.localtime()[3] >= 16: # do cleanup # raise SystemExit or import sys;sys.exit() you don't even need the continue. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Thu Dec 8 01:20:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 07 Dec 2005 19:20:49 -0500 Subject: [Tutor] Run script automatically in IDLE shell In-Reply-To: References: Message-ID: <43977C61.6070303@tds.net> Yann Le Du wrote: > P.S. I do all this to have accentuated characters (French) correctly > displayed, and this is done in the IDLE Shell, but fails inside the DOS > window. So this is why I want to have my scripts run directly inside the > IDLE shell... The DOS shell uses code page 437 while IDLE uses Cp1252. Most likely you have data in Cp1252 (or latin-1, which is almost the same). When you write it to the shell in IDLE it is fine because IDLE expects it. When you write it to the DOS shell it is misinterpreted as Cp437 and the wrong characters print. Try setting the DOS shell to Cp1252 with the command > chcp 1252 before you run your Python program. For more details see http://www.pycs.net/users/0000323/stories/14.html Kent From kent37 at tds.net Thu Dec 8 13:51:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 08 Dec 2005 07:51:13 -0500 Subject: [Tutor] my text adventure In-Reply-To: <001b01c5f8d6$a1e11620$0201a8c0@d71bh5mhis9p7o> References: <000601c5f87b$7d660130$0201a8c0@d71bh5mhis9p7o> <001201c5f87c$09330960$0201a8c0@d71bh5mhis9p7o> <001b01c5f8d6$a1e11620$0201a8c0@d71bh5mhis9p7o> Message-ID: <43982C41.6040804@tds.net> david wrote: > thanks. i had actually coded this almost exactly the same. i'll try > to make my questions more specific. i am able to pickle and restore > world. which is a dictionary of coordinates : room objects. when i > look at the savefile that pickle generates i can see all my > descriptions and exits. however when i reload my world gets back all > the rooms that were created with dig. but the rooms don't have their > exits or descriptions. is pickle the right tool for this? can i > pickle.dump more than one thing to the same savefile? Yes, as long as you pickle and unpickle in the same order you can do this. > or how could i > go about creating a structure that holds room, coords, descriptions > and exits? You could put everything you want to pickle into a list or dictionary and pickle that, then extract them out again when you unpickle. Kent From ghasseler at gmail.com Thu Dec 8 14:12:25 2005 From: ghasseler at gmail.com (Greg Hasseler) Date: Thu, 8 Dec 2005 08:12:25 -0500 Subject: [Tutor] My First Program In-Reply-To: References: Message-ID: <200512080812.25709.ghassel1@twcny.rr.com> You should create a counting variable. Whenever the user answers incorrectly, increment that variable by one. Starting with the fourth question and any question after, you should check the value of the variable to see if it is three or greater. If it is, then exit, if not, then continue. Check only beginning with the fourth question, because at the start of the first three questions, it would not be possible to already have three incorrect answers. On Wednesday 07 December 2005 23:09, Trent Rigsbee wrote: > Hi! My first "ever" program that I've created is a simple game called > "State Capitals". It's straight forward; 5 simple questions about state > capitals in a non-GUI format. Can someone look over my code and offer tips, > suggestions, criticism? Also, I'd like to be able to end the program if the > user misses 3 questions (i.e., kick them out after the 3rd wrong answer). > How can I do this? Thanks! > > > print "\nState Capitals! Answer a or b to the following questions.\n" > question = raw_input("Question 1 - What is the capital of NC, a: Raleigh or > b: Atlanta? ") > if question == "a": > print "Yes\n" > else: > print "WRONG\n" > > question = raw_input("Question 2 - What is the capital of SC, a: Greenville > or b: Columbia? ") > if question == "b": > print "Yes\n" > else: > print "WRONG\n" > > question = raw_input("Question 3 - What is the capital of NY, a: Albany or > b: Buffalo?") > if question == "a": > print "Yes\n" > else: > print "WRONG\n" > > question = raw_input("Question 4 - What is the capital of OH, a: Cleveland > or b: Columbus? ") > if question == "b": > print "Yes\n" > else: > print "WRONG\n" > > question = raw_input("Question 5 - What is the capital of TX, a: Houston or > b: Austin? ") > if question == "b": > print "Yes\n" > else: > print "WRONG\n" > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From tim at johnsons-web.com Thu Dec 8 17:28:07 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 8 Dec 2005 07:28:07 -0900 Subject: [Tutor] Escaping double quotes In-Reply-To: <78b3a9580512072308h4ea3cc04u829d73c780f902c6@mail.gmail.com> References: <00b701c5fb86$d097b5c0$0a01a8c0@xp> <20051208005622.GD1806@johnsons-web.com> <20051208015046.GE1806@johnsons-web.com> <78b3a9580512072308h4ea3cc04u829d73c780f902c6@mail.gmail.com> Message-ID: <20051208162807.GF1806@johnsons-web.com> * w chun [051207 22:16]: > > > >>> label = 'this is "quoted"' > > > >>> label.replace('"','\"') > > > 'this is "quoted"' > > > ## This works > > > >>> label.replace('"','\'') > > > "this is 'quoted'" > > > > > > What I should have been using is label.replace('"','\\"') > > :-) Nevermind. > > > hold on a second pardner! :-) what were you trying to do, provide > escaped quotes? because if it was something else, like replacing the > double quotes with singles, you had it correct. Yes. Escaped quotes. To be inserted in web content as escaped quotes in code for a Javascript Alert call.... > otherwise your solution can also be done with raw strings: > > >>> label.replace('"','\\"') > 'this is \\"quoted\\"' > >>> label.replace('"',r'\"') > 'this is \\"quoted\\"' Good tip tho' .... I keep forgetting about raw strings. > ok, i'll stop thinking about it now. ;-) Thanks! tj > cheers, > -wesley -- Tim Johnson http://www.alaska-internet-solutions.com From ps_python3 at yahoo.co.in Thu Dec 8 19:39:53 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Thu, 8 Dec 2005 18:39:53 +0000 (GMT) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <78b3a9580512072308h4ea3cc04u829d73c780f902c6@mail.gmail.com> Message-ID: <20051208183953.83546.qmail@web8404.mail.in.yahoo.com> Hi, using ElementTree, how can I extract text of a particular element, or a child node. For example: Signal transduction __________________________________________________________ Yahoo! India Matrimony: Find your partner now. Go to http://yahoo.shaadi.com From ps_python3 at yahoo.co.in Thu Dec 8 19:42:15 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Thu, 8 Dec 2005 18:42:15 +0000 (GMT) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <78b3a9580512072308h4ea3cc04u829d73c780f902c6@mail.gmail.com> Message-ID: <20051208184215.54793.qmail@web8407.mail.in.yahoo.com> Hi, using ElementTree, how can I extract text of a particular element, or a child node. For example: Signal transduction Energy process I looked at some tutorials (eg. Ogbuji). Those examples described to extract all text of nodes and child nodes. In the case where I already know which element tags have the information that I need, in such case how do i get that specific text. Thanks Mdan __________________________________________________________ Yahoo! India Matrimony: Find your partner now. Go to http://yahoo.shaadi.com From kent37 at tds.net Thu Dec 8 20:43:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 08 Dec 2005 14:43:55 -0500 Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <20051208184215.54793.qmail@web8407.mail.in.yahoo.com> References: <20051208184215.54793.qmail@web8407.mail.in.yahoo.com> Message-ID: <43988CFB.2070609@tds.net> ps python wrote: > Hi, > > using ElementTree, how can I extract text of a > particular element, or a child node. > > For example: > > > > Signal transduction > > > Energy process > > > > In the case where I already know which element tags > have the information that I need, in such case how do > i get that specific text. Use find() to get the nodes of interest. The text attribute of the node contains the text. For example: data = ''' Signal transduction Energy process ''' from elementtree import ElementTree tree = ElementTree.fromstring(data) for process in tree.findall('biological_process'): print process.text.strip() prints Signal transduction Energy process You will have to modify the path in the findall to match your actual data, assuming what you have shown is just a snippet. I stripped whitespace from the text because otherwise it includes the newlines and indents exactly as in the original. Kent From dyoo at hkn.eecs.berkeley.edu Thu Dec 8 20:47:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 8 Dec 2005 11:47:45 -0800 (PST) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <20051208184215.54793.qmail@web8407.mail.in.yahoo.com> Message-ID: > For example: > > > > Signal transduction > > > Energy process > > > > I looked at some tutorials (eg. Ogbuji). Those > examples described to extract all text of nodes and > child nodes. Hi Mdan, The following might help: http://article.gmane.org/gmane.comp.python.tutor/24986 http://mail.python.org/pipermail/tutor/2005-December/043817.html The second post shows how we can use the findtext() method from an ElementTree. Here's another example that demonstrates how we can treat elements as sequences of their subelements: ################################################################## from elementtree import ElementTree from StringIO import StringIO text = """ skywalker luke valentine faye reynolds mal """ people = ElementTree.fromstring(text) for person in people: print "here's a person:", print person.findtext("firstName"), person.findtext('lastName') ################################################################## Does this make sense? The API allows us to treat an element as a sequence that we can march across, and the loop above marches across every person subelement in people. Another way we could have written the loop above would be: ########################################### >>> for person in people.findall('person'): ... print person.find('firstName').text, ... print person.find('lastName').text ... luke skywalker faye valentine mal reynolds ########################################### Or we might go a little funkier, and just get the first names anywhere in people: ########################################### >>> for firstName in people.findall('.//firstName'): ... print firstName.text ... luke faye mal ########################################### where the subelement "tag" that we're giving findall is really an XPath-query. ".//firstName" is an query in XPath format that says "Give me all the firstName elements anywhere within the current element." The documentation in: http://effbot.org/zone/element.htm#searching-for-subelements should also be helpful. If you have more questions, please feel free to ask. From cpu.crazy at gmail.com Thu Dec 8 21:14:29 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Thu, 8 Dec 2005 14:14:29 -0600 Subject: [Tutor] My First Program Message-ID: <66ca60fc0512081214v2c57cb9dg192e29ded7469a6a@mail.gmail.com> > > > Hi! My first "ever" program that I've created is a simple game called > "State > Capitals". It's straight forward; 5 simple questions about state capitals > in > a non-GUI format. Can someone look over my code and offer tips, > suggestions, > criticism? Also, I'd like to be able to end the program if the user misses > 3 > questions (i.e., kick them out after the 3rd wrong answer). How can I do > this? Thanks! > > > print "\nState Capitals! Answer a or b to the following questions.\n" > question = raw_input("Question 1 - What is the capital of NC, a: Raleigh > or > b: Atlanta? ") > if question == "a": > print "Yes\n" > else: > print "WRONG\n" > > question = raw_input("Question 2 - What is the capital of SC, a: > Greenville > or b: Columbia? ") > if question == "b": > print "Yes\n" > else: > print "WRONG\n" > > question = raw_input("Question 3 - What is the capital of NY, a: Albany or > b: Buffalo?") > if question == "a": > print "Yes\n" > else: > print "WRONG\n" > > question = raw_input("Question 4 - What is the capital of OH, a: Cleveland > or b: Columbus? ") > if question == "b": > print "Yes\n" > else: > print "WRONG\n" > > question = raw_input("Question 5 - What is the capital of TX, a: Houston > or > b: Austin? ") > if question == "b": > print "Yes\n" > else: > print "WRONG\n" > Hi! Glad you picked up Python. You'll probably enjoy it. This might be over your head, but I'd use functions for your Yes and WRONG: def yes(): print "Yes\n" def WRONG(): print "WRONG\n" # Now for the sample code: question = raw_input("Question 4 - What is the capital of OH, a: Cleveland or b: Columbus? ") if question == "b": yes() else: WRONG() Hope this helps. Joe -- There are 10 different types of people in the world. Those who understand binary and those who don't. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051208/fa630dec/attachment.html From ps_python3 at yahoo.co.in Thu Dec 8 21:22:27 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Thu, 8 Dec 2005 20:22:27 +0000 (GMT) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <43988CFB.2070609@tds.net> Message-ID: <20051208202227.57117.qmail@web8408.mail.in.yahoo.com> Kent and Dany, Thanks for your replies. Here fromstring() assuming that the input is in a kind of text format. what should be the case when I am reading files directly. I am using the following : from elementtree.ElementTree import ElementTree mydata = ElementTree(file='00001.xml') iter = root.getiterator() Here the whole XML document is loaded as element tree and how should this iter into a format where I can apply findall() method. thanks mdan --- Kent Johnson wrote: > ps python wrote: > > Hi, > > > > using ElementTree, how can I extract text of a > > particular element, or a child node. > > > > For example: > > > > > > > > Signal transduction > > > > > > Energy process > > > > > > > > In the case where I already know which element > tags > > have the information that I need, in such case how > do > > i get that specific text. > > Use find() to get the nodes of interest. The text > attribute of the node > contains the text. For example: > > data = ''' > > Signal transduction > > > Energy process > > > ''' > > from elementtree import ElementTree > > tree = ElementTree.fromstring(data) > > for process in tree.findall('biological_process'): > print process.text.strip() > > > prints > Signal transduction > Energy process > > You will have to modify the path in the findall to > match your actual > data, assuming what you have shown is just a > snippet. > > I stripped whitespace from the text because > otherwise it includes the > newlines and indents exactly as in the original. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________________ Yahoo! India Matrimony: Find your partner now. Go to http://yahoo.shaadi.com From kent37 at tds.net Thu Dec 8 21:45:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 08 Dec 2005 15:45:43 -0500 Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <20051208202227.57117.qmail@web8408.mail.in.yahoo.com> References: <20051208202227.57117.qmail@web8408.mail.in.yahoo.com> Message-ID: <43989B77.8060107@tds.net> ps python wrote: > Kent and Dany, > Thanks for your replies. > > Here fromstring() assuming that the input is in a kind > of text format. Right, that is for the sake of a simple example. > > what should be the case when I am reading files > directly. > > I am using the following : > > from elementtree.ElementTree import ElementTree > mydata = ElementTree(file='00001.xml') > iter = root.getiterator() > > Here the whole XML document is loaded as element tree > and how should this iter into a format where I can > apply findall() method. Call findall() directly on mydata, e.g. for process in mydata.findall('//biological_process'): print process.text The path //biological_process means find any biological_process element at any depth from the root element. Kent From dyoo at hkn.eecs.berkeley.edu Thu Dec 8 22:52:54 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 8 Dec 2005 13:52:54 -0800 (PST) Subject: [Tutor] My First Program In-Reply-To: <66ca60fc0512081214v2c57cb9dg192e29ded7469a6a@mail.gmail.com> Message-ID: > > Hi! My first "ever" program that I've created is a simple game called > > "State Capitals". It's straight forward; 5 simple questions about > > state capitals in a non-GUI format. [some code cut] Hi Trent, Looks good so far! There is one direct thing we can do to make the program a little shorter: we can use "functions". If you want, we can go through an example to see what these things do. There's a fairly consistant pattern to each of the quiz questions. If we look at the first two blocks of questions, for example: > > question = raw_input("Question 1 - What is the capital of NC, a: Raleigh > > or > > b: Atlanta? ") > > if question == "a": > > print "Yes\n" > > else: > > print "WRONG\n" > > question = raw_input("Question 2 - What is the capital of SC, a: > > Greenville > > or b: Columbia? ") > > if question == "b": > > print "Yes\n" > > else: > > print "WRONG\n" and if we squint our eyes a bit, we might see a pattern here, something like: question = raw_input( {some question here} ) if question == {some right answer here}: print "Yes\n" else: print "Wrong\n" where I've put placeholders (the stuff in braces) to mark the places that are different. There is a feature in many programming languages called the "function" that allows us to capture this pattern and give it a name. Think Mad Libs: what we can do is make a mad-lib game form, and then let people fill in what they want. The block above can be turned into this function: ################################################### def quiz_question(some_question, some_right_answer): question = raw_input(some_question) if question == some_right_answer: print "Yes\n" else: print "Wrong\n" ################################################### 'quiz_question' is the name I've given this, though if you want to call it something else, please feel free to change the name. Once we have 'quiz_question', how do we use this? Let try this from the interactive interpreter: ###### >>> quiz_question("what's your favorite color?", "green") what's your favorite color?green Yes >>> quiz_question("what's your favorite color?", "green") what's your favorite color?blue no red! Wrong ###### Does this make sense so far? By having that function, it'll lets you add more questions to your quiz by just adding the stuff that's really important: the content of the questions and their right answers. The tutorials on: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers should talk about functions a bit. Try playing with functions: it should make your program shorter, and that'll make it a little easier to think about how to do the three-strikes-you're-out! thing. From tim at johnsons-web.com Fri Dec 9 02:24:18 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 8 Dec 2005 16:24:18 -0900 Subject: [Tutor] bitwise manipulation In-Reply-To: References: <66ca60fc0512081214v2c57cb9dg192e29ded7469a6a@mail.gmail.com> Message-ID: <20051209012418.GL1806@johnsons-web.com> Hello Snake Charmers: I'm designing a database and am thinking about how to store a number number of boolean values in one field. Are there any python resources available that can make setting/unsetting bits directly? I used to do that in "C" with preprocessor macros that made calls like set_bit(vInteger,bit_position) and unset_bit(vInteger,bit_position). Thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From john at fouhy.net Fri Dec 9 02:43:57 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 9 Dec 2005 14:43:57 +1300 Subject: [Tutor] bitwise manipulation In-Reply-To: <20051209012418.GL1806@johnsons-web.com> References: <66ca60fc0512081214v2c57cb9dg192e29ded7469a6a@mail.gmail.com> <20051209012418.GL1806@johnsons-web.com> Message-ID: <5e58f2e40512081743n3eb4b8bfi@mail.gmail.com> On 09/12/05, Tim Johnson wrote: > Are there any python resources available that can make setting/unsetting > bits directly? I used to do that in "C" with preprocessor macros that > made calls like set_bit(vInteger,bit_position) > and unset_bit(vInteger,bit_position). Well, you could write them yourself? [untested] def set_bit(i, n): return i | (1 << n) def unset_bit(i, n): return i & ~(1 << n) def test_bit(i, n): return i & (1 << n) Note that integers are immutable, so there's no way to change an existing int. Also, if you're playing with stuff at that level, you might find the struct module helpful. -- John. From tim at johnsons-web.com Fri Dec 9 03:20:15 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 8 Dec 2005 17:20:15 -0900 Subject: [Tutor] bitwise manipulation In-Reply-To: <5e58f2e40512081743n3eb4b8bfi@mail.gmail.com> References: <66ca60fc0512081214v2c57cb9dg192e29ded7469a6a@mail.gmail.com> <20051209012418.GL1806@johnsons-web.com> <5e58f2e40512081743n3eb4b8bfi@mail.gmail.com> Message-ID: <20051209022015.GM1806@johnsons-web.com> * John Fouhy [051208 16:55]: > On 09/12/05, Tim Johnson wrote: > > Are there any python resources available that can make setting/unsetting > > bits directly? I used to do that in "C" with preprocessor macros that > > made calls like set_bit(vInteger,bit_position) > > and unset_bit(vInteger,bit_position). > > Well, you could write them yourself? OK > [untested] > > def set_bit(i, n): > return i | (1 << n) > > def unset_bit(i, n): > return i & ~(1 << n) > > def test_bit(i, n): > return i & (1 << n) You just did most of the work for me! > Note that integers are immutable, so there's no way to change an existing int. That's what objects are for... > Also, if you're playing with stuff at that level, you might find the > struct module helpful. I believe it would. Thanks I will call the class Bitters .... cheers Tim (off to brew some Bitters) > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From bgailer at alum.rpi.edu Wed Dec 7 17:27:54 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 07 Dec 2005 08:27:54 -0800 Subject: [Tutor] Timer In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1554@chbnt01.alpha.wd. govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1554@chbnt01.alpha.wd.govt.nz> Message-ID: <7.0.0.16.0.20051207082704.01d2bcf0@alum.rpi.edu> At 07:18 PM 12/6/2005, Liam Clarke-Hutchinson wrote: >Hi, > >time.sleep() takes an argument as seconds. Oh yeah I know that but forgot.Sigh. Thanks for the correction. From itechsys at gmail.com Fri Dec 9 12:32:54 2005 From: itechsys at gmail.com (vikas mohan) Date: Fri, 9 Dec 2005 12:32:54 +0100 Subject: [Tutor] Can I get some feedback on my currency converter program Message-ID: <1114f05f0512090332k12f5aa60jc940b49ab8f0b6f7@mail.gmail.com> Hi all, this is my first program in python. It's a currency converter mini-program, but I am not getting the desired output. What wrong am I doing here? *Program code:* #converts currencies to Indian rupees def print_options(): print "Options:" print " 'p' print options" print " 'c' convert from US Dollars to Indian Rupees" print " 'f' convert from Swedish Kronors to Indian Rupees" print " 'g' convert from British Pound Sterling to Indian Rupees" print " 'q' quit the program" def rupees_from_dollars(c_doll): return 43*1 --*The function is supposed to multiply the value of dollars x 43(value of an Indian rupee) *def rupees_from_kronor(f_kron): return 8*f_kron --*The function is supposed to multiply the value of kronor x 8(value of an Indian rupee)* def rupees_from_pounds(g_pound): return 68*g_pound --*The function is supposed to multiply the value of pounds x 68(value of an Indian rupee)* choice = "p" while choice != "q": if choice == "c": Rupees = input("US Dollars:") print "Rupees:",--*The problem is here: I only get Rupees but not the value multiplied as stated in the function.* elif choice == "f": Rupees = input("Swedish Kronor:") print "Rupees:" --*The problem is here: I only get Rupees but not the value multiplied as stated in the function.* elif choice == "g": Rupees = input("UK Sterling:") print "Rupees:"--*The problem is here: I only get Rupees but not the value multiplied as stated in the function.* elif choice != "q": print_options() choice = raw_input("option:") ----------------------------------------- Much appreciate your help! VikasM ** ** -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051209/ab7168c3/attachment.htm From lists at janeden.org Fri Dec 9 12:39:07 2005 From: lists at janeden.org (Jan Eden) Date: Fri, 9 Dec 2005 12:39:07 +0100 Subject: [Tutor] XSLT module Message-ID: Hi, I intend to use an XSLT processor, and found various modules (4suite, Sab-Pyth) on the web. Could anyone recommend a specific module for transforming XML files? Thanks, Jan -- It's overkill, of course. But you can never have too much overkill. From ewald.ertl at hartter.com Fri Dec 9 13:13:37 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Fri, 09 Dec 2005 13:13:37 +0100 Subject: [Tutor] Can I get some feedback on my currency converter program In-Reply-To: <1114f05f0512090332k12f5aa60jc940b49ab8f0b6f7@mail.gmail.com> References: <1114f05f0512090332k12f5aa60jc940b49ab8f0b6f7@mail.gmail.com> Message-ID: <439974F1.6040009@hartter.com> Hi! vikas mohan wrote: > Hi all, this is my first program in python. > > It's a currency converter mini-program, but I am not getting the desired > output. What wrong am I doing here? > > *Program code:* > > #converts currencies to Indian rupees > > def print_options(): > print "Options:" > print " 'p' print options" > print " 'c' convert from US Dollars to Indian Rupees" > print " 'f' convert from Swedish Kronors to Indian Rupees" > print " 'g' convert from British Pound Sterling to Indian Rupees" > print " 'q' quit the program" > > def rupees_from_dollars(c_doll): > return 43*1 --*The function is supposed to multiply the value of Here is the c_doll missing return 43*c_doll > dollars x 43(value of an Indian rupee) > *def rupees_from_kronor(f_kron): > return 8*f_kron -- *The function is supposed to multiply the value > of kronor x 8(value of an Indian rupee)* > def rupees_from_pounds(g_pound): > return 68*g_pound --*The function is supposed to multiply the value > of pounds x 68(value of an Indian rupee) * > > choice = "p" > while choice != "q": > if choice == "c": > Rupees = input("US Dollars:") Rupees contains the inserted value > print "Rupees:",--*The problem is here: I only get Rupees but Here just the Text"Rupees:" is printed print "Rupees:", rupees_from_dollars(Rupees) or print "Rupees: %d\n" % ( rupees_from_dollars( Rupees ) ) You have to call the function to get the converted value. > not the value multiplied as stated in the function. * > elif choice == "f": > Rupees = input("Swedish Kronor:") > print "Rupees:" --*The problem is here: I only get Rupees but > not the value multiplied as stated in the function. * > elif choice == "g": > Rupees = input("UK Sterling:") > print "Rupees:"--*The problem is here: I only get Rupees but not > the value multiplied as stated in the function. * > elif choice != "q": > print_options() > choice = raw_input("option:") > > ----------------------------------------- > > Much appreciate your help! > > VikasM > > ** > ** > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor HTH Ewald From itechsys at gmail.com Fri Dec 9 13:57:34 2005 From: itechsys at gmail.com (vikas mohan) Date: Fri, 9 Dec 2005 13:57:34 +0100 Subject: [Tutor] Can I get some feedback on my currency converter program In-Reply-To: <439974F1.6040009@hartter.com> References: <1114f05f0512090332k12f5aa60jc940b49ab8f0b6f7@mail.gmail.com> <439974F1.6040009@hartter.com> Message-ID: <1114f05f0512090457k724fa6c3wb15610b8bc74bdf3@mail.gmail.com> Thanks! Looks in a better shape now! I have a diffrent question now: What if like in Java, i would like to have live currency quotes fed to my function, from some forex dealer website? So, that my program can provide uptodate info. How can I hot/live link my function? /VikasM #converts currencies indo Indian rupees print "Welcome to your currency converter\n" print "Plese choose from the following opitons\n" def print_options(): print "Options:" print " 'p' print options" print " '$' convert from US Dollars to Indian Rupees" print " 'kr' convert from Swedish Kronors to Indian Rupees" print " '?' convert from British Pound Sterling to Indian Rupees" print " 'eu' convert from Euros to Indian Rupees" print " 'q' quit the program" def rupees_from_dollars(d_doll): return 43*(d_doll) def rupees_from_kronor(kr_kron): return 8*(kr_kron) def rupees_from_pounds(p_pound): return 68*(p_pound) def rupees_from_euros(eu_euros): return 54*(eu_euros) choice = "p" while choice != "q": if choice == "$": Rupees = input("US Dollars:") print "Rupees:",rupees_from_dollars(Rupees) elif choice == "kr": Rupees = input("Swedish Kronor:") print "Rupees:",rupees_from_kronor(Rupees) elif choice == "?": Rupees = input("UK Sterling:") print "Rupees:",rupees_from_pounds(Rupees) elif choice == "eu": Rupees = input("Euros:") print "Rupees:",rupees_from_euros(Rupees) elif choice != "q": print_options() choice = raw_input("Choose option:") On 12/9/05, Ewald Ertl wrote: > Hi! > > vikas mohan wrote: > > Hi all, this is my first program in python. > > > > It's a currency converter mini-program, but I am not getting the desired > > output. What wrong am I doing here? > > > > *Program code:* > > > > #converts currencies to Indian rupees > > > > def print_options(): > > print "Options:" > > print " 'p' print options" > > print " 'c' convert from US Dollars to Indian Rupees" > > print " 'f' convert from Swedish Kronors to Indian Rupees" > > print " 'g' convert from British Pound Sterling to Indian Rupees" > > print " 'q' quit the program" > > > > def rupees_from_dollars(c_doll): > > return 43*1 --*The function is supposed to multiply the value of > > Here is the c_doll missing > return 43*c_doll > > > dollars x 43(value of an Indian rupee) > > *def rupees_from_kronor(f_kron): > > return 8*f_kron -- *The function is supposed to multiply the value > > of kronor x 8(value of an Indian rupee)* > > def rupees_from_pounds(g_pound): > > return 68*g_pound --*The function is supposed to multiply the value > > of pounds x 68(value of an Indian rupee) * > > > > choice = "p" > > while choice != "q": > > if choice == "c": > > Rupees = input("US Dollars:") > Rupees contains the inserted value > > print "Rupees:",--*The problem is here: I only get Rupees but > Here just the Text"Rupees:" is printed > > print "Rupees:", rupees_from_dollars(Rupees) > > or print "Rupees: %d\n" % ( rupees_from_dollars( Rupees ) ) > > You have to call the function to get the converted value. > > > not the value multiplied as stated in the function. * > > elif choice == "f": > > Rupees = input("Swedish Kronor:") > > print "Rupees:" --*The problem is here: I only get Rupees but > > not the value multiplied as stated in the function. * > > elif choice == "g": > > Rupees = input("UK Sterling:") > > print "Rupees:"--*The problem is here: I only get Rupees but not > > the value multiplied as stated in the function. * > > elif choice != "q": > > print_options() > > choice = raw_input("option:") > > > > ----------------------------------------- > > > > Much appreciate your help! > > > > VikasM > > > > ** > > ** > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > HTH Ewald > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051209/ed734be7/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Dec 9 19:41:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 9 Dec 2005 10:41:37 -0800 (PST) Subject: [Tutor] Can I get some feedback on my currency converter program In-Reply-To: <1114f05f0512090457k724fa6c3wb15610b8bc74bdf3@mail.gmail.com> Message-ID: On Fri, 9 Dec 2005, vikas mohan wrote: > Thanks! Looks in a better shape now! I have a diffrent question now: > What if like in Java, i would like to have live currency quotes fed to > my function, from some forex dealer website? So, that my program can > provide uptodate info. How can I hot/live link my function? Hi Vikas, I'm not familiar with the terminology of 'hot/live linking', and my Google searches on this aren't effective. ('hot live linking java' is giving me spicy coffee recipes. *grin*) Can you point out how you'd do what you want in Java? That'll help us understand the question better. From srini_iyyer_bio at yahoo.com Fri Dec 9 20:32:27 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 9 Dec 2005 11:32:27 -0800 (PST) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <43989B77.8060107@tds.net> Message-ID: <20051209193227.99844.qmail@web31607.mail.mud.yahoo.com> Hi group, I just have another question in parsin XML files. I found it very easy to parse XML files with kent and danny's help. I realized that all my XML files have '\t' and '\n' and whitespace. these extra features are making to extract the text data from the xml files very difficult. I can make these XML parser work when I rekove '\n' and '\t' from xml files. is there a way to get rid of '\n' and '\t' characters from xml files easily. thank you very much. MDan --- Kent Johnson wrote: > ps python wrote: > > Kent and Dany, > > Thanks for your replies. > > > > Here fromstring() assuming that the input is in a > kind > > of text format. > > Right, that is for the sake of a simple example. > > > > what should be the case when I am reading files > > directly. > > > > I am using the following : > > > > from elementtree.ElementTree import ElementTree > > mydata = ElementTree(file='00001.xml') > > iter = root.getiterator() > > > > Here the whole XML document is loaded as element > tree > > and how should this iter into a format where I can > > apply findall() method. > > Call findall() directly on mydata, e.g. > for process in > mydata.findall('//biological_process'): > print process.text > > The path //biological_process means find any > biological_process element > at any depth from the root element. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Fri Dec 9 20:42:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 09 Dec 2005 14:42:10 -0500 Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <20051209193227.99844.qmail@web31607.mail.mud.yahoo.com> References: <20051209193227.99844.qmail@web31607.mail.mud.yahoo.com> Message-ID: <4399DE12.4090703@tds.net> Srinivas Iyyer wrote: > Hi group, > I just have another question in parsin XML files. I > found it very easy to parse XML files with kent and > danny's help. > > I realized that all my XML files have '\t' and '\n' > and whitespace. these extra features are making to > extract the text data from the xml files very > difficult. I can make these XML parser work when I > rekove '\n' and '\t' from xml files. > > is there a way to get rid of '\n' and '\t' characters > from xml files easily. Did you see how I did this in my original example? I called strip() on the text part of the element. This removes leading and trailing whitespace. Is that what you need? Kent From dyoo at hkn.eecs.berkeley.edu Fri Dec 9 22:33:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 9 Dec 2005 13:33:24 -0800 (PST) Subject: [Tutor] Can I get some feedback on my currency converter program In-Reply-To: Message-ID: > On Fri, 9 Dec 2005, vikas mohan wrote: > > > Thanks! Looks in a better shape now! I have a diffrent question now: > > What if like in Java, i would like to have live currency quotes fed to > > my function, from some forex dealer website? So, that my program can > > provide uptodate info. How can I hot/live link my function? Hi Vikas, Ok, so I looked into this a bit more; I think you mean to grab the currency rates that are being used at any given time. There's a web site on finance.yahoo.com that gives quotes: http://finance.yahoo.com/currency and it seems common for people to write tools to scrap information off that page. We can grab such pages in Python by using the 'urllib' library. http://www.python.org/doc/lib/module-urllib.html For example, the following program: ###### import urllib text = urllib.urlopen("http://finance.yahoo.com/d/quotes.csv" + "?s=USDJPY=X&f=sl1d1t1ba&e=.csv").read() print text ###### shows how we can download a page and get some data --- the program above grabs data for the US-to-Japanese-Yen exchange rate. If you take this route, you'll probably need to do a bit more to make this work across all the currency types you want. If you look around the web, you should be able to find some module that people have written to do this. Besides Yahoo, there appears to be other places where live currency-exchange data can be grabbed in bulk. For example, the European Central Bank (ECB) appears to provide this data against the Euro: http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html Not only does ECB provides this information in HTML, but also in a machine-parsable XML format: http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml So one way to grab the live data would be to take the above XML document and use an XML parser to yank out the data values. One popular one that we've been using recently is a third-party module called ElementTree, which can be found here: http://effbot.org/zone/element-index.htm This seems to be XML-parsing week for me, so for fun, I wrote something to parse the content out. If you don't want to be spoiled, don't read the end of this message. *grin* ** spoiler space ahead ** ** spoiler space ** Here's a small program that can do this retrieval and parsing. (I'm still an ElementTree newbie, so there may be a more concise way of programming the following): ###################################################################### """A small module to grab the reference rates against the Euro, using statistics from the European Central Bank.""" import urllib from elementtree import ElementTree def getLiveEuroData(): """Returns a dictionary mapping currency codes from the Euro to that particular currency.""" tree = getTree() euroData = {} for elt in tree.findall(".//*"): if (elt.attrib.get('currency', None) and elt.attrib.get('rate', None)): euroData[elt.attrib.get('currency')] = ( float(elt.attrib.get('rate'))) return euroData def getTree(): """Grabs the latest xml document from the European Central Bank at http://www.ecb.int.""" f = urllib.urlopen("http://www.ecb.int/stats/eurofxref/" + "eurofxref-daily.xml") tree = ElementTree.parse(f) f.close() return tree ####################################################################### So, for example, to find the currency exchange rate from the Euro to US dollars, we can do: ##### >>> euroToOtherCurrencyRate = getLiveEuroData() >>> euroToOtherCurrencyRate['USD'] 1.1785000000000001 ##### If we wanted to be nice, we'd probably add something to cache the exchange rates somewhere in memory, so that we don't hammer ECB. Anyway, I hope this comes in handy! From alan.gauld at freenet.co.uk Sat Dec 10 01:24:43 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 10 Dec 2005 00:24:43 -0000 Subject: [Tutor] how to extract text by specifying an element usingElementTree References: <20051209193227.99844.qmail@web31607.mail.mud.yahoo.com> Message-ID: <002101c5fd20$1e44e6e0$0a01a8c0@xp> > is there a way to get rid of '\n' and '\t' characters > from xml files easily. You can read the entire file as a string then apply standard string replace functionality to substitute an empty string.. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Dec 10 01:22:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 10 Dec 2005 00:22:58 -0000 Subject: [Tutor] Can I get some feedback on my currency converter program References: <1114f05f0512090332k12f5aa60jc940b49ab8f0b6f7@mail.gmail.com><439974F1.6040009@hartter.com> <1114f05f0512090457k724fa6c3wb15610b8bc74bdf3@mail.gmail.com> Message-ID: <001b01c5fd1f$dffe84e0$0a01a8c0@xp> > like in Java, i would like to have live currency quotes fed to my > function, Look at the urllib module. However I suspect you might be better working on the basics for a little longer before getting too ambitious! def rupees_from_dollars(d_doll): return 43*(d_doll) You don;t need the () in the line above. They are needed as part of the function definition but not within the function unless you need to group things together. Here you only have one value so there is no need for the () choice = "p" while choice != "q": if choice == "$": Rupees = input("US Dollars:") print "Rupees:",rupees_from_dollars(Rupees) It might be better toi choose a more apt name for the input value - dollars in this case maybe? Then it would look like: if choice == "$": dollars = input("US Dollars:") print "Rupees:",rupees_from_dollars(dollars) It just makes a bit more sense since the value being read is, in fact, the dollar value not the Rupee value. choice = raw_input("Choose option:") You could also put the raw_input statement inside your menu function and have it return the chosebn value - just a thought. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From sweetdaddysiki at hotmail.com Sat Dec 10 01:43:14 2005 From: sweetdaddysiki at hotmail.com (Trent Rigsbee) Date: Sat, 10 Dec 2005 00:43:14 +0000 Subject: [Tutor] My First Program In-Reply-To: Message-ID: Here's my new and improved program: def quiz_question(some_question, some_right_answer): question = raw_input(some_question) if question == some_right_answer: print "Yes!\n" else: print "Wrong\n" quiz_question("Name the capital of NC? ", "Raleigh") quiz_question("Name the capital of SC? ", "Columbia") quiz_question("Name the capital of NY? ", "Albany") quiz_question("Name the capital of OH? ", "Columbus") quiz_question("Name the capital of TX? ", "Austin") I took Danny's advice and plagerized his function code (sorry about that, Danny). I like it! It's much neater and I'm kicking myself for not realizing this. I didn't like the if-else chain but I was stuck on what to do. Creating programs is the way to learn! I know you've heard countless of wannabe coders say this but I'll read the material and I think I know what functions and loops (etc) are but when I try to create something, I'm stuck and not sure how to proceed. Speaking of stuck, I'm not sure how to create the counting variable that Greg suggested. Can someone lead me but don't tell me the answer? Thanks! >From: Danny Yoo >To: sweetdaddysiki at hotmail.com >CC: Joseph Quigley , Tutor >Subject: Re: [Tutor] My First Program >Date: Thu, 8 Dec 2005 13:52:54 -0800 (PST) > > > > > Hi! My first "ever" program that I've created is a simple game called > > > "State Capitals". It's straight forward; 5 simple questions about > > > state capitals in a non-GUI format. > >[some code cut] > >Hi Trent, > > >Looks good so far! There is one direct thing we can do to make the >program a little shorter: we can use "functions". If you want, we can go >through an example to see what these things do. > > >There's a fairly consistant pattern to each of the quiz questions. If we >look at the first two blocks of questions, for example: > > > > > question = raw_input("Question 1 - What is the capital of NC, a: >Raleigh > > > or > > > b: Atlanta? ") > > > if question == "a": > > > print "Yes\n" > > > else: > > > print "WRONG\n" > > > > > question = raw_input("Question 2 - What is the capital of SC, a: > > > Greenville > > > or b: Columbia? ") > > > if question == "b": > > > print "Yes\n" > > > else: > > > print "WRONG\n" > > >and if we squint our eyes a bit, we might see a pattern here, something >like: > > question = raw_input( {some question here} ) > if question == {some right answer here}: > print "Yes\n" > else: > print "Wrong\n" > >where I've put placeholders (the stuff in braces) to mark the places >that are different. > > >There is a feature in many programming languages called the "function" >that allows us to capture this pattern and give it a name. Think Mad >Libs: what we can do is make a mad-lib game form, and then let people fill >in what they want. > >The block above can be turned into this function: > >################################################### >def quiz_question(some_question, some_right_answer): > question = raw_input(some_question) > if question == some_right_answer: > print "Yes\n" > else: > print "Wrong\n" >################################################### > > >'quiz_question' is the name I've given this, though if you want to call >it something else, please feel free to change the name. > > >Once we have 'quiz_question', how do we use this? Let try this from the >interactive interpreter: > >###### > >>> quiz_question("what's your favorite color?", "green") >what's your favorite color?green >Yes > > >>> quiz_question("what's your favorite color?", "green") >what's your favorite color?blue no red! >Wrong >###### > > >Does this make sense so far? > >By having that function, it'll lets you add more questions to your quiz by >just adding the stuff that's really important: the content of the >questions and their right answers. > > >The tutorials on: > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > >should talk about functions a bit. Try playing with functions: it should >make your program shorter, and that'll make it a little easier to think >about how to do the three-strikes-you're-out! thing. > From dyoo at hkn.eecs.berkeley.edu Sat Dec 10 03:31:52 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 9 Dec 2005 18:31:52 -0800 (PST) Subject: [Tutor] My First Program In-Reply-To: Message-ID: > def quiz_question(some_question, some_right_answer): > question = raw_input(some_question) > if question == some_right_answer: > print "Yes!\n" > else: > print "Wrong\n" > > quiz_question("Name the capital of NC? ", "Raleigh") > quiz_question("Name the capital of SC? ", "Columbia") > quiz_question("Name the capital of NY? ", "Albany") > quiz_question("Name the capital of OH? ", "Columbus") > quiz_question("Name the capital of TX? ", "Austin") Hi Trent, Yeah, much better. *grin* > Speaking of stuck, I'm not sure how to create the counting variable that > Greg suggested. Can someone lead me but don't tell me the answer? > Thanks! One possible way to do this is to modify quiz_question() so that it doesn't just print out "Yes" or "Wrong" as a side effect, but is actively involved in maintaining the counter. One way to do this is to modify quiz_question() to take in the number of chances the player has before asking the question, and have it return the number of chances after asking the question. So we might say something like: quiz_question("Name the capital of NC? ", "Raleigh", 5) and expect to either see 5 or 4 as the return value. Alternatively, you can modify quiz_question so that it actively changes a global variable. I don't like globals, but for what you're doing, it also makes sense to use them. If you have questions, please feel free to ask! From pythontut at pusspaws.net Sat Dec 10 09:07:15 2005 From: pythontut at pusspaws.net (dave s) Date: Sat, 10 Dec 2005 08:07:15 +0000 Subject: [Tutor] smtplib mail header problem In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1561@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1561@chbnt01.alpha.wd.govt.nz> Message-ID: <200512100807.16235.pythontut@pusspaws.net> On Wednesday 07 December 2005 22:47, Liam Clarke-Hutchinson wrote: > Heheh, yah, the Python docs take a bit of scrutinisation to yield fruit. > Also, when working with emails, you'll probably end up trying to figure > what exactly what a RFC or three mean. > > Good luck, > > Liam > But its all worth it, problem now solved & work gets my emails :) Cheers Dave From din22 at earthlink.net Sat Dec 10 13:23:16 2005 From: din22 at earthlink.net (david) Date: Sat, 10 Dec 2005 06:23:16 -0600 Subject: [Tutor] (no subject) Message-ID: <000601c5fd84$7ff525d0$0201a8c0@d71bh5mhis9p7o> hello everyone. i was looking at python docs and i came across this letter ::= lowercase | uppercase what does ::= mean? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051210/f93bb8b6/attachment.html From din22 at earthlink.net Sat Dec 10 13:31:16 2005 From: din22 at earthlink.net (david) Date: Sat, 10 Dec 2005 06:31:16 -0600 Subject: [Tutor] bnf Message-ID: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> ::= is bnf notation for "is defined as" please spend that extra minute googling before you bother all the nice people on this list. ----- Original Message ----- From: david To: tutor at python.org Sent: Saturday, December 10, 2005 6:23 AM hello everyone. i was looking at python docs and i came across this letter ::= lowercase | uppercase what does ::= mean? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051210/756e12f0/attachment.htm From itechsys at gmail.com Sat Dec 10 14:19:22 2005 From: itechsys at gmail.com (vikas mohan) Date: Sat, 10 Dec 2005 14:19:22 +0100 Subject: [Tutor] bnf In-Reply-To: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> References: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> Message-ID: <1114f05f0512100519n61ef4e50y6177db01856f2fa8@mail.gmail.com> Hi again I have a question regarding lowercase|uppercase. How can one turn an input, and output it back in lowercase or uppercase? cheers/V On 12/10/05, david wrote: > > ::= is bnf notation for "is defined as" > > please spend that extra minute googling before > you bother all the nice people on this list. > > > ----- Original Message ----- > *From:* david > *To:* tutor at python.org > *Sent:* Saturday, December 10, 2005 6:23 AM > > > hello everyone. i was looking at python docs and i came across this > > letter ::= > lowercase | uppercase > > > what does ::= mean? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051210/75fc9562/attachment.html From broek at cc.umanitoba.ca Sat Dec 10 23:26:09 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 10 Dec 2005 16:26:09 -0600 Subject: [Tutor] bnf In-Reply-To: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> References: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> Message-ID: <439B5601.9060403@cc.umanitoba.ca> david said unto the world upon 2005-12-10 06:31: > ::= is bnf notation for "is defined as" > > please spend that extra minute googling before > you bother all the nice people on this list. > > ----- Original Message ----- > From: david > To: tutor at python.org > Sent: Saturday, December 10, 2005 6:23 AM > > > hello everyone. i was looking at python docs and i came across this > > letter ::= > lowercase | uppercase > > > what does ::= mean? David, goodness knows, maillists and usenet would be better if more people (myself included) would do a better job of their own googling. But, I'm not sure that your comment is fair in this context. Maybe my google-fu is lacking, but googling for ::= or "::=" doesn't produce anything. Google doesn't seem to handle non-alphanumeric search terms too well. If you know how to make google yield useful results for '::=' I'd appreciate the lesson. Best, Brian vdB From din22 at earthlink.net Sat Dec 10 23:56:53 2005 From: din22 at earthlink.net (david) Date: Sat, 10 Dec 2005 16:56:53 -0600 Subject: [Tutor] lowercase, uppercase References: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> <1114f05f0512100519n61ef4e50y6177db01856f2fa8@mail.gmail.com> Message-ID: <000a01c5fddd$03b9b8b0$0201a8c0@d71bh5mhis9p7o> i am thinking that string.upper and string.lower may be what you are looking for. ----- Original Message ----- From: vikas mohan To: david Cc: tutor at python.org Sent: Saturday, December 10, 2005 7:19 AM Subject: Re: [Tutor] bnf Hi again I have a question regarding lowercase|uppercase. How can one turn an input, and output it back in lowercase or uppercase? cheers/V On 12/10/05, david wrote: ::= is bnf notation for "is defined as" please spend that extra minute googling before you bother all the nice people on this list. ----- Original Message ----- From: david To: tutor at python.org Sent: Saturday, December 10, 2005 6:23 AM hello everyone. i was looking at python docs and i came across this letter ::= lowercase | uppercase what does ::= mean? _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051210/2b0a812e/attachment.htm From python at venix.com Sun Dec 11 00:27:31 2005 From: python at venix.com (Python) Date: Sat, 10 Dec 2005 18:27:31 -0500 Subject: [Tutor] lowercase, uppercase In-Reply-To: <000a01c5fddd$03b9b8b0$0201a8c0@d71bh5mhis9p7o> References: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> <1114f05f0512100519n61ef4e50y6177db01856f2fa8@mail.gmail.com> <000a01c5fddd$03b9b8b0$0201a8c0@d71bh5mhis9p7o> Message-ID: <1134257251.24044.197.camel@www.venix.com> On Sat, 2005-12-10 at 16:56 -0600, david wrote: > i am thinking that string.upper and string.lower may be what you are > looking for. >>> x = 'This is Some Mixed CaSe TExt' >>> x.lower() 'this is some mixed case text' >>> x.upper() 'THIS IS SOME MIXED CASE TEXT' Unless you are using a very old version of Python, there is no need to use the string module. the upper and lower methods now built into str and unicode objects. -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Sun Dec 11 03:23:20 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 10 Dec 2005 18:23:20 -0800 (PST) Subject: [Tutor] bnf In-Reply-To: <439B5601.9060403@cc.umanitoba.ca> Message-ID: > > hello everyone. i was looking at python docs and i came across this > > > > letter ::= > > lowercase | uppercase > > > > > > what does ::= mean? > > goodness knows, maillists and usenet would be better if more people > (myself included) would do a better job of their own googling. But, > I'm not sure that your comment is fair in this context. Maybe my > google-fu is lacking, but googling for ::= or "::=" doesn't produce > anything. The question is a little mixed here. I agree that '::=' is obscure enough that asking for help about it is certainly appropriate and right. At the same time, though, there's a section right at the beginning of the Python Reference Manual that does talk about the notation used in the rest of the document: http://www.python.org/doc/ref/notation.html Ideally, the original poster would have found and seen the "notation" section of the reference manual, at least to get a good name for what they're looking at --- "BNF" format. Then we're in a better position to ask what in the world BNF is. I think the lesson here is: let's encourage people to learn how to read technical documentation, by pointing out the conventions that technical writers will use. In technical documentation that uses weird notation, there will usually be a section called "Notation" that at least will try to give English names to the weird symbols. Good luck to you! From broek at cc.umanitoba.ca Sun Dec 11 05:01:49 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 10 Dec 2005 22:01:49 -0600 Subject: [Tutor] bnf In-Reply-To: References: Message-ID: <439BA4AD.8030707@cc.umanitoba.ca> Danny Yoo said unto the world upon 2005-12-10 20:23: >>> hello everyone. i was looking at python docs and i came across this >>> >>> letter ::= >>> lowercase | uppercase >>> >>> >>> what does ::= mean? >> >>goodness knows, maillists and usenet would be better if more people >>(myself included) would do a better job of their own googling. But, >>I'm not sure that your comment is fair in this context. Maybe my >>google-fu is lacking, but googling for ::= or "::=" doesn't produce >>anything. > > > The question is a little mixed here. I agree that '::=' is obscure enough > that asking for help about it is certainly appropriate and right. > > At the same time, though, there's a section right at the beginning of the > Python Reference Manual that does talk about the notation used in the rest > of the document: Hi Danny and all, I take your point about the information being available to the OP in the docs. I was reacting to the follow up post which I read as saying something like "Don't bug us if you are lazy". That struck me as less friendly than the usual tone on the list. The mistake was entirely mine, though. I didn't notice that the "google it" follow-up *was* from the OP by way of apologizing for asking a question that was easy enough to answer for oneself. So, :-[ Best to all, Brian vdB From dyoo at hkn.eecs.berkeley.edu Sun Dec 11 07:36:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 10 Dec 2005 22:36:24 -0800 (PST) Subject: [Tutor] bnf In-Reply-To: <439BA4AD.8030707@cc.umanitoba.ca> Message-ID: > I take your point about the information being available to the OP in the > docs. I was reacting to the follow up post which I read as saying > something like "Don't bug us if you are lazy". That struck me as less > friendly than the usual tone on the list. Hi Brian, Yes. I read the tone as that too. Then again, we can be our own worse critic. > The mistake was entirely mine, though. I didn't notice that the "google > it" follow-up *was* from the OP by way of apologizing for asking a > question that was easy enough to answer for oneself. Actually, I was having a little trouble too with that too. *grin* But no permanent damage caused. Hope everyone's having a good weekend! From ml.cyresse at gmail.com Sun Dec 11 07:31:06 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 11 Dec 2005 19:31:06 +1300 Subject: [Tutor] bnf In-Reply-To: <439BA4AD.8030707@cc.umanitoba.ca> References: <439BA4AD.8030707@cc.umanitoba.ca> Message-ID: > Hi Danny and all, > > I take your point about the information being available to the OP in > the docs. I was reacting to the follow up post which I read as saying > something like "Don't bug us if you are lazy". That struck me as less > friendly than the usual tone on the list. > > The mistake was entirely mine, though. I didn't notice that the > "google it" follow-up *was* from the OP by way of apologizing for > asking a question that was easy enough to answer for oneself. > > So, :-[ > > Best to all, > > Brian vdB I think Brian, from context, that the OP was Vikas. I agree, however, it was a tad less friendly than normal especially considering the low ball odds of getting a definite hit from searching for "::="... I have enough trouble searching for .NET... But then, we all have bad days, wherein a particular question invokes in us a flame/answer, and we regret it almost as soon as sent. Also, with regard to the Python docs... they aren't very newbie friendly, not really intended for the nubs. It's taken me a year to learn how to extract useful information from them. The trick of "read them really carefully, because the important bits usually aren't bullet-pointed for you" is the best one. Which reminds me of why Powerpoint is considered harmful. regards, Liam Clarke From ml.cyresse at gmail.com Sun Dec 11 07:32:38 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 11 Dec 2005 19:32:38 +1300 Subject: [Tutor] smtplib mail header problem In-Reply-To: <200512100807.16235.pythontut@pusspaws.net> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1561@chbnt01.alpha.wd.govt.nz> <200512100807.16235.pythontut@pusspaws.net> Message-ID: Ah, good to hear. I like it when stuff gets fixed. :-) On 12/10/05, dave s wrote: > On Wednesday 07 December 2005 22:47, Liam Clarke-Hutchinson wrote: > > Heheh, yah, the Python docs take a bit of scrutinisation to yield fruit. > > Also, when working with emails, you'll probably end up trying to figure > > what exactly what a RFC or three mean. > > > > Good luck, > > > > Liam > > > > But its all worth it, problem now solved & work gets my emails :) > > Cheers > Dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sun Dec 11 09:46:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 11 Dec 2005 08:46:22 -0000 Subject: [Tutor] bnf References: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> Message-ID: <005b01c5fe2f$5d67d110$0a01a8c0@xp> > ::= is bnf notation for "is defined as" > > please spend that extra minute googling before > you bother all the nice people on this list. To be fair, unless you knew that it was BNF I doubt you'd find much by Googling. I tried several variations of '::=' etc and Google came back empty. Once you know than you are kooking at BNF then Googling for BNF broings back loads of stuff but its not obvious if you don't already know... Alan G. From westside_indie at yahoo.com Sun Dec 11 20:01:41 2005 From: westside_indie at yahoo.com (John Walton) Date: Sun, 11 Dec 2005 11:01:41 -0800 (PST) Subject: [Tutor] information needed to make a connection between computers Message-ID: <20051211190141.89870.qmail@web33610.mail.mud.yahoo.com> Hello again! I'm still working on that instant messenger (for science fair), and I have been reading about networking in some Java tutorials. In one part of it, it said to have a connection with another computer, you need to know the IP name of the computer you want to connect with. I don't know whether or not this is the same for Python, but could someone please tell me what information of the computer you want to connect with the you actually need for a connection? In other words (or plain english), what information do I need to get a connection with another computer (IP address, name, IP name)? Also, could you tell me how to find it on a computer? Since I'll be testing the instant messenger on the three computers in my house, I just need to know how to find the information on the computer I'd currently be on (not from any remote location). Thanks! :) -John --------------------------------- Yahoo! Shopping Find Great Deals on Holiday Gifts at Yahoo! Shopping -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051211/8b770f9a/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Dec 12 01:01:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 11 Dec 2005 16:01:19 -0800 (PST) Subject: [Tutor] information needed to make a connection between computers In-Reply-To: <20051211190141.89870.qmail@web33610.mail.mud.yahoo.com> Message-ID: [Taking catalog-sig and python-list out of CC.] John, please don't crosspost. catalog-sig in particular is off-topic of your question. When we crosspost, we add noise to those lists and frustrate members of the community. It's generally a bad thing to do. See: http://catb.org/~esr/faqs/smart-questions.html and: http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html for more details about this. Please make sure your replies are only going to a single mailing list unless you really have overriding reasons for crossposting. In fact, you've been called on this behavior back in August: http://mail.python.org/pipermail/catalog-sig/2005-August/0000692.html Ian Bicking there was fairly civil, but you need to pick up on the clue: he didn't give you much help besides saying, in effect: you're posting on the wrong mailing list, and he and others on catalog-sig won't even bother responding to you if you ignore his request for topicality. It look like you didn't really hear what he said, so let me say it explicitely: crossposting is considered inconsiderate behavior. If you continue to do so, people will respond in kind by ignoring your questions, and that will be bad. So avoid getting people annoyed: don't crosspost. Thanks. Anyway, to your question. > I don't know whether or not this is the same for Python, but could > someone please tell me what information of the computer you want to > connect with the you actually need for a connection? Computers on the internet all have an IP address in the form of dotted numbers. For example, 82.94.237.218 is an example of an IP address. Many computers on the Internet can register to get a nice, mnemonic name, like: python.org > In other words (or plain english), what information do I need to get a > connection with another computer (IP address, name, IP name)? Also, > could you tell me how to find it on a computer? Either IP address or name should be sufficient. For example, here's a little snippet of code that shows how we might contact the web server on Python.org. (Note that in real life, we'd probably use the 'urllib' library instead.): ###### >>> import socket >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.connect(("python.org", 80)) >>> s.send("GET /\n") 6 >>> s.recv(20) ' Hi all, I have a case like this toy code: import random list1 = [1,2,3] list2 = ['a', 'b', 'c'] item = random.choice(list1 +list2) if item in list1: others = list2 else: others = list1 Another way occurred to me, but I wonder if I'm being too cute: item = random.choice(list1 +list2) others = [list1, list2][item in list1] I believe we can rely on True and False being 1 and 0 until Python 3.0. But, even assuming that's right, I wonder if it is obscure to others. Thanks and best, Brian vdB From bgailer at alum.rpi.edu Mon Dec 12 03:58:09 2005 From: bgailer at alum.rpi.edu (bob) Date: Sun, 11 Dec 2005 18:58:09 -0800 Subject: [Tutor] advice on idiom replacing if test requested In-Reply-To: <439CC10E.1050909@cc.umanitoba.ca> References: <439CC10E.1050909@cc.umanitoba.ca> Message-ID: <7.0.0.16.0.20051211182740.02273d88@alum.rpi.edu> At 04:15 PM 12/11/2005, Brian van den Broek wrote: >Hi all, > >I have a case like this toy code: > >import random >list1 = [1,2,3] >list2 = ['a', 'b', 'c'] >item = random.choice(list1 +list2) >if item in list1: > others = list2 >else: > others = list1 > > >Another way occurred to me, but I wonder if I'm being too cute: > >item = random.choice(list1 +list2) >others = [list1, list2][item in list1] > >I believe we can rely on True and False being 1 and 0 until Python >3.0. But, even assuming that's right, I wonder if it is obscure to others. It is not obscure to me. I do tings like that all the time. But I think your algorithm is unnecessarily complex and costly. Consider import random list1 = [1,2,3] list2 = ['a', 'b', 'c'] len1 = len(list1) len2 = len(list2) item = random.randint(1, len1 + len2) if item <= len1: others = list2 else: others = list1 But then we also could: import random ... same as above lists = [list1, list2] others = lists[random.randint(1, len1 + len2) <= len1] From dyoo at hkn.eecs.berkeley.edu Mon Dec 12 05:13:00 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 11 Dec 2005 20:13:00 -0800 (PST) Subject: [Tutor] advice on idiom replacing if test requested In-Reply-To: <439CC10E.1050909@cc.umanitoba.ca> Message-ID: On Sun, 11 Dec 2005, Brian van den Broek wrote: > I have a case like this toy code: > > import random > list1 = [1,2,3] > list2 = ['a', 'b', 'c'] > item = random.choice(list1 +list2) > if item in list1: > others = list2 > else: > others = list1 Hi Brian, This code works, and as long as you give it a good function name, I think it's fine the way it is. If we're concerned with efficiency, we might want to change the random.choice() call to a random.randrange(), to avoid building the concatenation of list1 and list2. This looks like: #### def sampleFromTwoLists(list1, list2): """Given two lists, returns a random element out of one of the lists as well as the other list.""" index = random.randrange(len(list1) + len(list2)) if index < len(list1): return list1[index], list2 else: return list2[index - len(list1)], list1 #### Just out of curiosity, are you planning to do some kind of stratified sampling with this? > Another way occurred to me, but I wonder if I'm being too cute: > > item = random.choice(list1 +list2) > others = [list1, list2][item in list1] Too cute. *grin* Although it's concise, I'm having a hard time reading it. Talk to you later! From broek at cc.umanitoba.ca Mon Dec 12 05:46:33 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 11 Dec 2005 22:46:33 -0600 Subject: [Tutor] advice on idiom replacing if test requested In-Reply-To: References: Message-ID: <439D00A9.3050104@cc.umanitoba.ca> Danny Yoo said unto the world upon 2005-12-11 22:13: > > On Sun, 11 Dec 2005, Brian van den Broek wrote: > > >>I have a case like this toy code: >> >>import random >>list1 = [1,2,3] >>list2 = ['a', 'b', 'c'] >>item = random.choice(list1 +list2) >>if item in list1: >> others = list2 >>else: >> others = list1 > > > Hi Brian, > > This code works, and as long as you give it a good function name, I think > it's fine the way it is. > > If we're concerned with efficiency, Hi Danny, thanks for the reply. My concern wasn't efficiency, but screen space. I'm refactoring some code and had a method that was too long. I was trying to fix it while avoiding real work :-) > we might want to change the > random.choice() call to a random.randrange(), to avoid building the > concatenation of list1 and list2. This looks like: > > #### > def sampleFromTwoLists(list1, list2): > """Given two lists, returns a random element out of one of the lists > as well as the other list.""" > index = random.randrange(len(list1) + len(list2)) > if index < len(list1): > return list1[index], list2 > else: > return list2[index - len(list1)], list1 > #### > > Just out of curiosity, are you planning to do some kind of stratified > sampling with this? Thanks for the example. Nothing so interesting as that, I'm afraid :-) I'm just goofing around with a text-based game, so efficiency isn't an issue. The two list represent teams of characters and the point of the code is to select a random character and oppose them to the other team. >>Another way occurred to me, but I wonder if I'm being too cute: >> >>item = random.choice(list1 +list2) >>others = [list1, list2][item in list1] > > > Too cute. *grin* Although it's concise, I'm having a hard time reading > it. Thanks for the feedback. I still don't trust my intuitions on issues like this. Best to all, Brian vdB From ajikoe at gmail.com Mon Dec 12 10:41:17 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 12 Dec 2005 10:41:17 +0100 Subject: [Tutor] information needed to make a connection between computers In-Reply-To: <20051211190141.89870.qmail@web33610.mail.mud.yahoo.com> References: <20051211190141.89870.qmail@web33610.mail.mud.yahoo.com> Message-ID: yes you can do that in python. But I recommend to use pyro. http://pyro.sourceforge.net/ pujo On 12/11/05, John Walton wrote: > > Hello again! I'm still working on that instant messenger (for science > fair), and I have been reading about networking in some Java tutorials. In > one part of it, it said to have a connection with another computer, you need > to know the IP name of the computer you want to connect with. I don't know > whether or not this is the same for Python, but could someone please tell me > what information of the computer you want to connect with the you actually > need for a connection? In other words (or plain english), what information > do I need to get a connection with another computer (IP address, name, IP > name)? Also, could you tell me how to find it on a computer? Since I'll be > testing the instant messenger on the three computers in my house, I just > need to know how to find the information on the computer I'd currently be on > (not from any remote location). Thanks! :) > -John > > ------------------------------ > Yahoo! Shopping > Find Great Deals on Holiday Gifts at Yahoo! Shopping > > > _______________________________________________ > 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/20051212/ca5236e2/attachment.html From kent37 at tds.net Mon Dec 12 12:01:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Dec 2005 06:01:43 -0500 Subject: [Tutor] information needed to make a connection between computers In-Reply-To: <20051211190141.89870.qmail@web33610.mail.mud.yahoo.com> References: <20051211190141.89870.qmail@web33610.mail.mud.yahoo.com> Message-ID: <439D5897.2050302@tds.net> John Walton wrote: > please tell me what information of the computer you want to connect with > the you actually need for a connection? In other words (or plain > english), what information do I need to get a connection with another > computer (IP address, name, IP name)? Also, could you tell me how to > find it on a computer? You need the IP address or domain name. On Windows you can find out the IP address by typing the command > ipconfig in a command window. Kent From davholla2002 at yahoo.co.uk Mon Dec 12 14:24:36 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon, 12 Dec 2005 13:24:36 +0000 (GMT) Subject: [Tutor] Currency conversion Message-ID: <20051212132436.54367.qmail@web25903.mail.ukl.yahoo.com> Apologies if anyone has said this and I missed it, but wouldn't it be better to change :- "def rupees_from_dollars(d_doll): return 43*(d_doll) etc to" :- "def conversiond_doll, x): return x*(d_doll) " And in the main for eg dollars to dollar_amount = conversionsion(doll, dollarexchange rate) etc You can then have one function for all currencies and would be less code and easier to maintain. ___________________________________________________________ Yahoo! Exclusive Xmas Game, help Santa with his celebrity party - http://santas-christmas-party.yahoo.net/ From pekka.henrik.karjalainen at googlemail.com Mon Dec 12 16:49:16 2005 From: pekka.henrik.karjalainen at googlemail.com (Pekka Karjalainen) Date: Mon, 12 Dec 2005 17:49:16 +0200 Subject: [Tutor] Please review my code - a simple iterator thingy to make round-robin pairings Message-ID: <1a1cc2160512120749tbc0fb5fgcd921d2f078b720c@mail.gmail.com> I hope my code and comments are clear enough for you to work out what I want to do. Please review my code, my commenting and give some advice on how to use the testing module. This is a fairly trivial example, but I'd like to learn how to make & run tests properly, so as to use them with Real Code. I'm looking forward to your replies. Pekka (first posting, I hope the code doesn't break in transit) # rrobin.py - Round-robin pairing algorithm # Implementation of the standard Round-robin pairing algorithm. See: # http://en.wikipedia.org/wiki/Round-robin_tournament # # The algorithm works as follows. Assume an even number of # participants, since with odd numbers a dummy player can be added. # (Drawing the dummy as opponent means having a free round.) Let there be # n players, with n even. # # Initially the players are in a list ordered by their number from 1 to # n. Pair each players number k from 0 to n/2-1 with number n-k-1 in the # first round. Then modify the list as follows for all successive # rounds. There are total of n-1 rounds. (NB: k starts from 0 as in # Python list indices.) # # To modify the list for further rounds, first fix player 1. Then place # the last player in the list after player 1, which causes the other # players' positions to move higher by one step each. After this the # pairing proceeds as in the first round, using the player's current # position in the list. # # Additionally, colors are often important, e.g. in chess. However, it is # not possible to assign colors perfectly fairly. # # The fairest possible color assignment follows from fixing the colors # by playing position in all tables except where player 1 plays. Have # player 1 draw alternating colors on alternating rounds. In this # program the colors are indicated by the pairing order, so # # ("player1", "player2") implies player 1 has white and # ("player2", "player1") implies player 1 has black (v.v. for pl. 2) # # This program creates an iterator that returns a list of tuples # indicating the pairings for each round in order. Its input is a list # of players. Passing a list of players' names as strings works well. # # Written by Pekka Karjalainen December 2005 # This code is in the public domain. class RoundRobinPairs (object): """Iterator for Round-robin pairing. The constructor takes a list of players (strings recommended) and an optional argument indicating the possible empty player needed to round up to even players. By default this is the string 'empty', and it is placed in the beginning of the list. """ # the constructor def __init__ (self,players,empty="empty"): if len(players)%2: players.insert(0,empty) self.players = players[:] # copy, so can modify self.times = 0 # the iterator protocol def __iter__ (self): return self # next() def next(self): "Returns the next pairing." self.times += 1 n = len(self.players) if self.times == n: # max number of rounds is len -1 raise StopIteration # only modify list on later passes if self.times > 1: mover=self.players.pop() self.players.insert(1,mover) # build pairings pairings = [] for k in range(n/2): playwhite = self.players[k] playblack = self.players[n-k-1] # switch colors on every odd table and on first table # every other round for balanced colors if (self.times%2 and k==0) or (k%2): playblack,playwhite = playwhite,playblack pairings.append( (playwhite,playblack) ) # parens make tuple return pairings # End of class defn def main(): # default small odd pairing mylist = ["player1","player2","player3","player4","player5"] pairs = RoundRobinPairs (mylist) for pairing in pairs: print pairing if __name__=="__main__": main() From mi.janssen at gmail.com Mon Dec 12 19:42:57 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Mon, 12 Dec 2005 19:42:57 +0100 Subject: [Tutor] Currency conversion In-Reply-To: <20051212132436.54367.qmail@web25903.mail.ukl.yahoo.com> References: <20051212132436.54367.qmail@web25903.mail.ukl.yahoo.com> Message-ID: <1ff2dfbf0512121042l1596e49ah4cf0dc6417fc9dd7@mail.gmail.com> On 12/12/05, David Holland wrote: > wouldn't it be better to change :- > "def rupees_from_dollars(d_doll): > return 43*(d_doll) > > etc to" :- > "def conversiond_doll, x): > return x*(d_doll) > " > You can then have one function for all currencies and > would be less code and easier to maintain. Having just one function instead of several is fine, perhaps even for the cost of one additional function argument. Good to maintain, nice flexibility. OTOH usability is important, too. Eg. I'm always driven crazy by concurrency conversions, never can imaging what to take and what to get, so I prefer a single pretty clear named function for my use case like "rupees_from_dollars" instead of a "conversion(d_doll, dollar_exchange_rate)" (the hard thing for me is to remember, if it must be dollar_exchange_rate or 1/dollar_exchange_rate) What you can often/sometimes find in code is an all purpose function/class with full flexibility and additionally some easy-to-use functions provided for the common case. As in the email package with it's message_from_string and message_from_file functions. You can read about them and their relationship to the package in: http://docs.python.org/lib/node584.html regards Michael From dyoo at hkn.eecs.berkeley.edu Mon Dec 12 19:52:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 12 Dec 2005 10:52:53 -0800 (PST) Subject: [Tutor] Please review my code - a simple iterator thingy to make round-robin pairings In-Reply-To: <1a1cc2160512120749tbc0fb5fgcd921d2f078b720c@mail.gmail.com> Message-ID: On Mon, 12 Dec 2005, Pekka Karjalainen wrote: > I hope my code and comments are clear enough for you to work out what I > want to do. Please review my code, my commenting and give some advice on > how to use the testing module. This is a fairly trivial example, but I'd > like to learn how to make & run tests properly, so as to use them with > Real Code. I'm looking forward to your replies. Hi Pekka, One thing you can add is unit tests to see that your program is doing what you expect. There's a great example of how unit tests work in Mark Pilgrim's "Dive into Python": http://diveintopython.org/unit_testing/index.html and the things they talk about there can be applied to your program. Have you played with 'unittest' before? Some casual comments so far: > # the constructor > def __init__ (self,players,empty="empty"): > if len(players)%2: players.insert(0,empty) > self.players = players[:] # copy, so can modify > self.times = 0 We might want to interchange the list copying with the code that ensures len(players) is even. Otherwise, the caller can see mutation of their input list, which goes contrary to doing the list copy in the first place. *grin* Otherwise, the main thing I'd recommend is to back the algorithm with unit tests; the implementation has some subtle details (like interchanging colors) that has enough special cases to make me a little hesitant. Unit testing would help us to have more confidence in those special cases. Otherwise, looks good! Good luck! From mosinu at gmail.com Mon Dec 12 20:50:13 2005 From: mosinu at gmail.com (Will Harris) Date: Mon, 12 Dec 2005 14:50:13 -0500 Subject: [Tutor] Editors Message-ID: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> Any of you familar with SPE? I found this just recently on freshmeat and was curious if anyone had used it? If so how well it works and what not. This caught my attention because its cross platform (written in python). -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051212/08f74b5a/attachment.htm From moparfan90 at gmail.com Mon Dec 12 23:12:33 2005 From: moparfan90 at gmail.com (moparfan90) Date: Mon, 12 Dec 2005 14:12:33 -0800 Subject: [Tutor] (no subject) Message-ID: <9560d3c0512121412n59849e9fv2ede27c87216f8d4@mail.gmail.com> hello. i want to mke a program that will do a couple of things that are hard to do: -keep track of what it does.. and learn from what the user does in a sense -be in a nice looking setup.. like Tkinter or something similar -and always know that uptodate time and weather if possible i know this seem crazy but ill start it and when someone replys ill email it to you. thanks ~ moparfan90 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051212/ebe415e6/attachment.html From ismaelgf at adinet.com.uy Tue Dec 13 06:07:12 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Tue, 13 Dec 2005 03:07:12 -0200 Subject: [Tutor] Editors In-Reply-To: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> Message-ID: <439E5700.2080606@adinet.com.uy> Will Harris wrote: > Any of you familar with SPE > > ? I found this just recently on freshmeat and was curious if anyone > had used it? If so how well it works and what not. This caught my > attention because its cross platform (written in python). Try it. :) I don't like that it's not able to run all that IDLE can run... Things like pygame don't go well with SPE. BTW: Does anyone know how to change the color configuration? I really like IDLE's one.. Kinda grew up with that one, I'd love to see it in SPE Ismael From pekka.henrik.karjalainen at googlemail.com Tue Dec 13 08:32:45 2005 From: pekka.henrik.karjalainen at googlemail.com (Pekka Karjalainen) Date: Tue, 13 Dec 2005 09:32:45 +0200 Subject: [Tutor] Please review my code - a simple iterator thingy to make round-robin pairings In-Reply-To: References: <1a1cc2160512120749tbc0fb5fgcd921d2f078b720c@mail.gmail.com> Message-ID: <1a1cc2160512122332i5e737d7akfc643526a8f2d58b@mail.gmail.com> Thank you for the response, Danny! On 12/12/05, Danny Yoo wrote: > > One thing you can add is unit tests to see that your program is doing what > you expect. There's a great example of how unit tests work in Mark > Pilgrim's "Dive into Python": > > http://diveintopython.org/unit_testing/index.html > > and the things they talk about there can be applied to your program. > Have you played with 'unittest' before? It's time I started. I'll look there first and work on it. > We might want to interchange the list copying with the code that ensures > len(players) is even. Otherwise, the caller can see mutation of their > input list, which goes contrary to doing the list copy in the first place. > *grin* That's a very good point. Noted. > Otherwise, the main thing I'd recommend is to back the algorithm with unit > tests; the implementation has some subtle details (like interchanging > colors) that has enough special cases to make me a little hesitant. Unit > testing would help us to have more confidence in those special cases. > Otherwise, looks good! I have an informal, but to my mind solid, proof for it working elsewhere. But being aware of what even Don Knuth thinks of correctness proofs wrt to programs ("I've only proved it correct..."), I'm not going to disregard testing. Time to think of good test cases now and do some reading. Thanks for the heads up. (Also, I should check how to handle empty lists.) Pekka From broek at cc.umanitoba.ca Tue Dec 13 19:23:54 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 13 Dec 2005 12:23:54 -0600 Subject: [Tutor] Editors In-Reply-To: <439E5700.2080606@adinet.com.uy> References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> Message-ID: <439F11BA.9010602@cc.umanitoba.ca> Ismael Garrido said unto the world upon 2005-12-12 23:07: > Will Harris wrote: > > >>Any of you familar with SPE >> >>? I found this just recently on freshmeat and was curious if anyone >>had used it? If so how well it works and what not. This caught my >>attention because its cross platform (written in python). > > > Try it. :) > > I don't like that it's not able to run all that IDLE can run... Things > like pygame don't go well with SPE. > > BTW: Does anyone know how to change the color configuration? I really > like IDLE's one.. Kinda grew up with that one, I'd love to see it in SPE > > Ismael Hi Ismael, Will, and all, I've just started using spe in the last week or so. I'm still undecided if the interface is too busy, or if the extra tools make it worthwhile. I share Ismael's preference for IDLE's colour scheme. I've yet to fix it, but I did get as far as reading this spe forum post which points out the file to change by hand. The definitions live in the PythonBaseSTC.SetStyles method of that module. I've not yet done the changes save for getting rid of italics on the comments, but that worked just fine. (Ismael, if you do it, would you mind emailing me the changed text privately? Thanks.) Best to all, Brian vdB From broek at cc.umanitoba.ca Tue Dec 13 20:15:03 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 13 Dec 2005 13:15:03 -0600 Subject: [Tutor] Editors In-Reply-To: <439F11BA.9010602@cc.umanitoba.ca> References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> <439F11BA.9010602@cc.umanitoba.ca> Message-ID: <439F1DB7.2000302@cc.umanitoba.ca> Brian van den Broek said unto the world upon 2005-12-13 12:23: > Ismael Garrido said unto the world upon 2005-12-12 23:07: >>BTW: Does anyone know how to change the color configuration? I really >>like IDLE's one.. Kinda grew up with that one, I'd love to see it in SPE >> >>Ismael > > > > Hi Ismael, Will, and all, > I share Ismael's preference for IDLE's colour scheme. I've yet to fix > it, but I did get as far as reading this spe forum post > > which points out the file to change by hand. > > The definitions live in the PythonBaseSTC.SetStyles method of that > module. I've not yet done the changes save for getting rid of italics > on the comments, but that worked just fine. > > (Ismael, if you do it, would you mind emailing me the changed text > privately? Thanks.) Hi all, sorry for the self reply. I got motivated and largely got SPE to use the IDLE colour scheme. I've emailed it to Ismael. If anyone else want is, write me privately. Best to all, Brian vdB From norman at littletank.org Tue Dec 13 20:38:11 2005 From: norman at littletank.org (Norman Silverstone) Date: Tue, 13 Dec 2005 19:38:11 +0000 Subject: [Tutor] Editors In-Reply-To: <439F1DB7.2000302@cc.umanitoba.ca> References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> <439F11BA.9010602@cc.umanitoba.ca> <439F1DB7.2000302@cc.umanitoba.ca> Message-ID: <1134502691.22883.1.camel@localhost.localdomain> > sorry for the self reply. I got motivated and largely got SPE to use > the IDLE colour scheme. I've emailed it to Ismael. If anyone else want > is, write me privately. Just out of interest I use Ubuntu Linux and gedit is the editor. Norman From broek at cc.umanitoba.ca Tue Dec 13 22:14:37 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 13 Dec 2005 15:14:37 -0600 Subject: [Tutor] better way to make __repr__ methods for family of similar classes Message-ID: <439F39BD.4080008@cc.umanitoba.ca> Hi all, I think I must be doing something incorrectly. I have a family of classes that all have the same arguments to their __init__ methods. I want to give them all __repr__ methods. From the docs, this method should be written so that it looks like "a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment)." If I understand that aright, this means each __repr__ method needs to know the name of the class that it is a method of. So, naively, I end up with something not too far from: class A1(object): def __init__(self, arg1, arg2): # code here def __repr__(self): return "A1(self.arg1, self.arg2)" class A2(object): def __init__(self, arg1, arg2): # code here def __repr__(self): return "A2(self.arg1, self.arg2)" (Not too far from as I am including the module name. So module.An rather than An. This feels fine as the module I am writing will never be run directly in real use.) But, as I have more than 30 classes all with the same signature, this starts to seem silly. What I have come up with is: class _A_Base(object): def __init__(self, arg1, arg2): # code here def __repr__(self): # str(self.__class__).split("'")[1] as # str(self.__class__) returns something of the form # and the split("'"[1] pulls # out module.classname return "%s%s" %(str(self.__class__).split("'")[1], (self.arg1, self.arg2)) class A1(_A_Base): def __init__(self, arg1, arg2): # code here etc. This feels smelly and I think that the desire to give a family of similar classes __repr__ methods must be common enough that there will be a better way I am not thinking of. Thanks for any suggestions, Brian vdB From kent37 at tds.net Tue Dec 13 23:34:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Dec 2005 17:34:21 -0500 Subject: [Tutor] better way to make __repr__ methods for family of similar classes In-Reply-To: <439F39BD.4080008@cc.umanitoba.ca> References: <439F39BD.4080008@cc.umanitoba.ca> Message-ID: <439F4C6D.7000304@tds.net> Brian van den Broek wrote: > Hi all, > > I think I must be doing something incorrectly. I have a family of > classes that all have the same arguments to their __init__ methods. > > I want to give them all __repr__ methods. From the docs, this method > should be written so that it looks like "a valid Python expression > that could be used to recreate an object with the same value (given an > appropriate environment)." > > What I have come up with is: > > class _A_Base(object): > def __init__(self, arg1, arg2): > # code here > def __repr__(self): > # str(self.__class__).split("'")[1] as > # str(self.__class__) returns something of the form > # and the split("'"[1] pulls > # out module.classname > return "%s%s" %(str(self.__class__).split("'")[1], > (self.arg1, self.arg2)) > > class A1(_A_Base): > def __init__(self, arg1, arg2): > # code here > > etc. > > > This feels smelly and I think that the desire to give a family of > similar classes __repr__ methods must be common enough that there will > be a better way I am not thinking of. You can use self.__class__.__module__ and self.__class__.__name__ instead of parsing str(self.__class__). You could use a metaclass instead of a common base class. There are some dubious advantages to this approach: - your classes don't have to inherit from a common base - you can set the custom __repr__ for all classes in a module by assigning __metaclass__ at the module (instead of class) level. For example: class AutoRepr(type): def __init__(cls, name, bases, d): super(type, cls).__init__(name, bases, d) def __repr__(self): return '%s.%s(%s, %s)' % (cls.__module__, cls.__name__, self.arg1, self.arg2) setattr(cls, '__repr__', __repr__) __metaclass__ = AutoRepr # This makes AutoRepr be the meta class of A1 class A1: def __init__(self, arg1, arg2): self.arg1 = arg1 self.arg2 = arg2 a=A1(1, 2) print repr(a) prints: __main__.A1(1, 2) Kent From broek at cc.umanitoba.ca Wed Dec 14 01:33:34 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 13 Dec 2005 18:33:34 -0600 Subject: [Tutor] better way to make __repr__ methods for family of similar classes In-Reply-To: <439F4C6D.7000304@tds.net> References: <439F39BD.4080008@cc.umanitoba.ca> <439F4C6D.7000304@tds.net> Message-ID: <439F685E.1020805@cc.umanitoba.ca> Kent Johnson said unto the world upon 2005-12-13 16:34: > Brian van den Broek wrote: > >>Hi all, >> >>I think I must be doing something incorrectly. I have a family of >>classes that all have the same arguments to their __init__ methods. >> >>I want to give them all __repr__ methods. From the docs, this method >>should be written so that it looks like "a valid Python expression >>that could be used to recreate an object with the same value (given an >>appropriate environment)." >> >>What I have come up with is: >> >>class _A_Base(object): >> def __init__(self, arg1, arg2): >> # code here >> def __repr__(self): >> # str(self.__class__).split("'")[1] as >> # str(self.__class__) returns something of the form >> # and the split("'"[1] pulls >> # out module.classname >> return "%s%s" %(str(self.__class__).split("'")[1], >> (self.arg1, self.arg2)) >> >>class A1(_A_Base): >> def __init__(self, arg1, arg2): >> # code here >> >>etc. >> >> >>This feels smelly and I think that the desire to give a family of >>similar classes __repr__ methods must be common enough that there will >>be a better way I am not thinking of. > > > You can use self.__class__.__module__ and self.__class__.__name__ > instead of parsing str(self.__class__). Hi Kent, thanks! I knew there had to be an easier way that the manual parse. I tried to find it with dir(), but now I see this as odd: >>> class A(object):pass >>> a=A() >>> dir(a.__class__) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> a.__class__.__name__ 'A' >>> So, a.__class__ has a __name__ attribute, but dir() doesn't know about it. Odd. Is there a reason for the dir-invisibility of the __name__ attribute that you know of? I just checked, and the docs say that dir's returned list is "is not necessarily complete" . which I did not know. > You could use a metaclass instead of a common base class. There are some > dubious advantages to this approach: > - your classes don't have to inherit from a common base In my case, I actually need a common base anyway, so this is no temptation. I can see how it would be if the classes didn't actually all have a conceptually common "is a" ancestor, though. > - you can set the custom __repr__ for all classes in a module by > assigning __metaclass__ at the module (instead of class) level. > > For example: > > class AutoRepr(type): > def __init__(cls, name, bases, d): > super(type, cls).__init__(name, bases, d) > > def __repr__(self): > return '%s.%s(%s, %s)' % (cls.__module__, cls.__name__, > self.arg1, self.arg2) > > setattr(cls, '__repr__', __repr__) > > __metaclass__ = AutoRepr # This makes AutoRepr be the meta class of A1 > > class A1: > def __init__(self, arg1, arg2): > self.arg1 = arg1 > self.arg2 = arg2 > > a=A1(1, 2) > > print repr(a) > > > prints: > __main__.A1(1, 2) That's pretty cool! I think I'm going to have to try to unpack what's going on and then play with it to see if I can make it work with variable signatures, etc. Thanks for showing it. Best, Brian vdB From kent37 at tds.net Wed Dec 14 03:57:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Dec 2005 21:57:47 -0500 Subject: [Tutor] better way to make __repr__ methods for family of similar classes In-Reply-To: <439F685E.1020805@cc.umanitoba.ca> References: <439F39BD.4080008@cc.umanitoba.ca> <439F4C6D.7000304@tds.net> <439F685E.1020805@cc.umanitoba.ca> Message-ID: <439F8A2B.2050506@tds.net> Brian van den Broek wrote: > Kent Johnson said unto the world upon 2005-12-13 16:34: >>You can use self.__class__.__module__ and self.__class__.__name__ >>instead of parsing str(self.__class__). > > thanks! I knew there had to be an easier way that the manual parse. I > tried to find it with dir(), but now I see this as odd: > > >>> class A(object):pass > > >>> a=A() > >>> dir(a.__class__) > ['__class__', '__delattr__', '__dict__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > '__weakref__'] > >>> a.__class__.__name__ > 'A' > >>> > > So, a.__class__ has a __name__ attribute, but dir() doesn't know about > it. Odd. Is there a reason for the dir-invisibility of the __name__ > attribute that you know of? __name__ is an attribute of 'type' - the class of the class of A: >>> dir(type) ['__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', '__flags__', '__getattribute__', '__hash__', '__init__', '__itemsize__', '__module__', '__mro__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasses__', '__weakrefoffset__', 'mro'] None of these show up when you do dir(A). The guts of the dir() function are in Objects\object.c in the Python source. A comment in PyObject_Dir() says, /* Elif some form of type or class, grab its dict and its bases. We deliberately don't suck up its __class__, as methods belonging to the metaclass would probably be more confusing than helpful. */ So metaclass attributes are deliberately left out. In general I think they would be confusing, if you did dir(A) and saw __getattribute__ and __setattr__, for example, you would think the class was doing some attribute magic, but they might just be the metaclass attributes which do the normal class magic :-) > > I just checked, and the docs say that dir's returned list is "is not > necessarily complete" . > which I did not know. The docs also say, "it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names". So it is someone's judgement of what is useful. >>- you can set the custom __repr__ for all classes in a module by >>assigning __metaclass__ at the module (instead of class) level. >> >>For example: >> >>class AutoRepr(type): >> def __init__(cls, name, bases, d): >> super(type, cls).__init__(name, bases, d) >> >> def __repr__(self): >> return '%s.%s(%s, %s)' % (cls.__module__, cls.__name__, >>self.arg1, self.arg2) >> >> setattr(cls, '__repr__', __repr__) >> >>__metaclass__ = AutoRepr # This makes AutoRepr be the meta class of A1 >> >>class A1: >> def __init__(self, arg1, arg2): >> self.arg1 = arg1 >> self.arg2 = arg2 >> >>a=A1(1, 2) >> >>print repr(a) >> >> >>prints: >>__main__.A1(1, 2) > > > > That's pretty cool! I think I'm going to have to try to unpack what's > going on and then play with it to see if I can make it work with > variable signatures, etc. Thanks for showing it. Basically the metaclass is manipulating the class when it is created, jamming in a __repr__ function. Defining a module-level __metaclass__ variable sets the default the metaclass for any classes in the module that don't define a metaclass some other way. See Guido's "Unifying Types and Classes" essay and PEP 253 for details. And ask questions - maybe if I answer enough questions I will understand this stuff! http://www.python.org/2.2.3/descrintro.html#metaclasses http://www.python.org/peps/pep-0253.html Kent From sfbell at keasdesign.net Wed Dec 14 05:28:31 2005 From: sfbell at keasdesign.net (Steven Bell) Date: Tue, 13 Dec 2005 23:28:31 -0500 Subject: [Tutor] Editors In-Reply-To: <1134502691.22883.1.camel@localhost.localdomain> References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> <439F11BA.9010602@cc.umanitoba.ca> <439F1DB7.2000302@cc.umanitoba.ca> <1134502691.22883.1.camel@localhost.localdomain> Message-ID: <439F9F6F.4010909@keasdesign.net> Here's my two cents on ide's for Python. Idle... It's got a nice color scheme but it's tkinter gui is a bit dated and it's short many of the built-in convenience features. PyWin... Slightly better, but still feels weak to me. Win32 specific though. PyCrust (and it's derivatives) last I knew were included with wxPython the gui toolkit. wasn't a big fan of them. SPE. Just installed it yesterday and used it today on a sizable web service/plpythonu program. I was pleased in general with the color scheme, I liked the vertical lines showing indentation down through the document. I tried a couple of the fun frilly features like the run, debug and explorer a bit. It's interesting enough to keep me coming back for a bit. Jedit. Java editor. Really my swiss-army knife of development. I use it for Perl, PHP, asp, JSP, Java, Python, C++...blah blah blah... Komodo - untried, but the screenies look decent. Eclipse - tried it, found the one plugin to be ok. Seemed a bit overkill for my usual python work Boa Constructor (Mostly RAD Gui Development) complex, but very useful for those wxPython projects. Top Three: Jedit Idle (surprise!) SPE Norman Silverstone wrote: >> sorry for the self reply. I got motivated and largely got SPE to use >> the IDLE colour scheme. I've emailed it to Ismael. If anyone else want >> is, write me privately. >> > > Just out of interest I use Ubuntu Linux and gedit is the editor. > > Norman > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From broek at cc.umanitoba.ca Wed Dec 14 05:23:13 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 13 Dec 2005 22:23:13 -0600 Subject: [Tutor] better way to make __repr__ methods for family of similar classes In-Reply-To: <439F8A2B.2050506@tds.net> References: <439F39BD.4080008@cc.umanitoba.ca> <439F4C6D.7000304@tds.net> <439F685E.1020805@cc.umanitoba.ca> <439F8A2B.2050506@tds.net> Message-ID: <439F9E31.9090802@cc.umanitoba.ca> Kent Johnson said unto the world upon 2005-12-13 20:57: > See Guido's "Unifying Types and Classes" essay and PEP 253 for details. > And ask questions - maybe if I answer enough questions I will understand > this stuff! > http://www.python.org/2.2.3/descrintro.html#metaclasses > http://www.python.org/peps/pep-0253.html > Thanks for the added info, Kent; much appreciated. I'm not sure I'll have time in the immediate future to follow up (real life and all that) :-( Best, Brian vdB From tanner at real-time.com Wed Dec 14 07:32:05 2005 From: tanner at real-time.com (Bob Tanner) Date: Wed, 14 Dec 2005 00:32:05 -0600 Subject: [Tutor] ElementTree, TidyHTMLTreeBuilder, find Message-ID: Having problem understanding how find() works. The html file I'm using is attached. Python 2.4.2 (No.2, Nov 20 2005, 17:04:48) >>> from elementtidy import TidyHTMLTreeBuilder >>> doc = TidyHTMLTreeBuilder.parse('048229.html') >>> root = doc.getroot() >>> print root.find('html/body') None >>> print root.find('body') None >>> Viewing the html under firefox DOM tool -#document -HTML +HEAD #TEXT +BODY No sure how to use the find. -- Bob Tanner | Phone : (952)943-8700 http://www.real-time.com, Minnesota, Linux | Fax : (952)943-8500 Key fingerprint = AB15 0BDF BCDE 4369 5B42 1973 7CF1 A709 2CC1 B288 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051214/42288ace/048229.html From franz.steinhaeusler at gmx.at Wed Dec 14 09:57:12 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Wed, 14 Dec 2005 09:57:12 +0100 Subject: [Tutor] Editors References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> <439F11BA.9010602@cc.umanitoba.ca> <439F1DB7.2000302@cc.umanitoba.ca> <1134502691.22883.1.camel@localhost.localdomain> <439F9F6F.4010909@keasdesign.net> Message-ID: On Tue, 13 Dec 2005 23:28:31 -0500, Steven Bell wrote: >Here's my two cents on ide's for Python. >Idle... It's got a nice color scheme but it's tkinter gui is a bit dated >and it's short many of the built-in convenience features. And no calltips and autocompletion, although there exists a patch to support them. >PyWin... Slightly better, but still feels weak to me. Win32 specific though. looks nice, but I never used it. Provides Autocomplete. >PyCrust (and it's derivatives) last I knew were included with wxPython >the gui toolkit. wasn't a big fan of them. This is my favorite replacement of IDLE. Namespace viewer (this alone justifies the use of PyCrust), autocomplete and Calltips. >SPE. Just installed it yesterday and used it today on a sizable web >service/plpythonu program. I was pleased in general with the color >scheme, I liked the vertical lines showing indentation down through the >document. I tried a couple of the fun frilly features like the run, >debug and explorer a bit. It's interesting enough to keep me coming back >for a bit. Looks good and professional, but for some reasons, I don't like it. The bloated "blender" part for example. But at the other side, it has included wxGlade, the new Python debugger winpdb and a lot of nice editor functions. >Jedit. Java editor. Really my swiss-army knife of development. I use it >for Perl, PHP, asp, JSP, Java, Python, C++...blah blah blah... Bloated, slow in startup and in response of userinputs and not developed in Python itself. ;) >Komodo - untried, but the screenies look decent. Payware. >Eclipse - tried it, found the one plugin to be ok. Seemed a bit overkill >for my usual python work Never tried it seriously; seems very bloated to me. >Boa Constructor (Mostly RAD Gui Development) complex, but very useful >for those wxPython projects. Good editor functions (browse code for example). Debugger, many plugins (bycicle repair man for instance). I don't like the three parts components (how shall i say this). In Windows, you have three entries in the taskbar. > >Top Three: >Jedit DrPython ;) Many plugins are available. And it is easy to accomodate the editor to your needs (customize shortcuts, write little "DrPython scripts", make your own plugins. >Idle (surprise!) Pycrust (for interactive use and testing) >SPE SciTE. -- Franz Steinhaeusler From ml.cyresse at gmail.com Wed Dec 14 11:14:58 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 14 Dec 2005 23:14:58 +1300 Subject: [Tutor] Python - SQL paradigm (Will I need a hammer to make it fit?) Message-ID: Hi all, Just contemplating. If in Python I were organising a data index along the lines of - j = { "k_word1" : ["rec1","rec2","rec3","rec4"], ... "k_wordn" :["recX","rec4"] } and I was going to find records that matched by seeing what record occurred in the most lists (via set intersections or similar; going to have a play see what works faster) selected by searching keywords... how easily does that translate to a SQL table and query format? If I had columns k_word1 ... k_wordn rec1 recX rec2 rec4 rec3 rec4 is that even valid? Or does every row have to have a primary key? I've been looking at sqlcourse.com, and I'm thinking of having a table for each keyword, and adding each record as a primary key on that table. i.e. table k_word1 prim_key_unique rec1 rec2 rec3 rec4 And then querying each table for that primary key and then once again, return results in order of number of matches to keywords. Have I aroused anyone's Code Smell nose yet? Regards, Liam Clarke From din22 at earthlink.net Wed Dec 14 12:39:58 2005 From: din22 at earthlink.net (david) Date: Wed, 14 Dec 2005 05:39:58 -0600 Subject: [Tutor] empty class methods Message-ID: <000601c600a3$1d422060$0201a8c0@d71bh5mhis9p7o> class foo: def sayhi(self): print 'hello world' def saybye(self): ##is there any reason for this to be here? pass class bar(foo): def saybye(self): print 'bye now' class baz(foo): def saybye(self): print 'later tater' x = foo() y = bar() z = baz() x.sayhi() y.sayhi() y.saybye() z.sayhi() z.saybye() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051214/39b5328e/attachment.html From kent37 at tds.net Wed Dec 14 12:58:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Dec 2005 06:58:02 -0500 Subject: [Tutor] Python - SQL paradigm (Will I need a hammer to make it fit?) In-Reply-To: References: Message-ID: <43A008CA.5060500@tds.net> Liam Clarke wrote: > Hi all, > > Just contemplating. > > If in Python I were organising a data index along the lines of - > > j = { > > "k_word1" : ["rec1","rec2","rec3","rec4"], > ... > "k_wordn" :["recX","rec4"] > > } > > and I was going to find records that matched by seeing what record > occurred in the most lists (via set intersections or similar; going to > have a play see what works faster) selected by searching keywords... If I understand correctly, the problem is, given a selection of keywords, find the records containing any of those keywords, and show the records ordered by how many keywords they contain? If all your data fits in memory this might be a good solution. You could pickle the sets for storage and it could be fairly fast to compile the counts. Something like this (not tested!): import operator # Build a dict of counts for each record that matches the keywords counts = {} for kwd in search_words: # a list of desired keywords recs = j[kwd] for rec in recs: counts[rec] = counts.get(rec, 0) + 1 # Show the records sorted by count for rec, count in sorted(counts.iteritems(), \ key=operator.itemgetter(1)): print count, rec > > how easily does that translate to a SQL table and query format? The simplest thing would be to make a table of keyword, record pairs. Then I think you could construct a query something like this (my SQL reference is at work so this probably needs some tweaking): select record, count(*) from keyword_table where keyword = "k_word1" or keyword = "k_word3" or group by record order by count(*) > > If I had columns > > k_word1 ... k_wordn > rec1 recX > rec2 rec4 > rec3 > rec4 > > is that even valid? Or does every row have to have a primary key? It's bad database design. It implies a relation between rec1 and recX, for example, because they appear in the same row. It will only work if you have a fixed set of keywords. Bad, bad, bad database design ;) > > I've been looking at sqlcourse.com, and I'm thinking of having a table > for each keyword, and adding each record as a primary key on that > table. This reduces the database to nothing more than a bunch of sets. It hardcodes the keywords. It is awkward to access - you will end up doing a bunch of searches in each table. > > Have I aroused anyone's Code Smell nose yet? Yes. You might be interested in this book: http://www.aw-bc.com/catalog/academic/product/0,1144,0201703092,00.html Kent From kent37 at tds.net Wed Dec 14 13:08:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Dec 2005 07:08:01 -0500 Subject: [Tutor] ElementTree, TidyHTMLTreeBuilder, find In-Reply-To: References: Message-ID: <43A00B21.8000405@tds.net> Bob Tanner wrote: > Having problem understanding how find() works. > > The html file I'm using is attached. > > Python 2.4.2 (No.2, Nov 20 2005, 17:04:48) > >>>>from elementtidy import TidyHTMLTreeBuilder >>>>doc = TidyHTMLTreeBuilder.parse('048229.html') >>>>root = doc.getroot() >>>>print root.find('html/body') > > None > >>>>print root.find('body') > > None > > > Viewing the html under firefox DOM tool > > -#document > -HTML > +HEAD > #TEXT > +BODY > > No sure how to use the find. Let's try it at the interpreter prompt to see what is going on: >>> from elementtidy import TidyHTMLTreeBuilder as Tidy >>> doc = Tidy.parse(r'D:\WUTemp\temp.html') >>> doc >>> doc.find('body') >>> doc.find('BODY') >>> doc.find('//BODY') OK, that doesn't work :-) but you knew that! Let's just look at the root element: >>> doc.getroot() Ah, that explains it! TidyHTMLTreeBuilder puts the elements in a namespace. That means you have to include the namespace as part of the search string for find: >>> doc.find('{http://www.w3.org/1999/xhtml}body') That works! Kent From kent37 at tds.net Wed Dec 14 13:16:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Dec 2005 07:16:45 -0500 Subject: [Tutor] empty class methods In-Reply-To: <000601c600a3$1d422060$0201a8c0@d71bh5mhis9p7o> References: <000601c600a3$1d422060$0201a8c0@d71bh5mhis9p7o> Message-ID: <43A00D2D.4040102@tds.net> david wrote: > > > class foo: > def sayhi(self): > print 'hello world' > def saybye(self): ##is there any reason for this to be here? > pass Is foo.saybye() a default implementation or a placeholder for an 'abstract' method? A base class can have a default implementation of a method. The default is used if subclasses don't override it. In some cases a do-nothing default such as this one might be appropriate, for example if the method is a hook that subclasses override to provide specialized behaviour. A base class can have an empty implementation of a method that is there as a marker saying, "subclasses must define this". In this case, a better implementation is def saybye(self): raise NotImplementedError, "Subclasses must define saybye()" which clearly shows the intent and will cause a run time error if a subclass omits the definition of saybye(). Kent > > class bar(foo): > def saybye(self): > print 'bye now' > > class baz(foo): > def saybye(self): > print 'later tater' > > x = foo() > y = bar() > z = baz() > > x.sayhi() > y.sayhi() > y.saybye() > z.sayhi() > z.saybye() > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dndfan at hotpop.com Wed Dec 14 14:05:07 2005 From: dndfan at hotpop.com (Vlad Popescu) Date: Wed, 14 Dec 2005 15:05:07 +0200 Subject: [Tutor] Tkinter help required Message-ID: <1134565507.2694.6.camel@localhost.localdomain> Hello everyone, I have been desperately trying to get Tkinter to run, but without much success thus far. I've followed the instructions at http://wiki.python.org/moin/TkInter ; importing _tkinter does not work and I have no idea what files I should edit in order to add the module. Both Tcl and Tk, along with their -devel packages, are installed and updated. Python version is 2.4.1 Any suggestions? Thanks in advance, Vlad From burge.kurt at gmail.com Wed Dec 14 15:35:37 2005 From: burge.kurt at gmail.com (Burge Kurt) Date: Wed, 14 Dec 2005 15:35:37 +0100 Subject: [Tutor] Editors In-Reply-To: References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> <439F11BA.9010602@cc.umanitoba.ca> <439F1DB7.2000302@cc.umanitoba.ca> <1134502691.22883.1.camel@localhost.localdomain> <439F9F6F.4010909@keasdesign.net> Message-ID: Hi; I am a newbie and want to find a suitable editor for myself.. I will not need a UI implementation just thinking to make file transportation over IP. If you will guide; I would be thankful :) Burge From burge.kurt at gmail.com Wed Dec 14 15:56:53 2005 From: burge.kurt at gmail.com (Burge Kurt) Date: Wed, 14 Dec 2005 15:56:53 +0100 Subject: [Tutor] Editors In-Reply-To: References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> <439F11BA.9010602@cc.umanitoba.ca> <439F1DB7.2000302@cc.umanitoba.ca> <1134502691.22883.1.camel@localhost.localdomain> <439F9F6F.4010909@keasdesign.net> Message-ID: Btw I am using Suse Linux 9.0 .. Today I have tried to install drPython but could not manage ; because I could not install wxPython that was due to gtk problem (i was seeing pkg-config but it could not) ... Is there something easy for me ?? which does not require wxPython (consequently glib gtk atk pango pfg-config ...etc) and will not take my hours to build&install :) Burge On 12/14/05, Burge Kurt wrote: > Hi; > > I am a newbie and want to find a suitable editor for myself.. I will > not need a UI implementation just thinking to make file transportation > over IP. > > If you will guide; I would be thankful :) > > Burge > From kent37 at tds.net Wed Dec 14 16:20:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Dec 2005 10:20:04 -0500 Subject: [Tutor] Editors In-Reply-To: References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> <439F11BA.9010602@cc.umanitoba.ca> <439F1DB7.2000302@cc.umanitoba.ca> <1134502691.22883.1.camel@localhost.localdomain> <439F9F6F.4010909@keasdesign.net> Message-ID: <43A03824.6090705@tds.net> Burge Kurt wrote: > Btw I am using Suse Linux 9.0 .. > > Today I have tried to install drPython but could not manage ; because > I could not install wxPython that was due to gtk problem (i was seeing > pkg-config but it could not) ... Is there something easy for me ?? > which does not require wxPython (consequently glib gtk atk pango > pfg-config ...etc) and will not take my hours to build&install :) If you have an editor you are already comfortable with then just use that, at least to get started. If you have Tk on your computer you could try IDLE which comes with Python. Otherwise look here for a long list of possibilities: http://wiki.python.org/moin/PythonEditors Kent From burge.kurt at gmail.com Wed Dec 14 17:29:25 2005 From: burge.kurt at gmail.com (Burge Kurt) Date: Wed, 14 Dec 2005 17:29:25 +0100 Subject: [Tutor] Editors In-Reply-To: <43A03824.6090705@tds.net> References: <5faf36700512121150u44b1b5c0ie214f1a2a27f3f42@mail.gmail.com> <439E5700.2080606@adinet.com.uy> <439F11BA.9010602@cc.umanitoba.ca> <439F1DB7.2000302@cc.umanitoba.ca> <1134502691.22883.1.camel@localhost.localdomain> <439F9F6F.4010909@keasdesign.net> <43A03824.6090705@tds.net> Message-ID: Thaks to all.. I have started with Scite and may be change later; let me see first what can I do with python? Burge On 12/14/05, Kent Johnson wrote: > Burge Kurt wrote: > > Btw I am using Suse Linux 9.0 .. > > > > Today I have tried to install drPython but could not manage ; because > > I could not install wxPython that was due to gtk problem (i was seeing > > pkg-config but it could not) ... Is there something easy for me ?? > > which does not require wxPython (consequently glib gtk atk pango > > pfg-config ...etc) and will not take my hours to build&install :) > > If you have an editor you are already comfortable with then just use that, > at least to get > started. If you have Tk on your computer you could try IDLE which comes with > Python. > Otherwise look here for a long list of possibilities: > http://wiki.python.org/moin/PythonEditors > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nephish at xit.net Wed Dec 14 17:21:43 2005 From: nephish at xit.net (nephish) Date: Wed, 14 Dec 2005 16:21:43 +0000 Subject: [Tutor] dont understand this error MySQLdb Message-ID: <1134577303.8835.1.camel@localhost.localdomain> hey there, i am using the MySQLdb module and i keep getting this error, it doesnt offer much in the way of explanation _mysql_exceptions.InterfaceError: (0, '') does anyone know what this means ? thanks From klappnase at freenet.de Wed Dec 14 20:13:57 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed, 14 Dec 2005 20:13:57 +0100 Subject: [Tutor] Tkinter help required In-Reply-To: <1134565507.2694.6.camel@localhost.localdomain> References: <1134565507.2694.6.camel@localhost.localdomain> Message-ID: <20051214201357.5b8fabbb.klappnase@freenet.de> On Wed, 14 Dec 2005 15:05:07 +0200 Vlad Popescu wrote: Hi Vlad, > Hello everyone, > > I have been desperately trying to get Tkinter to run, but without much > success thus far. I've followed the instructions at > http://wiki.python.org/moin/TkInter ; importing _tkinter does not work > and I have no idea what files I should edit in order to add the module. > Both Tcl and Tk, along with their -devel packages, are installed and > updated. Python version is 2.4.1 > it looks like you are running a linux box? If so , probably Tkinter is in a separate package that may be called "tkinter" or "python-tk" or something similar, depending on the distro. May be this package is not installed? Regards Michael From Barry.Carroll at psc.com Wed Dec 14 20:13:05 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 14 Dec 2005 11:13:05 -0800 Subject: [Tutor] Scope Problem with Files Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C359F@eugsrv400.psc.pscnet.com> Greetings: I am implementing a (crude but useful) debug facility in my test system client software. Basically, I test the value of a global Boolean. It True, I write pertinent data to a text file. I want to do this in multiple functions in a module. Rather than open and close the file each time I write, I want to open the file once at the start of process and close it at the end. Here are excerpts from the module. ########################## import socket import struct import time # initialize the debug flag DEBUG = True . . . dbgf = None # File object and path for saving debug output dbgfname = "debug.txt" def snd_cmd(sock,cmd): . . . while remainlen > 0: if remainlen > MTU: pktstp = pktstrt + MTU else: pktstp = pktlen pktflags |= EOD pkthdr = struct.pack('@2BH',pktflags,seq,pktlen) sndpkt = pkthdr+cmd[pktstrt:pktstp] if DEBUG: dbgf.write("command: " + cmd + "\n") dbgf.write("flags: 0x%X, seq: %u, len: %u\n" % (pktflags, seq, pktlen)) sock.sendto(sndpkt,addr) pktstrt += MTU remainlen -= MTU pktflags = pktflags & ~SOD seq = (seq + 1) % 256 . . . def recv_resp(sock): response = '' try: response = sock.recv(MTU) except socket.timeout: errtupl = ("ERROR", 'Server did not respond') return (errtupl, response) . . . if DEBUG: dbgf.write("response: " + response + "\n") dbgf.write("flags: 0x%X, seq: %u, len: %u\n" % (flags, retseq, dlen)) . . . return (errtupl, response) def do_cmd(cmd): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(timetowait) retriesleft = retries if DEBUG: dbgf = open(dbgfname,mode="a") dbgf.write("\n"+str(time.localtime())+"\n") while retriesleft > 0: snd_cmd(sock, cmd) recvtupl = recv_resp(sock) if recvtupl[0][0] != "ERROR": break retriesleft -= 1 if DEBUG: dbgf.close() sock.close( ) return recvtupl ########################## When I run this code, I get the following error message: <<<<<<<<<<<<<<<<<<<<<<< A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /var/www/cgi-bin/pagen.py 76 # function. Check the returned error code for success. 77 cmdtosnd = state['s']['getcmd'] *****78 (errorcode, errorstr), platformstate['itype']['curstate'] = do_cmd(cmdtosnd) 79 if errorcode == 0: 80 cmdtosnd = state['t']['getcmd'] . . . /var/www/cgi-bin/Client.py in do_cmd(cmd='cmd') 160 161 while retriesleft > 0: *****162 snd_cmd(sock, cmd) 163 recvtupl = recv_resp(sock) 164 if recvtupl[0][0] != IIPSRVERROR: global snd_cmd = , sock = , cmd = 'cmd' /var/www/cgi-bin/Client.py in snd_cmd(sock=, cmd='cmd') 65 66 if DEBUG: *****67 dbgf.write("command: " + cmd + "\n") 69 global dbgf = None, dbgf.write undefined, cmd = 'cmd' AttributeError: 'NoneType' object has no attribute 'write' args = ("'NoneType' object has no attribute 'write'",) >>>>>>>>>>>>>>>>>>>>>>> dbgf is declared at the top of the module. It is opened and closed in do_cmd. I attempt to write to it in snd_cmd and recv_resp, both of which are called by do_cmd. Since dbgf is global to all of these functions, I expected its value (the open file object) to persist. I don't understand why it didn't. I expect I have misunderstood Python's scoping rules. Can someone enlighten me? Thanks and enjoy the holidays. BGC ________________________ "Never trust anything that can think for itself if you can't see where it keeps its brain" JK Rowling ? From broek at cc.umanitoba.ca Wed Dec 14 20:37:17 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 14 Dec 2005 13:37:17 -0600 Subject: [Tutor] empty class methods In-Reply-To: <000601c600a3$1d422060$0201a8c0@d71bh5mhis9p7o> References: <000601c600a3$1d422060$0201a8c0@d71bh5mhis9p7o> Message-ID: <43A0746D.5000909@cc.umanitoba.ca> david said unto the world upon 2005-12-14 05:39: > > class foo: > def sayhi(self): > print 'hello world' > def saybye(self): ##is there any reason for this to be here? > pass > > class bar(foo): > def saybye(self): > print 'bye now' > > class baz(foo): > def saybye(self): > print 'later tater' > Hi David, as Kent pointed out, a baseclass hook method is a common use case. When I do that I write it as follows: class foo: def saybye(self): '''Hook method for subclasses to override''' pass which makes it abundantly clear :-) The other reason I sometime use pass is if I've had a Big Design[1] idea and want to put in stub methods before I lose the overall picture. Then the pass is there just to make the code legal while the existence of the method name reminds me I wanted to make an actual method. def a_method(self): pass # FIXME stub [1] Whether I ought give in to Big Design Ideas is, of course, a separate question :-) HTH, Brian vdB From kent37 at tds.net Wed Dec 14 21:20:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Dec 2005 15:20:38 -0500 Subject: [Tutor] ElementTree in Python 2.5! Message-ID: <43A07E96.4030803@tds.net> By some miracle of the gods smiling and the planets aligning, a comp.lang.python thread that started with the question "ElementTree - Why not part of the core?" has actually resulted in ElementTree *becoming* part of the core for Python 2.5! Pretty cool! So the core Python distribution will finally have a Pythonic XML processor. Kent http://groups.google.com/group/comp.lang.python/browse_frm/thread/e095cc79d1efb99/a4523a6e9b7061af?rnum=1#a4523a6e9b7061af From kent_johnson at skillsoft.com Wed Dec 14 21:06:48 2005 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed, 14 Dec 2005 15:06:48 -0500 Subject: [Tutor] ElementTree in Python 2.5! Message-ID: <43A07B58.70606@skillsoft.com> By some miracle of the gods smiling and the planets aligning, a comp.lang.python thread that started with the question "ElementTree - Why not part of the core?" has actually resulted in ElementTree *becoming* part of the core for Python 2.5! Pretty cool! So the core Python distribution will finally have a Pythonic XML processor. Kent http://groups.google.com/group/comp.lang.python/browse_frm/thread/e095cc79d1efb99/a4523a6e9b7061af?rnum=1#a4523a6e9b7061af From tdwdotnet at gmail.com Sun Dec 11 20:25:46 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Sun, 11 Dec 2005 19:25:46 +0000 Subject: [Tutor] information needed to make a connection between computers In-Reply-To: References: Message-ID: <9afea2ac0512111125h758ecd01s@mail.gmail.com> On 11/12/05, John Walton wrote: > > Hello again! I'm still working on that instant messenger (for science > fair), and I have been reading about networking in some Java tutorials. In > one part of it, it said to have a connection with another computer, you need > to know the IP name of the computer you want to connect with. I don't know > whether or not this is the same for Python, but could someone please tell me > what information of the computer you want to connect with the you actually > need for a connection? In other words (or plain english), what information > do I need to get a connection with another computer (IP address, name, IP > name)? Also, could you tell me how to find it on a computer? Since I'll be > testing the instant messenger on the three computers in my house, I just > need to know how to find the information on the computer I'd currently be on > (not from any remote location). Thanks! :) > You need to know the hostname of the remote machine you are trying to make a connection to. From this you can work out the IP address of the machine and then connect to it directly. You could work with just the IP address, but these are liable to change, where as the hostname in theory won't. >>> import socket >>> socket.gethostbyname('www.yahoo.com') '216.109.117.207' >>> If the machine is on your network, using its name (eg 'JohnW' ) should give the same result HTH :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051211/3c80f4f2/attachment.html From falcon3166 at hotmail.com Wed Dec 14 21:22:29 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 14 Dec 2005 13:22:29 -0700 Subject: [Tutor] Is this a good idea to improve my currency program? Message-ID: I was thinking of using a dictionary to hold the currency exchange rates, and saving it to a file, and loading it every time the program opens. It still would not be GUI, but it would be a step towards a better program, I believe. Is this a good idea, or is there stronger ways of doing it? Thanks Nathan Pinno, MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051214/34d4739a/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051214/34d4739a/attachment-0001.gif From tubaranger at gmail.com Wed Dec 14 22:01:04 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Wed, 14 Dec 2005 15:01:04 -0600 Subject: [Tutor] Is this a good idea to improve my currency program? Message-ID: <57aa55060512141301q5daeb9c1wba9cb3f246c1cced@mail.gmail.com> >I was thinking of using a dictionary to hold the currency exchange rates, >and saving it to a file, and loading it every time the program opens. It >still would not be GUI, but it would be a step towards a better program, I >believe. Is this a good idea, or is there stronger ways of doing it? Is it possible to load your exchange rates in a database? That way changes can be made without opening up your code everytime. --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051214/c8159216/attachment.htm From falcon3166 at hotmail.com Wed Dec 14 22:58:46 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 14 Dec 2005 14:58:46 -0700 Subject: [Tutor] How do I fix this error so that my exchange rates program will work? Message-ID: I added the dictionary and loading and saving for the rates in my exchange currency rates program, and when I ran it, I got the following error: Traceback (most recent call last): File "D:\Python24\exchange.py", line 84, in -toplevel- save_rates(rates) File "D:\Python24\exchange.py", line 9, in save_rates store.write(rate + '\n') TypeError: unsupported operand type(s) for +: 'float' and 'str' Here is the program's code: rates = {'can_us' : 0.80276, 'us_can' : 1.245702, 'can_euro' : 1.488707, 'euro_can' : 0.671724} def save_rates(exch): store = open("exch.txt","w") for exch, rate in rates.items(): store.write(exch + '\n') store.write(rate + '\n') store.close() def load_rates(exch): import os filename = 'exch.txt' if os.path.exists(filename): store = open(filename,'r') for line in store: exch = line.strip() rates = store.next().strip() exch[rates] = rate else: store = open(filename,'w') # create new empty file store.close() def menu(): print "1. Change Canadian currency into American." print "2. Change American currency into Canadian." print "3. Change Canadian currency into Euros." print "4. Change Euros into Canadian currency." print "5. Update exchange rates." print "9. Save and Exit" def exchange_update(): print "1. Update Canadian to US rate." print "2. Update US to Canadian rate." print "3. Update Canadian to Euro rate." print "4. Update Euro to Canadian update." print "5. Main menu" def menu_choice(): return int(raw_input("Which option? ")) print "The Currency Exchange Program" print "By Nathan Pinno" load_rates(rates) while 1: menu() menu_option = menu_choice() if menu_option == 1: can = float(raw_input("Canadian $")) print "US $",can*rates['can_us'] elif menu_option == 2: us = float(raw_input("US $")) print "CAN $",us*rates['us_can'] elif menu_option == 3: can = float(raw_input("CAN $")) print "Euros",can*rates['can_euro'] elif menu_option == 4: euro = float(raw_input("Euros")) print "CAN $",euro*rates['euro_can'] elif menu_option == 5: while 1: exchange_update() sub = menu_choice() if sub == 1: new_can = float(raw_input("New CAN-US Exchange rate: ")) rates['can_us'] = new_can print "Exchange rate successfully updated!" elif sub == 2: new_us = float(raw_input("New US-CAN Exchange rate: ")) rates['us_can'] = new_us print "Exchange rate successfully updated!" elif sub == 3: new_cxr = float(raw_input("New CAN-Euro Exchange rate: ")) rates['can_euro'] = new_cxr print "Exchange rate successfully updated!" elif sub == 4: new_euro = float(raw_input("New Euro-CAN Exchange rate: ")) rates['euro_can'] = new_euro print "Exchange rate successfully updated!" elif sub == 5: break elif menu_option == 9: save_rates(rates) break print "Goodbye." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051214/1f1b891d/attachment.html From bgailer at alum.rpi.edu Wed Dec 14 23:00:03 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 14 Dec 2005 14:00:03 -0800 Subject: [Tutor] Scope Problem with Files In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C359F@eugsrv400.psc.pscne t.com> References: <2BBAEE949D384D40A2B851287ADB6A432C359F@eugsrv400.psc.pscnet.com> Message-ID: <7.0.0.16.0.20051214135810.02255828@alum.rpi.edu> At 11:13 AM 12/14/2005, Carroll, Barry wrote: >Greetings: > >I am implementing a (crude but useful) debug facility in my test >system client software. Basically, I test the value of a global >Boolean. It True, I write pertinent data to a text file. I want to >do this in multiple functions in a module. Rather than open and >close the file each time I write, I want to open the file once at >the start of process and close it at the end. Here are excerpts >from the module. > >########################## >import socket >import struct >import time > ># initialize the debug flag >DEBUG = True >. . . > >dbgf = None # File object and path for saving debug output >dbgfname = "debug.txt" > >def snd_cmd(sock,cmd): > > . . . > > while remainlen > 0: > if remainlen > MTU: > pktstp = pktstrt + MTU > else: > pktstp = pktlen > pktflags |= EOD > > pkthdr = struct.pack('@2BH',pktflags,seq,pktlen) > sndpkt = pkthdr+cmd[pktstrt:pktstp] > > if DEBUG: > dbgf.write("command: " + cmd + "\n") > dbgf.write("flags: 0x%X, seq: %u, len: %u\n" % > (pktflags, seq, pktlen)) > > sock.sendto(sndpkt,addr) > > pktstrt += MTU > remainlen -= MTU > pktflags = pktflags & ~SOD > seq = (seq + 1) % 256 > > . . . > >def recv_resp(sock): > response = '' > try: > response = sock.recv(MTU) > except socket.timeout: > errtupl = ("ERROR", 'Server did not respond') > return (errtupl, response) > > . . . > > if DEBUG: > dbgf.write("response: " + response + "\n") > dbgf.write("flags: 0x%X, seq: %u, len: %u\n" % (flags, retseq, dlen)) > > . . . > > return (errtupl, response) > >def do_cmd(cmd): > > sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > sock.settimeout(timetowait) > retriesleft = retries > if DEBUG: > dbgf = open(dbgfname,mode="a") dbgf is a local variable. If you want to reassign to the global you must add global dbgf to the function > dbgf.write("\n"+str(time.localtime())+"\n") > > while retriesleft > 0: > snd_cmd(sock, cmd) > recvtupl = recv_resp(sock) > if recvtupl[0][0] != "ERROR": > break > retriesleft -= 1 > > if DEBUG: > dbgf.close() > > sock.close( ) > return recvtupl >########################## > >When I run this code, I get the following error message: > ><<<<<<<<<<<<<<<<<<<<<<< >A problem occurred in a Python script. Here is the sequence of >function calls leading up to the error, in the order they occurred. >/var/www/cgi-bin/pagen.py > 76 # function. Check the returned error code for success. > 77 cmdtosnd = state['s']['getcmd'] > *****78 (errorcode, errorstr), > platformstate['itype']['curstate'] = do_cmd(cmdtosnd) > 79 if errorcode == 0: > 80 cmdtosnd = state['t']['getcmd'] > > . . . > >/var/www/cgi-bin/Client.py in do_cmd(cmd='cmd') > 160 > 161 while retriesleft > 0: > *****162 snd_cmd(sock, cmd) > 163 recvtupl = recv_resp(sock) > 164 if recvtupl[0][0] != IIPSRVERROR: > >global snd_cmd = , sock = object>, cmd = 'cmd' > > > /var/www/cgi-bin/Client.py in snd_cmd(sock= object>, cmd='cmd') > 65 > 66 if DEBUG: > *****67 dbgf.write("command: " + cmd + "\n") > 69 > >global dbgf = None, dbgf.write undefined, cmd = 'cmd' > > >AttributeError: 'NoneType' object has no attribute 'write' > args = ("'NoneType' object has no attribute 'write'",) > >>>>>>>>>>>>>>>>>>>>>>> > >dbgf is declared at the top of the module. It is opened and closed >in do_cmd. I attempt to write to it in snd_cmd and recv_resp, both >of which are called by do_cmd. Since dbgf is global to all of these >functions, I expected its value (the open file object) to >persist. I don't understand why it didn't. I expect I have >misunderstood Python's scoping rules. Can someone enlighten me? > >Thanks and enjoy the holidays. > >BGC >________________________ >"Never trust anything that can think for itself >if you can't see where it keeps its brain" >JK Rowling > > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From Barry.Carroll at psc.com Wed Dec 14 23:24:17 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 14 Dec 2005 14:24:17 -0800 Subject: [Tutor] Scope Problem with Files Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C35A0@eugsrv400.psc.pscnet.com> Thanks, Bob. I figured it was something simple. BGC ________________________ "Never trust anything that can think for itself if you can't see where it keeps its brain" JK Rowling <> > > > > sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > > sock.settimeout(timetowait) > > retriesleft = retries > > if DEBUG: > > dbgf = open(dbgfname,mode="a") > > dbgf is a local variable. If you want to reassign to the global you must > add > global dbgf > to the function > > > dbgf.write("\n"+str(time.localtime())+"\n") > > <> From tim at johnsons-web.com Thu Dec 15 01:02:45 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 14 Dec 2005 15:02:45 -0900 Subject: [Tutor] Introspecting class and method names Message-ID: <20051215000245.GF1806@johnsons-web.com> I was pleasantly surprised to notice in a previous thread that python can automagically retrieve a class name thru __class__.__name__ 1)Can someone point me to further documentation on this topic? 2)Is it possible for the name of a class method to be programmatically retrieved from within the scope of the method? If so, how? and pointers to docs would be welcome also. thanks -- Tim Johnson http://www.alaska-internet-solutions.com From nequeo at gmail.com Thu Dec 15 01:24:58 2005 From: nequeo at gmail.com (Simon Gerber) Date: Thu, 15 Dec 2005 11:24:58 +1100 Subject: [Tutor] FWD: How do I fix this error so that my exchange rates program will work? In-Reply-To: <667ca7b60512141601q614e23e6l@mail.gmail.com> References: <667ca7b60512141601q614e23e6l@mail.gmail.com> Message-ID: <667ca7b60512141624y483cf1d2t@mail.gmail.com> Sorry - Forgot to reply to the list as well. ---------- Forwarded message ---------- Hi Nathan, Let's take a look at the debugger message: > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 84, in -toplevel- > save_rates(rates) > File "D:\Python24\exchange.py", line 9, in save_rates > store.write(rate + '\n') > TypeError: unsupported operand type(s) for +: 'float' and 'str' Well, looks like you're trying to add a number to a string. Sorry mate, can't be done! Luckily, there's an easy fix. Change the number into a string, just for the purpose of writing to the file. Python has a very quick way of doing this. Replace this: > store.write(rate + '\n') With this: store.write(`rate` + \n') Note that these are not your regular sungle quotes. You'll find them above the tab key, under escape, on most standard keyboards. Good luck! -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From kent37 at tds.net Thu Dec 15 01:54:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Dec 2005 19:54:43 -0500 Subject: [Tutor] Introspecting class and method names In-Reply-To: <20051215000245.GF1806@johnsons-web.com> References: <20051215000245.GF1806@johnsons-web.com> Message-ID: <43A0BED3.8020403@tds.net> Tim Johnson wrote: > I was pleasantly surprised to notice in a previous thread that python > can automagically retrieve a class name thru __class__.__name__ > 1)Can someone point me to further documentation on this topic? __name__ and __module__ at least are documented here: http://docs.python.org/ref/types.html#l2h-118 You can also try dir(type) to see attributes of type 'type', the base class of all new-style classes, or dir(A) for any class A to see attributes of the class. Many of the special attributes (__xxx__) are referenced in the index to the Python Reference Manual. http://docs.python.org/ref/genindex.html > 2)Is it possible for the name of a class method to be > programmatically retrieved from within the scope of the method? > If so, how? and pointers to docs would be welcome also. You can look at the stack frame to find out what method you are in. See for example http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Kent > > thanks From broek at cc.umanitoba.ca Thu Dec 15 02:04:27 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 14 Dec 2005 19:04:27 -0600 Subject: [Tutor] Introspecting class and method names In-Reply-To: <20051215000245.GF1806@johnsons-web.com> References: <20051215000245.GF1806@johnsons-web.com> Message-ID: <43A0C11B.6070203@cc.umanitoba.ca> Tim Johnson said unto the world upon 2005-12-14 18:02: > I was pleasantly surprised to notice in a previous thread that python > can automagically retrieve a class name thru __class__.__name__ > 1)Can someone point me to further documentation on this topic? > 2)Is it possible for the name of a class method to be > programmatically retrieved from within the scope of the method? > If so, how? and pointers to docs would be welcome also. > > thanks Hi Tim, I'm glad that other got use out of Kent's answers to my questions :-) (Thanks again Kent.) For points related to (2), you might want to check out the inspect module, Tim. I don't immediately see a way to accomplish (2), but I've not looked closely. However, if these points interest you, much of inspect will be of likely interest, too. Best, Brian vdB From tim at johnsons-web.com Thu Dec 15 02:40:20 2005 From: tim at johnsons-web.com (tim@johnsons-web.com) Date: Wed, 14 Dec 2005 16:40:20 -0900 Subject: [Tutor] Introspecting class and method names In-Reply-To: <43A0BED3.8020403@tds.net> References: <20051215000245.GF1806@johnsons-web.com> <43A0BED3.8020403@tds.net> Message-ID: <20051215014020.GG1806@johnsons-web.com> * Kent Johnson [051214 16:00]: > Tim Johnson wrote: > > I was pleasantly surprised to notice in a previous thread that python > > can automagically retrieve a class name thru __class__.__name__ > > 1)Can someone point me to further documentation on this topic? > > __name__ and __module__ at least are documented here: > http://docs.python.org/ref/types.html#l2h-118 > > You can also try dir(type) to see attributes of type 'type', the base class of all > new-style classes, or dir(A) for any class A to see attributes of the class. Many of the > special attributes (__xxx__) are referenced in the index to the Python Reference Manual. > http://docs.python.org/ref/genindex.html > > > 2)Is it possible for the name of a class method to be > > programmatically retrieved from within the scope of the method? > > If so, how? and pointers to docs would be welcome also. > > You can look at the stack frame to find out what method you are in. See for example > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Thanks! This is really nice! I'm too old to write things like wwwoooo! - so I won't - but I am impressed. quick, handy function here: def Here(): """ Return file, name and line number of calling function""" return 'File: %s Function: %s Line Number: %s' % \ (sys._getframe(1).f_code.co_filename, sys._getframe(1).f_code.co_name, sys._getframe(1).f_lineno) Must tie a string around my finger with "sys._getframe" on it. I'm sure it has many other goodies. cheers ====== Tim Johnson http://www.alaska-internet-solutions.com From kent37 at tds.net Thu Dec 15 02:44:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Dec 2005 20:44:29 -0500 Subject: [Tutor] How do I fix this error so that my exchange rates program will work? In-Reply-To: References: Message-ID: <43A0CA7D.1020900@tds.net> Nathan Pinno wrote: > I added the dictionary and loading and saving for the rates in my > exchange currency rates program, and when I ran it, I got the following > error: > > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 84, in -toplevel- > save_rates(rates) > File "D:\Python24\exchange.py", line 9, in save_rates > store.write(rate + '\n') > TypeError: unsupported operand type(s) for +: 'float' and 'str' Simon has explained the error. However you might want to look into the pickle module as a way to save your data. Kent From ismaelgf at adinet.com.uy Thu Dec 15 02:49:31 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed, 14 Dec 2005 23:49:31 -0200 Subject: [Tutor] FWD: How do I fix this error so that my exchange rates program will work? In-Reply-To: <667ca7b60512141624y483cf1d2t@mail.gmail.com> References: <667ca7b60512141601q614e23e6l@mail.gmail.com> <667ca7b60512141624y483cf1d2t@mail.gmail.com> Message-ID: <43A0CBAB.3040507@adinet.com.uy> Simon Gerber wrote: >> store.write(rate + '\n') >> >> > >With this: > > store.write(`rate` + \n') > >Note that these are not your regular sungle quotes. You'll find them >above the tab key, under escape, on most standard keyboards. > > I have to say I don't like that. It's a too subtle difference, meaning, you really can't tell until you stop and examine closely that it's really not a ' but a `... Depending on font, they might even look alike! I'd vote for either: str(rate) or "%s" %(rate) They both are more readable, not easy to mistake for another thing and seem more python-like (to me, that is :) Just my opinion. Ismael From kent37 at tds.net Thu Dec 15 02:59:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Dec 2005 20:59:45 -0500 Subject: [Tutor] Introspecting class and method names In-Reply-To: <20051215014020.GG1806@johnsons-web.com> References: <20051215000245.GF1806@johnsons-web.com> <43A0BED3.8020403@tds.net> <20051215014020.GG1806@johnsons-web.com> Message-ID: <43A0CE11.9070101@tds.net> tim at johnsons-web.com wrote: > * Kent Johnson [051214 16:00]: >>You can look at the stack frame to find out what method you are in. See for example >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 > > > Thanks! This is really nice! > > Must tie a string around my finger with "sys._getframe" on it. > I'm sure it has many other goodies. Search the cookbook and comp.lang.python for _getframe to find more. Kent From kraus at hagen-partner.de Thu Dec 15 08:44:41 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 15 Dec 2005 08:44:41 +0100 Subject: [Tutor] dont understand this error MySQLdb In-Reply-To: <1134577303.8835.1.camel@localhost.localdomain> References: <1134577303.8835.1.camel@localhost.localdomain> Message-ID: nephish wrote: > hey there, > i am using the MySQLdb module and i keep getting this error, it doesnt > offer much in the way of explanation > > _mysql_exceptions.InterfaceError: (0, '') > > does anyone know what this means ? > > thanks > I think you should better post in the Mysql for Python forum over at sf.net: http://sourceforge.net/forum/forum.php?forum_id=70461 And beside that it is hard to tell without any code. Can you write a very simple example to reproduce this error? HTH, Wolfram From bob at farms.coop Thu Dec 15 14:41:27 2005 From: bob at farms.coop (Bobby Castleberry) Date: Thu, 15 Dec 2005 07:41:27 -0600 Subject: [Tutor] serial data capture/event driven help Message-ID: <43A17287.6070608@farms.coop> I'm looking to capture weights coming off of several in-motion scales through serial ports and dump them into a database. The database part is easy but I've never worked with serial collection. I would like to setup several data collection objects (one for each serial port) and as they recieve data they hand off the data to the data dumper object which pushes it up to the database for storage. This seems to me to be the essence of event-driven programming and thus I'm thinking the twisted python framework is the way to go. I've read the paper on defered execution and several articles on asynchonis programming but I'm really having problems wrapping my mind around how this does work (the whole event driven programming/asynchonis programming paradigm). Any advice or linkage to some tutorial type articles for event driven design. Thanks for any input -- Bobby Castleberry System Administrator Meadowbrook Farms Coop From dndfan at hotpop.com Thu Dec 15 16:36:32 2005 From: dndfan at hotpop.com (Vlad Popescu) Date: Thu, 15 Dec 2005 17:36:32 +0200 Subject: [Tutor] Tkinter help required Message-ID: <1134660992.2684.2.camel@localhost.localdomain> Thanks a bunch, Michael. I am using Fedora Core 4 and have installed the tkinter package via yum. Everything is working great as far as I can tell. That really helped. Thanks again > On Wed, 14 Dec 2005 15:05:07 +0200 > Vlad Popescu wrote: > > Hi Vlad, > > > Hello everyone, > > > > I have been desperately trying to get Tkinter to run, but > without much > > success thus far. I've followed the instructions at > > http://wiki.python.org/moin/TkInter ; importing _tkinter > does not work > > and I have no idea what files I should edit in order to add > the module. > > Both Tcl and Tk, along with their -devel packages, are > installed and > > updated. Python version is 2.4.1 > > > > it looks like you are running a linux box? > If so , probably Tkinter is in a separate package that may be > called "tkinter" or "python-tk" > or something similar, depending on the distro. May be this > package is not installed? > > Regards > > Michael From f at ke1g.mv.com Thu Dec 15 17:51:14 2005 From: f at ke1g.mv.com (Bill Freeman) Date: Thu, 15 Dec 2005 11:51:14 -0500 Subject: [Tutor] [Python-talk] ElementTree in Python 2.5! In-Reply-To: <43A07E96.4030803@tds.net> References: <43A07E96.4030803@tds.net> Message-ID: <17313.40706.180342.856047@localhost.localdomain> Kent Johnson writes: > ... ElementTree My dear Watson!!! > ... From dyoo at hkn.eecs.berkeley.edu Thu Dec 15 19:26:29 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 15 Dec 2005 10:26:29 -0800 (PST) Subject: [Tutor] serial data capture/event driven help In-Reply-To: <43A17287.6070608@farms.coop> Message-ID: On Thu, 15 Dec 2005, Bobby Castleberry wrote: > I'm looking to capture weights coming off of several in-motion scales > through serial ports and dump them into a database. The database part > is easy but I've never worked with serial collection. Hi Bobby, There's a module for handling the serial port called PySerial: http://pyserial.sourceforge.net/ Does this look useful for you? You could set up a thread to read data from each of your those ports, and just call read(). There does appear to be work on making PySerial asynchronous: http://mail.python.org/pipermail/python-list/2005-July/292174.html but I don't know how far this has gone yet; you may want to talk with the Twisted folks for an up-to-date status on it. Best of wishes! From reddazz at gmail.com Thu Dec 15 20:44:48 2005 From: reddazz at gmail.com (William Mhlanga) Date: Thu, 15 Dec 2005 19:44:48 +0000 Subject: [Tutor] Guess my number game Message-ID: I have been trying to write a guess my number game (using Michael Dawsons book), where the computer guesses the number that I thought of. Here is my code so far, #The Guess My Number Game # #The computer picks a random number between 1 and 50 #The player tries to guess it and the computer lets #the player know if the guess is too high, too low #or right on the money #If the player fails to guess the number after 5 tries #the game ends and the computer prints a chastising message # print "\t\t\tWelcome to \"Guess My Number\"!" import random print "\nThink of a number between 1 and 50." print "I will try to guess it in as few attempts as possible.\n" number = input ("Enter the number: ") #the computer guesses the number using the random function guess = random.randrange (50) + 1 tries = 1 #FIXME while (guess != number): if (guess > number): print "You chose", guess, "the number is Lower ..." else: print "You chose", guess, "the number is Higher ..." guess = random.randrange (50) + 1 tries += 1 print "You guessed it! The number was", number print "And it only took you", tries, "tries!\n" raw_input ("Press to exit.") The program works ok, but the computer sometimes repeats the same numbers when asked to guess. How can I rewrite it so that it guesses like what a human being does i.e. if the number is less than 20, you do not guess numbers above 20. Thanks for your help. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051215/4f2082eb/attachment.htm From ps_python3 at yahoo.co.in Thu Dec 15 21:37:09 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Thu, 15 Dec 2005 20:37:09 +0000 (GMT) Subject: [Tutor] writing list elements into a string In-Reply-To: Message-ID: <20051215203709.18302.qmail@web8411.mail.in.yahoo.com> hi, can any one pls. help me on this simple issue. I keep forgetting some simple things and they turn out to be very important later. i have a list 'a', and now i want to write all the elements back in to a string. 'apple is a good fruit' - getting this back into a string has drained my brain. appreciate your help all. >>> a = ['apple','is','a','good','fruit'] >>> for m in a: print m, apple is a good fruit >>> ab ='' >>> for m in a: k = ''.join(m) ab.join(k) 'apple' 'is' 'a' 'good' 'fruit' >>> __________________________________________________________ Yahoo! India Matrimony: Find your partner now. Go to http://yahoo.shaadi.com From john at fouhy.net Thu Dec 15 21:42:45 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 16 Dec 2005 09:42:45 +1300 Subject: [Tutor] writing list elements into a string In-Reply-To: <20051215203709.18302.qmail@web8411.mail.in.yahoo.com> References: <20051215203709.18302.qmail@web8411.mail.in.yahoo.com> Message-ID: <5e58f2e40512151242q18f65542r@mail.gmail.com> On 16/12/05, ps python wrote: > >>> a = ['apple','is','a','good','fruit'] > >>> ab ='' > >>> for m in a: > k = ''.join(m) > ab.join(k) You're almost there... >>> a = ['apple', 'is', 'a', 'good', 'fruit'] >>> ' '.join(a) 'apple is a good fruit' >>> '...'.join(a) 'apple...is...a...good...fruit' >>> '\n'.join(a) 'apple\nis\na\ngood\nfruit' >>> print '\n'.join(a) apple is a good fruit HTH! -- John. From ps_python3 at yahoo.co.in Thu Dec 15 21:50:46 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Thu, 15 Dec 2005 20:50:46 +0000 (GMT) Subject: [Tutor] writing list elements into a string Message-ID: <20051215205046.12153.qmail@web8409.mail.in.yahoo.com> -Repost. considering that my previous email lost - hi, can any one pls. help me on this simple issue. I keep forgetting some simple things and they turn out to be very important later. i have a list 'a', and now i want to write all the elements back in to a string. 'apple is a good fruit' - getting this back into a string has drained my brain. appreciate your help all. >>> a = ['apple','is','a','good','fruit'] >>> for m in a: print m, apple is a good fruit >>> ab ='' >>> for m in a: k = ''.join(m) ab.join(k) 'apple' 'is' 'a' 'good' 'fruit' __________________________________________________________ Yahoo! India Matrimony: Find your partner now. Go to http://yahoo.shaadi.com From ajikoe at gmail.com Thu Dec 15 21:52:52 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 15 Dec 2005 21:52:52 +0100 Subject: [Tutor] Guess my number game In-Reply-To: References: Message-ID: Hi, your guess still use random.randrange that's make computer doesn't care about whether guess is low or higher than your number. This code should be like this: print "\t\t\tWelcome to \"Guess My Number\"!" print "\nThink of a number between 1 and 50." print "I will try to guess it in as few attempts as possible.\n" number = input ("Enter the number: ") #the computer guesses the number using the random function guess = random.randrange (50) + 1 tries = 1 #FIXME while (guess != number): if (guess > number): print "You chose", guess, "the number is Lower ..." guess = random.randint(1, guess-1) else: print "You chose", guess, "the number is Higher ..." guess = random.randint(guess+1, 50) tries += 1 print "You guessed it! The number was", number print "And it only took you", tries, "tries!\n" raw_input ("Press to exit.") Hope this help pujo On 12/15/05, William Mhlanga wrote: > > I have been trying to write a guess my number game (using Michael Dawsons > book), where the computer guesses the number that I thought of. Here is my > code so far, > #The Guess My Number Game > # > #The computer picks a random number between 1 and 50 > #The player tries to guess it and the computer lets > #the player know if the guess is too high, too low > #or right on the money > #If the player fails to guess the number after 5 tries > #the game ends and the computer prints a chastising message > # > > print "\t\t\tWelcome to \"Guess My Number\"!" > import random > > print "\nThink of a number between 1 and 50." > print "I will try to guess it in as few attempts as possible.\n" > > number = input ("Enter the number: ") > > #the computer guesses the number using the random function > guess = random.randrange (50) + 1 > tries = 1 > > #FIXME > while (guess != number): > if (guess > number): > print "You chose", guess, "the number is Lower ..." > else: > print "You chose", guess, "the number is Higher ..." > guess = random.randrange (50) + 1 > tries += 1 > > print "You guessed it! The number was", number > print "And it only took you", tries, "tries!\n" > > raw_input ("Press to exit.") > > The program works ok, but the computer sometimes repeats the same numbers > when asked to guess. How can I rewrite it so that it guesses like what a > human being does i.e. if the number is less than 20, you do not guess > numbers above 20. > > Thanks for your help. > > _______________________________________________ > 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/20051215/3465fbad/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Thu Dec 15 22:53:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 15 Dec 2005 13:53:50 -0800 (PST) Subject: [Tutor] serial data capture/event driven help (fwd) Message-ID: [keeping Tutor in CC] ---------- Forwarded message ---------- Date: Thu, 15 Dec 2005 13:40:11 -0600 From: Bobby Castleberry To: Danny Yoo Subject: Re: [Tutor] serial data capture/event driven help Danny Yoo wrote: > There's a module for handling the serial port called PySerial: > > http://pyserial.sourceforge.net/ > > Does this look useful for you? You could set up a thread to read data > from each of your those ports, and just call read(). The threading on this worries me because the app could end up scaling very large and the program will be running on a vmware box with already reasonable utilization. I've read on several lists that threading becomes mighty complicated when you start scaling up. Our perl guy has a program that is collecting off of four scales currently (was thinking about reusing his implementation) but with threads and poling it pegs an athlon 2800+ at 80% cpu and it's the only thing running. Of course that could just be perl and the way it handles threading. I'll probably take a run at implementing this with threads and polling first just to see how it performs (doesn't seem difficult in theory :). > > but I don't know how far this has gone yet; you may want to talk with the > Twisted folks for an up-to-date status on it. I've heard the twisted project mentioned a few times on the list and was hoping to get a eye brow raise from someone who has sunk their teeth in it. Just kind of looking for a red light, green light type of feeling before I proceed to bang my head against the concept of asynchronous programming some more (is that learning through osmosis). I appreciate the links though, I hadn't read about the other asynchronous serial project before so maybe I can take my time learning twisted and just whip this out using the other module. Anyone know of a link for the "Bent" module, I'm not getting anything useful through google. I haven't joined the twisted list yet. Judging by the archive the topics are a bit over my head at this stage of the game, although a twisted beginner list would be handy if said thing exists. -- Bobby Castleberry System Administrator Meadowbrook Farms Coop From nequeo at gmail.com Fri Dec 16 00:41:23 2005 From: nequeo at gmail.com (Simon Gerber) Date: Fri, 16 Dec 2005 10:41:23 +1100 Subject: [Tutor] Guess my number game In-Reply-To: References: Message-ID: <667ca7b60512151541r1a2f8735l@mail.gmail.com> Hi William, Just a word of warning, you should get used to using 'raw_input()' rather than 'input()' in your progams. Why? Because input() attempts to run whatever you type in as a Python program. If you want to know why that's a problem, try running your progam. When it asks you to "Enter the number: " type in this: open('test.txt', 'w') Your program will crash. But look in the directory where you ran it, and you'll see a blank 'test.txt' document! Obviously, it's just as easy to delete files, and cause other malicious damage. Obviously, this isn't much of a problem if you're just writing a small game as a learning excercise. But it's a good habit to practice secure coding whenever possible. raw_input saves anything typed in as a string. Which is good, because you don't want people to be able to execute arbitrary code using your program. But it's bad, because you can't do mathematics with a string. So you need to use 'type casting', which you might not know about yet, to turn the string into a number. Try this instead: number = int(raw_input("Enter the number: ")) Your program will still look the same, but it'll be a lot safer. -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From murtog at gmail.com Fri Dec 16 00:42:54 2005 From: murtog at gmail.com (Murtog) Date: Thu, 15 Dec 2005 19:42:54 -0400 Subject: [Tutor] Guess my number game In-Reply-To: References: Message-ID: Try this code: #The Guess My Number Game # #The computer picks a random number between 1 and 50 #The player tries to guess it and the computer lets #the player know if the guess is too high, too low #or right on the money #If the player fails to guess the number after 5 tries #the game ends and the computer prints a chastising message # import random print """\t\t\tWelcome to \"Guess My Number\"! \nThink of a number between 1 and 50. I will try to guess it in as few attempts as possible.\n""" number = input ("Enter the number: ") #the computer guesses the number using the random function guess = random.randrange (50) + 1 tries = 1 useds = [] #FIXED while (guess != number): if (guess > number): print "You chose", guess, "the number is Lower ..." useds.append(guess) else: print "You chose", guess, "the number is Higher ..." useds.append(guess) guess = random.randrange (50) + 1 if guess in useds: while guess in useds: guess = random.randrange(50) + 1 else: tries += 1 print "You guessed it! The number was", number print "And it only took you", tries, "tries!\n" raw_input ("Press to exit.") It should work now. Cheers! =] On 12/15/05, William Mhlanga wrote: > > I have been trying to write a guess my number game (using Michael Dawsons > book), where the computer guesses the number that I thought of. Here is my > code so far, > #The Guess My Number Game > # > #The computer picks a random number between 1 and 50 > #The player tries to guess it and the computer lets > #the player know if the guess is too high, too low > #or right on the money > #If the player fails to guess the number after 5 tries > #the game ends and the computer prints a chastising message > # > > print "\t\t\tWelcome to \"Guess My Number\"!" > import random > > print "\nThink of a number between 1 and 50." > print "I will try to guess it in as few attempts as possible.\n" > > number = input ("Enter the number: ") > > #the computer guesses the number using the random function > guess = random.randrange (50) + 1 > tries = 1 > > #FIXME > while (guess != number): > if (guess > number): > print "You chose", guess, "the number is Lower ..." > else: > print "You chose", guess, "the number is Higher ..." > guess = random.randrange (50) + 1 > tries += 1 > > print "You guessed it! The number was", number > print "And it only took you", tries, "tries!\n" > > raw_input ("Press to exit.") > > The program works ok, but the computer sometimes repeats the same numbers > when asked to guess. How can I rewrite it so that it guesses like what a > human being does i.e. if the number is less than 20, you do not guess > numbers above 20. > > Thanks for your help. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- \(^_^)/ Murtog -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051215/ce445fd5/attachment.htm From alan.gauld at freenet.co.uk Fri Dec 16 01:32:17 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 16 Dec 2005 00:32:17 -0000 Subject: [Tutor] serial data capture/event driven help References: <43A17287.6070608@farms.coop> Message-ID: <003a01c601d8$2b50b0f0$0a01a8c0@xp> > event driven programming/asynchonis programming paradigm). Any advice > or linkage to some tutorial type articles for event driven design. You seem to have the basic concepts at least, but my tutorial does have a topic on event driven programming you can try. It may be too basic however. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From broek at cc.umanitoba.ca Fri Dec 16 01:59:30 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 15 Dec 2005 18:59:30 -0600 Subject: [Tutor] Guess my number game In-Reply-To: References: Message-ID: <43A21172.7000803@cc.umanitoba.ca> Pujo Aji said unto the world upon 2005-12-15 14:52: > Hi, > your guess still use random.randrange that's make computer doesn't care > about whether guess is low or higher than your number. > > This code should be like this: > Hope this help > > pujo > > On 12/15/05, William Mhlanga wrote: > >>I have been trying to write a guess my number game (using Michael Dawsons >>book), where the computer guesses the number that I thought of. Here is my >>code so far, >> >>The program works ok, but the computer sometimes repeats the same numbers >>when asked to guess. How can I rewrite it so that it guesses like what a >>human being does i.e. if the number is less than 20, you do not guess >>numbers above 20. >> >>Thanks for your help. >> Hi William, I have a suggestion for you: once you get the "guess by random flailing" approach to work, you might think about ways to try to make you code live up to the claim "I will try to guess it in as few attempts as possible.\n" :-) Right now, if the number is 1, it could take the code 50 tries in the worst case, even with pujo's suggestion to improve the strategy you started with. If you get stuck on that, post back. Best, Brian vdB From bgailer at alum.rpi.edu Fri Dec 16 06:39:05 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 15 Dec 2005 21:39:05 -0800 Subject: [Tutor] Python - SQL paradigm (Will I need a hammer to make it fit?) In-Reply-To: References: Message-ID: <7.0.0.16.0.20051215212900.02431810@alum.rpi.edu> At 02:14 AM 12/14/2005, Liam Clarke wrote: >Hi all, > >Just contemplating. > >If in Python I were organising a data index along the lines of - > >j = { > >"k_word1" : ["rec1","rec2","rec3","rec4"], >... >"k_wordn" :["recX","rec4"] > >} > >and I was going to find records that matched by seeing what record >occurred in the most lists (via set intersections or similar; going to >have a play see what works faster) selected by searching keywords... > >how easily does that translate to a SQL table and query format? Data modeling looks for relationships between objects. Relationships can be 1-1 1-many or many-many. Your case is a many-many (each keyword may appear in one or more records, and each record may contain one or more keywords.) The customary way to represent this in a relational database 3 tables. One with one row per keyword, one with one row per record and one "junction" or "association" table with one row for each keyword-record pair. KEYWORD TABLE kid keyword 1 cat 2 dog 3 mouse 4 bird 5 banana RECORD TABLE rid record 1 rexX 2 rec4 3 recAB 4 rec99 5 recFoo KEYWORD-RECORD TABLE kid rid 1 1 1 3 1 4 2 2 3 5 4 1 5 3 For processing things like this nothing IMHO beats a relational database and SQL. With many databases accessible from Python I strongly suggest this approach. SQLite is especially attractive. [snip] From falcon3166 at hotmail.com Fri Dec 16 07:37:22 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 15 Dec 2005 23:37:22 -0700 Subject: [Tutor] How do I fix this StopIteration error? Message-ID: I edited my code so that it looks like this: def save_rates(exch): store = open("exch.txt","w") for exch, rate in rates.items(): store.write(exch + '\n') store.write(`rate` + '\n') store.close() def load_rates(exch): import os filename = 'exch.txt' if os.path.exists(filename): store = open(filename,'r') for line in store: conv = line.strip() rate = float(store.next().strip()) exch[conv] = rate else: store = open(filename,'w') # create new empty file store.close() When I ran the program, I got this: The Currency Exchange Program By Nathan Pinno Traceback (most recent call last): File "D:\Python24\exchange.py", line 45, in -toplevel- load_rates(rates) File "D:\Python24\exchange.py", line 19, in load_rates rate = float(store.next().strip()) StopIteration How do I fix this? Thanks for the help so far, Nathan Pinno, MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051215/1403a6c7/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051215/1403a6c7/attachment.gif From wilson at visi.com Fri Dec 16 07:18:29 2005 From: wilson at visi.com (Tim Wilson) Date: Fri, 16 Dec 2005 00:18:29 -0600 Subject: [Tutor] Simple XML parsing Message-ID: Hi everyone, I've got a little project that requires me to parse a simple XML file. The file comes from the browser history of Apple's Safari and includes the URL that was visited, the title of the Web page, the date and time it was last visited, and the total number of times it was visited. Here's a snippet: WebHistoryDates http://www.hopkins.k12.mn.us/pages/eisenhower/ eisenhower.lasso displayTitle Welcome to Eisenhower Elementary lastVisitedDate 156350702.0 title Welcome to Eisenhower Elementary visitCount 285 WebHistoryFileVersion 1 Let's say that instead of one , the xml file had 100 of them. I want to generate a simple table of URLs and the dates they were last visited. I can handle everything except parsing the XML file and extracting the information. Anyone have any pointers? -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson at visi.com aim: tis270 blog: http://technosavvy.org From itechsys at gmail.com Fri Dec 16 09:27:53 2005 From: itechsys at gmail.com (vikas mohan) Date: Fri, 16 Dec 2005 09:27:53 +0100 Subject: [Tutor] How to open a file with images Message-ID: <1114f05f0512160027p72360b87mcf8acee75bcbbea0@mail.gmail.com> Hi everybody! In Java we have the appletviewer and frames, through which we can access image files. In python, if I want to open an image file in IDLE, how can I do that, and what should my command look like? Many thanks Vikas -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051216/05c73028/attachment.htm From itechsys at gmail.com Fri Dec 16 10:54:29 2005 From: itechsys at gmail.com (vikas mohan) Date: Fri, 16 Dec 2005 10:54:29 +0100 Subject: [Tutor] Codehelp: confused by the output in IDLE Message-ID: <1114f05f0512160154x767bdbaeldb2d520f49a42f4d@mail.gmail.com> Hi again! The following is a piece of code that I have written: *def funcA(x): # function describiing the oddness or eveness of an x number if x%2 == 0: print x, "is even" else: print x, "is odd" def funcB(y): # function describiing the oddness or eveness of an y number if y%2 ==0: print y, "is even" else: print y, "is odd" # no more functions after this line * > *x=input("Please type a number: ") > print x* > > *y=input("Please type another number: ") > print y* > > *if x>y: > print x,("is greater than"),y > else: > print y,("is greater than"),x* > > *if y and x >=0: > print ("Both are positive numbers!")* > > *print funcA(x) > print funcB(y)* > And this is the output in IDLE after execution: > *Please type a number: 5 > 5 > Please type another number: 10 > 10 > 10 is greater than 5 > Both are positive numbers! > 5 is odd > None > 10 is even > None* > I don't understand why I am getting 2 instances of "None" in the output, when it has not been programmed by me. What is going on? Pls. advice Thanks again, V -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051216/c51843bd/attachment.html From singletoned at gmail.com Fri Dec 16 11:10:30 2005 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 16 Dec 2005 10:10:30 +0000 Subject: [Tutor] Accessing next and previous items during iteration Message-ID: <34bb7f5b0512160210t1e5f03dep@mail.gmail.com> Is it possible to access the next and previous items during an iteration? I want to use it to iterate through html files in a folder and add links in to the next and previous pages. For example for page in folder: #add link to previous page #add link to next page I'm currently using: prev = 0 current = 0 next = 0 for page in folder: prev = current current = next next = page if current: if prev: #add link to previous page #add link to next page if current: if prev: #add link to previous page #add link to next page But this seems a really awkward way to do it. I've considered iterating and dumping them all into a list and then iterating through the list, but that also seems awkward (having to iterate twice). Is there a nice way to do it? Thanks Ed From kent37 at tds.net Fri Dec 16 12:04:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Dec 2005 06:04:28 -0500 Subject: [Tutor] How do I fix this StopIteration error? In-Reply-To: References: Message-ID: <43A29F3C.8010404@tds.net> Nathan Pinno wrote: >> store = open(filename,'r') > for line in store: > conv = line.strip() > rate = float(store.next().strip()) > exch[conv] = rate > > When I ran the program, I got this: > > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 45, in -toplevel- > load_rates(rates) > File "D:\Python24\exchange.py", line 19, in load_rates > rate = float(store.next().strip()) > StopIteration > > How do I fix this? StopIteration is an iterator's way of saying it has reached the end. When you iterate using a for loop, the exception is caught internally and used to terminate the loop. When you call next() explicitly, you should be prepared to catch the exception yourself. In this case though, the exception means you have a conv without a rate, so it is a symptom of bad data or an error reading the data. Have you looked at the file to make sure it is correct? If it is, you might try a slightly different loop. I'm not sure if it really works to mix a for loop iteration with calls to next() on the iterator. Try something like this: store = open(filename,'r') try: while True: conv = store.next().strip() rate = float(store.next().strip()) exch[conv] = rate except StopIteration: pass Or use the pickle module to save and load your exch dictionary, it is perfect for this and as simple as import pickle # save store = open(filename, 'wb') pickle.dump(exch, store) store.close() # load store = open(filename, 'b') exch = pickle.load(store) store.close() Kent From kent37 at tds.net Fri Dec 16 12:26:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Dec 2005 06:26:02 -0500 Subject: [Tutor] Simple XML parsing In-Reply-To: References: Message-ID: <43A2A44A.60100@tds.net> Tim Wilson wrote: > Hi everyone, > > I've got a little project that requires me to parse a simple XML > file. The file comes from the browser history of Apple's Safari and > includes the URL that was visited, the title of the Web page, the > date and time it was last visited, and the total number of times it > was visited. Here's a snippet: > > > www.apple.com/DTDs/PropertyList-1.0.dtd"> > > > > Let's say that instead of one , the xml file had 100 of them. I > want to generate a simple table of URLs and the dates they were last > visited. I can handle everything except parsing the XML file and > extracting the information. These look promising: http://online.effbot.org/2005_03_01_archive.htm#elementplist http://www.shearersoftware.com/software/developers/plist/ though the empty for the URL might be a problem. The effbot version could be changed to "dict": lambda x: dict((x[i].text or 'url', x[i+1].text) for i in range(0, len(x), 2)), to change empty keys to 'url'; as long as there is only one per (and it is actually the url) that will work. If these don't work you can use ElementTree to do the parse and walk the results tree yourself to pull out the data. Kent From kent37 at tds.net Fri Dec 16 12:36:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Dec 2005 06:36:47 -0500 Subject: [Tutor] How to open a file with images In-Reply-To: <1114f05f0512160027p72360b87mcf8acee75bcbbea0@mail.gmail.com> References: <1114f05f0512160027p72360b87mcf8acee75bcbbea0@mail.gmail.com> Message-ID: <43A2A6CF.2060908@tds.net> vikas mohan wrote: > Hi everybody! > > In Java we have the appletviewer and frames, through which we can access > image files. In python, if I want to open an image file in IDLE, how can > I do that, and what should my command look like? Here is a simple program to open an image file and display it using PIL and Tkinter. It is based on an example program that comes with PIL. http://effbot.org/imagingbook/imagetk.htm import Image, ImageTk from Tkinter import Tk, Label im = Image.open('wire.png') class UI(Label): def __init__(self, master, im): if im.mode == "1": # bitmap image self.image = ImageTk.BitmapImage(im, foreground="white") Label.__init__(self, master, image=self.image, bg="black", bd=0) else: # photo image self.image = ImageTk.PhotoImage(im) Label.__init__(self, master, image=self.image, bd=0) root = Tk() UI(root, im).pack() root.mainloop() Kent From alan.gauld at freenet.co.uk Fri Dec 16 12:45:01 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 16 Dec 2005 11:45:01 -0000 Subject: [Tutor] Codehelp: confused by the output in IDLE References: <1114f05f0512160154x767bdbaeldb2d520f49a42f4d@mail.gmail.com> Message-ID: <001201c60236$264b0ca0$0a01a8c0@xp> > def funcA(x): # function describiing the oddness or eveness of an x number > if x%2 == 0: > print x, "is even" > else: > print x, "is odd" >def funcB(y): # function describiing the oddness or eveness of an y number > if y%2 ==0: > print y, "is even" > else: > print y, "is odd" These two functions are identical. What you call the parameter is irrelevant to the outside world its only a local name inside the function! Neither function returns a value so Python will silently return the special value 'None' Also its usually a bad idea to do the printing of results inside the function, its better to return the result and let the caller display the result. Thus a better solution here is probably: def isOdd(x): return x % 2 Now you can do things like: x = int(raw_input('Type a number: ')) y = int(raw_input('Type a number: ')) if isOdd(x): print x, ' is odd' else: print x, ' is even' if isOdd(y): print y, ' is odd' else: print y, ' is even' > *if x>y: > print x,("is greater than"),y > else: > print y,("is greater than"),x* > > *if y and x >=0: > print ("Both are positive numbers!")* This doesn't work because Python will evaluate it like: if y if x >=0: print ... you need to use if y >=0 and x >= 0 print ... > *print funcA(x) > print funcB(y)* Because your functions don't retuirn any value Python returns None. So that is the value that you print. Thats why its probably better to return the result of the test and lat your calling program display the result as described above. > 10 is greater than 5 > Both are positive numbers! This is because of the incorrect if test > 5 is odd This is printed inside the function > None And this is what was returned by the function > 10 is even > None* and the same here HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kraus at hagen-partner.de Fri Dec 16 12:45:21 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 16 Dec 2005 12:45:21 +0100 Subject: [Tutor] Codehelp: confused by the output in IDLE In-Reply-To: <1114f05f0512160154x767bdbaeldb2d520f49a42f4d@mail.gmail.com> References: <1114f05f0512160154x767bdbaeldb2d520f49a42f4d@mail.gmail.com> Message-ID: vikas mohan wrote: > Hi again! > > The following is a piece of code that I have written: > > def funcA(x): # function describiing the oddness or eveness of an x number > if x%2 == 0: > print x, "is even" > else: > print x, "is odd" > > def funcB(y): # function describiing the oddness or eveness of an y number > if y%2 ==0: > print y, "is even" > else: > print y, "is odd" > > # no more functions after this line > > *x=input("Please type a number: ") > print x* > > *y=input("Please type another number: ") > print y* > > *if x>y: > print x,("is greater than"),y > else: > print y,("is greater than"),x* > > *if y and x >=0: > print ("Both are positive numbers!")* > > print funcA(x) > print funcB(y) > > And this is the output in IDLE after execution: > > *Please type a number: 5 > 5 > Please type another number: 10 > 10 > 10 is greater than 5 > Both are positive numbers! > 5 is odd > None > 10 is even > None* > > > I don't understand why I am getting 2 instances of "None" in the output, > when it has not been programmed by me. What is going on? > > Pls. advice > > Thanks again, > V You print inside your function (print x, "is odd") and you print the result of your function (print funcA(x)). As your function doesn't explicitly return a value, you get None, see: http://www.python.org/doc/2.4.2/tut/node6.html#SECTION006600000000000000000 So either just call the function or return the string from your function. HTH, Wolfram From kent37 at tds.net Fri Dec 16 13:37:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Dec 2005 07:37:53 -0500 Subject: [Tutor] Accessing next and previous items during iteration In-Reply-To: <34bb7f5b0512160210t1e5f03dep@mail.gmail.com> References: <34bb7f5b0512160210t1e5f03dep@mail.gmail.com> Message-ID: <43A2B521.2040305@tds.net> Ed Singleton wrote: > Is it possible to access the next and previous items during an iteration? There is nothing built in to support this directly. > I'm currently using: > > prev = 0 > current = 0 > next = 0 > for page in folder: > prev = current > current = next > next = page > if current: > if prev: > #add link to previous page > #add link to next page > if current: > if prev: > #add link to previous page > #add link to next page I think there is a bug here - when the loop exits, prev, current and next will all be valid with next containing the last page. You have already added the links to current, it is next that needs a link to the previous page. > > But this seems a really awkward way to do it. > > I've considered iterating and dumping them all into a list and then > iterating through the list, but that also seems awkward (having to > iterate twice). You don't say what kind of object folder is. If it is a directory listing e.g. from os.listdir() then it is already a list. In any case you should be able to make a list without an explicit iteration using pages = list(folder) > > Is there a nice way to do it? How about this: pages = list(folder) # make sure we have a list for i, page in enumerate(pages): if i > 0: previous = pages[i-1] # add link to previous if i+1 < len(pages): next = pages[i+1] # add link to next Kent From ml.cyresse at gmail.com Fri Dec 16 14:41:13 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 17 Dec 2005 02:41:13 +1300 Subject: [Tutor] Python - SQL paradigm (Will I need a hammer to make it fit?) In-Reply-To: <7.0.0.16.0.20051215212900.02431810@alum.rpi.edu> References: <7.0.0.16.0.20051215212900.02431810@alum.rpi.edu> Message-ID: On 12/16/05, bob wrote: > At 02:14 AM 12/14/2005, Liam Clarke wrote: > >Hi all, > > > >Just contemplating. > > > >If in Python I were organising a data index along the lines of - > > > >j = { > > > >"k_word1" : ["rec1","rec2","rec3","rec4"], > >... > >"k_wordn" :["recX","rec4"] > > > >} > > > >and I was going to find records that matched by seeing what record > >occurred in the most lists (via set intersections or similar; going to > >have a play see what works faster) selected by searching keywords... > > > >how easily does that translate to a SQL table and query format? > > Data modeling looks for relationships between objects. Relationships > can be 1-1 1-many or many-many. Your case is a many-many > (each keyword may appear in one or more records, and each record may > contain one or more keywords.) The customary way to represent this in > a relational database 3 tables. One with one row per keyword, one > with one row per record and one "junction" or "association" table > with one row for each keyword-record pair. > > KEYWORD TABLE > kid keyword > 1 cat > 2 dog > 3 mouse > 4 bird > 5 banana > > RECORD TABLE > rid record > 1 rexX > 2 rec4 > 3 recAB > 4 rec99 > 5 recFoo > > KEYWORD-RECORD TABLE > kid rid > 1 1 > 1 3 > 1 4 > 2 2 > 3 5 > 4 1 > 5 3 > > For processing things like this nothing IMHO beats a relational > database and SQL. With many databases accessible from Python I > strongly suggest this approach. SQLite is especially attractive. > [snip] > > Ah... so then on the last table I would use something along the lines of select rid where kid = 1... thanks for that, it was the modelling it part I was finding tricky. And yeah, I have pysqlite up and ready to go. I wrote a basic tutorial for it when it was 1.x :) (On account of how people like me need tutorials sometimes, although I have managed to use BeautifulSoup and py2exe today for the first time, so I've definitely progressed beyond when I first looked at them.) Regards, Liam Clarke From smiles at worksmail.net Fri Dec 16 16:01:12 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 16 Dec 2005 09:01:12 -0600 Subject: [Tutor] Accessing next and previous items during iteration References: Message-ID: <001601c60251$993a9e40$3a2c4fca@csmith> | Is it possible to access the next and previous items during an | iteration? | | I want to use it to iterate through html files in a folder and add | links in to the next and previous pages. | I just did this :-) What I did was 1) use the glob module to get a list of the files in the directory (*.htm) 2) sort this using a special sort function (in my case the files were named as #_# where # was a number and I wanted to sort according to the first number and subsort according to the second) 3) then I just stepped through the list using enumerate and used the index to find the next and previous names in the list, e.g. #### for i, fil in enumerate(flist): if i<>1: prev = flist[i-1] #do previous link if i<> len(flist): next = flist[i+1] #do next link #### /c From smiles at worksmail.net Fri Dec 16 15:55:25 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 16 Dec 2005 08:55:25 -0600 Subject: [Tutor] Accessing next and previous items during iteration References: Message-ID: <001401c60250$e33701b0$3a2c4fca@csmith> | Is it possible to access the next and previous items during an | iteration? | | I want to use it to iterate through html files in a folder and add | links in to the next and previous pages. | I just did this :-) What I did was 1) use the glob module to get a list of the files in the directory (*.htm) 2) sort this using a special sort function (in my case the files were named as #_# where # was a number and I wanted to sort according to the first number and subsort according to the second) 3) then I just stepped through the list using enumerate and used the index to find the next and previous names in the list, e.g. #### for i, fil in enumerate(flist): if i<>1: prev = flist[i-1] #do previous link if i<> len(flist): next = flist[i+1] #do next link #### /c From smiles at worksmail.net Fri Dec 16 16:01:01 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 16 Dec 2005 09:01:01 -0600 Subject: [Tutor] Accessing next and previous items during iteration References: Message-ID: <001501c60251$95967570$3a2c4fca@csmith> | Is it possible to access the next and previous items during an | iteration? | | I want to use it to iterate through html files in a folder and add | links in to the next and previous pages. | I just did this :-) What I did was 1) use the glob module to get a list of the files in the directory (*.htm) 2) sort this using a special sort function (in my case the files were named as #_# where # was a number and I wanted to sort according to the first number and subsort according to the second) 3) then I just stepped through the list using enumerate and used the index to find the next and previous names in the list, e.g. #### for i, fil in enumerate(flist): if i<>1: prev = flist[i-1] #do previous link if i<> len(flist): next = flist[i+1] #do next link #### /c From kent37 at tds.net Fri Dec 16 16:17:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Dec 2005 10:17:58 -0500 Subject: [Tutor] Accessing next and previous items during iteration In-Reply-To: <001601c60251$993a9e40$3a2c4fca@csmith> References: <001601c60251$993a9e40$3a2c4fca@csmith> Message-ID: <43A2DAA6.4060707@tds.net> Chris or Leslie Smith wrote: > I just did this :-) What I did was > > 1) use the glob module to get a list of the files in the directory (*.htm) > 2) sort this using a special sort function (in my case the files were named as #_# where # was a number and I wanted to sort according to the first number and subsort according to the second) > 3) then I just stepped through the list using enumerate and used the index to find the next and previous names in the list, e.g. > You have a couple of errors in your conditionals > #### > for i, fil in enumerate(flist): > if i<>1: > prev = flist[i-1] This should be 'if i >= 1'. If i==0 your condition will be true and you will set prev = flist[-1] which is the *last* item in flist. > #do previous link > if i<> len(flist): > next = flist[i+1] should be 'if i+1 < len(flist)' to avoid an IndexError on the last element. Kent > #do next link > #### > > /c > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From smiles at worksmail.net Fri Dec 16 16:29:42 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 16 Dec 2005 09:29:42 -0600 Subject: [Tutor] synchronized enumeration Message-ID: <002c01c60255$c16eaf10$3a2c4fca@csmith> Has anyone else run into the desire to synchronize the indices that are being used during an enumeration with the true indices of the list that is being enumerated when you use a slice of the list? e.g. more than a couple of times, I want to use the enumeration function, but I don't want to start at the beginning of a list. I do something like: ### for i, x in enumerate(aList[3:]): pass #do something with the index and or x ### Of course, if I do something with x in this case, there is no problem, but (often enough) I forget that the index 0 that is returned by enumerate is actually corresponding to index 3 (b/c that's where I started the slice). What I would love to see--and is there a chance of this being considered--is something like the following behavior for enumerate: ### def enumerate(l, start=None, stop=None, step=None, alwaysPos = False): if step==None:step=1 if start==None: if step<0: start=-1 else: start=0 for i, dat in enumerate(l[start:stop:step]): j = i*step+start if alwaysPos and j<0: j+=len(l) yield j, dat for i, x in enumerate(range(5),3): print i, x ### which gives output: 3 3 4 4 rather than enumerate(range(5)[3:])'s output of 0 3 1 4 Any thoughts? /c From kent37 at tds.net Fri Dec 16 17:42:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Dec 2005 11:42:42 -0500 Subject: [Tutor] synchronized enumeration In-Reply-To: <002c01c60255$c16eaf10$3a2c4fca@csmith> References: <002c01c60255$c16eaf10$3a2c4fca@csmith> Message-ID: <43A2EE82.2060509@tds.net> Chris or Leslie Smith wrote: > Has anyone else run into the desire to synchronize the indices that are being used during an enumeration with the true indices of the list that is being enumerated when you use a slice of the list? > > e.g. more than a couple of times, I want to use the enumeration function, but I don't want to start at the beginning of a list. I do something like: > > ### > for i, x in enumerate(aList[3:]): > pass #do something with the index and or x > > ### > > Of course, if I do something with x in this case, there is no problem, but (often enough) I forget that the index 0 that is returned by enumerate is actually corresponding to index 3 (b/c that's where I started the slice). > > What I would love to see--and is there a chance of this being considered--is something like the following behavior for enumerate: > > ### > def enumerate(l, start=None, stop=None, step=None, alwaysPos = False): > if step==None:step=1 > if start==None: > if step<0: > start=-1 > else: > start=0 > for i, dat in enumerate(l[start:stop:step]): > j = i*step+start > if alwaysPos and j<0: j+=len(l) > yield j, dat > > for i, x in enumerate(range(5),3): > print i, x > ### > > which gives output: > > 3 3 > 4 4 > > rather than enumerate(range(5)[3:])'s output of > > 0 3 > 1 4 > > Any thoughts? Take a look at this thread on c.l.py for some discussion and possibilities. The part you are interested in starts around message 14. http://groups.google.com/group/comp.lang.python/browse_frm/thread/ab1658dca4023e2b?hl=en& If you seriously want this to be considered for inclusion in Python you will need to broaden the discussion beyond this list. PEP 1 outlines the official process for getting something added to Python; it doesn't show the unofficial process which usually seems to involve a discussion on c.l.py or python-dev. http://www.python.org/peps/pep-0001.html Kent From falcon3166 at hotmail.com Fri Dec 16 23:37:21 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 16 Dec 2005 15:37:21 -0700 Subject: [Tutor] How do I fix this IndexError? In-Reply-To: Message-ID: Kent and all, Here is the latest code: import pickle rates = {'can_us' : 0.80276, 'us_can' : 1.245702, 'can_euro' : 1.488707, 'euro_can' : 0.671724} def save_rates(exch): store = open("exch.txt",'w') pickle.dump(conv,rate) store.close() def load_rates(exch): store = open('exch.txt','r') exch = pickle.load(store) store.close() And here is the latest error: The Currency Exchange Program By Nathan Pinno Traceback (most recent call last): File "D:\Python24\exchange.py", line 36, in -toplevel- load_rates(rates) File "D:\Python24\exchange.py", line 13, in load_rates exch = pickle.load(store) File "D:\Python24\lib\pickle.py", line 1390, in load return Unpickler(file).load() File "D:\Python24\lib\pickle.py", line 872, in load dispatch[key](self) File "D:\Python24\lib\pickle.py", line 1207, in load_appends mark = self.marker() File "D:\Python24\lib\pickle.py", line 888, in marker while stack[k] is not mark: k = k-1 IndexError: list index out of range How do I fix this error? Thanks for all the help so far, Nathan Pinno, MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 StopIteration is an iterator's way of saying it has reached the end. When you iterate using a for loop, the exception is caught internally and used to terminate the loop. When you call next() explicitly, you should be prepared to catch the exception yourself. In this case though, the exception means you have a conv without a rate, so it is a symptom of bad data or an error reading the data. Have you looked at the file to make sure it is correct? If it is, you might try a slightly different loop. I'm not sure if it really works to mix a for loop iteration with calls to next() on the iterator. Try something like this: store = open(filename,'r') try: while True: conv = store.next().strip() rate = float(store.next().strip()) exch[conv] = rate except StopIteration: pass Or use the pickle module to save and load your exch dictionary, it is perfect for this and as simple as import pickle # save store = open(filename, 'wb') pickle.dump(exch, store) store.close() # load store = open(filename, 'b') exch = pickle.load(store) store.close() Kent From dyoo at hkn.eecs.berkeley.edu Fri Dec 16 23:49:25 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 16 Dec 2005 14:49:25 -0800 (PST) Subject: [Tutor] How do I fix this IndexError? In-Reply-To: Message-ID: > import pickle > rates = {'can_us' : 0.80276, > 'us_can' : 1.245702, > 'can_euro' : 1.488707, > 'euro_can' : 0.671724} > > def save_rates(exch): > store = open("exch.txt",'w') > pickle.dump(conv,rate) > store.close() Hi Nathan, You may want to double check the use of pickle.dump(). I'm not sure I'm understanding what values are being passed here: what is 'conv' and what is 'rate' here? From falcon3166 at hotmail.com Sat Dec 17 00:06:00 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 16 Dec 2005 16:06:00 -0700 Subject: [Tutor] How do I fix this IndexError? In-Reply-To: Message-ID: Danny, 'conv' is for the name of the conversion [i.e 'can_us'] and rate is for the conversion rate [i.e. 0.80276] Thanks, Nathan Pinno, MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -----Original Message----- From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] Sent: December 16, 2005 3:49 PM To: Nathan Pinno Cc: tutor at python.org Subject: Re: [Tutor] How do I fix this IndexError? > import pickle > rates = {'can_us' : 0.80276, > 'us_can' : 1.245702, > 'can_euro' : 1.488707, > 'euro_can' : 0.671724} > > def save_rates(exch): > store = open("exch.txt",'w') > pickle.dump(conv,rate) > store.close() Hi Nathan, You may want to double check the use of pickle.dump(). I'm not sure I'm understanding what values are being passed here: what is 'conv' and what is 'rate' here? From ronin_cpim at hotmail.com Sat Dec 17 00:44:43 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Fri, 16 Dec 2005 18:44:43 -0500 Subject: [Tutor] [tutor] Python magazines? In-Reply-To: Message-ID: Is there a monthly Python hardcopy magazine? Otherwise what general programming mags carry the most python articles? Thx! RC _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From gsf at panix.com Sat Dec 17 02:59:39 2005 From: gsf at panix.com (Gabriel Farrell) Date: Fri, 16 Dec 2005 20:59:39 -0500 Subject: [Tutor] ElementTree in Python 2.5! In-Reply-To: <43A07E96.4030803@tds.net> References: <43A07E96.4030803@tds.net> Message-ID: <20051217015939.GB4147@panix.com> This is great news. And the thread on comp.lang.python is awesome. The eff-bot and the martelli-bot and everyone's just talking about how great it would be to have it in the core, and, then, it just ... happens. Wow! gsf On Wed, Dec 14, 2005 at 03:20:38PM -0500, Kent Johnson wrote: > By some miracle of the gods smiling and the planets aligning, a > comp.lang.python thread that started with the question "ElementTree - > Why not part of the core?" has actually resulted in ElementTree > *becoming* part of the core for Python 2.5! Pretty cool! So the core > Python distribution will finally have a Pythonic XML processor. > > Kent > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/e095cc79d1efb99/a4523a6e9b7061af?rnum=1#a4523a6e9b7061af > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Dec 17 06:34:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Dec 2005 00:34:41 -0500 Subject: [Tutor] How do I fix this IndexError? In-Reply-To: References: Message-ID: <43A3A371.6060805@tds.net> Nathan Pinno wrote: > Danny, > > 'conv' is for the name of the conversion [i.e 'can_us'] and rate is for the > conversion rate [i.e. 0.80276] Look at the pickle docs and my previous example. These are not the correct arguments to dump(). Kent From kent37 at tds.net Sat Dec 17 06:40:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Dec 2005 00:40:38 -0500 Subject: [Tutor] [tutor] Python magazines? In-Reply-To: References: Message-ID: <43A3A4D6.8020108@tds.net> CPIM Ronin wrote: > Is there a monthly Python hardcopy magazine? Otherwise what general > programming mags carry the most python articles? PyZine seems to be resuming publication: http://www.pyzine.com/index_html I don't know any mags with good Python coverage. I read comp.lang.python and many python-related blogs such as Planet Python http://planet.python.org/ Kent From ml.cyresse at gmail.com Sat Dec 17 08:59:55 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 17 Dec 2005 20:59:55 +1300 Subject: [Tutor] RegEx query Message-ID: Hi all, Using Beautiful Soup and regexes.. I've noticed that all the examples used regexes like so - anchors = parseTree.fetch("a", {"href":re.compile("pattern")} ) instead of precompiling the pattern. Myself, I have the following code - >>> z = [] >>> x = q.findNext("a", {"href":re.compile(".*?thread/[0-9]*?/.*", re.IGNORECASE)}) >>> while x: ... num = x.findNext("td", "tableColA") ... h = (x.contents[0],x.attrMap["href"],num.contents[0]) ... z.append(h) ... x = x.findNext("a",{"href":re.compile(".*?thread/[0-9]*?/.*", re.IGNORECASE)}) ... This gives me a correct set of results. However, using the following - >>> z = [] >>> pattern = re.compile(".*?thread/[0-9]*?/.*", re.IGNORECASE) >>> x = q.findNext("a", {"href":pattern)}) >>> while x: ... num = x.findNext("td", "tableColA") ... h = (x.contents[0],x.attrMap["href"],num.contents[0]) ... z.append(h) ... x = x.findNext("a",{"href":pattern} ) will only return the first found tag. Is the regex only evaluated once or similar? (Also any pointers on how to get negative lookahead matching working would be great. the regex (/thread/[0-9]*)(?!\/) still matches "/thread/28606/" and I'd assumed it wouldn't. Regards, Liam Clarke From kent37 at tds.net Sat Dec 17 14:20:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Dec 2005 08:20:32 -0500 Subject: [Tutor] RegEx query In-Reply-To: References: Message-ID: <43A410A0.805@tds.net> Liam Clarke wrote: > Hi all, > > Using Beautiful Soup and regexes.. I've noticed that all the examples > used regexes like so - anchors = parseTree.fetch("a", > {"href":re.compile("pattern")} ) instead of precompiling the pattern. > > Myself, I have the following code - > >>>>z = [] >>>>x = q.findNext("a", {"href":re.compile(".*?thread/[0-9]*?/.*", > > re.IGNORECASE)}) > > >>>>while x: > > ... num = x.findNext("td", "tableColA") > ... h = (x.contents[0],x.attrMap["href"],num.contents[0]) > ... z.append(h) > ... x = x.findNext("a",{"href":re.compile(".*?thread/[0-9]*?/.*", > re.IGNORECASE)}) > ... > > This gives me a correct set of results. However, using the following - > > >>>>z = [] >>>>pattern = re.compile(".*?thread/[0-9]*?/.*", re.IGNORECASE) >>>>x = q.findNext("a", {"href":pattern)}) > > >>>>while x: > > ... num = x.findNext("td", "tableColA") > ... h = (x.contents[0],x.attrMap["href"],num.contents[0]) > ... z.append(h) > ... x = x.findNext("a",{"href":pattern} ) > > will only return the first found tag. > > Is the regex only evaluated once or similar? I don't know why there should be any difference unless BS modifies the compiled regex object and for some reason needs a fresh one each time. That would be odd and I don't see it in the source code. The code above has a syntax error (extra paren in the first findNext() call) - can you post the exact non-working code? > > (Also any pointers on how to get negative lookahead matching working > would be great. > the regex (/thread/[0-9]*)(?!\/) still matches "/thread/28606/" and > I'd assumed it wouldn't. Putting these expressions into Regex Demo is enlightening - the regex matches against "/thread/2860" - in other words the "not /" is matching against the 6. You don't give an example of what you do want to match so it's hard to know what a better solution is. Some possibilities - match anything except a digit or a slash - [^0-9/] - match the end of the string - $ - both of the above - ([^0-9/]|$) Kent > > Regards, > > Liam Clarke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From falcon3166 at hotmail.com Sat Dec 17 20:00:33 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 17 Dec 2005 12:00:33 -0700 Subject: [Tutor] How do I fix this Invalid Mode? Message-ID: Here is the latest error: The Currency Exchange Program By Nathan Pinno Traceback (most recent call last): File "D:\Python24\exchange.py", line 27, in -toplevel- store = open('exch.txt', 'b')#load IOError: invalid mode: b and the latest code: import pickle rates = {'can_us' : 0.80276, 'us_can' : 1.245702, 'can_euro' : 1.488707, 'euro_can' : 0.671724} def menu(): print "1. Change Canadian currency into American." print "2. Change American currency into Canadian." print "3. Change Canadian currency into Euros." print "4. Change Euros into Canadian currency." print "5. Update exchange rates." print "9. Save and Exit" def exchange_update(): print "1. Update Canadian to US rate." print "2. Update US to Canadian rate." print "3. Update Canadian to Euro rate." print "4. Update Euro to Canadian update." print "5. Main menu" def menu_choice(): return int(raw_input("Which option? ")) print "The Currency Exchange Program" print "By Nathan Pinno" store = open('exch.txt', 'b')#load exch = pickle.load(store) store.close() while 1: menu() menu_option = menu_choice() if menu_option == 1: can = float(raw_input("Canadian $")) print "US $",can*rates['can_us'] elif menu_option == 2: us = float(raw_input("US $")) print "CAN $",us*rates['us_can'] elif menu_option == 3: can = float(raw_input("CAN $")) print "Euros",can*rates['can_euro'] elif menu_option == 4: euro = float(raw_input("Euros")) print "CAN $",euro*rates['euro_can'] elif menu_option == 5: while 1: exchange_update() sub = menu_choice() if sub == 1: new_can = float(raw_input("New CAN-US Exchange rate: ")) rates['can_us'] = new_can print "Exchange rate successfully updated!" elif sub == 2: new_us = float(raw_input("New US-CAN Exchange rate: ")) rates['us_can'] = new_us print "Exchange rate successfully updated!" elif sub == 3: new_cxr = float(raw_input("New CAN-Euro Exchange rate: ")) rates['can_euro'] = new_cxr print "Exchange rate successfully updated!" elif sub == 4: new_euro = float(raw_input("New Euro-CAN Exchange rate: ")) rates['euro_can'] = new_euro print "Exchange rate successfully updated!" elif sub == 5: break elif menu_option == 9: store = open("exch.txt", 'wb') #save pickle.dump(exch, store) store.close() break print "Goodbye." How do I fix it this time? Thanks, Nathan Pinno, MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051217/d3339b3c/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051217/d3339b3c/attachment.gif From dan at tangledhelix.com Sat Dec 17 20:39:16 2005 From: dan at tangledhelix.com (Dan Lowe) Date: Sat, 17 Dec 2005 14:39:16 -0500 Subject: [Tutor] How do I fix this Invalid Mode? In-Reply-To: References: Message-ID: <884006C0-A0A6-4AAE-A422-04F99A6AC746@tangledhelix.com> On Dec 17, 2005, at 2:00 PM, Nathan Pinno wrote: > Here is the latest error: > The Currency Exchange Program > By Nathan Pinno > > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 27, in -toplevel- > store = open('exch.txt', 'b')#load > IOError: invalid mode: b [snip...] > store = open('exch.txt', 'b')#load > exch = pickle.load(store) > store.close() It looks like what you are trying to do is read exch.txt as a binary file. The problem is that 'b' by itself is not a valid mode; it's a modifier to one of the other modes (r, w or a). So to read a file in binary mode, what you want to do is: store = open('exch.txt', 'rb') Using your own code as an example, see how you implemented the save feature (option 9). That open() correctly uses the 'wb' flag to write the file in binary mode. elif menu_option == 9: store = open("exch.txt", 'wb') #save pickle.dump(exch, store) store.close() break -dan -- Black holes are where God divided by zero. -Steven Wright -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051217/da5b0b4a/attachment.htm From cspears2002 at yahoo.com Sun Dec 18 00:42:27 2005 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sat, 17 Dec 2005 15:42:27 -0800 (PST) Subject: [Tutor] mysterious object Message-ID: <20051217234227.52682.qmail@web51614.mail.yahoo.com> I'm working on Exercise 4 from Part 4 from Learning Python. I'm trying to write a function using **args. I want to create a function that adds its arguments together. Here is what I have written: def adder(**args): for x in args.keys(): print x print adder() print "---" print adder(a=5) print "---" print adder(a=5,b=6) print "---" print adder(a=5,b=6,c=7) print "---" print adder(ugly=7, good=6, bad=5) print "---" Here is my output: None --- a None --- a b None --- a c b None --- ugly bad good None --- Where do the None objects come from? From broek at cc.umanitoba.ca Sun Dec 18 01:07:32 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 17 Dec 2005 18:07:32 -0600 Subject: [Tutor] mysterious object In-Reply-To: <20051217234227.52682.qmail@web51614.mail.yahoo.com> References: <20051217234227.52682.qmail@web51614.mail.yahoo.com> Message-ID: <43A4A844.8020703@cc.umanitoba.ca> Christopher Spears said unto the world upon 2005-12-17 17:42: > I'm working on Exercise 4 from Part 4 from Learning > Python. I'm trying to write a function using **args. > I want to create a function that adds its arguments > together. Here is what I have written: > > def adder(**args): > for x in args.keys(): > print x > > print adder() > print "---" > print adder(a=5) > print "---" > > > Here is my output: > > None > --- > a > None > --- Hi Christopher, all functions that terminate return a value, even if they don't have an explicit return statement. If they either have a bare "return" or no return at all, then they return None. You've put prints both in the functions and at the function calls. So, each time you've written print adder(), you've asked Python to print the return value of adder -- which is None. >>> def Noner(): return >>> print Noner() None >>> Does that clear it up? Best, Brian vdB From alan.gauld at freenet.co.uk Sun Dec 18 01:45:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 18 Dec 2005 00:45:46 -0000 Subject: [Tutor] mysterious object References: <20051217234227.52682.qmail@web51614.mail.yahoo.com> Message-ID: <001101c6036c$629103e0$04000100@xp> > def adder(**args): > for x in args.keys(): > print x A function which doesn't return a value returns None by default. > print adder() You are asking Python to print the return value of the function, which is None. As a general rule its better to do the printing outside of the function and just do the calculation bit inside, this makes the function much easier to reuse in future. HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From cspears2002 at yahoo.com Sun Dec 18 08:30:17 2005 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sat, 17 Dec 2005 23:30:17 -0800 (PST) Subject: [Tutor] design advice for function Message-ID: <20051218073017.45073.qmail@web51607.mail.yahoo.com> I got my function to work! It takes arguments and adds them: def adder(**args): argsList = args.values() sum = argsList[0] for x in argsList[1:]: sum = sum + x return sum print adder() print "---" print adder(a=5) print "---" print adder(a=5,b=6) print "---" print adder(a=5,b=6,c=7) print "---" print adder(ugly=7, good=6, bad=5) print "---" However, if I run the above code. I get an error: Traceback (most recent call last): File "C:\Documents and Settings\Christopher Spears\My Documents\programming\PythonScripts\Part4\Ex04\adder.py", line 8, in -toplevel- print adder() File "C:\Documents and Settings\Christopher Spears\My Documents\programming\PythonScripts\Part4\Ex04\adder.py", line 3, in adder sum = argsList[0] IndexError: list index out of range This is caused by the line: print adder(). Obviously if adder() doesn't receive any arguments, it can't build the lists resulting in an IndexError. What is the best way to solve this? Should I write some syntax into the function to check for arguments? Should I just write a seperate function to check for arguments? From broek at cc.umanitoba.ca Sun Dec 18 10:11:23 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 18 Dec 2005 03:11:23 -0600 Subject: [Tutor] design advice for function In-Reply-To: <20051218073017.45073.qmail@web51607.mail.yahoo.com> References: <20051218073017.45073.qmail@web51607.mail.yahoo.com> Message-ID: <43A527BB.3080002@cc.umanitoba.ca> Christopher Spears said unto the world upon 2005-12-18 01:30: > I got my function to work! It takes arguments and > adds them: Hi Christopher, great! > def adder(**args): > argsList = args.values() > sum = argsList[0] > for x in argsList[1:]: > sum = sum + x > return sum > > print adder() > print "---" > print adder(a=5) > print "---" > print adder(a=5,b=6) > print "---" > print adder(a=5,b=6,c=7) > print "---" > print adder(ugly=7, good=6, bad=5) > print "---" > > However, if I run the above code. I get an error: > > Traceback (most recent call last): > File "C:\Documents and Settings\Christopher > Spears\My > Documents\programming\PythonScripts\Part4\Ex04\adder.py", > line 8, in -toplevel- > print adder() > File "C:\Documents and Settings\Christopher > Spears\My > Documents\programming\PythonScripts\Part4\Ex04\adder.py", > line 3, in adder > sum = argsList[0] > IndexError: list index out of range > > This is caused by the line: print adder(). Obviously > if adder() doesn't receive any arguments, it can't > build the lists resulting in an IndexError. Right. You are also going to have a like problem with the next chunk of you function: for x in argsList[1:]: sum = sum + x (If you fix the adder() problem alone, you will still have a adder(one_arg) problem.) > What is > the best way to solve this? Should I write some > syntax into the function to check for arguments? > Should I just write a seperate function to check for arguments? Well, what you like adder() to do? It is not uncommon for operations of a sequence to have a separate clause for the special case of the empty sequence. So, you could do: if not argsList: return what_Christopher_wants If you do that, can you think of a way to get around the adder(one_arg) problem? Hint: do you really need to treat the first element of argsList as a special case? Have a think, and if you get stuck, post again. Best, Brian vdB From kent37 at tds.net Sun Dec 18 13:31:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Dec 2005 07:31:39 -0500 Subject: [Tutor] design advice for function In-Reply-To: <20051218073017.45073.qmail@web51607.mail.yahoo.com> References: <20051218073017.45073.qmail@web51607.mail.yahoo.com> Message-ID: <43A556AB.7010909@tds.net> Christopher Spears wrote: > I got my function to work! It takes arguments and > adds them: > > def adder(**args): > argsList = args.values() > sum = argsList[0] > for x in argsList[1:]: > sum = sum + x > return sum > > print adder() > > However, if I run the above code. I get an error: > > Traceback (most recent call last): > sum = argsList[0] > IndexError: list index out of range > > This is caused by the line: print adder(). Obviously > if adder() doesn't receive any arguments, it can't > build the lists resulting in an IndexError. What is > the best way to solve this? Should I write some > syntax into the function to check for arguments? > Should I just write a seperate function to check for arguments? Actually adder is still receiving an argument, it is an empty dictionary: >>> def adder(**args): ... print args ... >>> adder() {} If you iterate the whole items() list then Python will do the right thing (i.e. nothing) when the list is empty. Can you think of another way to initialize sum that lets you iterate the whole list instead of slicing off the first element? A couple of notes: - I'm not sure why you are passing keyword arguments, do you know that there is a way to pass a variable list of arguments to a function? Use a single * in the parameter list and unnamed arguments at the point of call. The argument list is passed as a tuple: >>> def adder(*args): ... print args ... >>> adder() () >>> adder(1, 2, 3) (1, 2, 3) Of course if you want the keyword style of argument passing then keep doing what you are doing. - The name of the keyword parameter is conventionally something like kwds or kwargs. 'args' is usually used for a variable argument list as in my second example. Your code may be easier for others to understand if you use this convention. (At least I was thrown for a moment by **args and read it as *args.) Kent From alan.gauld at freenet.co.uk Sun Dec 18 15:53:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 18 Dec 2005 14:53:58 -0000 Subject: [Tutor] design advice for function References: <20051218073017.45073.qmail@web51607.mail.yahoo.com> Message-ID: <002301c603e2$e0a21a50$04000100@xp> > def adder(**args): > argsList = args.values() > sum = argsList[0] > for x in argsList[1:]: > sum = sum + x > return sum > line 3, in adder > sum = argsList[0] > IndexError: list index out of range > > This is caused by the line: print adder(). Obviously > if adder() doesn't receive any arguments, it can't > build the lists resulting in an IndexError. What is > the best way to solve this? Should I write some > syntax into the function to check for arguments? The Pythonic way is to use exceptions. You can either handle the exception inside the function or outside: def adder(**args): try: # your code hee except IndexError: return 0 # or some other default, perhaps even None?! OR def adder(**args): try: # your code hee except IndexError: raise try: print adder() print addre(a=1) # etc... except IndexError: print 'oops, no arguments to adder' In this case I'd probably use the first approach (with None as default), but its up to you... Alan G From dyoo at hkn.eecs.berkeley.edu Sun Dec 18 22:11:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 18 Dec 2005 13:11:22 -0800 (PST) Subject: [Tutor] design advice for function In-Reply-To: <002301c603e2$e0a21a50$04000100@xp> Message-ID: On Sun, 18 Dec 2005, Alan Gauld wrote: > > def adder(**args): > > argsList = args.values() > > sum = argsList[0] > > for x in argsList[1:]: > > sum = sum + x > > return sum > > > line 3, in adder > > sum = argsList[0] > > IndexError: list index out of range > > > > This is caused by the line: print adder(). Obviously if adder() > > doesn't receive any arguments, it can't build the lists resulting in > > an IndexError. What is the best way to solve this? Should I write > > some syntax into the function to check for arguments? > > The Pythonic way is to use exceptions. Hi Alan, I disagree for this particular situation: adder() can be written so it doesn't raise an exception on empty input. Brian gave a hint about this when he asked: what happens if we try to sum up an empty sequence? Without looking at the body of the function, what value do we want to get from the call to "adder()" with no arguments? Once we know this, then we can go toward defining our function to do what we want. From kent37 at tds.net Sun Dec 18 22:11:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Dec 2005 16:11:44 -0500 Subject: [Tutor] Accessing next and previous items during iteration In-Reply-To: <34bb7f5b0512160210t1e5f03dep@mail.gmail.com> References: <34bb7f5b0512160210t1e5f03dep@mail.gmail.com> Message-ID: <43A5D090.6060206@tds.net> Ed Singleton wrote: > Is it possible to access the next and previous items during an iteration? This just came up on c.l.python. Bengt Richter has a nice generator-based solution. http://groups.google.com/group/comp.lang.python/browse_thread/thread/2e4533f108fbf172/90d87c91dac844d3?hl=en#90d87c91dac844d3 Kent From dyoo at hkn.eecs.berkeley.edu Sun Dec 18 22:19:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 18 Dec 2005 13:19:39 -0800 (PST) Subject: [Tutor] design advice for function In-Reply-To: <43A527BB.3080002@cc.umanitoba.ca> Message-ID: > > This is caused by the line: print adder(). Obviously > > if adder() doesn't receive any arguments, it can't > > build the lists resulting in an IndexError. > > Right. Hello! Just wanted to clarify the situation: argsList ends up being the empty list, which is a perfectly good value: ###### >>> d = {} >>> l = d.values() >>> l [] ###### So lists are being built perfectly ok. The issue is that the operations that we do on them later should account for the possibility that the lists are empty. One thing about the empty list, in particular, is this: because it has no elements, it's an invalid operation to try to get the first element of an empty list: ###### >>> l[0] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range ###### Programmers will often call say something like "Don't forget the null/empty case!", which is what this is. *grin* Best of wishes! From alan.gauld at freenet.co.uk Sun Dec 18 23:48:37 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 18 Dec 2005 22:48:37 -0000 Subject: [Tutor] design advice for function References: Message-ID: <002d01c60425$2f1fc4b0$04000100@xp> >> > line 3, in adder >> > sum = argsList[0] >> > IndexError: list index out of range >> > >> > an IndexError. What is the best way to solve this? Should I write >> > some syntax into the function to check for arguments? >> >> The Pythonic way is to use exceptions. > > I disagree for this particular situation: adder() can be written so it > doesn't raise an exception on empty input. Brian gave a hint about this > when he asked: what happens if we try to sum up an empty sequence? That's why I said I'd use the exception internally but return None from within the exception handler. I just think that catching the exception is the natural way to process the case of an empty input. Certainly cleaner than putting special processing in the main code body. (The real problem here is to figure out what exactly an adder should do when given nothing to add...) But maybe that's just me... Alan G. From 3dbernard at gmail.com Mon Dec 19 03:56:19 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Sun, 18 Dec 2005 18:56:19 -0800 Subject: [Tutor] Name tables questions Message-ID: <61d0e2b40512181856u7aba3faet991fac91dd23055f@mail.gmail.com> Hello, I have a few theoric questions regarding name tables. I wish to better understand a few things about this aspect of Python, in particular how module names and the import statements fit into the picture of name tables. - First of all, I understand each scope has its "local" name table, containing all the names defined in this scope, no matter the origin of the name. So, if you import a module in a scope, its name is added to the local scope name table, correct? - When you import a module, I understand the module name is appended to Python dictionary of imported modules. I can see the name of the module if I print out the sys.modules attribute. If the module name is also added to the local scope name table, it does mean that the module is added in two tables: the local scope name table and the imported modules table. Is that correct? - I *think* I have read in Learning Python (sorry I don't have the book near me) that during execution, when Python doesn't find a name in the current scope name table, then it will look up every encompassing name table one after another, until it can find it, and if it can't, will raise an error. If I remember correctly about my reading, this lookup into an encompassing name table has a performance cost. The author suggests that, without regard to the practical considerations, it would not be such a bad idea to pass down all possible names to functions and encapsulated functions so name lookup into other tables could be avoided. Now, let say I would do something like that, and be zealous at that, to the point where I would write import statements for the same modules in every possible function to define the module name there. Since the module name is already in the module names dictionary but not in the global name table, would there be any advantage, or disadvantage in doing so? Thanks in advance Bernard From broek at cc.umanitoba.ca Mon Dec 19 10:23:34 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 19 Dec 2005 03:23:34 -0600 Subject: [Tutor] design advice for function In-Reply-To: References: Message-ID: <43A67C16.2050406@cc.umanitoba.ca> Danny Yoo said unto the world upon 2005-12-18 15:19: >> > This is caused by the line: print adder(). Obviously >> > if adder() doesn't receive any arguments, it can't >> > build the lists resulting in an IndexError. >> >>Right. > > > Hello! > > Just wanted to clarify the situation: argsList ends up being the empty > list, which is a perfectly good value: Danny is, of course, perfectly correct. Apologies to the op for the imprecision. Once again, I vow never to post after 3:00. Oh, wait, it is 3:23! Brian vdB From ml.cyresse at gmail.com Mon Dec 19 11:12:44 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 19 Dec 2005 23:12:44 +1300 Subject: [Tutor] RegEx query In-Reply-To: <43A410A0.805@tds.net> References: <43A410A0.805@tds.net> Message-ID: Hi Kent, I apologise for the not overly helpful initial post. I had six possible uris to deal with - /thread/28742/ /thread/28742/?s=1291819247219837219837129 /thread/28742/5/ /thread/28742/5/?s=1291819247219837219837129 /thread/28742/?goto=lastpost /thread/28742/?s=1291819247219837219837129&goto=lastpost The only one I wanted to match was the first two. My initial pattern /thread/[0-9]*?/(\?s\=.*)?(?!lastpost)$ matched the first two and the last in redemo.py (which I've got stashed as a py2exe bundle, should I ever find myself sans Python but having to use regexes). I managed to sort it by using /thread /[0-9]*?/ (\?s\=\w*)?$ The s avoids the fourth possibility, and the \w precludes the & in the last uri. But, circumventing the problem irks me no end, as I haven't fixed what I was doing wrong, which means I'll probably do it again, and avoiding problems instead of resolving them feels too much like programming for the Win32 api to me. (Where removing a service from the service database doesn't actually remove the service from the service database until you open and close a handle to the service database a second time...) So yes, any advice on how to use negative lookaheads would be great. I get the feeling it was the .* before it. As for my problem with BeautifulSoup, I'm not sure what was happening there. It was happening in interactive console only, and I can't replicate it today, which suggests to me that I've engaged email before brain again. I do like BeautifulSoup, however. Although people keep telling about some XPath programme that's better, apparently, I like BeautifulSoup, it works. Regards, Liam Clarke On 12/18/05, Kent Johnson wrote: > Liam Clarke wrote: > > Hi all, > > > > Using Beautiful Soup and regexes.. I've noticed that all the examples > > used regexes like so - anchors = parseTree.fetch("a", > > {"href":re.compile("pattern")} ) instead of precompiling the pattern. > > > > Myself, I have the following code - > > > >>>>z = [] > >>>>x = q.findNext("a", {"href":re.compile(".*?thread/[0-9]*?/.*", > > > > re.IGNORECASE)}) > > > > > >>>>while x: > > > > ... num = x.findNext("td", "tableColA") > > ... h = (x.contents[0],x.attrMap["href"],num.contents[0]) > > ... z.append(h) > > ... x = x.findNext("a",{"href":re.compile(".*?thread/[0-9]*?/.*", > > re.IGNORECASE)}) > > ... > > > > This gives me a correct set of results. However, using the following - > > > > > >>>>z = [] > >>>>pattern = re.compile(".*?thread/[0-9]*?/.*", re.IGNORECASE) > >>>>x = q.findNext("a", {"href":pattern)}) > > > > > >>>>while x: > > > > ... num = x.findNext("td", "tableColA") > > ... h = (x.contents[0],x.attrMap["href"],num.contents[0]) > > ... z.append(h) > > ... x = x.findNext("a",{"href":pattern} ) > > > > will only return the first found tag. > > > > Is the regex only evaluated once or similar? > > I don't know why there should be any difference unless BS modifies the compiled regex > object and for some reason needs a fresh one each time. That would be odd and I don't see > it in the source code. > > The code above has a syntax error (extra paren in the first findNext() call) - can you > post the exact non-working code? > > > > (Also any pointers on how to get negative lookahead matching working > > would be great. > > the regex (/thread/[0-9]*)(?!\/) still matches "/thread/28606/" and > > I'd assumed it wouldn't. > > Putting these expressions into Regex Demo is enlightening - the regex matches against > "/thread/2860" - in other words the "not /" is matching against the 6. > > You don't give an example of what you do want to match so it's hard to know what a better > solution is. Some possibilities > - match anything except a digit or a slash - [^0-9/] > - match the end of the string - $ > - both of the above - ([^0-9/]|$) > > Kent > > > > > Regards, > > > > Liam Clarke > > _______________________________________________ > > 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 singletoned at gmail.com Mon Dec 19 11:49:34 2005 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 19 Dec 2005 10:49:34 +0000 Subject: [Tutor] Accessing next and previous items during iteration In-Reply-To: <43A5D090.6060206@tds.net> References: <34bb7f5b0512160210t1e5f03dep@mail.gmail.com> <43A5D090.6060206@tds.net> Message-ID: <34bb7f5b0512190249v18f9d53bw@mail.gmail.com> On 18/12/05, Kent Johnson wrote: > Ed Singleton wrote: > > Is it possible to access the next and previous items during an iteration? > > This just came up on c.l.python. Bengt Richter has a nice generator-based solution. > http://groups.google.com/group/comp.lang.python/browse_thread/thread/2e4533f108fbf172/90d87c91dac844d3?hl=en#90d87c91dac844d3 That's perfect! It's a lovely piece of code as well. Obvious once you've seen it, but you wouldn't have thought of it before hand. Thanks Ed From kent37 at tds.net Mon Dec 19 12:05:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Dec 2005 06:05:09 -0500 Subject: [Tutor] RegEx query In-Reply-To: References: <43A410A0.805@tds.net> Message-ID: <43A693E5.4000008@tds.net> Liam Clarke wrote: > Hi Kent, > > I apologise for the not overly helpful initial post. > > I had six possible uris to deal with - > > /thread/28742/ > /thread/28742/?s=1291819247219837219837129 > /thread/28742/5/ > /thread/28742/5/?s=1291819247219837219837129 > /thread/28742/?goto=lastpost > /thread/28742/?s=1291819247219837219837129&goto=lastpost > > The only one I wanted to match was the first two. > > My initial pattern /thread/[0-9]*?/(\?s\=.*)?(?!lastpost)$ > > matched the first two and the last in redemo.py (which I've got > stashed as a py2exe bundle, should I ever find myself sans Python but > having to use regexes). > > I managed to sort it by using > > /thread > /[0-9]*?/ > (\?s\=\w*)?$ > > The s avoids the fourth possibility, and the \w precludes the & in the last uri. This seems like a good solution to me. The patterns you want to accept and reject are pretty similar so your regex has to be very specific to discriminate them. > > But, circumventing the problem irks me no end, as I haven't fixed what > I was doing wrong, which means I'll probably do it again, and avoiding > problems instead of resolving them feels too much like programming for > the Win32 api to me. > (Where removing a service from the service database doesn't actually > remove the service from the service database until you open and close > a handle to the service database a second time...) > > So yes, any advice on how to use negative lookaheads would be great. I > get the feeling it was the .* before it. I think you may misunderstand how * works. It will match as much as possible but it will backtrack and match less if that makes the whole match work. For example the regex ab*d will match abbd with b* matching bb. If I change the regex to ab*(?!d) then it will still match abbd but the b* will just match one b and the d doesn't participate in the match. So b* doesn't mean "match all the b's no matter what" it means "match as many b's as you can and still have the rest of the match succeed". In the case of ab*(?!d) this means, match an 'a', then a sequence of 'b', then something that is not 'd'. By shortening the match for b*, the 'not d' can match against the last 'b'. > > As for my problem with BeautifulSoup, I'm not sure what was happening > there. It was happening in interactive console only, and I can't > replicate it today, which suggests to me that I've engaged email > before brain again. > > I do like BeautifulSoup, however. Although people keep telling about > some XPath programme that's better, apparently, I like BeautifulSoup, > it works. Which XPath program is that? I haven't found one I really like. Kent From python at kapitalisten.no Mon Dec 19 13:45:52 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Mon, 19 Dec 2005 13:45:52 +0100 (CET) Subject: [Tutor] List-question Message-ID: <63400.193.71.38.142.1134996352.squirrel@mail.sporck.net> I have one function that finds some values. Then I want that function to find new values based on the values it found first. However, by just looping, it starts on an eternal job. As illustrated in: >>> list = [1,2,3] >>> list2 = list >>> list2 [1, 2, 3] >>> for i in list: ... print i ... list2.append(4) ... 1 2 3 4 4 4 and it will forever continue with 4's. Why would list be expanded with the values of list2? How can I copy the result from one list, and do things with the list without getting it to expand? -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From singletoned at gmail.com Mon Dec 19 14:02:16 2005 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 19 Dec 2005 13:02:16 +0000 Subject: [Tutor] List-question In-Reply-To: <63400.193.71.38.142.1134996352.squirrel@mail.sporck.net> References: <63400.193.71.38.142.1134996352.squirrel@mail.sporck.net> Message-ID: <34bb7f5b0512190502i9664b19l@mail.gmail.com> On 19/12/05, ?yvind wrote: > I have one function that finds some values. Then I want that function to > find new values based on the values it found first. However, by just > looping, it starts on an eternal job. > > As illustrated in: > >>> list = [1,2,3] > >>> list2 = list > >>> list2 > [1, 2, 3] > >>> for i in list: > ... print i > ... list2.append(4) > ... > 1 > 2 > 3 > 4 > 4 > 4 and it will forever continue with 4's. > > Why would list be expanded with the values of list2? How can I copy the > result from one list, and do things with the list without getting it to > expand? Because they point to the same thing. Type "list2 is list" after your other code and see. You want list2 to be a COPY of list not a pointer to it. Do this by using list2 = list.copy() Slices create a copy, so a shortcut is: list2 = list[:] Ed From singletoned at gmail.com Mon Dec 19 14:10:21 2005 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 19 Dec 2005 13:10:21 +0000 Subject: [Tutor] List-question In-Reply-To: <34bb7f5b0512190502i9664b19l@mail.gmail.com> References: <63400.193.71.38.142.1134996352.squirrel@mail.sporck.net> <34bb7f5b0512190502i9664b19l@mail.gmail.com> Message-ID: <34bb7f5b0512190510g33e2b0dfx@mail.gmail.com> On 19/12/05, Ed Singleton wrote: > On 19/12/05, ?yvind wrote: > > I have one function that finds some values. Then I want that function to > > find new values based on the values it found first. However, by just > > looping, it starts on an eternal job. > > > > As illustrated in: > > >>> list = [1,2,3] > > >>> list2 = list > > >>> list2 > > [1, 2, 3] > > >>> for i in list: > > ... print i > > ... list2.append(4) > > ... > > 1 > > 2 > > 3 > > 4 > > 4 > > 4 and it will forever continue with 4's. > > > > Why would list be expanded with the values of list2? How can I copy the > > result from one list, and do things with the list without getting it to > > expand? > > Because they point to the same thing. > > Type "list2 is list" after your other code and see. > > You want list2 to be a COPY of list not a pointer to it. Do this by using > > list2 = list.copy() > > Slices create a copy, so a shortcut is: > > list2 = list[:] Sorry, you need to: from copy import copy before you can use copy. Also, you shouldn't use "list" as a variable name. as it is a built-in function that converts things to lists. Use "list1". That way you can also use list2 = list(list1). Ed From kent37 at tds.net Mon Dec 19 14:33:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Dec 2005 08:33:54 -0500 Subject: [Tutor] Name tables questions In-Reply-To: <61d0e2b40512181856u7aba3faet991fac91dd23055f@mail.gmail.com> References: <61d0e2b40512181856u7aba3faet991fac91dd23055f@mail.gmail.com> Message-ID: <43A6B6C2.6030803@tds.net> Bernard Lebel wrote: > Hello, > > I have a few theoric questions regarding name tables. I wish to better > understand a few things about this aspect of Python, in particular how > module names and the import statements fit into the picture of name > tables. > > - First of all, I understand each scope has its "local" name table, > containing all the names defined in this scope, no matter the origin > of the name. So, if you import a module in a scope, its name is added > to the local scope name table, correct? Yes, with a couple of notes: - The correct term is "namespace", not "name table". - Instead of talking about defining a name, a better term is "binding". Binding a name in a namespace means associating the name with a value in the context of the namespace. This is usually implemented by making an entry in some dictionary that implements the namespace. - "All the names defined in this scope" could be interpreted to mean "all the names accessible in this scope." With this interpretation your statement is *not* correct. The local namespace includes all names that are actually bound in the local scope, not all names accessible in the local scope. For example: >>> import sys >>> a = 1 >>> def f(): ... import os ... b = 2 ... print 'locals:', locals() ... print 'globals:', globals() ... >>> f() locals: {'b': 2, 'os': } globals: {'a': 1, 'f': , '__builtins__': , '__file__': 'C:\\Documents and Settings\\ktjohns on\\pythonstartup.py', 'sys': , '__name__': '__main__', '__doc__': None} The local namespace of f() includes os and b, which are bound in f(). The global namespace includes sys, a and f, all names bound at global scope, and several other names inserted automatically by the Python runtime. > > - When you import a module, I understand the module name is appended > to Python dictionary of imported modules. I can see the name of the > module if I print out the sys.modules attribute. If the module name is > also added to the local scope name table, it does mean that the module > is added in two tables: the local scope name table and the imported > modules table. Is that correct? Yes. The module object itself is cached in sys.modules. sys.modules is a dict whose keys are module names and values are the actual module objects. Subsequent imports will find the cached module and bind a name to it. > > - I *think* I have read in Learning Python (sorry I don't have the > book near me) that during execution, when Python doesn't find a name > in the current scope name table, then it will look up every > encompassing name table one after another, until it can find it, and > if it can't, will raise an error. Yes. > If I remember correctly about my reading, this lookup into an > encompassing name table has a performance cost. The author suggests > that, without regard to the practical considerations, it would not be > such a bad idea to pass down all possible names to functions and > encapsulated functions so name lookup into other tables could be > avoided. Yes, there is a performance cost. No, it doesn't make sense to "pass down" all possible names. If a name is not used in a function, then you have incurred the cost of looking it up and binding it in the local namespace without any benefit. If the name is used once in the function, it is still probably cheaper to just look it up once globally and skip the local rebinding and lookup. Where this makes sense is in a loop that is a known performance bottleneck that you are trying to optimize. Then there is a benefit to making local copies of any global names that are in the loop. It is also beneficial to make local copies of attributes that are accessed in the loop such as methods. > Now, let say I would do something like that, and be zealous at that, > to the point where I would write import statements for the same > modules in every possible function to define the module name there. > Since the module name is already in the module names dictionary but > not in the global name table, would there be any advantage, or > disadvantage in doing so? Again the only advantage of this would be if the module is used repeatedly in a loop. But in that case you are better off making a local reference to the module attribute you actually use, rather than the module itself. For example something like this to generate the paths to all files in a directory: import os def allFiles(path): join = os.path.join isfile = os.path.isfile for f in os.listdir(path): p = join(path, f) if isfile(p): yield p This is not a very good example because the performance of this fn is likely to be dominated by the I/O, not the name lookup, but it gives the idea. You might be interested in this recipe which automatically performs this kind of optimization: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 But I should stress that this is an *optimization*, which you should use only on known bottlenecks! Kent > > > > Thanks in advance > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From carroll at tjc.com Mon Dec 19 20:21:51 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 19 Dec 2005 11:21:51 -0800 (PST) Subject: [Tutor] List-question In-Reply-To: <34bb7f5b0512190510g33e2b0dfx@mail.gmail.com> Message-ID: On Mon, 19 Dec 2005, Ed Singleton wrote: > On 19/12/05, Ed Singleton wrote: > > > > list2 = list.copy() > > > > Slices create a copy, so a shortcut is: > > > > list2 = list[:] > > Sorry, you need to: > > from copy import copy > > before you can use copy. It should also be, after the import: list2=copy.copy(list1) rather than list2=list1.copy() # or list2=list.copy() From hugonz-lists at h-lab.net Mon Dec 19 20:41:25 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 19 Dec 2005 13:41:25 -0600 Subject: [Tutor] bnf In-Reply-To: <1114f05f0512100519n61ef4e50y6177db01856f2fa8@mail.gmail.com> References: <000701c5fd85$9dbe4fa0$0201a8c0@d71bh5mhis9p7o> <1114f05f0512100519n61ef4e50y6177db01856f2fa8@mail.gmail.com> Message-ID: <43A70CE5.2080401@h-lab.net> >>> mystring = 'laLA' >>> mystring.upper() 'LALA' >>> mystring.lower() 'lala' From jivotni at yahoo.com Tue Dec 20 00:31:31 2005 From: jivotni at yahoo.com (Krava Magare) Date: Mon, 19 Dec 2005 15:31:31 -0800 (PST) Subject: [Tutor] question ! Message-ID: <20051219233131.23308.qmail@web54003.mail.yahoo.com> How can I remove and add record ( dictionary type) to a file. This is the program that I'm working on: the program should create a text file, print the contents of the text file, read the file after it's been created, add a record and print the contents of the file, remove a record(s) from the specified file, write it again, read it again, print the contens of the new file. Here is what I have so far: import cPickle, shelve def write_file(): CIT101 = ["Academic Computer Skills"] CIT111 = ["Database Management"] CIT115 = ["Intro to Computer scince"] CIT127 = ["ACCESS"] CIT211 = ["Systems Analysis and Design"] CIT216 = ["Visual Basic"] CIT218 = ["Intermediate Visual Basic"] CIT234 = ["Decision Support Using Excel"] pickle_file = open("pickles1.dat","w") cPickle.dump(CIT101, pickle_file) cPickle.dump(CIT111, pickle_file) cPickle.dump(CIT115, pickle_file) cPickle.dump(CIT127, pickle_file) cPickle.dump(CIT211, pickle_file) cPickle.dump(CIT216, pickle_file) cPickle.dump(CIT218, pickle_file) cPickle.dump(CIT234, pickle_file) print "A file has been created and the required specifications have been added" pickle_file.close def read_file(): pickle_file = open("pickles1.dat","r") CIT101 = cPickle.load(pickle_file) CIT111 = cPickle.load(pickle_file) CIT115 = cPickle.load(pickle_file) CIT127 = cPickle.load(pickle_file) CIT211 = cPickle.load(pickle_file) CIT216 = cPickle.load(pickle_file) CIT218 = cPickle.load(pickle_file) CIT234 = cPickle.load(pickle_file) pickle_file.close() pickles = shelve.open("pickles2.dat") pickles["CIT101"] = ["Academic Computer Skills"] pickles["CIT111"] = ["Database Management"] pickles["CIT115"] = ["Intro to Computer scince"] pickles["CIT127"] = ["ACCESS"] pickles["CIT211"] = ["Systems Analysis and Design"] pickles["CIT216"] = ["Visual Basic"] pickles["CIT218"] = ["Intermediate Visual Basic"] pickles["CIT234"] = ["Decision Support Using Excel"] pickles.sync() for key in pickles.keys(): print key, "-", pickles[key] def dele_file(): word_dele = raw_input("Which record do u want to delete?: ") if word_dele in picles.keys(): del word_dele else: print "There is no such record in file pickles2.dat" pickles.close() def add_record(): CIT236 = ["SQL Programming"] CIT240 = ["Database programming"] pickle_file = open("pickles1.dat","a") cPickle.dump(CIT236, pickle_file) cPickle.dump(CIT240, pickle_file) print "New data was added to the file" pickle_file.close def display_instructions(): """Display the Main menue""" print \ """ Main Manue: 1. Exit 2. Create a new file and add specifications 3. (not working)Add more courses to the file 4. Read the file 5. (not working)Delete file """ # exit the program >>> 1 <<< def over_program(): """Exit the program""" print "Good Bye!" def main(): choice = None display_instructions() while choice != 1: choice = raw_input("\nChoice: ") if choice == "1": over_program() break elif choice == "2": write_file() elif choice == "3": add_to_file() elif choice == "4": read_file() elif choice == "5": delete_file() else: print "\nSorry, but", choice, "isn't a valid choice." main() raw_input("Press Enter Key to Exit.") __________________________________________________ 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/20051219/354b8632/attachment-0001.html From samrobertsmith at gmail.com Tue Dec 20 07:26:13 2005 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 19 Dec 2005 22:26:13 -0800 Subject: [Tutor] float question Message-ID: <1d987df30512192226m247df428kcf5196ddffe02400@mail.gmail.com> what does 2 mean in %2.4f ? From smiles at worksmail.net Tue Dec 20 06:44:57 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Mon, 19 Dec 2005 23:44:57 -0600 Subject: [Tutor] synchronized enumerate References: Message-ID: <024601c60530$48fa9a70$0b2c4fca@csmith> Kent wrote: | Take a look at this thread on c.l.py for some discussion and | possibilities. The part you | are interested in starts around message 14. | http://groups.google.com/group/comp.lang.python/browse_frm/thread/ab1658dca4023e2b?hl=en& | After looking at that I found something on python-dev that showed how to create an object that is sliceable but returns a slice object: sslice[::-1] --> slice(None, None, -1). It would be interesting if a single object could be sliced or accessed as a function, but I'm not sure that is possible. If it were, you could do: sslice(3) --> slice(None, 3, None) sslice[:3]--> slice(None, 3, None) Here's the code from python-dev: class MetaSlice(object): def __getitem__(cls, item): return item def __init__(self, *args, **kw): return super(MetaSlice,self).__init__(self, *args, **kw) class sslice(slice): __metaclass__=MetaSlice Anway, after seeing that, I decided to re-write the enumerate so it takes a slice argument and then I get the start and step values from that rather than having those passed in as arguments. I also initiated the discussion on python-dev (and they said that comp.lang.python was a better place for it) and c.l.p. The updated version of the enuerate can be found on compl.lang.python under "synchronized enumerate" at http://tinyurl.com/e35mh Thanks for the pointers and advice, Kent. /c From dyoo at hkn.eecs.berkeley.edu Tue Dec 20 09:38:11 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 20 Dec 2005 00:38:11 -0800 (PST) Subject: [Tutor] float question In-Reply-To: <1d987df30512192226m247df428kcf5196ddffe02400@mail.gmail.com> Message-ID: On Mon, 19 Dec 2005, linda.s wrote: > what does 2 mean in %2.4f ? Hello, It's a "minimal field width" modifier, according to: http://docs.python.org/lib/typesseq-strings.html Let's try experimenting with it. ###### >>> '%20f' % 3.14 ' 3.140000' >>> '%20.2f' % 3.14 ' 3.14' ###### Does this make sense? If you have more questions, please feel free to ask. From samrobertsmith at gmail.com Tue Dec 20 09:51:34 2005 From: samrobertsmith at gmail.com (linda.s) Date: Tue, 20 Dec 2005 00:51:34 -0800 Subject: [Tutor] float question In-Reply-To: References: <1d987df30512192226m247df428kcf5196ddffe02400@mail.gmail.com> Message-ID: <1d987df30512200051v24530b1ct96c0cf2188c63836@mail.gmail.com> On 12/20/05, Danny Yoo wrote: > > > On Mon, 19 Dec 2005, linda.s wrote: > > > what does 2 mean in %2.4f ? > > Hello, > > It's a "minimal field width" modifier, according to: > > http://docs.python.org/lib/typesseq-strings.html > > > Let's try experimenting with it. > > ###### > >>> '%20f' % 3.14 > ' 3.140000' > >>> '%20.2f' % 3.14 > ' 3.14' > ###### > > > Does this make sense? If you have more questions, please feel free to > ask. Danny, Thanks. Still confused. I changed the code a little. >>> '%3.2f' % 3.14 '3.14' >>> '%4.2f' % 3.14 '3.14' there is no difference in the above two codes. so what does 3 and 4 mean? From ajikoe at gmail.com Tue Dec 20 09:59:08 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 20 Dec 2005 09:59:08 +0100 Subject: [Tutor] float question In-Reply-To: <1d987df30512200051v24530b1ct96c0cf2188c63836@mail.gmail.com> References: <1d987df30512192226m247df428kcf5196ddffe02400@mail.gmail.com> <1d987df30512200051v24530b1ct96c0cf2188c63836@mail.gmail.com> Message-ID: Th format %x1.x2f where x1 is the total space and x2 is decimal digit place. If your data is longer than the specified x1 and x2. the data rules. Look at 3.14 takes 4 places total # 4 places rules >>> '%3.2f' % 3.14 '3.14' # perfect >>> '%4.2f' % 3.14 '3.14' # try this >>> '%5.2f' % 3.14 ' 3.14' Cheers, pujo On 12/20/05, linda.s wrote: > > On 12/20/05, Danny Yoo wrote: > > > > > > On Mon, 19 Dec 2005, linda.s wrote: > > > > > what does 2 mean in %2.4f ? > > > > Hello, > > > > It's a "minimal field width" modifier, according to: > > > > http://docs.python.org/lib/typesseq-strings.html > > > > > > Let's try experimenting with it. > > > > ###### > > >>> '%20f' % 3.14 > > ' 3.140000' > > >>> '%20.2f' % 3.14 > > ' 3.14' > > ###### > > > > > > Does this make sense? If you have more questions, please feel free to > > ask. > > Danny, > Thanks. Still confused. I changed the code a little. > >>> '%3.2f' % 3.14 > '3.14' > >>> '%4.2f' % 3.14 > '3.14' > there is no difference in the above two codes. so what does 3 and 4 mean? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051220/a13311c5/attachment.htm From alan.gauld at freenet.co.uk Tue Dec 20 13:32:00 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 20 Dec 2005 12:32:00 -0000 Subject: [Tutor] float question References: <1d987df30512192226m247df428kcf5196ddffe02400@mail.gmail.com> Message-ID: <001601c60561$607c6710$0a01a8c0@xp> > what does 2 mean in %2.4f ? In this case nothing because it will always be over-ridden by the 4. Basically the first number specifies the *minimum* number of characters output, ie 2 in this case. The second number specifies the number of decimal placess output, 4 in this case. Since 4 decimal places plus the decimal point is 5 characters minimum, then any value of the first digit less than 5 has no effect in this case. To be useful at all the first digit must be greater than the second digit plus one (for the decimal point). See the examples below: >>> '%2.4f' % 456.7 '456.7000' >>> '%2.4f' % 456.789 '456.7890' >>> '%5.4f' % 456.789 '456.7890' >>> '%8.4f' % 456.789 '456.7890' >>> '%9.4f' % 456.789 ' 456.7890' >>> Notice we always have 4 decimal digits even when we only supply 1. And there is no difference in the overall length until the last one with length 9, which is one greater than the length of the number expanded to four decimals. Does that help? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ps_python3 at yahoo.co.in Tue Dec 20 18:26:39 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Tue, 20 Dec 2005 17:26:39 +0000 (GMT) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <43989B77.8060107@tds.net> Message-ID: <20051220172639.12624.qmail@web8413.mail.in.yahoo.com> Dear Drs. Johnson and Yoo , for the last 1 week I have been working on parsing the elements from a bunch of XML files following your suggestions. until now I have been unsuccessul. I have no clue why i am failing. I have ~16K XML files. this data obtained from johns hopkins university (of course these are public data and is allowed to use for teaching and non-commercial purposes). from elementtree.ElementTree import ElementTree >>> mydata = ElementTree(file='00004.xml') >>> for process in mydata.findall('//biological_process'): print process.text >>> for proc in mydata.findall('functions'): print proc >>> I do not understand why I am unable to parse this file. I questioned if this file is not well structures (well formedness). I feel it is properly structured and yet it us unparsable. Would you please help me /guide me what the problem is. Apologies if i am completely ignoring somethings. PS: Attached is the XML file that I am using. --- Kent Johnson wrote: > ps python wrote: > > Kent and Dany, > > Thanks for your replies. > > > > Here fromstring() assuming that the input is in a > kind > > of text format. > > Right, that is for the sake of a simple example. > > > > what should be the case when I am reading files > > directly. > > > > I am using the following : > > > > from elementtree.ElementTree import ElementTree > > mydata = ElementTree(file='00001.xml') > > iter = root.getiterator() > > > > Here the whole XML document is loaded as element > tree > > and how should this iter into a format where I can > > apply findall() method. > > Call findall() directly on mydata, e.g. > for process in > mydata.findall('//biological_process'): > print process.text > > The path //biological_process means find any > biological_process element > at any depth from the root element. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Send instant messages to your online friends http://in.messenger.yahoo.com -------------- next part -------------- A non-text attachment was scrubbed... Name: 00004.xml Type: text/xml Size: 10855 bytes Desc: 1023413501-00004.xml Url : http://mail.python.org/pipermail/tutor/attachments/20051220/cfdc0134/00004.bin From kent37 at tds.net Tue Dec 20 18:58:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Dec 2005 12:58:40 -0500 Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <20051220172639.12624.qmail@web8413.mail.in.yahoo.com> References: <20051220172639.12624.qmail@web8413.mail.in.yahoo.com> Message-ID: <43A84650.809@tds.net> ps python wrote: > Dear Drs. Johnson and Yoo , > for the last 1 week I have been working on parsing > the elements from a bunch of XML files following your > suggestions. > > from elementtree.ElementTree import ElementTree > >>>>mydata = ElementTree(file='00004.xml') >>>>for process in > > mydata.findall('//biological_process'): > print process.text Looking at the data, neither nor elements directly contain text, they have children that contain text. Try print process.get('title').text to print the title. >>>>for proc in mydata.findall('functions'): > print proc I think you want findall('//functions') to find at any depth in the tree. If this doesn't work please show the results you get and tell us what you expect. Kent From ps_python3 at yahoo.co.in Tue Dec 20 19:33:17 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Tue, 20 Dec 2005 18:33:17 +0000 (GMT) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <43A84650.809@tds.net> Message-ID: <20051220183318.89719.qmail@web8414.mail.in.yahoo.com> Thank you for your email Dr. Johnson. I need to print : gene_symbol (from line ALDH3A1) entry_cdna (from line NM_000691.3) molecular_class (from line Enzyme:Dehydrogenase) title (from tags Catalytic activity) title (from tags section Metabolism) title (from tags section cytoplasm) This is how I tried: from elementtree.ElementTree import ElementTree mydata = ElementTree(file='00004.xml') >>> for process in mydata.findall('//biological_process'): print process.get('title').text >>> for m in mydata.findall('//functions'): print m.get('molecular_class').text >>> for m in mydata.findall('//functions'): print m.find('molecular_class').text.strip() >>> for process in mydata.findall('//biological_process'): print process.get('title').text >>> for m in mydata.findall('//functions'): print m.get('molecular_class').text >>> for m in mydata.findall('//functions'): print m.get('title').text.strip() >>> for m in mydata.findall('//biological_processes'): print m.get('title').text.strip() >>> Result: I get nothing. No error. I have no clue why it is not giving me the result. I also tried this alternate way: >>> strdata = """ Enzyme: Dehydrogenase Catalytic activity 0003824 Metabolism 0008152 Energy pathways 0006091 """ >>> from elementtree import ElementTree >>> tree = ElementTree.fromstring(strdata) >>> for m in tree.findall('//functions'): print m.find('molecular_class').text Traceback (most recent call last): File "", line 1, in -toplevel- for m in tree.findall('//functions'): File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py", line 352, in findall return ElementPath.findall(self, path) File "C:\Python23\Lib\site-packages\elementtree\ElementPath.py", line 195, in findall return _compile(path).findall(element) File "C:\Python23\Lib\site-packages\elementtree\ElementPath.py", line 173, in _compile p = Path(path) File "C:\Python23\Lib\site-packages\elementtree\ElementPath.py", line 74, in __init__ raise SyntaxError("cannot use absolute path on element") SyntaxError: cannot use absolute path on element >>> for m in tree.findall('functions'): print m.find('molecular_class').text >>> for m in tree.findall('functions'): print m.find('molecular_class').text.strip() >>> for m in tree.findall('functions'): print m.get('molecular_class').text Do you thing it is a problem with the XML files instead. Thank you for valuable suggestions. kind regards, M --- Kent Johnson wrote: > ps python wrote: > > Dear Drs. Johnson and Yoo , > > for the last 1 week I have been working on > parsing > > the elements from a bunch of XML files following > your > > suggestions. > > > > from elementtree.ElementTree import ElementTree > > > >>>>mydata = ElementTree(file='00004.xml') > >>>>for process in > > > > mydata.findall('//biological_process'): > > print process.text > > Looking at the data, neither > nor elements directly > contain text, they have children that contain text. > Try > print process.get('title').text > to print the title. > > >>>>for proc in mydata.findall('functions'): > > print proc > > I think you want findall('//functions') to find > at any depth in the tree. > > If this doesn't work please show the results you get > and tell us what you expect. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Send instant messages to your online friends http://in.messenger.yahoo.com From dyoo at hkn.eecs.berkeley.edu Tue Dec 20 21:42:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 20 Dec 2005 12:42:37 -0800 (PST) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <20051220183318.89719.qmail@web8414.mail.in.yahoo.com> Message-ID: > >>> for m in mydata.findall('//functions'): > print m.get('molecular_class').text > > >>> for m in mydata.findall('//functions'): > print m.find('molecular_class').text.strip() > > >>> for process in > mydata.findall('//biological_process'): > print process.get('title').text Hello, I believe we're running into XML namespace issues. If we look at all the tag names in the XML, we can see this: ###### >>> from elementtree import ElementTree >>> tree = ElementTree.parse(open('00004.xml')) >>> for element in tree.getroot()[0]: print element.tag ... {org:hprd:dtd:hprdr2}title {org:hprd:dtd:hprdr2}alt_title {org:hprd:dtd:hprdr2}alt_title {org:hprd:dtd:hprdr2}alt_title {org:hprd:dtd:hprdr2}alt_title {org:hprd:dtd:hprdr2}alt_title {org:hprd:dtd:hprdr2}omim {org:hprd:dtd:hprdr2}gene_symbol {org:hprd:dtd:hprdr2}gene_map_locus {org:hprd:dtd:hprdr2}seq_entry {org:hprd:dtd:hprdr2}molecular_weight {org:hprd:dtd:hprdr2}entry_sequence {org:hprd:dtd:hprdr2}protein_domain_architecture {org:hprd:dtd:hprdr2}expressions {org:hprd:dtd:hprdr2}functions {org:hprd:dtd:hprdr2}cellular_component {org:hprd:dtd:hprdr2}interactions {org:hprd:dtd:hprdr2}EXTERNAL_LINKS {org:hprd:dtd:hprdr2}author {org:hprd:dtd:hprdr2}last_updated ###### (I'm just doing a quick view of the toplevel elements in the tree.) As we can see, each element's tag is being prefixed with the namespace URL provided in the XML document. If we look in our XML document and search for the attribute 'xmlns', we'll see where this 'org:hprd:dtd:hprdr2' thing comes from. So we may need to prepend the namespace to get the proper terms: ###### >>> for process in tree.find("//{org:hprd:dtd:hprdr2}biological_processes"): ... print process.findtext("{org:hprd:dtd:hprdr2}title") ... Metabolism Energy pathways ###### To tell the truth, I don't quite understand how to work fluently with XML namespaces, so perhaps there's an easier way to do what you want. But the examples above should help you get started parsing all your Gene Ontology annotations. Good luck! From rich.424 at gmail.com Tue Dec 20 21:46:07 2005 From: rich.424 at gmail.com (Richard) Date: Tue, 20 Dec 2005 14:46:07 -0600 Subject: [Tutor] Learning books Message-ID: <43A86D8F.7000407@gmail.com> Afternoon all, My son asked me what books I would like for Christmas this year. So what would you recommend? I am a beginner here. Thanks Richard From dyoo at hkn.eecs.berkeley.edu Tue Dec 20 22:09:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 20 Dec 2005 13:09:17 -0800 (PST) Subject: [Tutor] question ! In-Reply-To: <20051219233131.23308.qmail@web54003.mail.yahoo.com> Message-ID: On Mon, 19 Dec 2005, Krava Magare wrote: > How can I remove and add record ( dictionary type) to a file. Hi Krava, Hmmmm... I have to admit that I don't understand the question yet. *grin* It looks like you're already pickling lists into your file. Picking dictionaries should be similar; are you running into problems with this, and if so, can you show us? Some more comments on your program: > def write_file(): > CIT101 = ["Academic Computer Skills"] > CIT111 = ["Database Management"] > CIT115 = ["Intro to Computer scince"] > CIT127 = ["ACCESS"] > CIT211 = ["Systems Analysis and Design"] > CIT216 = ["Visual Basic"] > CIT218 = ["Intermediate Visual Basic"] > CIT234 = ["Decision Support Using Excel"] This does feel like a place where a dictionary would come in very handy: The program uses names of the form 'CIT???' which I am assuming are academic class identifier name, and you're trying to store a relationship between those names and their descriptsions. That's a key-value thing. > pickle_file.close Don't forget that Python requires parentheses to make function calls fire off. The above call to close doesn't do anything yet: you need parens: pickle_file.close() > def dele_file(): > word_dele = raw_input("Which record do u want to delete?: ") > > if word_dele in picles.keys(): ^^^^^^ This is misspelled. Also, the del call on the next statement: > del word_dele is ineffective because it only drops the local name 'word_dele' and does not affect your pickle. You probably meant to write: del pickles[word_dele] instead. It looks like you're getting mixed up when you're using pickles. Mixing the 'pickle' and 'shelve' modules together is confusing and something you may want to avoid. If you're used to using dictionaries, I'd strongly recommend just sticking with the 'shelve' module for persistance: it provides a dictionary-like interface that is fairly straightforward. You can even say something like: pickles['academic_classes'] = {'CIT101' : 'Academic Computer Skills'} The values that we store in shelves can be Python data structures: they're not limited to numbers. If you have more questions, please feel free to ask. From nephish at xit.net Tue Dec 20 22:18:31 2005 From: nephish at xit.net (nephish) Date: Tue, 20 Dec 2005 15:18:31 -0600 Subject: [Tutor] Learning books In-Reply-To: <43A86D8F.7000407@gmail.com> References: <43A86D8F.7000407@gmail.com> Message-ID: <1135113511.32594.1.camel@localhost.localdomain> Learning Python by O'Reilly, got me started after realizing that Programming Python by O'Reilly was a tad over me head. i am new here too. On Tue, 2005-12-20 at 14:46 -0600, Richard wrote: > Afternoon all, My son asked me what books I would like for Christmas > this year. So what would you recommend? > > I am a beginner here. > > > Thanks > > > Richard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue Dec 20 22:17:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 20 Dec 2005 13:17:47 -0800 (PST) Subject: [Tutor] Learning books In-Reply-To: <43A86D8F.7000407@gmail.com> Message-ID: On Tue, 20 Dec 2005, Richard wrote: > Afternoon all, My son asked me what books I would like for Christmas > this year. So what would you recommend? Merry Chrismas! I'm partial to George Polya's "How to Solve It": http://www.math.utah.edu/~alfeld/math/polya.html It's not Python nor programming specific, but instead it's more of a general problem-solving-strategy book. I wish I had seen it earlier in life, so I'm hoping this recommendation is helpful. It's one of those books that's surprisingly applicable. I'm also very fond of "The Psycology Of Computer Programming": http://www.dorsethouse.com/books/psy.html which also talks about learning. Again, not Python specific in the slightest (some of the code in there is Cobol! *grin*), but very useful and fun to read. Good luck to you! From broek at cc.umanitoba.ca Tue Dec 20 22:18:46 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 20 Dec 2005 15:18:46 -0600 Subject: [Tutor] question ! In-Reply-To: <20051219233131.23308.qmail@web54003.mail.yahoo.com> References: <20051219233131.23308.qmail@web54003.mail.yahoo.com> Message-ID: <43A87536.2030007@cc.umanitoba.ca> Krava Magare said unto the world upon 2005-12-19 17:31: > How can I remove and add record ( dictionary type) to a file. This is the program that I'm working on: the program should create a text file, print the contents of the text file, read the file after it's been created, add a record and print the contents of the file, remove a record(s) from the specified file, write it again, read it again, print the contens of the new file. > Here is what I have so far: Hi, I see that you did follow up to comp.lang.python with code and then found your way here. Both are better than how you started :-) But you really might want to read to understand why you've had no replies. This list (tutor) is far less strict about the etiquette, but the advice is still good. (Keep in mind it is a busy time of year, too :-) Looking at what you have: > import cPickle, shelve > def write_file(): > CIT101 = ["Academic Computer Skills"] > CIT234 = ["Decision Support Using Excel"] > pickle_file = open("pickles1.dat","w") > > cPickle.dump(CIT101, pickle_file) > cPickle.dump(CIT234, pickle_file) > print "A file has been created and the required specifications have been added" > pickle_file.close I suspect you don't really understand what pickle does. The task you describe is to create text files, whereas pickle and cpickle are used to save state of Python objects. They produce just barely human readable files. For instance: >>> pickled = open('pick', 'w') >>> pickle.dump("This is a string", pickled) >>> pickle.dump(["This is a list containing a string"], pickled) >>> pickled.close() produces this file: S'This is a string' p0 .(lp0 S'This is a list containing a string' p1 a. where the strings are still there, but surrounded by 'gunk' that lets the pickle modules reconstruct what was pickled. In a more complicated case, pickled files are not at all readable. H here is a pickle of an instance of a simple class: ccopy_reg _reconstructor p0 (c__main__ A p1 c__builtin__ object p2 Ntp3 Rp4 (dp5 S'a' p6 I1 sS'c' p7 I3 sS'b' p8 I2 sb.ccopy_reg _reconstructor p0 (c__main__ A p1 c__builtin__ object p2 Ntp3 Rp4 (dp5 S'a' p6 I4 sS'c' p7 I6 sS'b' p8 I5 sb. Definitely not the sort of thing that is useful to a human! I think you should consider switching tactics, and examine file() and the read, readlines, write, and writelines methods of file objects. HTH, Brian vdB From srini_iyyer_bio at yahoo.com Tue Dec 20 22:19:47 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue, 20 Dec 2005 13:19:47 -0800 (PST) Subject: [Tutor] Learning books In-Reply-To: <43A86D8F.7000407@gmail.com> Message-ID: <20051220211947.35193.qmail@web31608.mail.mud.yahoo.com> 1. Learn to Program Using Python by Alan Gauld (Stage 1) 2. Learning Python by Mark Lutz and David Ascher (Stage 2) 3. If u are serious in learning python - my sincere advise : STICK TO THIS LIST. You can never find good teachers with lots of patience and with real appetite to teach elesewhere. To name some excellent teachers here on this list: Kent, Danny, Alan (Alan gauld himself). There are many more and I do not remember their names. I thank them a lot every time I try to solve my problems. Without this list my Ph.D. would not have been possible and I learned many thing in just 5 months. So, these 3 sources are enough to help you carve a good python programmer inside you. Good luck. --- Richard wrote: > Afternoon all, My son asked me what books I would > like for Christmas > this year. So what would you recommend? > > I am a beginner here. > > > Thanks > > > Richard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From falcon3166 at hotmail.com Tue Dec 20 22:48:40 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 20 Dec 2005 14:48:40 -0700 Subject: [Tutor] How do I fix this IndexError? Message-ID: Here is the error: The Currency Exchange Program By Nathan Pinno Traceback (most recent call last): File "D:\Python24\exchange.py", line 28, in -toplevel- exch = pickle.load(store) File "D:\Python24\lib\pickle.py", line 1390, in load return Unpickler(file).load() File "D:\Python24\lib\pickle.py", line 872, in load dispatch[key](self) File "D:\Python24\lib\pickle.py", line 1207, in load_appends mark = self.marker() File "D:\Python24\lib\pickle.py", line 888, in marker while stack[k] is not mark: k = k-1 IndexError: list index out of range and here is the relevant code: [code] import pickle rates = {'can_us' : 0.80276, 'us_can' : 1.245702, 'can_euro' : 1.488707, 'euro_can' : 0.671724} def menu(): print "1. Change Canadian currency into American." print "2. Change American currency into Canadian." print "3. Change Canadian currency into Euros." print "4. Change Euros into Canadian currency." print "5. Update exchange rates." print "9. Save and Exit" def exchange_update(): print "1. Update Canadian to US rate." print "2. Update US to Canadian rate." print "3. Update Canadian to Euro rate." print "4. Update Euro to Canadian update." print "5. Main menu" def menu_choice(): return int(raw_input("Which option? ")) print "The Currency Exchange Program" print "By Nathan Pinno" store = open('exch.txt', 'rb')#load exch = pickle.load(store) store.close() while 1: menu() menu_option = menu_choice() if menu_option == 1: can = float(raw_input("Canadian $")) print "US $",can*rates['can_us'] elif menu_option == 2: us = float(raw_input("US $")) print "CAN $",us*rates['us_can'] elif menu_option == 3: can = float(raw_input("CAN $")) print "Euros",can*rates['can_euro'] elif menu_option == 4: euro = float(raw_input("Euros")) print "CAN $",euro*rates['euro_can'] elif menu_option == 5: while 1: exchange_update() sub = menu_choice() if sub == 1: new_can = float(raw_input("New CAN-US Exchange rate: ")) rates['can_us'] = new_can print "Exchange rate successfully updated!" elif sub == 2: new_us = float(raw_input("New US-CAN Exchange rate: ")) rates['us_can'] = new_us print "Exchange rate successfully updated!" elif sub == 3: new_cxr = float(raw_input("New CAN-Euro Exchange rate: ")) rates['can_euro'] = new_cxr print "Exchange rate successfully updated!" elif sub == 4: new_euro = float(raw_input("New Euro-CAN Exchange rate: ")) rates['euro_can'] = new_euro print "Exchange rate successfully updated!" elif sub == 5: break elif menu_option == 9: store = open("exch.txt", 'wb') #save pickle.dump(exch, store) store.close() break print "Goodbye." [/code] How do I fix the IndexError? Thanks, Nathan Pinno, MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051220/5ce4be69/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051220/5ce4be69/attachment-0001.gif From nequeo at gmail.com Tue Dec 20 23:37:33 2005 From: nequeo at gmail.com (Simon Gerber) Date: Wed, 21 Dec 2005 09:37:33 +1100 Subject: [Tutor] How do I fix this IndexError? In-Reply-To: References: Message-ID: <667ca7b60512201437l14600a93h@mail.gmail.com> Hi Nathan, > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 28, in -toplevel- > exch = pickle.load(store) > File "D:\Python24\lib\pickle.py", line 1390, in load > return Unpickler(file).load() > File "D:\Python24\lib\pickle.py", line 872, in load > dispatch[key](self) > File "D:\Python24\lib\pickle.py", line 1207, in load_appends > mark = self.marker() > File "D:\Python24\lib\pickle.py", line 888, in marker > while stack[k] is not mark: k = k-1 > IndexError: list index out of range As you can see from the traceback, the error is occuring entirely in the pickle module. Which probably means your pickle file is corrupted. Or that you're trying to load your old exch.txt file which wasn't in pickle format. Simply delete 'exch.txt' and try again. Although you'll notice your program still doesn't work, because it tries to load 'exch.txt' even if there isn't an exch.txt. You should consider rewriting your program so that it checks to see if an 'exch.txt' file exists. If it does, it unpickles it. If not, it uses your default 'rates' variables. Speaking of rates, you have two typos in your code which you also need to fix. > exch = pickle.load(store) Should be rates = pick.load(store) And similarly, > pickle.dump(exch, store) pickle.dump(rates, store) Otherwise you're not saving or loading anyhing! Cheers, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From alan.gauld at freenet.co.uk Tue Dec 20 23:35:55 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 20 Dec 2005 22:35:55 -0000 Subject: [Tutor] Learning books References: <43A86D8F.7000407@gmail.com> Message-ID: <003201c605b5$be239420$0a01a8c0@xp> > Afternoon all, My son asked me what books I would like for Christmas this > year. So what would you recommend? I love these questions! :-) > I am a beginner here. The question you need to answer is what do you want to get out of the book? For example you could get a book that teaches you the basics of programming, (and from this list probably doing so in Python). But after you understand it you probably won't read it again. My book, Learning Python and a few others fit in here. Alternatively you could get a reference book that will be used constantly *after* you learn but will be of limited use until then. Programming Python, Python Prog on Win32, Python in a Nutshell etc are good examples here Or you might pick a specific subject area(Web, Databases, GUI, Games) and get a book that focuses on that area. ie. A specialised tutorial and reference. Text Processing in Python, Python & Tkinter Programming, etc are examples of this genre Finally you might get a more general computer science type book that applies to all programming languages. Code Complete, Programming Pearls, The Pragmatic Programmer and Structure and Interpretation of Computer Programs are all examples here. Or of course you might just opt for a novel, put your feet up and relax for a few hours! :-) FWIW The books I actually use most (for Python programming) are: Python in a Nutshell Python Programming on Win32 Tcl/Tk in a Nutshell (for Tkinter/Tix stuff) Using C on the Unix System (for low level OS stuff) [This is now superceded by Unix Systems Programming for SVR4 but I prefer the older books shorter explanations!] Java in a Nutshell (for Jython) Programming Pearls HTML The Definitive Guide And for general computing: Code Complete Programming Pearls Software Engineering, A Practitioners Approach(2nd and 5th editions) OO Design & Analysis(1st edition) by Grady Booch Oracle 8 the Complete Reference (for SQL/Database topics) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Dec 20 23:41:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 20 Dec 2005 22:41:56 -0000 Subject: [Tutor] How do I fix this IndexError? References: Message-ID: <003801c605b6$94f579a0$0a01a8c0@xp> Nathan, I haven't read your code in detail but from the error message: > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 28, in -toplevel- > exch = pickle.load(store) > File "D:\Python24\lib\pickle.py", line 1390, in load > return Unpickler(file).load() > File "D:\Python24\lib\pickle.py", line 872, in load > dispatch[key](self) > File "D:\Python24\lib\pickle.py", line 1207, in load_appends > mark = self.marker() > File "D:\Python24\lib\pickle.py", line 888, in marker > while stack[k] is not mark: k = k-1 > IndexError: list index out of range The exception is happeming deep inside the picklle library so that usually indicates that you are not calling pickle properly - maybe a wrong type of data in the argument? > store = open('exch.txt', 'rb')#load > exch = pickle.load(store) Have you checked that the exch.txt file is in fact a valid pickle file? And that a readable binary file is what pickle.load() expects - from memory I think it is - so I'd check that exch.txt is a valid pickle file. And check that its the right exch.txt - are there two files of that name that you might be picking up the wrong name for example? Sorry, no definitive answer just some ideas for you to check out. Alan G. From falcon3166 at hotmail.com Tue Dec 20 23:47:05 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 20 Dec 2005 15:47:05 -0700 Subject: [Tutor] How do I fix this IndexError? In-Reply-To: <667ca7b60512201437l14600a93h@mail.gmail.com> Message-ID: Simon and all, What would you recommend? I don't know what I should code, because I haven't coded anything that loads a file. Thanks, Nathan Pinno MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -----Original Message----- From: Simon Gerber [mailto:nequeo at gmail.com] Sent: December 20, 2005 3:38 PM To: Nathan Pinno Cc: tutor at python.org Subject: Re: [Tutor] How do I fix this IndexError? Hi Nathan, > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 28, in -toplevel- > exch = pickle.load(store) > File "D:\Python24\lib\pickle.py", line 1390, in load > return Unpickler(file).load() > File "D:\Python24\lib\pickle.py", line 872, in load > dispatch[key](self) > File "D:\Python24\lib\pickle.py", line 1207, in load_appends > mark = self.marker() > File "D:\Python24\lib\pickle.py", line 888, in marker > while stack[k] is not mark: k = k-1 > IndexError: list index out of range As you can see from the traceback, the error is occuring entirely in the pickle module. Which probably means your pickle file is corrupted. Or that you're trying to load your old exch.txt file which wasn't in pickle format. Simply delete 'exch.txt' and try again. Although you'll notice your program still doesn't work, because it tries to load 'exch.txt' even if there isn't an exch.txt. You should consider rewriting your program so that it checks to see if an 'exch.txt' file exists. If it does, it unpickles it. If not, it uses your default 'rates' variables. Speaking of rates, you have two typos in your code which you also need to fix. > exch = pickle.load(store) Should be rates = pick.load(store) And similarly, > pickle.dump(exch, store) pickle.dump(rates, store) Otherwise you're not saving or loading anyhing! Cheers, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From nequeo at gmail.com Tue Dec 20 23:55:14 2005 From: nequeo at gmail.com (Simon Gerber) Date: Wed, 21 Dec 2005 09:55:14 +1100 Subject: [Tutor] How do I fix this IndexError? In-Reply-To: References: <667ca7b60512201437l14600a93h@mail.gmail.com> Message-ID: <667ca7b60512201455ye8d02bfg@mail.gmail.com> Hi Nathan, I've attached a crude hack that fixes the problem. It should give you an idea of how to proceed. I've put comments next to the things I've changed. Bear in mind I'm hardly more than a beginner myself, so there are definitely better ways to do this. But it's somewhere to start, anyway. Cheers! [code] import pickle, os #LOAD THE OS MODULE def menu(): print "1. Change Canadian currency into American." print "2. Change American currency into Canadian." print "3. Change Canadian currency into Euros." print "4. Change Euros into Canadian currency." print "5. Update exchange rates." print "9. Save and Exit" def exchange_update(): print "1. Update Canadian to US rate." print "2. Update US to Canadian rate." print "3. Update Canadian to Euro rate." print "4. Update Euro to Canadian update." print "5. Main menu" def menu_choice(): return int(raw_input("Which option? ")) print "The Currency Exchange Program" print "By Nathan Pinno" if os.path.exists('exch.txt'): # Check to see if 'exch.txt' exists store = open('exch.txt', 'rb') # Only open the file if it exists rates = pickle.load(store) # Save as 'rates', not 'exch' store.close() else: # If there's no exch.txt file, use these default rates. rates = {'can_us' : 0.80276, 'us_can' : 1.245702, 'can_euro' : 1.488707, 'euro_can' : 0.671724} while 1: menu() menu_option = menu_choice() if menu_option == 1: can = float(raw_input("Canadian $")) print "US $",can*rates['can_us'] elif menu_option == 2: us = float(raw_input("US $")) print "CAN $",us*rates['us_can'] elif menu_option == 3: can = float(raw_input("CAN $")) print "Euros",can*rates['can_euro'] elif menu_option == 4: euro = float(raw_input("Euros")) print "CAN $",euro*rates['euro_can'] elif menu_option == 5: while 1: exchange_update() sub = menu_choice() if sub == 1: new_can = float(raw_input("New CAN-US Exchange rate: ")) rates['can_us'] = new_can print "Exchange rate successfully updated!" elif sub == 2: new_us = float(raw_input("New US-CAN Exchange rate: ")) rates['us_can'] = new_us print "Exchange rate successfully updated!" elif sub == 3: new_cxr = float(raw_input("New CAN-Euro Exchange rate: ")) rates['can_euro'] = new_cxr print "Exchange rate successfully updated!" elif sub == 4: new_euro = float(raw_input("New Euro-CAN Exchange rate: ")) rates['euro_can'] = new_euro print "Exchange rate successfully updated!" elif sub == 5: break elif menu_option == 9: store = open("exch.txt", 'wb') #save pickle.dump(rates, store) # Save 'rates' variable, not 'exch'. store.close() break print "Goodbye." -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From falcon3166 at hotmail.com Wed Dec 21 00:10:04 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 20 Dec 2005 16:10:04 -0700 Subject: [Tutor] How do I fix this IndexError? In-Reply-To: <667ca7b60512201455ye8d02bfg@mail.gmail.com> Message-ID: Thanks Simon! It worked like a charm! All I have to do now is change it into GUI format, and then use py2exe to create an executable file. Thanks for all the help! Nathan Pinno MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -----Original Message----- From: Simon Gerber [mailto:nequeo at gmail.com] Sent: December 20, 2005 3:55 PM To: Nathan Pinno Cc: tutor at python.org Subject: Re: [Tutor] How do I fix this IndexError? Hi Nathan, I've attached a crude hack that fixes the problem. It should give you an idea of how to proceed. I've put comments next to the things I've changed. Bear in mind I'm hardly more than a beginner myself, so there are definitely better ways to do this. But it's somewhere to start, anyway. Cheers! [code] import pickle, os #LOAD THE OS MODULE def menu(): print "1. Change Canadian currency into American." print "2. Change American currency into Canadian." print "3. Change Canadian currency into Euros." print "4. Change Euros into Canadian currency." print "5. Update exchange rates." print "9. Save and Exit" def exchange_update(): print "1. Update Canadian to US rate." print "2. Update US to Canadian rate." print "3. Update Canadian to Euro rate." print "4. Update Euro to Canadian update." print "5. Main menu" def menu_choice(): return int(raw_input("Which option? ")) print "The Currency Exchange Program" print "By Nathan Pinno" if os.path.exists('exch.txt'): # Check to see if 'exch.txt' exists store = open('exch.txt', 'rb') # Only open the file if it exists rates = pickle.load(store) # Save as 'rates', not 'exch' store.close() else: # If there's no exch.txt file, use these default rates. rates = {'can_us' : 0.80276, 'us_can' : 1.245702, 'can_euro' : 1.488707, 'euro_can' : 0.671724} while 1: menu() menu_option = menu_choice() if menu_option == 1: can = float(raw_input("Canadian $")) print "US $",can*rates['can_us'] elif menu_option == 2: us = float(raw_input("US $")) print "CAN $",us*rates['us_can'] elif menu_option == 3: can = float(raw_input("CAN $")) print "Euros",can*rates['can_euro'] elif menu_option == 4: euro = float(raw_input("Euros")) print "CAN $",euro*rates['euro_can'] elif menu_option == 5: while 1: exchange_update() sub = menu_choice() if sub == 1: new_can = float(raw_input("New CAN-US Exchange rate: ")) rates['can_us'] = new_can print "Exchange rate successfully updated!" elif sub == 2: new_us = float(raw_input("New US-CAN Exchange rate: ")) rates['us_can'] = new_us print "Exchange rate successfully updated!" elif sub == 3: new_cxr = float(raw_input("New CAN-Euro Exchange rate: ")) rates['can_euro'] = new_cxr print "Exchange rate successfully updated!" elif sub == 4: new_euro = float(raw_input("New Euro-CAN Exchange rate: ")) rates['euro_can'] = new_euro print "Exchange rate successfully updated!" elif sub == 5: break elif menu_option == 9: store = open("exch.txt", 'wb') #save pickle.dump(rates, store) # Save 'rates' variable, not 'exch'. store.close() break print "Goodbye." -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From kent37 at tds.net Wed Dec 21 01:47:19 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Dec 2005 19:47:19 -0500 Subject: [Tutor] Learning books In-Reply-To: <43A86D8F.7000407@gmail.com> References: <43A86D8F.7000407@gmail.com> Message-ID: <43A8A617.6090504@tds.net> Richard wrote: > Afternoon all, My son asked me what books I would like for Christmas > this year. So what would you recommend? I have started a book list on my web site. http://personalpages.tds.net/~kent37/BookList.html Kent From ps_python3 at yahoo.co.in Wed Dec 21 06:05:40 2005 From: ps_python3 at yahoo.co.in (ps python) Date: Wed, 21 Dec 2005 05:05:40 +0000 (GMT) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: Message-ID: <20051221050540.19818.qmail@web8412.mail.in.yahoo.com> Dear drs. Yoo and johnson, Thank you very much for your help. I successully parsed my GO annotation from all 16,000 files. thanks again for your kind help --- Danny Yoo wrote: > > > >>> for m in mydata.findall('//functions'): > > print m.get('molecular_class').text > > > > >>> for m in mydata.findall('//functions'): > > print m.find('molecular_class').text.strip() > > > > >>> for process in > > mydata.findall('//biological_process'): > > print process.get('title').text > > > Hello, > > I believe we're running into XML namespace issues. > If we look at all the > tag names in the XML, we can see this: > > ###### > >>> from elementtree import ElementTree > >>> tree = ElementTree.parse(open('00004.xml')) > >>> for element in tree.getroot()[0]: print > element.tag > ... > {org:hprd:dtd:hprdr2}title > {org:hprd:dtd:hprdr2}alt_title > {org:hprd:dtd:hprdr2}alt_title > {org:hprd:dtd:hprdr2}alt_title > {org:hprd:dtd:hprdr2}alt_title > {org:hprd:dtd:hprdr2}alt_title > {org:hprd:dtd:hprdr2}omim > {org:hprd:dtd:hprdr2}gene_symbol > {org:hprd:dtd:hprdr2}gene_map_locus > {org:hprd:dtd:hprdr2}seq_entry > {org:hprd:dtd:hprdr2}molecular_weight > {org:hprd:dtd:hprdr2}entry_sequence > {org:hprd:dtd:hprdr2}protein_domain_architecture > {org:hprd:dtd:hprdr2}expressions > {org:hprd:dtd:hprdr2}functions > {org:hprd:dtd:hprdr2}cellular_component > {org:hprd:dtd:hprdr2}interactions > {org:hprd:dtd:hprdr2}EXTERNAL_LINKS > {org:hprd:dtd:hprdr2}author > {org:hprd:dtd:hprdr2}last_updated > ###### > > (I'm just doing a quick view of the toplevel > elements in the tree.) > > As we can see, each element's tag is being prefixed > with the namespace URL > provided in the XML document. If we look in our XML > document and search > for the attribute 'xmlns', we'll see where this > 'org:hprd:dtd:hprdr2' > thing comes from. > > > So we may need to prepend the namespace to get the > proper terms: > > ###### > >>> for process in > tree.find("//{org:hprd:dtd:hprdr2}biological_processes"): > ... print > process.findtext("{org:hprd:dtd:hprdr2}title") > ... > Metabolism > Energy pathways > ###### > > > To tell the truth, I don't quite understand how to > work fluently with XML > namespaces, so perhaps there's an easier way to do > what you want. But the > examples above should help you get started parsing > all your Gene Ontology > annotations. > > > > Good luck! > > Send instant messages to your online friends http://in.messenger.yahoo.com From shivayogiks at gmail.com Wed Dec 21 11:13:25 2005 From: shivayogiks at gmail.com (shivayogi kumbar) Date: Wed, 21 Dec 2005 02:13:25 -0800 Subject: [Tutor] Differnce between java and python Message-ID: <6434a4300512210213g30219090v80b6224a08753f0@mail.gmail.com> sir plz tell me the main differnces between java and python?And What are the advantages of python? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051221/c829ac77/attachment.html From ajikoe at gmail.com Wed Dec 21 11:34:16 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 21 Dec 2005 11:34:16 +0100 Subject: [Tutor] Differnce between java and python In-Reply-To: <6434a4300512210213g30219090v80b6224a08753f0@mail.gmail.com> References: <6434a4300512210213g30219090v80b6224a08753f0@mail.gmail.com> Message-ID: Hi, you can check this website: http://www.ferg.org/projects/python_java_side-by-side.html above all. python is very compact, clear language. I did some code using C# for 1 year, and when I move to python I can rewrite it even more in about 3 months. My code becomes clearer than ever before.... Cheers, pujo On 12/21/05, shivayogi kumbar wrote: > > sir plz tell me the main differnces between java and python?And What are > the advantages of 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/20051221/702bb7c5/attachment.htm From kent37 at tds.net Wed Dec 21 12:04:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Dec 2005 06:04:00 -0500 Subject: [Tutor] Differnce between java and python In-Reply-To: References: <6434a4300512210213g30219090v80b6224a08753f0@mail.gmail.com> Message-ID: <43A936A0.4000302@tds.net> Pujo Aji wrote: > Hi, > > you can check this website: > http://www.ferg.org/projects/python_java_side-by-side.html Don't miss the links on that site, either. Compared to Java, Python is compact, expressive and lightweight. It is dynamically typed with first-class functions and far better built-in support for simple data structures, introspection and metaprogramming. After writing Python for a while, Java seems full of unneccessary restrictions and artificial limitations. In comparison, Python stays out of the way. Here are a few more links: My own comparison with some details: http://www.pycs.net/users/0000323/stories/18.html Python is not Java: http://dirtsimple.org/2004/12/python-is-not-java.html Java is not Python, either: http://dirtsimple.org/2004/12/java-is-not-python-either.html Kent From johan at accesstel.co.za Wed Dec 21 14:37:39 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 21 Dec 2005 15:37:39 +0200 Subject: [Tutor] Pygame mailing list info needed Message-ID: <43A95AA3.6070909@accesstel.co.za> Hi, I subscribed to the pygame-users mailing list through majordomo at ......., but I don't know where to send the mail too so that everybody can see it. Any suggestion on how to use that mailing list? Thanks, Johan From alan.gauld at freenet.co.uk Wed Dec 21 16:47:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 21 Dec 2005 15:47:20 -0000 Subject: [Tutor] Differnce between java and python References: <6434a4300512210213g30219090v80b6224a08753f0@mail.gmail.com> Message-ID: <000b01c60645$d49459c0$0b01a8c0@xp> > sir plz tell me the main differnces between java and python? What kind of information do you want? Differences in syntax?, architecture? resource usage? They are completely different programming languages. Do you have a programming background? If so which languages do you know? That way we can compare with what you do know. If you don't have a programming background forget Java and learn Python. You can learn Java later if you like but it will be easier to start from a knowledge of Python. > And What are the advantages of python? Python is easier to learn Python produces more functionality for fewer lines of code Python is more forgiving And dont you want to know the advantages of Java? Java is slightly faster (nowadays, it didn't use to be) Java is easier to deploy because the JVM tends to be everywhere There are more jobs for Java programmers Thats a start... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From murtog at gmail.com Wed Dec 21 17:05:54 2005 From: murtog at gmail.com (Murtog) Date: Wed, 21 Dec 2005 12:05:54 -0400 Subject: [Tutor] Differnce between java and python In-Reply-To: <000b01c60645$d49459c0$0b01a8c0@xp> References: <6434a4300512210213g30219090v80b6224a08753f0@mail.gmail.com> <000b01c60645$d49459c0$0b01a8c0@xp> Message-ID: A good point is that Python is fun to program with. But the jobs point is important too. In my country 80% of the jobs for informatic?s area is to C#, VB, Delphi and Java(50% of the 80%) programmers. So, having a job with Python is hard. :( Cheers! =] On 12/21/05, Alan Gauld wrote: > > > sir plz tell me the main differnces between java and python? > > What kind of information do you want? Differences in syntax?, > architecture? resource usage? They are completely different > programming languages. Do you have a programming background? > If so which languages do you know? That way we can compare > with what you do know. > > If you don't have a programming background forget Java and learn > Python. You can learn Java later if you like but it will be easier to > start from a knowledge of Python. > > > And What are the advantages of python? > > Python is easier to learn > Python produces more functionality for fewer lines of code > Python is more forgiving > > And dont you want to know the advantages of Java? > > Java is slightly faster (nowadays, it didn't use to be) > Java is easier to deploy because the JVM tends to be everywhere > There are more jobs for Java programmers > > Thats a start... > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- O_o Murtog -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051221/a6b950a3/attachment.htm From pcarey at lexmark.com Wed Dec 21 17:46:15 2005 From: pcarey at lexmark.com (pcarey@lexmark.com) Date: Wed, 21 Dec 2005 11:46:15 -0500 Subject: [Tutor] Differnce between java and python Message-ID: Mr Gauld wrote: >Python is more forgiving Could you elaborate on this feature? Thanks, Pete From 3dbernard at gmail.com Wed Dec 21 18:45:01 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 21 Dec 2005 12:45:01 -0500 Subject: [Tutor] Performance of Python loops vs multiple MySQL queries Message-ID: <61d0e2b40512210945q57bb674ew503a1e2ff8b50d48@mail.gmail.com> Hello, Finally, after a year and a half of learning and messing around with Python, I'm writing THE code that made learn Python in the first place: a render farm client management software. I may have several questions regarding this, but for now I only have one. The script I'm writing is the client script that runs on render nodes. It checks a database for a job to do, then based on some factors like pooling, priority, age and stuff, will determine what job it can work on. The client connects, performs evaluation of jobs, get a job, update the database, and starts the actual job. Now, there might be up to 80 clients connecting to the database at any moment to get a job to do. So understandably, I want the "evaluation" step to be as fast as possible. Right now, my script works this way: it selects a bunch of rows based on a few factors. Then when this is done, everything else is done in the script, that is, doesn't rely on a MySQL query. The script builds a variety of sorted lists and dictionaries, to ultimately end up with a single job. So I am wondering this: in case there are only a handful of jobs to evaluate, then I understand the script may run fast. But if it has to build lists and dictionary on thousands of jobs, then I'm affrait that it might become slower than simply running a series of queries to the database using various ordering schemes. Any advice on this? Here is a link to the current code (that build lists and dictionaries). Keep in mind it's in early alpha stage. The section to look for is the function getJob(), that starts at line 776. I have changed the extention to txt for security purposes. http://www.bernardlebel.com/scripts/nonxsi/farmclient_2.0_beta03.txt Thanks in advance Bernard From cspears2002 at yahoo.com Wed Dec 21 19:22:40 2005 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 21 Dec 2005 10:22:40 -0800 (PST) Subject: [Tutor] import a module Message-ID: <20051221182240.78346.qmail@web51607.mail.yahoo.com> I'm feeling a little foolish because I cannot do this. I created a module called functions (Clever, huh?) at this path: C:\Documents and Settings\Christopher Spears\My Documents\programming\PythonScripts\Part4\Ex07\functions.py I want to launch IDLE, import the file, and use it. I tried: import "C:\Documents and Settings\Christopher Spears\My Documents\programming\PythonScripts\Part4\Ex07\functions.py" However, I keep getting a syntax error on the last double quote. According to the docs, I might be able to get Python to find this file by modifying sys.path. I would prefer not do that because this is just an exercise out of the Learning Python book. Thanks! From kent37 at tds.net Wed Dec 21 19:50:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Dec 2005 13:50:28 -0500 Subject: [Tutor] import a module In-Reply-To: <20051221182240.78346.qmail@web51607.mail.yahoo.com> References: <20051221182240.78346.qmail@web51607.mail.yahoo.com> Message-ID: <43A9A3F4.90901@tds.net> Christopher Spears wrote: > I'm feeling a little foolish because I cannot do this. > I created a module called functions (Clever, huh?) at > this path: > > C:\Documents and Settings\Christopher Spears\My > Documents\programming\PythonScripts\Part4\Ex07\functions.py > > I want to launch IDLE, import the file, and use it. I > tried: > > import "C:\Documents and Settings\Christopher > Spears\My > Documents\programming\PythonScripts\Part4\Ex07\functions.py" > > However, I keep getting a syntax error on the last > double quote. According to the docs, I might be able > to get Python to find this file by modifying sys.path. > I would prefer not do that because this is just an > exercise out of the Learning Python book. You can't give a full path to the import statement. The module to be imported has to be somewhere in sys.path. Two simple possibilities: - Open a command line window to C:\Documents and Settings\Christopher Spears\My Documents\programming\PythonScripts\Part4\Ex07\. Run Python from the command line. You should be able to import functions because the current working directory is part of sys.path. - Put functions.py in C:\Python24\Lib\site-packages\. This directory is also part of sys.path. - (THREE possibilities...) Modify sys.path. You can do this at runtime, just import sys sys.path.append(r'C:\Documents and Settings\Christopher Spears\My Documents\programming\PythonScripts\Part4\Ex07\') import functions Kent From johan at accesstel.co.za Wed Dec 21 21:07:48 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 21 Dec 2005 22:07:48 +0200 Subject: [Tutor] Print random letters Message-ID: <43A9B614.4040101@accesstel.co.za> Hi all, I want to print out random letters from A - Z. I know how to do this with numbers, but don't know with letters. Any ideas wil be greatly appreciated. Johan From kent37 at tds.net Wed Dec 21 21:12:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Dec 2005 15:12:52 -0500 Subject: [Tutor] Print random letters In-Reply-To: <43A9B614.4040101@accesstel.co.za> References: <43A9B614.4040101@accesstel.co.za> Message-ID: <43A9B744.40803@tds.net> Johan Geldenhuys wrote: > Hi all, > > I want to print out random letters from A - Z. I know how to do this > with numbers, but don't know with letters. > > Any ideas wil be greatly appreciated. Take a look at random.choice() or possibly random.shuffle() or random.sample(). And remember that a string is a kind of sequence. Kent From davholla2002 at yahoo.co.uk Wed Dec 21 21:45:01 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 21 Dec 2005 20:45:01 +0000 (GMT) Subject: [Tutor] Books Message-ID: <20051221204501.85397.qmail@web25903.mail.ukl.yahoo.com> I would recommend python programming for the absolute beginner. ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From carroll at tjc.com Wed Dec 21 21:57:57 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed, 21 Dec 2005 12:57:57 -0800 (PST) Subject: [Tutor] Print random letters In-Reply-To: <43A9B614.4040101@accesstel.co.za> Message-ID: On Wed, 21 Dec 2005, Johan Geldenhuys wrote: > I want to print out random letters from A - Z. I know how to do this > with numbers, but don't know with letters. >>> import string >>> import random >>> string.uppercase[random.randint(0,len(string.uppercase)-1)] 'K' >>> >>> string.uppercase[random.randint(0,len(string.uppercase)-1)] 'W' >>> string.uppercase[random.randint(0,len(string.uppercase)-1)] 'J' >>> string.uppercase[random.randint(0,len(string.uppercase)-1)] 'M' >>> string.uppercase[random.randint(0,len(string.uppercase)-1)] 'G' From johan at accesstel.co.za Wed Dec 21 21:58:46 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 21 Dec 2005 22:58:46 +0200 Subject: [Tutor] Books In-Reply-To: <20051221204501.85397.qmail@web25903.mail.ukl.yahoo.com> References: <20051221204501.85397.qmail@web25903.mail.ukl.yahoo.com> Message-ID: <43A9C206.30501@accesstel.co.za> Are here any new books on web programming with Python? Johan David Holland wrote: >I would recommend python programming for the absolute beginner. > > > > > >___________________________________________________________ >Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From carroll at tjc.com Wed Dec 21 22:00:45 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed, 21 Dec 2005 13:00:45 -0800 (PST) Subject: [Tutor] Print random letters In-Reply-To: <43A9B744.40803@tds.net> Message-ID: On Wed, 21 Dec 2005, Kent Johnson wrote: > Take a look at random.choice() or possibly random.shuffle() or > random.sample(). And remember that a string is a kind of sequence. Good call; I should have read all the replies first. >>> random.choice(string.uppercase) is much clearer than my suggestion. From alan.gauld at freenet.co.uk Wed Dec 21 22:09:50 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 21 Dec 2005 21:09:50 -0000 Subject: [Tutor] import a module References: <20051221182240.78346.qmail@web51607.mail.yahoo.com> <43A9A3F4.90901@tds.net> Message-ID: <002f01c60672$e1711200$0b01a8c0@xp> And to add to Kent's comments.... >> C:\Documents and Settings\Christopher Spears\My >> Documents\programming\PythonScripts\Part4\Ex07\functions.py >> >> I want to launch IDLE, import the file, and use it. I >> tried: >> >> import "C:\Documents and Settings\Christopher >> Spears\My >> Documents\programming\PythonScripts\Part4\Ex07\functions.py" >> > You can't give a full path to the import statement. The module to be > imported has to be somewhere in sys.path. And once you have it in the path you do NOT add the .py at the end. Simply use import functions And to add yet another possibility for setting the sys.path, you can add your folder to the PYTHONPATH environment variable, by editing AUTOEXEC.BAT in Win9x or by setting the value in the "MyComputer->Properties->Advanced" dialog tab. HTH, Alan G. From alan.gauld at freenet.co.uk Wed Dec 21 22:21:50 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 21 Dec 2005 21:21:50 -0000 Subject: [Tutor] Differnce between java and python References: Message-ID: <003701c60674$8ed1b980$0b01a8c0@xp> >>Python is more forgiving > > Could you elaborate on this feature? Python allows you to do things, without complaining, that Java just won't allow. As one example: you create a Java module M containing a class C with a method F that throws exception E. Now to use that in your code, say called by function g() you must import the module and also ensure that the function g() is either defined to throw E - or to handle the exception E. The compiler complains otherwise. In Python you simply import the module and call the function. If the exeception is thrown it will generate a stack trace exactly as if you had thrown it inside your code. Of course you might want to handle it locally, but you don't have to be explicit about it. Another example is that Python supports "Duck Typing", that is its type checking is protocol based. So if I declare a function def f(aNumber): ... I can pass in anything that acts like a number, provided it can respond to the subset of numeric operations that I use I can pass in anything. If I nor define a Java funtion/method void f(int n){....} I can only pass in an integer or something that can be typecast as an integer. Very often that's far too strict a limitation. Now the strictness is there for a reason and it encourages good design, but it does require much more thought up front about exactly what will be passed where and which exceptions will be thrown where etc. If you are just learning, or want to get a quick job done then Java's approach is frustrating rather than helpful. That's what I mean by Pyython being more forgiving, or tolerant, than Java. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Dec 21 23:24:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Dec 2005 17:24:41 -0500 Subject: [Tutor] Books In-Reply-To: <43A9C206.30501@accesstel.co.za> References: <20051221204501.85397.qmail@web25903.mail.ukl.yahoo.com> <43A9C206.30501@accesstel.co.za> Message-ID: <43A9D629.9080303@tds.net> Johan Geldenhuys wrote: > Are here any new books on web programming with Python? Depending on what you mean by web programming, you might be interested in these: Foundations of Python Network Programming http://www.apress.com/book/bookDisplay.html?bID=363 Twisted Network Programming Essentials http://www.oreilly.com/catalog/twistedadn/index.html If you are looking for something like the Ruby on Rails book, I don't know of anything like that for Python web frameworks other than Twisted (and maybe Zope). A TurboGears book has been announced but I think they just started writing it so it will be a while: http://www.blueskyonmars.com/2005/12/19/turbogears-book-from-prentice-hall/ Kent From pcarey at lexmark.com Wed Dec 21 23:30:06 2005 From: pcarey at lexmark.com (pcarey@lexmark.com) Date: Wed, 21 Dec 2005 17:30:06 -0500 Subject: [Tutor] Differnce between java and python Message-ID: Alan, thanks for the response. >Python allows you to do things, without complaining, that Java just >won't allow. Checked exceptions are a pain, but at least there's no ambiguity about what f(x) is gonna throw (unless it throws a RuntimeException). Nevertheless, I agree: checked exceptions are probably a misfeature. >Another example is that Python supports "Duck Typing", that is >its type checking is protocol based. I see your point, but duck typing seems awfully implicit and behind-the-scenes. Seems like if I expect a protocol, and you provide something that claims to implement said protocol, there ought to be some contract that ensures we're dealing with the same protocol. I ought not to be able to pass my car and my nose to the same function, just because the both run(). Despite all of this, I still prefer python! (when given the choice). I learned java first, so I probably rely on its compiler crutches. --PETE From kent37 at tds.net Wed Dec 21 23:29:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Dec 2005 17:29:37 -0500 Subject: [Tutor] Differnce between java and python In-Reply-To: <003701c60674$8ed1b980$0b01a8c0@xp> References: <003701c60674$8ed1b980$0b01a8c0@xp> Message-ID: <43A9D751.9080001@tds.net> Alan Gauld wrote: >>>Python is more forgiving >> >>Could you elaborate on this feature? > > > Python allows you to do things, without complaining, that Java just > won't allow. Another way to put it is, Java is way more picky than Python. Much of this is a consequence of Python's dynamic typing - you never declare the type of anything in Python. This alone saves a ton of (finger) typing. Also exceptions in Python don't have to be declared, like unchecked exceptions in Java. It's a matter of some debate whether the extra strictness of Java provides enough safety to be worth the cost. Kent From missive at hotmail.com Wed Dec 21 23:50:33 2005 From: missive at hotmail.com (Lee Harr) Date: Thu, 22 Dec 2005 03:20:33 +0430 Subject: [Tutor] Pygame mailing list info needed Message-ID: >I subscribed to the pygame-users mailing list through majordomo at ......., >but I don't know where to send the mail too so that everybody can see it. > >Any suggestion on how to use that mailing list? > http://www.google.com/search?q=pygame+mailing+list 2nd link ... """ Pygame maintains an active mailing list. You can email the list at pygame-users at seul.org """ Or have you already found that and you are you having a problem with your mail not going through or your questions not being answered? _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From dyoo at hkn.eecs.berkeley.edu Thu Dec 22 01:02:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 21 Dec 2005 16:02:08 -0800 (PST) Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: <20051221050540.19818.qmail@web8412.mail.in.yahoo.com> Message-ID: On Wed, 21 Dec 2005, ps python wrote: > Dear drs. Yoo and johnson, Thank you very much for your help. I > successully parsed my GO annotation from all 16,000 files. thanks again > for your kind help I'm glad to hear that it's working for you now. Just as a clarification: I'm not a doctor. *grin* But I do work with bioinformaticians, so I recognize the Gene Ontology annotations you are working with. From dyoo at hkn.eecs.berkeley.edu Thu Dec 22 01:08:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 21 Dec 2005 16:08:33 -0800 (PST) Subject: [Tutor] Print random letters In-Reply-To: <43A9B614.4040101@accesstel.co.za> Message-ID: > I want to print out random letters from A - Z. I know how to do this > with numbers, but don't know with letters. Hi Johan, There's a "mapping" between numbers and letters through the ord() and chr() built-in functions. ord() takes in a character and returns a number, and chr() takes in a number and returns a character. For example: ###### >>> ord('a') 97 >>> chr(97 + 25) 'z' ###### So yet another approach might be to take what you already know --- getting random numbers --- and just translating those numbers to characters. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Thu Dec 22 01:21:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 21 Dec 2005 16:21:35 -0800 (PST) Subject: [Tutor] Differnce between java and python In-Reply-To: <6434a4300512210213g30219090v80b6224a08753f0@mail.gmail.com> Message-ID: On Wed, 21 Dec 2005, shivayogi kumbar wrote: > sir plz tell me the main differnces between java and python? And What > are the advantages of python? Hi Shivayogi, When you post on a mailing list that's dedicated to help teach programming with Python, you do anticipate what kind of answers you're going to get here, right? *grin* Are you a beginner programmer? Do you have any previous experience with programming? I'd really like us to turn the discussion toward what you really want to learn. Advocacy and cheerleading is fun, of course, but let's see if we can help you too. What are you trying to do? From kent37 at tds.net Thu Dec 22 01:28:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Dec 2005 19:28:18 -0500 Subject: [Tutor] Performance of Python loops vs multiple MySQL queries In-Reply-To: <61d0e2b40512210945q57bb674ew503a1e2ff8b50d48@mail.gmail.com> References: <61d0e2b40512210945q57bb674ew503a1e2ff8b50d48@mail.gmail.com> Message-ID: <43A9F322.30408@tds.net> Bernard Lebel wrote: > Hello, > > Finally, after a year and a half of learning and messing around with > Python, I'm writing THE code that made learn Python in the first > place: a render farm client management software. I may have several > questions regarding this, but for now I only have one. Congratulations Bernard, you have come a long way! > > The script I'm writing is the client script that runs on render nodes. > It checks a database for a job to do, then based on some factors like > pooling, priority, age and stuff, will determine what job it can work > on. The client connects, performs evaluation of jobs, get a job, > update the database, and starts the actual job. > > Now, there might be up to 80 clients connecting to the database at any > moment to get a job to do. So understandably, I want the "evaluation" > step to be as fast as possible. > > Right now, my script works this way: it selects a bunch of rows based > on a few factors. Then when this is done, everything else is done in > the script, that is, doesn't rely on a MySQL query. The script builds > a variety of sorted lists and dictionaries, to ultimately end up with > a single job. > > So I am wondering this: in case there are only a handful of jobs to > evaluate, then I understand the script may run fast. But if it has to > build lists and dictionary on thousands of jobs, then I'm affrait that > it might become slower than simply running a series of queries to the > database using various ordering schemes. > > > Any advice on this? I haven't looked at your code closely so I will just offer some general advice. - Don't assume there is going to be a problem. Python dicts are very fast - they are the data structure underlying namespaces and they have been heavily optimized for years. - Measure! The only way to truly answer your question is to try it both ways and time it. My guess is that the dictionary approach will be faster. I assume the database is on a remote host since it is serving multiple clients. So at a minimum you will have the network round-trip delay for each query. - Your getJob() code seems to use some variables before they are assigned, such as tPoolIDs and aJob. Is this working code? Also it would be easier to read if you broke it up into smaller functions that each do a small piece of the problem. Kent > > > Here is a link to the current code (that build lists and > dictionaries). Keep in mind it's in early alpha stage. The section to > look for is the function getJob(), that starts at line 776. I have > changed the extention to txt for security purposes. > http://www.bernardlebel.com/scripts/nonxsi/farmclient_2.0_beta03.txt > > > > Thanks in advance > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Dec 22 01:31:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Dec 2005 19:31:21 -0500 Subject: [Tutor] how to extract text by specifying an element using ElementTree In-Reply-To: References: Message-ID: <43A9F3D9.4080108@tds.net> Danny Yoo wrote: > > On Wed, 21 Dec 2005, ps python wrote: > > >>Dear drs. Yoo and johnson, Thank you very much for your help. I >>successully parsed my GO annotation from all 16,000 files. thanks again >>for your kind help > > > I'm glad to hear that it's working for you now. Just as a clarification: > I'm not a doctor. *grin* But I do work with bioinformaticians, so I > recognize the Gene Ontology annotations you are working with. No doctor here either. But I'll take it as a compliment! Kent From tim at johnsons-web.com Thu Dec 22 04:46:43 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 21 Dec 2005 18:46:43 -0900 Subject: [Tutor] Books In-Reply-To: <43A9D629.9080303@tds.net> References: <20051221204501.85397.qmail@web25903.mail.ukl.yahoo.com> <43A9C206.30501@accesstel.co.za> <43A9D629.9080303@tds.net> Message-ID: <20051222034643.GB26067@johnsons-web.com> * Kent Johnson [051221 13:40]: > Johan Geldenhuys wrote: > > Are here any new books on web programming with Python? I have "Python Web Programming" by Steve Holden, written in 2002 covering up to python 2.0 - I believe. http://www.amazon.com/gp/product/0735710902/qid=1135222880/sr=2-1/ref=pd_bbs_b_2_1/103-3865586-6854221?s=books&v=glance&n=283155 Foundations of Python Network Programming: http://www.amazon.com/gp/product/1590593715/qid=1135222941/sr=2-1/ref=pd_bbs_b_2_1/103-3865586-6854221?s=books&v=glance&n=283155 -- Tim Johnson http://www.alaska-internet-solutions.com From johan at accesstel.co.za Thu Dec 22 06:38:36 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 22 Dec 2005 07:38:36 +0200 Subject: [Tutor] Pygame mailing list info needed In-Reply-To: References: Message-ID: <43AA3BDC.1080707@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051222/7213ed4a/attachment.htm From eli.usmc.recon at gmail.com Thu Dec 22 10:21:54 2005 From: eli.usmc.recon at gmail.com (Eli Zabielski) Date: Thu, 22 Dec 2005 02:21:54 -0700 Subject: [Tutor] running as generic file type Message-ID: <3cc822320512220121y6db6527w7260fdb3e0a5c112@mail.gmail.com> Hi I'm very new to python, I created my first program, saved it as .py. I wanted to show it to my friends and I tested running it on another computer, one without python, and it didn't work, it gave me a list of programs to try to run it on (ex. word, IE, Mozilla). Is there any way to save it so anyone with windows can use it? Thanks for the help, Eli Zabielski -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051222/b903b758/attachment.html From alan.gauld at freenet.co.uk Thu Dec 22 10:27:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 22 Dec 2005 09:27:02 -0000 Subject: [Tutor] Differnce between java and python References: Message-ID: <005d01c606d9$de1c3be0$0b01a8c0@xp> >>Another example is that Python supports "Duck Typing", that is >>its type checking is protocol based. > > I see your point, but duck typing seems awfully implicit and > behind-the-scenes. When you first encounter it it is. I came from a C++ and Pascal background where strict typing was the rule, Python seemed very lax. But I had the advantage of having worked in Lisp and Smalltalk too so I kind of relaxed fairly quickly. > Seems like if I expect a protocol, and you provide something that claims > to > implement said protocol, there ought to be some contract that ensures > we're > dealing with the same protocol. I ought not to be able to pass my car and > my nose to the same function, just because the both run(). It depends. Obviously in this example its likely that the behaviour would result in boizarre results but on the other hand if the function was race(obj1, obj2) then both car and nose could be appropriate, but in the latter case with rather horrible connotations... But seriously, Duck Typing allows for a far more expreessive and powerful use of objects. When you are no longer bound by the limitations of inheritance heirarchies you can start to build much more powerful funcions. The downside is that there is an onus on the client to sanity check the usage of the function - will it really do what I expect? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Dec 22 10:38:31 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 22 Dec 2005 09:38:31 -0000 Subject: [Tutor] Differnce between java and python References: <6434a4300512210213g30219090v80b6224a08753f0@mail.gmail.com> <000b01c60645$d49459c0$0b01a8c0@xp> <6434a4300512212114w9fae298ub5ecd127b62fb7b1@mail.gmail.com> Message-ID: <006501c606db$7a14dd30$0b01a8c0@xp> [Putting this back on the list so others get the context info] ----- Original Message ----- From: "shivayogi kumbar" Subject: Re: [Tutor] Differnce between java and python Sir I have completed my Msc(c.s).I have worked on java and also done my project on javaa using swings ,RMI technology.The thing is now I have joined the company is working on the Python.So I would ike to know the difference between Java and Python ------------------------------ In that case since you have a good knowledge of Python we can focus on a feature comparison with Java. Python has much in common with Java in that both work by compiling to byte code, however Java does so in a traditional comipile first manner whereas Python compiles at first run. Python is dynamically typed and uses protocol based polymorphism rather than inheritance based(so called Duck typing). Python is a much higher level language than Java, I'd guess the ratio of lines of code per function point is around 3:1. Python is often called 'executable pseudo code'. Python has a much more elegant syntax, it is much less based on C (Although some C-isms do show through in places) Python is more object oriented than Java which is predominantly class based. By that I mean there are lots of objects around in Python where you never see the class. Similarly there are relatively few class methods (static in Java). You can't use Java wthout without seeing at least one class statement. Python has much better support for higher order programming, functional programming and, more debateably, meta-programming. There's lots more but that should e enough for now. Check the refeences others have sent. Also check out Jython which combines the best of both worlds with remarkably few compromises. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Dec 22 12:05:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Dec 2005 06:05:59 -0500 Subject: [Tutor] running as generic file type In-Reply-To: <3cc822320512220121y6db6527w7260fdb3e0a5c112@mail.gmail.com> References: <3cc822320512220121y6db6527w7260fdb3e0a5c112@mail.gmail.com> Message-ID: <43AA8897.9060403@tds.net> Eli Zabielski wrote: > Hi > I'm very new to python, I created my first program, saved it as .py. I > wanted to show it to my friends and I tested running it on another > computer, one without python, and it didn't work, it gave me a list of > programs to try to run it on (ex. word, IE, Mozilla). Is there any way > to save it so anyone with windows can use it? Eli, The .py file is just a text file containing the program, it requires Python to run. Just like you would not give a friend a Word file and expect them to be able to open it without the Word program on their computer, to run a Python program you need the Python interpreter. You have a few options: - Install Python on the other computer. If you have done this already on your computer you know it is not very hard. - Create an executable program that includes your program and the Python interpreter in one bundle. The program to do this is called py2exe, you can find it here: http://www.py2exe.org/ The disadvantage of this is that there is a bit to learn and the resulting executables are much larger than the original program (typically several megabytes) because they include the Python interpreter as well as your program. - Movable Python is a way of building a Python environment on a memory stick. You can bring it to another computer just by plugging in the memory stick. This might be a good solution for you especially if you already have a memory stick. http://www.voidspace.org.uk/python/movpy/ Kent From daniel.brown at realtimeworlds.com Thu Dec 22 12:00:55 2005 From: daniel.brown at realtimeworlds.com (daniel.brown@realtimeworlds.com) Date: Thu, 22 Dec 2005 11:00:55 -0000 Subject: [Tutor] Books Message-ID: <591BEE7C98CA7F48A7079C8221CC012F515580@CHICAGO.dundee.realtimeworlds.com> While we are on the topic of books, what book would you recommend for the experienced C++/C# programmer looking to pick up Python? I've been looking at 'Python in a Nutshell' and 'Programming Python' on amazon.co.uk, as I've found O'Reilly books good in the past. I'm mainly looking to use Python for general scripting tasks as I'm finding that batch files just aren't flexible or powerful enough on WinXP... Cheers, Daniel -----Original Message----- From: tutor-bounces+daniel.brown=realtimeworlds.com at python.org [mailto:tutor-bounces+daniel.brown=realtimeworlds.com at python.org] On Behalf Of Tim Johnson Sent: 22 December 2005 03:47 To: tutor at python.org Subject: Re: [Tutor] Books * Kent Johnson [051221 13:40]: > Johan Geldenhuys wrote: > > Are here any new books on web programming with Python? I have "Python Web Programming" by Steve Holden, written in 2002 covering up to python 2.0 - I believe. http://www.amazon.com/gp/product/0735710902/qid=1135222880/sr=2-1/ref=pd _bbs_b_2_1/103-3865586-6854221?s=books&v=glance&n=283155 Foundations of Python Network Programming: http://www.amazon.com/gp/product/1590593715/qid=1135222941/sr=2-1/ref=pd _bbs_b_2_1/103-3865586-6854221?s=books&v=glance&n=283155 -- Tim Johnson http://www.alaska-internet-solutions.com _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________ This email has been scanned by the MessageLabs Email Security System DISCLAIMER This message and any attachments contain privileged and confidential information intended for the use of the addressee named above. If you are not the intended recipient of this message, you are hereby notified that any use, dissemination, distribution or reproduction of this message is prohibited. Please note that we cannot guarantee that this message or any attachment is virus free or that it has not been intercepted and amended. The views of the author may not necessarily reflect those of Real Time Worlds Ltd. ____________________________________________________________________ This email has been scanned by the MessageLabs Email Security System From johan at accesstel.co.za Thu Dec 22 13:58:39 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 22 Dec 2005 14:58:39 +0200 Subject: [Tutor] Numeric import error Message-ID: <43AAA2FF.6010101@accesstel.co.za> Hi all, I have installed Numeric (Suse 10.0) and it is in my site-packages folder, but I can't import the module. Any idea how to fix this/ TIA Johan From ales at mur.at Thu Dec 22 13:54:54 2005 From: ales at mur.at (Ales Zemene) Date: Thu, 22 Dec 2005 13:54:54 +0100 Subject: [Tutor] md5 message digest algorithm Message-ID: <20051222125453.GC8294@ice.mur.at> hi, suprising for me is that making .py file: import md5 hash = md5.new() and running it produces : AttributeError: 'module' object has no attribute 'new' and similar : from Crypto.Hash import MD5 ImportError: cannot import name MD5 but in both cases it works on python command line intepretter. Ales -- From alan.gauld at freenet.co.uk Thu Dec 22 14:14:01 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 22 Dec 2005 13:14:01 -0000 Subject: [Tutor] running as generic file type References: <3cc822320512220121y6db6527w7260fdb3e0a5c112@mail.gmail.com> Message-ID: <008501c606f9$934df160$0b01a8c0@xp> Hi Eli, > I'm very new to python, I created my first program, saved it as .py. > I wanted to show it to my friends and I tested running it on another > computer, one without python, and it didn't work, That's because Python is an interpreted language so it needs an interpreter to be present. This is the same as Java and most Visual Basic programs, the difference being that Microsoft provide Visual Basic and Java interpreters on Windows as standard. One of the easiest ways for you to write code that works on any machine is to use Jython. It is a vesion of Python written in Java that comes with a compiler for converting the Python code into a Java program. That will then run on any computer with Java installed. The snag is that some of the standard modules that come with Python don't work with Jython! (Thats because Java provides similar modules so you can use them instead). Most beginner programs will work in Jython but as you progress you might start hitting problems. But by then you are ready for option 2... Another way to get the programs to run is to convert the python program into a standalone executable file (a .exe) which can be done using a downloadable tool called py2exe. Py2exe just bundles a copy of the interpreter and all the modules you use into one file. Unfortunately this is not the simplest tool for a beginner to use... Also it creates quite big files - too big for a floppy disk. Of course if your friends had Apple Macs or Linux boxes then Python would be installed already. And there is a version of Python for Microsoft's new .NET framework called IronPython. But I haven't tried it and don't know how well it works. Also your friends will need to have the .NET framework installed. Finally, you could just install Python on your friends PCs too and maybe get them interested in programming :-) So there is no perfect answer (yet), sorry. But there are some options for you to try... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From 3dbernard at gmail.com Thu Dec 22 15:53:24 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 22 Dec 2005 09:53:24 -0500 Subject: [Tutor] Performance of Python loops vs multiple MySQL queries In-Reply-To: <43A9F322.30408@tds.net> References: <61d0e2b40512210945q57bb674ew503a1e2ff8b50d48@mail.gmail.com> <43A9F322.30408@tds.net> Message-ID: <61d0e2b40512220653r2349031al19b0ce8398845c67@mail.gmail.com> On 12/21/05, Kent Johnson wrote: > Bernard Lebel wrote: > > Hello, > > > > Finally, after a year and a half of learning and messing around with > > Python, I'm writing THE code that made learn Python in the first > > place: a render farm client management software. I may have several > > questions regarding this, but for now I only have one. > > Congratulations Bernard, you have come a long way! [Bernard] Thanks a lot Kent, without and all the other gurus of this list, I wouldn't made it that far! > > > > The script I'm writing is the client script that runs on render nodes. > > It checks a database for a job to do, then based on some factors like > > pooling, priority, age and stuff, will determine what job it can work > > on. The client connects, performs evaluation of jobs, get a job, > > update the database, and starts the actual job. > > > > Now, there might be up to 80 clients connecting to the database at any > > moment to get a job to do. So understandably, I want the "evaluation" > > step to be as fast as possible. > > > > Right now, my script works this way: it selects a bunch of rows based > > on a few factors. Then when this is done, everything else is done in > > the script, that is, doesn't rely on a MySQL query. The script builds > > a variety of sorted lists and dictionaries, to ultimately end up with > > a single job. > > > > So I am wondering this: in case there are only a handful of jobs to > > evaluate, then I understand the script may run fast. But if it has to > > build lists and dictionary on thousands of jobs, then I'm affrait that > > it might become slower than simply running a series of queries to the > > database using various ordering schemes. > > > > > > Any advice on this? > > I haven't looked at your code closely so I will just offer some general advice. > > - Don't assume there is going to be a problem. [Bernard] Okay perhaps by "problem" I have not been very accurate. I meant "sync" problems. You see, when the script finds a job, it makes updates in the database, that is, it adds an entry into another table, and updates a certain field in the main jobs table. Other clients then testing if there is something to do rely on information that must be totally up-to-date. I just wanted to make sure I would not run into the case of multiple clients getting incorrect results because of not so up-to-date informations. Perhaps I should investigate table locks? > Python dicts are very fast - they are the data structure underlying namespaces and they > have been heavily optimized for years. [Bernard] Okay, good to know! > - Measure! The only way to truly answer your question is to try it both ways and time it. [Bernard] You are right. > > My guess is that the dictionary approach will be faster. I assume the database is on a > remote host since it is serving multiple clients. So at a minimum you will have the > network round-trip delay for each query. > > - Your getJob() code seems to use some variables before they are assigned, such as > tPoolIDs and aJob. Is this working code? Also it would be easier to read if you broke it > up into smaller functions that each do a small piece of the problem. [Bernard] This is not working code. tPoolIDs is bound after the first query of the function, but aJob is an error of mine. Indeed I could break down the getJob() function into smaller functions. It's just that since the class is already having a fair amount of methods and this is becoming some long code, I wanted to keep everything into a single function. Also there was a consideration of performance. I have one question on the topic breaking code into small functions and performance. I have read somewhere that *any* call whatoever, that is, methods, functions and such, involve a performance cost. Is that right? In the case it is true, the performance deterioration would be proportional with the number of calls being made, so the larger the number of iterations and the more function calls, the slower the code would run, is that correct? Thanks Bernard > > Kent > > > > > > Here is a link to the current code (that build lists and > > dictionaries). Keep in mind it's in early alpha stage. The section to > > look for is the function getJob(), that starts at line 776. I have > > changed the extention to txt for security purposes. > > http://www.bernardlebel.com/scripts/nonxsi/farmclient_2.0_beta03.txt > > > > > > > > Thanks in advance > > Bernard From ajikoe at gmail.com Thu Dec 22 16:05:32 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 22 Dec 2005 16:05:32 +0100 Subject: [Tutor] Numeric import error In-Reply-To: <43AAA2FF.6010101@accesstel.co.za> References: <43AAA2FF.6010101@accesstel.co.za> Message-ID: Can you open the python interpreter and write: import Numeric What kind of error message you have? Cheers, pujo On 12/22/05, Johan Geldenhuys wrote: > > Hi all, > > I have installed Numeric (Suse 10.0) and it is in my site-packages > folder, but I can't import the module. > > Any idea how to fix this/ > > TIA > > Johan > _______________________________________________ > 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/20051222/d7da44c2/attachment.html From johan at accesstel.co.za Thu Dec 22 16:13:38 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 22 Dec 2005 17:13:38 +0200 Subject: [Tutor] Numeric import error In-Reply-To: References: <43AAA2FF.6010101@accesstel.co.za> Message-ID: <43AAC2A2.9020804@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051222/d8387bc9/attachment-0001.htm From ajikoe at gmail.com Thu Dec 22 16:34:23 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 22 Dec 2005 16:34:23 +0100 Subject: [Tutor] Numeric import error In-Reply-To: <43AAC2A2.9020804@accesstel.co.za> References: <43AAA2FF.6010101@accesstel.co.za> <43AAC2A2.9020804@accesstel.co.za> Message-ID: Do you have other modules in your site-packages directory ? Such as spe, pyro, pyrobot etc. On 12/22/05, Johan Geldenhuys wrote: > > >>> import Numeric > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named Numeric > > Pujo Aji wrote: > > Can you open the python interpreter and write: > import Numeric > > What kind of error message you have? > Cheers, > pujo > > On 12/22/05, Johan Geldenhuys wrote: > > > > Hi all, > > > > I have installed Numeric (Suse 10.0) and it is in my site-packages > > folder, but I can't import the module. > > > > Any idea how to fix this/ > > > > TIA > > > > Johan > > _______________________________________________ > > 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/20051222/71d4f9d0/attachment.htm From ajikoe at gmail.com Thu Dec 22 16:35:40 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 22 Dec 2005 16:35:40 +0100 Subject: [Tutor] Numeric import error In-Reply-To: References: <43AAA2FF.6010101@accesstel.co.za> <43AAC2A2.9020804@accesstel.co.za> Message-ID: Can you find numeric.py inside your numeric folder ? On 12/22/05, Pujo Aji wrote: > > Do you have other modules in your site-packages directory ? > Such as spe, pyro, pyrobot etc. > > > > On 12/22/05, Johan Geldenhuys < johan at accesstel.co.za> wrote: > > > > >>> import Numeric > > Traceback (most recent call last): > > File "", line 1, in ? > > ImportError: No module named Numeric > > > > Pujo Aji wrote: > > > > Can you open the python interpreter and write: > > import Numeric > > > > What kind of error message you have? > > Cheers, > > pujo > > > > On 12/22/05, Johan Geldenhuys wrote: > > > > > > Hi all, > > > > > > I have installed Numeric (Suse 10.0) and it is in my site-packages > > > folder, but I can't import the module. > > > > > > Any idea how to fix this/ > > > > > > TIA > > > > > > Johan > > > _______________________________________________ > > > 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/20051222/625d8c7a/attachment.html From broek at cc.umanitoba.ca Thu Dec 22 16:51:42 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 22 Dec 2005 09:51:42 -0600 Subject: [Tutor] Books In-Reply-To: <591BEE7C98CA7F48A7079C8221CC012F515580@CHICAGO.dundee.realtimeworlds.com> References: <591BEE7C98CA7F48A7079C8221CC012F515580@CHICAGO.dundee.realtimeworlds.com> Message-ID: <43AACB8E.7000100@cc.umanitoba.ca> daniel.brown at realtimeworlds.com said unto the world upon 2005-12-22 05:00: > While we are on the topic of books, what book would you recommend for > the experienced C++/C# programmer looking to pick up Python? I've been > looking at 'Python in a Nutshell' and 'Programming Python' on > amazon.co.uk, as I've found O'Reilly books good in the past. I'm mainly > looking to use Python for general scripting tasks as I'm finding that > batch files just aren't flexible or powerful enough on WinXP... > > Cheers, > > Daniel Hi Daniel, the Nutshell is the one to have at hand when coding. I don't know if one could learn from it. Dive into Python is targeted at the experienced programmer and is available both in dead tree and electronic form . Best, Brian vdB From kent37 at tds.net Thu Dec 22 16:58:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Dec 2005 10:58:42 -0500 Subject: [Tutor] md5 message digest algorithm In-Reply-To: <20051222125453.GC8294@ice.mur.at> References: <20051222125453.GC8294@ice.mur.at> Message-ID: <43AACD32.1090405@tds.net> Ales Zemene wrote: > hi, suprising for me is that making .py file: > import md5 > hash = md5.new() > and running it produces : > AttributeError: 'module' object has no attribute 'new' By any chance is your program called md5.py? If so it is being imported instead of the md5 library module. > > and similar : > from Crypto.Hash import MD5 > ImportError: cannot import name MD5 > > but in both cases it works on python command line intepretter. Are you sure you are using the same interpreter in both cases? Maybe try import sys print sys.path to make sure the directory containing Crypto.Hash is in sys.path... HTH Kent > > Ales From kent37 at tds.net Thu Dec 22 17:20:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Dec 2005 11:20:48 -0500 Subject: [Tutor] Performance of Python loops vs multiple MySQL queries In-Reply-To: <61d0e2b40512220653r2349031al19b0ce8398845c67@mail.gmail.com> References: <61d0e2b40512210945q57bb674ew503a1e2ff8b50d48@mail.gmail.com> <43A9F322.30408@tds.net> <61d0e2b40512220653r2349031al19b0ce8398845c67@mail.gmail.com> Message-ID: <43AAD260.8060906@tds.net> Bernard Lebel wrote: > On 12/21/05, Kent Johnson wrote: >>- Don't assume there is going to be a problem. > > > [Bernard] Okay perhaps by "problem" I have not been very accurate. I > meant "sync" problems. You see, when the script finds a job, it makes > updates in the database, that is, it adds an entry into another table, > and updates a certain field in the main jobs table. Other clients then > testing if there is something to do rely on information that must be > totally up-to-date. I just wanted to make sure I would not run into > the case of multiple clients getting incorrect results because of not > so up-to-date informations. Perhaps I should investigate table locks? Yes, you should have a plan to avoid that kind of problem. Does your database support transactions? If so that is the easy way to ensure this - just put the whole getJob() into a transaction. >>- Your getJob() code seems to use some variables before they are assigned, such as >>tPoolIDs and aJob. Is this working code? Also it would be easier to read if you broke it >>up into smaller functions that each do a small piece of the problem. > > > [Bernard] This is not working code. tPoolIDs is bound after the first > query of the function, but aJob is an error of mine. > > Indeed I could break down the getJob() function into smaller > functions. It's just that since the class is already having a fair > amount of methods and this is becoming some long code, I wanted to > keep everything into a single function. hmm, not a good choice. The code will be more readable and maintainable if it is broken up. If the class gets to big, think about making a helper class for some of the code. For example you might put the whole getJob() function into a class or module whose job it is to talk to the database and figure out the next job. One hallmark of a good design is that each class or module has a single responsibility. In your class you have several responsibilities that could possibly be broken out into separate modules - maintain the state of a single client - this is the job of the Client class - low-level database access - the query() function could be in a separate module - details of a single job might fit well in a Job class, this would greatly simplify Client.setJob() - getJob() might move to a utility module that just accesses the database and returns a Job object. > > Also there was a consideration of performance. I have one question on > the topic breaking code into small functions and performance. I have > read somewhere that *any* call whatoever, that is, methods, functions > and such, involve a performance cost. Is that right? Yes. > In the case it is true, the performance deterioration would be > proportional with the number of calls being made, so the larger the > number of iterations and the more function calls, the slower the code > would run, is that correct? Yes, it is correct. Worrying about it at this point is gross premature optimization. It will only be a problem if you have many many function calls in a performance-critical loop. First make working code whose design clearly expresses the intent of the code. If it is too slow, then profile to find the hot spots and address them. Kent From 3dbernard at gmail.com Thu Dec 22 17:48:13 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 22 Dec 2005 11:48:13 -0500 Subject: [Tutor] Performance of Python loops vs multiple MySQL queries In-Reply-To: <43AAD260.8060906@tds.net> References: <61d0e2b40512210945q57bb674ew503a1e2ff8b50d48@mail.gmail.com> <43A9F322.30408@tds.net> <61d0e2b40512220653r2349031al19b0ce8398845c67@mail.gmail.com> <43AAD260.8060906@tds.net> Message-ID: <61d0e2b40512220848y288286f0hec4c5d8c06b55f53@mail.gmail.com> Thanks for all the advice Kent. Bernard On 12/22/05, Kent Johnson wrote: > Bernard Lebel wrote: > > On 12/21/05, Kent Johnson wrote: > >>- Don't assume there is going to be a problem. > > > > > > [Bernard] Okay perhaps by "problem" I have not been very accurate. I > > meant "sync" problems. You see, when the script finds a job, it makes > > updates in the database, that is, it adds an entry into another table, > > and updates a certain field in the main jobs table. Other clients then > > testing if there is something to do rely on information that must be > > totally up-to-date. I just wanted to make sure I would not run into > > the case of multiple clients getting incorrect results because of not > > so up-to-date informations. Perhaps I should investigate table locks? > > Yes, you should have a plan to avoid that kind of problem. Does your database support > transactions? If so that is the easy way to ensure this - just put the whole getJob() into > a transaction. > > >>- Your getJob() code seems to use some variables before they are assigned, such as > >>tPoolIDs and aJob. Is this working code? Also it would be easier to read if you broke it > >>up into smaller functions that each do a small piece of the problem. > > > > > > [Bernard] This is not working code. tPoolIDs is bound after the first > > query of the function, but aJob is an error of mine. > > > > Indeed I could break down the getJob() function into smaller > > functions. It's just that since the class is already having a fair > > amount of methods and this is becoming some long code, I wanted to > > keep everything into a single function. > > hmm, not a good choice. The code will be more readable and maintainable if it is broken > up. If the class gets to big, think about making a helper class for some of the code. For > example you might put the whole getJob() function into a class or module whose job it is > to talk to the database and figure out the next job. > > One hallmark of a good design is that each class or module has a single responsibility. In > your class you have several responsibilities that could possibly be broken out into > separate modules > - maintain the state of a single client - this is the job of the Client class > - low-level database access - the query() function could be in a separate module > - details of a single job might fit well in a Job class, this would greatly simplify > Client.setJob() > - getJob() might move to a utility module that just accesses the database and returns a > Job object. > > > > > Also there was a consideration of performance. I have one question on > > the topic breaking code into small functions and performance. I have > > read somewhere that *any* call whatoever, that is, methods, functions > > and such, involve a performance cost. Is that right? > > Yes. > > > In the case it is true, the performance deterioration would be > > proportional with the number of calls being made, so the larger the > > number of iterations and the more function calls, the slower the code > > would run, is that correct? > > Yes, it is correct. Worrying about it at this point is gross premature optimization. It > will only be a problem if you have many many function calls in a performance-critical loop. > > First make working code whose design clearly expresses the intent of the code. If it is > too slow, then profile to find the hot spots and address them. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Thu Dec 22 18:35:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 22 Dec 2005 17:35:53 -0000 Subject: [Tutor] Books References: <591BEE7C98CA7F48A7079C8221CC012F515580@CHICAGO.dundee.realtimeworlds.com> Message-ID: <009701c6071e$287298d0$0b01a8c0@xp> > While we are on the topic of books, what book would you recommend for > the experienced C++/C# programmer looking to pick up Python? > looking to use Python for general scripting tasks as I'm finding that > batch files just aren't flexible or powerful enough on WinXP... For your particular interest I'd recommend using the official tutorial plus this list to learn the language and buy Python Programming on Win32 by Mark Hammond (O'Reilly) as a reference book. It is essential reading for the serious XP Python programmer because many of the native Python stuff is very Unix biased. Hammond shows how to avoid the pitfalls and adapt to Win32 environments. The book is a little old now (Python 1.5.2) but the vast bulk of it is still absolutely relevant, being based largely on the win32 extensions written by Hammond and found in the winall python package(or included by default in the ActiveState download). Its not all win32 specific, it includes coverage of Tkinter etc too. Still a new version would be welcome! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Dec 22 18:44:19 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 22 Dec 2005 17:44:19 -0000 Subject: [Tutor] Performance of Python loops vs multiple MySQL queries References: <61d0e2b40512210945q57bb674ew503a1e2ff8b50d48@mail.gmail.com><43A9F322.30408@tds.net> <61d0e2b40512220653r2349031al19b0ce8398845c67@mail.gmail.com> Message-ID: <009d01c6071f$56398a70$0b01a8c0@xp> > Also there was a consideration of performance. I have one question on > the topic breaking code into small functions and performance. I have > read somewhere that *any* call whatoever, that is, methods, functions > and such, involve a performance cost. Is that right? Yes it is, but its not a huge cost. Unless you have a very time critical loop calling lots of functions calling functions then don't worry unduly. And if there is a problem use the profiler to tune the bits that need tuning. The benefits of breaking code into functions in terms of readability and maintenance far outweigh the performance hit in 99% of cases. Even in the 1% its better to get it working slowly first then optimise later, exactly where needed. > proportional with the number of calls being made, so the larger the > number of iterations and the more function calls, the slower the code > would run, is that correct? More or less, but a badly designed loop, or list comprehension will cancel out any function call overhead very quickly. And disk reads or network access will be order of magnitude slower still. Worrying about low level performance tuning before you have a problem is usually a wasted effort. High level performance tuning - getting the design clean - is another matter. In all of the cases (bar one) where I've had major performamce issues to fix they have been resolved at the architecture level (minimising network or database accesses) not at the low level code. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Thu Dec 22 19:14:52 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 22 Dec 2005 10:14:52 -0800 (PST) Subject: [Tutor] Differnce between java and python (fwd) Message-ID: [Keeping tutor at python.org in CC. Ok, so now we know that Shivayogi already has Java experience. Shivayogi might also be a little annoyed that he has to learn a new language. We have to tread more carefully in making claims like "Python is easier than Java", because for anyone starting on another language, the language we already know is obviously easier than the one we are trying to learn. *grin*] Hi Shivayogi, There are a few nice things about Python that make common tasks easier to do. We can go through a few examples, and if you have questions on them or would like to see more examples, please ask and folks on the list will be happy to talk with you. (Please make sure to keep tutor at python.org in CC by using your email client's "Reply to All" feature.) For example, Java has an "iterator" protocol, but until Java 1.5, it didn't have much syntactic support. As an example, writing loops to go across iterators involved manually next()ing the iterable and calling hasNext(): /*** Java ***/ import java.util.*; // ... within some method body List words = Arrays.asList(new String[] {"hello", "world", "this", "is", "a", "test"}); for (Iterator iter = words.iterator(); iter.hasNext(); ) { String word = (String) iter.next(); System.out.println(word.toUpperCase()); } /******/ Python's for loop, on the other hand, natively works across iterables: the 'for' loop itself is responsible for doing things like 'next()': ### Python ### words = ["hello", "world", "this", "is", "a", "test"] for word in words: print word.upper() ###### I understand that Java's for loop finally has iterator support, but from the examples I've seen, it looks a bit syntactically heavyweight. Another casual example where Python and Java differ is the treatment of common types. Python doesn't have a notion of "primitive" types, whereas in Java, we sometimes have to think about 'int' vs. Integer. For example, we know that the Java method: /******/ int double(int x) { return x * 2; } /******/ breaks on large input because the declared types are primitive ints. To make this really work, we have to use BigIntegers: /******/ BigInteger double(BigInteger x) { return x.multiply(new BigInteger("2")); } /******/ On the other hand, Python integers also automatically promote themselves to bignums rather than overflow, so the function: ###### def double(x): return x * 2 ###### just works. Does this make sense so far? Please feel free to ask more questions. There's also a book by Bruce Tate called "Beyond Java" that talks about these issues. Best of wishes! ---------- Forwarded message ---------- Date: Thu, 22 Dec 2005 10:40:13 +0530 From: shivayogi kumbar To: Danny Yoo Subject: Re: [Tutor] Differnce between java and python Sir, I hve done my MSc(c.s).I did my project on Java.Know I have joined the company where they work on Python.So It has forced to me learn PYthon.SoI have approaced you people.What are the advntages of Python over java. Thank you On 12/22/05, Danny Yoo wrote: > > > > On Wed, 21 Dec 2005, shivayogi kumbar wrote: > > > sir plz tell me the main differnces between java and python? And What > > are the advantages of python? > > Hi Shivayogi, > > When you post on a mailing list that's dedicated to help teach programming > with Python, you do anticipate what kind of answers you're going to get > here, right? *grin* > > Are you a beginner programmer? Do you have any previous experience with > programming? I'd really like us to turn the discussion toward what you > really want to learn. Advocacy and cheerleading is fun, of course, but > let's see if we can help you too. What are you trying to do? > > From barca_otto at earthlink.net Thu Dec 22 23:50:24 2005 From: barca_otto at earthlink.net (Robin Buyer) Date: Thu, 22 Dec 2005 17:50:24 -0500 Subject: [Tutor] running a .exe Message-ID: <005801c6074a$19930e40$0300000a@Me> How do you run a .exe from inside a python program. random example: print "What would you like to do today? " print "E - email" print "I - internet" what = input("Choose: ") if what == "E": Heres where i would need to run IEXPLORE.exe -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051222/bf024efb/attachment.htm From kent37 at tds.net Fri Dec 23 00:18:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Dec 2005 18:18:34 -0500 Subject: [Tutor] running a .exe In-Reply-To: <005801c6074a$19930e40$0300000a@Me> References: <005801c6074a$19930e40$0300000a@Me> Message-ID: <43AB344A.60806@tds.net> Robin Buyer wrote: > How do you run a .exe from inside a python program. > random example: > print "What would you like to do today? " > print "E - email" > print "I - internet" > what = input("Choose: ") > if what == "E": > Heres where i would need to run IEXPLORE.exe Look at os.system() (simple) and the subprocess module (more complicated and flexible). Kent From nick at javacat.f2s.com Wed Dec 21 22:04:03 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed, 21 Dec 2005 21:04:03 -0000 Subject: [Tutor] Books In-Reply-To: <43A9C206.30501@accesstel.co.za> Message-ID: Web/Network programming here http://www.amazon.com/gp/product/0596100329/qid=1135198935/sr=2-1/ref=pd_bbs _b_2_1/103-4720029-4050242?s=books&v=glance&n=283155 Not CGI specific, and I haven't bought it yet, but I bet it's a blinder :) > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On > Behalf Of Johan Geldenhuys > Sent: 21 December 2005 20:59 > To: David Holland > Cc: tutor at python.org > Subject: Re: [Tutor] Books > > > Are here any new books on web programming with Python? > > Johan > > David Holland wrote: > > >I would recommend python programming for the absolute beginner. > > > > > > > > > > > >___________________________________________________________ > >Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide > with voicemail http://uk.messenger.yahoo.com > >_______________________________________________ > >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 > > > -- > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.1.371 / Virus Database: 267.14.3/209 - Release Date: 21/12/2005 > > From barca_otto at earthlink.net Fri Dec 23 01:37:51 2005 From: barca_otto at earthlink.net (Robin Buyer) Date: Thu, 22 Dec 2005 19:37:51 -0500 Subject: [Tutor] running a .exe References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC02BF4EFD@chbnt01.alpha.wd.govt.nz> Message-ID: <009401c60759$20009270$0300000a@Me> The internet was just an example. I'm just looking at how to open .exe from python. ----- Original Message ----- From: "Liam Clarke-Hutchinson" To: "'Robin Buyer'" ; Sent: Thursday, December 22, 2005 7:35 PM Subject: RE: [Tutor] running a .exe > Hi Robin, > > Normally you would use > > import os > > os.system("c:/windows/iexplore.exe") # Or wherever it lives > > Build as you're attempting to run internet explorer you could use - > > import webbrowser > > webbrowser.open("http://www.google.co.nz") #Assuming IE is system default > broswe > > > Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic > Development > DDI +64 3 962 2639 | Fax +64 3 962 6220 > www.med.govt.nz > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of Robin Buyer > Sent: Friday, 23 December 2005 11:50 a.m. > To: Tutor at python.org > Subject: [Tutor] running a .exe > > > How do you run a .exe from inside a python program. > random example: > print "What would you like to do today? " > print "E - email" > print "I - internet" > what = input("Choose: ") > if what == "E": > Heres where i would need to run IEXPLORE.exe > > A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. > > > > > http://www.govt.nz - connecting you to New Zealand central & local government services > > Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From kent37 at tds.net Fri Dec 23 01:46:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Dec 2005 19:46:57 -0500 Subject: [Tutor] running a .exe In-Reply-To: <008a01c60757$57c40090$0300000a@Me> References: <005801c6074a$19930e40$0300000a@Me> <43AB344A.60806@tds.net> <008a01c60757$57c40090$0300000a@Me> Message-ID: <43AB4901.1000400@tds.net> Robin Buyer wrote: > I created a small program to test os.system: > > import os.path > os.system("C:\Program Files\Internet Explorer\IEXPLORE.EXE") > > when i run this from the command line I get an error message: > 'C:\Program' is not recognized as an internal or external command, operable > program or batch file. > > How do you put spaces into a path name? The same way you do if you are typing the command directly to the shell - put it in quotes. So now there are two sets of quotes - one to tell Python it is a string, and one to pass to the shell: os.system('"C:\Program Files\Internet Explorer\IEXPLORE.EXE"') Alternately use subprocess.call() which takes a list of command-line parameters so it knows to quote the first arg: >>> import subprocess >>> subprocess.call([r'C:\Program Files\Internet Explorer\IEXPLORE.EXE']) Also note that if you want to use paths with \ in them in Python strings you should use a raw string, otherwise the \ start escape sequences that you don't intend: os.system(r'"C:\Program Files\Internet Explorer\IEXPLORE.EXE"') Kent PS please respond to the list. From barca_otto at earthlink.net Fri Dec 23 01:56:04 2005 From: barca_otto at earthlink.net (Robin Buyer) Date: Thu, 22 Dec 2005 19:56:04 -0500 Subject: [Tutor] running a .exe References: <005801c6074a$19930e40$0300000a@Me> <43AB344A.60806@tds.net><008a01c60757$57c40090$0300000a@Me> <43AB4901.1000400@tds.net> Message-ID: <00ac01c6075b$a766d330$0300000a@Me> Ahhhhhh. That helps a lot. Thanks. -Robin ----- Original Message ----- From: "Kent Johnson" To: "Python Tutor" Sent: Thursday, December 22, 2005 7:46 PM Subject: Re: [Tutor] running a .exe > Robin Buyer wrote: > > I created a small program to test os.system: > > > > import os.path > > os.system("C:\Program Files\Internet Explorer\IEXPLORE.EXE") > > > > when i run this from the command line I get an error message: > > 'C:\Program' is not recognized as an internal or external command, operable > > program or batch file. > > > > How do you put spaces into a path name? > > The same way you do if you are typing the command directly to the shell - put it in > quotes. So now there are two sets of quotes - one to tell Python it is a string, and one > to pass to the shell: > os.system('"C:\Program Files\Internet Explorer\IEXPLORE.EXE"') > > Alternately use subprocess.call() which takes a list of command-line parameters so it > knows to quote the first arg: > >>> import subprocess > >>> subprocess.call([r'C:\Program Files\Internet Explorer\IEXPLORE.EXE']) > > Also note that if you want to use paths with \ in them in Python strings you should use a > raw string, otherwise the \ start escape sequences that you don't intend: > os.system(r'"C:\Program Files\Internet Explorer\IEXPLORE.EXE"') > > Kent > > PS please respond to the list. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From wescpy at gmail.com Fri Dec 23 09:56:05 2005 From: wescpy at gmail.com (w chun) Date: Fri, 23 Dec 2005 00:56:05 -0800 Subject: [Tutor] Learning books In-Reply-To: <43A86D8F.7000407@gmail.com> References: <43A86D8F.7000407@gmail.com> Message-ID: <78b3a9580512230056h10c5ca90g40c345473473225c@mail.gmail.com> On 12/20/05, Richard wrote: > Afternoon all, My son asked me what books I would like for Christmas > this year. So what would you recommend? > > I am a beginner here. hi richard, welcome to the list. are you a beginner to Python (but have programming experience), a beginner to programming *and* Python, or other? if you are new to programming period, then congratulations for finding Python and this mailing list... you've done your homework. good books to start here include: 1) michael dawson's python programming for the absolute beginner 2) alan (gauld)'s learn to program and as a good beginner's reference: 3) chris fehily's quick start guide if you're new to programming from a computer science student's perspective, there's: 1) john zelle's python programming: intro to computer science if you're new to programming from a graphic artist/designer or multimedia point-of-view, try: 1) mark guzdial's introduction to computing and programming in python if you're already a programmer and want to pick up Python as quickly as possible: 1) Core Python Programming by yours truly, however 2nd ed won't come out until Summer 2006, and i myself am having a hard time getting new copies of the 1st ed 2) mark pilgrim's dive into python 3) magnus hetland's beginning python 4) ascher and lutz learning python if you have a background in C programming good luck, and feel free to ask more specific questions about what you're looking for. cheers, - wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From shivayogiks at gmail.com Fri Dec 23 12:18:05 2005 From: shivayogiks at gmail.com (shivayogi kumbar) Date: Fri, 23 Dec 2005 03:18:05 -0800 Subject: [Tutor] assert Message-ID: <6434a4300512230318i206e974bn3f8f121e3c39774b@mail.gmail.com> sir, I would like to know about 'asser't keyword how it works in the fallowing program class myClass: count = 0 def __init__(self): myClass.count = myClass.count + 1 def __del__(self): myClass.count =myClass.count -1 assert myClass.count>0 def howmany(self): return myClass.count >>>a=myClass() >>>b=myClass() >>>a.howmany() >>>del b >>>del a From python-tutor at toddmaynard.com Fri Dec 23 12:55:41 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Fri, 23 Dec 2005 06:55:41 -0500 Subject: [Tutor] assert In-Reply-To: <6434a4300512230318i206e974bn3f8f121e3c39774b@mail.gmail.com> References: <6434a4300512230318i206e974bn3f8f121e3c39774b@mail.gmail.com> Message-ID: <200512230655.41966.python-tutor@toddmaynard.com> Try this: >>>a=myClass() >>>b=myClass() >>>a.howmany() >>>a.count=0 >>>del a Does this help clear things up? Todd Maynard On Friday 23 December 2005 06:18, shivayogi kumbar wrote: > class myClass: > ? ? ? ? ? ? ? ? ? ? ? ? count = 0 > ? ? ? ? ? ? ? ? ? ? ? ? ?def __init__(self): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? myClass.count = myClass.count + 1 > ? ? ? ? ? ? ? ? ? ? ? ? ? def __del__(self): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?myClass.count =myClass.count -1 > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? assert myClass.count>0 > ? ? ? ? ? ? ? ? ? ? ? ? ? def howmany(self): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?return myClass.count From kent37 at tds.net Fri Dec 23 13:56:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Dec 2005 07:56:30 -0500 Subject: [Tutor] assert In-Reply-To: <6434a4300512230318i206e974bn3f8f121e3c39774b@mail.gmail.com> References: <6434a4300512230318i206e974bn3f8f121e3c39774b@mail.gmail.com> Message-ID: <43ABF3FE.8040009@tds.net> shivayogi kumbar wrote: > sir, > I would like to know about 'asser't keyword how it works in the > fallowing program I'm not sure what the question is. Do you not understand assert at all or is there something about how this program works that you don't understand? assert is documented here: http://docs.python.org/ref/assert.html#l2h-461 Simplified a little, assert myClass.count>0 is essentially the same as if not myClass.count>0: raise AssertionError assert is usually used to verify an assumption about the state of a program at some point. The usage here doesn't really make sense, as myClass.count can legitimately be 0. A better assertion would be assert myClass.count>=0 since you would expect this to always be true. Kent > class myClass: > count = 0 > def __init__(self): > myClass.count = myClass.count + 1 > def __del__(self): > myClass.count =myClass.count -1 > assert myClass.count>0 > def howmany(self): > return myClass.count > > >>>a=myClass() > >>>>b=myClass() >>>>a.howmany() >>>>del b >>>>del a > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From p.atmatzidis at gmail.com Fri Dec 23 19:15:46 2005 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Fri, 23 Dec 2005 20:15:46 +0200 Subject: [Tutor] Input checking [letters or numbers] Message-ID: Hello, Can someone provide me with an error checking example about an x variable that needs to be number only? I used something like: def useridf(): print "" print "WARNING: If you don't understand why this must be unique, exit and read the manual." print "" userid = input("x : ") I know that "input" accepts only numbers, but I don't want the program to break if someone puts other chars in it. I want to, print "Only numbers are accepted." which is easy. But still I can't understand how to do the check using if/elif/else statements. From bgailer at alum.rpi.edu Fri Dec 23 19:45:05 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 23 Dec 2005 10:45:05 -0800 Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: References: Message-ID: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> At 10:15 AM 12/23/2005, Panagiotis Atmatzidis wrote: >Hello, > >Can someone provide me with an error checking example about an x >variable that needs to be number only? I used something like: > > def useridf(): > print "" > print "WARNING: If you don't understand why this must be unique, >exit and read the manual." You ask the user to exit but you don't tell him how to do that! > print "" > userid = input("x : ") > >I know that "input" accepts only numbers How did you "know" that? Try this: print input("x ; ") and enter "Hello world" Truth is input() "accepts" anything and attempts to evaluate it as a Python expression. If that fails it raises an exception. You should use raw_input() instead. This takes any input and returns it as a character string. x = raw_input("x : ") if x.isdigit(): # ensure input is a number y = int(x) # convert to integer else: print 'Boo" >, but I don't want the program >to break if someone puts other chars in it. I want to, print "Only >numbers are accepted." which is easy. But still I can't understand how >to do the check using if/elif/else statements. From python-tutor at toddmaynard.com Fri Dec 23 20:00:02 2005 From: python-tutor at toddmaynard.com (python-tutor@toddmaynard.com) Date: Fri, 23 Dec 2005 14:00:02 -0500 Subject: [Tutor] assert In-Reply-To: <200512230655.41966.python-tutor@toddmaynard.com> References: <6434a4300512230318i206e974bn3f8f121e3c39774b@mail.gmail.com> <200512230655.41966.python-tutor@toddmaynard.com> Message-ID: <200512231400.02971.python-tutor@toddmaynard.com> Shivayogi, Sorry my last e-mail wasn't very helpful. Better would have been: >>> a=myClass() >>> b=myClass() >>> a.howmany() >>> myClass.count=0 >>> del a which will (hopefully) give you something like: Exception exceptions.AssertionError: in > ignored Assert is commonly used as a sanity check for things that you always expect to be true. Hope this helps, Todd Maynard On Friday 23 December 2005 06:55, python-tutor at toddmaynard.com wrote: > Try this: > >>>a=myClass() > >>>b=myClass() > >>>a.howmany() > >>>a.count=0 > >>>del a > > Does this help clear things up? > > > Todd Maynard > > On Friday 23 December 2005 06:18, shivayogi kumbar wrote: > > class myClass: > > ? ? ? ? ? ? ? ? ? ? ? ? count = 0 > > ? ? ? ? ? ? ? ? ? ? ? ? ?def __init__(self): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? myClass.count = myClass.count + 1 > > ? ? ? ? ? ? ? ? ? ? ? ? ? def __del__(self): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?myClass.count =myClass.count -1 > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? assert myClass.count>0 > > ? ? ? ? ? ? ? ? ? ? ? ? ? def howmany(self): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?return myClass.count > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From p.atmatzidis at gmail.com Fri Dec 23 20:16:33 2005 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Fri, 23 Dec 2005 21:16:33 +0200 Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> References: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> Message-ID: Hello there, Thank you for the prompt response. On 12/23/05, bob wrote: > At 10:15 AM 12/23/2005, Panagiotis Atmatzidis wrote: > >Hello, > > > >Can someone provide me with an error checking example about an x > >variable that needs to be number only? I used something like: > > > > def useridf(): > > print "" > > print "WARNING: If you don't understand why this must be unique, > >exit and read the manual." > > You ask the user to exit but you don't tell him how to do that! > > > print "" > > userid = input("x : ") > > > >I know that "input" accepts only numbers > > How did you "know" that? Try this: > print input("x ; ") > and enter "Hello world" OSX atma ~ $ python Python 2.3.5 (#1, Mar 20 2005, 20:38:20) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input("x: ") x: hello world Traceback (most recent call last): File "", line 1, in ? File "", line 1 hello world ^ SyntaxError: unexpected EOF while parsing Just did.. and as you can see I get an error. I know because I read so in the tutorial I mentioned before.. I mean that it says so.. now I am taking the first steps into programming, hence I don't really know if there's another reason for input to break upon chars. >>> x = input("x: ") x: 12 >>> > > Truth is input() "accepts" anything and attempts to evaluate it as a > Python expression. If that fails it raises an exception. Okay. > > You should use raw_input() instead. This takes any input and returns > it as a character string. I already use raw_input for alphanumeric characters. > x = raw_input("x : ") > if x.isdigit(): # ensure input is a number > y = int(x) # convert to integer > else: > print 'Boo" Thank you for the sample code. > > >, but I don't want the program > >to break if someone puts other chars in it. I want to, print "Only > >numbers are accepted." which is easy. But still I can't understand how > >to do the check using if/elif/else statements. > > Best Regards, Panagiotis From dyoo at hkn.eecs.berkeley.edu Fri Dec 23 20:16:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 23 Dec 2005 11:16:35 -0800 (PST) Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> Message-ID: > x = raw_input("x : ") > if x.isdigit(): # ensure input is a number > y = int(x) # convert to integer > else: > print 'Boo" Hello Bob and Panagiotis, It might be good to make this number-reading thing a function, just to make it easier to reuse (and test!) it. Let's call this input_number() for the moment. ####################################################### def input_number(prompt): """Reads an integer from the next line of input.""" while 1: x = raw_input(prompt) if x.isdigit(): return int(x) else: print 'Boo' ####################################################### Does this work? Let's try it informally: ###### >>> input_number('number please: ') number please: 1 1 >>> input_number('number please: ') number please: 1234 1234 >>> input_number('number please: ') number please: 1st Boo number please: 74 74 >>> ###### I added one more behavior so that input_number continues to ask until it's satisified by a number. Hope this helps! From p.atmatzidis at gmail.com Fri Dec 23 20:25:12 2005 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Fri, 23 Dec 2005 21:25:12 +0200 Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: References: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> Message-ID: Hello Dany :-) On 12/23/05, Danny Yoo wrote: > > x = raw_input("x : ") > > if x.isdigit(): # ensure input is a number > > y = int(x) # convert to integer > > else: > > print 'Boo" > > > Hello Bob and Panagiotis, > > It might be good to make this number-reading thing a function, just to > make it easier to reuse (and test!) it. Let's call this input_number() > for the moment. > > ####################################################### > def input_number(prompt): > """Reads an integer from the next line of input.""" > while 1: > x = raw_input(prompt) > if x.isdigit(): > return int(x) > else: > print 'Boo' > ####################################################### > > > Does this work? Let's try it informally: > > ###### > >>> input_number('number please: ') > number please: 1 > 1 > >>> input_number('number please: ') > number please: 1234 > 1234 > >>> input_number('number please: ') > number please: 1st > Boo > number please: 74 > 74 > >>> > ###### > > I added one more behavior so that input_number continues to ask until it's > satisified by a number. Hope this helps! Yes, it really helps a lot. Now I can proceed with my script!! Thank you for the reply, Best Regards, Panagiotis From bgailer at alum.rpi.edu Fri Dec 23 20:27:53 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 23 Dec 2005 11:27:53 -0800 Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: References: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> Message-ID: <7.0.0.16.0.20051223112356.01dfaa50@alum.rpi.edu> At 11:16 AM 12/23/2005, Panagiotis Atmatzidis wrote: >Hello there, > >Thank you for the prompt response. > >On 12/23/05, bob wrote: >[snip] > > print input("x ; ") > > and enter "Hello world" > > >>> x = input("x: ") >x: hello world >Traceback (most recent call last): > File "", line 1, in ? > File "", line 1 > hello world > ^ >SyntaxError: unexpected EOF while parsing > >Just did.. and as you can see I get an error. I know because I read so >in the tutorial I mentioned before.. I mean that it says so.. now I am >taking the first steps into programming, hence I don't really know if >there's another reason for input to break upon chars. Enter "hello world" including the quotes. input expects a Python expression. hello world is not a Python expression "hello world" is [snip] From p.atmatzidis at gmail.com Fri Dec 23 20:28:47 2005 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Fri, 23 Dec 2005 21:28:47 +0200 Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: References: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> Message-ID: On 12/23/05, Panagiotis Atmatzidis wrote: > Hello Dany :-) > > On 12/23/05, Danny Yoo wrote: [...] > > > > > > Hello Bob and Panagiotis, > > > > It might be good to make this number-reading thing a function, just to > > make it easier to reuse (and test!) it. Let's call this input_number() > > for the moment. > > > > ####################################################### > > def input_number(prompt): > > """Reads an integer from the next line of input.""" > > while 1: > > x = raw_input(prompt) > > if x.isdigit(): > > return int(x) > > else: > > print 'Boo' > > ####################################################### [...] > > I added one more behavior so that input_number continues to ask until it's > > satisified by a number. Hope this helps! > > Yes, it really helps a lot. Now I can proceed with my script!! [...] Another newbe question! I use "while True: " to evaluate an expression, I see that you used while 1: .. what's the diffrence if any?! -- Panagiotis From p.atmatzidis at gmail.com Fri Dec 23 20:29:45 2005 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Fri, 23 Dec 2005 21:29:45 +0200 Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: <7.0.0.16.0.20051223112356.01dfaa50@alum.rpi.edu> References: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> <7.0.0.16.0.20051223112356.01dfaa50@alum.rpi.edu> Message-ID: Yeah works you're right. :-) On 12/23/05, bob wrote: > At 11:16 AM 12/23/2005, Panagiotis Atmatzidis wrote: > >Hello there, > > > >Thank you for the prompt response. > > > >On 12/23/05, bob wrote: > >[snip] > > > print input("x ; ") > > > and enter "Hello world" > > > > >>> x = input("x: ") > >x: hello world > >Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 1 > > hello world > > ^ > >SyntaxError: unexpected EOF while parsing > > > >Just did.. and as you can see I get an error. I know because I read so > >in the tutorial I mentioned before.. I mean that it says so.. now I am > >taking the first steps into programming, hence I don't really know if > >there's another reason for input to break upon chars. > > Enter "hello world" including the quotes. > input expects a Python expression. > hello world is not a Python expression > "hello world" is > [snip] > > -- Panagiotis From kent37 at tds.net Fri Dec 23 20:38:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Dec 2005 14:38:40 -0500 Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: References: Message-ID: <43AC5240.6000709@tds.net> Panagiotis Atmatzidis wrote: > Hello, > > Can someone provide me with an error checking example about an x > variable that needs to be number only? I used something like: > > def useridf(): > print "" > print "WARNING: If you don't understand why this must be unique, > exit and read the manual." > print "" > userid = input("x : ") > > I know that "input" accepts only numbers, but I don't want the program > to break if someone puts other chars in it. I want to, print "Only > numbers are accepted." which is easy. But still I can't understand how > to do the check using if/elif/else statements. Another way to do this is to use raw_input() to get the input as a string, then just try to convert it to an int and catch any exception. This also works well encapsulated into a function: def getInt(prompt): while 1: s = raw_input(prompt) try: return int(s) except ValueError: print 'Only numbers are accepted' This approach will accept negative numbers as well as positive: >>> def getInt(prompt): ... while 1: ... s = raw_input(prompt) ... try: ... return int(s) ... except ValueError: ... print 'Only numbers are accepted' ... >>> getInt('x: ') x: ae Only numbers are accepted x: -4 -4 Kent From rich.424 at gmail.com Fri Dec 23 21:05:22 2005 From: rich.424 at gmail.com (Richard) Date: Fri, 23 Dec 2005 14:05:22 -0600 Subject: [Tutor] Learning books In-Reply-To: <1135113511.32594.1.camel@localhost.localdomain> References: <43A86D8F.7000407@gmail.com> <1135113511.32594.1.camel@localhost.localdomain> Message-ID: <43AC5882.7000001@gmail.com> First of thanks for all the great input from everyone!!! Okay, so I have been reading some of the tutorials around the net on Python. great stuff I might add but I am getting all confused with the TCL, xwwidgets etc. I want to be able to program and I am just using the standard IDE that comes with Python. Am I on the right track? Or I am better off using a different one or ??? I see that some are someting with C++ but heck, I just want to learn Python for now. I do want the widgets to look nice sure. HELP! Thanks in advance and Happy Holidays!! Richard P.S. I think I am getting one or two of the recomended books for Christmas! (cant wait!) nephish wrote: >Learning Python by O'Reilly, >got me started after realizing that Programming Python by O'Reilly was a >tad over me head. > >i am new here too. > >On Tue, 2005-12-20 at 14:46 -0600, Richard wrote: > > >>Afternoon all, My son asked me what books I would like for Christmas >>this year. So what would you recommend? >> >>I am a beginner here. >> >> >>Thanks >> >> >>Richard >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > > > > From bgailer at alum.rpi.edu Fri Dec 23 21:42:07 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 23 Dec 2005 12:42:07 -0800 Subject: [Tutor] Input checking [letters or numbers] In-Reply-To: References: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> Message-ID: <7.0.0.16.0.20051223123232.02336d20@alum.rpi.edu> At 11:28 AM 12/23/2005, Panagiotis Atmatzidis wrote: >On 12/23/05, Panagiotis Atmatzidis wrote: > > Hello Dany :-) > > > > On 12/23/05, Danny Yoo wrote: >[...] > > > > > > > > > Hello Bob and Panagiotis, > > > > > > It might be good to make this number-reading thing a function, just to > > > make it easier to reuse (and test!) it. Let's call this input_number() > > > for the moment. > > > > > > ####################################################### > > > def input_number(prompt): > > > """Reads an integer from the next line of input.""" > > > while 1: > > > x = raw_input(prompt) > > > if x.isdigit(): > > > return int(x) > > > else: > > > print 'Boo' > > > ####################################################### >[...] > > > I added one more behavior so that input_number continues to ask > until it's > > > satisified by a number. Hope this helps! > > > > Yes, it really helps a lot. Now I can proceed with my script!! >[...] > >Another newbe question! I use "while True: " to evaluate an >expression, I see that you used while 1: .. what's the diffrence if any?! In this case, no difference. True and False are Python boolean constants, and also a subset of integer. So one may print True + 1 and see 2. Conditional statements (while, if, elif) and the if clause of list comprehensions and generator expressions expect an expression that will be treated as True if not empty and False if empty. From the L:angRef: "In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: None, numeric zero of all types, empty sequences (strings, tuples and lists), and empty mappings (dictionaries). All other values are interpreted as true." From nick at javacat.f2s.com Fri Dec 23 23:19:19 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri, 23 Dec 2005 22:19:19 -0000 Subject: [Tutor] Learning books In-Reply-To: <43AC5882.7000001@gmail.com> Message-ID: Hi Richard, I myself just about know enough python to help me in my job occasionally and to do some cool little hobby projects. When it comes to creating GUI's for my programs I always use pythoncard, see here www.pythoncard.org . It's very simple to use, and the tutorials on their site will have you up and running in no time. It's based on wxpython but you don't need to know wxpython to use it at all, unless pythoncard itself does not implement some functionality that you desire. The pythoncard mailing list is also very low volume and very helpful. As a side note, I am the senior unix admin for a uk financial corp and I know very well that learning perl would be the best 'prospective' language for me to get to grips with, but no matter what issue I come up with at work (or home) python is always, and I truly mean always, the better option. I wish you good luck with your python learning experience, and I'm sure that you will find it's also a very cool language to use. I can't help but feel that it is inevitable that it will eventually overtake perl as the scripting language of choice. I hope none of that went too far off topic :) Nick . > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On > Behalf Of Richard > Sent: 23 December 2005 20:05 > Cc: tutor > Subject: Re: [Tutor] Learning books > > > First of thanks for all the great input from everyone!!! > > Okay, so I have been reading some of the tutorials around the net on > Python. great stuff I might add but I am getting all confused with the > TCL, xwwidgets etc. I want to be able to program and I am just using the > standard IDE that comes with Python. Am I on the right track? Or I am > better off using a different one or ??? I see that some are someting > with C++ but heck, I just want to learn Python for now. I do want the > widgets to look nice sure. HELP! > > Thanks in advance and Happy Holidays!! > > Richard > > P.S. I think I am getting one or two of the recomended books for > Christmas! (cant wait!) > > nephish wrote: > > >Learning Python by O'Reilly, > >got me started after realizing that Programming Python by O'Reilly was a > >tad over me head. > > > >i am new here too. > > > >On Tue, 2005-12-20 at 14:46 -0600, Richard wrote: > > > > > >>Afternoon all, My son asked me what books I would like for Christmas > >>this year. So what would you recommend? > >> > >>I am a beginner here. > >> > >> > >>Thanks > >> > >> > >>Richard > >>_______________________________________________ > >>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 > > > -- > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.1.371 / Virus Database: 267.14.5/212 - Release Date: 23/12/2005 > > From p.atmatzidis at gmail.com Sat Dec 24 14:20:23 2005 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Sat, 24 Dec 2005 15:20:23 +0200 Subject: [Tutor] Problem with os.access function. [semantic error, if check does not work] Message-ID: Hello, I am writing a function in order to check if a directory exists. If exists the functions must do nothing, otherwise must check the users permissions and if it's possible create the dir. Looking at pydoc's httpd I found the module "os" and the function "access". From the http-doc: access(...) access(path, mode) -> 1 if granted, 0 otherwise Use the real uid/gid to test for access to a path. Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to the path. The mode argument can be F_OK to test existence, or the inclusive-OR of R_OK, W_OK, and X_OK. This is my function: def homedirhandle(): path = "/some/dir/" # check the existance of the directory mode = 755 check_path = os.access(path, mode) print check_path if check_path == 'False': print "" print "Directory /some/dir does not exist." print "Trying to create the directory." uid = os.geteuid() print "the uid is ", uid if uid == '0': try: os.mkdir(path, mode) print "" print "The directory has been created." print "" return path except OSError, e: print "" print >>sys.stderr, "The mkdir command failed: %d (%s)" % (e.errno, e.strerror) print "" print "Exiting" sys.exit(1) if check_path == '1': print "" print "The directory /some/dir has been created." print "" return path else: print "Please create the directory /some/dir manually and then re-run vuhalndler." print "Exiting" sys.exit() else: print "" print "The directory already exists." print "" return path Now the problem lies at the first check " if check_path == 'False': ". It's a semantic error, the program does not really check the dir, it just takes for granted that the dir exists. I tried with 1 before putting "False" there.. but it did not work so I took the print result of check_path and substitute 1 with False. But still nothing :-( Why does not make the check? I thought that the functions functionality was clear.. probably is not. -- Panagiotis From alan.gauld at freenet.co.uk Sat Dec 24 15:33:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 24 Dec 2005 14:33:11 -0000 Subject: [Tutor] Learning books References: <43A86D8F.7000407@gmail.com><1135113511.32594.1.camel@localhost.localdomain> <43AC5882.7000001@gmail.com> Message-ID: <011301c60896$f7b7c3d0$0b01a8c0@xp> > Okay, so I have been reading some of the tutorials around the net on > Python. great stuff I might add but I am getting all confused with the > TCL, xwwidgets etc. I want to be able to program and I am just using the > standard IDE that comes with Python. Am I on the right track? Yes, when beginning stick to the most basic tools. The wxWidgets stuff is the underbelly of wxPython but you should only need to worry about that once you get into quite deep GUI design. Similarly Tcl/Tk is the underbelly of Tkinter and again you should rarely ever see Tcl nowadays in Python, apart from a deeply nested error message from Tkinter - where you can nearly always ignore the Tcl aspects! Other languages are useful to compare with, seeing the same basic structures in different languages can emphasise that the concepts are the same, it's only syntax that changes. But only try to *learn* one lot of syntax at a time, otherwise you will get confused. > with C++ but heck, I just want to learn Python for now. I do want the > widgets to look nice sure. HELP! wxWidgets is written in C++, as are most native code applications etc. Unfortunately most of the documentation for wxPython still uses the C++ documents so you either have to work from the higher level Python documents or learn to read (at a superficial level) the C++ documents. To do that you really need to have covered the basics of OOP - which is one thing I like about Tkinter, you don't need OOP to use it, although OOP makes it easier... But as a beginner most of your programs should be targetted at the command line. To try to build GUIs too soon will simply distract from the fundamental proinciples of programming. And once you have a working command-line version its usually fairly easy to convert it for GUI use later, especially if you keep the display functions (ie. print statements) separate from the logic. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Dec 24 15:53:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 24 Dec 2005 14:53:28 -0000 Subject: [Tutor] Input checking [letters or numbers] References: <7.0.0.16.0.20051223103933.0233e588@alum.rpi.edu> Message-ID: <011f01c60899$cd0a7170$0b01a8c0@xp> > Another newbe question! I use "while True: " to evaluate an > expression, I see that you used while 1: .. what's the diffrence if > any?! Python only provided boolean literal values (True, False) relatively recently. Long time Python programmers, especially those with a C background(*) are used to writing 1 to mean True. It's a hard habit to break. But it means exactly the same as True and since True is usually more readable its probably better to use that. (In theory Python could change to make 1 and True non compatible, but in truth thats extremely unlikely because it is such a deeply embedded tradition and huge amounts of existing code would break!) (*) Strictly speaking the numeric definition is based on 0 being False and True being "non-zero". Thus C programmers used to do this: #define FALSE 0 #define TRUE !FALSE This left the numeric value of TRUE up to the compiler, in most cases it would be 1 but in some cases it could be -1 or very occasionally MAXINT (0xFFFF) This led to strange behaviour such as: if ((1-2) == TRUE) { // works in some compilers not in others!} The correct way was to compare to FALSE or just use the result as a value: if (2-1) {//this always works} Pythons introduction of boolean type values should have gotten round all that but unfortunately it doesn't: >>> if (1-2): print 'True' True >>> if True: print 'True' True >>> if (1-2) == True: print 'True' >>> So unfortunately Pythons implementation of Boolean values is only half True(sorry couldn't resist!:-). In a true boolean implementation any non zero value should test equal to True... No language is perfect! HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Sat Dec 24 18:36:12 2005 From: bgailer at alum.rpi.edu (bob) Date: Sat, 24 Dec 2005 09:36:12 -0800 Subject: [Tutor] Problem with os.access function. [semantic error, if check does not work] In-Reply-To: References: Message-ID: <7.0.0.16.0.20051224092233.0227b968@alum.rpi.edu> At 05:20 AM 12/24/2005, Panagiotis Atmatzidis wrote: >Hello, > >I am writing a function in order to check if a directory exists. If >exists the functions must do nothing, otherwise must check the users >permissions and if it's possible create the dir. Looking at pydoc's >httpd I found the module "os" and the function "access". From the >http-doc: > >access(...) >access(path, mode) -> 1 if granted, 0 otherwise > >Use the real uid/gid to test for access to a path. Note that most >operations will use the effective uid/gid, therefore this routine can >be used in a suid/sgid environment to test if the invoking user has the >specified access to the path. The mode argument can be F_OK to test >existence, or the inclusive-OR of R_OK, W_OK, and X_OK. > >This is my function: > >def homedirhandle(): > path = "/some/dir/" # check the existance of the >directory > mode = 755 should be mode = 0755 (octal representation) for mkdir. For access: "The mode argument can be F_OK to test existence, or the inclusive-OR of R_OK, W_OK, and X_OK." suggests that only 1 digit is expected. > check_path = os.access(path, mode) > print check_path > if check_path == 'False': Should be if check_path == False: Or even simpler if not check_path: Use print repr(check_path). Then you'd see either True or 'True'. That would help you see whether check_path is boolean or string. > print "" > print "Directory /some/dir does not exist." > print "Trying to create the directory." > uid = os.geteuid() > print "the uid is ", uid > if uid == '0': I think (not having UNIX access at the moment) that this should be if uid == 0: > try: > os.mkdir(path, mode) > print "" > print "The directory has been created." > print "" > return path > except OSError, e: > print "" > print >>sys.stderr, "The mkdir command failed: >%d (%s)" % (e.errno, e.strerror) > print "" > print "Exiting" > sys.exit(1) > > if check_path == '1': == 1 > print "" > print "The directory /some/dir has been created." > print "" > return path > else: > print "Please create the directory /some/dir manually and >then re-run vuhalndler." > print "Exiting" > sys.exit() > else: > print "" > print "The directory already exists." > print "" > return path > >Now the problem lies at the first check " if check_path == 'False': >". It's a semantic error, the program does not really check the dir, >it just takes for granted that the dir exists. I tried with 1 before >putting "False" there.. but it did not work so I took the print result >of check_path and substitute 1 with False. But still nothing :-( > >Why does not make the check? I thought that the functions >functionality was clear.. probably is not. > > > >-- >Panagiotis >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From john.corry at ntlword.com Sat Dec 24 18:28:48 2005 From: john.corry at ntlword.com (John Corry) Date: Sat, 24 Dec 2005 17:28:48 -0000 Subject: [Tutor] Printing Message-ID: Hi + Season's Greetings! I have put together a program that queries and modifies a Gadfly database. I have captured my output. I now want to print it to paper. I have written the output to a text file. I have searched the tutor mailing list and used the mailing list advice to get my data into nice looking columns + tables. I am using Python 2.4, Glade 2, pygtk2.8.0 + wxWidgets2.6.1. I have downloaded win32, win32com, Preppy and PIL. I have had a go at using them but can't get them to work. At the moment I can't even print the text file. Is there a good helpguide/FAQ page which deals with printing text files or is there simple code which prints a text file? Thanks, John. From dyoo at hkn.eecs.berkeley.edu Sat Dec 24 20:32:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 24 Dec 2005 11:32:39 -0800 (PST) Subject: [Tutor] Printing In-Reply-To: Message-ID: > I have downloaded win32, win32com, Preppy and PIL. I have had a go at > using them but can't get them to work. At the moment I can't even print > the text file. > > Is there a good helpguide/FAQ page which deals with printing text files > or is there simple code which prints a text file? Hi John, Let's see... ok, found it! Tim Golden has written a small introduction to printing: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html His recommendation is to use the ShellExecute function in win32api to send off documents to your printer. Best of wishes! From kent37 at tds.net Sun Dec 25 03:19:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 24 Dec 2005 21:19:33 -0500 Subject: [Tutor] Printing In-Reply-To: References: Message-ID: <43AE01B5.1080805@tds.net> John Corry wrote: > > Hi + Season's Greetings! > > I have put together a program that queries and modifies a Gadfly database. > I have captured my output. I now want to print it to paper. > > I have written the output to a text file. I have searched the tutor mailing > list and used the mailing list advice to get my data into nice looking > columns + tables. > > I am using Python 2.4, Glade 2, pygtk2.8.0 + wxWidgets2.6.1. wxWidgets has support for printing, though I have never used it. See http://wxwidgets.org/manuals/2.5.3/wx_printingoverview.html#printingoverview Kent From samrobertsmith at gmail.com Sun Dec 25 13:30:34 2005 From: samrobertsmith at gmail.com (linda.s) Date: Sun, 25 Dec 2005 04:30:34 -0800 Subject: [Tutor] is there any tool like "run line or selection" in Pythonwin? Message-ID: <1d987df30512250430n47aec9eek492c8b8ba1bc3956@mail.gmail.com> is there any tool like "run line or selection" in Pythonwin? Thanks! From alan.gauld at freenet.co.uk Sun Dec 25 17:06:17 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 25 Dec 2005 16:06:17 -0000 Subject: [Tutor] Problem with os.access function. [semantic error, if check does not work] References: Message-ID: <016e01c6096d$235bc5a0$0b01a8c0@xp> Take a look at my draft OS topic(click the url below). It will point you at several other functions that will be of use... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm ----- Original Message ----- From: "Panagiotis Atmatzidis" To: "Python Tutor" Sent: Saturday, December 24, 2005 1:20 PM Subject: [Tutor] Problem with os.access function. [semantic error,if check does not work] Hello, I am writing a function in order to check if a directory exists. If exists the functions must do nothing, otherwise must check the users permissions and if it's possible create the dir. Looking at pydoc's httpd I found the module "os" and the function "access". From the http-doc: access(...) access(path, mode) -> 1 if granted, 0 otherwise Use the real uid/gid to test for access to a path. Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to the path. The mode argument can be F_OK to test existence, or the inclusive-OR of R_OK, W_OK, and X_OK. This is my function: def homedirhandle(): path = "/some/dir/" # check the existance of the directory mode = 755 check_path = os.access(path, mode) print check_path if check_path == 'False': print "" print "Directory /some/dir does not exist." print "Trying to create the directory." uid = os.geteuid() print "the uid is ", uid if uid == '0': try: os.mkdir(path, mode) print "" print "The directory has been created." print "" return path except OSError, e: print "" print >>sys.stderr, "The mkdir command failed: %d (%s)" % (e.errno, e.strerror) print "" print "Exiting" sys.exit(1) if check_path == '1': print "" print "The directory /some/dir has been created." print "" return path else: print "Please create the directory /some/dir manually and then re-run vuhalndler." print "Exiting" sys.exit() else: print "" print "The directory already exists." print "" return path Now the problem lies at the first check " if check_path == 'False': ". It's a semantic error, the program does not really check the dir, it just takes for granted that the dir exists. I tried with 1 before putting "False" there.. but it did not work so I took the print result of check_path and substitute 1 with False. But still nothing :-( Why does not make the check? I thought that the functions functionality was clear.. probably is not. -- Panagiotis From bgailer at alum.rpi.edu Sun Dec 25 22:23:31 2005 From: bgailer at alum.rpi.edu (bob) Date: Sun, 25 Dec 2005 13:23:31 -0800 Subject: [Tutor] is there any tool like "run line or selection" in Pythonwin? In-Reply-To: <1d987df30512250430n47aec9eek492c8b8ba1bc3956@mail.gmail.co m> References: <1d987df30512250430n47aec9eek492c8b8ba1bc3956@mail.gmail.com> Message-ID: <7.0.0.16.0.20051225123930.0228bd70@alum.rpi.edu> At 04:30 AM 12/25/2005, linda.s wrote: >is there any tool like "run line or selection" in Pythonwin? Shades of Visual FoxPro? Create a script (I call it testbed.py). Open it in a script window, paste the selection there, hit F5. Since this executes in the main namespace the results will persist. It is fairly easy to use ctrl-a followed by ctrl-v to replace any prior script with the newly copied selection. Then you can play with it in the testbed and put back in the "real" script when you ar happy with it. FWIW before discovering this I would copy/paste into immediate window, and either string the lines together by putting ; at the end, the deleting the return or editing in ... before all continuation lines as follows: Example in script: a = 3 b = 4 print a+b Paste in immediate: >>> a = 3 b = 4 print a+b Edit and execute (need to hit enter twice): >>> a = 3; b = 4; print a+b If compound statements are involved I paste then type ... at the start of the 2nd line, copy that and paste in front of the remaining lines. These operations are fairly quick. Example 2 in script: if a == b: print 'Winner" c = b y = z Paste in immediate: >>> if a == b: print 'Winner" c = b y = z Type ... at left margin of print line and subsequent lines or copy & paste, then execute (need to hit enter twice). These operations are fairly quick. >>> if a == b: ... print 'Winner" ... c = b ... y = z hth Since all these approaches execute in the main namespace their results will persist. From p.atmatzidis at gmail.com Mon Dec 26 12:34:35 2005 From: p.atmatzidis at gmail.com (Panagiotis Atmatzidis) Date: Mon, 26 Dec 2005 13:34:35 +0200 Subject: [Tutor] Problem with os.access function. [semantic error, if check does not work] In-Reply-To: <7.0.0.16.0.20051224092233.0227b968@alum.rpi.edu> References: <7.0.0.16.0.20051224092233.0227b968@alum.rpi.edu> Message-ID: Hello, Thank you both for the tip's and the interesting links. I resolved my problem easily using another function, os.path.isdir(x) which was more specific. Best Regards. On 12/24/05, bob wrote: > At 05:20 AM 12/24/2005, Panagiotis Atmatzidis wrote: > >Hello, > > > >I am writing a function in order to check if a directory exists. If > >exists the functions must do nothing, otherwise must check the users > >permissions and if it's possible create the dir. Looking at pydoc's > >httpd I found the module "os" and the function "access". From the > >http-doc: > > > >access(...) > >access(path, mode) -> 1 if granted, 0 otherwise > > > >Use the real uid/gid to test for access to a path. Note that most > >operations will use the effective uid/gid, therefore this routine can > >be used in a suid/sgid environment to test if the invoking user has the > >specified access to the path. The mode argument can be F_OK to test > >existence, or the inclusive-OR of R_OK, W_OK, and X_OK. > > > >This is my function: > > > >def homedirhandle(): > > path = "/some/dir/" # check the existance of the > >directory > > mode = 755 > > should be mode = 0755 (octal representation) for mkdir. For > access: "The mode argument can be F_OK to test existence, or the > inclusive-OR of R_OK, W_OK, and X_OK." suggests that only 1 digit is expected. > > > check_path = os.access(path, mode) > > print check_path > > if check_path == 'False': > > Should be if check_path == False: > > Or even simpler if not check_path: > > Use print repr(check_path). Then you'd see either True or 'True'. > That would help you see whether check_path is boolean or string. > > > print "" > > print "Directory /some/dir does not exist." > > print "Trying to create the directory." > > uid = os.geteuid() > > print "the uid is ", uid > > if uid == '0': > > I think (not having UNIX access at the moment) that this should be if uid == 0: > > > try: > > os.mkdir(path, mode) > > print "" > > print "The directory has been created." > > print "" > > return path > > except OSError, e: > > print "" > > print >>sys.stderr, "The mkdir command failed: > >%d (%s)" % (e.errno, e.strerror) > > print "" > > print "Exiting" > > sys.exit(1) > > > > if check_path == '1': > > == 1 > > > print "" > > print "The directory /some/dir has been created." > > print "" > > return path > > else: > > print "Please create the directory /some/dir manually and > >then re-run vuhalndler." > > print "Exiting" > > sys.exit() > > else: > > print "" > > print "The directory already exists." > > print "" > > return path > > > >Now the problem lies at the first check " if check_path == 'False': > >". It's a semantic error, the program does not really check the dir, > >it just takes for granted that the dir exists. I tried with 1 before > >putting "False" there.. but it did not work so I took the print result > >of check_path and substitute 1 with False. But still nothing :-( > > > >Why does not make the check? I thought that the functions > >functionality was clear.. probably is not. > > > > > > > >-- > >Panagiotis > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > -- Panagiotis From john.corry at ntlword.com Mon Dec 26 17:52:14 2005 From: john.corry at ntlword.com (John Corry) Date: Mon, 26 Dec 2005 16:52:14 -0000 Subject: [Tutor] Printing In-Reply-To: Message-ID: Thanks for the prompt reply. This is exactly what I am looking for. However, I have tried the code on the page and I can't get it to work. import tempfile import win32api filename = tempfile.mktemp (".txt") open (filename, "w").write ("This is a test") win32api.ShellExecute ( 0, "print", filename, None, ".", 0 ) I am using the Pythoncard code editor and I get the following error: Traceback (most recent call last): File "c:\python24\jhc.py", line12, in ? 0 pywintypes.error: (2, 'ShellExecute', 'The system cannot find the file specified .') I have played about with it and saved it in various places but I can't get it to work. Any suggestions? Do I need to import other modules? Do I need to use Pythonwin? Thanks, John. -----Original Message----- From: tutor-bounces+john.corry=ntlworld.com at python.org [mailto:tutor-bounces+john.corry=ntlworld.com at python.org]On Behalf Of Danny Yoo Sent: 24 December 2005 19:33 To: John Corry Cc: Tutor Subject: Re: [Tutor] Printing > I have downloaded win32, win32com, Preppy and PIL. I have had a go at > using them but can't get them to work. At the moment I can't even print > the text file. > > Is there a good helpguide/FAQ page which deals with printing text files > or is there simple code which prints a text file? Hi John, Let's see... ok, found it! Tim Golden has written a small introduction to printing: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html His recommendation is to use the ShellExecute function in win32api to send off documents to your printer. Best of wishes! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From mosinu at gmail.com Tue Dec 27 08:05:21 2005 From: mosinu at gmail.com (Will Harris) Date: Tue, 27 Dec 2005 02:05:21 -0500 Subject: [Tutor] regex Message-ID: <5faf36700512262305j2a9c5a2cvc18fb3d30ffa8e91@mail.gmail.com> Does anyone see anything that jumps out at them on why these regex strings aren't catching this line: Dec 18 10:04:45 dragon logger: TCPWRAP: SERVICE=sshd@::ffff:192.168.0.1 ,TYPE=ALL_DENY,HOST_ADDRESS=::ffff:195.145.94.75,HOST_INFO=::ffff: 195.145.94.75,HOST_NAME=unknown,USER_NAME=unknown,OTHERINFO= This is the output of a tcpwrapper script I have, I am trying to write a script to parse this and tell me how many times host_address X has been denied access (among many other things). I have it working for the firewall rules just fine, but I am missing something somewhere to catch the string above. Below are the regex expressions I have tried: ------------------ initial regex to find the line and pass it back to the routine to sort all this out. This line works, I believe (least I can get it to print all the entries back to me I am looking for. ----------------------------------------------------------------------------- rc('logger\S*\sTCPWRAP') : self.twist_failure ---------------------------------------------------------------------------- Here is where I seem to run into trouble, none of the regex strings I have used seem to catch and sort out the strings. ---------------------------------------------------------------------------- self.twist_fail_re = rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s') ------------------------------------------------------------------ rc is set as rc = re.compile at the early part of my script. I have tried every combination I can think of for the expression above, below are the couple I still have written down. self.twist_fail_re = rc('SERVICE=(\.)\.TYPE=(\.)\.HOST_ADDRESS=(\.)\.HOST_INFO=(\.)\.USER_NAME=(\.)') self.twist_fail_re = rc('SERVICE=(\S*)\S*TYPE=(\S*)\S*HOST_ADDRESS=(\S*)\S*HOST_INFO=(\S*)\S*USER_NAME=(\S*)') rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s') But for some reason they are not picking up the strings. Any suggestions? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051227/5c8ba3d1/attachment.htm From carroll at tjc.com Tue Dec 27 09:55:37 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 27 Dec 2005 00:55:37 -0800 (PST) Subject: [Tutor] Printing In-Reply-To: Message-ID: On Mon, 26 Dec 2005, John Corry wrote: > Thanks for the prompt reply. This is exactly what I am looking for. > However, I have tried the code on the page and I can't get it to work. ... > Traceback (most recent call last): > File "c:\python24\jhc.py", line12, in ? > 0 > pywintypes.error: (2, 'ShellExecute', 'The system cannot find the file > specified > .') Odd. Works for me. Just for the heck of it, try using a known filename, instead of making a randomly-named one, and try closing the file first: import win32api filename = "testprint.txt" fileobj=open (filename, "w") fileobj.write ("This is a test") fileobj.close() win32api.ShellExecute ( 0, "print", filename, None, ".", 0 ) Then you can confirm at least, that your file is being created. What version python are you using? I'm using activestate's: C:\test\print>python ActivePython 2.4.1 Build 245 (ActiveState Corp.) based on Python 2.4.1 (#65, Mar 30 2005, 09:33:37) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. From dyoo at hkn.eecs.berkeley.edu Tue Dec 27 10:45:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 27 Dec 2005 01:45:19 -0800 (PST) Subject: [Tutor] regex In-Reply-To: <5faf36700512262305j2a9c5a2cvc18fb3d30ffa8e91@mail.gmail.com> Message-ID: > Dec 18 10:04:45 dragon logger: TCPWRAP: SERVICE=sshd@::ffff:192.168.0.1 > ,TYPE=ALL_DENY,HOST_ADDRESS=::ffff:195.145.94.75,HOST_INFO=::ffff: > 195.145.94.75,HOST_NAME=unknown,USER_NAME=unknown,OTHERINFO= Hi Will, Observation: the output above looks comma delimited, at least the stuff after the 'TCPWRAP:' part. > self.twist_fail_re = > rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s') The line given as example doesn't appear to have whitespace in the places that the regular expression expects. It does contain commas as delimiters between the key/value pairs encoded in the line. There's more information on regular expressions here: http://www.amk.ca/python/howto/regex/ that should help you get started. As an aside: the structure of the log line above is simple enough that you might not even need regexes --- regular string methods might just be powerful enough. For example, strings have a 'split()' method to break a string into a list of substrings: ###### >>> 'hello,world,this,is,a,test'.split(",") ['hello', 'world', 'this', 'is', 'a', 'test'] ###### If you have more questions, please feel free to ask. From kent37 at tds.net Tue Dec 27 13:28:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Dec 2005 07:28:10 -0500 Subject: [Tutor] regex In-Reply-To: References: Message-ID: <43B1335A.20008@tds.net> Danny Yoo wrote: >>Dec 18 10:04:45 dragon logger: TCPWRAP: SERVICE=sshd@::ffff:192.168.0.1 >>,TYPE=ALL_DENY,HOST_ADDRESS=::ffff:195.145.94.75,HOST_INFO=::ffff: >>195.145.94.75,HOST_NAME=unknown,USER_NAME=unknown,OTHERINFO= > > > Hi Will, > > Observation: the output above looks comma delimited, at least the stuff > after the 'TCPWRAP:' part. > > >>self.twist_fail_re = >>rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s') > > > The line given as example doesn't appear to have whitespace in the places > that the regular expression expects. It does contain commas as delimiters > between the key/value pairs encoded in the line. Expanding on Danny's comment... \S*\s matches any amount of non-whitespace followed by one whitespace. This doesn't match your sample. It looks like you want to match non-comma followed by comma. For example this will match the first field: SERVICE=[^,]*, Presumably you will want to pull out the value of the field so enclose it in parenthesis to make a group: SERVICE=([^,]*), Another thing I notice about your regex is it doesn't include all the fields in the sample, for example TYPE. If the fields are always the same you can just include them in your regex. If they vary you can try to make the regex skip them, use a different regex for each field, or try Danny's approach of using str.split() to break apart the data. The Regex Demo program that comes with Python is handy for creating and testing regexes. Look in C:\Python24\Tools\Scripts\redemo.py or the equivalent. Kent From jjk_saji at yahoo.com Tue Dec 27 14:07:35 2005 From: jjk_saji at yahoo.com (John Joseph) Date: Tue, 27 Dec 2005 13:07:35 +0000 (GMT) Subject: [Tutor] How to call mysqlcommand in Python , "mysqldump for backup " Message-ID: <20051227130735.52628.qmail@web34815.mail.mud.yahoo.com> Hi I am trying to execute some MySQL commands using some python scripts I want to do a ?mysqldump? of my database ?john? to a file backup.date.sql the normal command to take a dump is mysqldump john > backup.sql I tried python , by importing ?import os? but I am stuck in how to call ?mysqldump? in python and execute it Help and guidance requested Thanks Joseph ___________________________________________________________ NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! http://uk.cars.yahoo.com/ From nephish at xit.net Tue Dec 27 14:27:30 2005 From: nephish at xit.net (nephish) Date: Tue, 27 Dec 2005 07:27:30 -0600 Subject: [Tutor] How to call mysqlcommand in Python , "mysqldump for backup " In-Reply-To: <20051227130735.52628.qmail@web34815.mail.mud.yahoo.com> References: <20051227130735.52628.qmail@web34815.mail.mud.yahoo.com> Message-ID: <1135690050.2389.3.camel@localhost.localdomain> ooh ooh, i know this one, i have python do this for me every day ! target_dir = '/path/to/where/you/want/to/dump' os.system("mysqldump --add-drop-table -c -u user -ppassword database table > "+target_dir+"/table.bak.sql") dont forget the p in front of your password ! hope this helps On Tue, 2005-12-27 at 13:07 +0000, John Joseph wrote: > Hi > I am trying to execute some MySQL commands using > some python scripts > I want to do a ?mysqldump? of my database ?john? to > a file backup.date.sql > the normal command to take a dump is > mysqldump john > backup.sql > > I tried python , by importing > ?import os? > but I am stuck in how to call ?mysqldump? in > python and execute it > Help and guidance requested > Thanks > Joseph > > > > > ___________________________________________________________ > NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! http://uk.cars.yahoo.com/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From w.eakin at gmail.com Tue Dec 27 16:59:03 2005 From: w.eakin at gmail.com (Eakin, W) Date: Tue, 27 Dec 2005 07:59:03 -0800 Subject: [Tutor] code review please Message-ID: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> Hello, Although I've been coding in PHP and ASP and JavaScript for a couple of years now, I'm relatively new to Python. For learning exercises, I'm writing small Python programs that do limited things, but hopefully do them well. The following program takes a text file, reads through it, and any word longer than four characters will have the internal letters scrambled, but the first and last letters of the word will remain unchanged. Here's what happened when I ran the program on a file called example.txt. Before: This is a sample of text that has been scrambled, before and after. After: Tihs is a sapmle of txet taht has been sblrmcead, broefe and aetfr. The code follows, so any comments and/or suggestions as to what I did right or wrong, or what could be done better will be appreciated. thanks, William #!/usr/bin/env python #filename: wScramble.py #filelocation: /home/william/programming/code/python #filedate: 12/25/2005 import sys import random def fileScramble(fileName): newFile = file('scrambled.txt', 'w') newRow = '' for line in fileName: newRow = '' tempList = line.split(' ') for word in tempList: newRow = newRow + ' ' + wordScramble(word) newRow = newRow + '\n' newFile.write(newRow) newFile.close() def wordScramble(word): punctuation = ['.', ',', ':', ';', '(', ')'] if len(word) < 4: return word elif len(word) == 4 and word[-1] in punctuation or word[0] in punctuation: return word elif len(word) == 4: word = word[0] + word[2] + word[1] + word[3] return word else: (fCut, fLetter) = getLetter(word, 0, 'forward') (lCut, lLetter) = getLetter(word, -1, 'back') tempWord = list(word) del tempWord[:fCut + 1] del tempWord[lCut:] random.shuffle(tempWord) middleString = "".join(tempWord) scrambledWord = fLetter + middleString + lLetter return scrambledWord def getLetter(string, number, direction): if direction == 'forward': increment = 1 else: increment = -1 if string[number].isalpha() == True: if direction == 'forward': return (number, string[:number + 1]) else: return (number, string[number:]) elif string[number].isalpha() == False: return getLetter(string, number + increment, direction) if __name__ == "__main__": try: if sys.argv[1].isspace() == True: print "No file was given to the program to process.\n<----------> Program quitting <---------->\n" else: try: f = open(sys.argv[1]) fileScramble(f) f.close() except IOError: print "That file does not exist, or you do not have permission to access it.\n<----------> Program quitting <---------->\n" except IndexError: print "No file was given to the program to process.\n<----------> Program quitting <---------->\n" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051227/7a5e1c2b/attachment.htm From carroll at tjc.com Tue Dec 27 20:19:28 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 27 Dec 2005 11:19:28 -0800 (PST) Subject: [Tutor] Printing In-Reply-To: Message-ID: On Tue, 27 Dec 2005, John Corry wrote: > I am saving the code to c:\python24\jhc2.py > The code creates the file c:\python24\testprint.txt John, I would *very* strongly advise not to store your code in c:\python24 or any subdirectory in it. That is where Python itself lives, and it's very possible that you could create a file with the same name as a Python-supplied file, and the file you create will start getting erroneously used instead of the correct one. I don't know that this is your problem, but it's certainly a factor I would eliminate. Can you tell us what other files, and their names, you may have added there? I have a directory named C:\test where I do my coding. I generally create a subdirectory with some memorable name and work there. For example, for testing your problem out, I have C:\ test\ print\ testpr.py testpr2.py testprint.txt There may be some differences between what's installed in your Python installation and in mine. I'm a big fan of Activestate's ActivePython. It includes most of the Win32-specific stuff you'll need already. You may end up needing to re-install Python if you've put too much into the Python24 directory; if so, I'd suggest you re-install from the Activestate version. It's also free, and made to target Windows. I don't know of any downsides to using it instead of the Windows release from Python.org, and it just works. http://www.activestate.com/Products/ActivePython/?pysbx=1 From dyoo at hkn.eecs.berkeley.edu Tue Dec 27 23:11:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 27 Dec 2005 14:11:30 -0800 (PST) Subject: [Tutor] code review please In-Reply-To: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> Message-ID: Hi William, Here are some constructive comments on the program; if you have questions on any of it, please feel free to ask. > def fileScramble(fileName): We may want to rename "fileName" to something else, as it isn't being treated as a filename, but more like a file-like object. Good names help to clarify programs. I had expected the input here to be a string, and to see it be a file-like object was a little disorienting at first. [within fileScramble() ...] > newFile = file('scrambled.txt', 'w') > newRow = '' > for line in fileName: It's possible that the lines here still have their trailing newlines: you might want to rstrip() them out before further processing. > def wordScramble(word): > punctuation = ['.', ',', ':', ';', '(', ')'] > if len(word) < 4: > return word > elif len(word) == 4 and word[-1] in punctuation or word[0] in > punctuation: The complexity of the elif is a bit high. Do you mean: ((len(word) == 4 and word[-1] in punctuation) or word[0] in punctuation) or do you mean: len(word) == 4 and (word[-1] in punctuation or word[0] in punctuation) Explicit parenthesization is a good idea here, since there are two possible ways of parsing the expression. It's unambiguous to the computer of course, but since it's ambiguous for humans, let's make it explicit what we mean. > def getLetter(string, number, direction): > if direction == 'forward': > increment = 1 > else: > increment = -1 > if string[number].isalpha() == True: The above if statement can be simplified to: if string[number].isalpha(): ... because comparing True to True is a bit redundant. In fact, since either string[number].isalpha() is True or it isn't, this allows us simplify the block: if string[number].isalpha() == True: ... elif string[number].isalpha() == False: ... so that we use a simpler if/else: if string[number].isalpha(): ... else: ... Looking into the __main__, I see: > try: > f = open(sys.argv[1]) > fileScramble(f) > f.close() > except IOError: > print "That file does not exist, or you do not have In the exception handler, we may want to also show the message of the exception too, just in case another kind of IOError has occurred. According to: http://www.python.org/doc/lib/module-exceptions.html we can grab at the 'errno' and 'strerror' attributes of the exception object to display more detailed information --- I'd recommend including those in the error output, since that's useful debugging information. Similarly, the try/except for IndexError seems too pervasive: rather than wrap it around the whole program, we may want to limit its extent to just around the sys.argv access. Otherwise, any other IndexError has the potential of being misattributed. Much of the program does indexing of some sort, so that's why this concerns me. Alternatively, doing the explicit length check: if not sys.argv[1:]: print some kind of usage message raise SystemExit might be sufficient. Unless we really want to hide errors from the user, I'd avoid the exception handlers altogether: if bad things happen, the default exception handler gives a fairly good stack trace that aids debugging. But if we do want to handle the exceptions manually, we should try to make sure that useful information is preserved in the error messages: it's a terrible thing to get an error message that says "Something bad happened." when we can do much better. *grin* I hope this critique helps! From bgailer at alum.rpi.edu Wed Dec 28 01:47:36 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 27 Dec 2005 16:47:36 -0800 Subject: [Tutor] Printing In-Reply-To: References: Message-ID: <7.0.0.16.0.20051227164453.024849f8@alum.rpi.edu> At 08:52 AM 12/26/2005, John Corry wrote: >Thanks for the prompt reply. This is exactly what I am looking for. >However, I have tried the code on the page and I can't get it to work. > >import tempfile >import win32api > >filename = tempfile.mktemp (".txt") >open (filename, "w").write ("This is a test") >win32api.ShellExecute ( > 0, > "print", > filename, > None, > ".", > 0 >) Also beware that the file must have an extension associated with an application that recognizes the print command. e.g. if the file is named foo.doc and .doc is registered as belonging to MS Word, then this will open MSword, open the file, print the file and close Word. It is the equivalent of right-clicking the file in the explorer and then choosing Print from the context menu. >I am using the Pythoncard code editor and I get the following error: > >Traceback (most recent call last): > File "c:\python24\jhc.py", line12, in ? > 0 >pywintypes.error: (2, 'ShellExecute', 'The system cannot find the file >specified >.') > >I have played about with it and saved it in various places but I can't get >it to work. Any suggestions? Do I need to import other modules? Do I need >to use Pythonwin? > >Thanks, > >John. > >-----Original Message----- >From: tutor-bounces+john.corry=ntlworld.com at python.org >[mailto:tutor-bounces+john.corry=ntlworld.com at python.org]On Behalf Of >Danny Yoo >Sent: 24 December 2005 19:33 >To: John Corry >Cc: Tutor >Subject: Re: [Tutor] Printing > > > > > > I have downloaded win32, win32com, Preppy and PIL. I have had a go at > > using them but can't get them to work. At the moment I can't even print > > the text file. > > > > Is there a good helpguide/FAQ page which deals with printing text files > > or is there simple code which prints a text file? > >Hi John, > > >Let's see... ok, found it! Tim Golden has written a small introduction to >printing: > > http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html > >His recommendation is to use the ShellExecute function in win32api to send >off documents to your printer. > > > >Best of wishes! > >_______________________________________________ >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 ml.cyresse at gmail.com Wed Dec 28 03:55:40 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 28 Dec 2005 15:55:40 +1300 Subject: [Tutor] Sets and Python; new shiny tool syndrome? Message-ID: Hi all, I just tried out sets for the first time, and I'm finding multiple uses for them, particularly for replacing and simplifying what would normally be one or two list comprehensions i.e. def parseKws(self, kw_data): ignoreSet = set(['import', 'from', 'as', ' ', '']) kws = set([]) for line in kw_data: line = line.rstrip("\n") if "," in line: line = line.replace(",", " ") if ";" in line: line = line.replace(";", " ") l = set(line.split(" ")) k = l.difference(ignoreSet) kws.update(k) instead of l = line.split(" ") k = [ item for item in l if not (item in ignoreSet or item in kws) ] kws.extend(k) (Above just gets module names from various import statements.) However, I'm reminded of the joke about you can tell what chapter someone reading the Patterns book by the Gang of Four is up to by what new pattern they're trying to use the next day, no matter the problem. Are there any drawbacks to sets that I need to watch out for? Regards, Liam Clarke From dyoo at hkn.eecs.berkeley.edu Wed Dec 28 04:10:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 27 Dec 2005 19:10:21 -0800 (PST) Subject: [Tutor] Sets and Python; new shiny tool syndrome? In-Reply-To: Message-ID: > I just tried out sets for the first time, and I'm finding multiple uses > for them, particularly for replacing and simplifying what would normally > be one or two list comprehensions i.e. > > def parseKws(self, kw_data): > ignoreSet = set(['import', 'from', 'as', ' ', '']) > kws = set([]) > for line in kw_data: > line = line.rstrip("\n") > if "," in line: line = line.replace(",", " ") > if ";" in line: line = line.replace(";", " ") Hi Liam, Quick comment: the two if statements there can be simplified by just doing the replacement straight-out: ############################# line = line.replace(",", " ") line = line.replace(";", " ") ############################# The reason is that if those characters aren't present, no harm is done. But looking at the code, I'm curious: it looks like you're trying to tokenize the keywords out of Python source? If so, you may want to look at the 'tokenize' module: http://www.python.org/doc/lib/module-tokenize.html as it'll handle some of the especially tricky cases like handling string literals. > However, I'm reminded of the joke about you can tell what chapter > someone reading the Patterns book by the Gang of Four is up to by what > new pattern they're trying to use the next day, no matter the problem. > > Are there any drawbacks to sets that I need to watch out for? Use them when they're appropriate, and don't use them when they're not. *grin* It really is problem sensitive: if order matters, then sets probably aren't appropriate. But sets are such a pervasive concept that few problems don't provide opportunities to take advantage of them. Happy holidays to you! From Hans.Dushanthakumar at navman.com Wed Dec 28 04:38:29 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Wed, 28 Dec 2005 16:38:29 +1300 Subject: [Tutor] Writing/reading lists to a file Message-ID: <5667508E43F1B740BCFA57FF46E3530002D9E746@nav-akl-exch-c.newton.navman.com> Hi, Is there any easy way of writing lists to a file and more importantly, reading it back as a list of lists rather than as a list of strings. Eg: >>> t = ["t1", "PASS", 31] >>> f = open("pass.txt","a+") >>> f.write(str(t) + "\n") >>> f.write(str(t) + "\n") >>> f.close() At this stage, the file contains two lines. Now, if I use the readlines() function to read it back, heres what I get: >>> f = open("pass.txt","r+") >>> r = f.readlines() >>> r ["['t1', 'PASS', 31]\n", "['t1', 'PASS', 31]\n", "['t1', 'PASS', 31]\n"] >>> r[0] "['t1', 'PASS', 31]\n" So, r[0] is now a string. Is there ant direct way of extracting the list from this string? Or alternatively, can I read the file as a list of lists rather than list of strings (which is what readlines() appears to do). Thanks, Hans From ml.cyresse at gmail.com Wed Dec 28 04:53:54 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 28 Dec 2005 16:53:54 +1300 Subject: [Tutor] Sets and Python; new shiny tool syndrome? In-Reply-To: References: Message-ID: On 12/28/05, Danny Yoo wrote: > > > I just tried out sets for the first time, and I'm finding multiple uses > > for them, particularly for replacing and simplifying what would normally > > be one or two list comprehensions i.e. > > > > def parseKws(self, kw_data): > > ignoreSet = set(['import', 'from', 'as', ' ', '']) > > kws = set([]) > > for line in kw_data: > > line = line.rstrip("\n") > > if "," in line: line = line.replace(",", " ") > > if ";" in line: line = line.replace(";", " ") > > Hi Liam, > > Quick comment: the two if statements there can be simplified by just doing > the replacement straight-out: > > ############################# > line = line.replace(",", " ") > line = line.replace(";", " ") > ############################# > > The reason is that if those characters aren't present, no harm is done. > > > But looking at the code, I'm curious: it looks like you're trying to > tokenize the keywords out of Python source? If so, you may want to look > at the 'tokenize' module: > > http://www.python.org/doc/lib/module-tokenize.html > > as it'll handle some of the especially tricky cases like handling string > literals. Thanks Danny, I'm writing a little database to stash my code snippets in, and my thinking tends to go along the lines of "That code I did that use imaplib..." so I'm linking module names to the stored files; that said, I'll use tokenizer next time I try and write a wxPython frontend for IronPython and save myself a lot of grief! > > However, I'm reminded of the joke about you can tell what chapter > > someone reading the Patterns book by the Gang of Four is up to by what > > new pattern they're trying to use the next day, no matter the problem. > > > > Are there any drawbacks to sets that I need to watch out for? > > Use them when they're appropriate, and don't use them when they're not. > *grin* > > It really is problem sensitive: if order matters, then sets probably > aren't appropriate. But sets are such a pervasive concept that few > problems don't provide opportunities to take advantage of them. Good to know; I'm very glad that they're part of Python. They're making my job a whole lot simpler. > Happy holidays to you! And likewise. :) From ml.cyresse at gmail.com Wed Dec 28 04:59:24 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 28 Dec 2005 16:59:24 +1300 Subject: [Tutor] Writing/reading lists to a file In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002D9E746@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E3530002D9E746@nav-akl-exch-c.newton.navman.com> Message-ID: Hi Hans, If you're looking to store lists as lists, may I recommend the cPickle module? It's good for most times when you want to store an object as an object. >>> import cPickle >>> a = [1,2,3] >>> b = [4,5,6] >>> c = [7,8,9] >>> d = [a,b,c] >>> d [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> print d[0][1] 2 >>> f = file("filetosaveto","wb") >>> cPickle.dump(d, f) >>> f.close() >>> del d >>> f = file("filetosaveto","rb") >>> newD = cPickle.load(f) >>> f.close() >>> newD [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> newD[0][1] 2 Regards, Liam Clarke On 12/28/05, Hans Dushanthakumar wrote: > > Hi, > Is there any easy way of writing lists to a file and more > importantly, reading it back as a list of lists rather than as a list of > strings. > > Eg: > > >>> t = ["t1", "PASS", 31] > >>> f = open("pass.txt","a+") > >>> f.write(str(t) + "\n") > >>> f.write(str(t) + "\n") > >>> f.close() > > At this stage, the file contains two lines. > > Now, if I use the readlines() function to read it back, heres what I > get: > >>> f = open("pass.txt","r+") > >>> r = f.readlines() > >>> r > ["['t1', 'PASS', 31]\n", "['t1', 'PASS', 31]\n", "['t1', 'PASS', 31]\n"] > >>> r[0] > "['t1', 'PASS', 31]\n" > > So, r[0] is now a string. Is there ant direct way of extracting the list > from this string? > > Or alternatively, can I read the file as a list of lists rather than > list of strings (which is what readlines() appears to do). > > Thanks, > Hans > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Dec 28 05:29:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Dec 2005 23:29:12 -0500 Subject: [Tutor] code review please In-Reply-To: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> References: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> Message-ID: <43B21498.3020204@tds.net> Eakin, W wrote: > The code follows, so any comments and/or suggestions as to what I did > right or wrong, or what could be done better will be appreciated. > def fileScramble(fileName): > newFile = file('scrambled.txt', 'w') > newRow = '' > for line in fileName: > newRow = '' > tempList = line.split(' ') > for word in tempList: > newRow = newRow + ' ' + wordScramble(word) > newRow = newRow + '\n' > newFile.write(newRow) This seem pretty verbose to me. Using tempList doesn't IMO add anything, it might as well be for word in line.split(' '): or for word in line.split(): since you probably want to split on tabs also and this will strip the trailing newlines as a bonus. I usually prefer a list comprehension to an accumulation loop when possible so I would actually write it as newWords = [ wordScramble(word) for word in line.split() ] newRow = ' '.join(newWords) + '\n' or even newRow = ' '.join(wordScramble(word) for word in line.split()) + '\n' though that might be a little too terse for easy comprehension. > newFile.close() > > > def wordScramble(word): > punctuation = ['.', ',', ':', ';', '(', ')'] > if len(word) < 4: > return word > elif len(word) == 4 and word[-1] in punctuation or word[0] in > punctuation: > return word > elif len(word) == 4: > word = word[0] + word[2] + word[1] + word[3] > return word Rather than repeating the test for len(word) == 4, I would write elif len(word) == 4: if word[-1] in punctuation or word[0] in punctuation: return word else: word = word[0] + word[2] + word[1] + word[3] return word This also breaks up the long conditional that Danny complained about. > else: > (fCut, fLetter) = getLetter(word, 0, 'forward') > (lCut, lLetter) = getLetter(word, -1, 'back') > tempWord = list(word) > del tempWord[:fCut + 1] > del tempWord[lCut:] I think this is the same as tempWord = list(word[fCut+1:lCut]) > random.shuffle(tempWord) > middleString = "".join(tempWord) > scrambledWord = fLetter + middleString + lLetter > return scrambledWord > > > def getLetter(string, number, direction): I found it very hard to understand what this function does. A better name and a comment would help a lot. You might consider having separate getFirstLetter() and getLastLetter() since much of getLetter() is taken up with the conditionals and compensating for trying to do two things. def getFirstLetter(string, number=0): if string[number].isalpha() == True: return (number, string[:number + 1]) else: return getFirstLetter(string, number + 1) Even better would be to use a simple loop to find the index of the first letter, and split the string into three sections in the caller. BTW thinking of writing this as a loop brings to mind some problems - what will your program do with 'words' such as 555-1212 or "Ha!" ? > if direction == 'forward': > increment = 1 > else: > increment = -1 > if string[number].isalpha() == True: > if direction == 'forward': > return (number, string[:number + 1]) > else: > return (number, string[number:]) > elif string[number].isalpha() == False: > return getLetter(string, number + increment, direction) > > > if __name__ == "__main__": > try: > if sys.argv[1].isspace() == True: > print "No file was given to the program to > process.\n<----------> Program quitting <---------->\n" > else: > try: > f = open(sys.argv[1]) > fileScramble(f) > f.close() > except IOError: > print "That file does not exist, or you do not have > permission to access it.\n<----------> Program quitting <---------->\n" > except IndexError: > print "No file was given to the program to > process.\n<----------> Program quitting <---------->\n" > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From broek at cc.umanitoba.ca Wed Dec 28 09:05:38 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 28 Dec 2005 02:05:38 -0600 Subject: [Tutor] code review please In-Reply-To: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> References: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> Message-ID: <43B24752.5090309@cc.umanitoba.ca> Eakin, W said unto the world upon 27/12/05 09:59 AM: > Hello, > Although I've been coding in PHP and ASP and JavaScript for a couple of > years now, I'm relatively new to Python. For learning exercises, I'm writing > small Python programs that do limited things, but hopefully do them well. > > The following program takes a text file, reads through it, and any word > longer than four characters will have the internal letters scrambled, but > the first and last letters of the word will remain unchanged. Here's what > happened when I ran the program on a file called example.txt. > > Before: > This is a sample of text that has been scrambled, before and after. > > After: > Tihs is a sapmle of txet taht has been sblrmcead, broefe and aetfr. > > The code follows, so any comments and/or suggestions as to what I did right > or wrong, or what could be done better will be appreciated. > > thanks, > William Hi William, I coded up an approach; no guarantees that it is anywhere near optimal :-) I didn't bother with the file I/O portions. Also, it respects internal punctuation in compound-words and the like. It does not respect extra white-space in the sense that "A cat" and "A cat" produce identical output. Best, Brian vdB import random from string import punctuation tstring = ''' This is my test string for the scramble_words function. It contains lots of punctuation marks like ')', and '?'--well, not lots: instead, enough! Here's what happens when one occurs mid-word: punct#uation.''' def scramble_words(a_string): '''returns a_string with all internal substrings of words randomized The scramble_words function respects punctuation in that a word is a maximal string with neither whitespace nor characters from punctuation. Each word is scrambled in the sense that the characters excepting the first and last character are randomized. ''' output = [] for sequence in a_string.split(): chunks = punctuation_split(sequence) # appending the joined chunks prevents spurious spaces # around punctuation marks output.append(''.join([_scramble_word(x) for x in chunks])) output = ' '.join(output) return output def punctuation_split(sequence): '''returns list of character sequences separating punctuation characters''' for mark in punctuation: sequence = sequence.replace(mark, ' %s ' %mark) return sequence.split(' ') def _scramble_word(word): '''returns word with its internal substring randomized''' if len(word) < 4: return word middle = list(word[1:-1]) random.shuffle(middle) return ''.join((word[0], ''.join(middle), word[-1])) a = scramble_words(tstring) print a From mosinu at gmail.com Wed Dec 28 10:00:42 2005 From: mosinu at gmail.com (Will Harris) Date: Wed, 28 Dec 2005 04:00:42 -0500 Subject: [Tutor] regex In-Reply-To: <43B1335A.20008@tds.net> References: <43B1335A.20008@tds.net> Message-ID: <5faf36700512280100x6a06caf5w6412fbf7bdadbaea@mail.gmail.com> Thanks, this helped out. I hadn't thought of trying to use strings for this, I will give that a shot. I removed the TYPE field from the regex thinking that might have been causing a problem and forgot to add it back to my regex. On 12/27/05, Kent Johnson wrote: > > Danny Yoo wrote: > >>Dec 18 10:04:45 dragon logger: TCPWRAP: SERVICE=sshd@::ffff:192.168.0.1 > >>,TYPE=ALL_DENY,HOST_ADDRESS=::ffff:195.145.94.75,HOST_INFO=::ffff: > >>195.145.94.75,HOST_NAME=unknown,USER_NAME=unknown,OTHERINFO= > > > > > > Hi Will, > > > > Observation: the output above looks comma delimited, at least the stuff > > after the 'TCPWRAP:' part. > > > > > >>self.twist_fail_re = > > >>rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s') > > > > > > The line given as example doesn't appear to have whitespace in the > places > > that the regular expression expects. It does contain commas as > delimiters > > between the key/value pairs encoded in the line. > > Expanding on Danny's comment... > > \S*\s matches any amount of non-whitespace followed by one whitespace. > This doesn't match your sample. It looks like you want to match > non-comma followed by comma. For example this will match the first field: > SERVICE=[^,]*, > > Presumably you will want to pull out the value of the field so enclose > it in parenthesis to make a group: > > SERVICE=([^,]*), > > Another thing I notice about your regex is it doesn't include all the > fields in the sample, for example TYPE. If the fields are always the > same you can just include them in your regex. If they vary you can try > to make the regex skip them, use a different regex for each field, or > try Danny's approach of using str.split() to break apart the data. > > The Regex Demo program that comes with Python is handy for creating and > testing regexes. Look in C:\Python24\Tools\Scripts\redemo.py or the > equivalent. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051228/732547d1/attachment.htm From jjk_saji at yahoo.com Wed Dec 28 10:03:56 2005 From: jjk_saji at yahoo.com (John Joseph) Date: Wed, 28 Dec 2005 09:03:56 +0000 (GMT) Subject: [Tutor] How to call mysqlcommand in Python , "mysqldump for backup " In-Reply-To: <1135690050.2389.3.camel@localhost.localdomain> Message-ID: <20051228090356.61215.qmail@web34813.mail.mud.yahoo.com> --- nephish wrote: > ooh ooh, i know this one, i have python do this for > me every day ! > > target_dir = '/path/to/where/you/want/to/dump' > > os.system("mysqldump --add-drop-table -c -u user > -ppassword database > table > "+target_dir+"/table.bak.sql") > > dont forget the p in front of your password ! > > hope this helps > > Hi it helped me a lot , I did my script like this for backing my zabbix database import os, time # difine the target directory target_dir = '/home/john/backup/z-b-weekly/zabbix' # in the formar year-month-day-hours-minute-secound # uses time module today = time.strftime('%Y-%m-%d-%H-%M-%S') # For testing purpose only I had kept %M %S , we can remove it later now = target_dir + today os.system("mysqldump -u root -pjohn zabbix > "+now+" " ) Thanks A LOT Joseph ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From justin.mailinglists at gmail.com Wed Dec 28 10:05:33 2005 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 28 Dec 2005 17:05:33 +0800 Subject: [Tutor] threaded multipart FTP download Message-ID: <3c6718980512280105v1e4fdc12q5fa0e0803a7e42a1@mail.gmail.com> Greetings, Did not think I could post my code here as it's a bit long so I placed it in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465531 Can some of you have a look and post comments, suggestions, alternatives? Thanks. BTW, the recipe is sufficient for our needs at the moment but I am sure there must be better methods than what I used. From kent37 at tds.net Wed Dec 28 13:55:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Dec 2005 07:55:04 -0500 Subject: [Tutor] code review please In-Reply-To: <43B21498.3020204@tds.net> References: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> <43B21498.3020204@tds.net> Message-ID: <43B28B28.2000805@tds.net> Kent Johnson wrote: > BTW thinking of writing this as a loop brings to mind some problems - > what will your program do with 'words' such as 555-1212 or "Ha!" ? Hmm, on reflection I don't thing "Ha!" will be a problem, but a 'word' with no letters will cause an IndexError. Your test for 4 letters is really misplaced. What you want to find is words that have only two letters to scramble. I would put a test right where you call random.shuffle() to see if tempWord is longer than 2. In fact you might put the whole test and shuffle bit in a separate function. Kent From RPhillips at engineer.co.summit.oh.us Wed Dec 28 13:34:29 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Wed, 28 Dec 2005 07:34:29 -0500 Subject: [Tutor] Printing Message-ID: >>> "John Corry" < john.corry at ntlword.com > 12/24/2005 12:28 PM >>> Hi + Season's Greetings! I have put together a program that queries and modifies a Gadfly database. I have captured my output. I now want to print it to paper. I have written the output to a text file. I have searched the tutor mailing list and used the mailing list advice to get my data into nice looking columns + tables. I am using Python 2.4, Glade 2, pygtk2.8.0 + wxWidgets2.6.1. I have downloaded win32, win32com, Preppy and PIL. I have had a go at using them but can't get them to work. At the moment I can't even print the text file. Is there a good helpguide/FAQ page which deals with printing text files or is there simple code which prints a text file? Thanks, John. >>>> You might want to look at karrigell ( http://karrigell.sourceforge.net/ ) and consider making your output an html text file, styled with css, that you can view/print using the browser. I think karrigell is simple for desktop apps - - certainly simpler than wxWidgets, etc. TurboGears ( http://www.turbogears.org ) is more oriented toward a full website. Both frameworks are built on CherryPy, which is coming on strong as a full-featured, lightweight 'Pythonic" server. I like to use the browser for output because it does so much of the formatting for you and it's cross-platform, and I like using a framework because if you ever want to use your program over the web, you're nearly done. Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051228/81f6c752/attachment.htm From kent37 at tds.net Wed Dec 28 14:00:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Dec 2005 08:00:22 -0500 Subject: [Tutor] code review please In-Reply-To: References: Message-ID: <43B28C66.5050903@tds.net> Danny Yoo wrote: > Similarly, the try/except for IndexError seems too pervasive: rather than > wrap it around the whole program, we may want to limit its extent to just > around the sys.argv access. Otherwise, any other IndexError has the > potential of being misattributed. Much of the program does indexing of > some sort, so that's why this concerns me. > > Alternatively, doing the explicit length check: > > if not sys.argv[1:]: > print some kind of usage message > raise SystemExit > > might be sufficient. > > > Unless we really want to hide errors from the user, I'd avoid the > exception handlers altogether: if bad things happen, the default exception > handler gives a fairly good stack trace that aids debugging. > > But if we do want to handle the exceptions manually, we should try to make > sure that useful information is preserved in the error messages: it's a > terrible thing to get an error message that says "Something bad happened." > when we can do much better. *grin* I agree with Danny that in this case there is no need to catch the exceptions - just let the default exception handler do its thing. If you *do* want to handle the exceptions yourself, a good principle is to put the try / except around the least amount of code possible - just the lines that may generate the expected exception. This prevents the except clause from hiding unexpected exceptions. An easy way to do this is to use try / except / else. The else clause is only executed if no exception was caught by the except clause. In your case you could write try: fname = sys.argv[1] except IndexError: # report the error as you like else: # normal processing goes here Kent From kent37 at tds.net Wed Dec 28 14:06:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Dec 2005 08:06:03 -0500 Subject: [Tutor] code review please In-Reply-To: <43B24752.5090309@cc.umanitoba.ca> References: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> <43B24752.5090309@cc.umanitoba.ca> Message-ID: <43B28DBB.1010808@tds.net> Brian van den Broek wrote: > def punctuation_split(sequence): > '''returns list of character sequences separating punctuation > characters''' > for mark in punctuation: > sequence = sequence.replace(mark, ' %s ' %mark) > return sequence.split(' ') You should look at re.split(). Kent From nephish at xit.net Wed Dec 28 14:20:36 2005 From: nephish at xit.net (nephish) Date: Wed, 28 Dec 2005 07:20:36 -0600 Subject: [Tutor] How to call mysqlcommand in Python , "mysqldump for backup " In-Reply-To: <20051228090356.61215.qmail@web34813.mail.mud.yahoo.com> References: <20051228090356.61215.qmail@web34813.mail.mud.yahoo.com> Message-ID: <1135776036.2690.0.camel@bitsbam.com> Glad to help, glad you got it working too.! shawn On Wed, 2005-12-28 at 09:03 +0000, John Joseph wrote: > --- nephish wrote: > > > ooh ooh, i know this one, i have python do this for > > me every day ! > > > > target_dir = '/path/to/where/you/want/to/dump' > > > > os.system("mysqldump --add-drop-table -c -u user > > -ppassword database > > table > "+target_dir+"/table.bak.sql") > > > > dont forget the p in front of your password ! > > > > hope this helps > > > > > > Hi it helped me a lot , > I did my script like this for backing my zabbix > database > > import os, time > # difine the target directory > target_dir = '/home/john/backup/z-b-weekly/zabbix' > > # in the formar year-month-day-hours-minute-secound > # uses time module > today = time.strftime('%Y-%m-%d-%H-%M-%S') > > # For testing purpose only I had kept %M %S , we can > remove it later > now = target_dir + today > > os.system("mysqldump -u root -pjohn zabbix > > "+now+" " ) > Thanks A LOT > Joseph > > > > > > > ___________________________________________________________ > To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From jonasmg at softhome.net Wed Dec 28 15:18:15 2005 From: jonasmg at softhome.net (jonasmg@softhome.net) Date: Wed, 28 Dec 2005 07:18:15 -0700 Subject: [Tutor] matching a file Message-ID: Hi! I would to working with some files. But I have to using a regular expression with one of them: for file in [glob.glob('/etc/env.d/[0-9]*foo'), '/etc/bar']: glob returns a list so i'm supposed that i would that convert it into a string. Is it correct? Thanks for your help From kent37 at tds.net Wed Dec 28 15:36:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Dec 2005 09:36:09 -0500 Subject: [Tutor] matching a file In-Reply-To: References: Message-ID: <43B2A2D9.5050606@tds.net> jonasmg at softhome.net wrote: > Hi! > > I would to working with some files. But I have to using a regular expression > with one of them: > > for file in [glob.glob('/etc/env.d/[0-9]*foo'), '/etc/bar']: > > glob returns a list so i'm supposed that i would that convert it into a > string. glob.glob() returns a list of file paths that match your path spec. You are embedding this list in another list. The result of [glob.glob('/etc/env.d/[0-9]*foo'), '/etc/bar'] will be a list something like this: [ [ '/etc/env.d/123foo', '/etc/env.d/456foo' ], '/etc/bar' ] Iterating over this list will bind the name 'file' to the entire first list, then to '/etc/bar'. The solution is to create a flat list instead of a nested list. Try for file in glob.glob('/etc/env.d/[0-9]*foo') + ['/etc/bar']: Kent PS 'file' is the name of a built-in function, it would be better to choose a different name for your variable. From pkraus at pelsupply.com Wed Dec 28 16:18:13 2005 From: pkraus at pelsupply.com (Paul Kraus) Date: Wed, 28 Dec 2005 10:18:13 -0500 Subject: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list. Message-ID: <200512281018.13486.pkraus@pelsupply.com> I am trying to build a data structure that would be a dictionary of a dictionary of a list. In Perl I would build the structure like so $dictionary{key1}{key2}[0] = X I would iterate like so ... foreach my $key1 ( sort keys %dictionary ) { foreach my $key2 ( sort keys %{$dictionary{$key1}} ) { foreach my $element ( @{$dictionary{$key1}{$key2} } ) { print "$key1 => $key2 => $element\n"; } } } Sorry for the Perl reference but its the language I am coming from. I use data structures like this all the time. I don't always iterate them like this but If i can learn to build these and move through them in python then a good portion of the Perl apps I am using can be ported. Playing around I have come up with this but have no clue how to iterate over it or if its the best way. It seems "clunky" but it is most likely my lack of understanding. dictionary[(key1,key2)]=[ a,b,c,d,e,f,g ... ] This i think gives me a dictionary with two keys ( not sure how to doing anything usefull with it though) and a list. Now I am not sure how I can assign one element at a time to the list. here is the pseudo code. read text file. split line from text file into list of fields. One of the fields contains the date. Split the date into two fields Year and Month/Period. Build data structure that is a dictionary based on year, based on period, based on item code then store/increment the units sold based on period. dictionary[(year,period)] = [ jan, feb, mar, apr, may, jun, july, aug, sep, oct, nov ,dec] I would prefer to have the months just be an array index 0 through 11 and when it reads the file it increments the number contained there. TIA, -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From pkraus at pelsupply.com Wed Dec 28 17:13:28 2005 From: pkraus at pelsupply.com (Paul Kraus) Date: Wed, 28 Dec 2005 11:13:28 -0500 Subject: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list. In-Reply-To: <200512281018.13486.pkraus@pelsupply.com> References: <200512281018.13486.pkraus@pelsupply.com> Message-ID: <200512281113.28454.pkraus@pelsupply.com> On Wednesday 28 December 2005 10:18 am, Paul Kraus wrote: > I am trying to build a data structure that would be a dictionary of a > dictionary of a list. > > In Perl I would build the structure like so $dictionary{key1}{key2}[0] = X > I would iterate like so ... > foreach my $key1 ( sort keys %dictionary ) { > foreach my $key2 ( sort keys %{$dictionary{$key1}} ) { > foreach my $element ( @{$dictionary{$key1}{$key2} } ) { > print "$key1 => $key2 => $element\n"; > } > } > } > Here is the code that I used. Its functional and it works but there has got to be some better ways to do a lot of this. Transversing the data structure still seems like I have to be doing it the hard way. The input data file has fixed width fields that are delimited by pipe. So depending on the justification for each field it will either have leading or ending whitespace. TIA, Paul #!/usr/bin/python ############################# ## Paul D. Kraus - 2005-12-27 ## parse.py - Parse Text File ## Pipe deliminted '|' ############################# ## Fields: CustCode [0] ## : OrdrType [1] ## : OrdrReturn [2] ## : State [3] ## : QtyShipped [4] ## : VendCode [5] ## : InvoiceDate [7] ############################# import re import string results = {} def format_date(datestring): (period,day,year) = map(int,datestring.split('/') ) period += 2 if period == 13: period = 1; year += 1 if period == 14: period = 2; year += 1 if year > 80: year = '19%02d' % year else: year = '20%02d' % year return (year,period) def format_qty(qty,credit,oreturn): qty = float(qty) if credit == 'C' or oreturn == 'Y': return qty * -1 else: return qty textfile = open('orders.txt','r') for line in textfile: fields = map( string.strip, line.split( '|' ) ) fields[4] = format_qty(fields[ 4 ],fields[ 1 ], fields[ 2 ] ) (year, period) = format_date( fields[7] ) for count in range(12): if count == period: if results.get( ( year, fields[6], count), 0): results[ year,fields[6], count] += fields[4] else: results[ year,fields[6],count] = fields[4] sortedkeys = results.keys() sortedkeys.sort() for keys in sortedkeys: res_string = keys[0]+'|'+keys[1] for count in range(12): if results.get((keys[0],keys[1],count),0): res_string += '|'+str(results[keys[0],keys[1],count]) else: res_string += '|0' print res_string From kent37 at tds.net Wed Dec 28 17:30:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Dec 2005 11:30:31 -0500 Subject: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list. In-Reply-To: <200512281018.13486.pkraus@pelsupply.com> References: <200512281018.13486.pkraus@pelsupply.com> Message-ID: <43B2BDA7.9030208@tds.net> Paul Kraus wrote: > I am trying to build a data structure that would be a dictionary of a > dictionary of a list. > > In Perl I would build the structure like so $dictionary{key1}{key2}[0] = X > I would iterate like so ... > foreach my $key1 ( sort keys %dictionary ) { > foreach my $key2 ( sort keys %{$dictionary{$key1}} ) { > foreach my $element ( @{$dictionary{$key1}{$key2} } ) { > print "$key1 => $key2 => $element\n"; > } > } > } > > Sorry for the Perl reference but its the language I am coming from. I use data > structures like this all the time. I don't always iterate them like this but > If i can learn to build these and move through them in python then a good > portion of the Perl apps I am using can be ported. > > Playing around I have come up with this but have no clue how to iterate over > it or if its the best way. It seems "clunky" but it is most likely my lack of > understanding. > > dictionary[(key1,key2)]=[ a,b,c,d,e,f,g ... ] > > This i think gives me a dictionary with two keys ( not sure how to doing > anything usefull with it though) and a list. This gives you a dict whose keys are the tuple (key1, key2). Since tuples sort in lexicographical order you could print this out sorted by key1, then key2 with for (key1, key2), value in sorted(dictionary.iteritems()): for element in value: print key1, '=>', key2, '=>', element (Wow, Python code that is shorter than the equivalent Perl? There must be some mistake! ;) > > Now I am not sure how I can assign one element at a time to the list. Assuming the list already has an element 0, use dictionary[(key1, key2)][0] = X Python lists don't create new elements on assignment (I think Perl lists do this?) so for example dictionary[(key1, key2)][10] = X will fail if the list doesn't already have 11 elements or more. You can use list.append() or pre-populate the list with default values depending on your application. Kent From kent37 at tds.net Wed Dec 28 17:45:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Dec 2005 11:45:43 -0500 Subject: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list. In-Reply-To: <200512281113.28454.pkraus@pelsupply.com> References: <200512281018.13486.pkraus@pelsupply.com> <200512281113.28454.pkraus@pelsupply.com> Message-ID: <43B2C137.7090504@tds.net> Paul Kraus wrote: > Here is the code that I used. Its functional and it works but there has got to > be some better ways to do a lot of this. Transversing the data structure > still seems like I have to be doing it the hard way. > > The input data file has fixed width fields that are delimited by pipe. > So depending on the justification for each field it will either have leading > or ending whitespace. > ############################# > import re > import string > results = {} > def format_date(datestring): > (period,day,year) = map(int,datestring.split('/') ) > period += 2 > if period == 13: period = 1; year += 1 > if period == 14: period = 2; year += 1 if period > 12: period -= 12; year += 1 > if year > 80: > year = '19%02d' % year > else: > year = '20%02d' % year > return (year,period) > > def format_qty(qty,credit,oreturn): > qty = float(qty) > if credit == 'C' or oreturn == 'Y': > return qty * -1 > else: > return qty > > textfile = open('orders.txt','r') > for line in textfile: > fields = map( string.strip, line.split( '|' ) ) > fields[4] = format_qty(fields[ 4 ],fields[ 1 ], fields[ 2 ] ) qty = format_qty(fields[ 4 ],fields[ 1 ], fields[ 2 ] ) would be clearer in subsequent code. > (year, period) = format_date( fields[7] ) > for count in range(12): > if count == period: > if results.get( ( year, fields[6], count), 0): > results[ year,fields[6], count] += fields[4] > else: > results[ year,fields[6],count] = fields[4] The loop on count is not doing anything, you can use period directly. And the test on results.get() is not needed, it is safe to always add: key = (year, fields[6], period) results[key] = results.get(key, 0) + qty > > sortedkeys = results.keys() > sortedkeys.sort() > > for keys in sortedkeys: > res_string = keys[0]+'|'+keys[1] > for count in range(12): > if results.get((keys[0],keys[1],count),0): > res_string += '|'+str(results[keys[0],keys[1],count]) > else: > res_string += '|0' > print res_string This will give you duplicate outputs if you ever have more than one period for a given year and field[6] (whatever that is...). OTOH if you just show the existing keys you will not have entries for the 0 keys. So maybe you should go back to your original idea of using a 12-element list for the counts. Anyway in the above code the test on results.get() is not needed since you just use the default value in the else: res_string += str(results.get((keys[0],keys[1],count),0)) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pkraus at pelsupply.com Wed Dec 28 21:12:42 2005 From: pkraus at pelsupply.com (Paul Kraus) Date: Wed, 28 Dec 2005 15:12:42 -0500 Subject: [Tutor] Multiple Assignment from list. Message-ID: <200512281512.42183.pkraus@pelsupply.com> How do I code this in python. Assuming fields is a list of 3 things. (myfielda, myfieldb, myfieldc) = fields When i try that I get ValueError: need more than 1 value to unpack. If i print fields it is in need printed as ['somestring','somestring','somestring'] TIA, -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From pkraus at pelsupply.com Wed Dec 28 21:23:21 2005 From: pkraus at pelsupply.com (Paul Kraus) Date: Wed, 28 Dec 2005 15:23:21 -0500 Subject: [Tutor] Multiple Assignment from list. In-Reply-To: <200512281512.42183.pkraus@pelsupply.com> References: <200512281512.42183.pkraus@pelsupply.com> Message-ID: <200512281523.21255.pkraus@pelsupply.com> Never mind. i figured this out. the top line of a file i was reading in and splitting only had 1 char so "fields" on that line was not a list. I fixed this. On Wednesday 28 December 2005 3:12 pm, Paul Kraus wrote: > How do I code this in python. Assuming fields is a list of 3 things. > > (myfielda, myfieldb, myfieldc) = fields > > When i try that I get > ValueError: need more than 1 value to unpack. > If i print fields it is in need printed as > ['somestring','somestring','somestring'] > > TIA, -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From motorolaguy at gmx.net Wed Dec 28 22:26:59 2005 From: motorolaguy at gmx.net (motorolaguy@gmx.net) Date: Wed, 28 Dec 2005 22:26:59 +0100 (MET) Subject: [Tutor] Extracting data from HTML files Message-ID: <3658.1135805219@www67.gmx.net> Hello, I`m very new to Python and programming in general.I`ve been reading Dive in to Python as an introduction to the language and I think I`m doing pretty well,but I`m stuck on this problem. I`m trying to make a python script for extracting certain data from HTML files.These files are from a template so they all have the same formatting.I just want to extract the data from certain fields.It would also be nice to insert it into a mysql database, but I`ll leave that for later since I`m stuck in just reading the files. Say for example the HTML file has the following format: Category:Category1

[...] Name:Filename.exe

[...] Description:Description1.

Taking in to account that each HTML file has a load of code in between each [...], what I want to do is extract the information for each field.In this case what I want to do is the script to read Category1, filename.exe and Description1.And later on insert this in to a mysql database, or read the info and generate a CSV file to make db insertion easier. Since all the files are generated by a script each field I want to read is,from what I`ve seen, in the same line number so this could make things easier.But not all fields are of the same length. I`ve read Chapter 8 of Dive in to Python so I`m basing my work on that. I also thought regexes might be useful for this but I suck at using regexes so that`s another problem. Do any of you have an idea of where I could get a good start on this and if there`s any modules (like sgmllib.py) that might come in handy for this. Thanks! -- Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko! Satte Provisionen für GMX Partner: http://www.gmx.net/de/go/partner From bgailer at alum.rpi.edu Wed Dec 28 23:23:22 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 28 Dec 2005 14:23:22 -0800 Subject: [Tutor] Extracting data from HTML files In-Reply-To: <3658.1135805219@www67.gmx.net> References: <3658.1135805219@www67.gmx.net> Message-ID: <7.0.0.16.0.20051228142144.024347b0@alum.rpi.edu> At 01:26 PM 12/28/2005, motorolaguy at gmx.net wrote: >[snip] >I`m trying to make a python script for extracting certain data from HTML >files....Say for example the HTML file has the following format: >Category:Category1

>[...] >Name:Filename.exe

>[...] >Description:Description1.

> >Taking in to account that each HTML file has a load of code in between each >[...], what I want to do is extract the information for each field.In this >case what I want to do is the script to read Category1, filename.exe and >Description1. Check out BeautifulSoup http://www.crummy.com/software/BeautifulSoup/ >And later on insert this in to a mysql database, or read the >info and generate a CSV file to make db insertion easier. >Since all the files are generated by a script each field I want to read >is,from what I`ve seen, in the same line number so this could make things >easier.But not all fields are of the same length. >I`ve read Chapter 8 of Dive in to Python so I`m basing my work on that. >I also thought regexes might be useful for this but I suck at using regexes >so that`s another problem. >Do any of you have an idea of where I could get a good start on this and if >there`s any modules (like sgmllib.py) that might come in handy for this. >Thanks! > >-- >Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko! >Satte Provisionen f?r GMX Partner: http://www.gmx.net/de/go/partner > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From broek at cc.umanitoba.ca Wed Dec 28 23:23:12 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 28 Dec 2005 16:23:12 -0600 Subject: [Tutor] code review please In-Reply-To: <43B28DBB.1010808@tds.net> References: <9be26a2e0512270759r628f0275q5b35eff63cc75db6@mail.gmail.com> <43B24752.5090309@cc.umanitoba.ca> <43B28DBB.1010808@tds.net> Message-ID: <43B31050.9030906@cc.umanitoba.ca> Kent Johnson said unto the world upon 28/12/05 07:06 AM: > Brian van den Broek wrote: > >>def punctuation_split(sequence): >> '''returns list of character sequences separating punctuation >>characters''' >> for mark in punctuation: >> sequence = sequence.replace(mark, ' %s ' %mark) >> return sequence.split(' ') > > > You should look at re.split(). > > Kent What, and have *2* problems? :-) (But seriously, thanks for the pointer. As I was coding, I thought there must have been a better way drawing off of the library. See my other post for why I couldn't find it.) Best, Brian vdB From broek at cc.umanitoba.ca Wed Dec 28 23:29:52 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 28 Dec 2005 16:29:52 -0600 Subject: [Tutor] new to linux and I cannot find some python things Message-ID: <43B311E0.5040507@cc.umanitoba.ca> Hi all, I'm a week or so into having switched from WinXP to linux (ubuntu breezy). There is a lot to learn about the differences in the OS'es and that's just fine. But, a couple of things have been in my way with Python. Most notably, I don't know how one browses the documentation. On Windows, I just fired up the .chm (I think cmh--at any rate, the compiled help file.) I have installed the docs on the linux side and they can be found by python: >>> help() help> NONE ------------------------------------------------------------------------ 2.3.10.7 The Null Object This object is returned by functions that don't explicitly return a I assume there is some linux facility for documentation browsing that beats importing modules and accessing docstrings. I'd work it out eventually, but a timesaving pointer would be appreciated. Best to all, Brian vdB From nequeo at gmail.com Thu Dec 29 00:12:16 2005 From: nequeo at gmail.com (Simon Gerber) Date: Thu, 29 Dec 2005 10:12:16 +1100 Subject: [Tutor] new to linux and I cannot find some python things In-Reply-To: <43B311E0.5040507@cc.umanitoba.ca> References: <43B311E0.5040507@cc.umanitoba.ca> Message-ID: <667ca7b60512281512t27c3b52br@mail.gmail.com> > Hi all, > > I'm a week or so into having switched from WinXP to linux (ubuntu > breezy). There is a lot to learn about the differences in the OS'es > and that's just fine. Excellent! Another Ubuntu Breezy user here. If there's anything Ubuntu I can help you with, drop me an e-mail and I'll do what I can to help. > But, a couple of things have been in my way with Python. Most notably, > I don't know how one browses the documentation. On Windows, I just > fired up the .chm (I think cmh--at any rate, the compiled help file.) Yeah, chm. Incidentally, there's a chm reader for Linux. Very primative, but it works in a pinch. Look for 'xchm' in the Universe repository. > I have installed the docs on the linux side and they can be found by > python: > > >>> help() > > help> NONE Nah, that's part of core Python. Nothing to do with the 'python-doc' package you installed. > I assume there is some linux facility for documentation browsing that > beats importing modules and accessing docstrings. I'd work it out > eventually, but a timesaving pointer would be appreciated. Firefox! file:///usr/share/doc/python2.4/html/index.html The python-doc package is just an offline version of http://www.python.org/doc/2.4.2/ You can also probably find a copy of the book 'Dive into Python' here: file:///usr/share/doc/diveintopython/html/index.html I know Hoary installed it by default. Not sure about Breezy, since I just did a dist-upgrade from Hoary. As a rule, with Ubuntu (and most other Linux distros), the documentation goes under /usr/share/doc/. But you can always check to see exactly what a package has put where. From the command-line, just type 'dpkg -L python-doc'. Hope that helps, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' From broek at cc.umanitoba.ca Thu Dec 29 00:58:24 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 28 Dec 2005 17:58:24 -0600 Subject: [Tutor] new to linux and I cannot find some python things In-Reply-To: <667ca7b60512281512t27c3b52br@mail.gmail.com> References: <43B311E0.5040507@cc.umanitoba.ca> <667ca7b60512281512t27c3b52br@mail.gmail.com> Message-ID: <43B326A0.8030507@cc.umanitoba.ca> Simon Gerber said unto the world upon 28/12/05 05:12 PM: >>Hi all, >> >>I'm a week or so into having switched from WinXP to linux (ubuntu >>breezy). There is a lot to learn about the differences in the OS'es >>and that's just fine. > > > Excellent! Another Ubuntu Breezy user here. If there's anything Ubuntu > I can help you with, drop me an e-mail and I'll do what I can to help. Hi Simon, thanks for the reply and the offer :-) >>But, a couple of things have been in my way with Python. Most notably, >> I don't know how one browses the documentation. On Windows, I just >>fired up the .chm (I think cmh--at any rate, the compiled help file.) > > > Yeah, chm. Incidentally, there's a chm reader for Linux. Very > primative, but it works in a pinch. Look for 'xchm' in the Universe > repository. Thanks. A bit part of the difficulty in the transition is suddenly I don't know what program to use for what. Pointers help :-) > >>I have installed the docs on the linux side and they can be found by >>python: >> >> >>> help() >> >>help> NONE > > > Nah, that's part of core Python. Nothing to do with the 'python-doc' > package you installed. I beg to differ :-) Before I installed I got this: IDLE 1.1.2 >>> help() Welcome to Python 2.4! This is the online help utility. help> topics Here is a list of available topics. Enter any topic name to get more help. ASSERTION DELETION LOOPING SEQUENCES help> ASSERTION Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. On Debian GNU/{Linux,Hurd} systems you have to install the corresponding pythonX.Y-doc package, i.e. python2.3-doc. help> On windows, one has to download the html version of the documentation and point the PYDOCS (or something close) env. variable at them. On ubuntu, once I installed python2.4-doc, it worked as shown in my OP. (I did test by removing the python2.4-doc package to get the behaviour shown in this post, then reinstalling to get the original behaviour.) >>I assume there is some linux facility for documentation browsing that >>beats importing modules and accessing docstrings. I'd work it out >>eventually, but a timesaving pointer would be appreciated. > > > Firefox! > > file:///usr/share/doc/python2.4/html/index.html But shouldn't it be harder than that? :-) > The python-doc package is just an offline version of > http://www.python.org/doc/2.4.2/ > > You can also probably find a copy of the book 'Dive into Python' here: > file:///usr/share/doc/diveintopython/html/index.html > > I know Hoary installed it by default. Not sure about Breezy, since I > just did a dist-upgrade from Hoary. Yep, it was installed by default. I'd wondered where it lived. But, since I've the dead-tree version, I didn't get motivated enough to find out. Still, thanks. > As a rule, with Ubuntu (and most other Linux distros), the > documentation goes under /usr/share/doc/. But you can always > check to see exactly what a package has put where. From the > command-line, just type 'dpkg -L python-doc'. > > Hope that helps, Thanks, it did. Especially that last bit. I've been learnign the various shell commands almost as quickly as I've been finding I want to know what command does foo. Thanks muchly, Brian vdB From broek at cc.umanitoba.ca Thu Dec 29 01:22:42 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 28 Dec 2005 18:22:42 -0600 Subject: [Tutor] [OT] A thanks for all the help since I've found tutor Message-ID: <43B32C52.3010905@cc.umanitoba.ca> Hi all, I'd like to thank the tutor community, especially Alan, Danny, and Kent, but all the other posters, regular and occasional, tutor or tutee, too. I've recently been engaged in what, for pre-python and -tutor me, would have been some deeply black magic unrelated to python, and the tutor list is a big part of why I had the confidence to try my hand at conjuring.
I've mentioned in another thread that I've recently installed ubuntu. It's on a laptop, and there has been some pain. My fan isn't working right, nor is much of the other acpi governed stuff. Within a few days of the install, I found myself decompiling the DSDT (Differentiated System Description Table) file provided by my OEM and fixing the code (C, I think) so that it would compile with an intel-provided complier. Apparently, the MS compiler which Fujitsu used would ignore various "Object does not exist" errors that an intel compiler (and, by extension, the linux kernel attempting to employ the DSDT file) choked on. Now, all that has nothing to do with python. But, I don't think I'd have felt up to even trying to fix code produced by Fujitsu in a language I don't really understand had I not had python and the community to give me confidence in my abilities. FWIW, my fix worked on the immediate problem of compilation failure. The ultimate problem remains, as Fujitsu is very proud of its proprietary fan control technology :-( Be that as it may, while I didn't succeed, at least I failed nobly in the effort rather than merely turning tail :-) So, thanks to all, and best wishes for 2006! Brian vdB From kent37 at tds.net Thu Dec 29 04:16:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Dec 2005 22:16:47 -0500 Subject: [Tutor] Extracting data from HTML files In-Reply-To: <3658.1135805219@www67.gmx.net> References: <3658.1135805219@www67.gmx.net> Message-ID: <43B3551F.70908@tds.net> motorolaguy at gmx.net wrote: > I`m trying to make a python script for extracting certain data from HTML > files.These files are from a template so they all have the same formatting.I > just want to extract the data from certain fields.It would also be nice to > insert it into a mysql database, but I`ll leave that for later since I`m > stuck in just reading the files. > Say for example the HTML file has the following format: > > Category:Category1

> [...] > Name:Filename.exe

> [...] > Description:Description1.

Since your data is all in the same form, I think a regex will easily find this data. Something like import re catRe = re.compile(r'Category:(.*?)

') data = ...read the HTML file here m = catRe.search(data) category = m.group(1) > I also thought regexes might be useful for this but I suck at using regexes > so that`s another problem. Regexes take some effort to learn but it is worth it, they are a very useful tool in many contexts, not just Python. Have you read the regex HOW-TO? http://www.amk.ca/python/howto/regex/ Kent From motorolaguy at gmx.net Thu Dec 29 08:46:58 2005 From: motorolaguy at gmx.net (motorolaguy@gmx.net) Date: Thu, 29 Dec 2005 08:46:58 +0100 (MET) Subject: [Tutor] Extracting data from HTML files References: <43B3551F.70908@tds.net> Message-ID: <775.1135842418@www77.gmx.net> Hello, I was taking a look at BeautifulSoup as recommended by bob and from what I can tell it`s just what I`m looking for but it`s a bit over my current skills with python I`m afraid.I`ll still keep playing with it and see what I can come up with. I`ll also take a look at regexes as recommended by Kent Johnson to see if it`ll work here.My guess is this is the way to go since the data I need is always in the same line number in the HTML source.So I could just go to the specific line numbers, look for my data and strip out the unnecesary tags. Thanks for the help guys, if anyone`s got more tips they are more than welcome :) Thanks again and happy holidays! > --- Urspr?ngliche Nachricht --- > Von: Kent Johnson > An: Python Tutor > Betreff: Re: [Tutor] Extracting data from HTML files > Datum: Wed, 28 Dec 2005 22:16:47 -0500 > > motorolaguy at gmx.net wrote: > > I`m trying to make a python script for extracting certain data from HTML > > files.These files are from a template so they all have the same > formatting.I > > just want to extract the data from certain fields.It would also be nice > to > > insert it into a mysql database, but I`ll leave that for later since I`m > > stuck in just reading the files. > > Say for example the HTML file has the following format: > > > > Category:Category1

> > [...] > > Name:Filename.exe

> > [...] > > Description:Description1.

> > > Since your data is all in the same form, I think a regex will easily > find this data. Something like > > import re > catRe = re.compile(r'Category:(.*?)

') > data = ...read the HTML file here > m = catRe.search(data) > category = m.group(1) > > > I also thought regexes might be useful for this but I suck at using > regexes > > so that`s another problem. > > Regexes take some effort to learn but it is worth it, they are a very > useful tool in many contexts, not just Python. Have you read the regex > HOW-TO? > http://www.amk.ca/python/howto/regex/ > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 10 GB Mailbox, 100 FreeSMS/Monat http://www.gmx.net/de/go/topmail +++ GMX - die erste Adresse f?r Mail, Message, More +++ From kent37 at tds.net Thu Dec 29 14:18:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 Dec 2005 08:18:29 -0500 Subject: [Tutor] Extracting data from HTML files In-Reply-To: <775.1135842418@www77.gmx.net> References: <43B3551F.70908@tds.net> <775.1135842418@www77.gmx.net> Message-ID: <43B3E225.4000103@tds.net> motorolaguy at gmx.net wrote: > I`ll also take a look at regexes as recommended by Kent Johnson to see if > it`ll work here.My guess is this is the way to go since the data I need is > always in the same line number in the HTML source.So I could just go to the > specific line numbers, look for my data and strip out the unnecesary tags. > Thanks for the help guys, if anyone`s got more tips they are more than > welcome :) I don't think you have to bother with finding the correct line numbers, just read the entire HTML into one string and search it with a regex. You don't say where the HTML is coming from, do you know how to read it? If you have trouble come back and show us what you have done so far, we'll help you with the next step. Kent From anna-s at internet.is Thu Dec 29 16:37:33 2005 From: anna-s at internet.is (=?iso-8859-1?Q?Anna_M._Sigur=F0ard=F3ttir?=) Date: Thu, 29 Dec 2005 15:37:33 -0000 Subject: [Tutor] unsubscribe Message-ID: <20051229160418.33D9F1E4002@bag.python.org> lk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051229/1f347759/attachment.htm From bernd at prager.ws Thu Dec 29 16:31:10 2005 From: bernd at prager.ws (Bernd Prager) Date: Thu, 29 Dec 2005 10:31:10 -0500 (EST) Subject: [Tutor] curses delwin functionality? Message-ID: <11162.198.45.19.20.1135870270.squirrel@mail.prager.ws> Hi, I'm trying to get my hands on some curses experiences in Python. The examples I found don't really tell me how to get rid of subwindows and restore the underlying window again. Is there something that replaces the curses functionality "delwin"? Thanks for any help! Here's my example: #!/usr/bin/python import sys, curses def sub(scrn): s = curses.newwin(4, 30, 1, 1) s.erase() s.box() s.addstr(1, 1, "sub window") s.refresh() s.getch() # curses.delwin(s) <-- that doesn't exist :-/ scrn.refresh() def main(scrn): scrn = curses.initscr() curses.curs_set(0) # turn cursor off scrn.erase() scrn.addstr(2, 2, "press to continue, to quit"); while 1: c = scrn.getch() if c == curses.KEY_F12: sys.exit() elif c == curses.KEY_F1: sub(scrn) # main loop if __name__ == '__main__': curses.wrapper(main) sys.exit() From zmerch at 30below.com Thu Dec 29 19:27:45 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Thu, 29 Dec 2005 13:27:45 -0500 Subject: [Tutor] curses delwin functionality? In-Reply-To: <11162.198.45.19.20.1135870270.squirrel@mail.prager.ws> Message-ID: <5.1.0.14.2.20051229132353.03a80558@mail.30below.com> Rumor has it that Bernd Prager may have mentioned these words: [snippety] > # curses.delwin(s) <-- that doesn't exist :-/ I've *only* done curses in python, so quite often I don't know the C analogue, but try: curses.endwin() I'm not sure if that's exactly what your looking for, but if not, try here: http://heather.cs.ucdavis.edu/~matloff/Python/PyCurses.pdf Google is your friend! ;-) HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- SysAdmin, Iceberg Computers zmerch at 30below.com Hi! I am a .signature virus. Copy me into your .signature to join in! From motorolaguy at gmx.net Thu Dec 29 20:06:39 2005 From: motorolaguy at gmx.net (motorolaguy@gmx.net) Date: Thu, 29 Dec 2005 20:06:39 +0100 (MET) Subject: [Tutor] Extracting data from HTML files References: <27769.1135882991@www46.gmx.net> Message-ID: <14466.1135883199@www69.gmx.net> The HTML comes from a bunch of files which are saved in my computer.They were generated by a php script and I want to extract certain fields for insertion in to a MySQL db. I`m trying to get the hang of correctly opening the files first :) There are about a thousand of them so I have to use a loop in the script since the files are named article1.html,article2.html,etc. Thanks for the help! > --- Urspr?ngliche Nachricht --- > Von: Kent Johnson > An: unknown > Kopie: tutor at python.org > Betreff: Re: [Tutor] Extracting data from HTML files > Datum: Thu, 29 Dec 2005 08:18:29 -0500 > I don't think you have to bother with finding the correct line numbers, > just read the entire HTML into one string and search it with a regex. > You don't say where the HTML is coming from, do you know how to read it? > > If you have trouble come back and show us what you have done so far, > we'll help you with the next step. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Telefonieren Sie schon oder sparen Sie noch? NEU: GMX Phone_Flat http://www.gmx.net/de/go/telefonie -- Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko! Satte Provisionen f?r GMX Partner: http://www.gmx.net/de/go/partner From kent37 at tds.net Thu Dec 29 20:18:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 Dec 2005 14:18:38 -0500 Subject: [Tutor] Extracting data from HTML files In-Reply-To: <27769.1135882991@www46.gmx.net> References: <43B3E225.4000103@tds.net> <27769.1135882991@www46.gmx.net> Message-ID: <43B4368E.8070702@tds.net> motorolaguy at gmx.net wrote: > The HTML comes from a bunch of files which are saved in my computer.They > were generated by a php script and I want to extract certain fields for > insertion in to a MySQL db. > I`m trying to get the hang of correctly opening the files first :) > There are about a thousand of them so I have to use a loop in the script > since the files are named article1.html,article2.html,etc. > Thanks for the help! Try something like this: def process(data): # this is a function you define to process the data from one file maxFileIndex = ... # whatever the max count is for i in range(1, maxFileIndex+1): # i will take on each value # from 1 to maxFileIndex name = 'article%s.html' % i # make a file name f = open(name) # open the file and read its contents data = f.read() f.close() process(data) Kent PS Please reply to the list From pkraus at pelsupply.com Thu Dec 29 20:23:08 2005 From: pkraus at pelsupply.com (Paul Kraus) Date: Thu, 29 Dec 2005 14:23:08 -0500 Subject: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list. In-Reply-To: <43B2BDA7.9030208@tds.net> References: <200512281018.13486.pkraus@pelsupply.com> <43B2BDA7.9030208@tds.net> Message-ID: <200512291423.08673.pkraus@pelsupply.com> On Wednesday 28 December 2005 11:30 am, Kent Johnson wrote: > Python lists don't create new elements on assignment (I think Perl lists > do this?) so for example > dictionary[(key1, key2)][10] = X ok so assuming I had a dictionary with 1key that contained a list like so... dictionary[key1][0] How would I increment it or assign it if it didn't exist. I assumed like this. dict[key1][0] = dictionary.get(key1[0],0) + X -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From motorolaguy at gmx.net Thu Dec 29 21:20:24 2005 From: motorolaguy at gmx.net (Oswaldo Martinez) Date: Thu, 29 Dec 2005 21:20:24 +0100 (MET) Subject: [Tutor] Extracting data from HTML files References: <43B4368E.8070702@tds.net> Message-ID: <31612.1135887624@www26.gmx.net> OK before I got in to the loop in the script I decided to try first with one file and I have some doubts with the some parts in the script,plus I got an error: >>> import re >>> file = open("file1.html") >>> data = file.read() >>> catRe = re.compile(r'Title:(.*?)
') # I searched around the docs on regexes I have and found that the "r" #after the re.compile(' will detect repeating words.Why is this useful in #my case? I want to read the whole string even if it has repeating words. #Also, I dont understand the actual regex (.*?) . If I want to match #everything inside and
, shouldn`t I just put a "*" # ? I tried that and it gave me an error of course. >>> m = catRe.search(data) >>> category = m.group(1) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'group' >>> I also found that on some of the strings I want to extract, when python reads them using file.read(), there are newline characters and other stuff that doesn`t show up in the actual html source.Do I have to take these in to account in the regex or will it automatically include them? > --- Urspr?ngliche Nachricht --- > Von: Kent Johnson > An: Python Tutor > Betreff: Re: [Tutor] Extracting data from HTML files > Datum: Thu, 29 Dec 2005 14:18:38 -0500 > > Try something like this: > > def process(data): > # this is a function you define to process the data from one file > > maxFileIndex = ... # whatever the max count is > for i in range(1, maxFileIndex+1): # i will take on each value > # from 1 to maxFileIndex > name = 'article%s.html' % i # make a file name > f = open(name) # open the file and read its contents > data = f.read() > f.close() > process(data) > > Kent > > PS Please reply to the list -- Telefonieren Sie schon oder sparen Sie noch? NEU: GMX Phone_Flat http://www.gmx.net/de/go/telefonie From dyoo at hkn.eecs.berkeley.edu Thu Dec 29 22:13:03 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 29 Dec 2005 13:13:03 -0800 (PST) Subject: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list. In-Reply-To: <200512291423.08673.pkraus@pelsupply.com> Message-ID: > ok so assuming I had a dictionary with 1key that contained a list like > so... dictionary[key1][0] > > How would I increment it or assign it if it didn't exist. I assumed like > this. dict[key1][0] = dictionary.get(key1[0],0) + X Hi Paul, Given a dictionary d and some arbitrary key k, let's assume two possibilities: 1. k is a key in d. If so, no problem, and we'll assume that d[k] is associated to some twelve-element list. 2. k isn't yet a key in d. This is the situation we want to work on. We can go the uncomplicated route and just say something like this: if k not in d: d[k] = [0] * 12 in which case we change Possibility 2 to Possibility 1: the end result is that we make sure that d[k] points to a twelve-element list of zeros. Once we guarantee this, we can go on our merry way. For example: if k not in d: d[k] = [0] * 12 d[k][0] += 1 There is a one-liner way of doing this: we can use the setdefault() method of dictionaries. d.setdefault(k, [0] * 12)[0] += 1 This is a bit dense. There's no shame in not using setdefault() if you don't want to. *grin* I actually prefer the longer approach unless I'm really in a hurry. This being said, what data are you modeling? It almost sounds like you're implementing some kind of 3d matrix, even a sparse one. More information about the data you're modelling might lead to a different representation For example, would using a dictionary whose keys are three-tuples be approrpriate? ###### def increment(d, x, y, z): """Given a dictionary whose keys are 3-tuples, increments at the position (x, y, z).""" d[(x, y, z)] = d.get((x, y, z), 0) + 1 ###### Here's this code in action: ### >>> map = {} >>> increment(map, 3, 1, 4) >>> map {(3, 1, 4): 1} >>> increment(map, 2, 7, 1) >>> map {(2, 7, 1): 1, (3, 1, 4): 1} >>> increment(map, 2, 7, 1) >>> map {(2, 7, 1): 2, (3, 1, 4): 1} ### Best of wishes to you! From Hans.Dushanthakumar at navman.com Thu Dec 29 22:22:32 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Fri, 30 Dec 2005 10:22:32 +1300 Subject: [Tutor] new to linux and I cannot find some python things Message-ID: <5667508E43F1B740BCFA57FF46E3530002D9E988@nav-akl-exch-c.newton.navman.com> Anothet linux noobie here :) How do I uninstall python? I use the SimplyMepis flavor of linux. The reason I want to uninstall python is that its an old version (2.3). Not that I particularly want the new version, but the IDLE installation that I downloaded reports all kinds of errors because apparently its meant to work with python 2.4. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Brian van den Broek Sent: Thursday, 29 December 2005 12:58 p.m. To: Simon Gerber Cc: Tutor Subject: Re: [Tutor] new to linux and I cannot find some python things Simon Gerber said unto the world upon 28/12/05 05:12 PM: >>Hi all, >> >>I'm a week or so into having switched from WinXP to linux (ubuntu >>breezy). There is a lot to learn about the differences in the OS'es >>and that's just fine. > > > Excellent! Another Ubuntu Breezy user here. If there's anything Ubuntu > I can help you with, drop me an e-mail and I'll do what I can to help. Hi Simon, thanks for the reply and the offer :-) >>But, a couple of things have been in my way with Python. Most notably, >> I don't know how one browses the documentation. On Windows, I just >>fired up the .chm (I think cmh--at any rate, the compiled help file.) > > > Yeah, chm. Incidentally, there's a chm reader for Linux. Very > primative, but it works in a pinch. Look for 'xchm' in the Universe > repository. Thanks. A bit part of the difficulty in the transition is suddenly I don't know what program to use for what. Pointers help :-) > >>I have installed the docs on the linux side and they can be found by >>python: >> >> >>> help() >> >>help> NONE > > > Nah, that's part of core Python. Nothing to do with the 'python-doc' > package you installed. I beg to differ :-) Before I installed I got this: IDLE 1.1.2 >>> help() Welcome to Python 2.4! This is the online help utility. help> topics Here is a list of available topics. Enter any topic name to get more help. ASSERTION DELETION LOOPING SEQUENCES help> ASSERTION Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. On Debian GNU/{Linux,Hurd} systems you have to install the corresponding pythonX.Y-doc package, i.e. python2.3-doc. help> On windows, one has to download the html version of the documentation and point the PYDOCS (or something close) env. variable at them. On ubuntu, once I installed python2.4-doc, it worked as shown in my OP. (I did test by removing the python2.4-doc package to get the behaviour shown in this post, then reinstalling to get the original behaviour.) >>I assume there is some linux facility for documentation browsing that >>beats importing modules and accessing docstrings. I'd work it out >>eventually, but a timesaving pointer would be appreciated. > > > Firefox! > > file:///usr/share/doc/python2.4/html/index.html But shouldn't it be harder than that? :-) > The python-doc package is just an offline version of > http://www.python.org/doc/2.4.2/ > > You can also probably find a copy of the book 'Dive into Python' here: > file:///usr/share/doc/diveintopython/html/index.html > > I know Hoary installed it by default. Not sure about Breezy, since I > just did a dist-upgrade from Hoary. Yep, it was installed by default. I'd wondered where it lived. But, since I've the dead-tree version, I didn't get motivated enough to find out. Still, thanks. > As a rule, with Ubuntu (and most other Linux distros), the > documentation goes under /usr/share/doc/. But you can always > check to see exactly what a package has put where. From the > command-line, just type 'dpkg -L python-doc'. > > Hope that helps, Thanks, it did. Especially that last bit. I've been learnign the various shell commands almost as quickly as I've been finding I want to know what command does foo. Thanks muchly, Brian vdB _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Dec 29 22:38:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 29 Dec 2005 13:38:50 -0800 (PST) Subject: [Tutor] Extracting data from HTML files In-Reply-To: <31612.1135887624@www26.gmx.net> Message-ID: > >>> import re > >>> file = open("file1.html") > >>> data = file.read() > >>> catRe = re.compile(r'Title:(.*?)
') > > # I searched around the docs on regexes I have and found that the "r" > # after the re.compile(' will detect repeating words. Hi Oswaldo, Actually, no. What you're seeing is a "raw" string literal. See: http://www.amk.ca/python/howto/regex/regex.html#SECTION000420000000000000000 for more details about this. The idea is that we often want to make strings where backslashes are just literally backslashes, rather than treated by Python as escape characters. The Regular Expression HOWTO itself is pretty good and talks about some of the stuff you've been running into, so here's a link to the base url that you may want to look at: http://www.amk.ca/python/howto/regex/ > I want to read the whole string even if it has repeating words. #Also, > I dont understand the actual regex (.*?) . If I want to match > #everything inside and
, shouldn`t I just put a > "*" #? You're confusing the "globbing" notation used in Unix shells with the miniature pattern language used in regular expressions. They both use similar symbols, but with totally different interpretations. Be aware of this context, as it's easy to get confused because of their surface similarities. For example, "ab*" under a globbing interpretation means: 'a' and 'b', followed by any number of characters. But under a regular expression interpretation, this means: 'a', followed by any number of 'b's. As a followup: to express the idea: "'a' and 'b', followed by any number of characters," as a regular expression pattern, we'd write: "ab.*" So any globbing pattern can be translated fairly easily to a regular expression pattern. However, going the other way don't usually work: it's often not possible to take an arbitrary regular expression, like "ab*", and make it work as a glob. So regular expressions are more expressive than globs, but with that power comes great resp... err, I mean, more complexity. *grin* > I also found that on some of the strings I want to extract, when python > reads them using file.read(), there are newline characters and other > stuff that doesn`t show up in the actual html source. Not certain that I understand what you mean there. Can you show us? read() should not adulterate the byte stream that comes out of your files. > Do I have to take these in to account in the regex or will it > automatically include them? Newlines are, by default, handled differently than other characters. You can add an 're.DOTALL' flag so that newlines are also matched by the '.' regular expression metacharacter; see the Regex HOWTO above to see how this might work. As an aside: the problems you're running into is very much why we encourage folks not to process HTML with regular expressions: RE's also come with their own somewhat-high learning curve. Good luck to you. From dyoo at hkn.eecs.berkeley.edu Thu Dec 29 22:46:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 29 Dec 2005 13:46:06 -0800 (PST) Subject: [Tutor] new to linux and I cannot find some python things In-Reply-To: <5667508E43F1B740BCFA57FF46E3530002D9E988@nav-akl-exch-c.newton.navman.com> Message-ID: > Anothet linux noobie here :) > How do I uninstall python? I use the SimplyMepis flavor of linux. Hi Hans, Ask the Mepis folks about this. I understand that Mepis is a Debian-based distribution, and you should be able to use the 'dpkg' command to drop debs. That being said, I have no idea if Mepis uses Python as a part of its core system. It might not be a good idea to remove it because doing so might suddenly break a whole lot more than just IDLE. That's why you need to talk with folks who are familiar with your particular Linux distribution. > The reason I want to uninstall python is that its an old version (2.3). > Not that I particularly want the new version, but the IDLE installation > that I downloaded reports all kinds of errors because apparently its > meant to work with python 2.4. This sounds unusual. Try: $ which idle at your shell prompt. What shows up? What happens with: $ which python Good luck to you! From bernd at prager.ws Thu Dec 29 23:16:55 2005 From: bernd at prager.ws (Bernd Prager) Date: Thu, 29 Dec 2005 17:16:55 -0500 (EST) Subject: [Tutor] curses delwin functionality? In-Reply-To: <5.1.0.14.2.20051229132353.03a80558@mail.30below.com> References: <11162.198.45.19.20.1135870270.squirrel@mail.prager.ws> <5.1.0.14.2.20051229132353.03a80558@mail.30below.com> Message-ID: <13584.198.45.19.20.1135894615.squirrel@mail.prager.ws> > Rumor has it that Bernd Prager may have mentioned these words: > > [snippety] > >> # curses.delwin(s) <-- that doesn't exist :-/ > > I've *only* done curses in python, so quite often I don't know the C > analogue, but try: > > curses.endwin() > I am looking for a functionality that destroys only a single subwindow created with curses.newwin so that the underlying area can get restored again. curses.endwin() terminates the curses main screen, right? From wescpy at gmail.com Fri Dec 30 07:04:48 2005 From: wescpy at gmail.com (w chun) Date: Thu, 29 Dec 2005 22:04:48 -0800 Subject: [Tutor] identifier token parsing [was Re: (no subject)] Message-ID: <78b3a9580512292204x1f12b404kfadbef3b718062e6@mail.gmail.com> > hello everyone. i was looking at python docs and i came across this > > letter ::= > lowercase | uppercase > > what does ::= mean? you must be referring to identifiers and keywords page at http://docs.python.org/ref/identifiers.html take it as meaning, "may expand to." in other words, when you are trying to "parse" the language, meaning taking a look at the construct of a valid Python program with the following substitutions: identifier ::= (letter|"_") (letter | digit | "_")* letter ::= lowercase | uppercase lowercase ::= "a"..."z" uppercase ::= "A"..."Z" digit ::= "0"..."9" identifier expands to exactly one occurrence of (letter or _) followed by zero or more (*) occurrences of (letter or digit or _). so.... a variable such as 'testVar_123' matches the identifier token because it can be broken down in that fashion. for example, 't' is matched by letter -> lowercase -> 't' while 'estVar_123' is matched by zero or more occurrences of (letter or digit or _) --> (letter, letter, letter, letter, letter, letter, _, digit, digit, digit) -> lowercase, lowercase, lowercase, uppercase, lowercase, lowercase, _, '1', '2', '3') --> ('e', 's', 't', 'V', 'a', 'r', '_', '1', '2', '3'). you get the picture. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Fri Dec 30 13:45:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 Dec 2005 07:45:26 -0500 Subject: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list. In-Reply-To: References: Message-ID: <43B52BE6.2030601@tds.net> Danny Yoo wrote: > This being said, what data are you modeling? It almost sounds like you're > implementing some kind of 3d matrix, even a sparse one. More information > about the data you're modelling might lead to a different representation > > For example, would using a dictionary whose keys are three-tuples be > approrpriate? That is the approach Paul took originally (see the other fork of this thread). He is accumulating a sparse 3d matrix where the keys are year, field6 and month. (He hasn't said what field6 represents.) The problem is that he wants to print out counts corresponding to all the existing year and field6 values and every possible month value. To do this I think a two-level data structure is appropriate, such as the dict[ (year, field6) ][month] approach you outlined. Kent From guillermo.fernandez.castellanos at gmail.com Fri Dec 30 13:45:38 2005 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Fri, 30 Dec 2005 13:45:38 +0100 Subject: [Tutor] [OT] Python Tutor like java mailing list Message-ID: <43B52BF2.8030403@gmail.com> Hi, After python I have to start learning Java. Do you know of any Tutor-like list for Java you could recommend? I've been looking and I've been unable to find any... and i miss it :-) Thanks, Guille From kent37 at tds.net Fri Dec 30 13:58:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 Dec 2005 07:58:28 -0500 Subject: [Tutor] Extracting data from HTML files In-Reply-To: <31612.1135887624@www26.gmx.net> References: <43B4368E.8070702@tds.net> <31612.1135887624@www26.gmx.net> Message-ID: <43B52EF4.6000002@tds.net> Oswaldo Martinez wrote: > OK before I got in to the loop in the script I decided to try first with one > file and I have some doubts with the some parts in the script,plus I got an > error: > > >>>>import re >>>>file = open("file1.html") >>>>data = file.read() >>>>catRe = re.compile(r'Title:(.*?)
') Thi regex does not agree with the data you originally posted. Your original data was Category:Category1

Do you see the difference? Your regex has a different ending. > > > # I searched around the docs on regexes I have and found that the "r" #after > the re.compile(' will detect repeating words.Why is this useful in #my case? > I want to read the whole string even if it has repeating words. #Also, I > dont understand the actual regex (.*?) . If I want to match #everything > inside
and
, shouldn`t I just put a "*" > # ? I tried that and it gave me an error of course. As Danny said, the r is not part of the regex, it marks a 'raw' string. In this case it is not needed but I use it always for regex strings out of habit. The whole string is the regex, not just the (.*?) part. Most of it just matches against fixed text. The part in parenthesis says . match anything * match 0 or more of the previous character, i.e. 0 or more of anything ? match non-greedy - match the minimum number of characters to make the whole match succeed. Without this, the .* could match the whole file up to the *last*
which is not what you want! The parentheses create a group which you can use to pull out the part of the string which matched inside them. This is the data you want. > > >>>>m = catRe.search(data) >>>>category = m.group(1) > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'NoneType' object has no attribute 'group' In this case the match failed, so m is None and m.group(1) gives an error. > > > I also found that on some of the strings I want to extract, when python > reads them using file.read(), there are newline characters and other stuff > that doesn`t show up in the actual html source.Do I have to take these in to > account in the regex or will it automatically include them? This will only be a problem if the newlines are in the text you are actually trying to match. Kent From pkraus at pelsupply.com Fri Dec 30 17:59:29 2005 From: pkraus at pelsupply.com (Paul Kraus) Date: Fri, 30 Dec 2005 11:59:29 -0500 Subject: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list. In-Reply-To: <43B52BE6.2030601@tds.net> References: <43B52BE6.2030601@tds.net> Message-ID: <200512301159.29952.pkraus@pelsupply.com> > That is the approach Paul took originally (see the other fork of this > thread). He is accumulating a sparse 3d matrix where the keys are year, > field6 and month. (He hasn't said what field6 represents.) The problem > is that he wants to print out counts corresponding to all the existing > year and field6 values and every possible month value. To do this I > think a two-level data structure is appropriate, such as the dict[ > (year, field6) ][month] approach you outlined. Field6 is just an arbitrary field that represents some generic key. So for clarity lets say in this instance it represents a customer code. so dict(2005,12130)[0..11] would hold sales by month for customer number 12130 in 2005. This problem has evolved since it started and I have created a class that lets me build rolling 24 month data structures.I need to create a bunch of reports that will be run monthly that will show a rolling 24 month total for different things. Sales by customer, sales by vendor, purchases by vendor. So by making a class that on construction takes the current year and month it will build the structure I need. I then have a method that lets me fill the monthly buckets. All i do is pass it the arbitrary key (customercode) year, month, and amount and it will increment that bucket. So now for all my reports all I have to write are little 5 or 6 line scripts that take a text file split the fields and format them before basing them off into my custom object. Very slick and this is my first python project. Its cluttered and messy but for about 1 hours worth of work on a brand new language I am impressed with the usability of this language. Now I have to find a way to take the output at the end and pipe it out to an external Perl program that creates an excel spreadsheet ( no real clean easy way to do this in python but hey each tool has its usefullness). I wish I could hide this in the object though so that I could call a "dump" method that would then create the spreadsheet. I will have to play with this later. Current Script - Critique away! :) =-=-=-=-=--=-= #!/usr/bin/python import string import re class Tbred_24Months: def __init__(self,currentyear,currentmonth): ### Takes Ending Year and Ending Month Inits List guide = [] self.results = {} self.guide = {} self.end_month = currentmonth self.end_year = currentyear self.start_month = currentmonth self.start_year = currentyear for count in range(24): guide.append((self.start_month,self.start_year)) self.start_month -= 1 if self.start_month < 1: self.start_month = 12 self.start_year -= 1 guide.reverse() count = 0 for key in guide: self.guide[key[1],key[0]]=count count += 1 self.sortedkeys = self.guide.keys() self.sortedkeys.sort() def insert(self,key,year,month,number): if self.guide.has_key((year,month)): if self.results.has_key(key): seq = self.guide[(year,month)] self.results[key][seq] += number else: self.results[key] = [] for x in range(24):self.results[key].append(0) def splitfields(record): fields = [] datestring='' ### Regular Expr. re_negnum = re.compile('(\d?)\.(\d+)(-)') re_date = re.compile('(\d\d)/(\d\d)/(\d\d)') for element in record.split('|'): element=element.strip() # remove leading/trailing whitespace ### Move Neg Sign from right to left of number negnum_match = re_negnum.search( element ) if negnum_match: if negnum_match.group(1):element = "%s%d.%02d" %(negnum_match.group(3),int(negnum_match.group(1)),int(negnum_match.group(2))) else:element = "%s0.%02d" %(negnum_match.group(3),int(negnum_match.group(2))) ### Format Date date_match = re_date.search(element) if date_match: (month,day,year) = (date_match.group(1),date_match.group(2),date_match.group(3)) ### Convert 2 year date to 4 year if int(year) > 80:year = "19%02d" %int(year) else:year = "20%02d" %int(year) element = (year,month,day) if element == '.000': element = 0.00 fields.append( element ) return fields ### Build Vendor Sales sales = Tbred_24Months(2005,11) vendorsales = open('vendorsales.txt','r') for line in vendorsales: fields = splitfields( line ) if len(fields) == 7: (vendor,otype,oreturn,discountable,discperc,amount,date) = fields amount = float(amount);discperc = float(discperc) #if discperc and discountable == 'Y': amount = amount - ( amount * (discperc/100) ) if otype == 'C' or oreturn == 'Y':amount = amount * -1 sales.insert(vendor,int(date[0]),int(date[1]),amount) result = '' for key in sales.results: sum = float(0) result = str(key) for amount in sales.results[key]: sum += amount result += "|" + str(amount) print str(key),sum #print result,sum From motorolaguy at gmx.net Fri Dec 30 23:39:30 2005 From: motorolaguy at gmx.net (Oswaldo Martinez) Date: Fri, 30 Dec 2005 23:39:30 +0100 (MET) Subject: [Tutor] Extracting data from HTML files References: <18272.1135982175@www93.gmx.net> Message-ID: <22155.1135982370@www93.gmx.net> > From: Danny Yoo > [...] > The Regular Expression HOWTO itself is pretty good and talks about some of > the stuff you've been running into, so here's a link to the base url that > you may want to look at: > > http://www.amk.ca/python/howto/regex/ Ah yes I`ve been reading that same doc and got confused on the use of the "r" I guess [......] > > I also found that on some of the strings I want to extract, when python > > reads them using file.read(), there are newline characters and other > > stuff that doesn`t show up in the actual html source. > > Not certain that I understand what you mean there. Can you show us? > read() should not adulterate the byte stream that comes out of your >files. >>> file = open("file1.html") >>> file.read() '\r\n\r\n\r\n\r\n