From urnerk@qwest.net Wed May 1 04:31:43 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 30 Apr 2002 20:31:43 -0700 Subject: [Tutor] more newbie questions In-Reply-To: <3CCF1617.6060803@venix.com> References: Message-ID: <4.2.0.58.20020430203032.01c1c750@pop3.norton.antivirus> > >def combo(n, r=None): > if r is None: r = int(n/2) > assert 0 <= r <= n, "r must be between 0 and n" > return int(fact(n,r)/fact(r)) Check this post by Tim Peters (archives, edu-sig) for an optimized version of combo: http://aspn.activestate.com/ASPN/Mail/Message/580860 Kirby From pythontutor@venix.com Wed May 1 14:39:38 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 01 May 2002 09:39:38 -0400 Subject: [Tutor] more newbie questions References: <4.2.0.58.20020430203032.01c1c750@pop3.norton.antivirus> Message-ID: <3CCFF01A.2010603@venix.com> Thanks. An interesting read. I think Python2.2 helps greatly on the overflow front. int * int will now return a long when necessary. Converting a float to a non-float still seems to require a test (that I omitted) to choose between long and int. Kirby Urner wrote: > >> >> def combo(n, r=None): >> if r is None: r = int(n/2) >> assert 0 <= r <= n, "r must be between 0 and n" >> return int(fact(n,r)/fact(r)) > > > Check this post by Tim Peters (archives, edu-sig) for > an optimized version of combo: > > http://aspn.activestate.com/ASPN/Mail/Message/580860 > > Kirby > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From jgregorio@ultrasw.com Wed May 1 17:03:23 2002 From: jgregorio@ultrasw.com (Josh Gregorio) Date: Wed, 1 May 2002 09:03:23 -0700 Subject: [Tutor] HP preinstalled Python! References: <1020022298.3ccc4e1a234ec@carrierpigeon.mail.umich.edu> Message-ID: <000f01c1f129$b8d36760$a6f1b542@computer> I'm a computer tech, and I've worked on three new HP's in the last few weeks. All three had python 1.5 preinstalled. No links to the program on the start menu, and python wasn't in the path, but it was there, and listed in add/remove programs on two of them. ----- Original Message ----- From: Lance E Sloan To: Sent: Sunday, April 28, 2002 12:31 PM Subject: [Tutor] HP preinstalled Python! > This weekend, my wife and I finally gave in and bought a Windows computer. Well, we've had one before, but we mostly used Macs and I use UNIX a lot. This is our first purchase of a brand-new, semi-beefy Windows computer. My wife wanted it to run certain programs that were only available for Windows and I figured it's best to "know thy enemy". So we bought an HP Pavilion 531w. It's not the most powerful machine, but good enough. > > So, as I was installing various apps, I discovered that in the "Program Files" directory, there is a Python directory. And there was also a TCL directory. Both of them apparently have working versions of those languages. I've not found anything in the documentation about them yet, but I figure that among the other third-party programs HP installed, there must be one that uses Python, probably with Tkinter. > > Has anybody else noticed this on new HP computers? > > -- > Lance E Sloan > Web Services, Univ. of Michigan: Full-service Web and database design, > development, and hosting. Specializing in Python & Perl CGIs. > http://websvcs.itd.umich.edu/ - "Putting U on the Web" > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From rob@uselesspython.com Wed May 1 17:06:01 2002 From: rob@uselesspython.com (Rob Andrews) Date: Wed, 01 May 2002 11:06:01 -0500 Subject: [Tutor] HP preinstalled Python! References: <1020022298.3ccc4e1a234ec@carrierpigeon.mail.umich.edu> <000f01c1f129$b8d36760$a6f1b542@computer> Message-ID: <3CD01269.9050102@uselesspython.com> A google.com search for "HP Python" and a search at hp.com for "Python" indicate that HP has taken more than a casual interest in Python. Rob http://uselesspython.com From alan.gauld@bt.com Wed May 1 17:39:59 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 1 May 2002 17:39:59 +0100 Subject: [Tutor] newbie with some basic questions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C596@mbtlipnt02.btlabs.bt.co.uk> Sorry if this is answered I'm playing catch up on the digests(again!) > im a total newbie to both programming and python (well i can write a > decent shell script...). So I'll assume you are on *nix... > just a few questions, most important one first: > 1.whats better for a newbie like myself, learning python or > core python programming? or any other recommendations? If you can do non trivial shell scripts then either is fine. If you are only doing basic shell scripts then I'd go with Core Python or maybe quick Python. (Or even my book! :-) > 2.how can i make input take only one character and not requrie a CR? You can't. You need curses.getch() > 3.i have a simple list of lists for example: people = > [["A","john","12345"],["B","joe","1231234"],["X","sally","1234"]] > and i need to do something like: > some_variable = X > new_variable = people[*][0] > that is, find the corresponding list with the list that has [0] = X > > i could use a dictionary like {"X":["sally","1234"]} but is there a > better way to do it? You know too much for my book, I'd go with Learning Python.... :-) A Dictionary looks like the best way (what do you mean "better"? That implies you don't think the dictionary approach is good...) The alternative is to traverse the list looking for X in the first position: for L in people: if L[0] == some_variable: break # L is your sublist Or in one line: sublist = filter(lambda L, v=some_variable: L[0] == v, people) Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Wed May 1 17:49:54 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 1 May 2002 17:49:54 +0100 Subject: [Tutor] more newbie questions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C597@mbtlipnt02.btlabs.bt.co.uk> > 1. how to simply clear the screen? Clearing a screen is never simple since like any console specific thing(like reading a character without hitting ENTER) it depends on your platform. On DOS the easiest thing is probably: os.system('CLS') on *nix: os.system('clear') There will also be escape codes that you can use but they are terminal specific - my old Wyse terminal was ESC J ESC H I dunno what a vt100/vt200 sequence is... Or generically on *nix I think there is a clrscr() call in curses. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Wed May 1 17:56:32 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 1 May 2002 17:56:32 +0100 Subject: [Tutor] Multifunction mapping Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C598@mbtlipnt02.btlabs.bt.co.uk> > I have a sequence of characters (a,b,c,d,e,f,g,h,i) I assume they are meant to have quotes around them? Otherwise they are a list of variables! > (61,62,63,64,65,66,67,68,69) OK > (061,062,063,064,065,066,067,068,069) and these must be strings since the leading zero has no significance for an int...? > (061062063064065066067068069) And this is one big string...? def fixChar(c): s = ord(c) s = '0%d' % i #get string return s string.join(map(fixChar, letters)) Something like that - sorry no python to test it... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From scarblac@pino.selwerd.nl Wed May 1 18:01:59 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 1 May 2002 19:01:59 +0200 Subject: [Tutor] Multifunction mapping In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C598@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Wed, May 01, 2002 at 05:56:32PM +0100 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C598@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020501190159.A3051@pino.selwerd.nl> On 0, alan.gauld@bt.com wrote: > > (061,062,063,064,065,066,067,068,069) > and these must be strings since the leading > zero has no significance for an int...? If only that were true. Python still has the moronic syntax from the C world, where a literal with a leading 0 is considered to be in octal (which sometimes leads to weird bugs). >>> 067 55 067 is 6*8+7 = 55, while 068 is actually a syntax error. But I think he meant strings, yes. :-) -- Remco Gerlich From urnerk@qwest.net Wed May 1 15:13:57 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 1 May 2002 10:13:57 -0400 Subject: [Tutor] more newbie questions In-Reply-To: <3CCFF01A.2010603@venix.com> References: <4.2.0.58.20020430203032.01c1c750@pop3.norton.antivirus> <3CCFF01A.2010603@venix.com> Message-ID: <200205011013.57751.urnerk@qwest.net> On Wednesday 01 May 2002 09:39 am, Lloyd Kvam wrote: > Thanks. An interesting read. > > I think Python2.2 helps greatly on the overflow front. int * int will > now return a long when necessary. True. =20 Another aspect of Tim's approach which makes it faster is it doesn't allow the factorial in the numerator to build up=20 so high before dividing. It's a more divide-as-you-go=20 approach that potentialy avoids a huge long/long at the end. Kirby > > Check this post by Tim Peters (archives, edu-sig) for > > an optimized version of combo: > > > > http://aspn.activestate.com/ASPN/Mail/Message/580860 From linuxconsult@yahoo.com.br Wed May 1 23:32:15 2002 From: linuxconsult@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito) Date: Wed, 1 May 2002 19:32:15 -0300 Subject: [Tutor] Re: Printable versions of "What's new" documents? In-Reply-To: <4.3.2.7.2.20020430124637.00cff6e0@pop3.norton.antivirus> References: <4.3.2.7.2.20020430104434.00b766a0@pop3.norton.antivirus> <20020430021202.12675.82815.Mailman@mail.python.org> <4.3.2.7.2.20020430104434.00b766a0@pop3.norton.antivirus> <4.3.2.7.2.20020430124637.00cff6e0@pop3.norton.antivirus> Message-ID: <20020501223215.GA1291@ime.usp.br> On Apr 30 2002, Alexandre Ratti wrote: > I just uploaded them to: > > http://alexandre.ratti.free.fr/python/docs/ Hi, Alexandre. Thank you very much for putting the documents on your site. I have already downloaded them and will print them. Just from a brief skimming, they seem to be a very useful aid in learning more about Python, as I thought earlier. Thank you very much, Roger... -- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/ =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From goodmansond@yahoo.com Wed May 1 23:52:50 2002 From: goodmansond@yahoo.com (Dean Goodmanson) Date: Wed, 1 May 2002 15:52:50 -0700 (PDT) Subject: [Tutor] HP pre-installing Python Message-ID: <20020501225250.60540.qmail@web21104.mail.yahoo.com> Could you supply more details to what kind of machine HP pre-installed Python? 1.5 is a bit of a disappointment, there was discussion on comp.lang.py that RedHat stuck with that version for awhile due to their configuration/management what-not programs. Did anything break or need to be changed when you updated to 2.2? Thanks, Dean __________________________________________________ Do You Yahoo!? Yahoo! Health - your guide to health and wellness http://health.yahoo.com From m_konermann@gmx.de Wed May 1 01:09:16 2002 From: m_konermann@gmx.de (Marcus) Date: Wed, 01 May 2002 02:09:16 +0200 Subject: [Tutor] Debug Settings Message-ID: <3CCF322C.9050005@gmx.de> Hi ! I never worked with Debug before and i´ve got problems to start the debug mode under Visual C++. I already created debug versions of my python skripts, but i don´t know how to start the script in debug . The compiler want´s a .exe or .com file, but i´ve got only .py files and the .dll which ein need under windows. So, can anyone tell me, how to start debug ? Greetings Marcus From Recoome16@chartermi.net Wed May 1 23:29:02 2002 From: Recoome16@chartermi.net (Del Kollhoff) Date: Wed, 1 May 2002 18:29:02 -0400 Subject: [Tutor] help mee Message-ID: <000801c1f15f$98dc8320$c080f718@Compaq> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C1F13E.119665A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable how do you put a plain text program into python command line? Recoome16@chartermi.net ------=_NextPart_000_0005_01C1F13E.119665A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
how do you put  a plain text = program into=20 python command line?
 
 
 
Recoome16@chartermi.net
 
------=_NextPart_000_0005_01C1F13E.119665A0-- From dyoo@hkn.eecs.berkeley.edu Thu May 2 02:54:46 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 May 2002 18:54:46 -0700 (PDT) Subject: [Tutor] Debug Settings In-Reply-To: <3CCF322C.9050005@gmx.de> Message-ID: On Wed, 1 May 2002, Marcus wrote: > I never worked with Debug before and i=B4ve got problems to start the > debug mode under Visual C++. I already created debug versions of my > python skripts Hi Marcus, Can you explain what you mean by a "debug" version of a Python script? Python itself makes no distinction between scripts, so I have to admit that I don't understand what you're trying to do. Can you tell us more about your background, and what kind of Python script you're writing? That may help us understand the situation. Also, 'DEBUG' is not a mode in Python, but instead a compiler-time flag when compiling C binaries in Visual C++. This doesn't have anything to do with Python really, and has more to do with the way that Microsoft libraries are organized. In fact, many people who start off using Python don't need to touch the DEBUG flag or Visual C++. > but i don=B4t know how to start the script in debug . The compiler want= =B4s > a .exe or .com file, but i=B4ve got only .py files and the .dll which ein > need under windows. So, can anyone tell me, how to start debug ? I'm still confused: are you trying to compile '.py' into '.exe' files? Since Python is an interpreted language, you don't need to compile '.py' files at all. 'python.exe' is the interpreter used to interpret a '.py' file. [lightbulb appears overhead] =2E.. Wait a minute! Are you trying to run the Visual C++ debugger on a Python file? If so, this won't work because Visual C++ has no idea how Python works. Just because Python itself is written in C doesn't mean that you should debug a Python program with a C debugger. A C debugger works at a level of abstraction, and you probably won't be able to discern what the program is doing. In fact, the C debugger would probably show too much detail about Python's interpreter loop, making the debugging quite miserable. Instead, you may want to use the Python Debugger for debugging your Python scripts: http://www.python.org/doc/current/lib/module-pdb.html It's better suited for debugging Python programs. I hope that I'm reading your intention correctly. Please feel free to ask more questions. Good luck! From linuxconsult@yahoo.com.br Thu May 2 02:56:17 2002 From: linuxconsult@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito) Date: Wed, 1 May 2002 22:56:17 -0300 Subject: Writing one-liners in Python (was: Re: [Tutor] help mee) In-Reply-To: <000801c1f15f$98dc8320$c080f718@Compaq> References: <000801c1f15f$98dc8320$c080f718@Compaq> Message-ID: <20020502015617.GA8825@ime.usp.br> On May 01 2002, Del Kollhoff wrote: > how do you put a plain text program into python command line? Perhaps you should use the -c option of the python interpreter? Something like: $ python -c 'print "a"' But I'd like to use your question as a starting point for a question of mine. Unfortunately, I have the impression that writing one-liners in Python isn't as easy as writing one-liners in Perl (for me at least -- I am still a newbie in Python). The reason for my impression is that there aren't block delimiters like C's or Perl's "{" and "}" available in Python. As a result, I don't know how one would convert to a one-liner, say, something along the lines of the following code: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - while (cond1 and cond2): # do something # now, which condition failed? cond1 or cond2? if (cond1): # cond2 failed and cond2 didn't else: # cond1 failed - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - So, while converting this to a one-liner, how does one indicate to that the if is not contained within the while loop? Any help with this issue would be more than welcome. Thanks in advance, Roger... -- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/ =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From dyoo@hkn.eecs.berkeley.edu Thu May 2 02:56:59 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 May 2002 18:56:59 -0700 (PDT) Subject: [Tutor] Debug Settings In-Reply-To: Message-ID: > A C debugger works at a level of abstraction, and you probably won't be > able to discern what the program is doing. Ugh. I was supposed to say "A C debugger works at the C level of abstraction, and you probably won't be able to discern what the program is doing at the Python level of abstraction." From dyoo@hkn.eecs.berkeley.edu Thu May 2 03:24:58 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 May 2002 19:24:58 -0700 (PDT) Subject: Writing one-liners in Python (was: Re: [Tutor] help mee) In-Reply-To: <20020502015617.GA8825@ime.usp.br> Message-ID: Hi Roger, > Unfortunately, I have the impression that writing one-liners > in Python isn't as easy as writing one-liners in Perl (for me > at least -- I am still a newbie in Python). Python's design puts constraints on one-liners, and I think it intentionally discourages people from doing one-liners. As an example of such a constraint, we can look at Python's assignment operation: ### a = b ## Assignment ### Assignment in Python is done using a "statement". What distinguishes a statement from the other kind of command that Python allows, the "expression", is that a statement can't be placed "within" another expression: ### (a = b) == None ## <--- Does not work in Python ### while an expression (like a boolean test or the result of a function call) can be imbedded within another expression: ### someFunctionCall((a == b) or (c < d) and not e, f) ### So Python really tries to make statements like assignment stand alone in a line. This is in contrast with a lot of other languages like C or Perl, which treat assignment as an expression. Personally, I don't think this is a "bad" thing, just because assignment can be a scary thing, and it's often good to have it stand out in a program. > The reason for my impression is that there aren't block > delimiters like C's or Perl's "{" and "}" available in Python. Very true: that's another constraint that narrows down the space for writing one liners. This is not to say it's not possible in Python: it's just that they're very hard to write and limited in what they can do... or maybe not! http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.015.htp I dunno, I feel a little sick when I see something like this. *grin* > As a result, I don't know how one would convert to a > one-liner, say, something along the lines of the following > code: > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > while (cond1 and cond2): > # do something > > # now, which condition failed? cond1 or cond2? > if (cond1): > # cond2 failed and cond2 didn't > else: > # cond1 failed To tell the truth, neither do I. I'm not seeing an immediate way to do this in one line in any language without severely sacrificing readability. FAQ entry 4.15 above showed how evil some of those nested expressions can get, so it might be possible, but may not be edifiable. Or is that editable? Good luck to you! From dman@dman.ddts.net Thu May 2 03:51:20 2002 From: dman@dman.ddts.net (dman) Date: Wed, 1 May 2002 21:51:20 -0500 Subject: Writing one-liners in Python (was: Re: [Tutor] help mee) In-Reply-To: References: <20020502015617.GA8825@ime.usp.br> Message-ID: <20020502025120.GA32051@dman.ddts.net> --EVF5PPMfhYS0aIcm Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 01, 2002 at 07:24:58PM -0700, Danny Yoo wrote: =20 | > Unfortunately, I have the impression that writing one-liners | > in Python isn't as easy as writing one-liners in Perl That's true, and it's by design. One-liners, while cute at first, are hard to comprehend or maintain in the long run. =20 | http://www.python.org/cgi-bin/faqw.py?req=3Dshow&file=3Dfaq04.015.htp Those are neat for show, but I wouldn't use them for anything else. Does anyone have a copy of that christmas tree one-liner someone posted on c.l.py a year or two ago? It was pretty cool and even involved checking the date. -D --=20 Be sure of this: The wicked will not go unpunished, but those who are righteous will go free. Proverbs 11:21 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --EVF5PPMfhYS0aIcm Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzQqagACgkQO8l8XBKTpRSlBQCgpvGSNOYy5p5t/XZsksDwHpF8 eukAnjdDs3YDYpNgZQ/BBhrJ8T8uosbZ =gfjy -----END PGP SIGNATURE----- --EVF5PPMfhYS0aIcm-- From hsteiger@comcast.net Thu May 2 05:47:48 2002 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Wed, 01 May 2002 23:47:48 -0500 Subject: [Tutor] Two questions Message-ID: <000801c1f194$833d21c0$0201a8c0@eagle> This is a multi-part message in MIME format. --Boundary_(ID_XS+CDA4saXBlvvm1QLKiew) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT To All: Question # 1 How can one append different types of variables together and store into a variable? For example, in the Tcl language, one can do the following: append site_id "$day$ob_time $wind $temp/$dwpt A$pres$equal_sign" The above example appends to the variable site_id, all the other variables located to the right. This piece of code appends different types of data together, integers, floats, and characters or strings (i.e. the letter A, and the equal sign). And notice that site_id will also contain the spaces located between some of the variables. There is a string.join function in Python, but this is used only to join different "strings" together. I cannot however find an example of how to combine different data forms together (strings, integers, floats, etc.) like my example above does in Tcl. Question # 2 I also see that one can change a string into an integer using string.atoi, but I cannot find a funtion that changes an integer or float into a string. Is there one in Python? I bet there is! The Quick Python Book that I have does not show one. Question # 3 Finally, is there a Web link that one can go to that describes each function in each Python module? For example, if I wanted to know what functions are available in the "time" or "string" modules, along with descriptions of each funtion and examples of how to use each, where can one go to get this information. Most Python books do not contain descriptions of each and every function in each and every Python module that comes with the language. Having this information would help one better understand the various functions, and hence more easily write Python programs. Thanks much ahead of time to anyone that responds! Henry Steigerwaldt Hermitage, TN --Boundary_(ID_XS+CDA4saXBlvvm1QLKiew) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: 7BIT
To All:
 
Question # 1
 
How can one append different types of variables together and store into a variable?
 
For example, in the Tcl language, one can do the following:
 
append site_id "$day$ob_time  $wind  $temp/$dwpt  A$pres$equal_sign"
 
The above example appends to the variable site_id, all the other variables located
to the right. This piece of code appends different types of data together, integers,
floats, and characters or strings (i.e. the letter A, and the equal sign). And notice
that site_id will also contain the spaces located between some of the variables.
 
There is a string.join function in Python, but this is used only to join different
"strings" together. I cannot however find an example of how to combine different
data forms together (strings, integers, floats, etc.) like my example above does in
Tcl.
 
Question # 2 
 
I also see that one can change a string into an integer using string.atoi, but I cannot
find a funtion that changes an integer or float into a string. Is there one in Python? I bet
there is! The Quick Python Book that I have does not show one.
 
Question # 3
 
Finally, is there a Web link that one can go to that describes each function in each
Python module? For example, if I wanted to know what functions are available in the
"time" or "string" modules, along with descriptions of each funtion and examples of
how to use each, where can one go to get this information.
 
Most Python books do not contain descriptions of each and every function in each
and every Python module that comes with the language. Having this information
would help one better understand the various functions, and hence more easily write
Python programs.
 
Thanks much ahead of time to anyone that responds!
 
Henry Steigerwaldt
Hermitage, TN
 
--Boundary_(ID_XS+CDA4saXBlvvm1QLKiew)-- From tbrauch@tbrauch.com Thu May 2 05:57:05 2002 From: tbrauch@tbrauch.com (Timothy M. Brauch) Date: Thu, 2 May 2002 00:57:05 -0400 Subject: [Tutor] Two questions References: <000801c1f194$833d21c0$0201a8c0@eagle> Message-ID: <001401c1f195$cea622a0$1f01040a@centre.edu> I'll leave the first question to someone better suited to answer it, but I can try to answer the other two. >To All: > >Question # 1 > >How can one append different types of variables together and store into a variable? > >For example, in the Tcl language, one can do the following: > >append site_id "$day$ob_time $wind $temp/$dwpt A$pres$equal_sign" > >The above example appends to the variable site_id, all the other variables located >to the right. This piece of code appends different types of data together, integers, >floats, and characters or strings (i.e. the letter A, and the equal sign). And notice >that site_id will also contain the spaces located between some of the variables. > >There is a string.join function in Python, but this is used only to join different >"strings" together. I cannot however find an example of how to combine different >data forms together (strings, integers, floats, etc.) like my example above does in >Tcl. > >Question # 2 > >I also see that one can change a string into an integer using string.atoi, but I cannot >find a funtion that changes an integer or float into a string. Is there one in Python? I bet >there is! The Quick Python Book that I have does not show one. > Try using str(x) to change x into a string. Similarly, you can use int(x) to attempt to change x into an int and float(x) to change x into a float. And, if you are so inclined, you can do float(str(int(x))). I'll leave it up to you to guess what the final result is. > >Question # 3 > >Finally, is there a Web link that one can go to that describes each function in each >Python module? For example, if I wanted to know what functions are available in the >"time" or "string" modules, along with descriptions of each funtion and examples of >how to use each, where can one go to get this information. > One thing to check is the online Module index available at That will explain most of the modules, and it is easy to find the specific one you are looking for. The other thing is to play around with the dir(x) function. It should tell you what you can do to x. And, if the module is coded nicely, you can try a print x.__str__() and see where that gets you. > >Thanks much ahead of time to anyone that responds! > >Henry Steigerwaldt >Hermitage, TN - Tim From dyoo@hkn.eecs.berkeley.edu Thu May 2 06:29:49 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 1 May 2002 22:29:49 -0700 (PDT) Subject: [Tutor] Two questions [string formatting / str() and repr()] In-Reply-To: <000801c1f194$833d21c0$0201a8c0@eagle> Message-ID: On Wed, 1 May 2002, Henry Steigerwaldt wrote: > How can one append different types of variables together and store into > a variable? > > For example, in the Tcl language, one can do the following: > > append site_id "$day$ob_time $wind $temp/$dwpt A$pres$equal_sign" > > The above example appends to the variable site_id, all the other > variables located to the right. This piece of code appends different > types of data together, integers, floats, and characters or strings > (i.e. the letter A, and the equal sign). And notice that site_id will > also contain the spaces located between some of the variables. Hi Henry, Ah, it looks like you're looking for the "String Formatting" operator. You can say something like this: ### ## Assuming that 'day', 'ob_time', and the other variables ## are already defined locally: site_id = "%(day)s%(ob_time)s %(wind)s %(temp)s/$dwpt)s " \ " A$(pres)s%(equal_sign)s" site_id = site_id % vars() ### which should do the equivalent to how Tcl concatenates strings. Here's a small example: ### >>> book_name = "The TeXBook" >>> author = "Knuth" >>> report = "The book %(book_name)s is written by %(author)s" % vars() >>> print report The book The TeXBook is written by Knuth ### String formatting is particularly well suited to format a string containing different data types. The example above opts for strings, but Formatting will accomodate numeric stuff as well: ### >>> import math >>> pi_to_five_places = "%1.5f" % math.pi >>> print pi_to_five_places 3.14159 >>> pi_to_ten_places = "%1.10f" % math.pi >>> pi_to_ten_places '3.1415926536' ### You can find out more about String Formatting in the Python Tutorial: http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000 and for the gruesome details, the library reference docs will oblige: http://www.python.org/doc/current/lib/typesseq-strings.html > There is a string.join function in Python, but this is used only to join > different "strings" together. I cannot however find an example of how to > combine different data forms together (strings, integers, floats, etc.) > like my example above does in Tcl. string.join() will also work as an alternative, although it involves extra steps to turn things into strings. I think that for your case, String Formatting is an effective way to go. Still, it might be good to see how we might manage with string concatenation. ### >>> 42 + " is the answer" Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand types for +: 'int' and 'str' >>> str(42) + " is the answer" '42 is the answer' >>> `42` + " is the answer" '42 is the answer' ### [Subtle point ahead; ignore when it gets boring. *grin*] The last example, the one using backquotes, uses shorthand for the repr() function: ### >>> repr(42) + " is the answer" '42 is the answer' ### The repr() function is almost like str(), except that repr() is the function that Python uses to "repr"esent data so that we can detect its type. Let's compare the two functions for a moment: ### >>> print str("I am a string") I am a string >>> print repr("I am a string") 'I am a string' ### Note that in the second case, repr() puts quotes around the string, to tell us that it's a string. repr() puts out a string representation that can be directly typed into the interactive interpreter, to get that same value. repr() can give small visual hints and is useful when doing debugging. Don't worry too much about it: usually, str() is what you want. http://python.org/doc/current/lib/built-in-funcs.html explains the definition of repr() in more detail. Anyway, hope this helps. Please feel free to ask more questions. Good luck to you! From shalehperry@attbi.com Thu May 2 06:29:52 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 01 May 2002 22:29:52 -0700 (PDT) Subject: Writing one-liners in Python (was: Re: [Tutor] help mee) In-Reply-To: <20020502015617.GA8825@ime.usp.br> Message-ID: > > As a result, I don't know how one would convert to a > one-liner, say, something along the lines of the following > code: > in shell scripts you could employ cat and HERE documents to send the code in. Usually though anything that begins life as a one liner quickly becomes a real script. Also there is a bit of "use the right tool for the right job". python is not quick and dirty. I usually use awk/sed when I need that and sometimes I dig deep into my psyche and use perl. From shalehperry@attbi.com Thu May 2 06:33:27 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 01 May 2002 22:33:27 -0700 (PDT) Subject: [Tutor] Two questions In-Reply-To: <000801c1f194$833d21c0$0201a8c0@eagle> Message-ID: On 02-May-2002 Henry Steigerwaldt wrote: > To All: > > Question # 1 > > How can one append different types of variables together and store into a > variable? > site_id = "%s%s %s %s/%s A%s%s" % (day, ob_time, wind, temp, dwpt, pres, equal_sign) This is basically C's sprintf(). > > Question # 3 > > Finally, is there a Web link that one can go to that describes each function > in each > Python module? For example, if I wanted to know what functions are available > in the > "time" or "string" modules, along with descriptions of each funtion and > examples of > how to use each, where can one go to get this information. > > Most Python books do not contain descriptions of each and every function in > each > and every Python module that comes with the language. Having this information > would help one better understand the various functions, and hence more easily > write > Python programs. > My fav book is by New Rider's "Essential Python". It has 50 pages of quick python reference and the rest of the book is a module reference. However I spend most of my python coding in an emacs window so I now use the info pages. From marcolinux@linuxbr.com.br Thu May 2 07:01:49 2002 From: marcolinux@linuxbr.com.br (Marco A. Sousa) Date: Thu, 2 May 2002 03:01:49 -0300 Subject: [Tutor] Two questions In-Reply-To: <001401c1f195$cea622a0$1f01040a@centre.edu> References: <000801c1f194$833d21c0$0201a8c0@eagle> <001401c1f195$cea622a0$1f01040a@centre.edu> Message-ID: <20020502030149.A2542@marcolab.net> Timothy M. Brauch (tbrauch@tbrauch.com) wrote: > >Finally, is there a Web link that one can go to that describes each > function in each > >Python module? For example, if I wanted to know what functions are > available in the > >"time" or "string" modules, along with descriptions of each funtion and > examples of > >how to use each, where can one go to get this information. > > > One thing to check is the online Module index available at > That will explain most > of the modules, and it is easy to find the specific one you are looking for. > The other thing is to play around with the dir(x) function. It should tell > you what you can do to x. And, if the module is coded nicely, you can try a > print x.__str__() and see where that gets you. You may also like this post: http://www.daa.com.au/pipermail/pygtk/2002-January/002348.html It's about auto completion in interactive sessions. Help me a lot, to the point I cant live without autocompletion :) Hope it helps. Marco From dyoo@hkn.eecs.berkeley.edu Thu May 2 08:00:15 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 2 May 2002 00:00:15 -0700 (PDT) Subject: [Tutor] A small math puzzle [recreational Python] In-Reply-To: <3CCDFCEA.C017DA3D@mail.verizon.net> Message-ID: On Mon, 29 Apr 2002, Lloyd Hugh Allen wrote: > Oops. Wrong puzzle. Now I feel sheepish. Seems related though (and it's > how I had remembered the puzzle until I reread my own post). > > Sorry 'bout that. Don't worry about it; I think this problem is really subtle. It has this disguise that makes it look trivial, but I still don't know how to solve it. I must find time to read that book on Combinatorial Math that's sitting on my bookshelf. From dyoo@hkn.eecs.berkeley.edu Thu May 2 08:13:23 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 2 May 2002 00:13:23 -0700 (PDT) Subject: [Tutor] A problem: scanning for keywords in a bunch of text? In-Reply-To: Message-ID: On Mon, 29 Apr 2002, Daniel Coughlin wrote: > This is just a thought, and I might be entirely off base, but can you > process the the strings prior to searching through them? If so then you > should be able to create some kind of numerical index on each chunk of > searchable data and that could make your scanning go faster. I have > thought about this for about 20 minutes so it might not make too much > sense or be very clear. No, this makes perfect sense. I think that's a great idea. Python has a function called intern() that I can use to do this: ### >>> print intern.__doc__ intern(string) -> string ``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value. ### I didn't think about using it before. It must have been some unconcious stigma from previous experience with Java, I think. Bug 4035345, to be exact. http://java.sun.com/products/jdk/1.1/knownbugs/runtime.html *grin* But I'll try this out and see if it speeds things up for me. It'll definitely reduce the amount of data I'm throwing around. > If you could process each searchable text (it looks like you might be > seaching through abstracts?) into a list of numbers, you could then > search that list of numbers. And it would be faster then searching the > whole text. Yes, that's what I'm doing. I need to be careful about preserving the ability to match sequences, because some of my keywords are not just words, but really long phrases. The one problem I'm thinking about is, later, I'd like to try extending this so it's not such an exact match. But I'm starting to think I should just use Udi Manber's 'agrep' approximate string-matching utility, now that I've read a bit more about it. http://citeseer.nj.nec.com/muth96approximate.html > It also looks a little less complicated than the suffix trees ;-) Yeah, I don't know what I was thinking. I'm surprised but the Suffix Trees actually work pretty well... but it takes forever to free() the darn things afterwards. Thanks again for the help! From alex@gabuzomeu.net Thu May 2 11:20:41 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Thu, 02 May 2002 12:20:41 +0200 Subject: [Tutor] Two questions In-Reply-To: <20020502044902.28386.91226.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020502120322.00bb0260@pop3.norton.antivirus> Hello Henry, At 00:49 02/05/2002 -0400, you wrote: >Date: Wed, 01 May 2002 23:47:48 -0500 >From: Henry Steigerwaldt >Subject: [Tutor] Two questions >How can one append different types of variables together and store into a >variable? > >For example, in the Tcl language, one can do the following: > >append site_id "$day$ob_time $wind $temp/$dwpt A$pres$equal_sign" Here is a Python equivalent: site_id = "%s%s%s" % (site_id, aValue, anotherValue) Basically, you specify a string "template" and insert variable values into it. Example: >>> titi = 0.1 >>> toto = 1 >>> tutu = "truc" >>> print "%s-%s-%s" % (titi, toto, tutu) 0.1-1-truc For more details, see: http://www.python.org/doc/current/lib/typesseq-strings.html >I also see that one can change a string into an integer using string.atoi, >but I cannot find a funtion that changes an integer or float into a >string. Is there one in Python? You can use the str() function. >Finally, is there a Web link that one can go to that describes each >function in each Python module? For example, if I wanted to know what >functions are available in the "time" or "string" modules, along with >descriptions of each funtion and examples of how to use each, where can >one go to get this information. You want the "Python Library Reference"; it is part of the standard Python doc. See: http://www.python.org/doc/ If you run Windows, the doc in HTML help format is very handy: http://www.orgmf.com.ar/condor/pytstuff.html#python Cheers. Alexandre From alex@gabuzomeu.net Thu May 2 11:39:27 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Thu, 02 May 2002 12:39:27 +0200 Subject: [Tutor] help mee In-Reply-To: <20020502044902.28386.91226.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020502115233.00b22c00@pop3.norton.antivirus> Hello Del, At 00:49 02/05/2002 -0400, you wrote: >From: "Del Kollhoff" >Date: Wed, 1 May 2002 18:29:02 -0400 >Subject: [Tutor] help mee >how do you put a plain text program into python command line? To run a Python programm, you can: 1) Run it directly in the system command line (eg. DOS box if you run Windows, shell if you run a Unix-like system). Basically, the command: python myscript.py should work, but this is system-specific. For more information, please tell us which system you run. 2) You can also import a module into the Python command line (I think this is what you asked). - Save your script in a text file. Call it myscript.py. In Python, this file is called a module. - Start the Python interpreter. - On the Python command line (>>>), try: import myscript Top-level Python code in the programm will run directly. Objects defined in "myscript" can be accessed individually. Eg. if "myscript" contains a function called "myFunction", try this to run it: myscript.myFunction() Cheers. Alexandre From stuart_clemons@us.ibm.com Thu May 2 15:25:11 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Thu, 2 May 2002 10:25:11 -0400 Subject: [Tutor] Book with extensive examples of string, list, and os modules ? Message-ID: --0__=0ABBE13EDFD8076D8f9e8a93df938690918c0ABBE13EDFD8076D Content-type: text/plain; charset=US-ASCII Hi all: I'm a newbie having a lot of fun and frustration with Python as I write my first Python app to help with a WinNT admin task. I have a number of other apps relating to WinNT admin that I plan to write. To help get me up to speed, I've gone thru parts of a couple of the on-line tutorials and I've purchased the "Learning Python" and "Python 2.1 Bible". Most of what I need to do is text based. While I've made pretty good progress thru trial & error and looking thru the learning materials, I found that most of the examples of string and list are pretty limited and pretty similar in most of the materials, and sometimes the examples are exactly the same in the materials. Can anyone recommend a book that has extensive examples of the use of string and lists ? (Actually, the Python 2.1 Bible is pretty comprehensive in showing the various string methods and functions, but they don't have enough code examples for a newbie like me.) Anyway, any book recommendation will be greatly appreciated. Thanks. -Stuart --0__=0ABBE13EDFD8076D8f9e8a93df938690918c0ABBE13EDFD8076D Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Hi all:

I'm a newbie having a lot of fun and frustration with Python as I write my first Python app to help with a WinNT admin task. I have a number of other apps relating to WinNT admin that I plan to write.

To help get me up to speed, I've gone thru parts of a couple of the on-line tutorials and I've purchased the "Learning Python" and "Python 2.1 Bible".

Most of what I need to do is text based. While I've made pretty good progress thru trial & error and looking thru the learning materials, I found that most of the examples of string and list are pretty limited and pretty similar in most of the materials, and sometimes the examples are exactly the same in the materials.

Can anyone recommend a book that has extensive examples of the use of string and lists ? (Actually, the Python 2.1 Bible is pretty comprehensive in showing the various string methods and functions, but they don't have enough code examples for a newbie like me.)

Anyway, any book recommendation will be greatly appreciated. Thanks.

-Stuart --0__=0ABBE13EDFD8076D8f9e8a93df938690918c0ABBE13EDFD8076D-- From rob@uselesspython.com Thu May 2 15:53:06 2002 From: rob@uselesspython.com (Rob Andrews) Date: Thu, 02 May 2002 09:53:06 -0500 Subject: [Tutor] Book with extensive examples of string, list, and os modules ? References: Message-ID: <3CD152D2.7040202@uselesspython.com> For ready access to code examples, I recommend the following. They aren't books, but online resources: Python Cookbook: http://aspn.activestate.com/ASPN/Python/Cookbook/ Useless Python (still in reconstruction, but quite handy): http://uselesspython.com Vaults of Parnassus: http://www.vex.net/parnassus/ Tutor List Archives: http://mail.python.org/pipermail/tutor/ Rob Andrews stuart_clemons@us.ibm.com wrote: > Hi all: > > I'm a newbie having a lot of fun and frustration with Python as I write > my first Python app to help with a WinNT admin task. I have a number of > other apps relating to WinNT admin that I plan to write. > > To help get me up to speed, I've gone thru parts of a couple of the > on-line tutorials and I've purchased the "Learning Python" and "Python > 2.1 Bible". > > Most of what I need to do is text based. While I've made pretty good > progress thru trial & error and looking thru the learning materials, I > found that most of the examples of string and list are pretty limited > and pretty similar in most of the materials, and sometimes the examples > are exactly the same in the materials. > > Can anyone recommend a book that has extensive examples of the use of > string and lists ? (Actually, the Python 2.1 Bible is pretty > comprehensive in showing the various string methods and functions, but > they don't have enough code examples for a newbie like me.) > > Anyway, any book recommendation will be greatly appreciated. Thanks. > > -Stuart > From shalehperry@attbi.com Thu May 2 16:15:13 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu, 02 May 2002 08:15:13 -0700 (PDT) Subject: [Tutor] Book with extensive examples of string, list, and os In-Reply-To: Message-ID: > > Can anyone recommend a book that has extensive examples of the use of > string and lists ? (Actually, the Python 2.1 Bible is pretty comprehensive > in showing the various string methods and functions, but they don't have > enough code examples for a newbie like me.) > > Anyway, any book recommendation will be greatly appreciated. Thanks. > most of the python modules are written in python and many of them are actually easy to read and understand. Good code written by some of the best and oldest python coders is a great learning tool. From kojo@hal-pc.org Thu May 2 16:26:56 2002 From: kojo@hal-pc.org (Kojo Idrissa) Date: Thu, 02 May 2002 10:26:56 -0500 Subject: [Tutor] Book with extensive examples of string, list, and os In-Reply-To: References: Message-ID: <5.1.0.14.0.20020502102453.00af0950@mail.hal-pc.org> --=====================_2010671==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed Python. It's a language and a teaching tool, all in one!! Coming soon, Python: Desert Topping and Floor Wax. :-) At 08:15 AM 5/2/2002 -0700, Sean 'Shaleh' Perry wrote: >most of the python modules are written in python and many of them are actually >easy to read and understand. Good code written by some of the best and oldest >python coders is a great learning tool. **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** --=====================_2010671==_.ALT Content-Type: text/html; charset="us-ascii" Python.  It's a language and a teaching tool, all in one!!  Coming soon, Python: Desert Topping and Floor Wax.
:-)

At 08:15 AM 5/2/2002 -0700, Sean 'Shaleh' Perry wrote:

most of the python modules are written in python and many of them are actually
easy to read and understand.  Good code written by some of the best and oldest
python coders is a great learning tool.

****************************
Kojo Idrissa
 
kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
**************************** --=====================_2010671==_.ALT-- From jeff@ccvcorp.com Thu May 2 19:17:48 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 02 May 2002 11:17:48 -0700 Subject: [Tutor] Two questions References: <000801c1f194$833d21c0$0201a8c0@eagle> Message-ID: <3CD182CC.37003015@ccvcorp.com> Henry Steigerwaldt wrote: > How can one append different types of variables together and store > into a variable? For example, in the Tcl language, one can do the > following: append site_id "$day$ob_time $wind $temp/$dwpt > A$pres$equal_sign" Other people have shown you several different ways that you can create a string from any number of different types of Python data, but I wonder if there isn't some other aspect to your question. I don't know Tcl well, but I have heard that "everything is a string". This makes me wonder if you're hoping to keep using each different type of variable as its own type (doing math on numbers, for instance). In Python, once you convert everything to a string (as previous examples have shown), then it's just a string. You can't do math on it (well, you can add strings, but "1" + "2" is "12", not 3), or any other operation that you'd normally do on the original type. You'd normally do this if you're going to present the information to a user in some way (like printing it to the screen). If what you want is to still use each of these as individual variables, but just be able to sling them around as a unit, you need to look at classes. A class instance is an object, much like other variables, but instead of having a "value" itself, it holds references to any number of other objects. Often, many of those objects are special functions that are intended to work on the instance itself -- these are called "methods". When you call these methods using the normal syntax (object.method()), then the first parameter the method receives will always be a reference to the object itself (and, by convention, is just called 'self' in Python). Here's a short example, using a some of your variables (and a few semi-fancy features), just to give you an idea of what can be done. (Note that __init__() is a special method that gets called when the object is created.) >>> class site: ... day = None ... time = None ... temp = None ... dewpt = None ... wind = None ... # This initializes several attributes to the ... # special value of None ... def __init__(self, id, **kwargs): ... self.id = id ... for key in kwargs: ... # kwargs is a special dictionary, of keyword arguments ... if hasattr(self, key): ... # This will only set values if the attribute ... # already exists, from the default class definition ... setattr(self, key, kwargs[key]) ... >>> s1 = site(1) # Create a new site object >>> s1.id # It has an ID of 1 1 >>> s1.temp # temp is None, so nothing is displayed >>> s1.temp = 47 # Now we set the temp... >>> s1.temp # ...and now it is displayed! 47 >>> s2 = site(2, temp=35, dewpt=37) # Another site object >>> # Note that I passed in two keyword arguments! >>> s2.id # This one has an ID of 2 2 >>> s2.temp # My special method stuff has set temp for me 35 >>> s2.dewpt # and also set dewpt 37 >>> s2.wind # but all the others are still None >>> s3 = site(3, temp=42, rainfall=2) # A third site >>> # One of those keywords didn't exist in the class... >>> s3.temp # temp still got set properly... 42 >>> s3.rainfall # but what happens here? Traceback (most recent call last): File "", line 1, in ? AttributeError: site instance has no attribute 'rainfall' >>> # the rainfall attribute didn't get set, since it wasn't already >>> # in the class definition! >>> Hope that this gives you some ideas of the possibilities. There's lots of tutorials that cover object-oriented programming in Python, find one and work through it for more details. And of course, don't be afraid to ask more questions here! :) Jeff Shannon Technician/Programmer Credit International From qwerqe@earthlink.net Thu May 2 14:54:52 2002 From: qwerqe@earthlink.net (William Monroe) Date: Thu, 02 May 2002 06:54:52 -0700 Subject: [Tutor] creating file objects Message-ID: Hello, i'v ebene programmingi n python for awhile now, and i was just recently trying to work on file objects. i can open, read, and write. but i was wondering how i can create a new file object out of nothing. as in make a text file called test. i run linux 2.4 so i was trying the fdopen command but i'm not sure i was getting it write. specificly i was trying to write a simple text editor and everything works except for the creating a new file. thanks -willis From dyoo@hkn.eecs.berkeley.edu Thu May 2 23:59:08 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 2 May 2002 15:59:08 -0700 (PDT) Subject: [Tutor] creating file objects In-Reply-To: Message-ID: > Hello, i'v ebene programmingi n python for awhile now, and i was just > recently trying to work on file objects. i can open, read, and write. > but i was wondering how i can create a new file object out of nothing. > as in make a text file called test. > > i run linux 2.4 so i was trying the fdopen command but i'm not sure i > was getting it write. Hi William, You can just use the open() command that you used to write to files: it will automatically create the file for you. For example: ### >>> open("filedoesnotexist") Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'filedoesnotexist' >>> open("filedoesnotexist", "w") >>> open("filedoesnotexist") ### Hope this helps! From dman@dman.ddts.net Fri May 3 01:08:25 2002 From: dman@dman.ddts.net (dman) Date: Thu, 2 May 2002 19:08:25 -0500 Subject: [Tutor] creating file objects In-Reply-To: References: Message-ID: <20020503000825.GA17225@dman.ddts.net> --EVF5PPMfhYS0aIcm Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, May 02, 2002 at 03:59:08PM -0700, Danny Yoo wrote: |=20 | > Hello, i'v ebene programmingi n python for awhile now, and i was just | > recently trying to work on file objects. i can open, read, and write. | > but i was wondering how i can create a new file object out of nothing. | > as in make a text file called test. | > | > i run linux 2.4 so i was trying the fdopen command but i'm not sure i | > was getting it write. |=20 | Hi William, |=20 | You can just use the open() command that you used to write to files: it | will automatically create the file for you.=20 Note that the directory in which you are creating the file must exist before you call open(). There are functions in the os and os.path modules to work with paths and directories and other file details. -D --=20 A)bort, R)etry, D)o it right this time =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --EVF5PPMfhYS0aIcm Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzR1PkACgkQO8l8XBKTpRT4CwCfSZdqpH6cC2xQtADRjKAuk1ZN sPQAn1D0+Mpf3Pny6cmyKpt7qdaUK6E8 =xiIH -----END PGP SIGNATURE----- --EVF5PPMfhYS0aIcm-- From rab121@york.ac.uk Fri May 3 10:58:00 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Fri, 03 May 2002 10:58:00 +0100 Subject: [Tutor] Working Directory Message-ID: <3CD25F28.A664CD26@york.ac.uk> Hello, Just before I start, thankyou everyone, I have been reading Tutor for months now, and have extracted much useful information from it, groovy. I am currently working on a little app and am having difficulties with finding out about what directory I am working in. I need this information for two reasons, 1. for the creation and use of a ConfigParser object and related file. 2. To import a module held in the same directory as the module that I am currently working on. I am aware 2. is not a pretty reason for using this information, I should be sticking the imported module somewhere more sensible, using packages for example, but I haven't read up on such things yet (my shiny new copy of Programming Python came in the post yesterday), and thought that as I needed the same stuff for 1. I might as well reuse it. Solutions then: os.getcwd() won't always return the directory in which my main module is hiding. I don't want to hard code the directory in, for obvious reasons. I can't think of a way in which passing the directory as an command line argument will guarantee precision. I am perhaps missing the obvious function that will tell what I need? All help gratefully received :o) Thankyou very much, Russell -- http://www.bigmaddrongo.com President of York University Trampoline Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From pythontutor@venix.com Fri May 3 13:10:35 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Fri, 03 May 2002 08:10:35 -0400 Subject: [Tutor] Working Directory References: <3CD25F28.A664CD26@york.ac.uk> Message-ID: <3CD27E3B.6000802@venix.com> >>> import mx.DateTime >>> mx.DateTime.__file__ 'F:\\Python22\\Lib\\site-packages\\mx\\DateTime\\__init__.pyc' I hope this fits the bill. I believe that if the module comes from your current directory, it simply returns the file name. Russell Bungay wrote: > Hello, > > Just before I start, thankyou everyone, I have been reading Tutor for > months now, and have extracted much useful information from it, groovy. > > I am currently working on a little app and am having difficulties with > finding out about what directory I am working in. I need this > information for two reasons, 1. for the creation and use of a > ConfigParser object and related file. 2. To import a module held in the > same directory as the module that I am currently working on. > > I am aware 2. is not a pretty reason for using this information, I > should be sticking the imported module somewhere more sensible, using > packages for example, but I haven't read up on such things yet (my shiny > new copy of Programming Python came in the post yesterday), and thought > that as I needed the same stuff for 1. I might as well reuse it. > > Solutions then: > > os.getcwd() won't always return the directory in which my main module is > hiding. > I don't want to hard code the directory in, for obvious reasons. > I can't think of a way in which passing the directory as an command line > argument will guarantee precision. > I am perhaps missing the obvious function that will tell what I need? > > All help gratefully received :o) > > Thankyou very much, > > Russell > -- > http://www.bigmaddrongo.com > President of York University Trampoline Club: > http://york.trampolining.net > Chair of The York Glee Singers: > http://www.gleesingers.co.uk > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From its_steevo@hotmail.com Fri May 3 15:30:41 2002 From: its_steevo@hotmail.com (steve king) Date: Fri, 03 May 2002 15:30:41 +0100 Subject: [Tutor] unicode files Message-ID: Hello, I am relatively new to Python so don't laugh if what I ask is painfully obvious... (or just plain wrong!!!) I have worked out how to open a file and how to write to it, but I need the file to be in unicode. I know there is a unicode() function but there isn't a great deal of documentation on how to use it. Is it a case of creating the file, writing to it and then saving it as unicode, or would I be better off writing the strings as unicode and then saving the file? At the moment I have something like this: import sys starting_dir=raw_input("Dir and file please: ") somename=starting_dir file=open(somename, 'w') file.write("The first line of a file") file.close() _________________________________________________________________ Join the world’s largest e-mail service with MSN Hotmail. http://www.hotmail.com From alan.gauld@bt.com Fri May 3 15:49:42 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 3 May 2002 15:49:42 +0100 Subject: [Tutor] Two questions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C59C@mbtlipnt02.btlabs.bt.co.uk> > >How can one append different types of variables together and > store into a variable? > > > >For example, in the Tcl language, one can do the following: > > > >append site_id "$day$ob_time $wind $temp/$dwpt A$pres$equal_sign" There is no direct equivalent in Python, it depends what you are using it for: Packed Storage: The nearest is probably the struct module. The conversion is not transparent as you have to etell struct about the types of data you are storing. Output formatting: The format string operation is best for that Encapsulation/Binding A tuple or class would be best. A Tuple is immutable (I think the Tcl append is too?) but a class can be changed. The clsass is more flexible in extracting the data - you don't need to know the location (as in the tuple) merely the name... > >There is a string.join function in Python, but this is used > only to join different "strings" together. I cannot however > find an example of how to combine different data forms together If its just a string representation then string formatting will do that just like Tcls format operation. Alan g. From alan.gauld@bt.com Fri May 3 16:07:54 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 3 May 2002 16:07:54 +0100 Subject: Writing one-liners in Python (was: Re: [Tutor] help mee) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C59E@mbtlipnt02.btlabs.bt.co.uk> > > As a result, I don't know how one would convert to a > > one-liner, say, something along the lines of the following > > code: > Also there is a bit of "use the right tool for the right > job". python is not quick and dirty. I usually use awk/sed I tend to agree with this but there is one other solution for 'non trivial' one liners that I'm surprised nobody has mentioned yet: The python prompt. Many things I'd do in Perl as a 'one liner' I do in Python by starting up the interactive prompt and typing the script one line at a time. It's a throwaway program like a one liner but more powerful too. I know Perl has a kind of interactive mode but it takes a whole script and compiles it and runs it after an EOF. Pythons real interpreter mode is more suitable for the one liner type programs IMHO. Alan G. From alan.gauld@bt.com Fri May 3 16:13:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 3 May 2002 16:13:01 +0100 Subject: [Tutor] Book with extensive examples of string, list, and os modules ? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C59F@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C1F2B5.0430E480 Content-type: text/plain; charset="iso-8859-1" > with a WinNT admin task. I have a number of other apps relating to WinNT admin The WinNT bit immediately suggests you should rush out and buy Hammonds O'Reilly book about Python on Win32. Its a must have for anyone doing OS level things on Win32 platforms. It won't help with the string stuff particularly but the os stuff for sure. On the string front, if you have specififc questions why not just post them here? Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld ------_=_NextPart_001_01C1F2B5.0430E480 Content-type: text/html; charset="iso-8859-1"

 >  with a WinNT admin task. I have a number of other apps relating to WinNT admin  
 
The WinNT bit immediately suggests you should rush out
and buy Hammonds O'Reilly book about Python on Win32.
Its a must have for anyone doing OS level things on Win32
platforms.
 
It won't help with the string stuff particularly but
the os stuff for sure.
 
On the string front, if you have specififc questions why
not just post them here?
 

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld

 
 
------_=_NextPart_001_01C1F2B5.0430E480-- From shalehperry@attbi.com Fri May 3 16:17:09 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri, 03 May 2002 08:17:09 -0700 (PDT) Subject: Writing one-liners in Python (was: Re: [Tutor] help mee) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C59E@mbtlipnt02.btlabs.bt.co.uk> Message-ID: > > I tend to agree with this but there is one other solution > for 'non trivial' one liners that I'm surprised nobody > has mentioned yet: > > The python prompt. > > Many things I'd do in Perl as a 'one liner' I do in Python > by starting up the interactive prompt and typing the script > one line at a time. It's a throwaway program like a one liner > but more powerful too. > This requires too much mucking about with files and import statements. If I have to go to this level I usually just write a script. From ak@silmarill.org Fri May 3 16:28:03 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 3 May 2002 11:28:03 -0400 Subject: [Tutor] standard lib methods list Message-ID: <20020503152803.GA7853@ak.silmarill.org> Hello, I'm making a list of keywords for vim completion and I need a list of all methods in standard lib. Is there a list somewhere with all of them, or should I read libref and make it manually? Thanks, - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From yduppen@xs4all.nl Fri May 3 17:13:02 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Fri, 3 May 2002 18:13:02 +0200 Subject: [Tutor] unicode files In-Reply-To: References: Message-ID: <200205031612.g43GCx5C046084@smtpzilla2.xs4all.nl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Steve, > Is it a case of creating the file, writing to it and then saving it as > unicode, or would I be better off writing the strings as unicode and then > saving the file? I'll come to that; however, from your question I got the feeling I'd better first explain a bit on file I/O in Python. When you 'open' a file for writing, a new file is created immediately; under the hood, this involves some interaction with the operating system where special resources are allocated; Then, whenever you call 'write', the text you write is _immediately_ written to the file. Finally, by calling 'close' you tell the operating system that all those special resources are no longer needed and that it can clean up your mess :). In other words, 'close'-ing a file is not at all similar to 'save'-ing a file like you do in a text-editor. (Hopefully this also clarifies that when you read a file, you should call 'close' as well -- when you read a file, special resources are allocated as well, and they too should be cleaned up). As you can see, since Python does not support the concept of 'save'-ing a file, you can not save it as unicode. Therefore your only option is to write your strings as unicode. (Note: in reality, 'write' does not always write your text to file immediately, due to a technique called buffering. 'close' also makes sure that everything is really really written to disk. So always call 'close' at the end) > At the moment I have something like this: > > import sys > > starting_dir=raw_input("Dir and file please: ") > somename=starting_dir > file=open(somename, 'w') > file.write("The first line of a file") > file.close() Writing unicode strings can be done as follows: file.write(unicode("The first line of a file")) or (if you write constant strings like in this example): file.write(u"The first line of a file") As I said, be sure to _always_ close the file, so you'd better do: file = open(somename, 'w') try: file.write("The first line of a file") finally: file.close() Hope this helps, YDD - -- .sigmentation Fault -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE80rcRLsKMuCf5EdwRAsJiAKCc3CnXcLnCmlH6yigGI3kJgwarRgCg+bEF 8ApNLgyKJQ/p1r3eO0q8TKo= =OPMc -----END PGP SIGNATURE----- From dman@dman.ddts.net Fri May 3 17:31:15 2002 From: dman@dman.ddts.net (dman) Date: Fri, 3 May 2002 11:31:15 -0500 Subject: [Tutor] unicode files In-Reply-To: References: Message-ID: <20020503163115.GB23461@dman.ddts.net> --CE+1k2dSO48ffgeK Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, May 03, 2002 at 03:30:41PM +0100, steve king wrote: | Hello, |=20 | I am relatively new to Python so don't laugh if what I ask is painfully= =20 | obvious... (or just plain wrong!!!) |=20 | I have worked out how to open a file and how to write to it, but I need t= he=20 | file to be in unicode. I know there is a unicode() function but there isn= 't=20 | a great deal of documentation on how to use it. |=20 | Is it a case of creating the file, writing to it and then saving it as=20 | unicode, or would I be better off writing the strings as unicode and then= =20 | saving the file? At the programmer level there is no such thing as "saving a file". You can write data to a file, and that's "all". The term "save as" only really applies to user interfaces where the user must pick which branch of the program to have write the data to the file. | At the moment I have something like this: |=20 | import sys |=20 | starting_dir=3Draw_input("Dir and file please: ") | somename=3Dstarting_dir | file=3Dopen(somename, 'w') | file.write("The first line of a file") | file.close() This works as long as the bytes in that string literal are exactly what you want in the file. The only difference when using unicode, for example, is converting that sequence of bytes/characters to the sequence of bytes that you want. Since unicode characters are multi-byte, various serialization schemes exist to allow putting the characters into a byte stream (file). Some of those encodings are UCS-4 UCS-2 UTF-16 UTF-7 and UTF-8. UTF-8 is the most widely known and has many advantages over the other encodings. If you want to read/write UTF-8 encoded data the following code will do it : f =3D open( "the_file" , "r+" ) f.write( "some data\n".encode( 'utf-8' ) ) f.seek( 0 ) raw_data =3D f.readline() unicode_string =3D raw_data.decode( 'utf-8' ) print repr( unicode_string ) f.close() This example isn't very interesting, though, because UTF-8 is designed so that US-ASCII is a proper subset of it. IOW, for characters 0x00-0x7f, US-ASCII and UTF-8 are identical (and so is ISO-8859-*). To make this more interesting use some data that lies outside the US-ASCII range. If you try to print the string, though, you'll likely get an error such as : >>> print u"\u20ac" Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) >>>=20 The reason for this is python doesn't know how I want to encode (serialize) the characters for output to my display. I can print the repr() of the string, though, since that only uses ASCII characters. >>> print repr( u"\u20ac" ) u'\u20ac' >>> HTH, -D --=20 If Microsoft would build a car... =2E.. Occasionally your car would die on the freeway for no reason. You would have to pull over to the side of the road, close all of the car windows, shut it off, restart it, and reopen the windows before you could continue. For some reason you would simply accept this. =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --CE+1k2dSO48ffgeK Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzSu1MACgkQO8l8XBKTpRT8jwCfaj9k8iZkSY2vQJieyLEA+6jp Bp4AoKZRMuARleTU2JWhzgaELg+OzESE =H/F8 -----END PGP SIGNATURE----- --CE+1k2dSO48ffgeK-- From alan.gauld@bt.com Fri May 3 17:28:28 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 3 May 2002 17:28:28 +0100 Subject: [Tutor] standard lib methods list Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5A0@mbtlipnt02.btlabs.bt.co.uk> > I'm making a list of keywords for vim completion and I need a list of > all methods in standard lib. Is there a list somewhere with all of > them, or should I read libref and make it manually? Try: for n in dir(__builtins__): if type(eval(n)) == type(open): print n Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From jeff@ccvcorp.com Fri May 3 17:41:43 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 03 May 2002 09:41:43 -0700 Subject: [Tutor] Writing one-liners in Python References: Message-ID: <3CD2BDC7.8CA7B545@ccvcorp.com> Sean 'Shaleh' Perry wrote: > > [Alan Gauld] > > Many things I'd do in Perl as a 'one liner' I do in Python > > by starting up the interactive prompt and typing the script > > one line at a time. It's a throwaway program like a one liner > > but more powerful too. > > This requires too much mucking about with files and import statements. If I > have to go to this level I usually just write a script. I don't see how the interactive prompt requires any more mucking about than writing a script does. For simple tasks, especially if I'm not sure what I'm doing to start with, I find the interactive prompt *very* useful, since I can create objects and then fiddle with them to see what exactly they do. And one of my normal methods of *writing* a script, is to try each bit out in interactive mode first, as I go, to see what works, and then copying that to a script window. I didn't think of interactive mode as being comparable to Perl one-liners because I think it's much more powerful than that. ;) But I can see the similarity -- I do tend to do a moderate amount of interactive fiddling, when I don't think I'll be likely to re-use the code. Jeff Shannon Technician/Programmer Credit International From shalehperry@attbi.com Fri May 3 18:04:22 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri, 03 May 2002 10:04:22 -0700 (PDT) Subject: [Tutor] Writing one-liners in Python In-Reply-To: <3CD2BDC7.8CA7B545@ccvcorp.com> Message-ID: On 03-May-2002 Jeff Shannon wrote: > > > Sean 'Shaleh' Perry wrote: > >> > [Alan Gauld] >> > Many things I'd do in Perl as a 'one liner' I do in Python >> > by starting up the interactive prompt and typing the script >> > one line at a time. It's a throwaway program like a one liner >> > but more powerful too. >> >> This requires too much mucking about with files and import statements. If I >> have to go to this level I usually just write a script. > > I don't see how the interactive prompt requires any more mucking about than > writing a script does. For simple tasks, especially if I'm not sure what I'm > doing to start with, I find the interactive prompt *very* useful, since I can > create objects and then fiddle with them to see what exactly they do. And > one > of my normal methods of *writing* a script, is to try each bit out in > interactive mode first, as I go, to see what works, and then copying that to > a > script window. > usually I can type awk '{print $1" "$5"}' faster than the equivalent python. Handling many simple things requires an import statement. So if I am going to use python and import what I need I tend to do this in a file where I can reuse the results. I too perform rapid testing and experimentation with the interactive interpreter. It is one of the reasons I like python. But there is often a better tool for the job when I just need simple file handling done which is the usual use of one liners. From wonderer@pakistanmail.com Fri May 3 10:31:23 2002 From: wonderer@pakistanmail.com (wonderer@pakistanmail.com) Date: Fri, 03 May 2002 14:31:23 +0500 Subject: [Tutor] Abt strings Message-ID: <3cd22a17.718d.0@pakistanmail.com> Hi all i m fairly new to python and it is driving me crazy. I have a simple problem but i m unable to sort it out My problem is like this. I m using a function which takes a string argument and i usually pass it the string in " " notation. the problem is if i run this program once in a session the string is passed and i get the results. but if i call this function second time it gives message like TypeError :this function requires a string with no null characters not a str can any body help TIA _______________________________________________________________________ Get your free @pakistanmail.com email address http://pakistanmail.com From jeff@ccvcorp.com Fri May 3 18:58:27 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 03 May 2002 10:58:27 -0700 Subject: [Tutor] Writing one-liners in Python References: Message-ID: <3CD2CFC2.9B4AA924@ccvcorp.com> Sean 'Shaleh' Perry wrote: > On 03-May-2002 Jeff Shannon wrote: > > > > Sean 'Shaleh' Perry wrote: > > > >> This requires too much mucking about with files and import statements. If I > >> have to go to this level I usually just write a script. > > > > I don't see how the interactive prompt requires any more mucking about than > > writing a script does. [...] > > usually I can type awk '{print $1" "$5"}' faster than the equivalent python. > Handling many simple things requires an import statement. So if I am going to > use python and import what I need I tend to do this in a file where I can reuse > the results. Ah, here's the difference, then. I never learned awk/sed/etc enough to have those as easily-accessible tools, in my head. Having learned Python before them, I tend to automatically reach for Python for such tasks. I expect that, for someone who's familiar with them, this would be considerably quicker than firing up an interpreter and importing stuff. However, I'm not entirely convinced that it's enough of an advantage to motivate me to learn them. :) Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Fri May 3 19:01:09 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 03 May 2002 11:01:09 -0700 Subject: [Tutor] Abt strings References: <3cd22a17.718d.0@pakistanmail.com> Message-ID: <3CD2D065.D4F653E1@ccvcorp.com> wonderer@pakistanmail.com wrote: > Hi all > i m fairly new to python and it is driving me crazy. > I have a simple problem but i m unable to sort it out > My problem is like this. > I m using a function which takes a string argument and i usually pass it the > string in " " notation. > the problem is if i run this program once in a session the string is passed > and i get the results. > but if i call this function second time it gives message like > TypeError :this function requires a string with no null characters not a str Please post both the full function that you're using, and the exact exception traceback that you get. I can't imagine why it would be failing the second time, unless you're doing something very odd, so we'll need to see exactly what you're doing in order to help. :) Jeff Shannon Technician/Programmer Credit International From alex@gabuzomeu.net Fri May 3 19:01:50 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Fri, 03 May 2002 20:01:50 +0200 Subject: [Tutor] Working Directory In-Reply-To: <20020503160006.19418.19149.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020503194921.00d01100@pop3.norton.antivirus> Hi Russell, At 12:00 03/05/2002 -0400, you wrote: >Date: Fri, 03 May 2002 10:58:00 +0100 >From: Russell Bungay >Subject: [Tutor] Working Directory >I am currently working on a little app and am having difficulties with >finding out about what directory I am working in. I need this >information for two reasons, 1. for the creation and use of a >ConfigParser object and related file. 2. To import a module held in the >same directory as the module that I am currently working on. Here is how I did it in my pet project. Note this project is a package (i.e. the base dir contains an empty "__init__.py" file): import os import yourPackageName def getAppBaseDir(): "Returns the directory path for the application." basePath = os.path.dirname(yourPackageName.__file__) return basePath This function is stored in a library file that is located in the root directory of my app. It return the base directory for the app. Cheers. Alexandre From dman@dman.ddts.net Fri May 3 19:26:51 2002 From: dman@dman.ddts.net (dman) Date: Fri, 3 May 2002 13:26:51 -0500 Subject: [Tutor] standard lib methods list In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5A0@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5A0@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020503182651.GF23461@dman.ddts.net> --ey/N+yb7u/X9mFhi Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, May 03, 2002 at 05:28:28PM +0100, alan.gauld@bt.com wrote: | > I'm making a list of keywords for vim completion and I need a list of | > all methods in standard lib. Is there a list somewhere with all of | > them, or should I read libref and make it manually? |=20 | Try: |=20 | for n in dir(__builtins__): | if type(eval(n)) =3D=3D type(open): | print n For built-in names, just set this in your .vimrc : " this takes effect when the syntax file is loaded let python_highlight_all=3D1 It will highlight names like 'open' and 'Exception'. I don't know of an easy way to get the rest of the standard library, and I'm not even sure having that much color would be helpful :-). -D --=20 The heart is deceitful above all things and beyond cure. Who can understand it? I the Lord search the heart and examine the mind, to reward a man according to his conduct, according to what his deeds deserve. Jeremiah 17:9-10 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --ey/N+yb7u/X9mFhi Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzS1msACgkQO8l8XBKTpRTIiACghl0qghG/K+gxAiqD07qlpQoz oKYAoIy8GPrjpUgVOVf/JSY9r2LTbzXk =pIbB -----END PGP SIGNATURE----- --ey/N+yb7u/X9mFhi-- From dyoo@hkn.eecs.berkeley.edu Fri May 3 19:41:29 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 3 May 2002 11:41:29 -0700 (PDT) Subject: [Tutor] Abt strings In-Reply-To: <3cd22a17.718d.0@pakistanmail.com> Message-ID: On Fri, 3 May 2002 wonderer@pakistanmail.com wrote: > i m fairly new to python and it is driving me crazy. Hello, and welcome! We'll do what we can to make it less stressful. *grin* > My problem is like this. I m using a function which takes a string > argument and i usually pass it the string in " " notation. the problem > is if i run this program once in a session the string is passed and i > get the results. but if i call this function second time it gives > message like TypeError :this function requires a string with no null > characters not a str If you can show us your function, that'll give us some leads why Python's not doing what you want. Please feel free to include code snippets as you ask questions: as long as the code isn't pages long, we'll be happy to take a look at it. Also, error messages are already terse, so paraphrasing an error message any further often strips too much information out of them. If you can include the verbatim error message that will also help us a lot. Good luck to you! From rab121@york.ac.uk Sat May 4 11:51:21 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Sat, 04 May 2002 11:51:21 +0100 Subject: [Tutor] Working Directory References: <3CD25F28.A664CD26@york.ac.uk> <3CD27E3B.6000802@venix.com> Message-ID: <3CD3BD29.ACE842C@york.ac.uk> Lloyd Kvam wrote: > >>> import mx.DateTime > >>> mx.DateTime.__file__ > 'F:\\Python22\\Lib\\site-packages\\mx\\DateTime\\__init__.pyc' >I hope this fits the bill. I believe that if the module comes from >your current directory, it simply returns the file name. Thankyou, my code now looks like: ### gofish.py import bmdutils,ConfigParser,os,os.path,sys gofishdir = os.path.dirname(__file__) sys.path.append(gofishdir) import cards #module in same directory as gofish.py etc Thankyou very much, Russell -- http://www.bigmaddrongo.com President of York University Trampoline Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From ak@silmarill.org Sat May 4 15:00:28 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 4 May 2002 10:00:28 -0400 Subject: [Tutor] standard lib methods list In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5A0@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5A0@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020504140028.GA18793@ak.silmarill.org> On Fri, May 03, 2002 at 05:28:28PM +0100, alan.gauld@bt.com wrote: > > I'm making a list of keywords for vim completion and I need a list of > > all methods in standard lib. Is there a list somewhere with all of > > them, or should I read libref and make it manually? > > Try: > > for n in dir(__builtins__): > if type(eval(n)) == type(open): > print n > Thanks but that only gives a list of a dozen or so keywords.. I need all the methods like .startswith(), math.frexp, etc. In other words, all the python "keywords" (I'm using a wider meaning than python builtin keyword) that you could possibly want to autocomplete in vim. > > Alan g. > Author of the 'Learning to Program' web site > http://www.freenetpages.co.uk/hp/alan.gauld > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ak@silmarill.org Sat May 4 15:01:46 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 4 May 2002 10:01:46 -0400 Subject: [Tutor] standard lib methods list In-Reply-To: <20020503182651.GF23461@dman.ddts.net> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5A0@mbtlipnt02.btlabs.bt.co.uk> <20020503182651.GF23461@dman.ddts.net> Message-ID: <20020504140146.GB18793@ak.silmarill.org> On Fri, May 03, 2002 at 01:26:51PM -0500, dman wrote: > On Fri, May 03, 2002 at 05:28:28PM +0100, alan.gauld@bt.com wrote: > | > I'm making a list of keywords for vim completion and I need a list of > | > all methods in standard lib. Is there a list somewhere with all of > | > them, or should I read libref and make it manually? > | > | Try: > | > | for n in dir(__builtins__): > | if type(eval(n)) == type(open): > | print n > > For built-in names, just set this in your .vimrc : > > " this takes effect when the syntax file is loaded > let python_highlight_all=1 > > It will highlight names like 'open' and 'Exception'. > > I don't know of an easy way to get the rest of the standard library, > and I'm not even sure having that much color would be helpful :-). > But I'm not talking about colors! I want to use ^X^K command in vim to auto-complete a list of keywords.. i.e. string.startswith, math.frexp, and so on - all methods in standard lib. > > -D > > -- > > The heart is deceitful above all things > and beyond cure. > Who can understand it? > > I the Lord search the heart > and examine the mind, > to reward a man according to his conduct, > according to what his deeds deserve. > > Jeremiah 17:9-10 > > GnuPG key : http://dman.ddts.net/~dman/public_key.gpg > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From wolf_binary@hotmail.com Sat May 4 15:16:02 2002 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Sat, 4 May 2002 09:16:02 -0500 Subject: [Tutor] colors Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_000B_01C1F34C.4FAD3520 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all, How do you change the screen colors and text colors in a program? I = have never seen a text color or background color example anywhere. Thanks, Cameron Stoner ------=_NextPart_000_000B_01C1F34C.4FAD3520 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi all,
 
How do you change the screen colors and = text colors=20 in a program?  I have never seen a text color or background color = example=20 anywhere.
 
Thanks,
Cameron = Stoner
------=_NextPart_000_000B_01C1F34C.4FAD3520-- From dman@dman.ddts.net Sat May 4 17:57:14 2002 From: dman@dman.ddts.net (dman) Date: Sat, 4 May 2002 11:57:14 -0500 Subject: [Tutor] colors In-Reply-To: References: Message-ID: <20020504165714.GA827@dman.ddts.net> --HcAYCG3uE/tztfnV Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, May 04, 2002 at 09:16:02AM -0500, Cameron Stoner wrote: | Hi all, |=20 | How do you change the screen colors and text colors in a program? I | have never seen a text color or background color example anywhere. Which terminal or which GUI toolkit? It is very terminal specific or GUI toolkit specific. If you're working with a terminal look at ncurses -- it defines everything needed for working with a terminal without needing to know the particular terminal the user is using at that time. (it uses the terminfo database to know which escape codes to use) -D --=20 Your beauty should not come from outward adornment, such as braided hair and the wearing of gold jewelry and fine clothes. Instead, it should be that of your inner self, the unfading beauty of a gentle and quiet spirit, which is of GREAT WORTH in God's sight. For this is the way the holy women of the past used to make themselves beautiful. I Peter 3:3-5 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --HcAYCG3uE/tztfnV Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzUEuoACgkQO8l8XBKTpRQMYACggUR6hRpgoM9rcc0YZbJa58K+ jP0AoMmJVS0586JYRMOMa5tWkZgLDCHc =VWyP -----END PGP SIGNATURE----- --HcAYCG3uE/tztfnV-- From dman@dman.ddts.net Sat May 4 18:04:08 2002 From: dman@dman.ddts.net (dman) Date: Sat, 4 May 2002 12:04:08 -0500 Subject: [Tutor] Working Directory In-Reply-To: <3CD3BD29.ACE842C@york.ac.uk> References: <3CD25F28.A664CD26@york.ac.uk> <3CD27E3B.6000802@venix.com> <3CD3BD29.ACE842C@york.ac.uk> Message-ID: <20020504170408.GB827@dman.ddts.net> --98e8jtXdkpgskNou Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, May 04, 2002 at 11:51:21AM +0100, Russell Bungay wrote: | Lloyd Kvam wrote: | > >>> import mx.DateTime | > >>> mx.DateTime.__file__ | > 'F:\\Python22\\Lib\\site-packages\\mx\\DateTime\\__init__.pyc' |=20 | > I hope this fits the bill. I believe that if the module comes | > from your current directory, it simply returns the file name. |=20 | Thankyou, my code now looks like: |=20 | ### gofish.py |=20 | import bmdutils,ConfigParser,os,os.path,sys |=20 | gofishdir =3D os.path.dirname(__file__) | sys.path.append(gofishdir) |=20 | import cards #module in same directory as gofish.py When importing a module, python first looks in the same directory as the module doing the importing. You really don't need to be futzing with sys.path for that. Eg: $ pwd /home/dman $ ls /tmp/foo mod1.py mod2.py $ cat /tmp/foo/mod1.py import mod2 print "mod1 done" print import sys print sys.path $ cat /tmp/foo/mod2.py print "mod2 done" $ python -S /tmp/foo/mod1.py mod2 done mod1 done ['/tmp/foo', '/usr/lib/python2.1/', '/usr/lib/python2.1/plat-linux2', '/usr/lib/python2.1/lib-tk', '/usr/lib/python2.1/lib-dynload'] $ As you can see, the directory the initial module was in (/tmp/foo) was included as the first thing in sys.path. -D --=20 Yes, Java is so bulletproofed that to a C programmer it feels like being in= a straightjacket, but it's a really comfy and warm straightjacket, and the wo= rld would be a safer place if everyone was straightjacketed most of the time. -- Mark 'Kamikaze' Hu= ghes =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --98e8jtXdkpgskNou Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzUFIgACgkQO8l8XBKTpRSCygCfVK+RIoblV8fNyxZ7Vq2UM8vO Te8AoLq3lRQX0HvuiUyANLymyMWnAfe/ =uzZT -----END PGP SIGNATURE----- --98e8jtXdkpgskNou-- From glidedon Sat May 4 21:40:29 2002 From: glidedon (glidedon) Date: Sat, 04 May 2002 13:40:29 -0700 Subject: [Tutor] Multifunction mapping In-Reply-To: <20020430184355.A30445@pino.selwerd.nl> References: <20020430184355.A30445@pino.selwerd.nl> Message-ID: <0003a02e1c0a76a5_mailit@mail.c-zone.net> >Shorter is not better. Clearer is better. Something can be obfuscated both >by making it too short and by making it too verbose. > >The shortest way to do this is > >L = "abcdefghij" > >s = ''.join(map(lambda x: '%03d' % ord(x), L)) > >or with a list comprehension, even shorter: > >s = ''.join(['%03d' % ord(x) for x in L]) > >Personally I don't think this is the best way though - too much happens on >one line. I'd prefer > >import string > >L = "abcdefghij" >ords = [ord(x) for x in L] >strs = ['%03d' % o for o in ords] >s = string.join(strs, '') > >Although maybe this is slightly too much on the verbose side, it is easier >to see which steps are taken. > >Note the use of the % string formatting operator to get a number that's >filled up with leading zeroes, and string.join(list, '') or ''.join(list) to >join the parts together with nothing in between. > >-- >Remco Gerlich Remco, Excellent post, especially that last parargraph. Even I can follow that ! Thanks for tutoring ! Don From sporting16lx@yahoo.com Sat May 4 22:06:21 2002 From: sporting16lx@yahoo.com (joão cabaco) Date: Sat, 4 May 2002 14:06:21 -0700 (PDT) Subject: [Tutor] e-mail Message-ID: <20020504210621.1368.qmail@web13007.mail.yahoo.com> greetings my e-mail is sporting16lx@yahoo.com __________________________________________________ Do You Yahoo!? Yahoo! Health - your guide to health and wellness http://health.yahoo.com From burgijja@yahoo.com Sun May 5 23:35:49 2002 From: burgijja@yahoo.com (cmelik igor) Date: Sun, 5 May 2002 15:35:49 -0700 (PDT) Subject: [Tutor] tutor@python.org Message-ID: <20020505223550.80636.qmail@web11202.mail.yahoo.com> HI all. I traying to learn to programing, from all program leanguies PYTHON look like easy one....BUT in all other programs is easy to make exe file. same with aplication . in all tutorials i can,t find a way to .....compile files or what ever i must doo to make file who is independent from python. Please i nead somme simple answer . HOW CAN I MAKE EXE. FILE ? I have= python 2.2 IDLE (GUI) in windows 98. if i can,t make exe.files with that ...WHAT I NEAD TO HAVE? __________________________________________________ Do You Yahoo!? Yahoo! Health - your guide to health and wellness http://health.yahoo.com From pythontutor@venix.com Mon May 6 00:59:45 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Sun, 05 May 2002 19:59:45 -0400 Subject: [Tutor] tutor@python.org References: <20020505223550.80636.qmail@web11202.mail.yahoo.com> Message-ID: <3CD5C771.1030106@venix.com> The simple answer is that you do not make .EXE files. There is a least one way to package python files into .EXE files, but a lot depends upon why you want or need an executable. For learning Python, the interpreter works well. If Python is installed properly, you should be able to execute your python programs by clicking them. Why do you need exe files? cmelik igor wrote: > HI all. I traying to learn to programing, from all > program leanguies PYTHON look like easy one....BUT in > all other programs is easy to make exe file. same with > aplication . > in all tutorials i can,t find a way to .....compile > files > or what ever i must doo to make file who is > independent from python. > Please i nead somme simple answer . > > > HOW CAN I MAKE EXE. FILE ? > I have= python 2.2 IDLE (GUI) > in windows 98. > if i can,t make exe.files with that ...WHAT I NEAD TO HAVE? > > __________________________________________________ > Do You Yahoo!? > Yahoo! Health - your guide to health and wellness > http://health.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo@hkn.eecs.berkeley.edu Mon May 6 01:39:37 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 5 May 2002 17:39:37 -0700 (PDT) Subject: [Tutor] tutor@python.org In-Reply-To: <20020505223550.80636.qmail@web11202.mail.yahoo.com> Message-ID: On Sun, 5 May 2002, cmelik igor wrote: > HI all. I traying to learn to programing, from all program leanguies > PYTHON look like easy one....BUT in all other programs is easy to make > exe file. same with aplication . Actually, you can usually avoid making .exe's in Python. Python is an 'interpreted' language --- that is, we use the Python program itself to run Python programs. A program in .EXE form is meant to be standalone, so that anyone without Python can run your program. If you're planning to share your programs with your friends, you can make an .EXE by using a program called 'py2exe': http://py2exe.sourceforge.net but while you're learning programming with Python, you usually don't need to make .EXE's, just because you're the only one who's running the program. *grin* If you have more questions, please feel free to ask! From rob@zoism.org Mon May 6 03:41:41 2002 From: rob@zoism.org (Rob Brown-Bayliss) Date: 06 May 2002 14:41:41 +1200 Subject: [Tutor] streaming audio Message-ID: <1020652901.21030.1.camel@orion.zoism.org> Hi, I am looking for some information on the basics of audio streaming, or any sort of data streaming really. I want to create an app to stream audio around a LAN and really have know Idea on where to start. Thanks in advance. -- R Brown-Bayliss ---====<=>=====--- http://zoism.org From urnerk@qwest.net Mon May 6 00:55:49 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 5 May 2002 19:55:49 -0400 Subject: [Tutor] tutor@python.org In-Reply-To: <20020505223550.80636.qmail@web11202.mail.yahoo.com> References: <20020505223550.80636.qmail@web11202.mail.yahoo.com> Message-ID: <200205051955.49523.urnerk@qwest.net> On Sunday 05 May 2002 06:35 pm, cmelik igor wrote: > HI all. I traying to learn to programing, from all > program leanguies PYTHON look like easy one....BUT in > all other programs is easy to make exe file. same with > aplication . > in all tutorials i can,t find a way to .....compile > files > or what ever i must doo to make file who is > independent from python. > Please i nead somme simple answer . Yes, I agree with Danny, that making an EXE is not required. In Windows, we create standalone files with the .exe extension=20 which are actually depending on interpreters. For example, Visual FoxPro (VFP) compiles exe files, but you need to=20 distruibute more than 3 meg of auxilliary runtime DLLs to provide the interpreter. Likewise, Visual Basic (VB) has large runtime DLLs. Java requires a large installation (the Java VM, part of Java Runtime), as does C, but many of the C libraries are=20 already part of Windows (written in C), so you don't always=20 think about them. And yes, C is a compiled language, meaning you have straight binaries, distributable independently of=20 source code (the whole basis of the closed source economy). In the GNU/Linux world, where Python makes its original home, executables are not signified with a specific suffix, the .exe=20 file extension. Rather, it is an attribute of the file, independent=20 of the file name, and if the source code needs an interpreter, such as bash, perl, or python, this is indicated in the top line using "bang notation". The most used interpreters, including=20 Python by now, are expected components of the user space. =20 One simply presumes that other users already have it. As we learned recently on this list, at least one Windows OEM, Hewlett-Packard, is including some version of Python in its=20 default Windows distro. This trend is probably contagious, and in future you may expect your target Windows platform to already have Python installed (just as you have a browser, with built-in support for JavaScript, also interpreted). It's a logical thing to=20 have, given the cross-platform nature of the language. =20 In that case, you simply expect a file association between=20 =2Epy, .pyc, .pyd and .pyw files and the interpreter, as mediated=20 by Windows which keeps a registry of such associations=20 (instead of using the Unix bang notation inside the source=20 code itself). Note that if you're anxious to distribute Python "binaries" that aren't source code, you may share .pyc files without the .py=20 files. This is not typical in the Python community, but it=20 certainly may be done, if you're not wanting to share source code. Kirby From wesc@deirdre.org Mon May 6 09:37:06 2002 From: wesc@deirdre.org (wesc@deirdre.org) Date: Mon, 6 May 2002 01:37:06 -0700 (PDT) Subject: [Tutor] ANN: Silicon Valley Python UG mtg WED nite 5/8 7:30pm Message-ID: <200205060837.g468b6317000@artemis.ucsc-extension.edu> What: BayPIGgies (Silicon Valley Python users group) meeting When: Wednesday, 8 May 2002, 7:30-9 PM Where: Coco's Restaurant, 1209 Oakmead Pkwy, Sunnyvale, CA Agenda: Eating Out with Python (Python round table) Speaker: everyone... The host (and BayPIGgies volunteer) for our normal meetings at Python will be out of the country, so we will be gathering at a local restaurant for a Python round table. We will be at the Coco's Restaurant in Sunnyvale on the Lawrence Expressway and Oakmead Parkway right off US-101. Yahoo! Map/Driving Directions (gee... i wonder what language they use to build their CGI-oriented scripts...): http://yp.yahoo.com/py/ypMap.py?Pyt=Typ&tuid=9803594&ck=1088317771 The round table is totally informal and ranges from current topics and news from the Python community or recent newsgroup postings, talking about Python and how it is used in some of your projects, or to help those are making an effort to learn about a new area of Python programming they are exploring. If we finish early, those who are interested may head to the Digital Guru bookstore or Fry's Electronics. Both are within 1-2 minutes by car from the restaurant. Come along to join in having dinner *and* being able to talk about your favorite development language... and be sure to invite friends and co-workers along who may be interested in Python. Hope to see you there! -wesley Call For Talks: We are actively seeking speakers for BayPIGgies! If you would like to give a talk at one of our meetings (any Python related topic), contact us to coordinate! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, © 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://deirdre.org/baypiggies wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ From rab121@york.ac.uk Mon May 6 10:45:21 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Mon, 06 May 2002 10:45:21 +0100 Subject: [Tutor] Working Directory References: <3CD25F28.A664CD26@york.ac.uk> <3CD27E3B.6000802@venix.com> <3CD3BD29.ACE842C@york.ac.uk> Message-ID: <3CD650B1.98672474@york.ac.uk> Russell Bungay wrote: >Thankyou, my code now looks like: > >### gofish.py > >import bmdutils,ConfigParser,os,os.path,sys > >gofishdir = os.path.dirname(__file__) though the slightly more obvious answer would be: gofishdir = sys.argv[0] Russell -- http://www.bigmaddrongo.com President of York University Trampoline Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From rab121@york.ac.uk Mon May 6 10:58:30 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Mon, 06 May 2002 10:58:30 +0100 Subject: [Tutor] Working Directory References: <3CD25F28.A664CD26@york.ac.uk> <3CD27E3B.6000802@venix.com> <3CD3BD29.ACE842C@york.ac.uk> <3CD650B1.98672474@york.ac.uk> Message-ID: <3CD653C6.3FA7A5FF@york.ac.uk> Russell Bungay wrote: >>gofishdir = os.path.dirname(__file__) > >though the slightly more obvious answer would be: >gofishdir = sys.argv[0] gofishdir = os.path.dirname(sys.argv[0]) Russell -- http://www.bigmaddrongo.com President of York University Trampoline Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From programer@iquebec.com Mon May 6 11:36:47 2002 From: programer@iquebec.com (programer@iquebec.com) Date: Mon, 6 May 2002 12:36:47 +0200 Subject: [Tutor] Interaction between Python and Windows? Message-ID: <3CD678DF.27805.F29E9@localhost> I had a question about the integration of Python with Windows; it may be Off-Topic, so I apologize in this case... When I type "python" at the command prompt in MS-Windows 98 SE, it starts automatically Python within a DOS-box. Does anyone know where it comes from, which files are modified (I searched the sysedit files and didn't find)? Have you pointers to a detailed resource about this topic? Thank you very much. -- G.-Joachim L. Dubuquoy-Portois http://gjldp.free.fr/real/ ______________________________________________________________________________ ifrance.com, l'email gratuit le plus complet de l'Internet ! vos emails depuis un navigateur, en POP3, sur Minitel, sur le WAP... http://www.ifrance.com/_reloc/email.emailif From glingl@aon.at Mon May 6 17:37:43 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 6 May 2002 18:37:43 +0200 Subject: [Tutor] IDLE has problem with Umlaute References: <981558358.1018888807@muon> Message-ID: <002c01c1f51c$58a48170$1615a8c0@mega> Hi! In my class (at a Viennese Highschool) there occured the following problem, which - if not solved - would enforce a seriously restricted use of IDLE: We use Python2.2. When trying to save the following fancy program print "Größtes Problem: Umlaute" from an IDLE editor window, I got the error messages: >>> Exception in Tkinter callback Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "C:\Python22\Tools\idle\IOBinding.py", line 136, in save_as if self.writefile(filename): File "C:\Python22\Tools\idle\IOBinding.py", line 154, in writefile f.write(chars) UnicodeError: ASCII encoding error: ordinal not in range(128) So IDLE seems to prohibit the use of "ÄÖÜäöüß" . For German native speakers i consider this to be a serious drawback, especially when using it with students. Shortly I'd prefer to teach programming instead of teaching to avoid Umlaute. As far as I remember we had previous Python versions, which did NOT show this 'feature'. ================================================= !!! Is there a patch to repair this problem? !!! ================================================= Wouldn't it be a nice idea to have an IDLE, which is able to digest German texts at the EURO-Python-Conference? a bit desparately Gregor From jeff@ccvcorp.com Mon May 6 17:55:41 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon, 06 May 2002 09:55:41 -0700 Subject: [Tutor] Working Directory References: <3CD25F28.A664CD26@york.ac.uk> <3CD27E3B.6000802@venix.com> <3CD3BD29.ACE842C@york.ac.uk> <3CD650B1.98672474@york.ac.uk> <3CD653C6.3FA7A5FF@york.ac.uk> Message-ID: <3CD6B58D.94E91274@ccvcorp.com> Russell Bungay wrote: > Russell Bungay wrote: > >>gofishdir = os.path.dirname(__file__) > > > >though the slightly more obvious answer would be: > >gofishdir = sys.argv[0] > > > gofishdir = os.path.dirname(sys.argv[0]) IIRC, depending on how Python and the script are invoked, it may or may not include the full path info in sys.argv[0]. If it *doesn't* include the full path, then your method won't work. (Though that probably means that the path is the current working directory, i.e., equivalent to os.getcwd().) However, __file__ should always include the full path. Jeff Shannon Technician/Programmer Credit International From paulsid@shaw.ca Mon May 6 18:17:58 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Mon, 06 May 2002 11:17:58 -0600 Subject: [Tutor] Interaction between Python and Windows? References: <3CD678DF.27805.F29E9@localhost> Message-ID: <3CD6BAC6.466093BF@shaw.ca> programer@iquebec.com wrote: > I had a question about the integration of Python with Windows; it > may be Off-Topic, so I apologize in this case... > > When I type "python" at the command prompt in MS-Windows 98 > SE, it starts automatically Python within a DOS-box. > > Does anyone know where it comes from, which files are modified (I > searched the sysedit files and didn't find)? Have you pointers to a > detailed resource about this topic? I'm not entirely sure what you mean, so here are a few things: - It sounds like you're just wondering how Windows knows where to find Python. The installer probably put Python's directory in your system path. Go to Start Menu->Run and enter "msconfig". Then under the Environment tab, look for "PATH" and click Edit, then look for "c:\python22". Each directory in the path is searched (in order) whenever you enter a command that can't be found in the current directory. (The best reference for this is probably an old MS-DOS manual.) - If you want a graphical interface to Python, type "python c:\python22\tools\idle\idle.py". Python should have put an icon for this in your Start menu, look for "IDLE". - If you don't want a DOS box to come up when you run Python programs, either save your scripts with a .pyw extension or (my preference) run them with "pythonw" instead of "python". I've assumed you're using Python 2.2 and that you put it in c:\python22. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From Anthony Baxter Mon May 6 06:29:10 2002 From: Anthony Baxter (Anthony Baxter) Date: Mon, 06 May 2002 15:29:10 +1000 Subject: [Tutor] Re: streaming audio In-Reply-To: Message from Rob Brown-Bayliss of "06 May 2002 14:41:41 +1200." <1020652901.21030.1.camel@orion.zoism.org> Message-ID: <200205060529.g465TA703422@localhost.localdomain> >>> Rob Brown-Bayliss wrote > I am looking for some information on the basics of audio streaming, or > any sort of data streaming really. Look into RTP, the basics of which are described in RFC 1889. There's other RFCs that describe various payload formats for RTP. See also the resources listed under http://www.cs.columbia.edu/~hgs/rtp/ > I want to create an app to stream audio around a LAN and really have > know Idea on where to start. One thing to beware is that you may find Python unsuitable for the actual streaming of the RTP packets. There are quite tight time constraints to be met, and if you mess it up it's very very audible to the end user. In my application (a unified messaging/voicemail server), all of it is in python, except for a small C part that actually plays or records the audio packets to/from the net. Anthony -- Anthony Baxter It's never too late to have a happy childhood. From wonderer@pakistanmail.com Mon May 6 16:14:18 2002 From: wonderer@pakistanmail.com (wonderer@pakistanmail.com) Date: Mon, 06 May 2002 20:14:18 +0500 Subject: [Tutor] arrays and strings Message-ID: <3cd66ed2.3250.0@pakistanmail.com> Hi can some one tell me how can we convert arrays to strings in python. I have seen functions like repr()and tostring() etc. I do it like this def funcA (): declare some array and assign some values .... showvalues(repr(array)) def showvalues(temp): for index in range (0,5,1): print "value ",temp[index] and it never shows me the values that i inserted but shows the declaration of array element like a,r,r,y,(,",l,") and so on with elements. what i was really trying to do was use an array(of type we use in c) and then send that array to some function for processing but the dispaly is never as i want it to be. I will be really reallly reallly thankfull for your help and suggestions _______________________________________________________________________ Get your free @pakistanmail.com email address http://pakistanmail.com From glingl@aon.at Mon May 6 18:54:20 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 6 May 2002 19:54:20 +0200 Subject: [Tutor] midi-support? References: <3CD6A584.2CAF719B@fa.disney.com> Message-ID: <007801c1f527$0cfd96c0$1615a8c0@mega> Hi! Does anybody know if there exist(s a) Python module(s) for midi-support, which work(s) under Python 2.2 (at least under Windows) ? Thanks, Gregor From dyoo@hkn.eecs.berkeley.edu Mon May 6 19:12:34 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 May 2002 11:12:34 -0700 (PDT) Subject: [Tutor] IDLE has problem with Umlaute In-Reply-To: <002c01c1f51c$58a48170$1615a8c0@mega> Message-ID: > print "Gr=F6=DFtes Problem: Umlaute" > > from an IDLE editor window, I got the error > messages: > > > >>> Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ > return apply(self.func, args) > File "C:\Python22\Tools\idle\IOBinding.py", line 136, in save_as > if self.writefile(filename): > File "C:\Python22\Tools\idle\IOBinding.py", line 154, in writefile > f.write(chars) > UnicodeError: ASCII encoding error: ordinal not in range(128) > > So IDLE seems to prohibit the use of "=C4=D6=DC=E4=F6=FC=DF" . For German= native > speakers i consider this to be a serious drawback, especially when > using it with students. Hi Gregor, It's a unicode encoding thing: you'll need to set the 'default encoding' scheme of your system to 'iso-8859-1', which is the encoding scheme for Central Europe. For example: ### >>> s =3D "" >>> s '\xc4\xd6\xdc\xe4\xf6\xfc\xdf' >>> unicode(s) Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII decoding error: ordinal not in range(128) >>> unicode(s, 'iso-8859-1') u'\xc4\xd6\xdc\xe4\xf6\xfc\xdf' ### There should be a way to set this up site-wide so that all of Python knows that it should use the Central European encoding... checking... Ah! http://www.faqts.com/knowledge_base/view.phtml/aid/11712 mentions something about this, but I don't see sys.setdefaultencoding() in my interpreter session... Doh. That's because site.py removes sys.setdefaultencoding() after Python loads up: ### site.py # # Remove sys.setdefaultencoding() so that users cannot change the # encoding after initialization. The test for presence is needed when # this module is run as a script, because this code is executed twice. # if hasattr(sys, "setdefaultencoding"): del sys.setdefaultencoding ### So you'll need to call sys.setdefaultencoding() within sitecustomize.py to have this work sitewide. Hope this helps. Good luck! From dman@dman.ddts.net Mon May 6 19:23:00 2002 From: dman@dman.ddts.net (dman) Date: Mon, 6 May 2002 13:23:00 -0500 Subject: [Tutor] IDLE has problem with Umlaute In-Reply-To: <002c01c1f51c$58a48170$1615a8c0@mega> References: <981558358.1018888807@muon> <002c01c1f51c$58a48170$1615a8c0@mega> Message-ID: <20020506182300.GA17041@dman.ddts.net> --zhXaljGHf11kAtnf Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 06, 2002 at 06:37:43PM +0200, Gregor Lingl wrote: =20 | We use Python2.2. | When trying to save the following fancy program |=20 | print "Gr=F6=DFtes Problem: Umlaute" |=20 | from an IDLE editor window, I got the error | messages: =2E.. | File "[DOESN'T MATTER]", line 154, in writefile | f.write(chars) | UnicodeError: ASCII encoding error: ordinal not in range(128) |=20 | So IDLE seems to prohibit the use of "=C4=D6=DC=E4=F6=FC=DF" . It's not IDLE that has the problem, but computer systems in general. The problem is rather historical in nature with characters being one byte and US-ASCII as the de-facto standard charset (it seems EBCDIC never took off except on IBM mainframes and terminals). =20 Since US-ASCII is really a 7-bit encoding, the ISO group decided to take advantage of the remaining 128 characters available in one byte and defined the iso-8859-* class of charsets. The advantage there was no change to programs to handle "wide" characters and allowing ulmauts, etc, to be representable. The latest solution is Unicode -- use 16 bit characters to allow representing (almost) all langauge's alphabets simultaneously. The problem here is the characters don't fit into a byte. Thus several encodings to transform the characters into byte streams (namely files and sockets) have been developed with a variety of tradeoffs. Python supports unicode, but has a problem that can't be solved with any sane defaults. The problem is how to serialize (or enocde, if you prefer) the unicode characters when a string is written to a file. Some people want latin1, utf-8, utf-7, ucs-2, utf-16, or something else. The lowest common demoninator is US-ASCII, so that is the only encoding that is supported *by default*. To demonstrate this fire up the interpreter on any system (windows, unix, etc) and try printing a unicode string that is not in the us-ascii subset. >>> print u'\xf6' Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) >>> print u'\xf6'.encode( 'latin1' ) =F6 >>> print u'\xf6'.encode( 'utf-8' ) =C3=B6 >>>=20 Here you see the beauty (=3Dp) of the terminal I'm using right now. It understands latin1 (iso8859-1) just fine, but not utf-8. Python has no way of knowing what I want to use, so it doesn't try and guess. | As far as I remember we had previous Python versions, which | did NOT show this 'feature'. Right, because they didn't support other languages ;-). | =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D | !!! Is there a patch to repair this problem? !!! | =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Sure, you can modify all file reads and writes to decode/encode the stream according to your encoding preference. Possibly adjusting the locale settings in your OS might have an effect on this. Or you can use sys.setdefaultencoding() to specify which encoding you want to be the default one. Ex : >>> sys.setdefaultencoding( 'latin1' ) >>> print u'\xf6' =F6 >>> There is a slight problem with this, though. It might break other software that doesn't expect this and can't properly handle a different encoding. The other problem could be your site.py. On debian the default site.py removes the name sys.setdefaultencoding so that us users can't play in the fire. You could modify your site's site.py to set the encoding to your preferred value and then hope nothing else blows up :-). HTH, -D --=20 Consider what God has done: Who can straighten what He has made crooked? Ecclesiastes 7:13 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --zhXaljGHf11kAtnf Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzWygQACgkQO8l8XBKTpRQFcwCfY9l3pk81VknIaEjZbiWv2FXT NwwAniIAOmio67TSKQjxuXk4pwBeKFHp =ndcl -----END PGP SIGNATURE----- --zhXaljGHf11kAtnf-- From dyoo@hkn.eecs.berkeley.edu Mon May 6 19:16:26 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 6 May 2002 11:16:26 -0700 (PDT) Subject: [Tutor] midi-support? In-Reply-To: <007801c1f527$0cfd96c0$1615a8c0@mega> Message-ID: On Mon, 6 May 2002, Gregor Lingl wrote: > Hi! > Does anybody know if there exist(s a) > Python module(s) for midi-support, > which work(s) under Python 2.2 > (at least under Windows) ? Hi Gregor, I did a quick check on Google. You might find this article on "Noisy Python" useful: http://www.onlamp.com/pub/a/python/2001/10/25/pythonnews.html The MusicKit system that the article mentions appears to have MIDI support, so perhaps you can use that: http://musickit.sourceforge.net/ Good luck! From dman@dman.ddts.net Mon May 6 19:26:23 2002 From: dman@dman.ddts.net (dman) Date: Mon, 6 May 2002 13:26:23 -0500 Subject: [Tutor] IDLE has problem with Umlaute In-Reply-To: References: <002c01c1f51c$58a48170$1615a8c0@mega> Message-ID: <20020506182623.GB17041@dman.ddts.net> --IiVenqGWf+H9Y6IX Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 06, 2002 at 11:12:34AM -0700, Danny Yoo wrote: =20 | scheme of your system to 'iso-8859-1', which is the encoding scheme for | Central Europe. As I understand it, latin1 is for western europe and latin2 is eastern europe. I know that all but a couple of Romanian's non-English letters are not in latin1. I don't know where the specific boundaries between "western", "central" and "eastern" europe lie, but I suppose the old Iron Curtain plays a large role in that. I think that latin1 is correct for German, though. -D --=20 The wise in heart are called discerning, and pleasant words promote instruction. Proverbs 16:21 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --IiVenqGWf+H9Y6IX Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzWys8ACgkQO8l8XBKTpRRNpgCfePzR6pM+LzVFeF2F+y8qFK7R yeoAoMElogFyLR0I1Nwq86JqosVVJQ5i =Yw00 -----END PGP SIGNATURE----- --IiVenqGWf+H9Y6IX-- From hernan@orgmf.com.ar Mon May 6 19:19:05 2002 From: hernan@orgmf.com.ar (Hernan Martinez Foffani) Date: Mon, 6 May 2002 20:19:05 +0200 Subject: [Idle-dev] Re: [Tutor] IDLE has problem with Umlaute In-Reply-To: Message-ID: See FAQ 4.102 at http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.102.htp Basically you just create a file sitecustomize.py under site-packages directory with the following content: # Set the string encoding used by the Unicode implementation. # The default is 'ascii' encoding = "ascii" # <= CHANGE THIS if you wish # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] if encoding != "ascii": import sys sys.setdefaultencoding(encoding) Beware that if you do that the python programs you write may not be portable between sites with different encodings!!!!!!!! Regards, -Hernan From paulsid@shaw.ca Mon May 6 19:32:01 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Mon, 06 May 2002 12:32:01 -0600 Subject: [Tutor] midi-support? References: <3CD6A584.2CAF719B@fa.disney.com> <007801c1f527$0cfd96c0$1615a8c0@mega> Message-ID: <3CD6CC21.7FBB8761@shaw.ca> Gregor Lingl wrote: > Does anybody know if there exist(s a) > Python module(s) for midi-support, > which work(s) under Python 2.2 > (at least under Windows) ? If you just want to play MIDI files and not manipulate them, pygame's mixer module supports them. The Windows installer for pygame will set up everything you need. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From programer@iquebec.com Mon May 6 19:31:52 2002 From: programer@iquebec.com (programer@iquebec.com) Date: Mon, 6 May 2002 20:31:52 +0200 Subject: [Tutor] Interaction between Python and Windows? In-Reply-To: <3CD6BAC6.466093BF@shaw.ca> Message-ID: <3CD6E838.11519.CA96F5@localhost> On 6 May 2002 at 11:17, Paul Sidorsky wrote: > I'm not entirely sure what you mean, so here are a few things: I apologize for the lack of according precision. It was the first option. I didn't find the Environment within the msconfig tool, that only read in a more clear form all the information that you may edit using the sysedit feature. It makes me for me even less clear (I had assumed that there were another file that the system took into account where the Python path would be written). That is very strange. I will look deeper; thank you for your help (and if you have an old dos manual... ;/) -- G.-Joachim L. Dubuquoy-Portois http://gjldp.free.fr/real/ ______________________________________________________________________________ ifrance.com, l'email gratuit le plus complet de l'Internet ! vos emails depuis un navigateur, en POP3, sur Minitel, sur le WAP... http://www.ifrance.com/_reloc/email.emailif From israel@lith.com Mon May 6 21:30:11 2002 From: israel@lith.com (Israel Evans) Date: Mon, 6 May 2002 13:30:11 -0700 Subject: [Tutor] Interaction between Python and Windows? Message-ID: For all things MS-DOS, I've found this to be an invaluable resource... http://www.computerhope.com/msdos.htm ~Israel~ -----Original Message----- From: programer@iquebec.com [mailto:programer@iquebec.com] Sent: 06 May 2002 11:32 AM To: tutor@python.org Subject: Re: [Tutor] Interaction between Python and Windows? On 6 May 2002 at 11:17, Paul Sidorsky wrote: > I'm not entirely sure what you mean, so here are a few things: I apologize for the lack of according precision. It was the first option. I didn't find the Environment within the msconfig tool, that only read in a more clear form all the information that you may edit using the sysedit feature. It makes me for me even less clear (I had assumed that there were another file that the system took into account where the Python path would be written). That is very strange. I will look deeper; thank you for your help (and if you have an old dos manual... ;/) -- G.-Joachim L. Dubuquoy-Portois http://gjldp.free.fr/real/ ____________________________________________________________________________ __ ifrance.com, l'email gratuit le plus complet de l'Internet ! vos emails depuis un navigateur, en POP3, sur Minitel, sur le WAP... http://www.ifrance.com/_reloc/email.emailif _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From budgester@budgester.com Mon May 6 22:54:09 2002 From: budgester@budgester.com (Martin Stevens) Date: Mon, 6 May 2002 22:54:09 +0100 Subject: [Tutor] Instant keypress response Message-ID: <20020506215409.GA17532@akira.budgenet> I was wondering if anyone could point me in the right direction. What i want to do is have my python program respond as soon as a key is pressed and not have to wait for the enter key to be pressed. Whats the best way of doing this ? Regards Martin Stevens -- Budgester Technologies Ltd Office : 01992 718568 Mobile : 07815 982380 mailto:martin@budgester.com http://www.budgester.com From dman@dman.ddts.net Mon May 6 23:09:18 2002 From: dman@dman.ddts.net (dman) Date: Mon, 6 May 2002 17:09:18 -0500 Subject: [Tutor] Instant keypress response In-Reply-To: <20020506215409.GA17532@akira.budgenet> References: <20020506215409.GA17532@akira.budgenet> Message-ID: <20020506220918.GA19345@dman.ddts.net> --zhXaljGHf11kAtnf Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 06, 2002 at 10:54:09PM +0100, Martin Stevens wrote: | I was wondering if anyone could point me in the right direction. |=20 | What i want to do is have my python program respond as soon as=20 | a key is pressed and not have to wait for the enter key to | be pressed. |=20 | Whats the best way of doing this ? ncurses -D --=20 Pleasant words are a honeycomb, sweet to the soul and healing to the bones. Proverbs 16:24 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --zhXaljGHf11kAtnf Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzW/w4ACgkQO8l8XBKTpRQMeACfVUn4LuH0qAFIa2hrwa0t050j QK4AnAz8cfgbtxh5TxoqRjyPvn1yvvwX =OgOp -----END PGP SIGNATURE----- --zhXaljGHf11kAtnf-- From budgester@budgester.com Mon May 6 23:13:46 2002 From: budgester@budgester.com (Martin Stevens) Date: Mon, 6 May 2002 23:13:46 +0100 Subject: [Tutor] Instant keypress response In-Reply-To: <20020506220918.GA19345@dman.ddts.net> References: <20020506215409.GA17532@akira.budgenet> <20020506220918.GA19345@dman.ddts.net> Message-ID: <20020506221346.GC17532@akira.budgenet> On Mon, May 06, 2002 at 05:09:18PM -0500, dman wrote: > On Mon, May 06, 2002 at 10:54:09PM +0100, Martin Stevens wrote: > | I was wondering if anyone could point me in the right direction. > | > | What i want to do is have my python program respond as soon as > | a key is pressed and not have to wait for the enter key to > | be pressed. > | > | Whats the best way of doing this ? > > ncurses So that'd be the curses module then ? > > -D > > -- > > Pleasant words are a honeycomb, > sweet to the soul and healing to the bones. > Proverbs 16:24 > > GnuPG key : http://dman.ddts.net/~dman/public_key.gpg > -- Budgester Technologies Ltd Office : 01992 718568 Mobile : 07815 982380 mailto:martin@budgester.com http://www.budgester.com From kalle@lysator.liu.se Mon May 6 23:40:11 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Tue, 7 May 2002 00:40:11 +0200 Subject: [Tutor] Instant keypress response In-Reply-To: <20020506215409.GA17532@akira.budgenet> References: <20020506215409.GA17532@akira.budgenet> Message-ID: <20020506224011.GB4521@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Martin Stevens] > What i want to do is have my python program respond as soon as > a key is pressed and not have to wait for the enter key to > be pressed. > > Whats the best way of doing this ? Platform dependent. Please provide more information. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE81wZLdNeA1787sd0RAj3IAJ9xsvu42jy2mtTFygXe++Vdd5GVUgCfXCde J1wh+PO2OcF5u94nWnxiWf0= =9o1h -----END PGP SIGNATURE----- From budgester@budgester.com Mon May 6 23:43:46 2002 From: budgester@budgester.com (Martin Stevens) Date: Mon, 6 May 2002 23:43:46 +0100 Subject: [Tutor] Instant keypress response In-Reply-To: <20020506224011.GB4521@i92.ryd.student.liu.se> References: <20020506215409.GA17532@akira.budgenet> <20020506224011.GB4521@i92.ryd.student.liu.se> Message-ID: <20020506224346.GA21579@akira.budgenet> On Tue, May 07, 2002 at 12:40:11AM +0200, Kalle Svensson wrote: > [Martin Stevens] > > What i want to do is have my python program respond as soon as > > a key is pressed and not have to wait for the enter key to > > be pressed. > > > > Whats the best way of doing this ? > > Platform dependent. Please provide more information. Using Debian GNU/Linux, just did a quick search on google and found a ncurses & python tutorial, so i am working through that at the moment. Thanks again for the help Martin Stevens > > Peace, > Kalle > -- > Kalle Svensson, http://www.juckapan.org/~kalle/ > Student, root and saint in the Church of Emacs. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Budgester Technologies Ltd Office : 01992 718568 Mobile : 07815 982380 mailto:martin@budgester.com http://www.budgester.com From dman@dman.ddts.net Mon May 6 23:51:35 2002 From: dman@dman.ddts.net (dman) Date: Mon, 6 May 2002 17:51:35 -0500 Subject: [Tutor] Instant keypress response In-Reply-To: <20020506221346.GC17532@akira.budgenet> References: <20020506215409.GA17532@akira.budgenet> <20020506220918.GA19345@dman.ddts.net> <20020506221346.GC17532@akira.budgenet> Message-ID: <20020506225135.GA19536@dman.ddts.net> --vkogqOf2sHV7VnPd Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 06, 2002 at 11:13:46PM +0100, Martin Stevens wrote: | On Mon, May 06, 2002 at 05:09:18PM -0500, dman wrote: | > On Mon, May 06, 2002 at 10:54:09PM +0100, Martin Stevens wrote: | > | I was wondering if anyone could point me in the right direction. | > |=20 | > | What i want to do is have my python program respond as soon as=20 | > | a key is pressed and not have to wait for the enter key to | > | be pressed. | > |=20 | > | Whats the best way of doing this ? | >=20 | > ncurses |=20 | So that'd be the curses module then ? Apparently that's the name of it :-). I've never done curses programming myself, but since you use mutt I thought you might know something about it. -D --=20 I can do all things through Christ who strengthens me. Philippians 4:13 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --vkogqOf2sHV7VnPd Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzXCPcACgkQO8l8XBKTpRRDTgCfaGOmCjltL03FFjg4XM9FgnO7 6q0An14ikXIZEf9dWEPU5ZM6QKZJnX4d =4kdb -----END PGP SIGNATURE----- --vkogqOf2sHV7VnPd-- From kalle@lysator.liu.se Tue May 7 00:06:14 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Tue, 7 May 2002 01:06:14 +0200 Subject: [Tutor] Instant keypress response In-Reply-To: <20020506224346.GA21579@akira.budgenet> References: <20020506215409.GA17532@akira.budgenet> <20020506224011.GB4521@i92.ryd.student.liu.se> <20020506224346.GA21579@akira.budgenet> Message-ID: <20020506230614.GC4521@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Martin Stevens] > Using Debian GNU/Linux, just did a quick search on google > and found a ncurses & python tutorial, so i am working > through that at the moment. Okay, great! There is also a Python/curses HOWTO on http://py-howto.sourceforge.net/ . Good luck! Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE81wxmdNeA1787sd0RApeiAJ4pYAhw1XL3+gn8j0PptZ+2nXpicgCfSL2A +/tpdU+lQ/IHL2xIrH7CXHs= =QmOk -----END PGP SIGNATURE----- From erikprice@mac.com Tue May 7 02:45:44 2002 From: erikprice@mac.com (Erik Price) Date: Mon, 6 May 2002 21:45:44 -0400 Subject: [Tutor] arrays and strings In-Reply-To: <3cd66ed2.3250.0@pakistanmail.com> Message-ID: <251ADA6E-615C-11D6-8049-00039351FE6A@mac.com> On Monday, May 6, 2002, at 11:14 AM, wonderer@pakistanmail.com wrote: > Hi can some one tell me how can we convert arrays to strings in python. > I have seen functions like repr()and tostring() etc. > I do it like this > def funcA (): > declare some array and assign some values > .... > showvalues(repr(array)) > > def showvalues(temp): > for index in range (0,5,1): > print "value ",temp[index] > > and it never shows me the values that i inserted but shows the > declaration of > array element like a,r,r,y,(,",l,") and so on with elements. > what i was really trying to do was use an array(of type we use in c) > and then > send that array to some function for processing but the dispaly is > never as > i want it to be. I'm not really sure exactly what the difference is myself, but I keep hearing that arrays are not the same thing as lists, so you may be referring to lists. I think it has something to do with the way memory is allocated. (I'm used to saying arrays too... ssh!) I'm curious as to why you would be using the repr() function -- it's a very useful tool for debugging, but you rarely want to see the canonical representation* of something in an application (as an end user). * http://www.tuxedo.org/~esr/jargon/html/entry/canonical.html I think that what you want to do is simply join the elements of a list together into one string? Well, there is an easy way to do this -- simply use the join method of string objects to concatenate a sequence of strings together: >>> mylist = ['item1', 'mutant', 'item3', 'indexnumber4'] >>> string = ' '.join(mylist) >>> string 'item1 mutant item3 indexnumber4' See what that does? It takes the string object (a space, in this case, located between quotes) and uses it as the separator of a sequence of other strings (which in this case is "mylist"). This does exactly what you want, I think. Remember that it only works in joining a sequence of strings, which means you have to convert the elements of a list into strings if you want to use the join() method on integers or some other data type. Erik From rahulsen@gmx.net Tue May 7 08:57:52 2002 From: rahulsen@gmx.net (Rahul Sen) Date: Tue, 7 May 2002 13:27:52 +0530 Subject: [Tutor] Digest mode Message-ID: <003401c1f59d$1cc92760$d98c3cca@roltanet.com> This is a multi-part message in MIME format. ------=_NextPart_000_0031_01C1F5CA.FD923160 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello, Could anyone tell me what 'digest mode' of the subsciption options to = the tutor mailing list would be. Thanks. ------=_NextPart_000_0031_01C1F5CA.FD923160 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello,
   Could anyone tell me what = 'digest=20 mode' of the subsciption options to the tutor mailing list would=20 be.
   = Thanks.
------=_NextPart_000_0031_01C1F5CA.FD923160-- From dyoo@hkn.eecs.berkeley.edu Tue May 7 08:44:08 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 May 2002 00:44:08 -0700 (PDT) Subject: [Tutor] Something that caught my eye: Robocode Message-ID: Hi everyone, I was just passing through the web, and saw an article that caught my attention: http://www-106.ibm.com/developerworks/library/j-robocode/?t=gr,l30a=ReSeF This looks really interesting! It's a battle-bot simulator, and looks really useful. Has anyone tried running Jython on this? Talk to you in two weeks! (I'll be vacationing in Korea.) From dyoo@hkn.eecs.berkeley.edu Tue May 7 08:47:33 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 7 May 2002 00:47:33 -0700 (PDT) Subject: [Tutor] Digest mode In-Reply-To: <003401c1f59d$1cc92760$d98c3cca@roltanet.com> Message-ID: On Tue, 7 May 2002, Rahul Sen wrote: > Could anyone tell me what 'digest mode' of the subsciption options to > the tutor mailing list would be. "Digest mode" packages about a day's worth of messages into a single message that is sent to you every night. So instead of getting each new message as it reaches Tutor, collections of messages arrive in one batch instead. If the number of messages that you get from Tutor start to feel overwhelming, you can use digest mode to reduce the traffic in your mailbox. Hope this helps! From rahulsen@gmx.net Tue May 7 09:36:07 2002 From: rahulsen@gmx.net (Rahul Sen) Date: Tue, 7 May 2002 14:06:07 +0530 Subject: [Tutor] Digest mode References: Message-ID: <005701c1f5a2$3f518a20$e7833cca@roltanet.com> Heavens that was quick. Thank you very much. ----- Original Message ----- From: "Danny Yoo" To: "Rahul Sen" Cc: Sent: Tuesday, May 07, 2002 1:17 PM Subject: Re: [Tutor] Digest mode > > > On Tue, 7 May 2002, Rahul Sen wrote: > > > Could anyone tell me what 'digest mode' of the subsciption options to > > the tutor mailing list would be. > > "Digest mode" packages about a day's worth of messages into a single > message that is sent to you every night. So instead of getting each new > message as it reaches Tutor, collections of messages arrive in one batch > instead. > > If the number of messages that you get from Tutor start to feel > overwhelming, you can use digest mode to reduce the traffic in your > mailbox. > > Hope this helps! > From budgester@budgester.com Tue May 7 10:53:09 2002 From: budgester@budgester.com (Martin Stevens) Date: Tue, 7 May 2002 10:53:09 +0100 Subject: [Tutor] Instant keypress response In-Reply-To: <20020506230614.GC4521@i92.ryd.student.liu.se> References: <20020506215409.GA17532@akira.budgenet> <20020506224011.GB4521@i92.ryd.student.liu.se> <20020506224346.GA21579@akira.budgenet> <20020506230614.GC4521@i92.ryd.student.liu.se> Message-ID: <20020507095309.GB10319@akira.budgenet> On Tue, May 07, 2002 at 01:06:14AM +0200, Kalle Svensson wrote: > [Martin Stevens] > > Using Debian GNU/Linux, just did a quick search on google > > and found a ncurses & python tutorial, so i am working > > through that at the moment. > > Okay, great! There is also a Python/curses HOWTO on > http://py-howto.sourceforge.net/ . Good luck! Once i get something working it'll got to useless python, because usually my coding if completely useless. > > Peace, > Kalle > -- > Kalle Svensson, http://www.juckapan.org/~kalle/ > Student, root and saint in the Church of Emacs. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Budgester Technologies Ltd Office : 01992 718568 Mobile : 07815 982380 mailto:martin@budgester.com http://www.budgester.com From aschmidt@nv.cc.va.us Tue May 7 12:30:58 2002 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Tue, 7 May 2002 07:30:58 -0400 Subject: [Tutor] Something that caught my eye: Robocode Message-ID: <47BCBF3251382B45893950D07804082475AFF0@novamail.nv.cc.va.us> Great! Now my productivity will be zero! 8^) My 15 year-old son will love this! He has been banging on Python and Zope but has been wanting to learn some Java too. What a great way to get a handle on it. Thanks Danny!!!! -Allen (of course, I will have to learn this, too, so my son's robots do not kick my butt!) -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Tuesday, May 07, 2002 3:44 AM To: tutor@python.org Subject: [Tutor] Something that caught my eye: Robocode Hi everyone, I was just passing through the web, and saw an article that caught my attention: http://www-106.ibm.com/developerworks/library/j-robocode/?t=gr,l30a=ReSeF This looks really interesting! It's a battle-bot simulator, and looks really useful. Has anyone tried running Jython on this? Talk to you in two weeks! (I'll be vacationing in Korea.) _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ak@silmarill.org Tue May 7 15:18:41 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 7 May 2002 10:18:41 -0400 Subject: [Tutor] arrays and strings In-Reply-To: <3cd66ed2.3250.0@pakistanmail.com> References: <3cd66ed2.3250.0@pakistanmail.com> Message-ID: <20020507141841.GA16708@ak.silmarill.org> On Mon, May 06, 2002 at 08:14:18PM +0500, wonderer@pakistanmail.com wrote: > Hi can some one tell me how can we convert arrays to strings in python. > I have seen functions like repr()and tostring() etc. > I do it like this > def funcA (): > declare some array and assign some values > .... > showvalues(repr(array)) > > def showvalues(temp): > for index in range (0,5,1): > print "value ",temp[index] > > and it never shows me the values that i inserted but shows the declaration of > array element like a,r,r,y,(,",l,") and so on with elements. > what i was really trying to do was use an array(of type we use in c) and then > send that array to some function for processing but the dispaly is never as > i want it to be. > You don't need to do anything with it to send it to some function: >>> lst = [1,2,3,'a','b'] >>> def a(array): ... for item in array: ... print item ... >>> a(lst) 1 2 3 a b I hope this is what you wanted, but not too sure.. if this is not it, please elaborate with some sample production code. > > I will be really reallly reallly thankfull for your help and suggestions > _______________________________________________________________________ > Get your free @pakistanmail.com email address http://pakistanmail.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From stuart_clemons@us.ibm.com Tue May 7 17:35:36 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Tue, 7 May 2002 12:35:36 -0400 Subject: [Tutor] Newbie text file processing question Message-ID: --0__=0ABBE121DFC6B6308f9e8a93df938690918c0ABBE121DFC6B630 Content-type: text/plain; charset=US-ASCII Hi all: I have a question about conditional branching based on the contents of a text file. I'll try my best to make this understandable ! My file is: foo.txt The contents of foo.txt are: (1)lineA (2) lineA1stuff=eggs (3) lineABstuff=spam (4)lineB (5) lineB1stuff=cars (6) lineABstuff=trucks (7) lineB2stuff=books (8)lineA (9) lineA1stuff=eggs (10 lineA2stuff=eggs I want to do conditional stuff based around if the line is lineA or lineB. For example if a line in foo.txt equals "lineA", then check that lineA1stuff equals eggs and lineABstuff equals spam. If a line equals "lineB", then check that lineB1stuff equals cars and lineABstuff equals trucks, etc. NOTICE that the contents of line, "lineABstuff", should be different if it follows line A or line B. (I hope this isn't too confusing !) I can more-or-less do what I want using line by line processing and if statements, but the lines, "lineA" and "lineB" aren't being used for conditional checking and actions (only the "*stuff" lines are). Is there a better way to do this ? Here's an example of the code construct I was thinking of using. infile = open('f:\\Python22\\foo.txt', 'r') for line in infile.xreadlines(): if line[3:8] == "lineA": print "Yes, this is line A", line if line[7:18] == "lineA1stuff": if line[19:23]== "eggs": print "this is correct" else: print "this is incorrect" if line[3:8] == "lineB": , etc, etc, etc Sorry if this is hopelessly incoherent. - Stuart --0__=0ABBE121DFC6B6308f9e8a93df938690918c0ABBE121DFC6B630 Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Hi all:

I have a question about conditional branching based on the contents of a text file. I'll try my best to make this understandable !

My file is: foo.txt

The contents of foo.txt are:

(1)lineA
(2) lineA1stuff=eggs
(3) lineABstuff=spam
(4)lineB
(5) lineB1stuff=cars
(6) lineABstuff=trucks
(7) lineB2stuff=books
(8)lineA
(9) lineA1stuff=eggs
(10 lineA2stuff=eggs


I want to do conditional stuff based around if the line is lineA or lineB.

For example if a line in foo.txt equals "lineA", then check that lineA1stuff equals eggs and lineABstuff equals spam. If a line equals "lineB", then check that lineB1stuff equals cars and lineABstuff equals trucks, etc. NOTICE that the contents of line, "lineABstuff", should be different if it follows line A or line B. (I hope this isn't too confusing !)

I can more-or-less do what I want using line by line processing and if statements, but the lines, "lineA" and "lineB" aren't being used for conditional checking and actions (only the "*stuff" lines are). Is there a better way to do this ?

Here's an example of the code construct I was thinking of using.

infile = open('f:\\Python22\\foo.txt', 'r')
for line in infile.xreadlines():
if line[3:8] == "lineA":
print "Yes, this is line A", line
if line[7:18] == "lineA1stuff":
if line[19:23]== "eggs":
print "this is correct"
else:
print "this is incorrect"
if line[3:8] == "lineB": , etc, etc, etc

Sorry if this is hopelessly incoherent.

- Stuart


--0__=0ABBE121DFC6B6308f9e8a93df938690918c0ABBE121DFC6B630-- From shalehperry@attbi.com Tue May 7 17:48:29 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 07 May 2002 09:48:29 -0700 (PDT) Subject: [Tutor] Newbie text file processing question In-Reply-To: Message-ID: > > > I want to do conditional stuff based around if the line is lineA or lineB. > > For example if a line in foo.txt equals "lineA", then check that > lineA1stuff equals eggs and lineABstuff equals spam. If a line equals > "lineB", then check that lineB1stuff equals cars and lineABstuff equals > trucks, etc. NOTICE that the contents of line, "lineABstuff", should be > different if it follows line A or line B. (I hope this isn't too confusing > !) > > I can more-or-less do what I want using line by line processing and if > statements, but the lines, "lineA" and "lineB" aren't being used for > conditional checking and actions (only the "*stuff" lines are). Is there a > better way to do this ? > there are two approaches I often use. 1) state checking and 2) function handlers. WANT_A = 1 WANT_B = 2 if line == lineA: state = WANT_A if line == lineB: state = WANT_B if state == WANT_A: if line is not A type: complain elif state == WANT_B: if line is not B type: complain or perhaps (second option): if line == lineA: read_a_data(file) elif line == lineB: read_b_data(file) the two functions would read lines from the file until they hit something they did not understand. From ak@silmarill.org Tue May 7 19:02:15 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 7 May 2002 14:02:15 -0400 Subject: [Tutor] Newbie text file processing question In-Reply-To: References: Message-ID: <20020507180215.GA3042@ak.silmarill.org> On Tue, May 07, 2002 at 12:35:36PM -0400, stuart_clemons@us.ibm.com wrote: > > Hi all: > > I have a question about conditional branching based on the contents of a > text file. I'll try my best to make this understandable ! > > My file is: foo.txt > > The contents of foo.txt are: > > (1)lineA > (2) lineA1stuff=eggs > (3) lineABstuff=spam > (4)lineB > (5) lineB1stuff=cars > (6) lineABstuff=trucks > (7) lineB2stuff=books > (8)lineA > (9) lineA1stuff=eggs > (10 lineA2stuff=eggs > > > I want to do conditional stuff based around if the line is lineA or lineB. > > For example if a line in foo.txt equals "lineA", then check that > lineA1stuff equals eggs and lineABstuff equals spam. If a line equals > "lineB", then check that lineB1stuff equals cars and lineABstuff equals > trucks, etc. NOTICE that the contents of line, "lineABstuff", should be > different if it follows line A or line B. (I hope this isn't too confusing > !) > > I can more-or-less do what I want using line by line processing and if > statements, but the lines, "lineA" and "lineB" aren't being used for > conditional checking and actions (only the "*stuff" lines are). Is there a > better way to do this ? > > Here's an example of the code construct I was thinking of using. > > infile = open('f:\\Python22\\foo.txt', 'r') > for line in infile.xreadlines(): > if line[3:8] == "lineA": > print "Yes, this is line A", line > if line[7:18] == "lineA1stuff": > if line[19:23]== "eggs": > print "this is correct" > else: > print "this is incorrect" > if line[3:8] == "lineB": , etc, etc, etc > This is no good because it relies on exact positions - this can easily break. if line.strip() == "lineA": print "This is line A" elif line.strip() == "lineB": print "Line B here" else: var, val = line.split('=') var = var.strip() val = val.strip() if var == "lineA1stuff": if val == "eggs": print "Line A1 is eggs" - Andrei > > Sorry if this is hopelessly incoherent. > > - Stuart > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From deirdre@deirdre.net Tue May 7 19:42:20 2002 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Tue, 7 May 2002 11:42:20 -0700 Subject: [Tutor] Glade In-Reply-To: <27012922025100.00939@localhost.localdomain> References: <27012922025100.00939@localhost.localdomain> Message-ID: At 9:20 PM -0500 1/29/27, djuro m. wrote: >Hello everyone! > >Could someone please "explain" to me how to make a simple gui working with >python code by using Glade. ( I only need to see a code or how is python code >tied with gui code file) > > I already tried several times according to >instructions in available "Getting started-s" but it didn't work. http://www.baypiggies.net/10mintig.html Yes, I bashed my head against that wall too. -- _Deirdre Stash-o-Matic: http://fuzzyorange.com http://deirdre.net "I'm writing a book. I've got the page numbers done." - Steven Wright From ak@silmarill.org Tue May 7 22:00:57 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 7 May 2002 17:00:57 -0400 Subject: [Tutor] toggle idiom? Message-ID: <20020507210057.GA5337@ak.silmarill.org> Hello, I'm not sure this is a "toggle idiom", but here's what it should do: if a: a = 0 else: a = 1 Is there a one-liner that can do this? - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From shalehperry@attbi.com Tue May 7 22:05:29 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 07 May 2002 14:05:29 -0700 (PDT) Subject: [Tutor] toggle idiom? In-Reply-To: <20020507210057.GA5337@ak.silmarill.org> Message-ID: On 07-May-2002 Andrei Kulakov wrote: > Hello, > > I'm not sure this is a "toggle idiom", but here's what it should do: > > if a: > a = 0 > else: > a = 1 > > Is there a one-liner that can do this? > a = not a From Lindsay@pobox.com Tue May 7 22:51:55 2002 From: Lindsay@pobox.com (Lindsay Davies) Date: Tue, 7 May 2002 22:51:55 +0100 Subject: [Tutor] toggle idiom? In-Reply-To: <20020507210057.GA5337@ak.silmarill.org> References: <20020507210057.GA5337@ak.silmarill.org> Message-ID: Yes, this will do it for you... a = a ^ 1 Lindsay >Hello, > >I'm not sure this is a "toggle idiom", but here's what it should do: > >if a: > a = 0 >else: > a = 1 > >Is there a one-liner that can do this? > >- Andrei > >-- >Cymbaline: intelligent learning mp3 player - python, linux, console. >get it at: cy.silmarill.org > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor -- From erikprice@mac.com Wed May 8 02:37:42 2002 From: erikprice@mac.com (Erik Price) Date: Tue, 7 May 2002 21:37:42 -0400 Subject: [Tutor] Digest mode In-Reply-To: <005701c1f5a2$3f518a20$e7833cca@roltanet.com> Message-ID: <3046A0F1-6224-11D6-AE1B-00039351FE6A@mac.com> On Tuesday, May 7, 2002, at 04:36 AM, Rahul Sen wrote: > Heavens that was quick. Thank you very much. > Ironically, that's the problem with digest mode -- you don't get a quick response like that because the mail server waits a set amount of time before sending a batch. But for the casual tutor@python subscriber, it can be helpful. - Erik who doesn't digest tutor@python, but experiences a similar phenom since he doesn't check it until at night and thus comes hours late to the conversations From idiot1@netzero.net Tue May 7 19:00:11 2002 From: idiot1@netzero.net (kirk Bailey) Date: Tue, 07 May 2002 14:00:11 -0400 Subject: [Tutor] Tampa Bay Python USers Group saught Message-ID: <3CD8162B.C6388032@netzero.net> Let's see if we can get a user group started here in Tampa Bay for Pythonistias. -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ NOTE: By sending SPAM to this address you agree to pay me a service fee of $100 for the service of receiving, storing, examining, and deleting your piece of SPAM. I am a postmaster, and take a dim view of such. From scot@possum.in-berlin.de Wed May 8 08:42:40 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Wed, 8 May 2002 09:42:40 +0200 Subject: [Tutor] Getting rid of global variables Message-ID: <200205071454.g47EsER01890@possum.cozen.org> Hello there, I'm trying to write a small program with tkinter that doesn't use global variables, but am having a hard time figuring out how to do this. I had written a command line version of the program: It takes a Unix style mailbox (with the mailbox module), reads the individual mails, lets the user modify them, and save them as individual files [yes, this is a toy problem, but I learned all kinds of nice stuff about mailboxes, quoted printables, manipulating date strings, calling external editors, etc - it has been very worthwhile]. I used the cmd module to do this -- and lots and lots of global variables. However, after reading Steve McConnell's "Code Complete", I realize that global variables are Evil and should be Cast Out. Also, I figured this was a good chance to do more tkinter. Here is the problem: I've been told that it is a good idea to keep the graphics parts and the actually working routines separate. So for example, I have a menu point that will let the user load a new mailbox file: FileBtn.menu.add_command(label='Open Mailbox...', command=open_mailbox) which calls a routine to actually do the work: def open_mailbox(): file = askopenfilename() try: mbox_file = open(file, 'r') except: showerror("Error", "Can't open file for some reason") mbox = mailbox.UnixMailbox(mbox_file) next(mbox) # gets first message and so forth. I have been told this is good, because I can see about switching the graphics to, say, qt or such in a year or so without much fuss. Now I conceptionally, I get to the point where I send the name of the file as a parameter to the routine that fetches the next mail in the mailbox (which, in this case, is the first one since we just opened it) - this is the last line of code above which calls the "next" routine (which is where I realized I was in trouble, so there is no new code). You can call "next" from a button press, though, too: nextBtn = Button(buttonarea, text='Next', underline=0, command=next) What I can't figure out is what or who, after I've gotten the first mail, "holds on" to the mailtext while I'm waiting for the user to figure out if he wants to "edit", "save", or "next" (discard) this message. In the old version, I had defined mbox and currentmessage etc. as global variables, so they hung around by themselves. I understand that when I'm passing stuff from one routine to the next, I stuff the data into the parameter list - but with tkinter, I'm waiting for the user to decide on what to do, and there is no "main loop" I can pass my data to in the mean time. I have the feeling I should be doing something with objects here - use a "mailbox" and/or "message" object that gets passed around. I don't see how this would solve the problem, though: When I am waiting for the user to make up his mind, who takes care of those objects if they are not a global variable? The other idea I've had is to make the whole program an object, using the constructor to set up the graphics part, but I'm not sure I can really get my mind around that. And it somehow feels like cheating =8). I think I'm missing some basic concept here and would be grateful if somebody could point out which ones of those trees make up the forest... Thanks, Y, Scot From paulsid@shaw.ca Wed May 8 10:21:14 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 08 May 2002 03:21:14 -0600 Subject: [Tutor] Getting rid of global variables References: <200205071454.g47EsER01890@possum.cozen.org> Message-ID: <3CD8EE0A.FBFCB8E8@shaw.ca> Scot Stevenson wrote: > I have the feeling I should be doing something with objects here - use a > "mailbox" and/or "message" object that gets passed around. I don't see how > this would solve the problem, though: When I am waiting for the user to > make up his mind, who takes care of those objects if they are not a global > variable? > > The other idea I've had is to make the whole program an object, using the > constructor to set up the graphics part, but I'm not sure I can really get > my mind around that. And it somehow feels like cheating =8). > > I think I'm missing some basic concept here and would be grateful if > somebody could point out which ones of those trees make up the forest... In C++ I've found that it often ends up that the most straightforward way to do things is to "cheat" with a global variable or two. Otherwise I'd end up with a bunch of "manager" classes that make the program much harder to understand than it would have been had I just made everything global to begin with. To me the the situation you're describing sounds similar. I hope my tiredness isn't causing me to misunderstand the problem, but the "who takes care of..." question suggests to me a "manager" class might be called for. The big problem with manager classes is that to use them you end up jumping through many hoops in order to do a very simple task. It can lead to a kind of "OO-spaghetti code" that makes your program really hard to understand. Part of this is because the manager class ends of duplicating the functionality of the class. For example, a situation I've often faced in the past in working with C++ is how to handle a "master collection" of objects that I'd ideally like to make global. The temptation was to make some sort of ListManager class that handled the list. This class would have to provide methods for add, delete, find, etc. But why bother when lists have this built in? So the next thought is to just put the list inside a class and make it a public variable. This is simpler, but BZZZT - it's cheating! Making variables public is a violation of good OO-style. So at this point I had to choose which OO convention to violate. I chose to make the lists global, my reasoning being that making it global left the cleanest code. The nice thing is that Python programmers tend to have a more liberal attitude towards globals, so using them is not really considered flagrant cheating like it would be in C++. :-) Anyhow, try to keep these tips in mind: - DO keep the logic and graphics as separate as possible. - DO get rid of as many global variables as you can because the book is right: globals are something that should be avoided whenever possible. - DON'T read a book like Code Complete and feel you have to revolutionize your way of doing things overnight. It would be foolish for a craftsperson to buy a tool kit and then try to learn to use them all on a current project, so why try to do that when coding? Apply what you can understand now - this will still make your code that much better. Later on you might find a better way to do things, and if the situation calls for it you can upgrade the program. If not, at least you saved yourself a bunch of frustration. Having said all of this, it's probably the case that there's an entirely suitable way to solve your problem that both of us are just missing. If so I look forward to hearing it because it means I'll get to learn something too! -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From erikprice@mac.com Wed May 8 12:55:08 2002 From: erikprice@mac.com (Erik Price) Date: Wed, 8 May 2002 07:55:08 -0400 Subject: [Tutor] arrays and strings In-Reply-To: <3cd8ef17.2b45.0@pakistanmail.com> Message-ID: <71B14C9C-627A-11D6-AE1B-00039351FE6A@mac.com> On Wednesday, May 8, 2002, at 08:46 AM, wonderer@pakistanmail.com wrote: > I m sorry to bother u again but i just wanted to know if there is any > equivalent > of c-style #define in python > coz i m decalring a varianle globally in one file (util.py)and then > want to > access in another file named test.py but that gives me error as > NameError:"name" > not defined wonderer, fyi I CC'd this msg to the list b/c I'm no Python master, and hopefully someone else can come up with something constructive. From what I understand of Python, you would want to import "util.py" as a module into the script where you're trying to use the global variable, which means that the global variable is now "util.variablename" (I think). I have no experience with C, so I'm not sure if this is the same thing as #define (not sure what that is...) Good luck though. Erik From pythontutor@venix.com Wed May 8 15:12:11 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 08 May 2002 10:12:11 -0400 Subject: [Tutor] arrays and strings References: <71B14C9C-627A-11D6-AE1B-00039351FE6A@mac.com> Message-ID: <3CD9323B.9000209@venix.com> You don't really need #define with Python. C needs #define to avoid unnecessary type restrictions. In C #define MAX_DAYS 31 provides a number that will work for most contexts while int MAX_DAYS=31; will only work in integer contexts. Since Python's type processing is dynamic and supports type checking, you can simply state: MAX_DAYS = 31 and use MAX_DAYS whereever necessary. Effectively, it is a global, variable and you want to avoid changing it. In practise you use it as a constant that is defined in one place. Erik Price wrote: > > On Wednesday, May 8, 2002, at 08:46 AM, wonderer@pakistanmail.com wrote: > >> I m sorry to bother u again but i just wanted to know if there is any >> equivalent >> of c-style #define in python >> coz i m decalring a varianle globally in one file (util.py)and then >> want to >> access in another file named test.py but that gives me error as >> NameError:"name" >> not defined > > > wonderer, fyi I CC'd this msg to the list b/c I'm no Python master, and > hopefully someone else can come up with something constructive. > > From what I understand of Python, you would want to import "util.py" as > a module into the script where you're trying to use the global variable, > which means that the global variable is now "util.variablename" (I > think). I have no experience with C, so I'm not sure if this is the > same thing as #define (not sure what that is...) > > Good luck though. > > > Erik > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From ak@silmarill.org Wed May 8 15:33:19 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 8 May 2002 10:33:19 -0400 Subject: [Tutor] toggle idiom? In-Reply-To: References: <20020507210057.GA5337@ak.silmarill.org> Message-ID: <20020508143319.GA13146@ak.silmarill.org> On Tue, May 07, 2002 at 02:05:29PM -0700, Sean 'Shaleh' Perry wrote: > > On 07-May-2002 Andrei Kulakov wrote: > > Hello, > > > > I'm not sure this is a "toggle idiom", but here's what it should do: > > > > if a: > > a = 0 > > else: > > a = 1 > > > > Is there a one-liner that can do this? > > > > a = not a > Thanks to all who answered.. all I can say is "Doh".. or maybe "Duh". - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From shalehperry@attbi.com Wed May 8 15:49:32 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 08 May 2002 07:49:32 -0700 (PDT) Subject: [Tutor] Getting rid of global variables In-Reply-To: <3CD8EE0A.FBFCB8E8@shaw.ca> Message-ID: > > In C++ I've found that it often ends up that the most straightforward > way to do things is to "cheat" with a global variable or two. Otherwise > I'd end up with a bunch of "manager" classes that make the program much > harder to understand than it would have been had I just made everything > global to begin with. > Like all rules it is important to understand why the rule exists and decide if that makes sense for the current application. Globals are hated and feared because they create hidden and problematic dependencies in your code. You have this nice function you want to reuse and discover "oh, I need THIS_VARIABLE" and things start to go bad. Another reason is globals are almost guaranteed to break threading code. > To me the the situation you're describing sounds similar. I hope my > tiredness isn't causing me to misunderstand the problem, but the "who > takes care of..." question suggests to me a "manager" class might be > called for. > perhaps, or perhaps he needs a State class. This would allow multiple mailboxes, users, etc. > > Part of this is because the manager class ends of duplicating the > functionality of the class. For example, a situation I've often faced > in the past in working with C++ is how to handle a "master collection" > of objects that I'd ideally like to make global. The temptation was to > make some sort of ListManager class that handled the list. This class > would have to provide methods for add, delete, find, etc. But why > bother when lists have this built in? > > So the next thought is to just put the list inside a class and make it a > public variable. This is simpler, but BZZZT - it's cheating! Making > variables public is a violation of good OO-style. So at this point I > had to choose which OO convention to violate. I chose to make the lists > global, my reasoning being that making it global left the cleanest code. > another approach is to use singleton style classes with a static member that returns the instance. class Foo { public: Foo* instance(void) { return singleton; } }; Foo::instance()->method(); > The nice thing is that Python programmers tend to have a more liberal > attitude towards globals, so using them is not really considered > flagrant cheating like it would be in C++. :-) > part of the C++ (and software industry) hatred of globals is the threading issues they create. Globals guarantee problems when it comes time to refactor or grow. > > - DON'T read a book like Code Complete and feel you have to > revolutionize your way of doing things overnight. It would be foolish > for a craftsperson to buy a tool kit and then try to learn to use them > all on a current project, so why try to do that when coding? Apply what > you can understand now - this will still make your code that much > better. Later on you might find a better way to do things, and if the > situation calls for it you can upgrade the program. If not, at least > you saved yourself a bunch of frustration. > This is very important and several of the good programming books comment on this. It is good to reevaluate your approach to programming. However when you start using every nifty tool in the box other people look at your code and can see it. A consistent style is more important than crafty uses of the language. From lha2@columbia.edu Wed May 8 23:21:28 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Wed, 08 May 2002 18:21:28 -0400 Subject: [Tutor] toggle idiom? References: <20020507210057.GA5337@ak.silmarill.org> Message-ID: <3CD9A4E8.9BDECECF@mail.verizon.net> a = 0 ** a also seems to work (is this c-dependent?), although 0 ** 0 really should be undefined (in real math, 0**a should be zero for a!=0, and b**0 should be one for b!=0; when you do 0**0, your head should explode). Lindsay Davies wrote: > > Yes, this will do it for you... > > a = a ^ 1 > > Lindsay > > >Hello, > > > >I'm not sure this is a "toggle idiom", but here's what it should do: > > > >if a: > > a = 0 > >else: > > a = 1 > > > >Is there a one-liner that can do this? > > > >- Andrei > > > >-- > >Cymbaline: intelligent learning mp3 player - python, linux, console. > >get it at: cy.silmarill.org > > > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > -- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dman@dman.ddts.net Wed May 8 23:42:28 2002 From: dman@dman.ddts.net (dman) Date: Wed, 8 May 2002 17:42:28 -0500 Subject: [Tutor] toggle idiom? In-Reply-To: <3CD9A4E8.9BDECECF@mail.verizon.net> References: <20020507210057.GA5337@ak.silmarill.org> <3CD9A4E8.9BDECECF@mail.verizon.net> Message-ID: <20020508224228.GA19140@dman.ddts.net> --dDRMvlgZJXvWKvBx Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 08, 2002 at 06:21:28PM -0400, Lloyd Hugh Allen wrote: | a =3D 0 ** a |=20 | also seems to work (is this c-dependent?), It is dependent upon the possible values of a. The original code was : if a: a =3D 0 else: a =3D 1 If a had been a list in the first place, the original would work. 0 ** [] is (naturally) a type error. The exponentiation version also fails if a was originally negative (divide-by-zero). If a can only be 0 or 1 to start with, then any mathematical expression that yields the other value would work. I would argue that a =3D not a is the best way of writing the original code because it clearly shows the logic (as apposed to arithmetic) intent of the operation and works for all cases the original works for. The only reason for using the original instead of this is if a must be 0 or 1 in the end, rather than simply a false or true value. | although 0 ** 0 really should be undefined (in real math, 0**a | should be zero for a!=3D0, and b**0 should be one for b!=3D0; when you | do 0**0, your head should explode). You're right. -D --=20 The teaching of the wise is a fountain of life, turning a man from the snares of death. Proverbs 13:14 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --dDRMvlgZJXvWKvBx Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzZqdQACgkQO8l8XBKTpRQPWgCgws5Z28mbcOqkmaB3qPOPKNst YJYAnilKmdwBlD69N05Cb+x8U+Msfgyp =FDE6 -----END PGP SIGNATURE----- --dDRMvlgZJXvWKvBx-- From shalehperry@attbi.com Wed May 8 23:36:15 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 08 May 2002 15:36:15 -0700 (PDT) Subject: [Tutor] toggle idiom? In-Reply-To: <20020508224228.GA19140@dman.ddts.net> Message-ID: > > I would argue that > a = not a > is the best way of writing the original code because it clearly > shows the logic (as apposed to arithmetic) intent of the operation and > works for all cases the original works for. The only reason for using > the original instead of this is if a must be 0 or 1 in the end, rather > than simply a false or true value. > is there a case where 'a = not a' will yield a value other than 0 or 1? i am not aware of one. From dman@dman.ddts.net Thu May 9 00:47:56 2002 From: dman@dman.ddts.net (dman) Date: Wed, 8 May 2002 18:47:56 -0500 Subject: [Tutor] toggle idiom? In-Reply-To: References: <20020508224228.GA19140@dman.ddts.net> Message-ID: <20020508234756.GB19140@dman.ddts.net> --yEPQxsgoJgBvi8ip Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 08, 2002 at 03:36:15PM -0700, Sean 'Shaleh' Perry wrote: | > I would argue that | > a =3D not a | > is the best way of writing the original code because it clearly | > shows the logic (as apposed to arithmetic) intent of the operation and | > works for all cases the original works for. The only reason for using | > the original instead of this is if a must be 0 or 1 in the end, rather | > than simply a false or true value. |=20 | is there a case where 'a =3D not a' will yield a value other than 0 or | 1? i am not aware of one. All boolean operations in CPython 2.3. (see PEP 285) It is also the case in Java (boolean operations return a 'boolean' not an 'int') and probably C++ as well. I know you are referring to current python implementations (eg CPython 1.5.2, 2.0, 2.1, 2.2), but it _is_ implementation dependent. It is never a good idea to rely on implementation dependent behavior if it is avoidable. IMO it is more obscure to use boolean operators when arithmetic results are required. Obscure code is not a good thing. -D --=20 Many a man claims to have unfailing love, but a faithful man who can find? Proverbs 20:6 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --yEPQxsgoJgBvi8ip Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzZuSwACgkQO8l8XBKTpRQPxgCeInbCVh2ulKqUpixGRpLvKb2H 0LoAoMRTTn6/6PKHn2AtjkuYG5zQw+Wf =tawo -----END PGP SIGNATURE----- --yEPQxsgoJgBvi8ip-- From paulsid@shaw.ca Thu May 9 00:22:38 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 08 May 2002 17:22:38 -0600 Subject: [Tutor] toggle idiom? References: Message-ID: <3CD9B33E.D44E095@shaw.ca> Sean 'Shaleh' Perry wrote: > > is the best way of writing the original code because it clearly > > shows the logic (as apposed to arithmetic) intent of the operation and > > works for all cases the original works for. The only reason for using > > the original instead of this is if a must be 0 or 1 in the end, rather > > than simply a false or true value. > > is there a case where 'a = not a' will yield a value other than 0 or 1? i am > not aware of one. Neither am I, and furthermore the new boolean type coming in for 2.3 will have True == 1 and False == 0. This strongly suggests that not False == True == 1 is already the norm, as is not == False == 0. If this wasn't the case then old code could break when the boolean type is introduced, and avoiding that was a key concern (see PEP 285). I can't see any problem with a = not a. It's been used in C for years, perhaps decades. In fact the only other reasonable alternative I've seen is using C's ternary ?: operator (a = a ? 0 : 1) which is really just a short form of what the OP already had, but since Python has no ?: or equivalent this isn't an option. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From dyoo@hkn.eecs.berkeley.edu Thu May 9 02:40:04 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 8 May 2002 18:40:04 -0700 (PDT) Subject: [Tutor] toggle idiom? In-Reply-To: Message-ID: On Tue, 7 May 2002, Lindsay Davies wrote: > Yes, this will do it for you... > > a = a ^ 1 > > Lindsay Alternatively: ### a = 1 - a ### is something that can toggle between zero and one. Another one-liner could be: ### a = (a + 1) % 2 ### although that one might be a bit more expensive than the other method. So there are a lots of good choices here. Good luck! From dman@dman.ddts.net Thu May 9 05:12:31 2002 From: dman@dman.ddts.net (dman) Date: Wed, 8 May 2002 23:12:31 -0500 Subject: [Tutor] toggle idiom? In-Reply-To: <3CD9B33E.D44E095@shaw.ca> References: <3CD9B33E.D44E095@shaw.ca> Message-ID: <20020509041231.GC22335@dman.ddts.net> --uXxzq0nDebZQVNAZ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 08, 2002 at 05:22:38PM -0600, Paul Sidorsky wrote: | Sean 'Shaleh' Perry wrote: |=20 | > > is the best way of writing the original code because it clearly | > > shows the logic (as apposed to arithmetic) intent of the operation and | > > works for all cases the original works for. The only reason for using | > > the original instead of this is if a must be 0 or 1 in the end, rather | > > than simply a false or true value. | >=20 | > is there a case where 'a =3D not a' will yield a value other than 0 or = 1? i am | > not aware of one. |=20 | Neither am I, and furthermore the new boolean type coming in for 2.3 | will have True =3D=3D 1 and False =3D=3D 0. This strongly suggests that = not | False =3D=3D True =3D=3D 1 is already the norm, as is not =3D= =3D False =3D=3D | 0. If this wasn't the case then old code could break when the boolean | type is introduced, and avoiding that was a key concern (see PEP 285). =20 Old code would only break when it uses the boolean values in a non-boolean context or when checking equality of two "boolean" values. For example the following snippets : if a and b : print "good" if a =3D=3D b : print "not good" The former will not break as long as the truth value of the objects remains the same (which is independent from "True=3D=3D1"). It can even handle the situation where different "true" values are used for a and b. The second expression would break if a and b were different objects both evaluating to true. | I can't see any problem with a =3D not a.=20 The only problem is *if* you want the result to be an integer rather than a boolean. "not a" is a logical operation, not an arithmetic one, and the fact that it _happens_ to return 0 or 1 in cpython today isn't behavior that should be relied upon. | It's been used in C for years, perhaps decades. Sure, but in C it is often unclear whether the value is meant as a regular number, as a boolean, or as a special case indicator (0 =3D=3D success , 0 =3D=3D failure , 0 =3D=3D NULL , 0 =3D=3D equality (eg strcmp))= . This is my only complaint with the technique -- readability later. This is also why I think adding the built-in names True and False is a Good Thing. (by the same token, no one should write code like if expr =3D=3D True : ... it should simply be if expr : ... ) | In fact the only other reasonable alternative I've | seen is using C's ternary ?: operator (a =3D a ? 0 : 1) This requires more conscious thought to understand. As Kernighan and Pike said, use the idiomatic expression of a concept as that is most easily recognized by other readers of your code. | which is really just a short form of what the OP already had, but | since Python has no ?: or equivalent this isn't an option. a and 1 or 0 *BUT* don't use it! The reason is the same as above. It just _happens_ that the current implementation of python will return the second object rather than normalizing it to a boolean object or some such. In fact, I expect that expression to fail for all future versions of python except in the case where 1 and 0 are used (as shown) In summary, I don't really disagree with you (Paul), but there are readability (and thus maintainability) repercussions to the various styles of operating with values that serve multiple purposes. -D --=20 He who finds a wife finds what is good and receives favor from the Lord. Proverbs 18:22 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --uXxzq0nDebZQVNAZ Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzZ9y8ACgkQO8l8XBKTpRQI6wCfX32+63t39JLxNP+bvukbVZzn 5yUAn2ZV98nrC+aPwWTKkhz0yLGOekN4 =LWse -----END PGP SIGNATURE----- --uXxzq0nDebZQVNAZ-- From idiot1@netzero.net Thu May 9 05:32:04 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 09 May 2002 00:32:04 -0400 Subject: [Tutor] board.py Message-ID: <3CD9FBC4.45303AA2@netzero.net> OK, crawling through the vaults of parynissus (spell check?) I tripped over no less than 2 discussion boards- one of which refuses to load, server not replying or somethign, but the other, board.py, is easy to find and installed in a flash. It is now at the TinyList website if anyone wants to see it working, and it is in the public domain. I love this toy. I love this language! Again, I found myself muttering, 'This is too easy...'. -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ NOTE: By sending SPAM to this address you agree to pay me a service fee of $100 for the service of receiving, storing, examining, and deleting your piece of SPAM. I am a postmaster, and take a dim view of such. From paulsid@shaw.ca Thu May 9 06:58:26 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 08 May 2002 23:58:26 -0600 Subject: [Tutor] toggle idiom? References: <3CD9B33E.D44E095@shaw.ca> <20020509041231.GC22335@dman.ddts.net> Message-ID: <3CDA1002.E476EE85@shaw.ca> dman wrote: > The only problem is *if* you want the result to be an integer rather > than a boolean. "not a" is a logical operation, not an arithmetic > one, and the fact that it _happens_ to return 0 or 1 in cpython today > isn't behavior that should be relied upon. Actually, it can (unlike in, say, C). The Python language reference guarantees it: > The operator not yields 1 if its argument is false, 0 otherwise. Now of course that will change to True and False in 2.3, but like I said since True == 1 and False == 0 old code won't break. IIRC in 2.3 int(somevaroftypebool) will return only 0 or 1 as well, though since bool will be derived from int this conversion is merely just a declaration of intent. > | It's been used in C for years, perhaps decades. > > Sure, but in C it is often unclear whether the value is meant as a > regular number, as a boolean, or as a special case indicator (0 == > success , 0 == failure , 0 == NULL , 0 == equality (eg strcmp)). This > is my only complaint with the technique -- readability later. This is > also why I think adding the built-in names True and False is a Good > Thing. (by the same token, no one should write code like > if expr == True : ... it should simply be if expr : ... ) I agree. Actually I was one of those who were trying to argue in c.l.py that expr == True should fail iff expr isn't of boolean type so that if expr was an integer people wouldn't be confused when 5 == True failed, but unfortunately it would break too much code to use "pure" boolean variables in this fashion. Like it or not, many people do rely on the idioms... > This requires more conscious thought to understand. As Kernighan and > Pike said, use the idiomatic expression of a concept as that is most > easily recognized by other readers of your code. Well personally I don't think a C programmer who is reasonably comfortable with the language would have to think twice about a ? 0 : 1. But we're talking about Python, not C, so I'll move on. > | which is really just a short form of what the OP already had, but > | since Python has no ?: or equivalent this isn't an option. > > a and 1 or 0 This isn't equivalent, though, because it fails if the middle part is false. Most people probably know this already, but in case anybody doesn't: The "contrapositive" of the above fails because 0 is false: >>> a = 0 >>> a and 1 or 0 # a ? 1 : 0 0 >>> (not a) and 0 or 1 # !a ? 0 : 1 - should be same as above 1 Furthermore this is an abuse of operators, whereas in C it's a built-in operation supported by the language. > *BUT* don't use it! The reason is the same as above. It just > _happens_ that the current implementation of python will return the > second object rather than normalizing it to a boolean object or some > such. In fact, I expect that expression to fail for all future > versions of python except in the case where 1 and 0 are used (as > shown) Yes, unlike the a = not a thing the behaviour of the "psuedo-ternary operator" is not specified anywhere. I'm not sure I agree about this failing in the future, but ideally that's something I'd rather not have to find out. :-) > In summary, I don't really disagree with you (Paul), but there are > readability (and thus maintainability) repercussions to the various > styles of operating with values that serve multiple purposes. Agreed. Though I'm not sure the following is any better (for integers): def signum(x): if x == 0: return 0 return 1 ... a = signum(a) This is undoubtedly explicit, but it is really easier to read or maintain? One would probably have to look up signum() (or whatever it's called - the name likely doesn't matter) to find out what it does, and then a maintenance programmer would have to remember to use this instead of a = not a to ensure consistent behaviour. (I realize you were never arguing against using a = not a. I just wanted to note that sometimes even the most explicit way isn't ideal.) BTW the name signum() is something I took from a logic textbook since it seems appropriate, although in the the text it applies only to natural numbers. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From erikprice@mac.com Thu May 9 12:50:37 2002 From: erikprice@mac.com (Erik Price) Date: Thu, 9 May 2002 07:50:37 -0400 Subject: [Tutor] toggle idiom? In-Reply-To: <20020509041231.GC22335@dman.ddts.net> Message-ID: On Thursday, May 9, 2002, at 12:12 AM, dman wrote: > Old code would only break when it uses the boolean values in a > non-boolean context or when checking equality of two "boolean" values. > For example the following snippets : > > if a and b : print "good" > if a == b : print "not good" > > The former will not break as long as the truth value of the objects > remains the same (which is independent from "True==1"). It can even > handle the situation where different "true" values are used for a and > b. The second expression would break if a and b were different > objects both evaluating to true. Won't the former also print "good" if for some reason the value of a is 1 and the value of b is 2? This could be problematic too, no? Or do we just have to trust that this test is ONLY being used for boolean value, and that we aren't checking for isequals or any other value test.... Erik From pythontutor@venix.com Thu May 9 13:45:40 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 09 May 2002 08:45:40 -0400 Subject: [Tutor] toggle idiom? References: <3CD9B33E.D44E095@shaw.ca> Message-ID: <3CDA6F74.3050006@venix.com> Paul Sidorsky wrote: > perhaps decades. In fact the only other reasonable alternative I've > seen is using C's ternary ?: operator (a = a ? 0 : 1) which is really > just a short form of what the OP already had, but since Python has no ?: > or equivalent this isn't an option. As an old C programmer I missed ?: and was interested to find this article by David Mertz. http://gnosis.cx/publish/programming/charming_python_13.html CHARMING PYTHON #13 (20000155) -- Functional Programming in Python -- Dr. Mertz later wrote the following correction for eliminating if statements. ( and [func1()]) or ( and [func2()]) or ([func3()])[0] The Python equivalent of (cond)?(e1):(e2) becomes ((cond and [e1]) or [e2])[0] The e1 and e2 get embedded into lists to cover the case where e1 is false. Otherwise Python would then go on to evaluate e2 whereas we really want to stop at e1 when cond is true. [e1] is always true. That is even [0] is true. The [0] at the end of the expression extracts the e1 or e2 result from the list. When e1 is true, the code is more reasonable (cond and e1) or e2 All in all, this is a bit ugly for casual use. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dman@dman.ddts.net Thu May 9 15:01:32 2002 From: dman@dman.ddts.net (dman) Date: Thu, 9 May 2002 09:01:32 -0500 Subject: [Tutor] toggle idiom? In-Reply-To: References: <20020509041231.GC22335@dman.ddts.net> Message-ID: <20020509140132.GA27022@dman.ddts.net> --MGYHOYXEY6WxJCY8 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, May 09, 2002 at 07:50:37AM -0400, Erik Price wrote: |=20 | On Thursday, May 9, 2002, at 12:12 AM, dman wrote: |=20 | >Old code would only break when it uses the boolean values in a | >non-boolean context or when checking equality of two "boolean" values. | >For example the following snippets : | > | >if a and b : print "good" | >if a =3D=3D b : print "not good" | > | >The former will not break as long as the truth value of the objects | >remains the same (which is independent from "True=3D=3D1"). It can even | >handle the situation where different "true" values are used for a and | >b. The second expression would break if a and b were different | >objects both evaluating to true. |=20 | Won't the former also print "good" if for some reason the value of a is= =20 | 1 and the value of b is 2? Yes, because both are "true". | This could be problematic too, no? *IF* you meant to perform an arithmetic operation. The original block of code contained only a boolean test, though the result of the test is ambiguous as to whether the result is boolean or arithmetic (which is a major reason for python 2.3 including the names True and False). | Or do we just have to trust that this test is ONLY being used for | boolean value, and that we aren't checking for isequals or any other | value test.... Right. If you want to work in the realm of logic, use logical operators and values (eg objectes named True and False). If you want to work in the realm of arithmetic, then use arithmetic values (ints, floats) and not boolean ones. Intermixing the two may be fun when coming up with the most obfuscated way of writing something, but not a good idea when writing real code. (eg don't use exponentiation to achieve a logic operation :-)) -D --=20 Like a gold ring in a pig's snout is a beautiful woman who shows no discretion. Proverbs 11:22 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --MGYHOYXEY6WxJCY8 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzagTwACgkQO8l8XBKTpRTI6gCgqbRF6azcKb7mMWU+ZAWFlGNu iCMAoMoL0HYGPzAtxCzCC5EGiSXOz352 =ez+S -----END PGP SIGNATURE----- --MGYHOYXEY6WxJCY8-- From dman@dman.ddts.net Thu May 9 15:15:44 2002 From: dman@dman.ddts.net (dman) Date: Thu, 9 May 2002 09:15:44 -0500 Subject: [Tutor] toggle idiom? In-Reply-To: <3CDA1002.E476EE85@shaw.ca> References: <3CD9B33E.D44E095@shaw.ca> <20020509041231.GC22335@dman.ddts.net> <3CDA1002.E476EE85@shaw.ca> Message-ID: <20020509141544.GB27022@dman.ddts.net> --hHWLQfXTYDoKhP50 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 08, 2002 at 11:58:26PM -0600, Paul Sidorsky wrote: | dman wrote: |=20 | > The only problem is *if* you want the result to be an integer rather | > than a boolean. "not a" is a logical operation, not an arithmetic | > one, and the fact that it _happens_ to return 0 or 1 in cpython today | > isn't behavior that should be relied upon. |=20 | Actually, it can (unlike in, say, C). The Python language reference | guarantees it: |=20 | > The operator not yields 1 if its argument is false, 0 otherwise. =20 Oh, I didn't realize that was part of the spec. I internally took a purer view of logic that's more in line with Java's spec (though I like the fact that all objects such as None and lists have a truth value). | Now of course that will change to True and False in 2.3, As it should (IMO). | but like I said since True =3D=3D 1 and False =3D=3D 0 old code won't bre= ak. Since the spec guaranteed a result of 1 or 0, this would be required to not break the spec (never mind code that mixes logic and arithmetic unnaturally). =20 | IIRC in 2.3 int(somevaroftypebool) will return only 0 or 1 as well, | though since bool will be derived from int this conversion is merely | just a declaration of intent. Ok. Note that this declaration of intent is very important for the maintainer of your code. | > | It's been used in C for years, perhaps decades. | >=20 | > Sure, but in C it is often unclear whether the value is meant as a | > regular number, as a boolean, or as a special case indicator (0 =3D=3D | > success , 0 =3D=3D failure , 0 =3D=3D NULL , 0 =3D=3D equality (eg strc= mp)). This | > is my only complaint with the technique -- readability later. This is | > also why I think adding the built-in names True and False is a Good | > Thing. (by the same token, no one should write code like | > if expr =3D=3D True : ... it should simply be if expr : ... ) |=20 | I agree. Actually I was one of those who were trying to argue in c.l.py | that expr =3D=3D True should fail iff expr isn't of boolean type so that = if | expr was an integer people wouldn't be confused when 5 =3D=3D True failed, Cool :-). I agree with that too. | but unfortunately it would break too much code to use "pure" boolean | variables in this fashion. Like it or not, many people do rely on the | idioms... Yeah, that's the real world of "backwards compatibility". | > This requires more conscious thought to understand. As Kernighan and | > Pike said, use the idiomatic expression of a concept as that is most | > easily recognized by other readers of your code. |=20 | Well personally I don't think a C programmer who is reasonably | comfortable with the language would have to think twice about a ? 0 : | 1. The thinking twice comes when the reader must determine whether the result of the expression is arithmetic or boolean. If it's boolean, then writing '!' is shorter and more idiomatic (IMO). It's precisely for this declaration of intent that I #define true and false and use the names instead of the integer literals. IIRC C99 now has a boolean type and the keywords true and false :-). | But we're talking about Python, not C, so I'll move on. Sure. =20 | > | which is really just a short form of what the OP already had, but | > | since Python has no ?: or equivalent this isn't an option. | >=20 | > a and 1 or 0 |=20 | This isn't equivalent, though, because it fails if the middle part is | false. Oh, yeah, I thought that expression looked too simple. More guru-like people have posted the "correct" python expression to achieve the ternary operator, and then threatened to break anybody's legs who actuall used it :-). | Most people probably know this already, but in case anybody doesn't: | The "contrapositive" of the above fails because 0 is false: |=20 | >>> a =3D 0 | >>> a and 1 or 0 # a ? 1 : 0 | 0 | >>> (not a) and 0 or 1 # !a ? 0 : 1 - should be same as above | 1 |=20 | Furthermore this is an abuse of operators, whereas in C it's a built-in | operation supported by the language. Right. | > *BUT* don't use it! The reason is the same as above. It just | > _happens_ that the current implementation of python will return the | > second object rather than normalizing it to a boolean object or some | > such. In fact, I expect that expression to fail for all future | > versions of python except in the case where 1 and 0 are used (as | > shown) |=20 | Yes, unlike the a =3D not a thing the behaviour of the "psuedo-ternary | operator" is not specified anywhere. I'm not sure I agree about this | failing in the future, but ideally that's something I'd rather not have | to find out. :-) PEP 285 says that all the boolean operations will be changed to return either True or False. If the expression returns True, and True !=3D , then the hack doesn't work anymore. It only works now because python doesn't "normalize" the result to a boolean object. =20 | > In summary, I don't really disagree with you (Paul), but there are | > readability (and thus maintainability) repercussions to the various | > styles of operating with values that serve multiple purposes. |=20 | Agreed. Though I'm not sure the following is any better (for integers): |=20 | def signum(x): | if x =3D=3D 0: | return 0 | return 1 | ... | a =3D signum(a) |=20 | This is undoubtedly explicit, but it is really easier to read or | maintain?=20 Is the result supposed to be arithmetic or boolean? | One would probably have to look up signum() (or whatever it's | called - the name likely doesn't matter) to find out what it does, and | then a maintenance programmer would have to remember to use this instead | of a =3D not a to ensure consistent behaviour. Yes, but naming is quite important, according to Martin Fowler (and I agree). | (I realize you were never arguing against using a =3D not a. I just | wanted to note that sometimes even the most explicit way isn't ideal.) =20 I argue against using o logical operations to achieve arithmetic results o arithmetic (or any other non-logic) operation to achieve a boolean result Of course, if non-logic operations are used in an algorithm, then a logical test is made against some other object, that's fine because a logical test was made to yield the boolean result. | BTW the name signum() is something I took from a logic textbook since it | seems appropriate, although in the the text it applies only to natural | numbers. While I did build a small adder using TTL, hardware doesn't have high-level operators like "+" the way software does. My whole point in beginning this discussion was to advocate being clear in the declaration of intent to aid future maintence of the code. HAND, -D --=20 Many a man claims to have unfailing love, but a faithful man who can find? Proverbs 20:6 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --hHWLQfXTYDoKhP50 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzahJAACgkQO8l8XBKTpRShTwCglFFODPN7nOD1MDaeglA779kS n0IAn3BLLMjZpzOeW/bunzz/JbtpUaCl =d9ys -----END PGP SIGNATURE----- --hHWLQfXTYDoKhP50-- From jeff@ccvcorp.com Thu May 9 17:44:21 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 09 May 2002 09:44:21 -0700 Subject: [Tutor] toggle idiom? References: <3CD9B33E.D44E095@shaw.ca> <20020509041231.GC22335@dman.ddts.net> <3CDA1002.E476EE85@shaw.ca> <20020509141544.GB27022@dman.ddts.net> Message-ID: <3CDAA764.254DD1BB@ccvcorp.com> dman wrote: > > | Yes, unlike the a = not a thing the behaviour of the "psuedo-ternary > | operator" is not specified anywhere. I'm not sure I agree about this > | failing in the future, but ideally that's something I'd rather not have > | to find out. :-) > > PEP 285 says that all the boolean operations will be changed to return > either True or False. If the expression returns True, and True != > , then the hack doesn't work anymore. It only works > now because python doesn't "normalize" the result to a boolean object. In discussions on c.l.py, the PythonLabs folks did specifically say that the behavior of and/or won't change -- they will still return the full result, and not normalize to boolean. I believe that the main reason for this *is* backwards compatibility, because the and/or pseudo-trinary thing has been in use for a long time. (Personally, I would never use it, as it seems unclear at best, and downright obfuscatory at worst, but that's me.) Jeff Shannon Technician/Programmer Credit International From dominic.fox" Hi all, I've just joined this list, and decided to dive right in rather than lurk as I tend to find that participation increases my enjoyment of email lists (as well as the likelihood of my reading anything that appears in them). I'm a shortly-to-be-married 27-year-old father of a two-year-old boy, living in Leicester, UK. Professionally I'm a VB-weenie working in the "Operational Development" department of a moderately well-known financial institution. I am getting rather sick and tired of VB; mainly I am sick and tired of its collection classes, its piecemeal OO support, its general clunkiness and the fact that to do anything really useful you have to hack the environment in truly *abysmal* ways (I read a few pages of a highly-rated book on subclassing and vtable jiggery-pokery, and thought: this is god's way of telling you to program in a different language. Possibly a "harder" one, but more importantly one that doesn't hide all this stuff away from you, then make you go look for it anyway whilst repeatedly poking you in the eye with a pointy stick). Python appeals to me because, rather like Perl, it lets you wade right in with all sorts of highly flexible and accommodating data structures - it took about half an hour of playing with Idle for my hatred of VB collections to crystallise into pure hard-boiled contempt. The shift from static to dynamic typing is a bit vertigo-inducing, but Javascript's already softened me up for that. Generally it seems like the language manages a good compromise between slack and rigor. I've got "Programming in Python" coming from Amazon. Anyone got any suggestions for other helpful texts, especially for VB-weenies? Dominic --> Nobody knows the trouble you've seen / walking from your desk to the staff canteen <-- homepage: http://www.geocities.com/domfox From marcolinux@linuxbr.com.br Mon May 6 18:39:24 2002 From: marcolinux@linuxbr.com.br (Marco) Date: Mon, 6 May 2002 14:39:24 -0300 Subject: [Tutor] streaming audio In-Reply-To: <1020652901.21030.1.camel@orion.zoism.org> References: <1020652901.21030.1.camel@orion.zoism.org> Message-ID: <20020506143924.A3073@marcolab.proconet> Rob Brown-Bayliss (rob@zoism.org) wrote: > > Hi, > > I am looking for some information on the basics of audio streaming, or > any sort of data streaming really. > > I want to create an app to stream audio around a LAN and really have > know Idea on where to start. > >From the "Yes-I-know-my-english-sux" dept: Probably this is not what you want but at least shows a very inefficient way of doing it, the wrong way :) Some days ago I was playing with my TV/radio board. I put it on my linux server so that I could record shows without leaving my workstation turned on all night. Then I thought: how can I listen the radio now? I need some way to tranfer some bytes from server sound board to local sound board. I remembered a litle program called netcat (nc). It's used for many things like send requests for servers, very useful for debbuging cgi scripts. Search for it on google. Felt it would be just what I needed: Did the following (server side): $ cat /dev/dsp | nc -l -p 8081 (Grab bytes from /dev/dsp (sound board) and make them available at port 8081.) And (workstation side): $ nc my.server.adress 8081 >/dev/dsp (Pull bytes from my.server.adress port 8081 and send them to my sound card.) And guess what? It worked :) Then I stared at it for some minutes, thinking about the joy of having command line tools and a unix shell.This things are really amazing, working with linux for more then 4 years and still discovering new tricks. Unfortunaly , having to get back to work I was forced to delay a project of controlling a radio board from intranet with python. BTW, does someone know how to do ioctl from python? The docs says some things about fctnl but is too vague. We can always do it in C/swig but it would be nice a pure python way. Thanks for reading this far and I hope it helps. Marco From rob@uselesspython.com Fri May 10 15:47:27 2002 From: rob@uselesspython.com (Rob Andrews) Date: Fri, 10 May 2002 09:47:27 -0500 Subject: [Tutor] Brainbench Python 1.5 Certification Message-ID: <3CDBDD7F.30106@uselesspython.com> I've never run across anyone commenting on the Python 1.5 Certification that brainbench.com offers. And since I have a Brainbench subscription, I figured I'd take a break from working on the new Useless Python site (about half-way done, BTW, if not better) and give it a stab. Until someone else comes up with a Python certification, this is the only one I know of. It's a bit dated, since a few things changed between 1.5 and where Python is today, but it was an interesting experience all around. The test consisted of 40 questions, and each one allows you 180 seconds to choose the correct answer from five choices and click the submit button. Brainbench uses CAT (computer adaptive testing, if I have the acronym right), which means that the test gets tougher if you're doing well. That way they can provide a meaningful report of your strengths and weaknesses and avoid having to ask you 250 questions to make the determination. When taking the test, you're on the honor system. Brainbench expects that you won't have Alan Gauld feeding you answers, but it's "open book" in the sense that if you can pull it off in the time allowed for each question, you can try to find answers in reference books sitting next to you or on the web. The truth of the matter is that if you can find the answer to these questions in 180 seconds, you've got nothing to be ashamed of. A few tips for Pythonistas attempting this test: - Bookmark your module documentation and have it open in a separate browser window. - Go ahead and open your interpreter of choice. You may want to double-check your answers on a few of the questions that ask you what the output of a given code segment might be. This might not help if you're a slow typist. - Have flow control down pat. - Know the difference between exec and eval() rather well. - Understand how exceptions and tracebacks work. peace, Rob http://uselesspython.com From alex@gabuzomeu.net Fri May 10 17:55:28 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Fri, 10 May 2002 18:55:28 +0200 Subject: [Tutor] Greetings In-Reply-To: <20020510160005.6579.14599.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020510183433.00b7a620@pop3.norton.antivirus> Hi Dominic, At 12:00 10/05/2002 -0400, you wrote: >From: "dominic.fox" >Date: Thu, 9 May 2002 22:19:48 +0100 >Subject: [Tutor] Greetings >I've just joined this list, and decided to dive right in rather than lurk as >I tend to find that participation increases my enjoyment of email lists (as >well as the likelihood of my reading anything that appears in them). Welcome onboard. >Python appeals to me because, rather like Perl, it lets you wade right in >with all sorts of highly flexible and accommodating data structures - it >took about half an hour of playing with Idle for my hatred of VB collections >to crystallise into pure hard-boiled contempt. I don't know VB, but I programmed a bit in VBA (to automate stuff in MS Office, etc.). IMO, VBA is no match for Python. Python feels much more flexible and powerful. In Python, I find myself attempting tricks I wouldn't have considered in VBA (and often, they work :-) >I've got "Programming in Python" coming from Amazon. Anyone got any >suggestions for other helpful texts, especially for VB-weenies? I liked "Learning Python" (Mark Lutz and David Ascher, edited by O'Reilly). It's fairly short and to the point. As an experienced programmer, you'll race through it. Online, I like http://diveintopython.org/. It's fast-paced, but packed with useful information. Cheers. Alexandre From jeff@ccvcorp.com Fri May 10 18:14:17 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 10 May 2002 10:14:17 -0700 Subject: [Tutor] Greetings References: <001401c1f79f$3fc01c20$82c10550@tinypc> Message-ID: <3CDBFFE9.8323C140@ccvcorp.com> "dominic.fox" wrote: > I've got "Programming in Python" coming from Amazon. Anyone got any > suggestions for other helpful texts, especially for VB-weenies? You should check out "Python Programming on Win32" -- it's not so much an introduction to Python, as it is a description of the ways that Python will interact with the usual Win32 environment, including quite a bit on getting Python and VB to interact and cooperate. I strongly recommend this book to *anyone* who is doing Python on Windows -- it is loaded with useful information. Jeff Shannon Technician/Programmer Credit International From dman@dman.ddts.net Fri May 10 19:06:05 2002 From: dman@dman.ddts.net (dman) Date: Fri, 10 May 2002 13:06:05 -0500 Subject: [Tutor] toggle idiom? In-Reply-To: <3CDAA764.254DD1BB@ccvcorp.com> References: <3CD9B33E.D44E095@shaw.ca> <20020509041231.GC22335@dman.ddts.net> <3CDA1002.E476EE85@shaw.ca> <20020509141544.GB27022@dman.ddts.net> <3CDAA764.254DD1BB@ccvcorp.com> Message-ID: <20020510180605.GA9920@dman.ddts.net> --ZGiS0Q5IWpPtfppv Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, May 09, 2002 at 09:44:21AM -0700, Jeff Shannon wrote: | dman wrote: | > | Yes, unlike the a =3D not a thing the behaviour of the "psuedo-ternary | > | operator" is not specified anywhere. I'm not sure I agree about this | > | failing in the future, but ideally that's something I'd rather not ha= ve | > | to find out. :-) | > | > PEP 285 says that all the boolean operations will be changed to return | > either True or False. If the expression returns True, and True !=3D | > , then the hack doesn't work anymore. It only works | > now because python doesn't "normalize" the result to a boolean object. |=20 | In discussions on c.l.py, the PythonLabs folks did specifically say that = the | behavior of and/or won't change -- they will still return the full result= , and | not normalize to boolean. Really? A snippet of the abstract of PEP 285 : All built-in operations that conceptually return a Boolean result will be changed to return False or True instead of 0 or 1; for example, comparisons, the "not" operator, and predicates like isinstance(). I thought this meant that all the boolean operations would return one of the bool objects. Whichever it returns is only relevant for obfuscated code like the psuedo-ternary operator anyways. | I believe that the main reason for this *is* backwards | compatibility, because the and/or pseudo-trinary thing has been in | use for a long time. I finally found the quote I was looking for :-). http://mail.python.org/pipermail/python-dev/2000-January/001890.html [Tim Peters] I've never used it in a real program, and shoot people who do. | (Personally, I would never use it, as it seems unclear at best, and | downright obfuscatory at worst, but that's me.) I agree. -D --=20 If we claim we have not sinned, we make Him out to be a liar and His Word has no place in our lives. I John 1:10 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --ZGiS0Q5IWpPtfppv Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzcDA0ACgkQO8l8XBKTpRSVXgCePruxpeKCXMwhsN4CXVsiLDOB 1JgAn2A43VhqOG9z7DIaXAr8ZIDJyLHo =YKyz -----END PGP SIGNATURE----- --ZGiS0Q5IWpPtfppv-- From ATrautman@perryjudds.com Fri May 10 20:54:16 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Fri, 10 May 2002 14:54:16 -0500 Subject: [Tutor] Printer output Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A273@CORP_EXCHANGE> I am wondering if there is any documentation about formatting printed reports in Python? I need to parse, perform calculations and then produce a few summary reports and I'm wandering if there is a good template type setup to use. Thanks Alan From dman@dman.ddts.net Fri May 10 21:10:39 2002 From: dman@dman.ddts.net (dman) Date: Fri, 10 May 2002 15:10:39 -0500 Subject: [Tutor] Printer output In-Reply-To: <75EDF89FDE81D511840D00A0C9AD25DD0261A273@CORP_EXCHANGE> References: <75EDF89FDE81D511840D00A0C9AD25DD0261A273@CORP_EXCHANGE> Message-ID: <20020510201039.GA11437@dman.ddts.net> --SUOF0GtieIMvvwua Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, May 10, 2002 at 02:54:16PM -0500, Alan Trautman wrote: | I am wondering if there is any documentation about formatting printed | reports in Python? I need to parse, perform calculations and then produce= a | few summary reports and I'm wondering if there is a good template type se= tup | to use. man printf or is that not what you mean by "print"? Python has built-in support for string formatting with the same rules as C's printf family of functions. With it you can align columns and format numbers, etc. As for outputing formatted data, the options really depend on what the communication medium is. There are template systems for web (html) stuff, it isn't too hard to generate some LaTeX as long as you know the tables won't have any page breaks in them. HTH, -D --=20 How to shoot yourself in the foot with Java: You find that Microsoft and Sun have released incompatible class libraries both implementing Gun objects. You then find that although there are plenty of feet objects implemented in the past in many other languages, you cannot get access to one. But seeing as Java is so cool, you don't care and go around shooting anything else you can find. (written by Mark Hammond) =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --SUOF0GtieIMvvwua Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzcKT8ACgkQO8l8XBKTpRRkkwCfbLnh0/S5Q2fHgGqO3GLbF2kb qDkAnAzod3pURv5YQHrfPpytiAZp7hfK =9LzF -----END PGP SIGNATURE----- --SUOF0GtieIMvvwua-- From kojo@hal-pc.org Fri May 10 21:26:28 2002 From: kojo@hal-pc.org (Kojo Idrissa) Date: Fri, 10 May 2002 15:26:28 -0500 Subject: [Tutor] Python 2.1 vs 2.2? Message-ID: <5.1.0.14.0.20020510152023.00ad50c0@mail.hal-pc.org> I'm "re-doing" stuff on my computer (new HD, blah, blah), so I'm downloading some stuff again. Can someone remind me of the major diffs between 2.1 and 2.2? Specifically 2.1.3 and 2.2.1. I'm planing to get the ActiveState stuff for my Win2K partiion. Is the 2.1.x branch the stable one, while 2.2.x is more "under development"? Any real functional diffs? I'm still using "Learning Python", "Programming Python for Win32" and a couple of other 1.5.2 books, so I doubt I'm advanced enough to really notice. I scanned A. Kuchling's "What's New in 2.2", but I just wanted to make sure I'm getting the "best" thing. Thanks, **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** From rob@uselesspython.com Fri May 10 21:37:34 2002 From: rob@uselesspython.com (Rob Andrews) Date: Fri, 10 May 2002 15:37:34 -0500 Subject: [Tutor] Python 2.1 vs 2.2? References: <5.1.0.14.0.20020510152023.00ad50c0@mail.hal-pc.org> Message-ID: <3CDC2F8E.10109@uselesspython.com> I'll defer to more authoritative speakers on the specific differences, but 2.2.1 is pretty darn stable in my experience. Rob http://uselesspython.com Kojo Idrissa wrote: > I'm "re-doing" stuff on my computer (new HD, blah, blah), so I'm > downloading some stuff again. > > Can someone remind me of the major diffs between 2.1 and 2.2? > Specifically 2.1.3 and 2.2.1. I'm planing to get the ActiveState stuff > for my Win2K partiion. > > Is the 2.1.x branch the stable one, while 2.2.x is more "under > development"? Any real functional diffs? I'm still using "Learning > Python", "Programming Python for Win32" and a couple of other 1.5.2 > books, so I doubt I'm advanced enough to really notice. > > I scanned A. Kuchling's "What's New in 2.2", but I just wanted to make > sure I'm getting the "best" thing. > > Thanks, > > **************************** > Kojo Idrissa > > kojo@hal-pc.org > http://www.hal-pc.org/~kojo/ > **************************** > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dominic.fox" Sorry, this was meant for the list - apologies to Alexandre, who will now have received it twice... > Alexandre wrote: > > > > I don't know VB, but I programmed a bit in VBA (to automate stuff in MS > > Office, etc.). IMO, VBA is no match for Python. Python feels much more > > flexible and powerful. In Python, I find myself attempting tricks I > > wouldn't have considered in VBA (and often, they work :-) > > If you work in an office full of people doing routine and highly automatable > tasks using MS Office software, then VB/A is your friend and, possibly, > theirs (job security might be an issue...). MS Excel is particularly > friendly about exposing its functionality for automation; you can write some > reasonably useful applications in Excel VBA without immense amounts of pain, > provided your head doesn't keep bumping on the ceiling of the VB > reality-tunnel. In _Code Complete_, which I've also been reading recently, > Steve McConnell supplies a good line about coding *into* a language, rather > than *in* a language. VB's all right if it's not the only thing you know, > although if you do know anything else it's only a matter of time before you > start resenting some of the shackles VB places on you. > > I gather there's a Python module which provides support for interfacing with > COM (MS's Component Object Model, which is what lets you write some code in > Word VBA to send a message in Outlook attaching a spreadsheet you build in > Excel out of some data you retrieved from Access), however. If I can > persuade COM objects to do the bidding of Python modules, then there will be > much rejoicing... > > Dominic > From ccampbell@ede.org Fri May 10 22:33:26 2002 From: ccampbell@ede.org (Colin Campbell) Date: Fri, 10 May 2002 15:33:26 -0600 Subject: [Tutor] Calling external DLLs from Python Message-ID: <5.1.0.14.0.20020510150427.00adf888@139.142.50.99> I've written a bit of Python to convert a LDIF file into Eudora's address book format (the company uses Netscape, which I find too unstable, and our IT staff are forgiving about my rebel tendencies). I've got the routine running reasonably well, using PythonWin so that I can browse for source and output files, but I would like to be able to read a .NA2 file directly. I think I need to be able to call NABAPI.dll from inside Python, but I need some kind soul to tell me whether this is even possible, and then second to point me in the direction of some documentation/sample source code/newsgroup archive. I've got the Address Book API from http://developer.netscape.com/docs/manuals/communicator/addrapi.htm and just need a pointer to the next step. TIA Colin Windows 2KSP2 Python 2.2 PyhtonWin -- Simplicity doesn't mean to live in misery and poverty. You have what you need, and you don't want to have what you don't need. -Charan Singh, mystic (1916-1990) From paulsid@shaw.ca Fri May 10 22:59:19 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Fri, 10 May 2002 15:59:19 -0600 Subject: [Tutor] Python 2.1 vs 2.2? References: <5.1.0.14.0.20020510152023.00ad50c0@mail.hal-pc.org> Message-ID: <3CDC42B7.FDC978B0@shaw.ca> Kojo Idrissa wrote: > Can someone remind me of the major diffs between 2.1 and 2.2? Specifically > 2.1.3 and 2.2.1. I'm planing to get the ActiveState stuff for my Win2K > partiion. Generators, better type-class integration, nested scoping as default, etc. There's not really much that's not covered in the What's New doc. I'm not familiar with ActivePython, though. It could have other differences that need to be considered, but I doubt it. > Is the 2.1.x branch the stable one, while 2.2.x is more "under > development"? Any real functional diffs? I'm still using "Learning > Python", "Programming Python for Win32" and a couple of other 1.5.2 books, > so I doubt I'm advanced enough to really notice. 2.1 is only more stable in that it's on the 3rd bugfix release while 2.2 has so far had just one, but that's minor. "Unstable" versions of Python are alpha, beta, and candidate releases and have an a, b, or c after their numbers, respectively. (2.3a1 is due out in less than 2 weeks.) > I scanned A. Kuchling's "What's New in 2.2", but I just wanted to make sure > I'm getting the "best" thing. Unless you have to maintain strict compatibility with 2.1 and can't afford to risk a major version change, get 2.2.1. More generally, always get the latest version of Python unless you have a good reason not to. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From jeff@ccvcorp.com Fri May 10 23:12:42 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 10 May 2002 15:12:42 -0700 Subject: Fw: [Tutor] Greetings References: <003c01c1f869$fb02be00$82c10550@tinypc> Message-ID: <3CDC45D9.40234E29@ccvcorp.com> "dominic.fox" wrote: > > > I gather there's a Python module which provides support for interfacing > with > > COM (MS's Component Object Model, which is what lets you write some code > in > > Word VBA to send a message in Outlook attaching a spreadsheet you build in > > Excel out of some data you retrieved from Access), however. If I can > > persuade COM objects to do the bidding of Python modules, then there will > be > > much rejoicing... Yes, the PythonCOM framework (part of Mark Hammond's win32all extensions, which are also bundled with ActiveState's ActivePython distribution) allows you to use any COM objects that support automation (the IDispatch interface) -- pretty much the same set of COM objects that are usable from VB. This includes, among *many* others, all of the MS Office components. Again, all of this is covered in the book, Python Programming on Win32, complete with example code. Jeff Shannon Technician/Programmer Credit International From erikprice@mac.com Fri May 10 23:20:23 2002 From: erikprice@mac.com (Erik Price) Date: Fri, 10 May 2002 18:20:23 -0400 Subject: [Tutor] Brainbench Python 1.5 Certification In-Reply-To: <3CDBDD7F.30106@uselesspython.com> Message-ID: <1ED7A41C-6464-11D6-8DBF-00039351FE6A@mac.com> On Friday, May 10, 2002, at 10:47 AM, Rob Andrews wrote: > I've never run across anyone commenting on the Python 1.5 Certification > that brainbench.com offers. And since I have a Brainbench subscription, > I figured I'd take a break from working on the new Useless Python site > (about half-way done, BTW, if not better) and give it a stab. > > Until someone else comes up with a Python certification, this is the > only one I know of. It's a bit dated, since a few things changed > between 1.5 and where Python is today, but it was an interesting > experience all around. I've heard of certification tests for Java and C, but not for Python. Being relatively new to the language (and to programming), it's not something I'm considering anytime soon. But I'm curious: what kind of skills are assessed in such a test? What sorts of things are considered valuable to test-creators? (Python, Java, whatever.) Btw, I ask this in all sincerity and am temporarily suspending my distrust of standardized tests -- I'm not trying to play devil's advocate or anything. Erik From python@rcn.com Sat May 11 02:43:39 2002 From: python@rcn.com (Raymond Hettinger) Date: Fri, 10 May 2002 21:43:39 -0400 Subject: [Tutor] Brainbench Python 1.5 Certification References: <1ED7A41C-6464-11D6-8DBF-00039351FE6A@mac.com> Message-ID: <001801c1f88d$474891e0$6de97ad1@othello> > I've heard of certification tests for Java and C, but not for Python. > Being relatively new to the language (and to programming), it's not > something I'm considering anytime soon. But I'm curious: what kind of > skills are assessed in such a test? What sorts of things are considered > valuable to test-creators? (Python, Java, whatever.) The test creators value: -- complete knowledge of the tutorial, all basic objects, methods, operators, etc -- some knowledge of the most commonly used modules in the library -- a few standard idioms and the most common pitfalls Employers would value, but testers have a hard time testing: -- ability to write a program to solve a problem -- ability to find an error in a program with a bug > Btw, I ask this in all sincerity and am temporarily suspending my > distrust of standardized tests -- I'm not trying to play devil's > advocate or anything. In this case, you should not suspend your distrust. The author of the test thinks it is seriously flawed because of Brainbench's test constraints: http://groups.google.com/groups?hl=en&th=fd6cd5dc680aceab&rnum=1 Raymond Hettinger From rob@uselesspython.com Sat May 11 03:55:49 2002 From: rob@uselesspython.com (Rob Andrews) Date: Fri, 10 May 2002 21:55:49 -0500 Subject: [Tutor] Brainbench Python 1.5 Certification References: <1ED7A41C-6464-11D6-8DBF-00039351FE6A@mac.com> <001801c1f88d$474891e0$6de97ad1@othello> Message-ID: <3CDC8835.3030803@uselesspython.com> Tests like the one under discussion can be valuable and/or interesting in a number of ways. Personally, I think the primary value of such a test is not its use as an assessment tool, but as material to engage the student to further thought on the subject. I actually hope to put together one or more tests that people can take through the Useless Python website, although the plan isn't to charge $$$ and provide credentials in return. The idea is still a mostly in pre-development and somewhat vague, really. But I think that having a few quizzes to test knowledge of basic facts may prove a valuable addition to the site. And at a planned cost of $0.00, I don't expect anyone to feel abused. 3;-> Brainbench now charges about $50(USD) for the Python 1.5 certification, and so I wouldn't likely have taken the test myself if I didn't have a subscription that allows me to take as many of their tests as I please. I can, however, say that I found the test to be a very successful way to clarify quite a few gaps and cracks in my Python knowledge. I find the test author's remarks regarding the test to be quite interesting. But I also note that of course he knows about the test's flaws and how he would want it to be better. It's still good, whether or not it's worth $50.00. A good exercise for someone learning the language, IMO, is to try to collect your own list of questions that you think would be good test questions. (In fact, that just might make a good Useless Python Challenge. A whole section could be set aside just to display people's lists of questions and/or proposed answers.) Rob Raymond Hettinger wrote: >>I've heard of certification tests for Java and C, but not for Python. >>Being relatively new to the language (and to programming), it's not >>something I'm considering anytime soon. But I'm curious: what kind of >>skills are assessed in such a test? What sorts of things are considered >>valuable to test-creators? (Python, Java, whatever.) >> > > The test creators value: > -- complete knowledge of the tutorial, all basic objects, methods, > operators, etc > -- some knowledge of the most commonly used modules in the library > -- a few standard idioms and the most common pitfalls > > Employers would value, but testers have a hard time testing: > -- ability to write a program to solve a problem > -- ability to find an error in a program with a bug > > >>Btw, I ask this in all sincerity and am temporarily suspending my >>distrust of standardized tests -- I'm not trying to play devil's >>advocate or anything. >> > > In this case, you should not suspend your distrust. The author of the > test thinks it is seriously flawed because of Brainbench's test constraints: > http://groups.google.com/groups?hl=en&th=fd6cd5dc680aceab&rnum=1 > > > Raymond Hettinger > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From dman@dman.ddts.net Sat May 11 05:52:49 2002 From: dman@dman.ddts.net (dman) Date: Fri, 10 May 2002 23:52:49 -0500 Subject: [Tutor] Brainbench Python 1.5 Certification In-Reply-To: <1ED7A41C-6464-11D6-8DBF-00039351FE6A@mac.com> References: <3CDBDD7F.30106@uselesspython.com> <1ED7A41C-6464-11D6-8DBF-00039351FE6A@mac.com> Message-ID: <20020511045249.GA1097@dman.ddts.net> --C7zPtVaVf+AK4Oqc Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, May 10, 2002 at 06:20:23PM -0400, Erik Price wrote: | On Friday, May 10, 2002, at 10:47 AM, Rob Andrews wrote: |=20 | >I've never run across anyone commenting on the Python 1.5 Certification= =20 | >that brainbench.com offers. And since I have a Brainbench subscription,= =20 | >I figured I'd take a break from working on the new Useless Python site= =20 | >(about half-way done, BTW, if not better) and give it a stab. | > | >Until someone else comes up with a Python certification, this is the=20 | >only one I know of. It's a bit dated, since a few things changed=20 | >between 1.5 and where Python is today, but it was an interesting=20 | >experience all around. |=20 | I've heard of certification tests for Java and C, but not for Python. =20 | Being relatively new to the language (and to programming), it's not=20 | something I'm considering anytime soon. But I'm curious: what kind of=20 | skills are assessed in such a test? What sorts of things are considered= =20 | valuable to test-creators? (Python, Java, whatever.) I took a sample java certification test once. It's supposed to be representative of the real test and useful for practicing. I just barely failed. (all closed-book too) Many of the questions were not terribly useful. For example, I didn't know that a numeric literal with a decimal piont is a *double*, and thus must be cast in order to assign it to a float. (I got that question wrong) My java work just didn't deal with floats or doubles because I wasn't doing number crunching. That sort of error is immediately learned from the compiler. Another question required detailed knowledge of how the paint() method of an AWT component worked. I don't write AWT (or Swing) components, I just use them. Some of the questions were trivial, some were just plain tricky. Some of them required tracing badly-formated code (the kind of code that a prof. would not accept). Those questions were rather like some test questions from a certain prof. at RIT. It was an interesting test, and interesting to see what I got right and what I got wrong. In fact, it was my boss who asked all of us to take the test just to see how we would do. He even had an applicant for a co-op position take it too, but didn't really count it in deciding whether or not to hire him. I certainly wouldn't spend any money to have someone else print a piece of paper saying that I passed that test. | Btw, I ask this in all sincerity and am temporarily suspending my=20 | distrust of standardized tests -- I'm not trying to play devil's=20 | advocate or anything. My opinion is that certification is not very valuable. Either you know what you're doing, in which case what does a piece of paper mean, or you don't, in which case I don't care about that paper. I've heard some stories about some MCSEs compared to a certain person who dropped out of college (and majored in EE anyways). It is certainly useful to obtain quality training from knowledgable people, but "certifications" are only as worthwhile and you (and everyone else who looks at the label) thinks it is. -D --=20 How great is the love the Father has lavished on us, that we should be called children of God! 1 John 3:1=20 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --C7zPtVaVf+AK4Oqc Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzco6EACgkQO8l8XBKTpRRSRwCgu3MdOgGg6eFEKimN+U4nuT+K KGIAoID7GWuCgQ7kViVx8j9zDYQPyaP1 =GxJy -----END PGP SIGNATURE----- --C7zPtVaVf+AK4Oqc-- From dman@dman.ddts.net Sat May 11 05:59:09 2002 From: dman@dman.ddts.net (dman) Date: Fri, 10 May 2002 23:59:09 -0500 Subject: [Tutor] Calling external DLLs from Python In-Reply-To: <5.1.0.14.0.20020510150427.00adf888@139.142.50.99> References: <5.1.0.14.0.20020510150427.00adf888@139.142.50.99> Message-ID: <20020511045909.GB1097@dman.ddts.net> --4bRzO86E/ozDv8r1 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, May 10, 2002 at 03:33:26PM -0600, Colin Campbell wrote: | I've written a bit of Python to convert a LDIF file into Eudora's address= =20 | book format (the company uses Netscape, which I find too unstable, and ou= r=20 | IT staff are forgiving about my rebel tendencies). |=20 | I've got the routine running reasonably well, using PythonWin so that I c= an=20 | browse for source and output files, but I would like to be able to read a= =20 | .NA2 file directly. I think I need to be able to call NABAPI.dll from=20 | inside Python, but I need some kind soul to tell me whether this is even= =20 | possible, and then second to point me in the direction of some=20 | documentation/sample source code/newsgroup archive. I've got the Address= =20 | Book API from=20 | http://developer.netscape.com/docs/manuals/communicator/addrapi.htm and= =20 | just need a pointer to the next step. I've only briefly looked over that document, and it won't be simple to use the library. If they had a COM interface it would be, but ... It will require o getting the header files (C++) o getting a win32 C++ compiler o getting the header files for python o writing C/C++ code to provide a python wrapper for the library's interface Once you've done that you can use your shiny new PyNABAPI module from python to pilot that library. -D --=20 One man gives freely, yet gains even more; another withholds unduly, but comes to poverty. Proverbs 11:24 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --4bRzO86E/ozDv8r1 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzcpR0ACgkQO8l8XBKTpRSSqQCeIRnbOKQZnbwg2KUR148mgWFG KtIAnRJkncPCLqRMSrb/9vRywcLyWLC5 =lWXb -----END PGP SIGNATURE----- --4bRzO86E/ozDv8r1-- From rab121@york.ac.uk Sat May 11 16:59:03 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Sat, 11 May 2002 16:59:03 +0100 Subject: [Tutor] GoFish Message-ID: <3CDD3FC7.9128D493@york.ac.uk> Hello, I have just finished my first pretty much working pythonised version of a little card game I like. I would be very much appreciative if the mighty minds of this list could cast their eyes over it and make any suggestions. If you don't mind, I shall use this email to explain about the game itself (I don't think it is too well known and will need explaining so you know what should happen), I shall reply with the code, and then reply to the code with own comments on it. GoFish then. It should be quite familiar to anyone who has played Happy Families or the like. Each person is dealt a hand, and the aim of the game os to get rid of all your cards as swiftly as possible. You accomplish this by collecting all four of a rank (a book) which you can then declare in front of you on display. The first person asks any other for a single card of a particulr rank. The second player must hand over the card if they have it, in which the starting player continues, or if they don't have if, they say 'Go Fish' and the first player fishes one of the undealt cards. Play then continues with the second player, and so on. The first player to have no cards (either through declareing books or another player taking all their cards) is the winner. That is pretty much it. Thankyou very very much for your time, Russell -- http://www.bigmaddrongo.com President of York University Trampoline Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From rab121@york.ac.uk Sat May 11 17:06:36 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Sat, 11 May 2002 17:06:36 +0100 Subject: [Tutor] GoFish References: <3CDD3FC7.9128D493@york.ac.uk> Message-ID: <3CDD418C.E5B003A9@york.ac.uk> Hello Again, As promised here is my code. It is arranged in four modules: gofish.py: the main program module cards.py: the module defining a pack of cards class players.py: the module defining the player classes for humans and AI players bmdutils.py: my general purpose module for useful functions (only the used code is included) I believe I have used code that will only work under Python 2.2. There is also a very little windows specific code (os.system('cls')). # #gofish.py # import bmdutils,cards,ConfigParser,os,os.path,players,sys gofishdir = os.path.dirname(players.__file__) # Get directory of module class GoFish: def __init__(self): self.fishers = {} self.deck =[] self.out = [] if not os.path.exists(gofishdir + '\\gofishini'): self.createini() gofishinifile = open(gofishdir + '\\gofishini', 'rw') self.ini = ConfigParser.ConfigParser() self.ini.readfp(gofishinifile) else: gofishinifile = open(gofishdir + '\\gofishini', 'rw') self.ini = ConfigParser.ConfigParser() self.ini.readfp(gofishinifile) bmdutils.bmdmenu([['1. Start a New game', self.new, ['1','n','N']],['2. Edit your Preferences', self.pref, ['2','p','P']], ['3. Quit this program', self.quit, ['3','q','Q']]]) def new(self): default = 'Default Options:\n' for a in range(self.ini.getint('default','ai')): # Create string showing default options default = default + self.ini.get('ai', str(a + 1)) + ' (' + self.ini.get('ai' , 'levels')[a] + ') ' bmdutils.bmdmenu([['1. Start with Default options', self.create, ['1','d','D']],['2. Start with New options', self.createopt, ['2','n','N']],[default,None,[]]]) # Third option prints default options with no possible selection def create(self, options=None): hum = 0 if not options: options = [] for opt in range(self.ini.getint('default','ai')): options.append([self.ini.get('ai','levels')[opt],self.ini.get('ai', str(opt + 1))]) if self.ini.getint('default', 'human') != 0: options.append([0,self.ini.get('default', 'name')]) for p in range(len(options)): if options[p][0] == 0: self.fishers[p] = players.Human(options[p][1]) hum = p else: level = 'AI' + str(options[p][0]) self.fishers[p] = eval('players.' + level + '(options[p][1])') newcards = cards.bmdcard() hands = newcards.deal(hands=[[len(self.fishers),self.ini.getint('default','cards')]], shuffles=self.ini.getint('prefs','shuffles')) for k in range(len(self.fishers)): for c in hands[k]: self.fishers[self.fishers.keys()[k]].receivecard(c) hands= hands[-1:] self.deck = hands[0] os.system('cls') self.mainloop(1,hum) def createopt(self): print 'opt' def mainloop(self,start,human): fish = start num = len(self.fishers) while len(self.fishers[human].hand) > 0: if fish not in self.out: fish = self.turn(fish,human) elif len(self.out) == len(self.fishers) - 1: print 'cheese' else: for f in self.fishers: if f not in self.out: fish = f fish = self.turn(fish,human) for p in self.fishers: if len(self.fishers[p].hand) == 0 and p not in self.out: print 'Well done ' + self.fishers[p].name + ' you finished in place number ' + str(len(self.out) + 1) self.out.append(p) raw_input() self.quit() def turn(self, fish, human): interface = 'You have: ' for card in self.fishers[human].hand: interface += self.numtocard(card) + ' ' interface += '\n' interface += 'You have declared: ' for rank in self.fishers[human].declared: interface += str(rank + 1) + ' ' interface += '\n\n' for player in self.fishers: if self.fishers[player] != self.fishers[human]: interface += self.fishers[player].name + ' has ' + str(len(self.fishers[player].hand)) + ' cards remaining, and has declared: ' for rank in self.fishers[player].declared: interface += str(rank + 1) + ' ' interface += '\n' interface += '\nThere are ' + str(len(self.deck)) + ' cards in the deck. \n' if fish != human: print interface #for t in self.fishers: # print self.fishers[t].name, self.fishers[t].hand play = 0,fish while play[1] == fish or play[1] in self.out: play = self.fishers[fish].askcard(len(self.fishers)) print self.fishers[fish].name + ' has asked ' + self.fishers[play[1]].name + ' for a ' + str(play[0] + 1) for p in (play[0]*4, play[0]*4 + 1, play[0]*4 + 2, play[0]*4 + 3): if p in self.fishers[play[1]].hand: print self.fishers[play[1]].name + ' has given ' + self.fishers[fish].name + ' a ' + str(play[0] + 1) self.fishers[fish].receivecard(p) self.fishers[play[1]].removecard(p) for player in self.fishers: if 'update' in dir(player): player.update() raw_input() os.system('cls') return fish if len(self.deck) != 0: self.fishers[fish].receivecard(self.deck[0]) self.deck = self.deck[1:] print 'GO FISH' raw_input() os.system('cls') return play[1] else: interface += '\nAsk for a card from:' for player in self.fishers: interface += '\n' if self.fishers[player] != self.fishers[human]: interface += str(player + 1) + '. ' + self.fishers[player].name + ' ' interface += '\nDeclare a rank.\n' interface += 'Quit the game.\n' print interface choice = '' choices = ['d','D','q','Q'] for i in range(len(self.fishers) - 1): choices.append(str(i + 1)) while choice not in choices: choice = raw_input('Please choose an option: ') if choice == 'd' or choice == 'D': print declare elif choice == 'q' or choice == 'Q': if raw_input('Are you sure? y/n') == 'y' or raw_input('Are you sure? y/n') == 'Y': self.quit() else: askfor = int(raw_input('Which rank do you wish to ask for?')) - 1 for a in (askfor*4, askfor*4 + 1, askfor*4 + 2, askfor*4 + 3): if a in self.fishers[int(choice) - 1].hand: print self.fishers[int(choice) - 1].name + ' has given you a ' + str(askfor + 1) self.fishers[fish].receivecard(a) self.fishers[int(choice) - 1].removecard(a) for player in self.fishers: if 'update' in dir(player): player.update() raw_input() os.system('cls') return fish if len(self.deck) != 0: self.fishers[fish].receivecard(self.deck[0]) self.deck = self.deck[1:] print 'GO FISH' raw_input() os.system('cls') return int(choice) - 1 def pref(self): print 'pref' def quit(self): sys.exit() def createini(self): gofishinifile = open(gofishdir + '\\gofishini', 'w') self.ini = ConfigParser.ConfigParser() self.ini.add_section('prefs') self.ini.set('prefs', 'sort', 0) self.ini.set('prefs', 'disp_actions', 1) self.ini.set('prefs', 'auto_dec', 0) self.ini.set('prefs', 'shuffles', 10) self.ini.add_section('default') self.ini.set('default', 'ai', 3) self.ini.set('default', 'human', 1) self.ini.set('default', 'name', 'Player') self.ini.set('default', 'cards', 7) self.ini.add_section('ai') self.ini.set('ai','levels','11111111') names = {1: 'Amy', 2: 'Theresa', 3:'Russell', 4:'Matthew', 5:'Richard', 6:'Susannah', 7:'Julia', 8:'John'} for num in names.keys(): self.ini.set('ai',str(num),names[num]) self.ini.write(gofishinifile) gofishinifile.close() def numtocard(self,num): if num % 4 == 0: return str(num/4 + 1) + 'S' elif (num - 1) % 4 == 0 : return str((num - 1)/4 + 1) + 'H' elif (num - 2) % 4 == 0 : return str((num - 2)/4 + 1) + 'D' elif (num - 3) % 4 == 0 : return str((num - 3)/4 + 1) + 'C' if __name__ == '__main__': newfish = GoFish() # #cards.py # class bmdcard: def __init__(self, size=52, comp=None): self.cards = [] self.deck = [] for c in range(size): self.deck.append(c) self.cards = self.deck def deal(self, hands=[[4,7]], shuffles=3): for s in range(shuffles): self.shuffle() dealt=[] for h in hands: for i in range(hands[hands.index(h)][0]): dealt.append(self.cards[:hands[hands.index(h)][1]]) self.cards = self.cards[hands[hands.index(h)][1]:] dealt.append(self.cards) self.cards=self.deck return dealt def shuffle(self): """Orignal code by Bruce Sass, as provided on Python Tutor Mailing list""" import random half = len(self.cards)/2 part1 = self.cards[:half] part2 = self.cards[half:] shuffled = [] mingrp = 1 maxgrp = 4 while part1 or part2: if part1: for i in range(random.randrange(mingrp, 1 + min(maxgrp, len(part1)))): shuffled.append(part1.pop()) if part2: for i in range(random.randrange(mingrp, 1 + min(maxgrp, len(part2)))): shuffled.append(part2.pop()) self.cards = shuffled # #players.py # import random class Player: def __init__(self,name): self.hand = [] self.count = [0]*13 self.name = name self.declared = [] def removecard(self,card): self.hand.remove(card) self.count[card/4] += -1 def receivecard(self,card): self.hand.append(card) self.count[card/4] += 1 self.bookcheck() def declare(self, rank): self.declared.append(rank) for c in (rank*4,rank*4 + 1,rank*4 + 2,rank*4 + 3): self.removecard(c) self.count[rank] = 0 def bookcheck(self): if max(self.count) == 4: self.declare(self.count.index(4)) class Human(Player): def cheese(self): print 'cheese' class AI1(Player): def askcard(self, players): return self.count.index(max(self.count)), random.randrange(0, players) # #bmdutils.py - part of # def bmdmenu(options, prompt='Please select an option:'): choice = '' choices = {} for o in options: print o[0] for p in o[2]: choices[p] = o[1] while choice not in choices.keys(): choice = raw_input(prompt) choices[choice]() # #end # Thankyou very much, Russell -- http://www.bigmaddrongo.com President of York University Trampoline Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From shalehperry@attbi.com Sat May 11 17:06:50 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat, 11 May 2002 09:06:50 -0700 (PDT) Subject: [Tutor] GoFish In-Reply-To: <3CDD3FC7.9128D493@york.ac.uk> Message-ID: On 11-May-2002 Russell Bungay wrote: > Hello, > > I have just finished my first pretty much working pythonised version of > a little card game I like. I would be very much appreciative if the > mighty minds of this list could cast their eyes over it and make any > suggestions. > um, so where is? (-: From rab121@york.ac.uk Sat May 11 17:08:46 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Sat, 11 May 2002 17:08:46 +0100 Subject: [Tutor] GoFish References: <3CDD3FC7.9128D493@york.ac.uk> <3CDD418C.E5B003A9@york.ac.uk> Message-ID: <3CDD420E.B834EAA8@york.ac.uk> Hello Again, As promised here are my comments on my code. General: Validation - there is none, it is very easy to break the script by entering false values in any number of places. Features - lots of unimplemented features, some already have anchors in code, I'll point them out. Commenting - poor and lacking, no doc strings. ># >#gofish.py ># class GoFish: > def create(self, options=None): > else: > level = 'AI' + str(options[p][0]) > self.fishers[p] = eval('players.' + level + '(options[p][1])') This will let me slip in extra (planned) AI levels at a later date by simply subclassing further in players.py. Is there a nicer way than using eval? I don't like it much, not sure why, it just seems wrong. > os.system('cls') Needs rewriting for portability. > def createopt(self): > > print 'opt' When implemented, this will allow the starting of a game from options gained from inquisiting. > def mainloop(self,start,human): > > fish = start > num = len(self.fishers) > > while len(self.fishers[human].hand) > 0: > > if fish not in self.out: > fish = self.turn(fish,human) > elif len(self.out) == len(self.fishers) - 1: > print 'cheese' > else: > for f in self.fishers: > if f not in self.out: > fish = f > fish = self.turn(fish,human) > > for p in self.fishers: > if len(self.fishers[p].hand) == 0 and p not in self.out: > print 'Well done ' + self.fishers[p].name + ' you finished in place number ' + str(len(self.out) + 1) > self.out.append(p) > > raw_input() > self.quit() The whole checking for game finishing seems a bit of a fudge to me, but I just couldn't think of a more elagant way of coding it... > def turn(self, fish, human): > for player in self.fishers: > if 'update' in dir(player): > player.update() This is for unimplemented higher AI levels which will track where cards are. > def pref(self): > > print 'pref' Will allow easy access to preference in settings file. > def quit(self): > > sys.exit() Is this the best/cleanest way to quit a script? I can find no other... Thankyou very much, Russell -- http://www.bigmaddrongo.com President of York University Trampoline Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From rab121@york.ac.uk Sat May 11 17:17:05 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Sat, 11 May 2002 17:17:05 +0100 Subject: [Tutor] GoFish References: <3CDD3FC7.9128D493@york.ac.uk> <3CDD418C.E5B003A9@york.ac.uk> Message-ID: <3CDD4401.CB66DBC0@york.ac.uk> Russell Bungay wrote: >As promised here is my code. It is arranged in four modules: >gofish.py: the main program module >cards.py: the module defining a pack of cards class >players.py: the module defining the player classes for humans and >AI players >bmdutils.py: my general purpose module for useful functions (only >the used code is included) The four modules can also be found at: http://www-users.york.ac.uk/~rab121/comp/prog/gofish/gofish.py http://www-users.york.ac.uk/~rab121/comp/prog/gofish/cards.py http://www-users.york.ac.uk/~rab121/comp/prog/gofish/players.py http://www-users.york.ac.uk/~rab121/comp/prog/gofish/bmdutils.py Russell -- http://www.bigmaddrongo.com President of York University Trampoline Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From printers@sendme.cz Sat May 11 19:25:20 2002 From: printers@sendme.cz (A) Date: Sat, 11 May 2002 20:25:20 +0200 Subject: [Tutor] Numbers of active threads Message-ID: <3CDD7E30.4391.BC376@localhost> Hi, I use threading module and I need to control numbers of active threads. Can you please give me an example how to do that. Thank you Ladislav From l8tr2000@yahoo.com Sun May 12 09:18:51 2002 From: l8tr2000@yahoo.com (Steve) Date: Sun, 12 May 2002 01:18:51 -0700 (PDT) Subject: [Tutor] help =) Message-ID: <20020512081851.85956.qmail@web10706.mail.yahoo.com> Lo all, I'm trying to learn python and just get this code to connect and perhaps send a few lines to the server. I've been having troubles figuring out a few things. First off if I want a variable to be shared between classes, and i've made the child class extend the parent, where do I place my multiclass variables? If I put then in the __init__ of the parent class and don't call the class directly it seems as if that method isn't called? I'm also not sure how instantiation works between classes, in my test function below don't I instanciate the class with my assignment to c? and when I open a socket doesn't sock instaciate the call? I'm also unsure about all the selfs I seem to be unsure as to when I need to call the class.method, self.method etc... any help would be greately appreciated. Seems the latest error I was getting was: AttributeError: ircConnect instance has no attribute 'send' This I also don't understand considering I import socket at the top of the file so I figured self.send would be a method of the socket class but apparently its not working either. I'm reading all I can and slowly moving up the learning curver sorry for the bother. #!/usr/bin/python import sys, time from select import select from socket import socket, AF_INET, SOCK_STREAM class selectSocket: def __init__(self): self.rxd = '' self.sent = '' def connServer(self, host, port): readsocks, writesocks = [], [] self.sock = socket(AF_INET, SOCK_STREAM) self.sock.connect((host, port)) readsocks.append(self.sock) writesocks.append(self.sock) def selectLoop(self): print 'select-server loop starting' while 1: r, w, e = select(readsocks, writesocks, []) for sockobj in r: self.rxd = sockobj.recv(1024) print 'DEBUG::', self.rxd, 'on', id(sockobj) if not self.rxd: # if closed by the clients sockobj.close() # close here and remove r.remove(sockobj) # else reselected for sockobj in w: if newConn == 1: pass else: pass time.sleep(.5) class ircConnect(selectSocket): def __init__(self): pass def connIRC(self, host, port, chan, nick, name): self.connServer(host, port) self.ircReg(nick, name) self.joinChan(self, chan) def ircReg(self, nick, name): self.send('NICK', nick) self.send('USER', nick, '+iw', name) self.send('PONG\n') def joinChan(self, chan): self.send('JOIN', chan) def test(host, port, chan, nick, name): c = ircConnect() c.connIRC(host, port, chan, nick, name) c.selectLoop() if __name__=='__main__': test('irc.openprojects.net', 6667, '#nix', 'testmoe', "testmoe neener") __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com From scot@possum.in-berlin.de Sun May 12 01:52:25 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Sun, 12 May 2002 02:52:25 +0200 Subject: [Tutor] Getting rid of global variables, reprise In-Reply-To: <3CD8EE0A.FBFCB8E8@shaw.ca> References: <200205071454.g47EsER01890@possum.cozen.org> <3CD8EE0A.FBFCB8E8@shaw.ca> Message-ID: <200205120146.g4C1k1mL006490@charmor.internal.use> Hi there, A while ago I had posted a question here about a Tkinter version of a program that I was attempting to write that lets you take mail out of a mailbox, modify it in various ways, and save it to a file. I had already written a text-only version with lots of global variables, and the idea was to get rid of those while getting more Tkinter time unter my belt. Last mail, I was having some problems with the concept of how to proceed, which led to a rather vague question, that some of you still valiantly tried to answer - thank you! Having figured out what my problem was, maybe the solution can be helpful to other people learning to program: Basically, I was still too stuck in a non-object mode of looking at programs. More specifically, I was having trouble with the concept of the constructor (or whatever you formally call the def __init__(self): part) creating a full fledged object that contains the code. I was thinking in terms of code /here/ and data /here/, instead of realizing that when you create an object, it contains not only the data but also the program logic to play around with that data. The moment when I realized how much fun this object stuff came when I wrote "return self" for the first time =8). More specifically, I ended up with three classes. One is the GUI object that builds the Tkinter interface in the constructor, has an instance created with the usual "if __name__ == "__main__": trick, and lets you load a mailbox file. When you read one mail out of this file, it creates an instance of the second class, a single message. The methods in the GUI object do little more than forward the method to the equivalent method in the mailbox file; the idea here is to keep the logic and the GUI separate so that I can do a Qt version in a year or two... The third class is a container for the mailbox which receives the file name that the user picked, and makes sure that there is a "next" method that returns a single mail. The idea here is to hide different kinds of mailboxes behind one interface, even tho at the moment the program can only handle Unix type mailboxes (but I'm getting so fed up with sendmail I I swear I'm going to look into qmail). The solution to the global variables, of course, was to use instance variables like "self.msg" and to pass everything else with the method call. I still have to think twice about when to use "self.msg" and when just "msg", especially with Tkinter stuff. However: I can proudly say that I didn't use /one/ global variable this time, just like I set out to do - Ha! Python satisfies another ego! What I also learned (apart from lots of Tkinter) was what Paul Sidorsky had predicted: > The big problem with manager classes is that to use them you end up > jumping through many hoops in order to do a very simple task. It can > lead to a kind of "OO-spaghetti code" that makes your program really > hard to understand. The program is rather longer than I had expected - 700-some lines, counting comments and blanks - and following the logic from the GUI class to the mailbox class to a single message and back took some getting use to. If anybody is interested in the code, I can gladly mail or post it (after cleaning it up a bit more). Thanks again to everybody who tried to answer my question, even though in retrospect I didn't understand enough of what my problems was to even formulate it correctly. You helped me get on the right track. Y, Scot From charlie@begeistert.org Sun May 12 12:54:11 2002 From: charlie@begeistert.org (Charlie Clark) Date: Sun, 12 May 2002 07:54:11 -0400 Subject: [Tutor] Creating typed files with Python, BeOS (OT) Message-ID: <54080016009-BeMail@gormenghast> >Dear Python people, > >How can you tell Python to make a simple text file or to make a kind of file >with your own kind of extension=3F I have looked around in books I have, and >online. I have only found stuff about how to open and close and recieve >input from. I don't know enough about file creation and operating systems >to know I guess how to tell Python to do it. Creating typed files depends on the operating system's support for file types. Extensions are not the same as file types!!! Python will let you create files with any name as long as it is allowd by the operating system: f =3D open("ourfile", "w") Giving textfiles a ".txt" extension is purely a convention required for primitive file systems such as FAT/ NTFS or Posix. Removing or changing the extension can make such files unreadable on that system. Some file systems such as the BFS provide sophisticated file typing and Python can hook into this. Bear in mind that this is platform specific The following code creates an e-mail file in BeOS from BeOS.fsattr import write=5Fattr newfile =3D "newfile.mail" # creat an empty file f =3D open(newfile, "w") f.close() #give our new file a file type write=5Fattr(newfile, "BEOS:TYPE", B=5FMIME=5FSTRING=5FTYPE, "text/x-email\0", 0) Our file "newfile.mail" now has the MIME-type "text/x-email". E-mail files are a subset of textfiles and can be read by any text editor or mail program independent of the file extension. Charlie From m_konermann@gmx.de Sun May 12 20:36:54 2002 From: m_konermann@gmx.de (Marcus) Date: Sun, 12 May 2002 21:36:54 +0200 Subject: [Tutor] where to find the file "pythonrun.c" ? Message-ID: <3CDEC456.3070006@gmx.de> Hi ! Can anyone tell me where i can find the file pythonrun.c ? I want to embed C Code with python, but after calling the Py_Initialize() Function from C Code the Debugger want´s to get the path for the File pythonrun.c . Have anyone got an idea what´s going wrong ? Perhaps i didn´t configure my VC++ Compiler in the right way. But the compiling and linking of my .c file was ok. Greetings Marcus From erikprice@mac.com Sun May 12 21:20:42 2002 From: erikprice@mac.com (Erik Price) Date: Sun, 12 May 2002 16:20:42 -0400 Subject: [Tutor] GoFish In-Reply-To: <3CDD420E.B834EAA8@york.ac.uk> Message-ID: On Saturday, May 11, 2002, at 12:08 PM, Russell Bungay wrote: > Is there a nicer way than using eval? I don't like it much, not sure > why, it just seems wrong. Keep in mind that eval() exists for a reason -- it is a useful function. The problem is only if it is used sloppily, such as evaluating user input. If you are certain that your code does not enable user input to work its way into the contents of an eval() argument, then you should be fine. I've heard it said that one never HAS to use eval(), that there is always another way. Perhaps. But there are times when it is an extremely useful way to generate dynamic variable names. Erik From rob@zoism.org Sun May 12 21:47:17 2002 From: rob@zoism.org (Rob Brown-Bayliss) Date: 13 May 2002 08:47:17 +1200 Subject: [Tutor] Printer output In-Reply-To: <75EDF89FDE81D511840D00A0C9AD25DD0261A273@CORP_EXCHANGE> References: <75EDF89FDE81D511840D00A0C9AD25DD0261A273@CORP_EXCHANGE> Message-ID: <1021236438.2208.27.camel@orion.zoism.org> On Sat, 2002-05-11 at 07:54, Alan Trautman wrote: > > I am wondering if there is any documentation about formatting printed > reports in Python? I need to parse, perform calculations and then produce a > few summary reports and I'm wandering if there is a good template type setup > to use. A long time ago I saw something called Report Lab that generates PDF files from python... Have not actually used it though -- R Brown-Bayliss ---====<=>=====--- http://zoism.org From dman@dman.ddts.net Sun May 12 22:37:33 2002 From: dman@dman.ddts.net (dman) Date: Sun, 12 May 2002 16:37:33 -0500 Subject: [Tutor] Creating typed files with Python, BeOS (OT) In-Reply-To: <54080016009-BeMail@gormenghast> References: <54080016009-BeMail@gormenghast> Message-ID: <20020512213733.GA9203@dman.ddts.net> --+QahgC5+KEYLbs62 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, May 12, 2002 at 07:54:11AM -0400, Charlie Clark wrote: =2E.. =20 | Giving textfiles a ".txt" extension is purely a convention required for | primitive file systems such as FAT/ NTFS or Posix. Removing or changing | the extension can make such files unreadable on that system. Just some clarification : AFAIK there is no filesystem "Posix". Instead there are several implementations of a posix-style fs (ext2, ext3, reiserfs, xfs, ...). These file systems don't care about so-called "extensions". It really isn't an extension, it's just part of the name ('.' is a legal character in a name). On UNIX systems the "extension" is only used by a few programs, such as the C compiler or the python interpreter, but otherwise is just a convention for human consumption. On UNIX systems a file is a file is a file. It's up to the application do decide what to do with the byte stream contained in it. I *think* FAT32 and NTFS allow files without "extensions" (cygwin seems capable of creating them), but many Windows applications don't like that idea and don't provide a human interface for creating such files. Older MS-DOS filesystems more-or-less required an extension (and there it _was_ an extension with the infamous 8.3 filename limit), but the extension could be the empty string. | Some file systems such as the BFS provide sophisticated file typing and | Python can hook into this. Bear in mind that this is platform specific I think MacOS has concept too, but I'm not sure about Darwin. -D --=20 Failure is not an option. It is bundled with the software. =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --+QahgC5+KEYLbs62 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjze4J0ACgkQO8l8XBKTpRSITwCgkP8iWGplp+tIZw7URJhOVnz7 +tAAoKHwkf71WG8dx6yNlgsVmbXcqI5e =I3Cc -----END PGP SIGNATURE----- --+QahgC5+KEYLbs62-- From dman@dman.ddts.net Sun May 12 22:44:56 2002 From: dman@dman.ddts.net (dman) Date: Sun, 12 May 2002 16:44:56 -0500 Subject: [Tutor] GoFish In-Reply-To: References: <3CDD420E.B834EAA8@york.ac.uk> Message-ID: <20020512214456.GB9203@dman.ddts.net> --TRYliJ5NKNqkz5bu Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, May 12, 2002 at 04:20:42PM -0400, Erik Price wrote: | On Saturday, May 11, 2002, at 12:08 PM, Russell Bungay wrote: |=20 | >Is there a nicer way than using eval? I don't like it much, not sure | >why, it just seems wrong. |=20 | Keep in mind that eval() exists for a reason -- it is a useful=20 | function. The problem is only if it is used sloppily, such as=20 | evaluating user input. If you are certain that your code does not=20 | enable user input to work its way into the contents of an eval()=20 | argument, then you should be fine. |=20 | I've heard it said that one never HAS to use eval(), that there is=20 | always another way. Perhaps. But there are times when it is an=20 | extremely useful way to generate dynamic variable names. Generating local (or global, or instance) variables with eval() is dangerous because you could accidentally end up with a conflict. It also makes the code harder to read due to variables magically appearing. If you think you need dynamic variable names, instead consider using a container. A dictionary allows you to use dynamic names (keys) to reference other objects. In fact, python uses dicts to implement namespaces. The only thing special about a local variable is the specific syntax used to index the mapping. This isn't to say that eval() is never useful, just that dynamically creating variable names is not considered good programming practice. -D --=20 Emacs is a nice operating system, it lacks a decent editor though =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --TRYliJ5NKNqkz5bu Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjze4lgACgkQO8l8XBKTpRTMOwCdFoM3l8dkYh/a+o0GtuxPqVXD A0QAoK4H3W09nKfB2zx7s8MUX8DSPAtp =r1Ot -----END PGP SIGNATURE----- --TRYliJ5NKNqkz5bu-- From erikprice@mac.com Sun May 12 22:51:09 2002 From: erikprice@mac.com (Erik Price) Date: Sun, 12 May 2002 17:51:09 -0400 Subject: [Tutor] Creating typed files with Python, BeOS (OT) In-Reply-To: <20020512213733.GA9203@dman.ddts.net> Message-ID: <5EBE3D28-65F2-11D6-8CB0-00039351FE6A@mac.com> On Sunday, May 12, 2002, at 05:37 PM, dman wrote: > Just some clarification : > > AFAIK there is no filesystem "Posix". Instead there are several > implementations of a posix-style fs (ext2, ext3, reiserfs, xfs, ...). > These file systems don't care about so-called "extensions". It really > isn't an extension, it's just part of the name ('.' is a legal > character in a name). On UNIX systems the "extension" is only used by > a few programs, such as the C compiler or the python interpreter, but > otherwise is just a convention for human consumption. On UNIX systems > a file is a file is a file. It's up to the application do decide what > to do with the byte stream contained in it. Further clarification, for the curious: If the particular blend of Unix that you use is Mac OS X, then keep in mind that one of the applications that dman mentions which depends on file extensions is the all-important Finder -- which is just as much an application as any other program on the system. Finder uses the file extension to determine what action to take upon double-click or Cmd-O (open). Usually this is simply deciding which application should be used to open the file. Note that, to preserve the older MacOS style, the Finder includes a preference which allows file extensions to be hidden from view, but generally the extensions are still there (the Finder just doesn't display them). Many applications on Mac OS X will generate the appropriate extension for you, regardless of whether you are actually showing extensions or not. > I think MacOS has concept too, but I'm not sure about Darwin. I'm not a specialist on hfs+ (the filesystem used by most Macs), but I do know that the original Mac OS did use metadata (such as type/creator codes), but Darwin does not. Erik From erikprice@mac.com Sun May 12 22:56:30 2002 From: erikprice@mac.com (Erik Price) Date: Sun, 12 May 2002 17:56:30 -0400 Subject: [Tutor] GoFish In-Reply-To: <20020512214456.GB9203@dman.ddts.net> Message-ID: <1DBCB23D-65F3-11D6-8CB0-00039351FE6A@mac.com> On Sunday, May 12, 2002, at 05:44 PM, dman wrote: > This isn't > to say that eval() is never useful, just that dynamically creating > variable names is not considered good programming practice. That makes sense, and I felt guilty doing it -- but the situation warranted it. I was writing server-side PHP code that would generate client-side JavaScript code to be echoed to an HTML document. (This gets pretty complicated, because it requires some characters to be escaped multiple times [from both JavaScript AND php].) Since variable names cannot be passed directly from PHP to JavaScript (you basically have to echo the JavaScript code you want), I had to do it this way. Erik From dominic.fox" Message-ID: <000701c1f9ff$48922ac0$82c10550@tinypc> I wonder whether anyone can help with a slightly more advanced Python/COM question. I'm being impatient here - as helpfully suggested, I ought to go and get Win32 Programming with Python, which no doubt contains the answer to this question, but I've just spend thirty-odd quid on an admittedly excellent Python book already this month and may have to hang on before I can convince my spouse that I can afford another one. If there's a quick answer someone can give me off the top of their head, then I'd be most grateful for it. I've managed to create an MSXML3 DOM and manipulate it in the ways I'm used to from VB using win32all's Dispatch('MSXML2.DOMDocument'). This didn't work for 'MSXML2.DOMDocument30' for some reason, which may have to do with my main question (the reason I'm using MSXML3, by the way, is that I'm a little hazy about the current level of support in Python for XPath and XSLT). This is good: it means that I can go into work tomorrow and talk about how I might like to start using Python quite soon to do some of the things we currently do in VB, and if they say "but what about XML / IE Explorer automation / Attachmate 3270 SNA Client automation / etc." I can say, "Oh, Python will do that too" with a reasonable amount of confidence. That doesn't mean they'll let me use it, of course, but it might be a start. A fairly common practice in writing VB code is to write a class which "implements" the COM interface of another. This is about as good as it gets in VB from an OO point of view; it means that you can create a number of classes which share the same methods, properties and functions, and pass instances of them interchangeably to client code. The trouble is that I can't see how to access the implemented attributes of these dual (or possibly multiple) interface classes using win32all's Dispatch. In VB you'd say something like: Dim GenericFoo as IFoo Set GenericFoo = New ActualFoo1 ' ActualFoo1 "implements" IFoo, which has a property Bar() Msgbox GenericFoo.Bar() Set GenericFoo = New ActualFoo2 ' ActualFoo2 also implements IFoo Msgbox GenericFoo.Bar() Now, assuming I had some VB classes IFoo, ActualFoo1 and ActualFoo2 which actually did something useful, and I wanted to use them in Python. How would I go about creating, and calling Bar() on, an instance of one of these classes? thanks for any help, Dominic From l8tr2000@yahoo.com Sun May 12 23:55:48 2002 From: l8tr2000@yahoo.com (Steve) Date: Sun, 12 May 2002 15:55:48 -0700 (PDT) Subject: [Tutor] Extending Classes, Instantiation, and attribute errors (Code Attached) Message-ID: <20020512225548.13013.qmail@web10706.mail.yahoo.com> NOTE: Code at he bottom of the post, also this is a repost, I posted late last night and I think my vague subject might have caused many to disreguard the post. If you've already seen this sorry for the repost! Lo all, I'm trying to learn python and just get this code to connect and perhaps send a few lines to the server I realize its incomplete. I've been having troubles figuring out a few things. First off if I want a variable to be shared between classes, and i've made the child class extend the parent, where do I place my multiclass variables? If I put then in the __init__ of the parent class and don't call the class directly it seems as if that method isn't called? I'm also not sure how instantiation works between classes, in my test function below don't I instantiate the class with my assignment to c? and when I open a socket doesn't sock instantiate the call? I'm also unsure about all the selfs I seem to be unsure as to when I need to call the class.method, self.method etc... (a few of the books i'm reading call class.method when one method in a class calls another in the same class) any help would be greately appreciated. Seems the latest error I was getting was: AttributeError: ircConnect instance has no attribute 'send' This I also don't understand considering I import socket at the top of the file so I figured self.send would be a method of the socket class but apparently its not working either. I'm reading all I can and slowly moving up the learning curver sorry for the bother. Steve (l8tr2000@yahoo.com) PS. Thanks in advance for the help #!/usr/bin/python import sys, time from select import select from socket import socket, AF_INET, SOCK_STREAM class selectSocket: def __init__(self): self.rxd = '' self.sent = '' def connServer(self, host, port): readsocks, writesocks = [], [] self.sock = socket(AF_INET, SOCK_STREAM) self.sock.connect((host, port)) readsocks.append(self.sock) writesocks.append(self.sock) def selectLoop(self): print 'select-server loop starting' while 1: r, w, e = select(readsocks, writesocks, []) for sockobj in r: self.rxd = sockobj.recv(1024) print 'DEBUG::', self.rxd, 'on', id(sockobj) if not self.rxd: # if closed by the clients sockobj.close() # close here and remove r.remove(sockobj) # else reselected for sockobj in w: if newConn == 1: pass else: pass time.sleep(.5) class ircConnect(selectSocket): def __init__(self): pass def connIRC(self, host, port, chan, nick, name): self.connServer(host, port) self.ircReg(nick, name) self.joinChan(self, chan) def ircReg(self, nick, name): self.send('NICK', nick) self.send('USER', nick, '+iw', name) self.send('PONG\n') def joinChan(self, chan): self.send('JOIN', chan) def test(host, port, chan, nick, name): c = ircConnect() c.connIRC(host, port, chan, nick, name) c.selectLoop() if __name__=='__main__': test('irc.openprojects.net', 6667, '#nix', 'testmoe', "testmoe neener") __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com From m_konermann@gmx.de Mon May 13 01:24:35 2002 From: m_konermann@gmx.de (Marcus) Date: Mon, 13 May 2002 02:24:35 +0200 Subject: [Tutor] Creating Debug version of python under windows ? Message-ID: <3CDF07C3.9080201@gmx.de> Hi ! It seems that if i want to use a newer python ver. (since 2.0.1) i have to create my own debug ver. of the python interpreter to get the debug files i need (python22_d.lib, etc.). I´m not so familiar in debugging, so, can anyone tell me how to create this debug ver. of python ? I need this files, because i want to embed a python script in c code and i get different runtime errors. I´m using the VC++ 6.0 Compiler under WindowsXP and Python ver2.2. Thanks a lot Marcus From dmanxiii@yahoo.com Mon May 13 02:26:21 2002 From: dmanxiii@yahoo.com (Mr. Derek L. Hoffmeister) Date: Sun, 12 May 2002 18:26:21 -0700 (PDT) Subject: [Tutor] Self Executing programs In-Reply-To: <20020512115502.12026.16431.Mailman@mail.python.org> Message-ID: <20020513012621.66609.qmail@web20904.mail.yahoo.com> --0-1202198348-1021253181=:66388 Content-Type: text/plain; charset=us-ascii Hi people, How can I make a program that is able to run on a computer that does not have python installed. So that I am able to bring little bits of code over to my friends and show it in action to him. On a machine running windows. Pre-Thanks Derek Hoffmeister --------------------------------- Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience --0-1202198348-1021253181=:66388 Content-Type: text/html; charset=us-ascii

Hi people,

How can I make a program that is able to run on a computer that does not have python installed.  So that I am able to bring little bits of code over to my friends and show it in action to him.  On a machine running windows. 

Pre-Thanks

Derek Hoffmeister



Do You Yahoo!?
LAUNCH - Your Yahoo! Music Experience --0-1202198348-1021253181=:66388-- From erikprice@mac.com Mon May 13 02:39:01 2002 From: erikprice@mac.com (Erik Price) Date: Sun, 12 May 2002 21:39:01 -0400 Subject: [Tutor] Self Executing programs In-Reply-To: <20020513012621.66609.qmail@web20904.mail.yahoo.com> Message-ID: <33DDFCCE-6612-11D6-8CB0-00039351FE6A@mac.com> On Sunday, May 12, 2002, at 09:26 PM, Mr. Derek L. Hoffmeister wrote: > Hi people, > > How can I make a program that is able to run on a computer that does=20= > not have python installed.=A0 So that I am able to bring little bits = of=20 > code over to my friends and show it in action to him.=A0 On a machine=20= > running windows.=A0 > http://starship.python.net/crew/theller/py2exe/ From dman@dman.ddts.net Mon May 13 03:02:26 2002 From: dman@dman.ddts.net (dman) Date: Sun, 12 May 2002 21:02:26 -0500 Subject: [Tutor] Creating Debug version of python under windows ? In-Reply-To: <3CDF07C3.9080201@gmx.de> References: <3CDF07C3.9080201@gmx.de> Message-ID: <20020513020226.GA10988@dman.ddts.net> --yrj/dFKFPuw6o+aM Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 13, 2002 at 02:24:35AM +0200, Marcus wrote: | Hi ! |=20 | It seems that if i want to use a newer python ver. (since 2.0.1) i have= =20 | to create my own debug ver. of the python interpreter to get the debug=20 | files i need (python22_d.lib, etc.). | I=B4m not so familiar in debugging, In that case you really don't need the debug version of the interpreter. It *won't* help you debug a pure-python program. It exists to help you debug a C/C++ extension to python. If you aren't familiar with debugging, then I'd wager that you aren't familiar with programming in C/C++ and haven't written a python extension in it and thus don't need the debug version of the interpreter. What is the real problem you're running into? If you need to debug a pure-python program, then either use the "print" technique or use 'pydb'. (in any case I'm not going to be helpful when it comes to compiling C/C++ stuff on windows unless you're using cygwin to pretend you're on unix) HTH, -D --=20 Do not pay attention to every word people say,=20 or you may hear your servant cursing you -- for you know in your heart=20 that many times you yourself have cursed others. Ecclesiastes 7:21-22 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --yrj/dFKFPuw6o+aM Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzfHrIACgkQO8l8XBKTpRTzUACgpAz+UKKU0//5moBaRWyoKQTN SyQAoJa+eTUkWJgextU5YMeL9R+2xUzU =0hsh -----END PGP SIGNATURE----- --yrj/dFKFPuw6o+aM-- From python@rcn.com Mon May 13 05:25:04 2002 From: python@rcn.com (Raymond Hettinger) Date: Mon, 13 May 2002 00:25:04 -0400 Subject: [Tutor] Creating Debug version of python under windows ? References: <3CDF07C3.9080201@gmx.de> Message-ID: <004f01c1fa36$28dc78c0$56f7a4d8@othello> >From the readme.txt file in the pcbuild directory: ''' All you need to do is open the workspace "pcbuild.dsw" in MSVC++, select the Debug or Release setting (using Build -> Set Active Configuration...), and build the projects. ''' Happy embedding, Raymond Hettinger ----- Original Message ----- From: "Marcus" To: "Tutor" Sent: Sunday, May 12, 2002 8:24 PM Subject: [Tutor] Creating Debug version of python under windows ? > Hi ! > > It seems that if i want to use a newer python ver. (since 2.0.1) i have > to create my own debug ver. of the python interpreter to get the debug > files i need (python22_d.lib, etc.). > I´m not so familiar in debugging, so, can anyone tell me how to create > this debug ver. of python ? > I need this files, because i want to embed a python script in c code and > i get different runtime errors. I´m using the VC++ 6.0 Compiler under > WindowsXP and Python ver2.2. > > Thanks a lot > Marcus > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From scarblac@pino.selwerd.nl Sat May 11 11:42:14 2002 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Sat, 11 May 2002 12:42:14 +0200 Subject: [Tutor] Leaving for a while. Message-ID: <20020511124213.A25466@pino.selwerd.nl> Just wanted to write a little post before I'm going to unsubscribe. I really enjoyed being on this list, programming is fun, and so is the discussion on here. I hope I managed to teach some people about some small things. However, at the moment I'm subscribed to too much, have to spend too much time on email, and 80%+ of everything stays unread. In the last months I didn't really post at all on this list :(. I'm unsubscribing everything for at least a month. Have fun. I'll be back, I like explaining about programming too much :) Hopefully with more time then. -- Remco Gerlich From pythontutor@venix.com Mon May 13 14:04:07 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 13 May 2002 09:04:07 -0400 Subject: [Tutor] COM Interfaces References: <20020512115502.12026.16431.Mailman@mail.python.org> <000701c1f9ff$48922ac0$82c10550@tinypc> Message-ID: <3CDFB9C7.5080700@venix.com> Python depends on the registry entries to find the COM object it is running. The name passed to Dispatch MUST exactly match the name in the registry. You can't make it up. I suspect that 'MSXML2.DOMDocument30' should be 'MSXML3.DOMDocument30'. If you search your registry, you should be able to find the name. To run your VB COM object, you need to get it registered. Then simply pass the name you used to register it to dispatch, just like you did for MSXML. The Win32 Programming with Python explains this very well. The VB documentation should tell you how to register your VB code. dominic.fox wrote: > I wonder whether anyone can help with a slightly more advanced Python/COM > question. I'm being impatient here - as helpfully suggested, I ought to go > and get Win32 Programming with Python, which no doubt contains the answer to > this question, but I've just spend thirty-odd quid on an admittedly > excellent Python book already this month and may have to hang on before I > can convince my spouse that I can afford another one. If there's a quick > answer someone can give me off the top of their head, then I'd be most > grateful for it. > > I've managed to create an MSXML3 DOM and manipulate it in the ways I'm used > to from VB using win32all's Dispatch('MSXML2.DOMDocument'). This didn't work > for 'MSXML2.DOMDocument30' for some reason, which may have to do with my > main question (the reason I'm using MSXML3, by the way, is that I'm a > little hazy about the current level of support in Python for XPath and > XSLT). This is good: it means that I can go into work tomorrow and talk > about how I might like to start using Python quite soon to do some of the > things we currently do in VB, and if they say "but what about XML / IE > Explorer automation / Attachmate 3270 SNA Client automation / etc." I can > say, "Oh, Python will do that too" with a reasonable amount of confidence. > That doesn't mean they'll let me use it, of course, but it might be a start. > > A fairly common practice in writing VB code is to write a class which > "implements" the COM interface of another. This is about as good as it gets > in VB from an OO point of view; it means that you can create a number of > classes which share the same methods, properties and functions, and pass > instances of them interchangeably to client code. The trouble is that I > can't see how to access the implemented attributes of these dual (or > possibly multiple) interface classes using win32all's Dispatch. In VB you'd > say something like: > > Dim GenericFoo as IFoo > Set GenericFoo = New ActualFoo1 ' ActualFoo1 "implements" IFoo, which has > a property Bar() > Msgbox GenericFoo.Bar() > Set GenericFoo = New ActualFoo2 ' ActualFoo2 also implements IFoo > Msgbox GenericFoo.Bar() > > Now, assuming I had some VB classes IFoo, ActualFoo1 and ActualFoo2 which > actually did something useful, and I wanted to use them in Python. How would > I go about creating, and calling Bar() on, an instance of one of these > classes? > > thanks for any help, > Dominic > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor@venix.com Mon May 13 14:13:43 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 13 May 2002 09:13:43 -0400 Subject: [Tutor] Extending Classes, Instantiation, and attribute errors (Code Attached) References: <20020512225548.13013.qmail@web10706.mail.yahoo.com> Message-ID: <3CDFBC07.9060004@venix.com> As a first step, remove the __init__(self): pass You only need __init__ if it does something useful. If you do write an __init__ function, it becomes YOUR responsibility to invoke the parent __init__. Otherwise, the Python Runtime will invoke the correct parent __init__'s automatically. Your child object is also an instance of the parent classes. It will normally have all of the parent attributes unless you do something to prevent that. In this case your __init__: pass prevents the child from getting the rxd and sent attributes that would be created by the parent __init__ Steve wrote: > NOTE: Code at he bottom of the post, also this is a > repost, I posted late last night and I think my vague > subject might have caused many to disreguard the post. > > If you've already seen this sorry for the repost! > > Lo all, > > I'm trying to learn python and just get this code > to > connect and perhaps send a few lines to the server I > realize its incomplete. I've been having troubles > figuring out a few things. First off if I want a > variable to be shared between classes, and i've made > the child class extend the parent, where do I place my > multiclass variables? If I put then in the __init__ of > the parent class and don't call the class directly it > seems as if that method isn't called? I'm also not > sure how instantiation works between classes, in my > test function below don't I instantiate the class with > my assignment to c? and when I open a socket doesn't > sock instantiate the call? I'm also unsure about all > the selfs I seem to be unsure as to when I need to > call the class.method, self.method etc... (a few of > the books i'm reading call class.method when one > method in a > class calls another in the same class) any help would > be greately appreciated. Seems the latest error I was > getting was: > > AttributeError: ircConnect instance has no attribute > 'send' > > This I also don't understand considering I import > socket at the top of the file so I figured self.send > would be a method of the socket class but apparently > its not working either. I'm reading all I can and > slowly moving up the learning curver sorry for the > bother. > > Steve (l8tr2000@yahoo.com) > > PS. Thanks in advance for the help > > #!/usr/bin/python > > import sys, time > from select import select > from socket import socket, AF_INET, SOCK_STREAM > > class selectSocket: > def __init__(self): > self.rxd = '' > self.sent = '' > > def connServer(self, host, port): > readsocks, writesocks = [], [] > self.sock = socket(AF_INET, SOCK_STREAM) > self.sock.connect((host, port)) > readsocks.append(self.sock) > writesocks.append(self.sock) > > def selectLoop(self): > print 'select-server loop starting' > > while 1: > r, w, e = select(readsocks, writesocks, > []) > > for sockobj in r: > self.rxd = sockobj.recv(1024) > print 'DEBUG::', self.rxd, 'on', > id(sockobj) > > if not self.rxd: # if closed by > the clients > sockobj.close() # close here > and remove > r.remove(sockobj) # else > reselected > > for sockobj in w: > > if newConn == 1: > pass > > else: > pass > > time.sleep(.5) > > class ircConnect(selectSocket): > def __init__(self): > pass > > def connIRC(self, host, port, chan, nick, name): > self.connServer(host, port) > self.ircReg(nick, name) > self.joinChan(self, chan) > > def ircReg(self, nick, name): > self.send('NICK', nick) > self.send('USER', nick, '+iw', name) > self.send('PONG\n') > > def joinChan(self, chan): > self.send('JOIN', chan) > > def test(host, port, chan, nick, name): > c = ircConnect() > c.connIRC(host, port, chan, nick, name) > c.selectLoop() > > if __name__=='__main__': > > test('irc.openprojects.net', 6667, '#nix', > 'testmoe', "testmoe neener") > > > > > __________________________________________________ > Do You Yahoo!? > LAUNCH - Your Yahoo! Music Experience > http://launch.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor@venix.com Mon May 13 14:55:14 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 13 May 2002 09:55:14 -0400 Subject: [Tutor] COM Interfaces References: <20020512115502.12026.16431.Mailman@mail.python.org> <000701c1f9ff$48922ac0$82c10550@tinypc> <3CDFB9C7.5080700@venix.com> Message-ID: <3CDFC5C2.1010903@venix.com> Lloyd Kvam wrote: > I suspect that 'MSXML2.DOMDocument30' should be 'MSXML3.DOMDocument30'. This is the value in my registry: Msxml2.DOMDocument.3.0 My suspicions were way off base. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From scot@possum.in-berlin.de Mon May 13 13:54:38 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Mon, 13 May 2002 14:54:38 +0200 Subject: [Tutor] "Hidden" stmpd module with Python 2.1? Message-ID: <200205131445.g4DEjUCr007378@charmor.internal.use> Hi there, I was browsing the code in the /usr/lib/python2.1 (as one does on a sunny afternoon) and found a module called "smtpd.py" which claims it is "An RFC 821 smtp proxy" from one Barry Warsaw . However, there is no word of this module in the docs. I've checked and the same is true of Python 2.2: The code is there (and can at least be imported), but no docs. Now before I mail Mr. Warsaw and make a fool out of myself: Is there something special about "hidden" modules I missed out on? Y, Scot Who has become interested in SMTP since sendmail lost some mail yesterday From ATrautman@perryjudds.com Mon May 13 15:09:12 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Mon, 13 May 2002 09:09:12 -0500 Subject: [Tutor] Printer output Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A275@CORP_EXCHANGE> Thanks for the help. I should have been clearer in my question. I have a variable size collection of CSV tables of variable length. I want to parse these, do a bunch of simple calcs. These are the easy parts. Finally I need them to create printed reports (HP LaserJet's if it matters) locally or across as Windows NT network. I am currently leaning to adding a simple web server and creating HTML but want to know if something like the ostream command in C exhists at least for trouble shooting. The ideal if I could find some docs/example is an XML based system using different style sheets for the different views but don't know much about either of these techniques. Peace Alan -----Original Message----- From: dman [mailto:dman@dman.ddts.net] Sent: Friday, May 10, 2002 3:11 PM To: 'tutor@python.org' Subject: Re: [Tutor] Printer output On Fri, May 10, 2002 at 02:54:16PM -0500, Alan Trautman wrote: | I am wondering if there is any documentation about formatting printed | reports in Python? I need to parse, perform calculations and then produce a | few summary reports and I'm wondering if there is a good template type setup | to use. man printf or is that not what you mean by "print"? Python has built-in support for string formatting with the same rules as C's printf family of functions. With it you can align columns and format numbers, etc. As for outputing formatted data, the options really depend on what the communication medium is. There are template systems for web (html) stuff, it isn't too hard to generate some LaTeX as long as you know the tables won't have any page breaks in them. HTH, -D -- How to shoot yourself in the foot with Java: You find that Microsoft and Sun have released incompatible class libraries both implementing Gun objects. You then find that although there are plenty of feet objects implemented in the past in many other languages, you cannot get access to one. But seeing as Java is so cool, you don't care and go around shooting anything else you can find. (written by Mark Hammond) GnuPG key : http://dman.ddts.net/~dman/public_key.gpg From pythontutor@venix.com Mon May 13 15:37:35 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 13 May 2002 10:37:35 -0400 Subject: [Tutor] Printer output References: <75EDF89FDE81D511840D00A0C9AD25DD0261A275@CORP_EXCHANGE> Message-ID: <3CDFCFAF.10407@venix.com> Taking an easy piece, the print statement is the python equivalent of ostream. Both default to stdout. print >> allows you to print to a different file. Alan Trautman wrote: > Thanks for the help. I should have been clearer in my question. > > I have a variable size collection of CSV tables of variable length. I want > to parse these, do a bunch of simple calcs. These are the easy parts. > > Finally I need them to create printed reports (HP LaserJet's if it matters) > locally or across as Windows NT network. I am currently leaning to adding a > simple web server and creating HTML but want to know if something like the > ostream command in C exhists at least for trouble shooting. The ideal if I > could find some docs/example is an XML based system using different style > sheets for the different views but don't know much about either of these > techniques. > > Peace > Alan > > > -----Original Message----- > From: dman [mailto:dman@dman.ddts.net] > Sent: Friday, May 10, 2002 3:11 PM > To: 'tutor@python.org' > Subject: Re: [Tutor] Printer output > > > On Fri, May 10, 2002 at 02:54:16PM -0500, Alan Trautman wrote: > > | I am wondering if there is any documentation about formatting printed > | reports in Python? I need to parse, perform calculations and then produce > a > | few summary reports and I'm wondering if there is a good template type > setup > | to use. > > man printf > > or is that not what you mean by "print"? > > Python has built-in support for string formatting with the same rules > as C's printf family of functions. With it you can align columns and > format numbers, etc. > > As for outputing formatted data, the options really depend on what the > communication medium is. There are template systems for web (html) > stuff, it isn't too hard to generate some LaTeX as long as you know > the tables won't have any page breaks in them. > > HTH, > -D > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From wilson@visi.com Mon May 13 15:42:20 2002 From: wilson@visi.com (Tim Wilson) Date: Mon, 13 May 2002 09:42:20 -0500 Subject: [Tutor] simple graphical labels with Tkinter Message-ID: <20020513144220.GA27925@isis.visi.com> Hi everyone, If I've got a GIF file, how can I place that graphic into a Tkinter Label widget? -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From bryce@bembry.org Mon May 13 16:18:31 2002 From: bryce@bembry.org (Bryce Embry) Date: Mon, 13 May 2002 10:18:31 -0500 Subject: [Tutor] simple graphical labels with Tkinter In-Reply-To: <20020513144220.GA27925@isis.visi.com> Message-ID: <5.1.0.14.0.20020513101221.00b01b08@www.bembry.org> Use PhotoImage to get the picture, then point the "image=" option to the PhotoImage object. Here's a sample script: from Tkinter import * root = Tk() pic = PhotoImage(file="k:\\Python\\tkinter\\test.gif") lbl = Label(root, image = pic) lbl.grid() root.mainloop() #omit if running in IDLE the PhotoImage needs the complete path only if the image is not in the current directory. If you are running the GUI from inside IDLE, this can be an issue for getting the path right. Also, according to Grayson's book, Tkinter is limited to gif, pgm, and ppm files. I think there is a way to extend it to accept png / jpg, but I don't know how. Hope this helps. Bryce At 09:42 AM 5/13/2002, you wrote: >Hi everyone, > >If I've got a GIF file, how can I place that graphic into a Tkinter >Label widget? > >-Tim > >-- >Tim Wilson | Visit Sibley online: | Check out: >Henry Sibley HS | http://www.isd197.org | http://www.zope.com >W. St. Paul, MN | | http://slashdot.org >wilson@visi.com | | http://linux.com > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor -------------------------------------------------------------------------------------------- "Lord, you establish peace for us. All that we have accomplished you have done for us" -- Isaiah 26:12 From dman@dman.ddts.net Mon May 13 16:38:53 2002 From: dman@dman.ddts.net (dman) Date: Mon, 13 May 2002 10:38:53 -0500 Subject: [Tutor] Printer output In-Reply-To: <75EDF89FDE81D511840D00A0C9AD25DD0261A275@CORP_EXCHANGE> References: <75EDF89FDE81D511840D00A0C9AD25DD0261A275@CORP_EXCHANGE> Message-ID: <20020513153853.GA17089@dman.ddts.net> --LQksG6bCIzRHxTLp Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 13, 2002 at 09:09:12AM -0500, Alan Trautman wrote: | Thanks for the help. I should have been clearer in my question. |=20 | I have a variable size collection of CSV tables of variable length. I want | to parse these, do a bunch of simple calcs. These are the easy parts. Ok. =20 | Finally I need them to create printed reports (HP LaserJet's if it matter= s) The HP LJs I've used understand both plain text and PostScript. If you can generate either of those, then you can feed it into the printer. The plain text option is the easiest. Another option is to use some library such as ReportLab (for generating PDFs) to "paint" your output on a "canvas" and have it generate the data to feed to the printer. You may need to do that to work with the windows printing system. | locally or across as Windows NT network. Sorry, I can't help there. My primary knowledge of windows printing is that it is _not_ as simple as UNIX -- you can't simply open a pipe to 'lp' and feed it the data. | I am currently leaning to adding a simple web server and creating | HTML but want to know if something like the HTML is also rather easy to generate, and doesn't require a web server at all. | ostream command in C exhists at least for trouble shooting. ostream is a C++ thing (it was 'printf' in C), and yes, python has a "print" statement that does the same thing. | The ideal if I could find some docs/example is an XML based system | using different style sheets for the different views but don't know | much about either of these techniques. I haven't used XML for that, I don't know how that would be done. The simplest technique is to simply generate plain text. It isn't fancy, but it is functional and easiest to generate and test. HTH, -D --=20 The heart is deceitful above all things and beyond cure. Who can understand it? I the Lord search the heart and examine the mind, to reward a man according to his conduct, according to what his deeds deserve. Jeremiah 17:9-10 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --LQksG6bCIzRHxTLp Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzf3g0ACgkQO8l8XBKTpRTj0wCfWVZB0Gk3GbehrfYVavglVQ7B E7kAn39y35Wu5wk4LHXO8c51+Y2hv5kq =mSPw -----END PGP SIGNATURE----- --LQksG6bCIzRHxTLp-- From m_konermann@gmx.de Mon May 13 16:58:28 2002 From: m_konermann@gmx.de (Marcus K.) Date: Mon, 13 May 2002 17:58:28 +0200 Subject: [Tutor] getting access violation error in kernel32.dll while debugging Message-ID: <3CDFE2A4.3030500@gmx.de> Hi ! I want to embbed C source code with a python script, named modulefile.py. Here´s the intresting part of my c code: void getValues(char **firstName, char **lastName, char **profession) { FILE *fp = NULL; PyObject *module, *fn, *ln, *prof; int res; module = PyImport_AddModule("__main__"); fp = fopen("modulefile.py","r"); res = PyRun_SimpleFile(fp,"modulefile.py"); } void main(int argc, char *argv[]) { char *firstName, *lastName, *profession; Py_Initialize(); PySys_SetArgv(argc, argv); getValues(&firstName, &lastName, &profession); After the debugger reaches the statemant: res = PyRun_SimpleFile(fp,"modulefile.py"); I get a acess violation error in kernel32.dll. Have anyone got an idea what happend ? All the examples in the source code (D:\home\...\Python-2.2.1\Demo\embed) are working, so it does´nt seem to be a compiler configuration error. Thanks a lot, greetings Marcus From cogs2002@hotmail.com Mon May 13 17:42:25 2002 From: cogs2002@hotmail.com (alex gigh) Date: Mon, 13 May 2002 16:42:25 +0000 Subject: [Tutor] Implementing a mail server in Python (socket programming) Message-ID: I sent this email earlier with embedded HTML (because of Hotmail...). So here is the text version Hi; I was surfing the web for Python related sources and I found out that you know some things about Python programming... I want to program a mail server (socket programming) writen in Python as part of my Computer Science degree in Sussex University but I am very unfamiliar with Python and socket programming. I was wondering if you could give me a little help or guidance regarding this matter. Below, I give some more details about the mail server that I actually have to produce and some questions I have... I kindly appreciate your help... *** I have to design and implement a simple mail server. The program is supposed to do two things: A) Receive emails from standard mailer. To this purpose it must implement the basic commands of SMTP, that is HELO, MAIL FROM, RCPT TO, DATA, QUIT. The messages received must be deposited in users mailboxes. These will be files the format of which must be compatible with standard mailer programs (so that users can actually read their emails!) Consider the set of users fixed. (So I don't have to do any administration like creating users etc...) I'm allowed to ignore all file locking problems. Users must be allowed to specify an antispam file (a kill file): messages that match keywords specified in such a file must be dropped and not inserted in the mailbox. Some questions I have about these requirements... maybe you're able to answer them... 1) How shall I design the format of the kill file so that it's suitable to solve the assignment. Should I use a file of words, an array of words or any other data structure? Would I compare every single word in all mails to each of the words in the kill file? THen maybe a search tree might be handy.... 2) How could/should I implement the mailboxes? Shall I create a folder for each user and have each message saved as a separate or shall I have a single file for each user and append each message new to this file? What would be the (dis)advantages of each approach? I know that mails end with a "." on a single line. How could I append new messages to a single file for each user if this is the better way? *** B) The server must deliver email messages written in the standard rfc822 format. To this purpose, in principle I will have to contact a DNS server to obtain the name of the mail exchanger (MX) associated to the given address. To simplify the task, I'm allowed to either ignore this part, and assume that all addresses already refer exclusively to mail exchangers, or I can use the function queryMX(hostname) provided below for free. (I put this function all the way at the bottom of this email in case it's relevant) After that, I must contact the mail exchanger at port 25 and play the SMTP protocol. Because SMTP works only with 7bit ASCII data, I will have to mime-encode all messages containing more complex stuff. I'm allowed to use the mimify library (and related ones) of the standard Python distribution. Question: The user agent will use pop3 or IMAP to get the mail from the mailbox. Is this why I have to decode Mime? *** I must implement the communication protocols using sockets, and not the high-level mailer classes available in Python. I'm allowed however to use any class I like for local computation, eg parsing email files and messages, searching headers, do text manipulation, and so on. I'm not supposed to implement any form of error recovery or reporting. While receiving messages, it is acceptable to close the connection if the protocol is broken and to drop messages to unknown users; while delivering, it is enough to report to the terminal that delivery is not possible if some serious error occur. *** Could you please give me ideas on how to tackle this programming exercise? I have read on Internet protocols and I'm familiar with the Java programming language (but I must use Python!). Do you know any open source Python project similar to what I have to do so that I can have a look at them? All the ones I saw use smtplib, which I think I'm not allowed to use... Your help is kindly appreciated... Thank you very much for helping me and sorry for taking your time! Alex *** The provided queryMX function mentioned above: The function queryMX(hostname)below returns a list of mail exchanger that serve host hostname in strict order of preference. The list will have the form of a list of pairs [(mailexchanger1, IP_address1),(mailexchanger2, IP_address2),....] where the first component of a pair is the mail exchanger name and the second is its IP address. (Notice that if the list is empty, the host has not got any mail exchanger and the message cannot be delivered.) For instance, invoking queryMX("cogs.susx.ac.uk") the result is: [('rsunx.crn.cogs.susx.ac.uk', '139.184.48.12'), ('tsunb.ctn.cogs.susx.ac.uk', '139.184.50.11'), ('tsunx.ctn.cogs.susx.ac.uk', '139.184.50.12'), ('rinka.central.susx.ac.uk', '139.184.14.19'), ('suna9.central.susx.ac.uk', '139.184.32.27')] Note: This code will only work on Solaris. To adapt it to Windows or Linux, you will have to adjust the path to the nslookup executable (most likely C:\WINDOWS\SYSTEM32\NSLOOKUP and /usr/bin/nslookup). The code of the function is as follows. import os,sys,popen2,re resolver = "/usr/sbin/nslookup -query=mx " def queryMX(host): mx = [] addr = {} fout,fin = popen2.popen2(resolver + host) line = fout.readline() while line <> '': m = re.search( 'preference\s*=\s*(\d+),\s*mail\sexchanger\s*=\s*([\w\.]+)', line) if m: mx.append((eval(m.group(1)),m.group(2))) else: m = re.search( '([\w\.]+)\s*internet\saddress\s*=\s*([\d\.]+)', line) if m: addr[m.group(1)] = m.group(2) line = fout.readline() if mx == []: return mx mx.sort() result = [] for i,k in mx: try: result.append((k,addr[k])) except: pass return result _________________________________________________________________ Join the world’s largest e-mail service with MSN Hotmail. http://www.hotmail.com From kalle@lysator.liu.se Mon May 13 17:55:12 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Mon, 13 May 2002 18:55:12 +0200 Subject: [Tutor] "Hidden" stmpd module with Python 2.1? In-Reply-To: <200205131445.g4DEjUCr007378@charmor.internal.use> References: <200205131445.g4DEjUCr007378@charmor.internal.use> Message-ID: <20020513165512.GA4105@i92.ryd.student.liu.se> [Scot Stevenson about smtpd.py lacking docs] > Now before I mail Mr. Warsaw and make a fool out of myself: Is there > something special about "hidden" modules I missed out on? Nope, but the missing docs for smtpd.py is a known bug: http://python.org/sf/450803 If you have the time, I'm sure some contributed documentation would be appreciated. > Y, Scot > Who has become interested in SMTP since sendmail lost some mail yesterday As an aside, I think you'd be better off by using a well tested SMTP daemon with a large user base than rolling your own. I use Postfix, and I'm happy with it. Many use sendmail, though, and I'd be a bit surprised if the lost mail was really caused by a sendmail bug. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From dominic.fox" <000701c1f9ff$48922ac0$82c10550@tinypc> <3CDFB9C7.5080700@venix.com> Message-ID: <001501c1fab3$4584b6e0$82c10550@tinypc> Lloyd Kvam was kind enough to reply: > Python depends on the registry entries to find the COM object it is running. > The name passed to Dispatch MUST exactly match the name in the registry. You > can't make it up. Well, this is much like creating an object in, say, VBScript or JavaScript by passing the progid to CreateObject(). You can't do much with multiple-interface objects in JavaScript, to my knowledge; what I was wondering was whether PyWin & c. managed to improve on the situation. > I suspect that 'MSXML2.DOMDocument30' should be 'MSXML3.DOMDocument30'. If you > search your registry, you should be able to find the name. > > To run your VB COM object, you need to get it registered. Then simply pass > the name you used to register it to dispatch, just like you did for MSXML. I can do this without difficulty for single-interface objects, but not at all for dual or multiple interface objects. Yesterday evening I coded up a small-ish .dll to try some of these things out with. Getting instances of the more conventional objects by progid was a doddle. There didn't seem to be any way at all of using the multiple-interface ones. Just to clarify: in VB you can do the following: Class MyInterface Public Sub DoSomethingExciting() End Sub --- Class InheritorTheFirst Implements MyInterface Private Sub MyInterface_DoSomethingExciting() Msgbox "Wow!" End Sub --- Class InheritorTheSecond Implements MyInterface Private Sub MyInterface_DoSomethingExciting() Msgbox "Whoopee!" End Sub --- and then... Dim MyInstance As MyInterface Set MyInstance = New InheritorTheSecond MyInstance.DoSomethingExciting Set MyInstance = New InheritorTheFirst MyInstance.DoSomethingExciting --- MyInterface is something like an abstract base class, which simply outlines in skeleton form the COM interface that the other two classes will use. Just to confuse matters, they are allowed to implement as many different interfaces as they like; they are also allowed their own 'native' COM interface as well. The specifics of how this is implemented escape me, but I think it has to do with the way IUnknown and IDispatch are mapped to method calls through whatever mechanism it is that VB uses. Whatever: it's ugly, and Python is beautiful, so I feel as if I ought to be apologising for bringing the matter up at all... Now the question is, assuming I have created and registered a .dll containing the above, and want to create an object in Python which behaves like an instance of InheritorTheSecond, and want Python to know that I can call MyInterface's methods on it, can I? If I can, how can I? You only get to pass one progid to Dispatch. If it's the progid of MyInterface, you get an instance of the base class which doesn't do anything. If it's the progid of InheritorTheSecond, the "inherited" or "implemented" member functions are invisible and can't be used. For my own purposes, it would be easy enough just to eschew this technique; or better still, write everything in Python to begin with. But there are other libraries out there that I didn't write, can't obtain the source code for, and might still want to use. Some of them (like MSHTML, which gives you access to the DOM in Internet Explorer HTML documents) use multiple interfaces fairly extensively. It would be useful to know whether I can use them directly in Python, or whether I'd need to come up with a set of simplified "wrapper" classes in VB for them first. As an aside, the reason why VB *has* multiple interfaces is that it's a statically typed language, which means amongst other things that, as in Java and C++, the signatures of method function calls include the types of the parameters being supplied (this might come as a surprise to some VB programmers of my acquaintance, who use Variants for everything...). So if I have a variety of different persistence mechanisms, say, which can all store basic plain-text strings, I might want to have a method which writes a given string in uppercase to any one of them, without needing to know what the underlying mechanism is. If my method looks like this: Public Sub writeUppercase( persistenceMechanism as IPersist, stringToWrite as String) IPersist.writeString strconv( stringToWrite, vbUpperCase ) End Sub then I can pass it an instance of any class that "implements" IPersist, be it a wrapper for database access, textfile access, storing things in cells in an Excel worksheet or whatever. In Python, which is dynamically typed, all of this is pretty much redundant...although I did read somewhere an article by a diehard Smalltalk enthusiast who nevertheless admitted, vis-a-vis Java, that programming to interfaces sounded like quite a sensible idea... Dominic From dman@dman.ddts.net Mon May 13 21:13:00 2002 From: dman@dman.ddts.net (dman) Date: Mon, 13 May 2002 15:13:00 -0500 Subject: [Tutor] Implementing a mail server in Python (socket programming) In-Reply-To: References: Message-ID: <20020513201300.GB13033@dman.ddts.net> --v9Ux+11Zm5mwPlX6 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 13, 2002 at 04:42:25PM +0000, alex gigh wrote: | I sent this email earlier with embedded HTML (because of Hotmail...). | So here is the text version |=20 | Hi; |=20 | I was surfing the web for Python related sources and I found out that | you know some things about Python programming... I want to program a | mail server (socket programming) writen in Python as part of my Computer= =20 | Science degree in | Sussex University but I am very unfamiliar with Python and socket | programming. I was wondering if you could give me a little help or | guidance regarding this matter. Below, I give some more details about | the mail server that I actually have to produce and some questions I have= ... | I kindly appreciate your help... |=20 | *** |=20 | I have to design and implement a simple mail server. The program is=20 | supposed to do two things: |=20 | A) |=20 | Receive emails from standard mailer. To this purpose it must implement th= e=20 | basic commands of SMTP, that is |=20 | HELO, | MAIL FROM, | RCPT TO, | DATA, | QUIT. |=20 | The messages received must be deposited in users mailboxes. | These will be files the format of which must be compatible with standard= =20 | mailer programs | (so that users can actually read their emails!) | Consider the set of users fixed. (So I don't have to do any administratio= n=20 | like creating users etc...) | I'm allowed to ignore all file locking problems. | Users must be allowed to specify an antispam file (a kill file): | messages that match keywords specified in such a file must be dropped and= =20 | not inserted in the mailbox. This sounds kinda interesting, and just a little invovled (but not too much). | Some questions I have about these requirements... maybe you're able to=20 | answer them... |=20 | 1) How shall I design the format of the kill file so that it's suitable | to solve the assignment. Should I use a file of words, an array of words | or any other data structure? Would I compare every single word in all | mails to each of the words in the kill file? THen maybe a search tree | might be handy.... Well, the killfile is a *file*. I'd probably design the format to have just one word per line. How you handle the data in-memory (after reading the user's killfile) is up to you. It depends what "match" means -- regex? glob? literal word?. =20 | 2) How could/should I implement the mailboxes? Shall I create a folder | for each user and have each message saved as a separate or shall I have | a single file for each user and append each message new to this file? | What would be the (dis)advantages of each approach? |=20 | I know that mails end with a "." on a single line. How could I append | new messages to a single file for each user if this is the better way? Messages end with a '.' only for the SMTP session. That spec is for SMTP and doesn't cover on-disk storage. The most commonly used format is 'mbox'. I prefer 'maildir' myself, and quite a few mailers support it now. The mbox format is like this : ~~~~ From From ~~~~ It is all stored in a single file. This format is flawed in several ways, one being locking and the other is the need to escape lines in a message that begin with "From " or else some parser might think it is the message separator line. Various implementations do slightly different things with the format of the "From " line. | B) |=20 | The server must deliver email messages written in the standard rfc822=20 | format. Why not be impressive and follow RFC2822? (it supercedes 822). | To this purpose, in principle I will have to contact a DNS server to obta= in=20 | the name of the mail exchanger (MX) associated to the given address. Why? RFC(2)822 doesn't discuss DNS or MX records at all. | To simplify the task, I'm allowed to either ignore this part, and assume= =20 | that all addresses already refer exclusively to mail exchangers, or I can= =20 | use the function queryMX(hostname) provided below for free. (I put this= =20 | function all the way at the bottom of this email in case it's relevant) | After that, I must contact the mail exchanger at port 25 and play the SMT= P=20 | protocol. Oh, no, don't pull the address from the To: header. That is bad. It's like a postal worker opening up the envelope of each letter, reading the salutation and then deciding they know where it should be delivered. That is wrong; the destonation should be determined from the envelope only. =20 Just look at any message from the tutor list. Your address is not in the To: header. That's because the message wasn't addressed to you, but the envelope was. In fact, RFC(2)821 forbids an MTA from doing anything with the message (in between DATA and .) apart from : o prepending a Received: header in RFC822 format o quoting/dequoting lines beginning with '.' to prevent them disrupting the SMTP conversation Real-world MTAs use the RCPT TO: in SMTP to determine where to deliver a message that arrives via smtp. They use a command line argument to determine where to deliver a message that arrives via a local pipe. =20 | Because SMTP works only with 7bit ASCII data, I will have to mime-encode= =20 | all messages containing more complex stuff. | I'm allowed to use the mimify library (and related ones) of the standard= =20 | Python distribution. Are you creating a MUA or MTA or some kind of hybrid (which, IMO, is bad design)? MTAs don't touch MIME. That's just part of the DATA segment of the SMTP session and they don't care what the actual data is. It is the responsibility of the client to properly encode (whether mime or not) the data for transport. Some MTAs support RFC 1652 (in conjunction with RFC 2821) to provide the 8BITMIME option. If an MTA advertises that option then it means it can accept an 8-bit data stream. Not all MTAs do that, however, and MMDF (used by a large ISP in the UK and Netherlands) is one that only properly transfers 7-bit data. Still, that shouldn't be an issue for an MTA. | Question: The user agent will use pop3 or IMAP to get the mail from the | mailbox. Is this why I have to decode Mime? No. I have courier-imap installed on my machine as an IMAP server. exim is my MTA. exim delivers the mail to a maildir format mailbox which courier understands. mutt (my MUA) also understands maildir. Of these 3 apps, only mutt understands MIME. MIME is a end user agent feature/issue and really doesn't affect the MTA or a POP/IMAP server. =20 | *** | I must implement the communication protocols using sockets, and not the= =20 | high-level mailer classes available in Python. | I'm allowed however to use any class I like for local computation, eg=20 | parsing email files and messages, searching headers, do text manipulation= ,=20 | and so on. Sounds reasonable. =20 | I'm not supposed to implement any form of error recovery or reporting.=20 That makes the project fun, but not for use in the real world :-). | While receiving messages, it is acceptable to close the connection if the= =20 | protocol is broken and to drop messages to unknown users; For an unkown user you should return a 5xx error code to the client. That is, you don't accept responsibility for the message; it is undeliverable. If you want to test it go ahead and interact with my mail server (dman.ddts.net) through telnet. | while delivering, it is enough to report to the terminal that delivery is= =20 | not possible if some serious error occur. That is convenient for you. I recommend returning the proper SMTP error code anyways. Why not impress the prof? :-) =20 | Could you please give me ideas on how to tackle this programming | exercise? I have read on Internet protocols and I'm familiar with the | Java programming language (but I must use Python!). Have you done any socket programming in Java or C? All three languages (their libraries, rather) are similar in this respect. When you open a socket connection you can get back a file-like object. With it you just read and write like you would with any other file. For an example of both server-side and client-side sockets see=20 http://www.python.org/doc/current/lib/socket-example.html =20 | Do you know any open source Python project similar to what I have to do | so that I can have a look at them? All the ones I saw use smtplib, which | I think I'm not allowed to use... No, I don't know of any. In the real world (outside of the classroom), most people try to avoid re-inventing the wheel. Since smtplib already exists, people use it rather than reimplementing it themselves. You could try reading through smtplib and see if it helps. The sockets themselves are quite easy. Start with an echo server; the socket equivalent of "hello world". Once you have that down it's just a matter of reading and writing lines of data and interpreting them according to RFC (2)821. I had to write a simple SMTP client in java for a class once. It really wasn't hard, but python's higher-level treatment of files and strings will make it even easier for you. Good luck, and don't hesitate to ask any more questions regarding SMTP. I find SMTP quite interesting. -D --=20 "...In the UNIX world, people tend to interpret `non-technical user' as meaning someone who's only ever written one device driver." --Daniel Pead =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --v9Ux+11Zm5mwPlX6 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzgHkwACgkQO8l8XBKTpRTHwQCfW+fQAjiPEvgvEfEqTmKDYxA3 vf8Ani2+WXfCIuqNucj0cksXcYPAQ4F2 =7j/D -----END PGP SIGNATURE----- --v9Ux+11Zm5mwPlX6-- From dominic.fox" Looked like this: class FSM: """A finite state machine.""" def __init__(self): self.state = '' self.states = {} def addState(self, name, rules=[]): self.states[name] = rules def addRule(self, name, rule): self.states[name].append(rule) def setState(self, state): self.state = state def receive(self, input): for nextRule in self.states[self.state]: result, toState = nextRule(input) if (result == 1): self.state = toState break The assignment rules=[] in addState was what got me. Every time I added a rule, it got added to everything... Dom --> Nobody knows the trouble you've seen / walking from your desk to the staff canteen <-- homepage: http://www.geocities.com/domfox From kalle@lysator.liu.se Mon May 13 22:48:55 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Mon, 13 May 2002 23:48:55 +0200 Subject: [Tutor] My first python gotcha In-Reply-To: <006601c1fac6$9f4a4d80$82c10550@tinypc> References: <006601c1fac6$9f4a4d80$82c10550@tinypc> Message-ID: <20020513214855.GA4862@i92.ryd.student.liu.se> [dominic.fox] > Looked like this: ... > def addState(self, name, rules=[]): > self.states[name] = rules ... > The assignment rules=[] in addState was what got me. Every time I > added a rule, it got added to everything... Yes, this is a classic. More information available here: http://python.org/doc/current/tut/node6.html#SECTION006710000000000000000 Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From pythontutor@venix.com Tue May 14 00:41:06 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 13 May 2002 19:41:06 -0400 Subject: [Tutor] COM Interfaces References: <20020512115502.12026.16431.Mailman@mail.python.org> <000701c1f9ff$48922ac0$82c10550@tinypc> <3CDFB9C7.5080700@venix.com> <001501c1fab3$4584b6e0$82c10550@tinypc> Message-ID: <3CE04F12.8050008@venix.com> I'm not going to be of much help to you. I've only used Excel, Word, and my own Python programs as COM objects. Chapter 12 of "Python Programming on Win32" discusses IID's. It also discussesIUnknown and the QueryInterface() method. "The pythoncom module is primarily concerned with exposing raw COM interfaces to Python." "win32com.client is a set of source files that use the pythoncom module ot provide additional services..." Hopefully, someone else will pick up the ball, or you will find what you are looking for in the win32 documentation. dominic.fox wrote: > Lloyd Kvam was kind enough to reply: > > >>Python depends on the registry entries to find the COM object it is >> > running. > >>The name passed to Dispatch MUST exactly match the name in the registry. >> > You > >>can't make it up. >> > > Well, this is much like creating an object in, say, VBScript or JavaScript > by passing the progid to CreateObject(). You can't do much with > multiple-interface objects in JavaScript, to my knowledge; what I was > wondering was whether PyWin & c. managed to improve on the situation. > > >>I suspect that 'MSXML2.DOMDocument30' should be 'MSXML3.DOMDocument30'. >> > If you > >>search your registry, you should be able to find the name. >> >>To run your VB COM object, you need to get it registered. Then simply >> > pass > >>the name you used to register it to dispatch, just like you did for MSXML. >> > > I can do this without difficulty for single-interface objects, but not at > all for dual or multiple interface objects. Yesterday evening I coded up a > small-ish .dll to try some of these things out with. Getting instances of > the more conventional objects by progid was a doddle. There didn't seem to > be any way at all of using the multiple-interface ones. > > Just to clarify: in VB you can do the following: > > Class MyInterface > > Public Sub DoSomethingExciting() > End Sub > > --- > > Class InheritorTheFirst > > Implements MyInterface > > Private Sub MyInterface_DoSomethingExciting() > > Msgbox "Wow!" > > End Sub > > --- > > Class InheritorTheSecond > > Implements MyInterface > > Private Sub MyInterface_DoSomethingExciting() > > Msgbox "Whoopee!" > > End Sub > > --- > > and then... > > Dim MyInstance As MyInterface > Set MyInstance = New InheritorTheSecond > MyInstance.DoSomethingExciting > Set MyInstance = New InheritorTheFirst > MyInstance.DoSomethingExciting > > --- > > MyInterface is something like an abstract base class, which simply outlines > in skeleton form the COM interface that the other two classes will use. Just > to confuse matters, they are allowed to implement as many different > interfaces as they like; they are also allowed their own 'native' COM > interface as well. The specifics of how this is implemented escape me, but I > think it has to do with the way IUnknown and IDispatch are mapped to method > calls through whatever mechanism it is that VB uses. Whatever: it's ugly, > and Python is beautiful, so I feel as if I ought to be apologising for > bringing the matter up at all... > > Now the question is, assuming I have created and registered a .dll > containing the above, and want to create an object in Python which behaves > like an instance of InheritorTheSecond, and want Python to know that I can > call MyInterface's methods on it, can I? If I can, how can I? You only get > to pass one progid to Dispatch. If it's the progid of MyInterface, you get > an instance of the base class which doesn't do anything. If it's the progid > of InheritorTheSecond, the "inherited" or "implemented" member functions are > invisible and can't be used. > > For my own purposes, it would be easy enough just to eschew this technique; > or better still, write everything in Python to begin with. But there are > other libraries out there that I didn't write, can't obtain the source code > for, and might still want to use. Some of them (like MSHTML, which gives you > access to the DOM in Internet Explorer HTML documents) use multiple > interfaces fairly extensively. It would be useful to know whether I can use > them directly in Python, or whether I'd need to come up with a set of > simplified "wrapper" classes in VB for them first. > > As an aside, the reason why VB *has* multiple interfaces is that it's a > statically typed language, which means amongst other things that, as in Java > and C++, the signatures of method function calls include the types of the > parameters being supplied (this might come as a surprise to some VB > programmers of my acquaintance, who use Variants for everything...). So if I > have a variety of different persistence mechanisms, say, which can all store > basic plain-text strings, I might want to have a method which writes a given > string in uppercase to any one of them, without needing to know what the > underlying mechanism is. If my method looks like this: > > Public Sub writeUppercase( persistenceMechanism as IPersist, stringToWrite > as String) > > IPersist.writeString strconv( stringToWrite, vbUpperCase ) > > End Sub > > then I can pass it an instance of any class that "implements" IPersist, be > it a wrapper for database access, textfile access, storing things in cells > in an Excel worksheet or whatever. In Python, which is dynamically typed, > all of this is pretty much redundant...although I did read somewhere an > article by a diehard Smalltalk enthusiast who nevertheless admitted, > vis-a-vis Java, that programming to interfaces sounded like quite a sensible > idea... > > Dominic > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From scot@possum.in-berlin.de Tue May 14 00:21:35 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Tue, 14 May 2002 01:21:35 +0200 Subject: [Tutor] "Hidden" stmpd module with Python 2.1? In-Reply-To: <20020513165512.GA4105@i92.ryd.student.liu.se> References: <200205131445.g4DEjUCr007378@charmor.internal.use> <20020513165512.GA4105@i92.ryd.student.liu.se> Message-ID: <200205140112.g4E1CRCr010039@charmor.internal.use> Hello Kalle, > If you have the time, I'm sure some contributed documentation would be > appreciated. Well, after going thru the code I'm not sure that it is acutally intended for general use yet. You might want to take a look at lines 237 to 239 - personally, I think it is funny as hell, but then not everybody might, especially if their address contains a 'stimpy'. Or, er, am I missing a joke here? > As an aside, I think you'd be better off by using a well tested SMTP > daemon with a large user base than rolling your own. I use Postfix, > and I'm happy with it. Many use sendmail, though, and I'd be a bit > surprised if the lost mail was really caused by a sendmail bug. Of course you right, but then I'm using my fury over having lost mail to constructive ends like learning more about SMTP. This is better than, say, taking a large axe to my modem. What seems to have happened (the exact details are not clear) is that while configuring the firewall and other security stuff, I screwed up either in /etc/hosts.allow or /etc/inetd.conf. So when sendmail got the mail that comes in from uucico (yeah, I'm one of those people) via rmail, sendmail didn't know where to put it. Now, I would expect sendmail to at least save it to some backup file somewhere, but no, it did a "panic" on me and "lost" the mail. /Wunderbar/. This probably doesn't qualify as a bug, but it my mind, it shouldn't have happened. But my basic problem is that sendmail is so completely overkill for a "mail leaf node" computer that doesn't forward anything to anywhere and only has one provider who is the "smart host" anyway. However, most other programs don't support uucp (anymore), and I like to pick up my mail in batches without having to worry about port scans and all the other dangers of TCP/IP (but that is a rant for another day). Actually, I don't think it should be too hard to write a crude Python program for my special situation: - Address resolution for incoming mail is reducted to the question if the user (or an alias) is on this computer or not. Any "not" is sent back with an error message. - Use standard Unix-style mailboxes. This lets the user read his mail with any POP3 capable program (kmail and pine in my case). Writing to Unix-style mailboxes can't be an insurmoutable problem, either. - Have the users use smtp for sending their mail. Anything that isn't local gets sent to the smart host, and so again address resolution is very basic. Well, there are some challenges: A surprising number of programs use the "mail" command that also interfaces with sendmail in some way that I don't think is SMTP, but that should be well documented, too. The real problem I see is the interaction with uucp. Probably what you would end up doing is invoking uucico with "--nouuxqt" so that the mail stays in the queue and is not sent to rmail, which, as the man page tells us, is "explicitly designed for use with uucp and sendmail". Then you have to write a routine that converts whatever baroque format the stuff is in into "normal" mail that can go in a mailbox. I'll play around with it for a while and if anything comes out it, I'll let you know =8). Y, Scot From scot@possum.in-berlin.de Tue May 14 03:19:03 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Tue, 14 May 2002 04:19:03 +0200 Subject: [Tutor] "Hidden" stmpd module with Python 2.1? References: <200205131445.g4DEjUCr007378@charmor.internal.use> <20020513165512.GA4105@i92.ryd.student.liu.se> Message-ID: <200205140409.g4E49tCr013019@charmor.internal.use> Hi there, I myself wrote on the subject of stmpd.py: > Well, after going thru the code I'm not sure that it is acutally > intended for general use yet. You might want to take a look at lines 237 > to 239 - personally, I think it is funny as hell, but then not everybody > might, especially if their address contains a 'stimpy'. I got feedback from Barry Warsaw: Skimpy is a debugging line that was left in by mistake =8). Y, Scot From alex@gabuzomeu.net Tue May 14 10:26:12 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Tue, 14 May 2002 11:26:12 +0200 Subject: [Tutor] Implementing a mail server in Python In-Reply-To: <20020513234303.27923.49882.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020514103934.00b768a0@pop3.norton.antivirus> Hi Alex, At 19:43 13/05/2002 -0400, you wrote: >From: "alex gigh" >Date: Mon, 13 May 2002 16:42:25 +0000 >Subject: [Tutor] Implementing a mail server in Python (socket programming) >I want to program a mail server (socket programming) writen in Python as >part of my Computer Science degree in Sussex University but I am very >unfamiliar with Python To get started with Python, you can read one of the available tutorials, eg: http://www.python.org/doc/current/tut/tut.html http://www.python.org/doc/Newbies.html >and socket programming. The book "Python Programming, 2nd edition" (by Mark Lutz, edited by O'Reilly) has information about socket programming (see Chapter 10). You may want to browse a copy to see if it's relevant for your assignment. Cheers. Alexandre From nhytro-python@web.de Tue May 14 10:59:23 2002 From: nhytro-python@web.de (Sharriff Aina) Date: Tue, 14 May 2002 11:59:23 +0200 Subject: [Tutor] dictionary swittching Message-ID: <200205140959.g4E9xNX27885@mailgate5.cinetic.de> hello! can someone tell me how to create key dependant actions? I have a dictionary that varies in contents: ## code snippet selector = ['a', 'b', 'c'] x = {'a': 1245, 'b': 'hello, 'c': 4444} if "a" in x: print 'test1' elif 'b' in x: print 'test2' elif 'c' in x: print 'test3' this does not work, any ideas? great thanks Sharriff ________________________________________________________________ Keine verlorenen Lotto-Quittungen, keine vergessenen Gewinne mehr! Beim WEB.DE Lottoservice: http://tippen2.web.de/?x=13 From python@rcn.com Tue May 14 11:07:50 2002 From: python@rcn.com (Raymond Hettinger) Date: Tue, 14 May 2002 06:07:50 -0400 Subject: [Tutor] dictionary swittching References: <200205140959.g4E9xNX27885@mailgate5.cinetic.de> Message-ID: <000701c1fb2f$35416f40$33d8accf@othello> The dispatcher part looks pretty good as is. The 'hello' is missing the close quote. I can't see from your example the role that selector plays or the purpose of the values like 1245 and 4444. Can you show us what output you want from inputs x and selector? Also, which version of Python are you using? Raymond Hettinger ----- Original Message ----- From: "Sharriff Aina" To: Sent: Tuesday, May 14, 2002 5:59 AM Subject: [Tutor] dictionary swittching > hello! > can someone tell me how to create key dependant actions? I have a dictionary that varies in contents: > > ## code snippet > > selector = ['a', 'b', 'c'] > > x = {'a': 1245, 'b': 'hello, 'c': 4444} > > if "a" in x: > print 'test1' > elif 'b' in x: > print 'test2' > elif 'c' in x: > print 'test3' > > this does not work, any ideas? > > > great thanks > > > Sharriff > ________________________________________________________________ > Keine verlorenen Lotto-Quittungen, keine vergessenen Gewinne mehr! > Beim WEB.DE Lottoservice: http://tippen2.web.de/?x=13 > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From lumbricus@gmx.net Tue May 14 11:27:54 2002 From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=) Date: Tue, 14 May 2002 12:27:54 +0200 (MEST) Subject: [Tutor] dictionary swittching References: <200205140959.g4E9xNX27885@mailgate5.cinetic.de> Message-ID: <8632.1021372074@www9.gmx.net> > hello! Hello! > can someone tell me how to create key dependant actions? I have a > dictionary that varies in contents: > > ## code snippet > > selector = ['a', 'b', 'c'] You don't use this. > x = {'a': 1245, 'b': 'hello, 'c': 4444} > > if "a" in x: if "a" in x.keys(): print "Does that do what you want?" > print 'test1' > elif 'b' in x: > print 'test2' > elif 'c' in x: > print 'test3' > > this does not work, any ideas? > > > great thanks > > > Sharriff HTH, HAND and Greetings, J"o! -- None -- GMX - Die Kommunikationsplattform im Internet. http://www.gmx.net From iumarumo@eidosnet.co.uk Tue May 14 11:26:51 2002 From: iumarumo@eidosnet.co.uk (ibraheem umaru-mohammed) Date: Tue, 14 May 2002 11:26:51 +0100 Subject: [Tutor] dictionary swittching In-Reply-To: <200205140959.g4E9xNX27885@mailgate5.cinetic.de> References: <200205140959.g4E9xNX27885@mailgate5.cinetic.de> Message-ID: <20020514102651.GG7258@micromuse.com> [Sharriff Aina wrote...] -| hello! -| can someone tell me how to create key dependant actions? I have a dictionary that varies in contents: -| -| ## code snippet -| -| selector = ['a', 'b', 'c'] -| -| x = {'a': 1245, 'b': 'hello, 'c': 4444} -| -| if "a" in x: -| print 'test1' -| elif 'b' in x: -| print 'test2' -| elif 'c' in x: -| print 'test3' -| -| this does not work, any ideas? -| -| -| great thanks -| -| -| Sharriff This only works as if under python2.2, where the in operator now works on dictionary objects, so: "key in dict" is now the same as "dict.has_key(key)" So assume your code is for an earlier version of python, you can change it to the following: -- cut -- selector = ['a', 'b', 'c'] x = {'a': 1245, 'b': 'hello, 'c': 4444} if "a" in x.keys(): print 'test1' elif 'b' in x.keys(): print 'test2' elif 'c' in x.keys(): print 'test3' -- cut -- or IMO, even better: -- cut -- selector = ['a', 'b', 'c'] x = {'a': 1245, 'b': 'hello, 'c': 4444} if x.has_key('a'): print "test1" elif x.has_key('b'): print "test2" elif x.has_key('c'): print "test3" -- cut -- HTH, --ibs. -- ibraheem umaru-mohammed www.micromuse.com --0-- From erikprice@mac.com Tue May 14 12:09:47 2002 From: erikprice@mac.com (Erik Price) Date: Tue, 14 May 2002 07:09:47 -0400 Subject: [Tutor] Implementing a mail server in Python In-Reply-To: <4.3.2.7.2.20020514103934.00b768a0@pop3.norton.antivirus> Message-ID: <1A72D915-672B-11D6-A35E-00039351FE6A@mac.com> On Tuesday, May 14, 2002, at 05:26 AM, Alexandre Ratti wrote: > The book "Python Programming, 2nd edition" (by Mark Lutz, edited by > O'Reilly) has information about socket programming (see Chapter 10). > You may want to browse a copy to see if it's relevant for your > assignment. While you're there, look at "Python Web Programming" (New Riders), the first few chapters are an intro to Python (for experienced programmers) and the rest of the book deals extensively with the socket APIs. Perhaps from this you can see how to "roll your own" as it were. Erik From kalle@lysator.liu.se Tue May 14 12:04:34 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Tue, 14 May 2002 13:04:34 +0200 Subject: [Tutor] dictionary swittching In-Reply-To: <8632.1021372074@www9.gmx.net> References: <200205140959.g4E9xNX27885@mailgate5.cinetic.de> <8632.1021372074@www9.gmx.net> Message-ID: <20020514110434.GA2060@i92.ryd.student.liu.se> [Jörg Wölke] > if "a" in x.keys(): > print "Does that do what you want?" Don't do that, it's O(N). First it gets all the keys from the dict, which is linear time. Then it does a linear search through the resulting list to see if "a" is a member. Use if x.has_key("a"): which is O(1), it uses hashing. if "a" in x: does the right thing in Python 2.2. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From nhytro-python@web.de Tue May 14 12:17:06 2002 From: nhytro-python@web.de (Sharriff Aina) Date: Tue, 14 May 2002 13:17:06 +0200 Subject: [Tutor] dictionary swittching Message-ID: <200205141117.g4EBH5X09374@mailgate5.cinetic.de> Thanks for the replies, unfortunately none of the suggestions work. Actual= ly the snippet is for a CGI script that takes values from a form. I would = like different actions to be taken depending on the values of the keys: ##snippet ## below is used to convert the form output to a user friendlier dictionar= y ## code thanks to the python list def FieldStorage2Dict(form): d =3D {} def decode=5Ffield(field): if isinstance(field, type([])): return map(decode=5Ffield, field) elif hasattr(field, "file") and field.file: return (field.filename, field.file) else: return field.value for key in form.keys(): d[key] =3D decode=5Ffield(form[key]) return d formdict =3D FieldStorage2Dict(form)=20 #selector =3D ['agentnum','bnumber', 'tname', 'tvorname', 'tnumber', 'vnumbe= r'] # these are the name values in the html form here just for clarity if formdict.has=5Fkey('agentnum'): print 'test1' elif formdict.has=5Fkey('bnumber'): print 'test2' elif formdict.has=5Fkey('tname'): print 'test3'=20 ##end snippet sadly, only the first "if" works, I=B4m running Python 2.1.1 on a Wintel mac= hine=20 thanks =5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F Keine verlorenen Lotto-Quittungen, keine vergessenen Gewinne mehr!=20 Beim WEB.DE Lottoservice: http://tippen2.web.de/=3Fx=3D13 From python@rcn.com Tue May 14 12:22:25 2002 From: python@rcn.com (Raymond Hettinger) Date: Tue, 14 May 2002 07:22:25 -0400 Subject: [Tutor] dictionary swittching References: <200205141117.g4EBH5X09374@mailgate5.cinetic.de> Message-ID: <004201c1fb39$a0871700$33d8accf@othello> Try changing all the 'elif' to 'if'. Raymond Hettinger ----- Original Message ----- From: "Sharriff Aina" To: Sent: Tuesday, May 14, 2002 7:17 AM Subject: Re: [Tutor] dictionary swittching Thanks for the replies, unfortunately none of the suggestions work. Actually the snippet is for a CGI script that takes values from a form. I would like different actions to be taken depending on the values of the keys: ##snippet ## below is used to convert the form output to a user friendlier dictionary ## code thanks to the python list def FieldStorage2Dict(form): d = {} def decode_field(field): if isinstance(field, type([])): return map(decode_field, field) elif hasattr(field, "file") and field.file: return (field.filename, field.file) else: return field.value for key in form.keys(): d[key] = decode_field(form[key]) return d formdict = FieldStorage2Dict(form) #selector = ['agentnum','bnumber', 'tname', 'tvorname', 'tnumber', 'vnumber'] # these are the name values in the html form here just for clarity if formdict.has_key('agentnum'): print 'test1' elif formdict.has_key('bnumber'): print 'test2' elif formdict.has_key('tname'): print 'test3' ##end snippet sadly, only the first "if" works, I´m running Python 2.1.1 on a Wintel machine thanks ________________________________________________________________ Keine verlorenen Lotto-Quittungen, keine vergessenen Gewinne mehr! Beim WEB.DE Lottoservice: http://tippen2.web.de/?x=13 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From nhytro-python@web.de Tue May 14 12:47:00 2002 From: nhytro-python@web.de (Sharriff Aina) Date: Tue, 14 May 2002 13:47:00 +0200 Subject: [Tutor] dictionary swittching Message-ID: <200205141147.g4EBl0X12811@mailgate5.cinetic.de> ..Thanks Raymond! that did the trick, would it be advisable to upgrade to python 2.2? Thanks Sharriff ________________________________________________________________ Keine verlorenen Lotto-Quittungen, keine vergessenen Gewinne mehr! Beim WEB.DE Lottoservice: http://tippen2.web.de/?x=13 From dman@dman.ddts.net Tue May 14 13:20:07 2002 From: dman@dman.ddts.net (dman) Date: Tue, 14 May 2002 07:20:07 -0500 Subject: [Tutor] dictionary swittching In-Reply-To: <200205141147.g4EBl0X12811@mailgate5.cinetic.de> References: <200205141147.g4EBl0X12811@mailgate5.cinetic.de> Message-ID: <20020514122007.GB22242@dman.ddts.net> --+g7M9IMkV8truYOl Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, May 14, 2002 at 01:47:00PM +0200, Sharriff Aina wrote: | ..Thanks Raymond! that did the trick, Yeah, if you say "else" it means "else". In more detail : if : elif : : else : This is the complete structure of an "if" statement. The elif and else sections are optional, the elif section can be repeated as desired. "elif" is short for "else-if". Here's how it evaluates : 1) is true? if yes then goto 2 if no then goto 3 2) execute code in goto 6 3) is true (AND is false)? if yes then goto 4 if no then goto 5 4) execute code in goto 6 5) ( and were false) execute 6) done (don't do anything more) This is basically how non-structured code is written (BASIC, M68K assembly). I'm sure you appreciate structure after trying to follow it :-). Hmm, maybe the on-line doc will do a better job of explaining the specific semantics of an "if" statement and the meaning of 'elif' and 'else'. | would it be advisable to upgrade to python 2.2? Yes. That has nothing to do with the problem you had, though. HTH, -D --=20 Better a little with righteousness than much gain with injustice. Proverbs 16:8 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --+g7M9IMkV8truYOl Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzhAPcACgkQO8l8XBKTpRRArACgleKrtvGHlEjK+ICNIex4XpoD RXYAnjUZCfB8/9x0cykFtHViat6uoM+Z =z1Yp -----END PGP SIGNATURE----- --+g7M9IMkV8truYOl-- From python@rcn.com Tue May 14 17:17:08 2002 From: python@rcn.com (Raymond Hettinger) Date: Tue, 14 May 2002 12:17:08 -0400 Subject: [Tutor] dictionary swittching References: <200205141147.g4EBl0X12811@mailgate5.cinetic.de> Message-ID: <002101c1fb62$ccb58720$8861accf@othello> Your welcome. Yes. Python 2.2 is a very worthwhile upgrade: type/class unification, __slots__, properties, generators, iterators, key in dict, help, and explicit floor division. All of these things can improve your Python life. Raymond Hettinger ----- Original Message ----- From: "Sharriff Aina" To: Sent: Tuesday, May 14, 2002 7:47 AM Subject: Re: [Tutor] dictionary swittching > ..Thanks Raymond! that did the trick, would it be advisable to upgrade to python 2.2? > > Thanks > > > Sharriff > ________________________________________________________________ > Keine verlorenen Lotto-Quittungen, keine vergessenen Gewinne mehr! > Beim WEB.DE Lottoservice: http://tippen2.web.de/?x=13 > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dman@dman.ddts.net Tue May 14 19:51:15 2002 From: dman@dman.ddts.net (dman) Date: Tue, 14 May 2002 13:51:15 -0500 Subject: [Tutor] getting access violation error in kernel32.dll while debugging In-Reply-To: <3CDFE2A4.3030500@gmx.de> References: <3CDFE2A4.3030500@gmx.de> Message-ID: <20020514185115.GA3693@dman.ddts.net> --gKMricLos+KVdGMg Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 13, 2002 at 05:58:28PM +0200, Marcus K. wrote: | Hi ! |=20 | I want to embbed C source code with a python script, named=20 | modulefile.py. =2E.. | After the debugger reaches the statemant: |=20 | res =3D PyRun_SimpleFile(fp,"modulefile.py"); |=20 | I get a acess violation error in kernel32.dll. Have anyone got an idea=20 | what happend ? I pity you. What happened is Windows! A friend of mine had a job for a while in which he did windows-based C++ work. He managed to generate that error more than once. (he now hates windows and doesn't want to develop on it again) The short of it is : a bug in your program triggers a bug in the windows kernel and it dies horridly giving you no help whatsoever. | Here=B4s the intresting part of my c code: =20 | FILE *fp =3D NULL; =20 | fp =3D fopen("modulefile.py","r"); | res =3D PyRun_SimpleFile(fp,"modulefile.py"); You don't check to see if fopen() returned an error. It could be that 'fp' is NULL at that point. My recommendation, since the debugger isn't going to help on windows, is to use the print technique for debugging. Slap a whole bunch of print statemtents in your code (and remember to flush the streams!) so you can see precisely what is going on. HTH, -D --=20 He who scorns instruction will pay for it, but he who respects a command is rewarded. Proverbs 13:13 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --gKMricLos+KVdGMg Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzhXKMACgkQO8l8XBKTpRTY6gCdFKBVgshDHiUOSf5BKPNU5/K8 ZOQAnjF80hF9FNuayxknSW329hvzYmG8 =MoBq -----END PGP SIGNATURE----- --gKMricLos+KVdGMg-- From m_konermann@gmx.de Tue May 14 19:58:40 2002 From: m_konermann@gmx.de (Marcus) Date: Tue, 14 May 2002 20:58:40 +0200 Subject: [Tutor] Using two different python.exe on a windows installer version ? Message-ID: <3CE15E60.9090603@gmx.de> Hi ! About one month ago i installed the windows installer version of python ver 2.2.1. Yesterday i generated a python.exe using pcbuild.dsw. Now my question: Is it possible to run the windows installer version with a self generated python.exe ? Thanks and greetings Marcus From dman@dman.ddts.net Tue May 14 20:30:28 2002 From: dman@dman.ddts.net (dman) Date: Tue, 14 May 2002 14:30:28 -0500 Subject: [Tutor] COM Interfaces In-Reply-To: <001501c1fab3$4584b6e0$82c10550@tinypc> References: <20020512115502.12026.16431.Mailman@mail.python.org> <000701c1f9ff$48922ac0$82c10550@tinypc> <3CDFB9C7.5080700@venix.com> <001501c1fab3$4584b6e0$82c10550@tinypc> Message-ID: <20020514193028.GB3693@dman.ddts.net> --1LKvkjL3sHcu1TtY Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 13, 2002 at 08:20:40PM +0100, dominic.fox wrote: =20 | Just to clarify: in VB you can do the following: =2E.. [SI and dynamic type example in VB] | Whatever: it's ugly, | and Python is beautiful, so I feel as if I ought to be apologising for | bringing the matter up at all... Python supports dynamic typing like you demonstrated, and it supports Multiple Inheritance too. All you've got left to figure out is how to deal with COM. | The specifics of how this is implemented escape me, but I think it | has to do with the way IUnknown and IDispatch are mapped to method | calls through whatever mechanism it is that VB uses. I haven't done any hands-on COM work (and I hope I never have to) but I think you need to use QueryInterface() to obtain a reference to the side of an object that implements a different interface than the one you have right now. I think that's a COM limitation in the way it handles MI, not a python thing. Just FYI here's your example in Python (I think, I don't know VB) : class MyInterface : def DoSomthingExciting( self ) :=20 # python doesn't yet have "interfaces" or "abstract classes", # so instead I define the method to indicate (at runtime) that # it isn't defined raise NotImplementedError class InheritorTheFirst( MyInterface ) : # oh, yeah, python doesn't have "private" stuff. Of the languages # that try to manage access control, only Eiffel got it right. def DoSomethingExciting( self ) : print "Wow!" class InheritorTheSecond( MyInterface ) : def DoSomethingExciting( self ) : print "Whoopee!" def foo( self ) : print "we need a different name or else we can't identify the metho= d" MyInstance =3D InheritorTheSecond() MyInstance.DoSomethingExciting() MyInstance =3D InheritorTheFirst() MyInstance.DoSomethingExciting() # now show how MI works : class MultipleInheritor( InheritorTheFirst , InheritorTheSecond ) : # the super classes provide all the implementation we need pass MyInstance =3D MultipleInheritor() MyInstance.DoSomethingExciting() # this will have different semantics with # "classic" classes and "new-style" classes MyInstance.foo() Here are a few things to note about these examples : o 3 objects are created, but only one exists at a given time o there is one name that referes to each of the objects, one at a time o the single inheritance isn't very interesting in this example. In fact it is pointless in python because of the dynamic typing. Inheritance is useful when you want to use the existing implementation of a class and extend it. The multiple inheritance shows that -- by extending both classes the subclass has both methods. o In the MI example, the InheritorTheFirst's method will be found because it is listed first in the inheritance tree. If you use python 2.2 and make the base interface extend 'object' then (IIRC) both methods will be found and called in order. COM behaves more like your VB example because you can't have a reference to both interfaces at the same time (with the same variable name), but it is different because you simply QueryInterface the object to get the reference you want, rather than creating a new object. HTH, -D --=20 How to shoot yourself in the foot with Java: You find that Microsoft and Sun have released incompatible class libraries both implementing Gun objects. You then find that although there are plenty of feet objects implemented in the past in many other languages, you cannot get access to one. But seeing as Java is so cool, you don't care and go around shooting anything else you can find. (written by Mark Hammond) =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --1LKvkjL3sHcu1TtY Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzhZdQACgkQO8l8XBKTpRS/tQCgpyLKoBL6DGV4180qQ2eweNdQ 8t0An3fAUfENI/C/3mj0ebUchvthKhgE =qORt -----END PGP SIGNATURE----- --1LKvkjL3sHcu1TtY-- From dominic.fox" <000701c1f9ff$48922ac0$82c10550@tinypc> <3CDFB9C7.5080700@venix.com> <001501c1fab3$4584b6e0$82c10550@tinypc> <3CE04F12.8050008@venix.com> Message-ID: <003b01c1fb83$4b1f13e0$b47869d5@tinypc> From: "Lloyd Kvam" To: "dominic.fox" Cc: Sent: Tuesday, May 14, 2002 12:41 AM Subject: Re: [Tutor] COM Interfaces > I'm not going to be of much help to you. Thanks for trying! - I guess I'll have to save up for the full reference after all. It was a pretty fair bet that the topic would be covered *somewhere* - I just couldn't find anything in the online docs, and wondered if anyone had any experience with the matter. It is still extremely cool to be able to automate Excel from within Python... Dominic From snoopyboy21@earthlink.net Wed May 15 00:32:28 2002 From: snoopyboy21@earthlink.net (Zachary Cousins) Date: Tue, 14 May 2002 18:32:28 -0500 Subject: [Tutor] Executing Programs Message-ID: <003401c1fb9f$9c6178d0$8405fea9@Laddie> This is a multi-part message in MIME format. ------=_NextPart_000_0031_01C1FB75.B36CC540 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable how do you execute a saved *.txt file from my hardrive? what do I type? = I tried 'open' but all it says is type 'file' and if I do it doesn't = work and gives me an error message. ------=_NextPart_000_0031_01C1FB75.B36CC540 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
how do you execute a saved *.txt file = from my=20 hardrive? what do I type? I tried 'open' but all it says is type 'file' = and if I=20 do it doesn't work and gives me an error = message.
------=_NextPart_000_0031_01C1FB75.B36CC540-- From erikprice@mac.com Wed May 15 02:45:29 2002 From: erikprice@mac.com (Erik Price) Date: Tue, 14 May 2002 21:45:29 -0400 Subject: [Tutor] dictionary swittching In-Reply-To: <20020514122007.GB22242@dman.ddts.net> Message-ID: <6FFAC555-67A5-11D6-BF87-00039351FE6A@mac.com> On Tuesday, May 14, 2002, at 08:20 AM, dman wrote: > Hmm, maybe the on-line doc will do a better job of explaining the > specific semantics of an "if" statement and the meaning of 'elif' and > 'else'. How about: if (condition1): execute green code elif (condition2): execute orange code elif (condition3): execute red code else: execute blue code is equivalent to if (condition1): execute green code else: if (condition2): execute orange code else: if (condition3): execute red code else: execute blue code Erik From idiot1@netzero.net Wed May 15 05:12:51 2002 From: idiot1@netzero.net (kirk Bailey) Date: Wed, 15 May 2002 00:12:51 -0400 Subject: [Tutor] Email list functions Message-ID: <3CE1E043.127EC60B@netzero.net> OK, thinking about lists, and 2 new functions, digests and archives. Archives are pretty simple. IF a file exists, ( such as '(listname).archive') we append a copy of the complete assembled message to it IN THAT FILE. So much for building the archive. We also create an alias; '(listname)-archive'. Anyone wishing to examine it sends a email to it. We have an autoreply program sitting in the alias pointed at the archive program; said archive is the reply to the request. As for digests, this is still under the microscope, but it's not too hard at all. Just how important do y'all feel this sort of thig is to add to TL? -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ NOTE: By sending SPAM to this address you agree to pay me a service fee of $100 for the service of receiving, storing, examining, and deleting your piece of SPAM. I am a postmaster, and take a dim view of such. From gncuster@firehead.org Wed May 15 05:41:52 2002 From: gncuster@firehead.org (Nate Custer) Date: 14 May 2002 23:41:52 -0500 Subject: [Tutor] Callbacks in a python module Message-ID: <1021437712.2094.5.camel@gncuster> Hey all, I like using callbacks in my pygtk programs, is there any way a python module can do the same thing? Specificly I need a class in one module to call a fcn in a different module. Here is the object tree: tn5250py \ |-lib5250 | \ | |-called from here | |-5250gui \ |- here is screen refesh method. What is the best way to do this? best regards, Nate Custer From nntp@stone.nu Mon May 13 10:40:35 2002 From: nntp@stone.nu (Fredrik Steen) Date: Mon, 13 May 2002 11:40:35 +0200 Subject: [Tutor] Re: Numbers of active threads References: Message-ID: On Sat, 11 May 2002 20:25:20 +0200, A wrote: > Hi, > I use threading module and I need to control numbers of active threads. > Can you please give me an example how to do that. Thank you Ladislav You could probably use the activeCount() from the threading module. ./fs From bembry@bembry.org Mon May 13 13:55:30 2002 From: bembry@bembry.org (Bryce Embry) Date: Mon, 13 May 2002 07:55:30 -0500 Subject: [Tutor] Self Executing programs In-Reply-To: <20020513012621.66609.qmail@web20904.mail.yahoo.com> References: <20020512115502.12026.16431.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20020513075341.00ae3348@www.bembry.org> --=====================_14021191==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed Try py2exe. You'll need to download it from http://starship.python.net/crew/theller/py2exe/ , and the directions for its use are on the site, but it does a good job of converting .py files into .exe for sharing with other Windows users. Bryce At 08:26 PM 5/12/2002, you wrote: >Hi people, > >How can I make a program that is able to run on a computer that does not >have python installed. So that I am able to bring little bits of code >over to my friends and show it in action to him. On a machine running >windows. > >Pre-Thanks > >Derek Hoffmeister > > > >Do You Yahoo!? >LAUNCH - Your Yahoo! >Music Experience -------------------------------------------------------------------------------------------- "Lord, you establish peace for us. All that we have accomplished you have done for us" -- Isaiah 26:12 --=====================_14021191==_.ALT Content-Type: text/html; charset="us-ascii" Try py2exe.  You'll need to download it from http://starship.python.net/crew/theller/py2exe/ , and the directions for its use are on the site, but it does a good job of converting .py files into .exe for sharing with other Windows users.

Bryce

At 08:26 PM 5/12/2002, you wrote:

Hi people,

How can I make a program that is able to run on a computer that does not have python installed.  So that I am able to bring little bits of code over to my friends and show it in action to him.  On a machine running windows.

Pre-Thanks

Derek Hoffmeister



Do You Yahoo!?
LAUNCH - Your Yahoo! Music Experience

--------------------------------------------------------------------------------------------
"Lord, you establish peace for us.
All that we have accomplished
you have done for us" -- Isaiah 26:12 --=====================_14021191==_.ALT-- From jbarbour@gladstone.ucsf.edu Mon May 13 20:02:50 2002 From: jbarbour@gladstone.ucsf.edu (Jason Barbour) Date: Mon, 13 May 2002 12:02:50 -0700 Subject: [Tutor] appending lists of objects Message-ID: Hello all, I am having trouble appending a list of class objects. I am using deepcopy on a list of objects which were successfully created, but when I print out the list, I just get pointers to the instantiation. Is there a way to get my append strategy to work? Thanks Jason class: class ANN: def __init__(self): self.numero = None self.inputs = [] self.weights = [] # or make bias as the last input, or first [0] self.bias = None # make a variable to store the 'true' answer self.verdad = None code: def InitializeTopology(datalist, num_nodes): # datalist is 'rawlist' # num_nodes is 'hidden_nodes' # take the length of the [0] element # of datalist, where input data is kept # to determine input unit number input_units = len(datalist[0]) output_units = len(datalist[1]) # List which will hold the entire network NN = [[]] # Temp lists to append to NN ent = [] out = [] hid = [] # NN example counter j = 0 print datalist # loop through each datalist element for i in range(len(datalist)): NN.append([]) # loop through input list within datalist element ent = [] for e in (range(input_units)): ent.append(datalist[i][e]) print "Input Nodes" print ent entx = copy.deepcopy(ent) NN[j].append(entx) # loop through desired hid node list and # instantiate and append that number hid = [] for h in (range(num_nodes)): # hnode is a temp instantiation hnode = ANN() # set numero hnode.numero = h # add one extra for the bias node for d in range(len(datalist[i][0])): # set random weights hnode.weights.append(GetRandom()) hid.append(hnode) # this works fine print "Hidden Node Weights" print hid[h].weights hidx = copy.deepcopy(hid) NN[j].append(hidx) # loop through output list within datalist element out = [] for s in (range(output_units)): # temp instantiation of node class onode = ANN() # set numero onode.numero = s # write 'true' value for this node in from datalist onode.verdad = datalist[i][1] # add one extra for the bias node for hi in range(len(hid) + 1): # set random weights onode.weights.append(GetRandom()) ond = copy.deepcopy(onode) out.append(ond) print "Output Node Weights" print out[s].weights outx = copy.deepcopy(out) NN[j].append(outx) j = j + 1 # when I view the final list, # i only see the pointers shown at the # end of the output below print NN print NN[0][1] return NN output: Input Nodes [['0', '1', '0', '1', '0', '1'], ['1']] Hidden Node Weights [-0.018296596687270905, -0.081403175088918187, -0.053187146906907665, 0.056229649302163988, -0.075566267128166456, -0.022527181800035524] Hidden Node Weights [-0.0065363445994707451, 0.069861139620503818, 0.0024552409969152309, 0.076356456899948924, -0.069533002904092575, -0.014238828091323708] Hidden Node Weights [-0.075400889950218292, -0.050053122099344274, -0.0048485866459656354, 0.08662597642000594, -0.017859878096892778, 0.055191369394788102] Output Node Weights [0.037663575883956704, 0.039522195201120526, 0.052848206171747923, - 0.01037766943868983] Output Node Weights [-0.078275023370294267, 0.069305743921806412, 0.025268759536601591, 0.056177439285214084] Input Nodes [['1', '0', '1', '0', '1', '0'], ['0']] Hidden Node Weights [0.081712459684275235, -0.073062555492460518, -0.089030582658396876, - 0.080425085755549922, -0.05533052873035009, 0.0087849646658016093] Hidden Node Weights [-0.00023837933585462155, 0.097517550486271948, 0.090236482283893277, 0.089746470744624232, -0.014322076190345668, -0.050886396966472083] Hidden Node Weights [0.00011939214512719509, 0.040501166817123305, -0.095668774128323864, 0.078139479446892604, 0.08745296237997438, -0.018099444839937705] Output Node Weights [-0.027795386749378048, -0.015904567714063299, 0.069970274891191647, - 0.0051844350890069887] Output Node Weights [0.062263405185009335, -0.070228462857787652, -0.058050767060430421, 0.092388392928725957] Input Nodes [['0', '1', '1', '0', '1', '1'], ['1']] Hidden Node Weights [-0.014520789653509381, 0.050637826018312279, -0.096331315026787184, - 0.015789978617662914, -0.080072518921819588, 0.057655140839156793] Hidden Node Weights [0.077143949905593145, -0.052093418319049123, 0.021041221782613872, - 0.073784377429996467, 0.081250167691744937, -0.073069394523676903] Hidden Node Weights [0.079183132057173283, -0.064352582341993106, -0.047743468583672025, 0.056374150998905657, -0.089680772685834367, 0.093224700033546687] Output Node Weights [0.031468967429602215, 0.037860013704278585, 0.026289431822902287, 0.047595309078331482] Output Node Weights [0.022103436047705573, 0.080429621649877797, -0.032776026302476426, - 0.044834187905566168] Input Nodes [['1', '1', '0', '0', '1', '0'], ['0']] Hidden Node Weights [-0.09723932133933047, 0.082793639556330317, -0.014779765311136072, 0.05815203111935676, 0.093341660960959721, -0.041596612150172387] Hidden Node Weights [-0.033319581113907759, 0.035324831017861325, -0.093066597933479517, 0.055496245555570048, 0.067858476165719578, -0.066920463380311906] Hidden Node Weights [-0.0266917262783797, 0.051820006475687741, -0.0093643674736724417, 0.084802963987182942, 0.029095629325276783, -0.057989083104446948] Output Node Weights [-0.09894360261541886, -0.096914462031604504, 0.059415174380555588, - 0.0036597219717522389] Output Node Weights [-0.015256824879165975, 0.010845872845301941, -0.029854732686460394, - 0.070282855919804182] [[[['0', '1', '0', '1', '0', '1'], ['1']], [<__main__.ANN instance at 0x02E02340 >, <__main__.ANN instance at 0x02E67500>, <__main__.ANN instance at 0x02E67150 >], [<__main__.ANN instance at 0x02E62B20>, <__main__.ANN instance at 0x02E641A0 >]], [[['1', '0', '1', '0', '1', '0'], ['0']], [<__main__.ANN instance at 0x02E12120>, <__main__.ANN instance at 0x02E13C40>, <__main__.ANN instance at 0x02E11360>], [<__main__.ANN instance at 0x02E654D0>, <__main__.ANN instance at 0x02E90EF0>]], [[['0', '1', '1', '0', '1', '1'], ['1']], [<__main__.ANN instance at 0x02EA51E0>, <__main__.ANN instance at 0x02EA6EA0>, <__main__.ANN instance at 0x02EA6C10>], [<__main__.ANN instance at 0x02DF75A0>, <__main__.ANN instance at 0x02DF7390>]], [[['1', '1', '0', '0', '1', '0'], ['0']], [<__main__.ANN instance at 0x02EB6F80>, <__main__.ANN instance at 0x02EB6D10>, <__main__.ANN instance at 0x02EB6A50>], [<__main__.ANN instance at 0x02DF53A0>, <__main__.ANN instance at 0x02E138F0>]], []] [<__main__.ANN instance at 0x02E02340>, <__main__.ANN instance at 0x02E67500>, <__main__.ANN instance at 0x02E67150>] From viera76@hotmail.com Tue May 14 04:58:41 2002 From: viera76@hotmail.com (aileen viera) Date: Tue, 14 May 2002 03:58:41 +0000 Subject: [Tutor] Help I am a newbie Message-ID:

Hi. I just started yesterday and I am attempting exercise 2, which wants me to Write a program that reads 100 numbers from the user and prints out the sum.  I can't quite figure this out can you help me?


MSN Photos is the easiest way to share and print your photos: Click Here
From ajs@ix.netcom.com Tue May 14 13:31:59 2002 From: ajs@ix.netcom.com (Netcom) Date: Tue, 14 May 2002 08:31:59 -0400 Subject: [Tutor] Looking for hints Message-ID: <000801c1fb43$598bcf80$a400a8c0@Arts> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C1FB21.D07ED4B0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am needing to track dependencies within a program. Meaning -=20 let's say I have 4 instances of a "point" class (each with its own position) , which in turn are used to create 2 line instances (each = take 2 of the points as input). The intersection of the 2 lines = determine another point instance. One of the original points is moved. As of now, there is a routine to recalculate the new position of everything when anything in the scene is moved. I would like things to be smarter - for the program to determine which instances are directly or indirectly effected by the change in position of a scene element, and only go through the full "update" routine for those instances. Guess I suspect this is a form of a relatively common=20 programming issue, and would appreciate hints. Even the proper terminology for a google search on this kind of issue woiuld be of great help. Art ------=_NextPart_000_0005_01C1FB21.D07ED4B0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I am needing to track dependencies = within a=20 program.
 
Meaning -
 
let's say I have 4 instances of a = "point" class=20 (each with its
own position) , which in turn are used to create 2 line instances (each take = 2 of the points as input). The intersection of the = 2 lines determine another point=20 instance.
 
One of the original points is = moved.  As of=20 now, there
is a routine to recalculate the new = position of=20 everything
when anything in the scene is = moved.
 
I would like things to be smarter - for = the program=20 to
determine which instances are directly = or=20 indirectly
effected by the change in position of a = scene=20 element, and
only go through the full "update" = routine for=20 those
instances.
 
Guess I suspect this is a form of a = relatively=20 common
programming issue, and would appreciate = hints.  Even
the proper terminology for a google = search on=20 this
kind of issue woiuld be of great = help.
 
Art
------=_NextPart_000_0005_01C1FB21.D07ED4B0-- From idiot1@netzero.net Wed May 15 06:45:33 2002 From: idiot1@netzero.net (kirk Bailey) Date: Wed, 15 May 2002 01:45:33 -0400 Subject: [Tutor] Minor update Message-ID: <3CE1F5FD.CDED8B5D@netzero.net> I made a new logo for the site- and conveted it into the .png format. I am going to convert all images to png or jpeg, most likely png, except animated gif banners. Also, I am working on creating a simple system for archives and for digests. Input eagerly saught on all of this, so fire away, direct or on (tinylist-foo) list! -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ NOTE: By sending SPAM to this address you agree to pay me a service fee of $100 for the service of receiving, storing, examining, and deleting your piece of SPAM. I am a postmaster, and take a dim view of such. From shalehperry@attbi.com Wed May 15 07:54:28 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 14 May 2002 23:54:28 -0700 (PDT) Subject: [Tutor] Help I am a newbie In-Reply-To: Message-ID: On 14-May-2002 aileen viera wrote: >
Hi. I just started yesterday and I > am attempting exercise 2, which wants me to Write a program that reads 100 > numbers from the user and prints out the sum.  I can't quite figure this > out can you help me?


MSN Photos is the easiest > way to share and print your photos: href='http://g.msn.com/1HM100901/157'>Click Here
> 1) kill the icky html mail (-: 2) show us what you have and point out where you are having problems. Otherwise we just write it for you and you do not learn anything,. From shalehperry@attbi.com Wed May 15 07:56:22 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 14 May 2002 23:56:22 -0700 (PDT) Subject: [Tutor] Callbacks in a python module In-Reply-To: <1021437712.2094.5.camel@gncuster> Message-ID: On 15-May-2002 Nate Custer wrote: > Hey all, > > I like using callbacks in my pygtk programs, is there any way a python > module can do the same thing? Specificly I need a class in one module to > call a fcn in a different module. > A call back is simply a stored name for a function. import foo callback_store(action, foo.func) callback_act(action) what are you not understanding? From alex@gabuzomeu.net Wed May 15 09:31:41 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Wed, 15 May 2002 10:31:41 +0200 Subject: [Tutor] Executing Programs In-Reply-To: <20020515052818.9241.64855.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020515101313.00c00b90@pop3.norton.antivirus> Hi Zachary, At 01:28 15/05/2002 -0400, you wrote: >From: "Zachary Cousins" >Date: Tue, 14 May 2002 18:32:28 -0500 >Subject: [Tutor] Executing Programs >how do you execute a saved *.txt file from my hardrive? Do you mean "how do I open a .txt file in an editor from Python"? Try this (on Windows): thePath = r"c:\temp\toto.txt" # Import a tool module from the library import os # Run a system command from Python # %s is replace by the file path os.system("notepad %s" % thePath) For more information, see: - Python Tutorial: http://www.python.org/doc/current/tut/tut.html - Tools available in the standard library: http://www.python.org/doc/current/modindex.html >what do I type? >I tried 'open' but all it says is type 'file' and if I do it doesn't >work and gives me an error message. Or do you mean "how do I read the content of a .txt file from Python"? In this case, try this: thePath = r"c:\temp\toto.txt" # Get a file object in read mode fileObj = open(thePath, 'r') # Read lines from the text file lineList = fileObj.readlines() # Print them out one by one for aLine in lineList: print aLine If I misunderstood your question, please give us more details. Cheers. Alexandre From alan.gauld@bt.com Wed May 15 10:00:35 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 15 May 2002 10:00:35 +0100 Subject: [Tutor] getting access violation error in kernel32.dll while debugging Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5CB@mbtlipnt02.btlabs.bt.co.uk> > program triggers a bug in the windows kernel and it dies horridly > giving you no help whatsoever. Thats not entirely treue you do get a Dr Watson dumnpo file if you set it up appropriately - siomilar to a coredump on Unix. By running a couple of command line progs you can even turn it into something the debugger can read. If you click the right boxes Visual C++ will do it automatically! > | fp = fopen("modulefile.py","r"); > | res = PyRun_SimpleFile(fp,"modulefile.py"); > > You don't check to see if fopen() returned an error. Yes, that's the problem but it would lead to a segv in Unix too... > 'fp' is NULL at that point. My recommendation, since the debugger > isn't going to help on windows, But the debugger should help. In fact if using the Borland one you can even reverse step back before the error and maybe fix it! without leaving the program... I'm not a huge Windoze fan but it is getting there and in some ways is superior to Unix in tool capability. (But mostly it still lags behind!) Alan G. From pythontutor@venix.com Wed May 15 13:44:22 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 15 May 2002 08:44:22 -0400 Subject: [Tutor] appending lists of objects References: Message-ID: <3CE25826.7080200@venix.com> This is a lot of code to wade through. Can you make a smaller example that illustrates the problem? I do not understand what kind of response you are looking for. Jason Barbour wrote: > Hello all, > > I am having trouble appending a list of class objects. > I am using deepcopy on a list of objects which were successfully > created, but when I print out the list, I just get pointers > to the instantiation. Is there a way to get my append strategy > to work? > > Thanks > > Jason > > class: > > class ANN: > > def __init__(self): > self.numero = None > self.inputs = [] > self.weights = [] > # or make bias as the last input, or first [0] > self.bias = None > # make a variable to store the 'true' answer > self.verdad = None > > code: > > def InitializeTopology(datalist, num_nodes): > > # datalist is 'rawlist' > # num_nodes is 'hidden_nodes' > > # take the length of the [0] element > # of datalist, where input data is kept > # to determine input unit number > input_units = len(datalist[0]) > output_units = len(datalist[1]) > > # List which will hold the entire network > NN = [[]] > # Temp lists to append to NN > ent = [] > out = [] > hid = [] > # NN example counter > j = 0 > print datalist > # loop through each datalist element > for i in range(len(datalist)): > NN.append([]) > # loop through input list within datalist element > ent = [] > for e in (range(input_units)): > ent.append(datalist[i][e]) > print "Input Nodes" > print ent > entx = copy.deepcopy(ent) > NN[j].append(entx) > > # loop through desired hid node list and > # instantiate and append that number > hid = [] > for h in (range(num_nodes)): > # hnode is a temp instantiation > hnode = ANN() > # set numero > hnode.numero = h > # add one extra for the bias node > for d in range(len(datalist[i][0])): > # set random weights > hnode.weights.append(GetRandom()) > hid.append(hnode) > # this works fine > print "Hidden Node Weights" > print hid[h].weights > hidx = copy.deepcopy(hid) > NN[j].append(hidx) > > # loop through output list within datalist element > out = [] > for s in (range(output_units)): > # temp instantiation of node class > onode = ANN() > # set numero > onode.numero = s > # write 'true' value for this node in from datalist > onode.verdad = datalist[i][1] > # add one extra for the bias node > for hi in range(len(hid) + 1): > # set random weights > onode.weights.append(GetRandom()) > ond = copy.deepcopy(onode) > out.append(ond) > print "Output Node Weights" > print out[s].weights > outx = copy.deepcopy(out) > NN[j].append(outx) > > j = j + 1 > > # when I view the final list, > # i only see the pointers shown at the > # end of the output below > print NN > print NN[0][1] > return NN > > output: > > Input Nodes > [['0', '1', '0', '1', '0', '1'], ['1']] > Hidden Node Weights > [-0.018296596687270905, -0.081403175088918187, -0.053187146906907665, > 0.056229649302163988, -0.075566267128166456, -0.022527181800035524] > Hidden Node Weights > [-0.0065363445994707451, 0.069861139620503818, 0.0024552409969152309, > 0.076356456899948924, -0.069533002904092575, -0.014238828091323708] > Hidden Node Weights > [-0.075400889950218292, -0.050053122099344274, -0.0048485866459656354, > 0.08662597642000594, -0.017859878096892778, 0.055191369394788102] > Output Node Weights > [0.037663575883956704, 0.039522195201120526, 0.052848206171747923, - > 0.01037766943868983] > Output Node Weights > [-0.078275023370294267, 0.069305743921806412, 0.025268759536601591, > 0.056177439285214084] > Input Nodes > [['1', '0', '1', '0', '1', '0'], ['0']] > Hidden Node Weights > [0.081712459684275235, -0.073062555492460518, -0.089030582658396876, - > 0.080425085755549922, -0.05533052873035009, 0.0087849646658016093] > Hidden Node Weights > [-0.00023837933585462155, 0.097517550486271948, 0.090236482283893277, > 0.089746470744624232, -0.014322076190345668, -0.050886396966472083] > Hidden Node Weights > [0.00011939214512719509, 0.040501166817123305, -0.095668774128323864, > 0.078139479446892604, 0.08745296237997438, -0.018099444839937705] > Output Node Weights > [-0.027795386749378048, -0.015904567714063299, 0.069970274891191647, - > 0.0051844350890069887] > Output Node Weights > [0.062263405185009335, -0.070228462857787652, -0.058050767060430421, > 0.092388392928725957] > Input Nodes > [['0', '1', '1', '0', '1', '1'], ['1']] > Hidden Node Weights > [-0.014520789653509381, 0.050637826018312279, -0.096331315026787184, - > 0.015789978617662914, -0.080072518921819588, 0.057655140839156793] > Hidden Node Weights > [0.077143949905593145, -0.052093418319049123, 0.021041221782613872, - > 0.073784377429996467, 0.081250167691744937, -0.073069394523676903] > Hidden Node Weights > [0.079183132057173283, -0.064352582341993106, -0.047743468583672025, > 0.056374150998905657, -0.089680772685834367, 0.093224700033546687] > Output Node Weights > [0.031468967429602215, 0.037860013704278585, 0.026289431822902287, > 0.047595309078331482] > Output Node Weights > [0.022103436047705573, 0.080429621649877797, -0.032776026302476426, - > 0.044834187905566168] > Input Nodes > [['1', '1', '0', '0', '1', '0'], ['0']] > Hidden Node Weights > [-0.09723932133933047, 0.082793639556330317, -0.014779765311136072, > 0.05815203111935676, 0.093341660960959721, -0.041596612150172387] > Hidden Node Weights > [-0.033319581113907759, 0.035324831017861325, -0.093066597933479517, > 0.055496245555570048, 0.067858476165719578, -0.066920463380311906] > Hidden Node Weights > [-0.0266917262783797, 0.051820006475687741, -0.0093643674736724417, > 0.084802963987182942, 0.029095629325276783, -0.057989083104446948] > Output Node Weights > [-0.09894360261541886, -0.096914462031604504, 0.059415174380555588, - > 0.0036597219717522389] > Output Node Weights > [-0.015256824879165975, 0.010845872845301941, -0.029854732686460394, - > 0.070282855919804182] > [[[['0', '1', '0', '1', '0', '1'], ['1']], [<__main__.ANN instance at 0x02E02340 > >>, <__main__.ANN instance at 0x02E67500>, <__main__.ANN instance at 0x02E67150 >>], [<__main__.ANN instance at 0x02E62B20>, <__main__.ANN instance at 0x02E641A0 >>]], [[['1', '0', '1', '0', '1', '0'], ['0']], [<__main__.ANN instance at >> > 0x02E12120>, <__main__.ANN instance at 0x02E13C40>, <__main__.ANN instance at > 0x02E11360>], [<__main__.ANN instance at 0x02E654D0>, <__main__.ANN instance at > 0x02E90EF0>]], [[['0', '1', '1', '0', '1', '1'], ['1']], [<__main__.ANN instance > at 0x02EA51E0>, <__main__.ANN instance at 0x02EA6EA0>, <__main__.ANN instance at > 0x02EA6C10>], [<__main__.ANN instance at 0x02DF75A0>, <__main__.ANN instance at > 0x02DF7390>]], [[['1', '1', '0', '0', '1', '0'], ['0']], [<__main__.ANN instance > at 0x02EB6F80>, <__main__.ANN instance at 0x02EB6D10>, <__main__.ANN instance at > 0x02EB6A50>], [<__main__.ANN instance at 0x02DF53A0>, <__main__.ANN instance at > 0x02E138F0>]], []] > [<__main__.ANN instance at 0x02E02340>, <__main__.ANN instance at 0x02E67500>, > <__main__.ANN instance at 0x02E67150>] > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dman@dman.ddts.net Wed May 15 15:59:50 2002 From: dman@dman.ddts.net (dman) Date: Wed, 15 May 2002 09:59:50 -0500 Subject: [Tutor] dictionary swittching In-Reply-To: <6FFAC555-67A5-11D6-BF87-00039351FE6A@mac.com> References: <20020514122007.GB22242@dman.ddts.net> <6FFAC555-67A5-11D6-BF87-00039351FE6A@mac.com> Message-ID: <20020515145950.GB13682@dman.ddts.net> --ADZbWkCsHQ7r3kzd Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable If you don't want to see a comparision against C then don't read this :-). On Tue, May 14, 2002 at 09:45:29PM -0400, Erik Price wrote: | On Tuesday, May 14, 2002, at 08:20 AM, dman wrote: |=20 | >Hmm, maybe the on-line doc will do a better job of explaining the | >specific semantics of an "if" statement and the meaning of 'elif' and | >'else'. |=20 | How about: |=20 | if (condition1): | execute green code | elif (condition2): | execute orange code | elif (condition3): | execute red code | else: | execute blue code |=20 | is equivalent to |=20 | if (condition1): | execute green code | else: | if (condition2): | execute orange code | else: | if (condition3): | execute red code | else: | execute blue code That's functionally equivalent, and is actually how the parse tree is built for the C/C++/Java if-else ladder. Just for your amusement, here's how the C version is written. Remember that indentation is not significant. if (condition1) { execute green code } else if (condition2) { execute orange code } else if (condition3) { execute red code } else { execute blue code } It almost looks the same, but notice that only 1 "else" block has braces and notice the space between "else" and "if". If I use braces for all blocks, and indent it like that, it would look like : if (condition1) { execute green code } else=20 { if (condition2) { execute orange code } else=20 { if (condition3) { execute red code } else { execute blue code } } } In this case I don't really need the braces since each block is just one line (which is why the braces can be omitted and the indentation easier to read as in the first example). =20 Notice, too, that C/C++/Java suffer from the "dangling else" problem. Take this example : if (condition1) execute green code if (condition2) execute orange code else=20 execute red code It doesn't do what you (as a python programmer) would expect. That last "else" clause really belongs with the inner "if". The solution is to use braces to explicitly denote the limit of the first "if" block. Python doesn't have this problem because the indentation is what defines the structure. -D --=20 Thy Word is a lamp unto my feet and a light unto my path. Psalms 119:105 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --ADZbWkCsHQ7r3kzd Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzid+YACgkQO8l8XBKTpRQoGQCgpBRB0x/zxEuNcQ9bAdwdSKKN G9cAoKgF7YJw+scR720DEox4ce1AGw4N =lubM -----END PGP SIGNATURE----- --ADZbWkCsHQ7r3kzd-- From dman@dman.ddts.net Wed May 15 16:06:20 2002 From: dman@dman.ddts.net (dman) Date: Wed, 15 May 2002 10:06:20 -0500 Subject: [Tutor] Email list functions In-Reply-To: <3CE1E043.127EC60B@netzero.net> References: <3CE1E043.127EC60B@netzero.net> Message-ID: <20020515150620.GC13682@dman.ddts.net> --YD3LsXFS42OYHhNZ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 15, 2002 at 12:12:51AM -0400, kirk Bailey wrote: | OK, thinking about lists, and 2 new functions, digests and archives. |=20 | Archives are pretty simple. IF a file exists, ( such as | '(listname).archive') we append a copy of the complete assembled | message to it IN THAT FILE. So much for building the archive. Archives are only simple if all you want is a mail folder containing all the messages. | We also create an alias; '(listname)-archive'. Anyone wishing to | examine it sends a email to it. We have an autoreply program sitting | in the alias pointed at the archive program; said archive is the reply | to the request. Looks like that's what you want, but that's an unusual way to browse archives. =20 The fun part about "regular" archives is decoding the email message, figuring out which messages it relates to (threads), and then re-encoding it into an HTML page that is actually usable by the users. There are many different archives out there, and some of them just plain suck, and others are quite easy to use and follow threads and search for information you need. Some of them do bad things like _not_ decode quoted-printable messages. Real fun to read =3Dp. =20 | As for digests, this is still under the microscope, but it's not too | hard at all. Just how important do y'all feel this sort of thig is to | add to TL? If you really have the time and ambition to re-invent the wheel while attending the School of Hard Knocks, go ahead. Otherwise I recommend taking a look at mailman. It can do the job for you if you just want to be an admin. If you want to learn, why not see what pitfalls others have already fallen in and see how they climbed out? If you find something new you can help build up and improve an already-mature and well-known product. The more people who work on a project the more likely subtle issues will be noticed and corrected. This is just my aversion to recreating complex software from scratch and effectively wasting resources. -D --=20 If you hold to [Jesus'] teaching, you are really [Jesus'] disciples. Then you will know the truth, and the truth will set you free. John 8:31-32 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --YD3LsXFS42OYHhNZ Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzieWwACgkQO8l8XBKTpRQADgCgxvh6+0WBhiWmrSx15V2GPNvf 1hEAmgLqbKtMor9d7h6q7jWaHP9I0B2j =lSu1 -----END PGP SIGNATURE----- --YD3LsXFS42OYHhNZ-- From dman@dman.ddts.net Wed May 15 16:10:53 2002 From: dman@dman.ddts.net (dman) Date: Wed, 15 May 2002 10:10:53 -0500 Subject: [Tutor] Callbacks in a python module In-Reply-To: <1021437712.2094.5.camel@gncuster> References: <1021437712.2094.5.camel@gncuster> Message-ID: <20020515151053.GD13682@dman.ddts.net> --Xm/fll+QQv+hsKip Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, May 14, 2002 at 11:41:52PM -0500, Nate Custer wrote: | Hey all, |=20 | I like using callbacks in my pygtk programs, is there any way a python | module can do the same thing? Specificly I need a class in one module to | call a fcn in a different module. |=20 | Here is the object tree: |=20 | tn5250py | \ | |-lib5250 | | \ | | |-called from here | | | |-5250gui=09 | \ | |- here is screen refesh method. I think you're trying to recreate Legacy Integrator (see http://www.redoaksw.com) in python. =20 | What is the best way to do this? I'll give an example that follows the Observer Patter[1] class Observable : def __init__( self ) : self._listeners =3D [] def add_listener( self , func ) : """ this is where we give it a "callback" """ self._listeners.append( func ) def notify_listeners( self ) : """ this is where we actually call back """ for f in self._listeners : f() # here is a function we want to have called by an "observable" object def our_callback() : print "Yea!" obj =3D Observable() obj.add_listener( our_callback ) # normally this next line would be somewhere else in the program obj.notify_listeners() -D [1] See "Design Patterns" by the Gang Of Four --=20 A wise servant will rule over a disgraceful son, and will share the inheritance as one of the brothers. Proverbs 17:2 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --Xm/fll+QQv+hsKip Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzien0ACgkQO8l8XBKTpRTg8gCdGE8vOkz53WzhQzPlktAEmKnA meUAoItMGFrtDqB2etXw9r3RgmC5ONP0 =AGZe -----END PGP SIGNATURE----- --Xm/fll+QQv+hsKip-- From dman@dman.ddts.net Wed May 15 15:52:40 2002 From: dman@dman.ddts.net (dman) Date: Wed, 15 May 2002 09:52:40 -0500 Subject: [Tutor] getting access violation error in kernel32.dll while debugging In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5CB@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5CB@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020515145240.GA13682@dman.ddts.net> --Kj7319i9nmIyA2yE Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 15, 2002 at 10:00:35AM +0100, alan.gauld@bt.com wrote: | > program triggers a bug in the windows kernel and it dies horridly | > giving you no help whatsoever. |=20 | Thats not entirely treue you do get a Dr Watson dumnpo file=20 | if you set it up appropriately - siomilar to a coredump on Unix. Hmm, after some searching on the web I find out that Dr. Watson comes with windows. I've only ever seen it running on 1 system, so I thought it was some sort of add-on product. Funny that users must run a program that is installed but not run by default in order to provide a mechanism for terminating misbehaving programs without hurting the kernel so bad. | By running a couple of command line progs you can even turn it into | something the debugger can read. If you click the right boxes Visual | C++ will do it automatically! Are those boxes well known? Do institutions that use windows teach that to students? (my school uses Solaris for CS majors, the SE's now use Windows but do everything in java anyways and start out using Solaris in the CS courses) =20 | > | fp =3D fopen("modulefile.py","r"); | > | res =3D PyRun_SimpleFile(fp,"modulefile.py"); | >=20 | > You don't check to see if fopen() returned an error. =20 |=20 | Yes, that's the problem but it would lead to a segv in Unix too... Ahh, but a SIGSEGV delivered to your app shows that your app is bugged, and a backtrace of the core file will point you to the line where the bad pointer was dereferenced. Unix doesn't tell you the *kernel* just did something fubar. =20 | > 'fp' is NULL at that point. My recommendation, since the debugger | > isn't going to help on windows,=20 |=20 | But the debugger should help. It should, but when the error occurs in kernel32.dll, how do you work through _that_ one? (unless you can figure out that your program is messed somewhere and can then guess where) | In fact if using the Borland one you can even reverse step back | before the error and maybe fix it! without leaving the program... Interesting. It can "undo" stuff? How does it do that? How does it know the operations are even reversible? What if your app sent some data to something else (a socket, a file, a pipe, whatever). Can it actually undo that? I think the idea of "backup and try again slower so it can be debugged" is great, it just seems infeasible to me. | I'm not a huge Windoze fan but it is getting there and in some ways | is superior to Unix in tool capability. (But mostly it still lags | behind!) If the debugger really can "step backwards" that would be an improvement, but I'm doubtful that it works for apps that don't stay within certain restrictive boundaries. I find that I get more frustrated when trying to work in windows than in many other environments. Say, while we're talking about debugging on windows, is there an equivalent to the 'host' command for testing if DNS works (or just to lookup DNS records)? -D --=20 Bugs come in through open windows. Keep Windows shut! =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --Kj7319i9nmIyA2yE Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzidjgACgkQO8l8XBKTpRSe6QCeP8Tq+i1rn7G/xF6xOh87cx0H yY8AoJVUGkbz3Pk7LzzaDobz9hM0a4Jg =FImh -----END PGP SIGNATURE----- --Kj7319i9nmIyA2yE-- From pythontutor@venix.com Wed May 15 16:30:53 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 15 May 2002 11:30:53 -0400 Subject: [Tutor] getting access violation error in kernel32.dll while debugging References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5CB@mbtlipnt02.btlabs.bt.co.uk> <20020515145240.GA13682@dman.ddts.net> Message-ID: <3CE27F2D.5080608@venix.com> nslookup netstat ping tracert (== traceroute) arp are the commands I usually rely on for network problems. These are all available for NT at least, but may require some extra effort to get them installed. I dimly remember downloading stuff from the Microsoft web site. ping and tracert are nearly always available. dman wrote: > I find that I get more frustrated when trying to work in windows than > in many other environments. Say, while we're talking about debugging > on windows, is there an equivalent to the 'host' command for testing > if DNS works (or just to lookup DNS records)? > > -D > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From python@rcn.com Wed May 15 16:33:57 2002 From: python@rcn.com (Raymond Hettinger) Date: Wed, 15 May 2002 11:33:57 -0400 Subject: [Tutor] Looking for hints References: <000801c1fb43$598bcf80$a400a8c0@Arts> Message-ID: <005201c1fc25$ef073120$a961accf@othello> This is a multi-part message in MIME format. ------=_NextPart_000_004F_01C1FC04.66DFDB60 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Try a google search for Observer Design Patterns. The basic idea is that every Line user of a Point registers itself with Point which uses its little maillist to notify dependent lines of a change. Raymond Hettinger ----- Original Message -----=20 From: Netcom=20 To: tutor@python.org=20 Sent: Tuesday, May 14, 2002 8:31 AM Subject: [Tutor] Looking for hints I am needing to track dependencies within a program. Meaning -=20 let's say I have 4 instances of a "point" class (each with its own position) , which in turn are used to create 2 line instances = (each take 2 of the points as input). The intersection of the 2 lines = determine another point instance. One of the original points is moved. As of now, there is a routine to recalculate the new position of everything when anything in the scene is moved. I would like things to be smarter - for the program to determine which instances are directly or indirectly effected by the change in position of a scene element, and only go through the full "update" routine for those instances. Guess I suspect this is a form of a relatively common=20 programming issue, and would appreciate hints. Even the proper terminology for a google search on this kind of issue woiuld be of great help. Art ------=_NextPart_000_004F_01C1FC04.66DFDB60 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Try a google search for Observer Design = Patterns.
 
The basic idea is that every Line user = of a=20 Point
registers itself with Point which uses = its=20 little
maillist to notify dependent lines of a = change.
 
Raymond Hettinger
----- Original Message -----
From:=20 Netcom
Sent: Tuesday, May 14, 2002 = 8:31 AM
Subject: [Tutor] Looking for = hints

I am needing to track dependencies = within a=20 program.
 
Meaning -
 
let's say I have 4 instances of a = "point" class=20 (each with its
own position) , which in turn are used to create 2 line instances (each take = 2 of the points as input). The intersection of = the=20 2 lines determine another point=20 instance.
 
One of the original points is = moved.  As of=20 now, there
is a routine to recalculate the new = position of=20 everything
when anything in the scene is = moved.
 
I would like things to be smarter - = for the=20 program to
determine which instances are = directly or=20 indirectly
effected by the change in position of = a scene=20 element, and
only go through the full "update" = routine for=20 those
instances.
 
Guess I suspect this is a form of a = relatively=20 common
programming issue, and would = appreciate=20 hints.  Even
the proper terminology for a google = search on=20 this
kind of issue woiuld be of great=20 help.
 
Art
------=_NextPart_000_004F_01C1FC04.66DFDB60-- From alan.gauld@bt.com Wed May 15 18:38:44 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 15 May 2002 18:38:44 +0100 Subject: [Tutor] getting access violation error in kernel32.dll while debugging Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5CE@mbtlipnt02.btlabs.bt.co.uk> > Hmm, after some searching on the web I find out that Dr. Watson comes > with windows. Every version except Win95 for some reason(maybe Me too?) > thought it was some sort of add-on product. Funny that users must run > a program that is installed but not run by default in order to provide > a mechanism for terminating misbehaving programs without hurting the > kernel so bad. It does that by accident, it really is just the tool that generates the core dump data. > Are those boxes well known? To professional Windows developers yes. They've been there since Windows 3.1 at least. > Do institutions that use windows teach that to students? My school didn't even teach us about debuggers so I doubt it! > Ahh, but a SIGSEGV delivered to your app shows that your app is > bugged, and a backtrace of the core file will point you to the line > where the bad pointer was dereferenced. Unix doesn't tell you the > *kernel* just did something fubar. Oh I dunno. I used to work on a Unix app where if you moved the mouse too fast it killed not just X but Unix too - you got back to the big white bootup screen on the Sun workstation - scary! > It should, but when the error occurs in kernel32.dll, how do you work > through _that_ one? (unless you can figure out that your program is > messed somewhere and can then guess where) The stack trace generated by Dr Watson will normally show where it came from - it only captures about 10 levels ISTR but thats usually enough. > | In fact if using the Borland one you can even reverse step back > | before the error and maybe fix it! without leaving the program... > > Interesting. It can "undo" stuff? How does it do that? How does it > know the operations are even reversible? What if your app sent some > data to something else (a socket, a file, a pipe, whatever). Can it > actually undo that? I think the idea of "backup and try again slower > so it can be debugged" is great, it just seems infeasible to me. Its pretty magical to me too and it does have limits but it will record values of some socket calls for example for replay purposes or redo the call depending on how you set it up. I assume they create a virtual machine and log all the steps and register values(I do know it operates at the assembler level) > If the debugger really can "step backwards" that would be an > improvement, but I'm doubtful that it works for apps that don't stay > within certain restrictive boundaries. Its pretty powerful but does impose a noticable performance hit over normal debugging. > on windows, is there an equivalent to the 'host' command for testing > if DNS works (or just to lookup DNS records)? What's that then? I don't seem to have it on either of my Unix boxes(Solaris and HP/Ux) and its not listed in 'Unix in a Nushell' Alan g. From marta_andrea@libero.it Wed May 15 05:41:50 2002 From: marta_andrea@libero.it (Andrea Valle) Date: Wed, 15 May 2002 06:41:50 +0200 Subject: [Tutor] a probably stupid question Message-ID: Dear members, I am a python user since 2 years. Very happy because of my discretly sophisticated py modules for music composition. I was still using py 1.5.2. That worked fine for me. However, I decided (obviously, indeed) to pass to 2.1. But there's a behaviour I cannot understand in all py versions newer than 1.5, probably because I am a self-taught. Here we are. (With IDLE) Python 1.5 >>> a=3D.234 >>> a 0.234 >>> 1.3/2 0.65 >>> 1.3/.2 6.5 >>> Python, 1.6 and newer >>> a=3D.234 >>> a 0.234000000000000001 >>> 1.3/2.0 0.650000000000000002 >>> 1.3/.2 6.5 >>> Why cannot I assign as 0.x value to a variable without this (curious) rounding? And why 1.3/2.0 must be rounded? Being too big to be a bug, I am sure I do not understand the real problem= =2E Thank you, Sirs. Any help is much appreciated. -a- Andrea Valle via Lanzo 108 10073 - Ciri=E8 (TO) ITALIA 011/921 45 84 - 349/55 47 343 From shalehperry@attbi.com Wed May 15 23:21:55 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 15 May 2002 15:21:55 -0700 (PDT) Subject: [Tutor] a probably stupid question In-Reply-To: Message-ID: > > Why cannot I assign as 0.x value to a variable without this (curious) > rounding? And why 1.3/2.0 must be rounded? > Being too big to be a bug, I am sure I do not understand the real problem. > Thank you, Sirs. Any help is much appreciated. > >>> a = 0.234 >>> a 0.23400000000000001 >>> repr(a) '0.23400000000000001' >>> str(a) '0.234' >>> 1.3 1.3 >>> 1.3/2.0 0.65000000000000002 >>> b = 1.3/2.0 >>> b 0.65000000000000002 >>> str(b) '0.65' >>> Not sure if that helps any, but if you look through the replease notes this may be enough of a clue to find the reason. From idiot1@netzero.net Thu May 16 06:14:36 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 16 May 2002 01:14:36 -0400 Subject: [Tutor] Email list functions References: <3CE1E043.127EC60B@netzero.net> <20020515150620.GC13682@dman.ddts.net> <3CE32F67.FE694E4A@netzero.net> <20020516045207.GA21936@dman.ddts.net> Message-ID: <3CE3403C.35AD4988@netzero.net> dman wrote: > > On Thu, May 16, 2002 at 12:02:47AM -0400, kirk Bailey wrote: > | dman wrote: > | > > | > On Wed, May 15, 2002 at 12:12:51AM -0400, kirk Bailey wrote: > | > | OK, thinking about lists, and 2 new functions, digests and archives. > | > | > | > | Archives are pretty simple. IF a file exists, ( such as > | > | '(listname).archive') we append a copy of the complete assembled > | > | message to it IN THAT FILE. So much for building the archive. > | > > | > > | > > | > Archives are only simple if all you want is a mail folder containing > | > all the messages. > | > | Granted, BUT... in advance, you do not know what you will want to look > | at and check, so you save everything, JUST IN CASE, so this simple > | method is good at the front end, but plenty to dig through later if > | looking for something specific. > > Ok, good point. What if you can parse out some of the headers and > store the message in a well-designed SQL table? Then you can do lots > of queries and let the SQL implementors worry about _how_ to do it and > how to do it fast. I'm no expert at this, though. > Me neither, but I slam ssi like a fiend. > | > | We also create an alias; '(listname)-archive'. Anyone wishing to > | > | examine it sends a email to it. We have an autoreply program sitting > | > | in the alias pointed at the archive program; said archive is the > | reply > | > | to the request. > | > > | > Looks like that's what you want, but that's an unusual way to browse > | > archives. > | > | OK, try a ssi include in a web page, and simply inhale the file into > | it, and scroll through it- it's your call. > > Oooh, just drop the raw message inside HTML tags. What if the message > is base64 encoded? What if it has large (or not-so-large) binary > attachments? You really do want to de-MIME the message and re-render > it in an aesthetic manner :-). > > | You DO grok ssi, right? > > I know what it's about. > > | > The fun part about "regular" archives is decoding the email message, > | > figuring out which messages it relates to (threads), and then > | > re-encoding it into an HTML page that is actually usable by the users. > | > There are many different archives out there, and some of them just > | > plain suck, and others are quite easy to use and follow threads and > | > search for information you need. Some of them do bad things like > | > _not_ decode quoted-printable messages. Real fun to read =p. > | > > | > | As for digests, this is still under the microscope, but it's not too > | > | hard at all. Just how important do y'all feel this sort of thig is > | > | to add to TL? > | > > | > If you really have the time and ambition to re-invent the wheel while > | > attending the School of Hard Knocks, go ahead. > | > | It's my alma mata. > | > | > Otherwise I recommend > | > taking a look at mailman. It can do the job for you if you just want > | > to be an admin. If you want to learn, why not see what pitfalls > | > others have already fallen in and see how they climbed out? > | > | Much more profitable approach, learn from the success and failure of > | others. > > Yep. > > | > If you find something new you can help build up and improve an > | > already-mature and well-known product. The more people who work > | > on a project the more likely subtle issues will be noticed and > | > corrected. This is just my aversion to recreating complex > | > software from scratch and effectively wasting resources. > | > | Imporoving my skills, and cooking something new and a little different > | is no waste my friend. > > Right, it isn't, but what if the "something new" is just another > wheel? I like to stand on the shoulders of giants and pull together > existing code, libraries, and frameworks to achieve the results I > want. The less code I personally have to write the more likely I'll > have a working solution :-). (and I'll be more likely to get that > solution sooner rather than later) > The archive is working. http://www.tinylist.org/tinylist-usersarchive.shtml I should do a script to handle this, se the get method. http://www.tinylist.org/cgi-bin/TLarchive.py?tinylist-users is what the link would look like. THIS SCRIPT DOES NOT EXIST YET! > -D > > -- > > For society, it's probably a good thing that engineers value function > over appearance. For example, you wouldn't want engineers to build > nuclear power plants that only _look_ like they would keep all the > radiation inside. > (Scott Adams - The Dilbert principle) > Yikes. > GnuPG key : http://dman.ddts.net/~dman/public_key.gpg > > ---------------------------------------------------------------------- > Part 1.2Type: application/pgp-signature -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ From idiot1@netzero.net Thu May 16 06:24:37 2002 From: idiot1@netzero.net (kirk Bailey) Date: Thu, 16 May 2002 01:24:37 -0400 Subject: [Tutor] archive working Message-ID: <3CE34295.493C1503@netzero.net> TinyList now will archive a complete copy of every email sent through a list IF you created the file (listname).archive. This can be access via ssi and a html page, or by a script, or by a autoreply program. To nake it wasy, I will write a script to make access easy, but nothis is going to stop you from using email or ssi. In fact, I already created a html page with ssi to access it. here is a link to it: http://www.tinylist.org/tinylist-usersarchive.shtml -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ From alex@gabuzomeu.net Thu May 16 10:21:12 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Thu, 16 May 2002 11:21:12 +0200 Subject: [Tutor] Design - Granularity of classes Message-ID: <4.3.2.7.2.20020516110702.00b71dd0@pop3.norton.antivirus> Hello, How granular do you make your classes? I.e. do you usually wrap fairly simple data in classes? Here is an example. Let's assume we upload files into a Web app. Let's call UploadFile the class that is used to handle these files. UploadFile will hold properties such as size and type. class UploadFile: """Uploaded file.""" def __init__(self, name, data, size, type): self.name = name self.data = data self.size = size self.type = type # etc For instance, would you create a FileType class to hold the mime type and a FileSize class to hold the type? class FileType: """File type""" def __init__(self, type): # Can test mime type here self.type = type def __repr__(self): return str(self.type) class FileSize: """File size""" def __init__(self, size): # Can test data type here self.size = size def __repr__(self): return str(self.size) Now UploadFile could be rewritten as: class UploadFile2: """Uploaded file.""" def __init__(self, name, data, size, type): self.name = name self.data = data self.size = FileSize(size) self.type = FileType(type) # etc => Does it make sense? I think this strategy would add overhead but it might help testing for correct data type. Thanks. Alexandre From alex@gabuzomeu.net Thu May 16 10:29:10 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Thu, 16 May 2002 11:29:10 +0200 Subject: [Tutor] Design - getFoo and setFoo methods Message-ID: <4.3.2.7.2.20020516112146.00bb5100@pop3.norton.antivirus> Hello, When do you use getFoo() and setFoo() methods in your classes? (I think there can be called "accessors"?). The question came up on c.l.py a couple of days ago and most participants said they did not usually use them, eg. they access attributes directly. => Do you only use get and set methods when data needs some extra work before it can be stored or returned? => If yes, do you use the _ convention in attribute names to remember when attributes can be accessed directly? Eg. self.foo can be read and written directly, but self._foo should not. So far I used many set and get methods, but now I wonder whether they really make sense when data is not somehow transformed before storing/returning. Thanks again. Alexandre From erikprice@mac.com Thu May 16 12:17:12 2002 From: erikprice@mac.com (Erik Price) Date: Thu, 16 May 2002 07:17:12 -0400 Subject: [Tutor] dictionary swittching In-Reply-To: <20020515145950.GB13682@dman.ddts.net> Message-ID: <7808BC4C-68BE-11D6-846D-00039351FE6A@mac.com> On Wednesday, May 15, 2002, at 10:59 AM, dman wrote: > If you don't want to see a comparision against C then don't read this Thanks for the comparison dman. I appreciated it because I work with PHP, which uses braces rather than indentation, and I am learning Java (also uses braces except with one-liner 'if's). > Notice, too, that C/C++/Java suffer from the "dangling else" problem. > Take this example : > > if (condition1) > execute green code > if (condition2) > execute orange code > else > execute red code > > It doesn't do what you (as a python programmer) would expect. That > last "else" clause really belongs with the inner "if". The solution > is to use braces to explicitly denote the limit of the first "if" > block. Python doesn't have this problem because the indentation is > what defines the structure. Python doesn't have this problem, as long as you are coding in Python! :) This is one of those rare occasions where learning Python first, and being used to the idea of whitespace has an effect in other languages as it does in Python, might cause a problem. Of the languages I've played with since I started programming, none use whitespace/indentation in this way, so I would HOPE that the programmer takes a careful look at their braces usage and continues to indent properly (regardless of whether it's enforced by the language). Erik From pythontutor@venix.com Thu May 16 13:25:09 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 16 May 2002 08:25:09 -0400 Subject: [Tutor] Design - getFoo and setFoo methods References: <4.3.2.7.2.20020516112146.00bb5100@pop3.norton.antivirus> Message-ID: <3CE3A525.2000002@venix.com> It is easy in python to catch changes to attributes in the __setattr__ method. This allows you to do any special processing while providing the appearance of a simple assignment. So I do not write special setFoo / getFoo methods. Python 2.2 now supports a new type called property designed to further simplify get/set processing. (I have not updated my code to adopt this yet.) http://www.amk.ca/python/2.2/index.html#SECTION000340000000000000000 What's New in Python 2.2 I do use the _name convention to indicate properties that should not be touched directly from outside the class. Alexandre Ratti wrote: > Hello, > > > When do you use getFoo() and setFoo() methods in your classes? (I think > there can be called "accessors"?). > > The question came up on c.l.py a couple of days ago and most > participants said they did not usually use them, eg. they access > attributes directly. > > => Do you only use get and set methods when data needs some extra work > before it can be stored or returned? > > => If yes, do you use the _ convention in attribute names to remember > when attributes can be accessed directly? Eg. self.foo can be read and > written directly, but self._foo should not. > > So far I used many set and get methods, but now I wonder whether they > really make sense when data is not somehow transformed before > storing/returning. > > > Thanks again. > > Alexandre > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From shalehperry@attbi.com Thu May 16 15:51:28 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu, 16 May 2002 07:51:28 -0700 (PDT) Subject: [Tutor] Design - Granularity of classes In-Reply-To: <4.3.2.7.2.20020516110702.00b71dd0@pop3.norton.antivirus> Message-ID: > > => Does it make sense? I think this strategy would add overhead but it > might help testing for correct data type. > I tend to make into classes the chunks that are self sufficient and likely to be reused. There is definately a balance between clean design, efficiency, and having way too many objects. From shalehperry@attbi.com Thu May 16 15:55:23 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu, 16 May 2002 07:55:23 -0700 (PDT) Subject: [Tutor] Design - getFoo and setFoo methods In-Reply-To: <3CE3A525.2000002@venix.com> Message-ID: On 16-May-2002 Lloyd Kvam wrote: > It is easy in python to catch changes to attributes in the __setattr__ > method. > This allows you to do any special processing while providing the appearance > of a simple assignment. So I do not write special setFoo / getFoo methods. > > Python 2.2 now supports a new type called property designed to further > simplify > get/set processing. (I have not updated my code to adopt this yet.) > http://www.amk.ca/python/2.2/index.html#SECTION000340000000000000000 > What's New in Python 2.2 > > I do use the _name convention to indicate properties that should not be > touched > directly from outside the class. > indeed, Python style is for fast writing and testing. Having to create lots of boiler plate functions: getFoo(self): return foo getBar(self): return bar goes against this. So general get/sets are used when giving direct access to the data would be bad. Note that this design idea changes a little as the code use changes. The more likely the object is to be used by a random python coder the more likely the object will be wrapped in protective code. I seem to recall _foo doing some magic in the class namespace to help hide the variable. From jeff@ccvcorp.com Thu May 16 17:32:34 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 16 May 2002 09:32:34 -0700 Subject: [Tutor] Design - getFoo and setFoo methods References: Message-ID: <3CE3DF21.1540728@ccvcorp.com> Sean 'Shaleh' Perry wrote: > I seem to recall _foo doing some magic in the class namespace to help hide the > variable. IIRC, _foo doesn't do much magic -- I believe that single-leading-underscore functions are, by default, not imported into a namespace by 'from foo import *', but they are accessible as 'import foo; foo._foo'. However, identifiers with a *double* leading underscore (and no trailing double underscore) do get "mangled". Thus, in class Foo, you can use self.__bar, but to access __bar from the outside of that class would require you to use Foo._Foo__bar (I'm not completely sure about the exact location of the extra underscores, and couldn't be bothered to look it up just now , but it's something like that.) Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Thu May 16 17:41:40 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 16 May 2002 17:41:40 +0100 Subject: [Tutor] Design - getFoo and setFoo methods Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5D5@mbtlipnt02.btlabs.bt.co.uk> > When do you use getFoo() and setFoo() methods in your > classes? There are a few good answers to this and a lot of bad ones! getXXX/setXXX makes sense if the XXX is a property accessed via a common protocol(like in JavaBeans) by a Tool (like a GUI builder). They also make sense if you put valuidation code in the set method to check the values lie within constraints. Or put security checks to make sure the user has valid access rights. But as a general principle they are a bad idea since they basically break the principle of data hiding. You should access objects using a behaviourally focussed API and the internal function of the methods should determine the data held. The data(attributes) should only be there to support the methods. Of course the methods may be there to expose data but usually this will be ion a lump not single attributes(eh a getAddress() method retuirns several fields not just one and a getAddressString returns the sae info as a single string. How it is stored internally is unknown and irrelevant to the class user. > said they did not usually use them, eg. they access > attributes directly. Thats a common Python idiom but if you are accessing too many attributes directly it suggests the class is missing some methods. Theres an OOP expression for this called the Law of deMeter if you want more research material - try the Cetus Links page. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Thu May 16 17:48:14 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 16 May 2002 17:48:14 +0100 Subject: [Tutor] dictionary swittching Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5D6@mbtlipnt02.btlabs.bt.co.uk> > From: Erik Price [mailto:erikprice@mac.com] > > if (condition1) > > execute green code > > if (condition2) > > execute orange code > > else > > execute red code > > > > It doesn't do what you (as a python programmer) would expect. That > Python doesn't have this problem, as long as you are coding in ... > the languages > I've played with since I started programming, none use > whitespace/indentation in this way, so I would HOPE that the > programmer takes a careful look at their braces usage and > continues to indent properly Unfortunately the dangling else problem s very common for C/Java etc programmers and we've nearly all been bitten at least once. This is one of Pythons strongest points. THe most common case is when you want the indentation shown, but in C etc you need to add a dummy else to achieve it: > > if (condition1) > > execute green code > > if (condition2) > > execute orange code else {} // needed to avoid the dangling else > > else > > execute red code The alternative (which I tend to use!) is to always use braces everytime, everywhere. > > if (condition1){ > > execute green code > > if (condition2){ > > execute orange code } } // avoids the dangling else > > else{ > > execute red code } Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From jeff@ccvcorp.com Thu May 16 17:58:44 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 16 May 2002 09:58:44 -0700 Subject: [Tutor] Design - Granularity of classes References: <4.3.2.7.2.20020516110702.00b71dd0@pop3.norton.antivirus> Message-ID: <3CE3E543.C28A7849@ccvcorp.com> Alexandre Ratti wrote: > Hello, > > How granular do you make your classes? I.e. do you usually wrap fairly > simple data in classes? Here is an example. [...] > For instance, would you create a FileType class to hold the mime type and a > FileSize class to hold the type? Personally, no, I would not, at least not as you're showing. I generally only create classes when one of two conditions applies-- 1) I have a group of data that I want to be able to access, and pass around, as a unit. This is what you've done with your UploadFile class -- it probably doesn't do much by itself, but it stores all the interesting information about a particular file, making it easy to keep track of what data belongs together. 2) There is a consistent set of operations that I want to perform on similar data. For instance, while I wouldn't create a FileType class just to store a mime type string, I *might* create a class that, when given a filename, will ensure that that file exits, determine the mime type from the file itself, perhaps even perform base64-encoding on request... In other words, I might use a class to *discover* and *act on* the mime type, but I wouldn't bother with a class just to *store* a single string value. In your examples, there's really no benefit to using a class instead of a normal string. The *only* thing that you "gain" by making them classes, is the ability to use isinstance() on them -- which is usually the wrong thing to do. You shouldn't care whether they're a normal string, a unicode string, a string-like class... Anything that *acts* like a string should work, whether it actually *is* a string or not, and requiring a specific FileType prevents that from happening. In Java and C++, you might use classes in these cases so that it would later be easier to expand your code. For instance, you might later *want* to add various sorts of checking to the creation of a FileType instance, and if you use simple strings at first, then later you'll have to change all your code to use the new class instance instead. But since Python does dynamic typing, then (as long as your replacement class is well-designed) there is no need to change any code beyond the creation of the instance. There's no StringType declarations to be changed to FileType declarations, etc., so there's really no benefit to that sort of "planning ahead". Something else that might seem like a good use for a class is to "normalize" a value to a limited, specific set of valid values -- in other words, an enumeration. For this sort of task, I would use a dictionary instead -- only using values that already existed as keys in the dictionary. Now, if I need to do a "closest match" calculation, taking some arbitrary input and determining the best fitting result from a limited set, *then* I might make a class to do that -- but I probably wouldn't create a new instance of the class for each match I wanted to make. Instead, I would create a single instance of that class that had a match() method, which took the arbitrary input string as an argument and returned a guaranteed valid result string (or threw an exception if no match could be found). Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Thu May 16 17:33:48 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 16 May 2002 17:33:48 +0100 Subject: [Tutor] Design - Granularity of classes Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5D4@mbtlipnt02.btlabs.bt.co.uk> > class UploadFile: > def __init__(self, name, data, size, type): > self.name = name > self.data = data > self.size = size > self.type = type > For instance, would you create a FileType class to hold the > mime type No but I might create a heirarchy of File classes each supporting a different mime type. 'Type' is one of the key indicators that you need to subclass. One goal of OOP is to avoid special processing of the if f.type == foo:.... elif f.type == bar:.... elif f.type == baz:... variety. > FileSize class to hold the type? Maybe. It depends on what size's responsibilities are. What do we do with a size object? The fact that its a *File*size indicates that its an attribute of File. So if we use a class its more likely to be a number class rather than a size class... > => Does it make sense? I think this strategy would add > overhead but it might help testing for correct data type. No it doesn't make sense unless you are going to do something different to the normal primitive types which are objects anyway! Class definitions should be driven by behaviour not data. If you have a bit of data decide whether it has any intrinsic behavior within your application. If the answer is no just use the raw data. At least thats how I do it :-) Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From kimtitu@yahoo.com Thu May 16 20:24:02 2002 From: kimtitu@yahoo.com (Titu Kim) Date: Thu, 16 May 2002 12:24:02 -0700 (PDT) Subject: [Tutor] Looking for html to pdf module Message-ID: <20020516192402.76408.qmail@web14703.mail.yahoo.com> Hi there, I am doing some simple reporting mechanism in cgi. I want to provide an option to output a pdf format instead of html page. So I need a module that can convert a complete html string into pdf format so it can be download. Is such module exist? Thanks. __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com From phoebus@fastmail.fm Thu May 16 22:05:08 2002 From: phoebus@fastmail.fm (Phoebus) Date: Thu, 16 May 2002 17:05:08 -0400 Subject: [Tutor] Backslashes inside of variable Message-ID: <3CE41F04.4060508@fastmail.fm> I am running Python 2.2 on Win2k. I have a program which writes a filename, with backslashes to a file, along with other stuff. I read the file in using readlines() and put each line into a variable. My problem is I want to use the filename, but I can't use it because of the backslashes. I know about doing open(r"d:\test\file.txt","w") or even open(`d:\test\file.txt`,"w"), but the filename is inside of a variable so when I do open(filename,'w'), I have problems. Can anyone help? Thanks, Steve -- From pythontutor@venix.com Thu May 16 22:58:48 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 16 May 2002 17:58:48 -0400 Subject: [Tutor] Backslashes inside of variable References: <3CE41F04.4060508@fastmail.fm> Message-ID: <3CE42B98.2010204@venix.com> Your problem is NOT the backslashes. They are an escape character when creating the string, that is in literal expressions. Once you have a variable with the correct value, you can use it. There is probably some other error. >>> filename = r'f:\freenet\readme.txt' >>> fh = open(filename,'r') >>> fh.readline() 'README - Freenet 0.3.8\n' Phoebus wrote: > I am running Python 2.2 on Win2k. I have a program which writes a > filename, with backslashes to a file, along with other stuff. I read > the file in using readlines() and put each line into a variable. > > My problem is I want to use the filename, but I can't use it because of > the backslashes. I know about doing open(r"d:\test\file.txt","w") or > even open(`d:\test\file.txt`,"w"), but the filename is inside of a > variable so when I do open(filename,'w'), I have problems. > > Can anyone help? > > Thanks, > Steve -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor@venix.com Thu May 16 23:05:21 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 16 May 2002 18:05:21 -0400 Subject: [Tutor] Backslashes inside of variable References: <3CE41F04.4060508@fastmail.fm> <3CE42B98.2010204@venix.com> Message-ID: <3CE42D21.7040308@venix.com> Whoops. Left out the display of the filename. Print the file name and verify that it is correct! 'README - Freenet 0.3.8\n' >>> filename 'f:\\freenet\\readme.txt' Lloyd Kvam wrote: > Your problem is NOT the backslashes. They are an escape character when > creating the string, that is in literal expressions. Once you have a > variable with the correct value, you can use it. There is probably some > other error. > > >>> filename = r'f:\freenet\readme.txt' > >>> fh = open(filename,'r') > >>> fh.readline() > 'README - Freenet 0.3.8\n' > > Phoebus wrote: > >> I am running Python 2.2 on Win2k. I have a program which writes a >> filename, with backslashes to a file, along with other stuff. I read >> the file in using readlines() and put each line into a variable. >> >> My problem is I want to use the filename, but I can't use it because >> of the backslashes. I know about doing open(r"d:\test\file.txt","w") >> or even open(`d:\test\file.txt`,"w"), but the filename is inside of a >> variable so when I do open(filename,'w'), I have problems. >> >> Can anyone help? >> >> Thanks, >> Steve > > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From idiot1@netzero.net Fri May 17 05:40:36 2002 From: idiot1@netzero.net (kirk Bailey) Date: Fri, 17 May 2002 00:40:36 -0400 Subject: [Tutor] archive viewer is next Message-ID: <3CE489C4.2A6A1D73@netzero.net> Next stop is to create a archive menuing program to let people select which archive is to be examined. This will look a lot like the menu system, but no descriptions, I think. OR, should I just build it into the existing menu? Comments? -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ From m_konermann@gmx.de Fri May 17 14:51:19 2002 From: m_konermann@gmx.de (Marcus K.) Date: Fri, 17 May 2002 15:51:19 +0200 Subject: [Tutor] Problems working with the function PyArg_Parse Message-ID: <3CE50AD7.2020203@gmx.de> Hi ! I want to convert a python script return value (9,2034) to c. It´s a double and it seems that i use the function PyArg_Parse in the the wrong way. Here' s the code: ... double *cstr; PyObject *pmod, *pargs, *pmeth, *pres; ... pres = PyEval_CallObject(pmeth, pargs); Py_DECREF(pmeth); Py_DECREF(pargs); if (pres == NULL) error("Error calling para()"); if (!PyArg_Parse(pres, "i", &cstr)) /* convert to C */ error("Can't convert para() result"); printf("%d\n", cstr); Py_DECREF(pres); Perhaps anyone can tell me to use the options (pres, "i", &cstr) in the right way. I only get a "9" ,but not 9,2034. Greetings Marcus From lumbricus@gmx.net Fri May 17 15:35:30 2002 From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=) Date: Fri, 17 May 2002 16:35:30 +0200 (MEST) Subject: [Tutor] Problems working with the function PyArg_Parse References: <3CE50AD7.2020203@gmx.de> Message-ID: <30771.1021646130@www7.gmx.net> > Hi ! > > I want to convert a python script return value (9,2034) to c. It´s a > double and it seems that i use the function PyArg_Parse in the the wrong > way. > Here' s the code: > > ... > double *cstr; > PyObject *pmod, *pargs, *pmeth, *pres; > ... > pres = PyEval_CallObject(pmeth, pargs); > Py_DECREF(pmeth); > Py_DECREF(pargs); > if (pres == NULL) > error("Error calling para()"); > if (!PyArg_Parse(pres, "i", &cstr)) /* convert to C */ > error("Can't convert para() result"); > printf("%d\n", cstr); ^^ printf("%f\n", cstr); > Py_DECREF(pres); > > Perhaps anyone can tell me to use the options (pres, "i", &cstr) in the > right way. I only get a "9" ,but not 9,2034. > > Greetings > Marcus HTH and Greetings, J"o! -- $ make LOVE Make: Don't know how to make LOVE. Stop. $ -- GMX - Die Kommunikationsplattform im Internet. http://www.gmx.net From stuart_clemons@us.ibm.com Fri May 17 15:50:35 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Fri, 17 May 2002 10:50:35 -0400 Subject: [Tutor] Creating unique output log files Message-ID: Hi all: I'm working on a program that will be run in the am and pm, everyday. The program needs to create a unique output log everytime it's run. I'm using Python v2.2.1 under WinNT4. Any hints on how I can automatically create a unique output log everytime it's run. Making the date a part of the output log file name seems to make a lot of sense, but I don't know how to do it. Something like 0517am.out & 0517pm.out. Thanks in advance. - Stuart From shalehperry@attbi.com Fri May 17 16:15:29 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri, 17 May 2002 08:15:29 -0700 (PDT) Subject: [Tutor] Creating unique output log files In-Reply-To: Message-ID: On 17-May-2002 stuart_clemons@us.ibm.com wrote: > > Hi all: > > I'm working on a program that will be run in the am and pm, everyday. The > program needs to create a unique output log everytime it's run. > > I'm using Python v2.2.1 under WinNT4. > > Any hints on how I can automatically create a unique output log everytime > it's run. Making the date a part of the output log file name seems to > make a lot of sense, but I don't know how to do it. Something like > 0517am.out & 0517pm.out. > Look at the standard module 'time' in the library reference. From GBunting864@Worldsavings.com Fri May 17 17:43:16 2002 From: GBunting864@Worldsavings.com (Bunting, Glen, IG) Date: Fri, 17 May 2002 09:43:16 -0700 Subject: [Tutor] Help with copying files Message-ID: <3BD366A4D49B7D4FAD4E41E4C99784B96AE7E6@OK1EMS2.worldsavings.com> Hello, I am very new to Python and programming in general. I thought that = the best way to start learning Python would be to write a small program tha= t does something similar to a batch file that I have already written. Basi= cally I want to be able to copy the same directory every night, a backup sc= ript if you will. Anyway, I've written what I thought would work, and it s= tart to work and creates the root directory and a file, but when it goes to= create the other file, it fails. Below is the code and the error message = I get. What am I doing wrong? =20 Thanks Glen PS I am on a win2k machine running ActiveState Python 2.2 ##Begin code import os, shutil def walker(arg, dirname, filenames): # Lists directories, files=20 for filename in filenames: path =3D dirname + os.sep + filename print path newdir =3D dirname[2:] os.makedirs('d:\\temp' +newdir) shutil.copy(path, 'd:\\temp\downloads') file =3D open('test1.txt', 'a') file.write(newdir + '\n') os.path.walk('c:\\downloads', walker, None) Here is the error I get: C:\python\examples\learning>walker.py c:\downloads\aaw.exe c:\downloads\active ports Traceback (most recent call last): File "C:\python\examples\learning\walker.py", line 14, os.path.walk('c:\\downloads', walker, None) File "C:\Python22\lib\ntpath.py", line 318, in walk func(arg, top, names) File "C:\python\examples\learning\walker.py", line 9, os.makedirs('d:\\temp' +newdir) File "C:\Python22\lib\os.py", line 203, in makedirs mkdir(name, mode) OSError: [Errno 17] File exists: 'd:\\temp\\downloads' ***************************************************************************= ** If you are not the intended recipient of this e-mail, please notify=20 the sender immediately. The contents of this e-mail do not amend=20 any existing disclosures or agreements unless expressly stated. ***************************************************************************= ** From alex@gabuzomeu.net Fri May 17 18:05:43 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Fri, 17 May 2002 19:05:43 +0200 Subject: [Tutor] Creating unique output log files In-Reply-To: <20020517160004.20750.67757.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020517190058.00e406a0@pop3.norton.antivirus> Hi Stuart, At 12:00 17/05/2002 -0400, tutor-request@python.org wrote: >From: stuart_clemons@us.ibm.com >Date: Fri, 17 May 2002 10:50:35 -0400 >Subject: [Tutor] Creating unique output log files >Any hints on how I can automatically create a unique output log everytime >it's run. Making the date a part of the output log file name seems to >make a lot of sense, but I don't know how to do it. Something like >0517am.out & 0517pm.out. Try this: import time timeStamp = time.gmtime(time.time()) formatString = "%Y-%m-%d-%H-%M-%S" print "%s.out" % time.strftime(formatString, timeStamp) >>> 2002-05-17-17-02-32.out You could use a similar value as a file name. See the library section for the "time" module for more info. Cheers. Alexandre From darkside666@mad.scientist.com Fri May 17 21:31:30 2002 From: darkside666@mad.scientist.com (CS Player) Date: Fri, 17 May 2002 15:31:30 -0500 Subject: [Tutor] question Message-ID: <20020517203130.8957.qmail@mail.com> I want know how to program with Python -- _______________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup From darkside666@mad.scientist.com Fri May 17 21:36:38 2002 From: darkside666@mad.scientist.com (CS Player) Date: Fri, 17 May 2002 15:36:38 -0500 Subject: [Tutor] re Message-ID: <20020517203638.18734.qmail@mail.com> Can you teach me how to break into a computer with Python? -- _______________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup From rob@uselesspython.com Fri May 17 22:11:07 2002 From: rob@uselesspython.com (Rob Andrews) Date: Fri, 17 May 2002 16:11:07 -0500 Subject: [Tutor] re References: <20020517203638.18734.qmail@mail.com> Message-ID: <3CE571EB.6050303@uselesspython.com> If the python was already petrified into a purely stone artifact, you could probably use it to beat on the computer until it broke open. CS Player wrote: > Can you teach me how to break into a computer with Python? > From stuart@sharedreality.org Fri May 17 22:08:33 2002 From: stuart@sharedreality.org (Stuart Smith) Date: Fri, 17 May 2002 22:08:33 +0100 Subject: [Tutor] question In-Reply-To: <20020517203130.8957.qmail@mail.com> Message-ID: <5.1.0.14.2.20020517220044.00a70468@sharedreality.org> Start off by taking a look at the Python Tutorial http://www.python.org/doc/current/tut/tut.html - I found it to be a really good intro to Python. There's a number of good books about too, I bought Learning Python, published by O'Reilly. Have a look at http://amk.ca/bookstore for a list of Python books. At 15:31 17/05/2002 -0500, CS Player wrote: >I want know how to program with Python From stuart@sharedreality.org Fri May 17 22:00:31 2002 From: stuart@sharedreality.org (Stuart Smith) Date: Fri, 17 May 2002 22:00:31 +0100 Subject: [Tutor] re In-Reply-To: <20020517203638.18734.qmail@mail.com> Message-ID: <5.1.0.14.2.20020517215922.00a71c10@sharedreality.org> I think you're looking in the wrong place here. At 15:36 17/05/2002 -0500, CS Player wrote: >Can you teach me how to break into a computer with Python? From darkside666@mad.scientist.com Sat May 18 00:37:11 2002 From: darkside666@mad.scientist.com (CS Player) Date: Fri, 17 May 2002 18:37:11 -0500 Subject: [Tutor] question Message-ID: <20020517233711.43276.qmail@mail.com> I've heard that Python is good for hacking -- I want to know more! -- _______________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup From jeff@ccvcorp.com Sat May 18 01:34:09 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 17 May 2002 17:34:09 -0700 Subject: [Tutor] question References: <20020517233711.43276.qmail@mail.com> Message-ID: <3CE5A180.E807A6AF@ccvcorp.com> CS Player wrote: > I've heard that Python is good for hacking -- I want to know > more! Check this out: http://www.tuxedo.org/~esr/faqs/hacker-howto.html If you're still interested in Python after reading that, talk to us then. Jeff Shannon Technician/Programmer Credit International From MBussell@aol.com Sat May 18 02:45:51 2002 From: MBussell@aol.com (MBussell@aol.com) Date: Fri, 17 May 2002 21:45:51 EDT Subject: [Tutor] Newbie Question: Define Funcations Message-ID: <23.1e5a1bc6.2a170c4f@aol.com> --part1_23.1e5a1bc6.2a170c4f_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Dear Tutor: I am attempting to learn my first language, and am having some trouble with defining functions. I understand the theory - but the application does not seem to perform like the two text's I have downloaded. >From my understanding, the parameter is the name used inside a function to refer to the value passed as an argument. Example: def printtwice(bruce): print bruce, bruce printtwice(spam) Theoretical output: spam spam Actual output: Traceback (most recent call last): File "", line 1, in ? printtwice(spam) NameError: name 'spam' is not defined Do I have to define the argument before I use it in a function (thought one of the benefits of a function was to assign an argument to the value)? Thanks, Andy --part1_23.1e5a1bc6.2a170c4f_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit Dear Tutor:

I am attempting to learn my first language, and am having some trouble with defining functions.  I understand the theory - but the application does not seem to perform like the two text's I have downloaded.

From my understanding, the parameter is the name used inside a function to refer to the value passed as an argument.  Example:

      def printtwice(bruce):
            print bruce, bruce

      printtwice(spam)       
Theoretical output:
      spam spam

Actual output:
      Traceback (most recent call last):
 File "<pyshell#3>", line 1, in ?
   printtwice(spam)
NameError: name 'spam' is not defined

Do I have to define the argument before I use it in a function (thought one of the benefits of a function was to assign an argument to the value)?

Thanks,
Andy
--part1_23.1e5a1bc6.2a170c4f_boundary-- From kalle@lysator.liu.se Sat May 18 03:23:38 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Sat, 18 May 2002 04:23:38 +0200 Subject: [Tutor] Newbie Question: Define Funcations In-Reply-To: <23.1e5a1bc6.2a170c4f@aol.com> References: <23.1e5a1bc6.2a170c4f@aol.com> Message-ID: <20020518022338.GB4535@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [MBussell@aol.com] > From my understanding, the parameter is the name used inside a > function to refer to the value passed as an argument. Example: > > def printtwice(bruce): > print bruce, bruce > > printtwice(spam) > Theoretical output: > spam spam > > Actual output: > Traceback (most recent call last): > File "", line 1, in ? > printtwice(spam) > NameError: name 'spam' is not defined The thing is that spam hasn't been defined in the place where you call printtwice(): >>> def printtwice(bruce): ... print bruce, bruce ... >>> printtwice(spam) Traceback (most recent call last): File "", line 1, in ? NameError: name 'spam' is not defined >>> spam = "Hello world" # Now give a value to spam >>> printtwice(spam) Hello world Hello world >>> When you call the function printtwice, the Python interpreter tries to find the value of the variable spam to send as an argument to the function. As it hasn't been given a value, there is an error message. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE85bsjdNeA1787sd0RAj8vAKCevrQL9FHFI1K+utWHgY9U3bEcfQCfaRk4 yJnNdAYccAwqI2JzCVmQpcE= =lJzj -----END PGP SIGNATURE----- From shalehperry@attbi.com Sat May 18 03:56:32 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri, 17 May 2002 19:56:32 -0700 (PDT) Subject: [Tutor] Newbie Question: Define Funcations In-Reply-To: <20020518022338.GB4535@i92.ryd.student.liu.se> Message-ID: > > The thing is that spam hasn't been defined in the place where you call > printtwice(): > >>>> def printtwice(bruce): > ... print bruce, bruce > ... >>>> printtwice(spam) > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'spam' is not defined >>>> spam = "Hello world" # Now give a value to spam >>>> printtwice(spam) > Hello world Hello world >>>> > > When you call the function printtwice, the Python interpreter tries to > find the value of the variable spam to send as an argument to the > function. As it hasn't been given a value, there is an error message. > and printtwice('spam') will print the word spam twice. Note the quotes. This makes spam into a string and not a variable name. From idiot1@netzero.net Sat May 18 06:00:24 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sat, 18 May 2002 01:00:24 -0400 Subject: [Tutor] TL footer issues Message-ID: <3CE5DFE8.77B3438B@netzero.net> In the devloping of TL, I am adding new features, and trying to refine existing ones, such as the footers. Spam people tend to not properly identify their site or how tio unsubscribe, and I am always afraid someone will use some of my work to produce spam or do other unethical things. so I was refining some features to insure this was inconvienced as much as possible. for example, I was going to insure that NO MATTER WHAT, TL offered a link to the menu to manage subscriptons, a 1 line footer that ALWAYS appeared, no matter what the user did. But a potential user testing it wrote back and let me know one of his co-hosting clients would REALLY like to have TOTAL footer control, and this uncontrollable featuer would eliminate TL from consideration. Hmmm... So I changed things. In 5 minutes. Python, ya gotta love it. IF this decision proves to be a problem, changing again is just as quick. Let's see how it works out. Oh, and the archiving feature works fine. Now to write an archive VIEWING script- actually, 2 of them, one as a menu maker, the other as the actual reader. Probably do that saterday night... -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ From charlie@begeistert.org Sat May 18 20:22:09 2002 From: charlie@begeistert.org (Charlie Clark) Date: Sat, 18 May 2002 19:22:09 +0000 Subject: [Tutor] Re: Help with copying files In-Reply-To: <20020518160004.23202.11594.Mailman@mail.python.org> References: <20020518160004.23202.11594.Mailman@mail.python.org> Message-ID: <20020518192508.4038.1@bepc.1021749079.fake> On 2002-05-18 at 16:00:04 [+0000], you wrote: > def walker(arg, dirname, filenames): > # Lists directories, files=20 > for filename in filenames: > path =3D dirname + os.sep + filename > print path > newdir =3D dirname[2:] > os.makedirs('d:\\temp' +newdir) > shutil.copy(path, 'd:\\temp\downloads') > file =3D open('test1.txt', 'a') > file.write(newdir + '\n') > > os.path.walk('c:\\downloads', walker, None) if this is your error: os.makedirs('d:\\temp' +newdir) File "C:\Python22\lib\os.py", line 203, in makedirs mkdir(name, mode) OSError: [Errno 17] File exists: 'd:\\temp\\downloads' I think it is because you are trying to make d:\temp\downloads more than once. Try os.mkdir('d:/temp/download' + newdir) instead and I suggest you use forward slashes as separators - it's easier to type and more portable. Charlie From erikprice@mac.com Sat May 18 20:13:15 2002 From: erikprice@mac.com (Erik Price) Date: Sat, 18 May 2002 15:13:15 -0400 Subject: [Tutor] re In-Reply-To: <20020517203638.18734.qmail@mail.com> Message-ID: <4E11FC2D-6A93-11D6-8F0D-00039351FE6A@mac.com> On Friday, May 17, 2002, at 04:36 PM, CS Player wrote: > Can you teach me how to break into a computer with Python? Why? From erikprice@mac.com Sat May 18 20:15:18 2002 From: erikprice@mac.com (Erik Price) Date: Sat, 18 May 2002 15:15:18 -0400 Subject: [Tutor] question In-Reply-To: <20020517233711.43276.qmail@mail.com> Message-ID: <9760FF20-6A93-11D6-8F0D-00039351FE6A@mac.com> On Friday, May 17, 2002, at 07:37 PM, CS Player wrote: > I've heard that Python is good for hacking -- I want to know > more! Read the tutorials. It's very good for hacking. I broke into a few computers with it just last week. There's tons of newsgroups and bulletin boards dedicated to hacking with Python, such as this one. But we can't just tell you how to hack -- you need to take the initiative to learn some of the basics. When you have a specific question, ask it here. From erikprice@mac.com Sat May 18 20:25:49 2002 From: erikprice@mac.com (Erik Price) Date: Sat, 18 May 2002 15:25:49 -0400 Subject: [Tutor] api vs library -- a definition Message-ID: <0FB69AE3-6A95-11D6-8F0D-00039351FE6A@mac.com> True or false: An API refers to the rules and guidelines and protocols etc that are set forth by a library. In other words, a library has an API. So API is really more of a description of a library, whereas a library is an actual physical chunk of code (well, as physical as code gets). I'm probably wrong about this, but if someone could clarify for me and set me right that would make me feel better. It seems that people are always referring to APIs as though they are physical things, but what they are really referring to is a library of code, right? (for example, "My company had to purchase an API to handle that problem.") Thank you, Erik From erikprice@mac.com Sat May 18 20:35:04 2002 From: erikprice@mac.com (Erik Price) Date: Sat, 18 May 2002 15:35:04 -0400 Subject: [Tutor] Design - getFoo and setFoo methods In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5D5@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <5A4D6CFA-6A96-11D6-8F0D-00039351FE6A@mac.com> Whoah Alan can we back up just a minute here... new to OO design myself so I am curious about this subject. First some context: > getXXX/setXXX makes sense if the XXX is a property accessed > via a common protocol(like in JavaBeans) by a Tool (like a > GUI builder). > > They also make sense if you put valuidation code in the > set method to check the values lie within constraints. > Or put security checks to make sure the user has valid > access rights. > > But as a general principle they are a bad idea since they > basically break the principle of data hiding. You should > access objects using a behaviourally focussed API and > the internal function of the methods should determine > the data held. The data(attributes) should only be there > to support the methods. Of course the methods may be > there to expose data but usually this will be ion a lump > not single attributes(eh a getAddress() method retuirns > several fields not just one and a getAddressString returns > the sae info as a single string. How it is stored internally > is unknown and irrelevant to the class user. I think I understand what you're saying. But it goes against what I was originally thinking when I was learning about objects. According to the above (I think) an object is there to perform certain actions or behaviors. This may include the handling/storage of data, but not necessarily. I thought that the idea of object oriented programming was to treat everything as objects, which helps organize your code. What you're saying above is that objects don't exist to turn data into objects but rather code constructs into objects. What's the official word? Here's another, related question -- I use objects to store bunches of data in my application, for instance a Person object keeps track of a name and a database primary key ID number, etc. A subclass of Person could be Recipient, who is someone with an address and a preferred shipping method. However, I've been taking a shortcut in my code (because I didn't know any better) by directly accessing the attributes of the class in the code itself. But in a book I am reading (Beginning Java Objects by Jacquie Barker) it is recommended to use setThing and getThing methods instead. Why do I do this? Well, because in one part of the application I need to display a Recipient's address. I would normally do this by creating a method in the Recipient class definition to display an address. But in another part of the application, I would do the same thing but the Recipient's name needs to be a hyperlink that points to a certain page. So that means I have to create a whole new method that does the exact same thing as the previous method but turns the name into a hyperlink. Not only does this seem clumsy, but URL in the "href" part of the hyperlink may change depending on circumstances. So right now, I just pull out the class attributes and the calling code does the work. But this seems to be NOT object oriented at all. One way around this would be to make a class to display addresses, and then a subclass of that which displays addresses with names as hyperlinks. But these things seem less like objects and more like methods, so I'm kind of hesitant to do that. And as far as defining the content of the "href" attribute, I could probably pass this as a string argument to the method... it gets very confusing. What would a Real Programmer do in this situation? Erik From ak@silmarill.org Sat May 18 21:05:28 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 18 May 2002 16:05:28 -0400 Subject: [Tutor] Design - getFoo and setFoo methods In-Reply-To: <5A4D6CFA-6A96-11D6-8F0D-00039351FE6A@mac.com> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5D5@mbtlipnt02.btlabs.bt.co.uk> <5A4D6CFA-6A96-11D6-8F0D-00039351FE6A@mac.com> Message-ID: <20020518200528.GA732@ak.silmarill.org> On Sat, May 18, 2002 at 03:35:04PM -0400, Erik Price wrote: > Whoah Alan can we back up just a minute here... new to OO design myself > so I am curious about this subject. First some context: > > >getXXX/setXXX makes sense if the XXX is a property accessed > >via a common protocol(like in JavaBeans) by a Tool (like a > >GUI builder). > > > >They also make sense if you put valuidation code in the > >set method to check the values lie within constraints. > >Or put security checks to make sure the user has valid > >access rights. > > > >But as a general principle they are a bad idea since they > >basically break the principle of data hiding. You should > >access objects using a behaviourally focussed API and > >the internal function of the methods should determine > >the data held. The data(attributes) should only be there > >to support the methods. Of course the methods may be > >there to expose data but usually this will be ion a lump > >not single attributes(eh a getAddress() method retuirns > >several fields not just one and a getAddressString returns > >the sae info as a single string. How it is stored internally > >is unknown and irrelevant to the class user. > > I think I understand what you're saying. But it goes against what I was > originally thinking when I was learning about objects. According to the > above (I think) an object is there to perform certain actions or > behaviors. This may include the handling/storage of data, but not > necessarily. > > I thought that the idea of object oriented programming was to treat > everything as objects, which helps organize your code. What you're > saying above is that objects don't exist to turn data into objects but > rather code constructs into objects. What's the official word? > I don't understand this fully myself, but I guess if you have a bunch of data, you can put it in a dictionary - a class instance is an overkill, because it also allows you to have methods, which you don't need. person = {"phone": "718 113 1134", "address": "1834 E13th St.", "name": "Bartley McBartolomeu" } instead of person.phone = ... person.address = ... etc Now if you had a function send_email to that person, it's better to wrap it all in one object: person.send_email(text) instead of: send_email(person_dict, text) I think it's still okay to just use classes to store only data, (if the overhead is not a problem), but it's not OO design, it's just preferring obj.member syntax to dict[member]. IOW it's now a matter of syntax, not design. Design is the same as in a dictionary. Again, I'm not too sure about all of this, so if anyone can correct me, please do :-). - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From shalehperry@attbi.com Sat May 18 21:12:25 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat, 18 May 2002 13:12:25 -0700 (PDT) Subject: [Tutor] api vs library -- a definition In-Reply-To: <0FB69AE3-6A95-11D6-8F0D-00039351FE6A@mac.com> Message-ID: On 18-May-2002 Erik Price wrote: > > True or false: > > An API refers to the rules and guidelines and protocols etc that are set > forth by a library. In other words, a library has an API. So API is > really more of a description of a library, whereas a library is an > actual physical chunk of code (well, as physical as code gets). > > I'm probably wrong about this, but if someone could clarify for me and > set me right that would make me feel better. It seems that people are > always referring to APIs as though they are physical things, but what > they are really referring to is a library of code, right? (for example, > "My company had to purchase an API to handle that problem.") > You have it right. The easy way to think about this is an API is a specification and the library is an implementation. One API can have many, many implementations. There is Windows and there is WINE for instance. Both implement the Windows GUI APIs. From pythontutor@venix.com Sat May 18 21:47:07 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Sat, 18 May 2002 16:47:07 -0400 Subject: [Tutor] Design - getFoo and setFoo methods References: <5A4D6CFA-6A96-11D6-8F0D-00039351FE6A@mac.com> Message-ID: <3CE6BDCB.7090409@venix.com> Erik Price wrote: > it gets very confusing. What would a Real Programmer do in this situation? Well, until we hear from a Real Programmer, here is my opinion: The emphasis on Get/Set methods from some sources misses the mark. The goal is to prevent "dumb" updates of an objects data. A Set method can check that the new value is consistent with the other values in the object and disallow the new value or change some of the other values to keep the object "consistent". Now Python can use "Set methods" even when doing what looks like a direct assignment. Typically, you write the amount of hidden Get/Set stuff that makes sense for your application and usage. See the Python2.2 documentation on property and __setattr__. In web applications, it is not usually practical to deal with setting one attribute at a time. The values come back from a form. Youe set them all if possible, or else return the form with some kind of error response so that the problem can be fixed and the form can be resubmitted. Your object's Set method will deal with all of the attributes that are grouped together on the form. In this case you probably won't need Set methods that deal with one attribute at a time. Methods are the key to using objects. In another post Alan Gauld wrote: "Class definitions should be driven by behaviour not data." You wrote about needing to produce two kinds of addresses, one with name and one with a hyperlinked name. I would be inclined to have methods: print_name(self, URL=None): if URL produce hyperlinked name print_address(self): prints address EXCEPT for name and possibly: print_name_address(self, URL=None): self.print_name(URL) self.print_address() HTH -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From Desai.Dinakar@mayo.edu Thu May 16 21:19:20 2002 From: Desai.Dinakar@mayo.edu (Dinakar Desai) Date: Thu, 16 May 2002 15:19:20 -0500 Subject: [Tutor] Looking for html to pdf module References: <20020516192402.76408.qmail@web14703.mail.yahoo.com> Message-ID: <3CE41448.F866D508@mayo.edu> Titu Kim wrote: > Hi there, > I am doing some simple reporting mechanism in cgi. > I want to provide an option to output a pdf format > instead of html page. So I need a module that can > convert a complete html string into pdf format so it > can be download. Is such module exist? > > Thanks. > > __________________________________________________ > Do You Yahoo!? > LAUNCH - Your Yahoo! Music Experience > http://launch.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor I used HTMLDoc software. It converts HTML to PDF. Here is the reference: www.easysw.com/ htmldoc. This is not a module for python but standalone program. Dinakar -- Dinakar Desai, Ph.D Phone: 289-3972/266-2831 From Desai.Dinakar@mayo.edu Sat May 18 00:26:16 2002 From: Desai.Dinakar@mayo.edu (Dinakar Desai) Date: Fri, 17 May 2002 18:26:16 -0500 Subject: [Tutor] need help with string References: <20020517203638.18734.qmail@mail.com> Message-ID: <3CE59198.F7A5E73C@mayo.edu> I have a long string say 80 characters and want to split into exactly 10 chars except last one. Last one can be 10 or less characters. I could do it in perl but want to convert that function from perl to python. I have looked in string and re modules. I could not find anything comparable. I am not proficient in perl or python. Please bear with me. Here is my perl code snippet: #!/usr/bin/env perl # use strict; my $strg = "This is very long string dfjksajdfkjskajfkjsdkajfksdjkfjkdjsakfjkdsjakfjsdkj"; my @arr_str; my $ind = 0; for (my $i = 0; $i < length($strg); $i +=10) { $arr_str[$ind++] = substr($strg,$i, 10); } foreach my $f (@arr_str) { print "$f\n"; } print "@arr_str"; Thank you. Dinakar From ak@silmarill.org Sun May 19 00:16:42 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 18 May 2002 19:16:42 -0400 Subject: [Tutor] need help with string In-Reply-To: <3CE59198.F7A5E73C@mayo.edu> References: <20020517203638.18734.qmail@mail.com> <3CE59198.F7A5E73C@mayo.edu> Message-ID: <20020518231642.GA2117@ak.silmarill.org> On Fri, May 17, 2002 at 06:26:16PM -0500, Dinakar Desai wrote: > I have a long string say 80 characters and want to split into exactly 10 > chars except last one. Last one can be 10 or less characters. I could do > it in perl but want to convert that function from perl to python. I > have looked in string and re modules. I could not find anything > comparable. > > I am not proficient in perl or python. Please bear with me. > > Here is my perl code snippet: > #!/usr/bin/env perl > # > use strict; > my $strg = "This is very long string > dfjksajdfkjskajfkjsdkajfksdjkfjkdjsakfjkdsjakfjsdkj"; > my @arr_str; > > my $ind = 0; > for (my $i = 0; $i < length($strg); $i +=10) > { > $arr_str[$ind++] = substr($strg,$i, 10); > } > foreach my $f (@arr_str) > { > print "$f\n"; > } > > print "@arr_str"; > > > Thank you. > > Dinakar > >>> s = 't'*75 >>> s 'ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt' >>> lst = [] >>> while 1: ... chunk, s = s[:10], s[10:] ... lst.append(chunk) ... if not s: ... break ... >>> lst ['tttttttttt', 'tttttttttt', 'tttttttttt', 'tttttttttt', 'tttttttttt', 'tttttttttt', 'tttttttttt', 'ttttt'] I don't know perl (I have vague memories from a few years back but your code didn't ring a bell), so this may be a bit off. Do you want to end up with the list of substrings? - Andrei > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From idiot1@netzero.net Sun May 19 01:05:10 2002 From: idiot1@netzero.net (kirk Bailey) Date: Sat, 18 May 2002 20:05:10 -0400 Subject: [Tutor] tl1.3.0 almost ready Message-ID: <3CE6EC36.789D13A9@netzero.net> Now includes archiving and archive menu and reader scripts, and a modification to how we manage footers give TOTAL control over footer presence and/or content; plug for TL is in default footer and dissapears if you create a custom footer for the list and do not include it. Archive will be available on the site as soon as some testing toinsure satisfactory service has happened- say 5 days. The archive menu is accessed via a link in the main menu for TL, and you can access it directly through a normal html link. Take a look. main menu link: http://www.tinylist.org/cgi-bin/TLwebmgr.py archive menu link: http://www.tinylist.org/cgi-bin/TLarchivemenu.py -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ From hsteiger@comcast.net Sun May 19 01:59:05 2002 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Sat, 18 May 2002 19:59:05 -0500 Subject: [Tutor] File access codes in Python Message-ID: <000d01c1fed0$602ed860$0201a8c0@eagle> This is a multi-part message in MIME format. --Boundary_(ID_9FVJrj2fxtLfbAnQ9gnvKA) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT To All: In Tcl, one can open a file for reading, writing, and both reading AND writing. However, in Python, it appears from the book I have, and from some online information, that one does not have the option to open a file for BOTH reading and writing. Is this true? If it is, it complicates the situation. One should not have to open a program TWICE, just to read the file at one point, and then write to the same file at some other point in the program. Thanks. Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net --Boundary_(ID_9FVJrj2fxtLfbAnQ9gnvKA) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: 7BIT
To All:
 
In Tcl, one can open a file for reading, writing, and both reading AND writing.
 
However, in Python, it appears from the book I have, and from some online
information, that one does not have the option to open a file for BOTH reading
and writing.
 
Is this true? If it is, it complicates the situation. One should not have to open
a program TWICE, just to read the file at one point, and then write to the same
file at some other point in the program.  
 
Thanks.
 
Henry Steigerwaldt
Hermitage, TN
--Boundary_(ID_9FVJrj2fxtLfbAnQ9gnvKA)-- From ak@silmarill.org Sun May 19 02:07:15 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 18 May 2002 21:07:15 -0400 Subject: [Tutor] File access codes in Python In-Reply-To: <000d01c1fed0$602ed860$0201a8c0@eagle> References: <000d01c1fed0$602ed860$0201a8c0@eagle> Message-ID: <20020519010715.GA2874@ak.silmarill.org> On Sat, May 18, 2002 at 07:59:05PM -0500, Henry Steigerwaldt wrote: > To All: > > In Tcl, one can open a file for reading, writing, and both reading AND writing. > > However, in Python, it appears from the book I have, and from some online > information, that one does not have the option to open a file for BOTH reading > and writing. > > Is this true? If it is, it complicates the situation. One should not have to open > a program TWICE, just to read the file at one point, and then write to the same > file at some other point in the program. > > Thanks. > > Henry Steigerwaldt > Hermitage, TN > Email: hsteiger@comcast.net > Yeah, you can do that: f = open("test", 'r+') -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From alex@gabuzomeu.net Sun May 19 10:18:27 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Sun, 19 May 2002 11:18:27 +0200 Subject: [Tutor] Design - getFoo and setFoo methods In-Reply-To: <20020519010601.1301.94978.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020519103721.00b72460@pop3.norton.antivirus> Hello, At 21:06 18/05/2002 -0400, you wrote: >Date: Sat, 18 May 2002 15:35:04 -0400 >Subject: Re: [Tutor] Design - getFoo and setFoo methods >From: Erik Price [about getFoo() and setFoo() methods:] > > But as a general principle they are a bad idea since they > > basically break the principle of data hiding. You should > > access objects using a behaviourally focussed API and > > the internal function of the methods should determine > > the data held. The data(attributes) should only be there > > to support the methods. Of course the methods may be > > there to expose data but usually this will be ion a lump > > not single attributes(eh a getAddress() method retuirns > > several fields not just one and a getAddressString returns > > the sae info as a single string. How it is stored internally > > is unknown and irrelevant to the class user. > >I think I understand what you're saying. But it goes against what I was >originally thinking when I was learning about objects. According to the >above (I think) an object is there to perform certain actions or >behaviors. This may include the handling/storage of data, but not >necessarily. > >I thought that the idea of object oriented programming was to treat >everything as objects, which helps organize your code. What you're >saying above is that objects don't exist to turn data into objects but >rather code constructs into objects. What's the official word? My understanding is that objects are chunks of (actions + data). Their behaviour will be "doing something to/with some stuff" (not a very precise definition, I'm afraid). >Here's another, related question -- I use objects to store bunches of >data in my application, for instance a Person object keeps track of a >name and a database primary key ID number, etc. A subclass of >Person could be Recipient, who is someone with an address and a preferred >shipping method. However, I've been taking a shortcut in my code (because >I didn't know any better) by directly accessing the attributes of the >class in the code itself. But in a book I am reading (Beginning Java >Objects by Jacquie Barker) it is recommended to use setThing and getThing >methods instead. > >Why do I do this? Well, because in one part of the application I need >to display a Recipient's address. I would normally do this by creating >a method in the Recipient class definition to display an address. But >in another part of the application, I would do the same thing but the >Recipient's name needs to be a hyperlink that points to a certain page. >So that means I have to create a whole new method that does the exact >same thing as the previous method but turns the name into a hyperlink. >Not only does this seem clumsy, but URL in the "href" part of the >hyperlink may change depending on circumstances. I have a related situation: in one app, I have "macros" (actions carried out on data). The macro results need to be rendered to HTML. I use two objects: a FooMacro class and an FooMacroRenderer class. I tried to standardize xMacro classes and xMacroRenderer classes along different lines (the ones select/transform data, the others display it in HTML format). Maybe you can try to look at your problem in this way. Maybe the "displaying" part of the problem does not belong in the Recipient class. Cheers. Alexandre From pythonpython@hotmail.com Sun May 19 12:02:51 2002 From: pythonpython@hotmail.com (Hy Python) Date: Sun, 19 May 2002 11:02:51 +0000 Subject: [Tutor] How to build a basic console with Tkinter. etc.? Message-ID: Could someone please give me some advice on how to build a console widget? This widget need to be embeded in a Tkinter frame and serve as STDOUT for DISPLAYING information generated by some functions' print statements? Thank you very much. Hy _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From apython101@yahoo.com Sun May 19 15:34:19 2002 From: apython101@yahoo.com (john public) Date: Sun, 19 May 2002 07:34:19 -0700 (PDT) Subject: [Tutor] python scripts in HTML documents Message-ID: <20020519143419.24619.qmail@web21104.mail.yahoo.com> --0-2091566826-1021818859=:19062 Content-Type: text/plain; charset=us-ascii Can I insert Python code into an HTML document like I can insert a piece of JavaScript code into an HTML document? JavaScript is a scripting language, and Python is a scripting language and also more. Yes? TIA John --------------------------------- Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience --0-2091566826-1021818859=:19062 Content-Type: text/html; charset=us-ascii

Can I insert Python code into an HTML document like I can insert a piece of JavaScript code into an HTML document? JavaScript is a scripting language, and Python is a scripting language and also more. Yes?

TIA

 John



Do You Yahoo!?
LAUNCH - Your Yahoo! Music Experience --0-2091566826-1021818859=:19062-- From alan.gauld@bt.com Sun May 19 17:28:38 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 May 2002 17:28:38 +0100 Subject: [Tutor] Design - getFoo and setFoo methods Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5DC@mbtlipnt02.btlabs.bt.co.uk> > above (I think) an object is there to perform certain actions or > behaviors. This may include the handling/storage of data, but not > necessarily. A object exists to fulfill certain responsibilities(recall my earlier post about CRC cards?). The responsibilities will either be functionally oriented or data oriented but in either case the focus should be on operations not data (which should be hidden(aka private). Jacobsen has the concept of 3 types of objects: interface - things the user or other systems interact with controller - things that encapsulate the flow of control of the system entity - things that hold the state(aka data) of the system Now this can be abused to create horrid OO systems by turning functions into controllers and data into entities but provided we also apply the Law of deMeter (summarized as "don't talk to strangers") we wind up with a nice categorisation of object types within an OO system. > I thought that the idea of object oriented programming was to treat > everything as objects, which helps organize your code. Correct. > What you're saying above is that objects don't exist to turn data into > objects but rather code constructs into objects. Forget data and code they don't exist as separate entities in an OO system. All data and code is contained within some object or other. > to display a Recipient's address. I would normally do this > by creating a method in the Recipient class definition to > display an address. But read the requirement. You want to display an address so the address object should have the display method. Now the Recipient may have one too to show all recipuient details and in part it will call the address.display() > .... I would do the same thing but the > Recipient's name needs to be a hyperlink that points to a > certain page. I'm not sure hopw this relates to the address bit? Do you mean you need to display recipient details where some recipients have text names and others URLs? Sounds like a job for inheritance/polymorphism and a urlRecipient? The latters display calls the same address display but formats the name as a URL? Or have I missed the point? > calling code does the work. But this seems to be > NOT object oriented at all. Correct. Refactor the classes to use an Address class and subclass recipient to the number of display methods you need. > way around this would be to make a class to display > addresses, # An address class. Its the old noun/verb rule. nouns = objects, verbs = methods > a subclass of that which displays addresses with names names are separate from addresses. More than one person can have the same address! > What would a Real Programmer do in this situation? See above, but... First I'd separate display from the classes. Get the methods to return a string and let the UI or application figure out how to display it to the user. Thats its responsibility. HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Sun May 19 17:46:41 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 May 2002 17:46:41 +0100 Subject: [Tutor] Newbie Question: Define Funcations Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5DE@mbtlipnt02.btlabs.bt.co.uk> > From my understanding, the parameter is the name used inside > a function to refer to the value passed as an argument. Example: Well done some programmers take years to appreciate that subtlety! > def printtwice(bruce): > print bruce, bruce > > printtwice(spam) > Traceback (most recent call last): > File "", line 1, in ? > printtwice(spam) > NameError: name 'spam' is not defined > > Do I have to define the argument before I use it in a function No you could pass a value directly. But yuou have passed an undefined name to python. I suspect you meant to pass the string value 'spam' (Note the quotes...) printtwice('spam') Or you could assign spam, thus: spam = 'spam' printtwice(spam) Either will achieve what you want. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Sun May 19 18:00:08 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 May 2002 18:00:08 +0100 Subject: [Tutor] Design - getFoo and setFoo methods Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5E0@mbtlipnt02.btlabs.bt.co.uk> > I think it's still okay to just use classes to store only data, > (if the overhead is not a problem), but it's not OO design, Absolutely. Let me clarify. There is absolutely nothing to prevent us from wrapping some data up as a class and even accessing the members directly. But its not Object ORIENTED design, its design using Objects. Good OO design tries to build abstract frameworks which are implemented using concrete instances specialising the abstract protocol of the framework to the specific problem at hand. The best book to cover this IMHO is Robert Martin's "OOD using Booch" but be warned it's quite heavy going. > just preferring obj.member syntax to dict[member]. IOW it's now a > matter of syntax, not design. Design is the same as in a > dictionary. Yes, and in Python its all dictionaries under the covers anyhow! Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From ak@silmarill.org Sun May 19 18:05:53 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sun, 19 May 2002 13:05:53 -0400 Subject: [Tutor] python scripts in HTML documents In-Reply-To: <20020519143419.24619.qmail@web21104.mail.yahoo.com> References: <20020519143419.24619.qmail@web21104.mail.yahoo.com> Message-ID: <20020519170553.GA454@ak.silmarill.org> On Sun, May 19, 2002 at 07:34:19AM -0700, john public wrote: > > Can I insert Python code into an HTML document like I can insert a piece of JavaScript code into an HTML document? JavaScript is a scripting language, and Python is a scripting language and also more. Yes? > No. Well, yes, you can, but most browsers won't be able to interpret it. They only understand javascript, html and some understand java. Python is useful on server side, though - a python program runs on server and produces a webpage entirely in HTML (and javascript if you want), then server sends it to the web browser. > > TIA > > John > > > > --------------------------------- > Do You Yahoo!? > LAUNCH - Your Yahoo! Music Experience -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From alan.gauld@bt.com Sun May 19 18:08:22 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 May 2002 18:08:22 +0100 Subject: [Tutor] need help with string Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5E1@mbtlipnt02.btlabs.bt.co.uk> > I have a long string say 80 characters and want to split into > exactly 10 chars except last one. strg = """This is very long string dfjksajdfkjskajfkjsdkajfksdjkfjkdjsakfjkdsjakfjsdkj""" arr_str = [] while len(strg) > 10: elem = strg[:10] # slice out 1st 10 chars strg = string[10:] # assign remainder to strg arr_str.append(elem) # add to array arr_str.append(strg) # now less than 10 chars long print arr_str However the string library method might have some magic for doing that in one go, I haven't checked... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Sun May 19 17:34:30 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 May 2002 17:34:30 +0100 Subject: [Tutor] Backslashes inside of variable Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5DD@mbtlipnt02.btlabs.bt.co.uk> > I am running Python 2.2 on Win2k. I have a program which writes a > filename, with backslashes to a file, along with other stuff. I read > the file in using readlines() and put each line into a variable. > > My problem is I want to use the filename, but I can't use it > because of the backslashes. Provided its only Python using the file then use forward slashes instead of backslashes, they work just as well and avpid the grief... string.replace() will do the swap if needed. Alan G From alan.gauld@bt.com Sun May 19 17:54:27 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 May 2002 17:54:27 +0100 Subject: [Tutor] api vs library -- a definition Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5DF@mbtlipnt02.btlabs.bt.co.uk> > An API refers to the rules and guidelines and protocols etc TRUE > that are set forth by a library. FALSE It could just be a single object. Every class you define creates an API. However it is customery o put commercial APIs into libraries so that they are easier to package and hence sell! > people are always referring to APIs as though they are physical > things, but what they are really referring to is a library of > code, right? 90% of the time yes. But the same API could be defined by lots of different libraries. eg XML parsers. You can get several Java SAX parsers but they all implement the SAX API. > "My company had to purchase an API to handle that problem.") Really this is shorthand for "My company had to purchase an implementation of an API (usually a Library) to handle that problem" Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Sun May 19 18:19:38 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 19 May 2002 18:19:38 +0100 Subject: [Tutor] File access codes in Python Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5E2@mbtlipnt02.btlabs.bt.co.uk> > In Tcl, one can open a file for reading, writing, > and both reading AND writing. > However, in Python, it appears from the book I have, and > from some online information, that one does not have the > option to open a file for BOTH reading and writing. You do, but its unusual and risky. > it complicates the situation. Actually having a file do both is the com,plicated bit, even in Tcl. Its very easy to wind up overwriting a bit of data you didn't mean to and you have to constantly track your location in the file. Very messy and to be avoided if posdsible IMHO. > a program TWICE, just to read the file at one point, > and then write to the same file at some other point Its how most programs work(eg MS Word, Excel etc) Its much safer since you work on a backup copy of the data and can revert in the case of an error. But if you must do it, check out the "r+" option of open() Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From cogs2002@hotmail.com Sun May 19 22:04:40 2002 From: cogs2002@hotmail.com (alex gigh) Date: Sun, 19 May 2002 21:04:40 +0000 Subject: [Tutor] Regular Expressions and RFC 822 Message-ID: Hi; I am trying to write a mail server in Python and I found out that I can use regular expressions and then grouping: "For example, an RFC-822 header line is divided into a header name and a value, separated by a ":". This can be handled by writing a regular expression which matches an entire header line, and has one group which matches the header name, and another group which matches the header's value. " Can someone help me by showing me an example of how I could do this... Many Thanks Alex _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From ak@silmarill.org Sun May 19 22:21:57 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sun, 19 May 2002 17:21:57 -0400 Subject: [Tutor] Regular Expressions and RFC 822 In-Reply-To: References: Message-ID: <20020519212157.GA2875@ak.silmarill.org> On Sun, May 19, 2002 at 09:04:40PM +0000, alex gigh wrote: > Hi; > > I am trying to write a mail server in Python and I found out that I can use > regular expressions and then grouping: > > "For example, an RFC-822 header line is divided into a header name and a > value, separated by a ":". This can be handled by writing a regular > expression which matches an entire header line, and has one group which > matches the header name, and another group which matches the header's > value. " > > Can someone help me by showing me an example of how I could do this... > I don't like regular expressions and I think a lot of people agree. You can do this easily without them: >>> h = "to: somebody@anywhere.com" >>> name, val = [x.strip() for x in h.split(':')] >>> name 'to' >>> val 'somebody@anywhere.com' h.split(':') splits header in two parts, on each side of ':' x.strip() for x in .. strips surrounding whitespace of each value. - Andrei > > Many Thanks > > Alex > > _________________________________________________________________ > Chat with friends online, try MSN Messenger: http://messenger.msn.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From shalehperry@attbi.com Sun May 19 23:15:31 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun, 19 May 2002 15:15:31 -0700 (PDT) Subject: [Tutor] Regular Expressions and RFC 822 In-Reply-To: <20020519212157.GA2875@ak.silmarill.org> Message-ID: >> >> Can someone help me by showing me an example of how I could do this... >> > I don't like regular expressions and I think a lot of people > agree. You can do this easily without them: > there is another reason than "not liking regular expressions". RFC822 allows for continuation lines: SUBJECT: this is my really long long long long long subject line from a galaxy far far far far far away So even if you used a regex to match re.compile(r'(\w+):(.+)') you would still miss the continuation line. So you almost need a preprocessor which concatenates lines if there is a continuation and when the line is finished parse it. Look at the rfc822 module for a better approach and to avoid reinventing the wheel. From stuart@sharedreality.org Sun May 19 22:37:07 2002 From: stuart@sharedreality.org (Stuart Smith) Date: Sun, 19 May 2002 22:37:07 +0100 Subject: [Tutor] Design - getFoo and setFoo methods In-Reply-To: <5A4D6CFA-6A96-11D6-8F0D-00039351FE6A@mac.com> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5D5@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <5.1.0.14.2.20020519220608.00a78ee8@sharedreality.org> My understanding of an object is that it represents some entity and encapsulates the data and code for manipulating that data. For example, considering a car, the class may define a number of different attributes of a car - engine size, fuel efficiency, etc. A method defined in that class could be to return amount of fuel consumed, given an average speed and distance. So basically, if you have something which has attributes and has some sort of processing involved, it's a good candidate for making an object. Deciding what should and shouldn't be an object is sometimes a matter of personal style - it all depends on how abstracted you want your code to be. Some things are pretty obvious that they should be objects, some aren't. If you're unsure, have a think about whether the advantages you'd gain from making something an object, are worth the extra complexity in the code. get and set methods I have learnt to be useful to make code more modular. By using get and set methods for data in objects, you can change how the object represents the data internally without affecting the rest of your application. If you have objects representing people, you might decide one attribute should be the person's age. For this explanation, I'll assume other parts of the program need to read the age - not set it. If you later decide that it would be better to store date of birth rather than age, you have to change any code that reads that value. If, on the other hand, you use a get method, all you need to do is change the get method to work out the age from the date of birth. Many projects change the data structures they use to represent things and if it's a large piece of software it can be awkward having to find every occurrence of a directly accessed variable to change the code. If the class that's changed is re-used by several projects (which is one of the goals of OO programming), then it becomes even worse. My two cents. -- Stuart Smith From erikprice@mac.com Mon May 20 02:56:26 2002 From: erikprice@mac.com (Erik Price) Date: Sun, 19 May 2002 21:56:26 -0400 Subject: [Tutor] Regular Expressions and RFC 822 In-Reply-To: Message-ID: On Sunday, May 19, 2002, at 06:15 PM, Sean 'Shaleh' Perry wrote: >> I don't like regular expressions and I think a lot of people >> agree. You can do this easily without them: >> > > there is another reason than "not liking regular expressions". > > RFC822 allows for continuation lines: > > SUBJECT: this is my really long long long long long subject line from a > galaxy > far far far far far away > > So even if you used a regex to match re.compile(r'(\w+):(.+)') you > would still > miss the continuation line. So you almost need a preprocessor which > concatenates lines if there is a continuation and when the line is > finished > parse it. Look at the rfc822 module for a better approach and to avoid > reinventing the wheel. For the record, I really like regular expressions, though I suppose that some people don't. Perl-compatible regular expression engines can handle the above situation (and many others) but I imagine it uses some sort of preprocessor. Python's regex implementation is a little different than I'm used to, but I still like 'em (especially in my text editor where I use them all the time to modify my code). Erik From erikprice@mac.com Mon May 20 03:09:23 2002 From: erikprice@mac.com (Erik Price) Date: Sun, 19 May 2002 22:09:23 -0400 Subject: [Tutor] python scripts in HTML documents In-Reply-To: <20020519143419.24619.qmail@web21104.mail.yahoo.com> Message-ID: <9AEC41CC-6B96-11D6-899E-00039351FE6A@mac.com> On Sunday, May 19, 2002, at 10:34 AM, john public wrote: > Can I insert Python code into an HTML document like I can insert a > piece of JavaScript code into an HTML document? JavaScript is a > scripting language, and Python is a scripting language and also more. > Yes? Scripting languages are also called interpreted languages. This is because you don't compile the code as a separate step, you just submit the code to an interpreter and the interpreter executes the appropriate actions based on the code. Python works this way, as does JavaScript. The difference between Python and JavaScript is that there is a JavaScript interpreter in most web browsers, but no Python interpreter that I have ever heard of. JavaScript has somehow become something of a standard client-side scripting language for web pages, but Python (and PHP and Perl) is for the most part limited to performing server-side scripting. For instance, you could create a Python script that generates a web page when the following HTTP request is made: http://domain.com/page.py?article=11232 What this request would do is send a variable "article" whose value is "11232" to a script called "page.py" at URL "domain.com". What "page.py" does with this variable could be anything, but possibly it could search a database for an article (using 11232 as the key of the article in the database), read the article, insert the contents of the article into a dynamically-generated string of HTML, and then send that HTML code (including the article) to your browser so that it looks like you have received a web page -- even though there may be no "traditional" web page whatsoever on that server (only scripts like this that imitate web pages by dynamically generating HTML from database content). To get back to your question: if someone ever created a browser with a Python interpreter built in, then yes you could do the kinds of things that you do with JavaScript but in Python instead. But I doubt that this will happen -- one of the nice things about JavaScript, from a security point of view, is that it is very limited in what it can and cannot do on the user's computer. For instance, the JavaScript implementation in most modern browsers cannot read or write any files on a user's hard disk without some kind of permission on the part of the user. This makes JavaScript a very safe scripting language from the perspective that it would be hard for a hacker or other malificant to do damage to someone using it. And of course, you can always turn your browser's JavaScript interpreter off, which means that none of the JavaScript code will work. Erik From idiot1@netzero.net Mon May 20 05:41:24 2002 From: idiot1@netzero.net (kirk Bailey) Date: Mon, 20 May 2002 00:41:24 -0400 Subject: [Tutor] Update Message-ID: <3CE87E74.EDB6225F@netzero.net> On the site, scroll down the home page to RESOURCES. There is a link to the new page 'quickstart' the html version of 'quickstart.readme' which will appear with version 1.3.0 which comes out the hanger door in a few days. Anyone who wants to see how easy it is to use TinyList, read this. -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking---------------------+ +--------+ From ibis2001@telocity.com Mon May 20 07:34:13 2002 From: ibis2001@telocity.com (Geoffrey Bays) Date: Mon, 20 May 2002 02:34:13 -0400 Subject: [Tutor] OO Python: How to change attributes of just one object in a list Message-ID: <5.1.0.14.2.20020520023357.00a140d0@mail.telocity.com> I am trying to write an OO program in Python to keep track of students in classes of mine. Unfortunately, the changeGrade() method in class Course changes all of the students' grades on the same test to the same grade. I have determined that the for and if clauses work correctly, and have tried defining __eq__() and __del__ in the Student class, writing a changeGrade method in class Student, etc, but none of this does any good. I just want to push student objects onto the studentList and change their grades individually. Any help would be much appreciated. class Student: def __init__(self, name): self.name = name self.record = {} def display(self): print self.name, '\n' for item in self.record.keys(): print item, '\t', self.record[item], print '\n' class Course: def __init__(self,name): self.name = name self.tests = {} self.design() self.studentList = [] def design(self): s = raw_input('Enter graded items for the course separated by commas:\ test = s.split(",") for X in test: self.tests[X] = -1 def display(self): print c.name," " for test in c.tests.keys(): print test,": ",c.tests[test], print '\n' def addStudent(self,name): s = Student(name) s.record = self.tests self.studentList.append(s) def displayCourse(self): for i in range(len(self.studentList)): self.studentList[i].display() def changeGrade(self,studName,test,score): boolean = 0 for i in range(len(self.studentList)): if(self.studentList[i].name == studName ): self.studentList[i].record[test] = score //This is the line that changes all the students grades, not just the one boolean = 1 if (boolean == 0): print "No student of that name found." From ak@silmarill.org Mon May 20 07:54:13 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 20 May 2002 02:54:13 -0400 Subject: [Tutor] OO Python: How to change attributes of just one object in a list In-Reply-To: <5.1.0.14.2.20020520023357.00a140d0@mail.telocity.com> References: <5.1.0.14.2.20020520023357.00a140d0@mail.telocity.com> Message-ID: <20020520065413.GA1442@ak.silmarill.org> On Mon, May 20, 2002 at 02:34:13AM -0400, Geoffrey Bays wrote: > I am trying to write an OO program in Python to keep track of students in > classes of mine. Unfortunately, the changeGrade() method in class Course > changes all of the students' grades on the same test to the same grade. > I have determined that the for and if clauses work correctly, and have > tried defining __eq__() and __del__ in the Student class, writing a > changeGrade method in class Student, etc, but none of this does any good. I > just want to push student objects onto the studentList and change their > grades individually. > Any help would be much appreciated. > > class Student: > def __init__(self, name): > self.name = name > self.record = {} > > def display(self): > print self.name, '\n' > for item in self.record.keys(): print item, '\t', self.record[item], > print '\n' > > class Course: > def __init__(self,name): > self.name = name > self.tests = {} > self.design() > self.studentList = [] > > def design(self): > s = raw_input('Enter graded items for the course separated by commas:\ > test = s.split(",") > for X in test: > self.tests[X] = -1 > > def display(self): > print c.name," " > for test in c.tests.keys(): print test,": ",c.tests[test], > print '\n' > > def addStudent(self,name): > s = Student(name) > s.record = self.tests > self.studentList.append(s) > > def displayCourse(self): > for i in range(len(self.studentList)): > self.studentList[i].display() > > def changeGrade(self,studName,test,score): > boolean = 0 > for i in range(len(self.studentList)): > if(self.studentList[i].name == studName ): > self.studentList[i].record[test] = score //This is the line that > changes all the students grades, not just the one > boolean = 1 > if (boolean == 0): > print "No student of that name found." > > > > This does not show up correctly formatted here.. could you please repost? Also add some test code. Wouldn't it be better though to store students in a dictionarary with names as keys, instead of a list? Then you can changeGrade as: students[name].record[test] = score Actually, it *should* be in Student class: self.record[test] = score > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From paulsid@shaw.ca Mon May 20 08:22:15 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Mon, 20 May 2002 01:22:15 -0600 Subject: [Tutor] OO Python: How to change attributes of just one object in alist References: <5.1.0.14.2.20020520023357.00a140d0@mail.telocity.com> Message-ID: <3CE8A427.B8CD8757@shaw.ca> Geoffrey Bays wrote: > I am trying to write an OO program in Python to keep track of students in > classes of mine. Unfortunately, the changeGrade() method in class Course > changes all of the students' grades on the same test to the same grade. > I have determined that the for and if clauses work correctly, and have > tried defining __eq__() and __del__ in the Student class, writing a > changeGrade method in class Student, etc, but none of this does any good. I > just want to push student objects onto the studentList and change their > grades individually. > Any help would be much appreciated. [snip] > def addStudent(self,name): > s = Student(name) > s.record = self.tests > self.studentList.append(s) The middle line above is the problem. It makes each student's record refer to the course's tests dictionary. Since all of the students' records refer to the same object, a change to one student is reflected in all of the others. Making a copy of self.tests will solve your problem. I don't know the standard idiom to copy a dictionary so I would probably just do it manually. On another note, your design looks shaky and will probably become increasingly difficult to manage as the program grows. I suggest rethinking your approach. I don't know too much about Design Patterns but I highly suspect there's one that will fit your situation quite well; try checking some DP sites. Failing that you can always ask us for help. :-) I haven't thought about it too much but FWIW I would probably give each student an ID number and store them all in a dictionary with the ID as the key. Then each course needs only to store a list of ID numbers of students enrolled in that course. I'd also use IDs for courses. For things like grades I might then use a nested dictionary stored inside each student, and access it like this: student.grades[courseid][test]. This might sound complicated but it's not really and I think it'll be quite a bit easier to manage. I can elaborate if you'd like. BTW in the future for your own sake and ours please try to paste your code directly into your message, without editing. The indentation got all messed up and that took a while to sort through. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From alex@gabuzomeu.net Mon May 20 09:22:18 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 20 May 2002 10:22:18 +0200 Subject: [Tutor] python scripts in HTML documents In-Reply-To: <20020520044202.26159.66258.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020520101253.00b76990@pop3.norton.antivirus> At 00:42 20/05/2002 -0400, you wrote: >Subject: Re: [Tutor] python scripts in HTML documents >To: john public >From: Erik Price >To get back to your question: if someone ever created a browser with a >Python interpreter built in, then yes you could do the kinds of things >that you do with JavaScript but in Python instead. But I doubt that >this will happen IIRC, a browser was implemented in Python. It's called Grail. "Grail is an extensible Internet browser written entirely in the interpreted object-oriented programming language Python. It runs on Unix, and, to some extent, on Windows and Macintosh. Grail is easily extended to support new protocols or file formats. Grail is distributed in source form, free of charge, and without warranties. It requires recent versions of Python and Tcl/Tk to run." http://grail.sourceforge.net/ It supports applets: "Grail lets you download Python programs that execute inside Grail on your local machine. These little applications ("applets") can do things like display animations, interact with the user in new ways, even create additional menus that pop up dialogs if you like. If you are using Grail now, visit our applet demo collection. Grail applets run in a restricted execution environment, so that broken or malicious applets ("Trojan Horses") can't erase your files or crash your computer." http://grail.sourceforge.net/ However, it is described as experimental and looks unmaintained. Cheers. Alexandre From shalehperry@attbi.com Mon May 20 10:04:51 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon, 20 May 2002 02:04:51 -0700 (PDT) Subject: [Tutor] Regular Expressions and RFC 822 In-Reply-To: Message-ID: >> >> So even if you used a regex to match re.compile(r'(\w+):(.+)') you >> would still >> miss the continuation line. So you almost need a preprocessor which >> concatenates lines if there is a continuation and when the line is >> finished >> parse it. Look at the rfc822 module for a better approach and to avoid >> reinventing the wheel. > > For the record, I really like regular expressions, though I suppose that > some people don't. Perl-compatible regular expression engines can > handle the above situation (and many others) but I imagine it uses some > sort of preprocessor. Python's regex implementation is a little > different than I'm used to, but I still like 'em (especially in my text > editor where I use them all the time to modify my code). > while (<>) { if (m/(\w+):(.+)/) { $type = $1; $data = $2; } } that code will not handle continuation lines any better than the above python solution. Which is the style of code we are discussing. A common perl idiom is to slurp a lot of text into a buffer and walk the buffer with a regex. That solves the continuation problem for you if you modify your regex to deal with it. From erikprice@mac.com Mon May 20 12:19:52 2002 From: erikprice@mac.com (Erik Price) Date: Mon, 20 May 2002 07:19:52 -0400 Subject: [Tutor] python scripts in HTML documents In-Reply-To: <4.3.2.7.2.20020520101253.00b76990@pop3.norton.antivirus> Message-ID: <812E183D-6BE3-11D6-A3D8-00039351FE6A@mac.com> On Monday, May 20, 2002, at 04:22 AM, Alexandre Ratti wrote: > IIRC, a browser was implemented in Python. It's called Grail. Wow, I never knew about that. Pretty neat -- too bad it's no longer maintained. Erik From stuart@sharedreality.org Mon May 20 12:39:27 2002 From: stuart@sharedreality.org (Stuart Smith) Date: Mon, 20 May 2002 12:39:27 +0100 Subject: [Tutor] python scripts in HTML documents Message-ID: <5.1.0.14.2.20020520123912.00abfc08@sharedreality.org> >To get back to your question: if someone ever created a browser with a >Python interpreter built in, then yes you could do the kinds of things >that you do with JavaScript but in Python instead. But I doubt that this >will happen -- one of the nice things about JavaScript, from a security >point of view, is that it is very limited in what it can and cannot do on >the user's computer. For instance, the JavaScript implementation in most >modern browsers cannot read or write any files on a user's hard disk >without some kind of permission on the part of the user. This makes >JavaScript a very safe scripting language from the perspective that it >would be hard for a hacker or other malificant to do damage to someone >using it. And of course, you can always turn your browser's JavaScript >interpreter off, which means that none of the JavaScript code will work. I've never tried this myself, but IIRC Internet Explorer can use any ActiveX scripting engine installed on the system. If you install ActiveState's ActivePython, you'll have a Python engine. All you need to do is register it with Windows (it's disabled by default) - see the docs. -- Stuart Smith From cogs2002@hotmail.com Mon May 20 13:47:11 2002 From: cogs2002@hotmail.com (alex gigh) Date: Mon, 20 May 2002 12:47:11 +0000 Subject: [Tutor] The use of MailDir for a mail server Message-ID: Hi; I am still trying to write a mail server in Python... I decided that instead of going for the simple option of creating a file for each user and append each new message to this file, I will use "MailDir"... the problem is... I searched the web to find an example on how I could use this (my program is going to be a simple mail server with pre-defined 2 or 3 users.... ) but couldn't find anything useful. Can someone give me an example of : 1) how I can create these maildirs 2) if i need to put a new message in there... how do I copy a new file in there 3) and finally, when delivering messages, how do I get the text from the possibly several different files Also... where exactly can I find the source code for the python libraries (namely smtp and rfc822) because I'm not allowed to use these... Many thanks for your time Alex _________________________________________________________________ Send and receive Hotmail on your mobile device: http://mobile.msn.com From alex@gabuzomeu.net Mon May 20 14:56:47 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 20 May 2002 15:56:47 +0200 Subject: [Tutor] Design - getFoo and setFoo methods In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5D5@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <4.3.2.7.2.20020520102408.00b88c70@pop3.norton.antivirus> At 17:41 16/05/2002 +0100, alan.gauld@bt.com wrote: > > When do you use getFoo() and setFoo() methods in your > > classes? [Direct access of class attributes:] >Thats a common Python idiom but if you are accessing too >many attributes directly it suggests the class is missing >some methods. Theres an OOP expression for this called the >Law of deMeter if you want more research material - try the >Cetus Links page. OK, I found these definitions: "The Law of Demeter was originally formulated as a style rule for designing object-oriented systems. "Only talk to your immediate friends" is the motto." "A more general formulation of the Law of Demeter is: Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Or: Each unit should only talk to its friends; Don't talk to strangers." http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/general-formulation.html Or: "As a guideline, it's simply "where possible, avoid middlemen"." http://c2.com/cgi/wiki?LawOfDemeter => So there is a kind of tension between two goals: - Allow direct access to attributes to avoid unnecessary setFoo/getFoo methods ; - But avoid creating tight coupling of distant objects through direct access of attributes (toto = foo.bar.baz.crunch). Cheers. Alexandre From max_ig@yahoo.com Mon May 20 14:55:47 2002 From: max_ig@yahoo.com (Maximiliano Ichazo) Date: Mon, 20 May 2002 06:55:47 -0700 (PDT) Subject: [Tutor] sorting tuples Message-ID: <20020520135547.97864.qmail@web11302.mail.yahoo.com> I have the following problem with tuples: I have a tuple with tuples in it (these sub-tuples have three items each). I want to sort the items of the main tuple based on the first item of the sub-tuples. However I don't know how can I do this. Thanks in advance. Max __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com From alex@gabuzomeu.net Mon May 20 15:06:54 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 20 May 2002 16:06:54 +0200 Subject: [Tutor] Design - Visitor pattern Message-ID: <4.3.2.7.2.20020520155716.00b81ba0@pop3.norton.antivirus> Hello, while reading up on Demeter law, I came across the Visitor pattern. "Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates." Source: http://c2.com/cgi/wiki?VisitorPattern I tried to reimplement it in Python based on a Java example. => Is this implementation correct? => In what kind of situation whould you use it in Python? Cheers. Alexandre ## class Element: def accept(self, visitor): visitor.visit(self) class Employee(Element): def __init__(self, name, salary, sickDays, vacDays): self.name = name self.salary = salary self.sickDays = sickDays self.vacDays = vacDays class Visitor: def visit(self, theClass): raise NotImplementedError def getResult(self): raise NotImplementedError class VacationVisitor(Visitor): def __init__(self): self.totalDays = 0 def visit(self, employee): self.totalDays += employee.vacDays def getResult(self): return self.totalDays if __name__ == "__main__": A = Employee("A", 100, 2, 5) B = Employee("B", 110, 3, 6) C = Employee("C", 120, 4, 7) vac = VacationVisitor() for employee in A, B, C: employee.accept(vac) print vac.getResult() ## Source: http://www.ciol.com/content/technology/sw_desg_patt/101110501.asp From python@rcn.com Mon May 20 15:35:17 2002 From: python@rcn.com (Raymond Hettinger) Date: Mon, 20 May 2002 10:35:17 -0400 Subject: [Tutor] sorting tuples References: <20020520135547.97864.qmail@web11302.mail.yahoo.com> Message-ID: <002d01c2000b$907ac380$cd61accf@othello> Convert the outer tuple to a list so that it can be sorted: >>> a = ((4,1,8), (9,2,5),(3,6,9)) >>> b = list(a) >>> b.sort() >>> a = tuple(b) >>> print a ((3, 6, 9), (4, 1, 8), (9, 2, 5)) Raymond Hettinger ----- Original Message ----- From: "Maximiliano Ichazo" To: Sent: Monday, May 20, 2002 9:55 AM Subject: [Tutor] sorting tuples > I have the following problem with tuples: > > I have a tuple with tuples in it (these sub-tuples have three items > each). I want to sort the items of the main tuple based on the first > item of the sub-tuples. However I don't know how can I do this. > > Thanks in advance. > > Max > > > > __________________________________________________ > Do You Yahoo!? > LAUNCH - Your Yahoo! Music Experience > http://launch.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From michael.williams@st-annes.oxford.ac.uk Mon May 20 16:21:50 2002 From: michael.williams@st-annes.oxford.ac.uk (Michael Williams) Date: Mon, 20 May 2002 16:21:50 +0100 Subject: [Tutor] Doing the Right Thing when converting strings to numbers Message-ID: <20020520152149.GA3889@st-annes.oxford.ac.uk> Hi, I'd like to convert a string to either a float or an integer ``intelligently", i.e.: >>> mystring = '5' >>> mynumber = clever_coerce(mystring) >>> print mynumber, type(mynumber) 5 >>> mystring = '4.9' >>> mynumber = clever_coerce(mystring) >>> print mynumber, type(mynumber) 4.9 The string should ideally also be coerced into a float in the event of it being, e.g. '5.0'. Does such a function exist in the standard library or, if not, perhaps there should be. Could someone suggest how I might go about writing one myself. -- Michael From rob@uselesspython.com Mon May 20 16:43:05 2002 From: rob@uselesspython.com (Rob Andrews) Date: Mon, 20 May 2002 10:43:05 -0500 Subject: [Tutor] jython showMessageDialog question Message-ID: <3CE91989.6040709@uselesspython.com> I just posted this question to the jython-users@lists.sourceforge.net list, and I figured I'd drop it here as well. The problem I describe in it is an example of trying to use Java swing components from the Jython prompt. In some cases, I can use swing with jython to do GUI stuff with great satisfaction, but it's a little mysterious on other occasions. Please forgive the cheesiness of the following example. I was aiming for brevity more than impressiveness. I encounter errors along the following lines when I attempt to use showMessageDialog in Jython. I have tried to attack the problem from a number of different angles, and have about concluded that I must be missing some simple, fundamental truth about how this works in Jython. >>> import javax.swing as sshwing >>> moreInput = sshwing.JOptionPane.showInputDialog("More input:") >>> sshwing.JOptionPane.showMessageDialog( null, "Your input is inadequate.") Traceback (innermost last): File "", line 1, in ? NameError: null I will appreciate any illumination. Rob Andrews From rob@uselesspython.com Mon May 20 16:52:19 2002 From: rob@uselesspython.com (Rob Andrews) Date: Mon, 20 May 2002 10:52:19 -0500 Subject: [Tutor] Re: [Jython-users] question about showMessageDialog usage References: <2448E81387350E478E9278BB707FA9381CFE38@eserver.microbrightfield.com> Message-ID: <3CE91BB3.2050505@uselesspython.com> (Cross-posting my reply to the Python Tutor list. -Rob) That hit the spot. Thanks much. Rob James Carroll wrote: > > Hey! one that I can help with! > > >>input:") >>> sshwing.JOptionPane.showMessageDialog( null, >>"Your input is >>inadequate.") >>Traceback (innermost last): >> File "", line 1, in ? >>NameError: null >> > > In Jython, use None insteada of null. > > btw sshwing: excellent! > > so it would read > > >>>>sshwing.JOptionPane.showMessageDialog(None, "inadequate.") >>>> > > -Jim > > >>-----Original Message----- >>From: Rob Andrews [mailto:rob@uselesspython.com] >>Sent: Monday, May 20, 2002 11:31 AM >>To: jython-users@lists.sourceforge.net >>Subject: [Jython-users] question about showMessageDialog usage >> >> >>Please forgive the cheesiness of the following example. I was >>aiming for >>brevity more than impressiveness. >> >>I encounter errors along the following lines when I attempt to use >>showMessageDialog in Jython. I have tried to attack the >>problem from a >>number of different angles, and have about concluded that I must be >>missing some simple, fundamental truth about how this works in Jython. >> >> >>> import javax.swing as sshwing >> >>> moreInput = sshwing.JOptionPane.showInputDialog("More >> >> >>I will appreciate any illumination. >> >>Rob Andrews >> >> >> >>_______________________________________________________________ >>Hundreds of nodes, one monster rendering program. >>Now that's a super model! Visit http://clustering.foundries.sf.net/ >> >>_______________________________________________ >>Jython-users mailing list >>Jython-users@lists.sourceforge.net >>https://lists.sourceforge.net/lists/listinfo/jython-users >> >> > > _______________________________________________________________ > Hundreds of nodes, one monster rendering program. > Now that's a super model! Visit http://clustering.foundries.sf.net/ > > _______________________________________________ > Jython-users mailing list > Jython-users@lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/jython-users > > From michael.williams@st-annes.oxford.ac.uk Mon May 20 17:39:10 2002 From: michael.williams@st-annes.oxford.ac.uk (Michael Williams) Date: Mon, 20 May 2002 17:39:10 +0100 Subject: [Tutor] Doing the Right Thing when converting strings to numbers Message-ID: <20020520163910.GD1923@st-annes.oxford.ac.uk> On Mon, May 20, 2002 at 04:40:15PM +0100, ibraheem umaru-mohammed wrote: > [Michael Williams wrote...] > -| Hi, > -| > -| I'd like to convert a string to either a float or an integer > -| ``intelligently", i.e.: > -| > -| >>> mystring = '5' > -| >>> mynumber = clever_coerce(mystring) > -| >>> print mynumber, type(mynumber) > -| 5 > -| >>> mystring = '4.9' > -| >>> mynumber = clever_coerce(mystring) > -| >>> print mynumber, type(mynumber) > -| 4.9 > > >>> s1='5' > >>> n1=int(s1) > >>> print n1,type(n1) > >>> 5 > >>> s2='4.9' > >>> n2=float(s2) > >>> print n2,type(n2) > >>> 4.9 > >>> I think you've misunderstood as I wasn't clear enough. I want to use the *same* function to do the conversion to both float and int. I am writing a program to read a series of numbers in from file. They are of unknown type (i.e. whether they're float or int) so it would be simplest to have/write a function that converted to float if the number ended contained a period, or in if it did not. It is no trouble for me to write such a function myself, but I was just asking whether it had already been done. -- Michael From alex@gabuzomeu.net Mon May 20 17:42:39 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 20 May 2002 18:42:39 +0200 Subject: [Tutor] sorting tuples In-Reply-To: <20020520154602.3860.9413.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020520183510.00b69d40@pop3.norton.antivirus> Hello Maximiliano, At 11:46 20/05/2002 -0400, you wrote: >Date: Mon, 20 May 2002 06:55:47 -0700 (PDT) >From: Maximiliano Ichazo >Subject: [Tutor] sorting tuples >I have a tuple with tuples in it (these sub-tuples have three items >each). I want to sort the items of the main tuple based on the first >item of the sub-tuples. However I don't know how can I do this. You could convert the tuple to a list, and then sort the list. Try this: toto = (('b', 'c', 'a'), ('d', 'e', 'e'), ('a','b','c')) titi = list(toto) titi.sort() print titi >>> [('a', 'b', 'c'), ('b', 'c', 'a'), ('d', 'e', 'e')] To convert the list back to a tuple, use "tuple(theList)". Cheers. Alexandre From alex@gabuzomeu.net Mon May 20 18:02:41 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 20 May 2002 19:02:41 +0200 Subject: [Tutor] The use of MailDir for a mail server In-Reply-To: <20020520154602.3860.9413.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020520183429.00c7c530@pop3.norton.antivirus> Hello Alex, At 11:46 20/05/2002 -0400, you wrote: >From: "alex gigh" >Date: Mon, 20 May 2002 12:47:11 +0000 >Subject: [Tutor] The use of MailDir for a mail server >I am still trying to write a mail server in Python... I decided that instead >of going for the simple option of creating a file for each user and append >each new message to this file, I will use "MailDir"... the problem is... I >searched the web to find an example on how I could use this Here are information about the maildir format. I don't know whether it is useful: http://www.qmail.org/qmail-manual-html/man5/maildir.html >Also... where exactly can I find the source code for the python libraries >(namely smtp and rfc822) because I'm not allowed to use these... AFAIK, the source code is included in every Python distribution. On Windows, look for a "lib" directory in the install directory. Or, in the Python interpreter, try this: import sys print sys.path The path to the "lib" directories should be listed in the output. Cheers. Alexandre From rob@uselesspython.com Mon May 20 18:40:30 2002 From: rob@uselesspython.com (Rob Andrews) Date: Mon, 20 May 2002 12:40:30 -0500 Subject: [Tutor] Jython swing example Message-ID: <3CE9350E.2010706@uselesspython.com> http://uselesspython.com/Jython_Swing_Basics.html At the URL above, I have posted first draft notes of how to grab user input, perform simple math on it, and display the results from a jython prompt. I'm certainly open to constructive criticism, especially since I haven't proofed it yet and might have left in a few stray blunders. The bulk of it was a copy/paste from the Windows 2000 command prompt. The example uses Java swing components for the GUI part, and features a few cropped screenshots to show what it looks like. For anyone who has been curious about Jython but hasn't fiddled with it yet, this might stimulate the curiosity a bit. Rob From shalehperry@attbi.com Mon May 20 18:41:12 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon, 20 May 2002 10:41:12 -0700 (PDT) Subject: [Tutor] Design - Visitor pattern In-Reply-To: <4.3.2.7.2.20020520155716.00b81ba0@pop3.norton.antivirus> Message-ID: > > I tried to reimplement it in Python based on a Java example. > > => Is this implementation correct? > => In what kind of situation whould you use it in Python? > usually Visitor implies a 'for i in foo: visit()'. This could a list of objects, files in a directory, network sockets, etc. for i in foo: print i ..... for i in foo: increment something .... for i in foo: # files in dir move to new bar/ in python this may end up being a function call along with map or a loop. From dman@dman.ddts.net Mon May 20 21:32:24 2002 From: dman@dman.ddts.net (dman) Date: Mon, 20 May 2002 15:32:24 -0500 Subject: [Tutor] Doing the Right Thing when converting strings to numbers In-Reply-To: <20020520163910.GD1923@st-annes.oxford.ac.uk> References: <20020520163910.GD1923@st-annes.oxford.ac.uk> Message-ID: <20020520203224.GA18245@dman.ddts.net> --EVF5PPMfhYS0aIcm Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 20, 2002 at 05:39:10PM +0100, Michael Williams wrote: | On Mon, May 20, 2002 at 04:40:15PM +0100, ibraheem umaru-mohammed wrote: | > [Michael Williams wrote...] | > -| Hi, | > -|=20 | > -| I'd like to convert a string to either a float or an integer | > -| ``intelligently", i.e.: =2E.. | I think you've misunderstood as I wasn't clear enough. I want to use the | *same* function to do the conversion to both float and int. =2E.. def clever_coerce( s ) : if s.find( '.' ) !=3D -1 : return float( s ) else : return int( s ) =20 --=20 But As for me and my household, we will serve the Lord. Joshua 24:15 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --EVF5PPMfhYS0aIcm Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzpXVgACgkQO8l8XBKTpRQLVQCcCB/bJTz5IPl9WpUpUEKnQl+V EZAAoID1a6B6I0g8iKMUR5UIhC2HTv+3 =iFOM -----END PGP SIGNATURE----- --EVF5PPMfhYS0aIcm-- From alex@gabuzomeu.net Mon May 20 17:51:44 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 20 May 2002 18:51:44 +0200 Subject: [Tutor] Doing the Right Thing when converting strings to numbers In-Reply-To: <20020520154602.3860.9413.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020520183657.00c60cc0@pop3.norton.antivirus> Hi Michael, At 11:46 20/05/2002 -0400, you wrote: >Date: Mon, 20 May 2002 16:21:50 +0100 >From: Michael Williams >Subject: [Tutor] Doing the Right Thing when converting strings to numbers >I'd like to convert a string to either a float or an integer >``intelligently", i.e.: >The string should ideally also be coerced into a float in the event of >it being, e.g. '5.0'. Does such a function exist in the standard library I'm not aware of such a function. >Could someone suggest how I might go about writing one myself. Maybe you could test whether the initial string contain a decimal separator (a dot in your example). >>> def convert(value): ... if "." in value: ... return float(value) ... else: ... return int(value) If your input strings are fairly standard (eg. they cannot contain sentences and you always use a dot as decimal separator), it should work. Cheers. Alexandre From printers@sendme.cz Mon May 20 21:40:14 2002 From: printers@sendme.cz (A) Date: Mon, 20 May 2002 22:40:14 +0200 Subject: [Tutor] Smtplib and exceptions- why it does NOT work Message-ID: <3CE97B4E.28930.54272A@localhost> Hi, How can I get response from Smtplib? For example I have class SMTPM: def sendMail(self): import smtplib s11 = smtplib.SMTP('smtp.sendme.cz') Response=s11.sendmail('a@NonExistingDomain1.com',"printers@sendme.cz","TEST") print Response A=SMTPM() A.sendMail() When I start the class I will get the following exception: SMTPSenderRefused: (501, '5.1.8 ... Domain of sender address a@NonExistingDomain1.com does not exist', 'a@NonExistingDomain1.com') and execution stops. I,however, would like to print only (501, '5.1.8 ... Domain of sender address a@NonExistingDomain1.com does not exist', 'a@NonExistingDomain1.com') without stopping execution. So I handled that exception and changed the class like this class SMTPM: def sendMail(self): import smtplib self.s11 = smtplib.SMTP('smtp.sendme.cz') try: Response=self.s11.sendmail('a@NonExistingDomain.com',"printers@sendme.cz","TEST") except(smtplib.SMTPRecipientsRefused,smtplib.SMTPSenderRefused ): print "Response ",Response A=SMTPM() A.sendMail() But it does not work. Can anybody please explain to me why? thanks Ladislav From pythontutor@venix.com Mon May 20 23:32:22 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 20 May 2002 18:32:22 -0400 Subject: [Tutor] Re: Abt python (using the sleep function in the time module) References: <3ce8d362.7e57.0@pakistanmail.com> Message-ID: <3CE97976.8020404@venix.com> >>> import time >>> def take5(): ... time.sleep(5) ... >>> def pause(): ... print time.localtime() ... take5() ... print time.localtime() ... >>> pause() (2002, 5, 20, 18, 29, 37, 0, 140, 1) (2002, 5, 20, 18, 29, 42, 0, 140, 1) >>> pause() (2002, 5, 20, 18, 29, 50, 0, 140, 1) (2002, 5, 20, 18, 29, 55, 0, 140, 1) >>> As you can see, when the sleep function is used like this, it pauses five seconds every time. There is probably something wrong with how your are using it. Also, you are better off mailing to the whole list rather than only me. Someone else will usually respond more quickly. wonderer@pakistanmail.com wrote: > Hi I was checking few python scripts which i wrote and found out something which > i could not understand i hope u could help in this regard. > My problem is I load a script and call a function defined in that script . > Now this function has a "time.sleep(5)" statement. > what happens is that first time script is "import"ed and that function called > it goes to sleep for 5 secionds but if i call that function again it outputs > the result without any delay without executing any delay or sleep. > I wonder if it is a problem with my code or something else. > The only solution i m relying on is to reload everything from scratch. > plzz any help > TIA > _______________________________________________________________________ > Get your free @pakistanmail.com email address http://pakistanmail.com > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From virketis@fas.harvard.edu Tue May 21 05:57:05 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Tue, 21 May 2002 00:57:05 -0400 Subject: [Tutor] Python does .NET? Message-ID: <200205210457.g4L4vff06310@smtp2.fas.harvard.edu>
Hi all,
 
I have been musing about this a while, but Rob Andrew's= intro to Jython (good job!) prompted me to put it forth in this= forum. .NET, as far as I understand it, is all about having a= common runtime, which all the different languages can use. But= Python seems to interact with its "colleagues"= already: you can write C/C++ extensions, pretty much co-opt= Java, interact with VB through COM objects, and now there is= even work to turn Parrot from one of the best April 1st jokes= ever into a real tool. (http://www.parrotcode.org/= ) Clearly, Python is a glue language par excellence. But perhaps= there something more here: perhaps the boundaries between all= the languages will be melting away? How does this compare with= the .NET project? Maybe Python is dissolving in a soup of other= languages? ;)
 
Cheers and thanks for your opinions,
 
Pijus
 
--
"Those who can make you believe absurdities
can make you commit atrocities" - Voltaire
From erikprice@mac.com Tue May 21 11:46:58 2002 From: erikprice@mac.com (Erik Price) Date: Tue, 21 May 2002 06:46:58 -0400 Subject: [Tutor] Python does .NET? In-Reply-To: <200205210457.g4L4vff06310@smtp2.fas.harvard.edu> Message-ID: <1305D322-6CA8-11D6-BB7C-00039351FE6A@mac.com> On Tuesday, May 21, 2002, at 12:57 AM, Pijus Virketis wrote: > Clearly, Python is a glue language par excellence. But perhaps there > something more here: perhaps the boundaries between all the languages > will be melting away? How does this compare with the .NET project? > Maybe Python is dissolving in a soup of other languages? ;) I think that would be really cool. And I don't mean to use this forum to promote ideology. But as far as .NET is concerned, Microsoft's track record is not very good for maintaining open standards. It is typical of that company to change their code interface when their competitors create a powerful, quality piece of software and MS is about to release a competing version (something that many skeptics worry could easily happen with .NET). The whole concept of .NET, in fact, is arguably just an attempt to stifle Java development for Winsystems. However, look at what happens with open source software (or in the case of Java, heavily documented and standardized proprietary software) -- the barriers between languages are easier to cross, and the cool things that Pijus mentions become possible. I'm not saying MS automatically bad, OSS automatically good (regardless of how I actually feel), but I am suggesting that open standards and "communication" (if you want to call it that) between coders and code seem to create some of the most robust and powerful software. IMO, juding from my limited experience. Of course I'm biased. Erik From cogs2002@hotmail.com Tue May 21 12:13:06 2002 From: cogs2002@hotmail.com (alex gigh) Date: Tue, 21 May 2002 11:13:06 +0000 Subject: [Tutor] Quick question: Is it more efficient to... Message-ID: Hi; In my mail server, I'm doing some sort of spam detection where I have a kill file which is a list of regular expressions and I have to check that the mail doesn't cotain any of these words... Is it more efficient to (A) check the lines one by one as I receive them or (B) save the whole mail in a file and then check the whole mail with the kill file... I have been told that if I use "pickle" I can do some very efficient searching... Which one would be better and why? Also... which number (i.e. 500) do I send back if: (1) The user is unknown or domain name isn't accepted (2) The mail isn't delivered because contains "unaccepted" word Thanks for your help... Poor CS student trying to finish a mail server before this Thursday!!! _________________________________________________________________ Send and receive Hotmail on your mobile device: http://mobile.msn.com From erikprice@mac.com Tue May 21 12:28:16 2002 From: erikprice@mac.com (Erik Price) Date: Tue, 21 May 2002 07:28:16 -0400 Subject: [Tutor] Quick question: Is it more efficient to... In-Reply-To: Message-ID: On Tuesday, May 21, 2002, at 07:13 AM, alex gigh wrote: > Is it more efficient to (A) check the lines one by one as I receive > them or (B) save the whole mail in a file and then check the whole mail > with the kill file... I have been told that if I use "pickle" I can do > some very efficient searching... Again, I don't know anything about mail servers, but option B sounds like it is more forward-thinking -- what would happen if you suddenly were flooded with more mail than your system's mem could handle? Option B lets you perform this intensive process at your own rate, completely independent of incoming mail. Also it just "feels" more modular this way. Erik From alan.gauld@bt.com Tue May 21 14:25:33 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 21 May 2002 14:25:33 +0100 Subject: [Tutor] python scripts in HTML documents Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5EA@mbtlipnt02.btlabs.bt.co.uk> > The difference between Python and JavaScript is that there is a > JavaScript interpreter in most web browsers, but no Python > interpreter In fact IE (under Windoze at least) does not have an interpreter in it instead it links to MS Active Scripting Engine - the same one that runs Windows Scripts (VBS files etc) from Exploder... Now the Windows Scripting Host(its other name) can be extended and versions exist to enable Perl and ...pause for drum roll.... Python! If you have the winall extensions you have that already, just run the script and WSH can now read Python. This maeans you can now write Web pages with embedded Python just like JavaScript. The snag is anyone else who needs the benefit also needs to add Python to their WSH install... > To get back to your question: if someone ever created a > browser with a Python interpreter built in, then yes you > could do the kinds of things that you do with JavaScript And that time is now. All you have to do is persuade your friends(and anyone else who needs it) to install the Python WSH extensions. The reason you don't need to do this for Jscript or VBScript is that MS ship those 'language packs' with WSH as default. Hammonds Python on Win32 book covers this and includes an example of Browser based python scripting. > this will happen -- one of the nice things about JavaScript, from a > security point of view, is that it is very limited in what it can and > cannot do on the user's computer. As is Python when running in restricted mode... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From python@rcn.com Tue May 21 14:39:12 2002 From: python@rcn.com (Raymond Hettinger) Date: Tue, 21 May 2002 09:39:12 -0400 Subject: [Tutor] Re: [Python-Help] Quick question: Is it more efficient to... References: Message-ID: <003e01c200cc$e5385d80$5ab53bd0@othello> Hello Alex, I like your second approach better. Rather than reading line by line, try a full read() into memory and run the regular expression scanners on that (their C coded internal looping is much faster than looping over lines in Python). If you can read directly, try that; however, if you have a complex object type, Cpickle is the simplest (not necessarily fastest) way of converting the whole object into a single string for scanning. Another idea for you is to combine all of your scans into a single regular expression: r'(sexy)|(free loan)|(out of debt)'. If you use the X or VERBOSE mode, it can be combined without loss of readability. Combining them into one allows the re compiler to create a single, efficient state machine for all of the scans. Be sure to compile you regular expressions. I'm not sure about which return codes you should use. Good luck with your server, Raymond Hettinger ----- Original Message ----- From: "alex gigh" To: ; Sent: Tuesday, May 21, 2002 7:13 AM Subject: [Python-Help] Quick question: Is it more efficient to... > Hi; > > In my mail server, I'm doing some sort of spam detection where I have a kill > file which is a list of regular expressions and I have to check that the > mail doesn't cotain any of these words... > > Is it more efficient to (A) check the lines one by one as I receive them or > (B) save the whole mail in a file and then check the whole mail with the > kill file... I have been told that if I use "pickle" I can do some very > efficient searching... > > Which one would be better and why? > > > Also... which number (i.e. 500) do I send back if: > > (1) The user is unknown or domain name isn't accepted > (2) The mail isn't delivered because contains "unaccepted" word > > > Thanks for your help... > > Poor CS student trying to finish a mail server before this Thursday!!! > > > _________________________________________________________________ > Send and receive Hotmail on your mobile device: http://mobile.msn.com > > > > _______________________________________________ > Python-Help maillist - Python-Help@python.org > http://mail.python.org/mailman/listinfo/python-help > From israel@lith.com Tue May 21 21:59:23 2002 From: israel@lith.com (Israel Evans) Date: Tue, 21 May 2002 13:59:23 -0700 Subject: [Tutor] Dynamic creation of class instances... Message-ID: This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2010A.62A29DD5 Content-Type: text/plain Hello All... I'm attempting to dynamically create an unknown number of class instances and I'm wondering if there is a better way. Right now I start out with a list of names, craft a string that looks like a class instantiation and then exec the sucker. After that I think I just have to "know" which objects I've just created, add them to a list and then for loop over the list to add them to a dict so that I can easily access them. Unfortunately I think when I add the objects to the dict I'm making the key an instance of the class as well as the value. >>> class Test: def __init__(self): pass >>> namelist = ["kaya", "felice", "chalma", "frisia"] >>> for name in namelist: thestring = '%s = Test()'%(name) exec(thestring) >>> kaya <__main__.Test instance at 0x0093E1A8> >>> oblist = [kaya, felice, chalma, frisia] >>> for obj in oblist: obdict[obj] = obj >>> obdict[kaya] <__main__.Test instance at 0x0093E1A8> Any Ideas? ps. exec() scares me. Thanks, ~Israel~ ------_=_NextPart_001_01C2010A.62A29DD5 Content-Type: text/html Content-Transfer-Encoding: quoted-printable

Hello All...

 

       &nbs= p;    I'm attempting to dynamically create an unknown number of class instances = and I'm wondering if there is a better way.  Right now I start out with a list of names, craft a string that = looks like a class instantiation and then exec the sucker.  After that I think I just have = to "know" which objects I've just created, add them to a list and then for loop over the list to add them to a dict so that = I can easily access them.  Unfortunately I think when I add the objects to the dict = I'm making the key an instance of the class as well as the value. =

 

>>> class = Test:

       &nbs= p;    def __init__(self):

       &nbs= p;           &nbs= p;    pass

 

>>> namelist =3D ["kaya", "felice", "chalma", "frisia"]

 

>>> for name in = namelist:

       &nbs= p;    thestring =3D '%s =3D = Test()'%(name)

       &nbs= p;    exec(thestring)

 

>>> kaya

<__main__.Test = instance at 0x0093E1A8>

 

>>> oblist =3D [kaya, felice, chalma, frisia]

 

>>> for obj in oblist:

       &nbs= p;    obdict[obj] =3D obj

       &nbs= p;   

>>> obdict[kaya]

<__main__.Test = instance at 0x0093E1A8>

 

Any = Ideas?

ps. exec() scares me.

 

Thanks,

 

 

 

~Israel<= font size=3D2 face=3D"Courier New">~

 

------_=_NextPart_001_01C2010A.62A29DD5-- From ak@silmarill.org Tue May 21 23:29:45 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 21 May 2002 18:29:45 -0400 Subject: [Tutor] Dynamic creation of class instances... In-Reply-To: References: Message-ID: <20020521222945.GA1339@ak.silmarill.org> On Tue, May 21, 2002 at 01:59:23PM -0700, Israel Evans wrote: > Hello All... > > I'm attempting to dynamically create an unknown number of class > instances and I'm wondering if there is a better way. Right now I start out > with a list of names, craft a string that looks like a class instantiation > and then exec the sucker. After that I think I just have to "know" which > objects I've just created, add them to a list and then for loop over the > list to add them to a dict so that I can easily access them. Unfortunately > I think when I add the objects to the dict I'm making the key an instance of > the class as well as the value. > > >>> class Test: > def __init__(self): > pass > > >>> namelist = ["kaya", "felice", "chalma", "frisia"] > > >>> for name in namelist: > thestring = '%s = Test()'%(name) > exec(thestring) > > >>> kaya > <__main__.Test instance at 0x0093E1A8> > > >>> oblist = [kaya, felice, chalma, frisia] > > >>> for obj in oblist: > obdict[obj] = obj > > >>> obdict[kaya] > <__main__.Test instance at 0x0093E1A8> > > Any Ideas? > ps. exec() scares me. > You don't need that here.. I think. >>> mydict = {} >>> for item in lst: ... mydict[item] = T() ... >>> mydict['kaya'] <__main__.T instance at 0x80df2d4> It's not clear to me how you plan to use these objects. - Andrei > > Thanks, > > > > ~Israel~ > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From csmith@blakeschool.org Tue May 21 22:29:14 2002 From: csmith@blakeschool.org (Christopher Smith) Date: Tue, 21 May 2002 16:29:14 -0500 Subject: [Tutor] http through squid Message-ID: Does anyone have enough experience to answer this question: I am trying to do a URL request from behind a firewall. If I understand it correctly (and I'll use generic symbols here) the proxy server is x.y.z at port 123. The Squid proxy-caching software is running. I can successfully request a local http page, but cannot figure out how to pass my user name and password on to the squid so it will let me through for a remote page. I've tried various permuations of creating openers with the different handlers and have tried to pass a proxy authentication handler the host, realm, user, password like 'x','y.z', 'myname', 'mypassword' and the proxy handler the dictionary {'http' : 'http://x.y.z:123'} without success. Does anyone have a working script that works in a similar squid/proxy configuration? When a browser is being used, I supply the proxy info (x.y.z and port number 123) to the preferences and then whenever I request an offsite page I am asked to authenticate by supplying a username and password. I would really like to know what info/format the browser is using to talk to the squid/proxy so I could replicate this with Python. /c From paulsid@shaw.ca Wed May 22 01:07:55 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Tue, 21 May 2002 18:07:55 -0600 Subject: [Tutor] Dynamic creation of class instances... References: Message-ID: <3CEAE15B.ACB807D8@shaw.ca> > I'm attempting to dynamically create an unknown number of class > instances and I'm wondering if there is a better way. Right now I > start out with a list of names, craft a string that looks like a > class instantiation and then exec the sucker. After that I think > I just have to "know" which objects I've just created, add them to > a list and then for loop over the list to add them to a dict so > that I can easily access them. Unfortunately I think when I add the > objects to the dict I'm making the key an instance of the class as > well as the value. I think the best way to do this is by using a dictionary: > >>> namelist = ["kaya", "felice", "chalma", "frisia"] > >>> for name in namelist: > thestring = '%s = Test()'%(name) > exec(thestring) This becomes: instdict = {} for name in namelist: instdict[name] = Test() > >>> kaya > <__main__.Test instance at 0x0093E1A8> Then you now access with this instead: instdict["kaya"] > >>> oblist = [kaya, felice, chalma, frisia] > >>> for obj in oblist: > obdict[obj] = obj > >>> obdict[kaya] > <__main__.Test instance at 0x0093E1A8> To be honest I'm not sure why you included this part. It looks as though you were trying to do something along the lines of what I've described above? I should point out why this makes no sense to me. If we use numbers instead of object names then the equivalent of what you're doing here is this: obdict = {} obdict[1] = 1 obdict[5] = 5 obdict[21] = 21 obdict[145] = 145 With numbers the oddness of this probably looks more obvious. The dictionary is useless because one of two things happens: 1) You want an object so you need the key to look up an object which you already know because it's the key that you need to look up the object which you already know because it's the key that you need to look up the object which you already know because it's the key that^C In other words, to look up an object you already need to know what it is. So the dictionary is superfluous. 2) You need a list of all instances. So you'd do obdict.values() or obdict.keys(). But both of these are lists and indeed they're equal, so you could have just used a list to begin with (which you did). In short, if you ever have a situation with D[A] = A where D is a dictionary and A is some object, then the dictionary can very likely be eliminated. In fact I can't imagine a situation where it shouldn't be eliminated, but I don't want to say "always" because one never knows. > ps. exec() scares me. As it should. :-) -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From csmith@blakeschool.org Wed May 22 03:07:59 2002 From: csmith@blakeschool.org (Christopher Smith) Date: Tue, 21 May 2002 21:07:59 -0500 Subject: [Tutor] Re: need help with string Message-ID: > I have a long string say 80 characters and want to split into > exactly 10 chars except last one. A list comprehension works nicely here: s='a string to be fragmented in chunks of 10' pieces = [s[i:i+10] for i in range(0,len(s),10)] Slices automatically re-adjust if the indices are out of range so even though i+10 might extend past the end of the list, the maximum value will be used instead. Of course you could append these slices to the list in a loop if you didn't want to do a list comprehension. /c From seiji_funai@yahoo.com Wed May 22 06:58:59 2002 From: seiji_funai@yahoo.com (Seiji Funai) Date: Tue, 21 May 2002 22:58:59 -0700 (PDT) Subject: [Tutor] Persistent values in functions Message-ID: <20020522055859.25757.qmail@web21306.mail.yahoo.com> I'd like to know if Python supports persistent values in functions: a variable type that saves its value when the function returns, and gives the value when the function is called again. I seem to recall that you can do this in C. Please provide syntax and perhaps a simple example. Thanks! __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com From virketis@fas.harvard.edu Wed May 22 07:03:16 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Wed, 22 May 2002 02:03:16 -0400 Subject: [Tutor] example of Python client accessing a DDE server Message-ID: <200205220603.g4M63JE29822@smtp1.fas.harvard.edu>
Dear all,
 
I am trying to access the Matlab engine from Python. I know= that Matlab exposes its engine as a DDE server/client; I also= have the Python win32 DDE module. I think that at least= theoretically this should work. However, I have little idea of= how to actually establish the link and do stuff with it. I think= I will go to the library soon to check out the "Programming= Python on Win32" book. However, in the meanwhile, if anyone= could just send me any sort of little script that connects to a= DDE server, passes some info, etc., that would be extremely= useful. And of course, if anyone knows of a more elegant way to= work with Matlab, that's even better :) I have already tried the= pymat module before turning to DDE, but it appears to work only= with Matlab 5.
 
Cheers,
 
Pijus
 
--
"Those who can make you believe absurdities
can make you commit atrocities" - Voltaire
From virketis@fas.harvard.edu Wed May 22 07:08:03 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Wed, 22 May 2002 02:08:03 -0400 Subject: [Tutor] Persistent values in functions Message-ID: <200205220608.g4M687f27679@smtp2.fas.harvard.edu>
Seiji,
 
>I'd like to know if Python supports persistent= values
>in functions:  a variable type that saves its= value
>when the function returns, and gives the value= when
>the function is called again.  I seem to recall= that
>you can do this in C.  Please provide syntax= and
>perhaps a simple example.
 
I think you want the generator functions, available in= Python 2.2. Check out this article's second half for= introduction and code samples: htt= p://www-106.ibm.com/developerworks/linux/library/l-
pycon.html?dwzone=3Dlinux.
Cheers,
Pijus
 
 
--
"Those who can make you believe absurdities
can make you commit atrocities" - Voltaire
From ak@silmarill.org Wed May 22 09:12:20 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 22 May 2002 04:12:20 -0400 Subject: [Tutor] Persistent values in functions In-Reply-To: <20020522055859.25757.qmail@web21306.mail.yahoo.com> References: <20020522055859.25757.qmail@web21306.mail.yahoo.com> Message-ID: <20020522081220.GA2326@ak.silmarill.org> On Tue, May 21, 2002 at 10:58:59PM -0700, Seiji Funai wrote: > I'd like to know if Python supports persistent values > in functions: a variable type that saves its value > when the function returns, and gives the value when > the function is called again. I seem to recall that > you can do this in C. Please provide syntax and > perhaps a simple example. > > Thanks! > There isn't anything exactly like that afaik, but you can use global vars or instances: >>> a = 1 >>> def A(): ... global a ... a += 1 ... print a ... >>> A() 2 >>> A() 3 > > __________________________________________________ > Do You Yahoo!? > LAUNCH - Your Yahoo! Music Experience > http://launch.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From dyoo@hkn.eecs.berkeley.edu Wed May 22 09:02:09 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 May 2002 01:02:09 -0700 (PDT) Subject: [Tutor] Persistent values in functions In-Reply-To: <20020522055859.25757.qmail@web21306.mail.yahoo.com> Message-ID: On Tue, 21 May 2002, Seiji Funai wrote: > I'd like to know if Python supports persistent values in functions: a > variable type that saves its value when the function returns, and gives > the value when the function is called again. I seem to recall that you > can do this in C. Please provide syntax and perhaps a simple example. Hello! Hmmm... by "persistant", do you mean static local variables? In the C language, it's possible to have local variables that don't get cleared off between function calls: /*** C Code ***/ int nextNumber() { static int counter = 0; counter++; return counter; } /***/ The example above is a function that, when we first call it, will give us '1'. The next time we call it, it'll return '2' because the static 'counter' variable doesn't get cleared off every time, but is only initialized at the very beginning of the program. In a sense, the function has a memory. Python doesn't have "static" variables as a language feature, but we can do a similar thing if we use Python classes. Class instances can store persistant data, and we can also make them look very much like functions if we write a "__call__()" method for them. Let's take that C function above and try writing something equivalent to it in Python: ### Python code ### class Enumerator: def __init__(self): self.counter = 0 def __call__(self): self.counter = self.counter + 1 return self.counter # Some test code: if __name__ == '__main__': nextNumber = Enumerator() print "The first value I get out of nextNumber is", nextNumber() print "The second value I get out of nextNumber is", nextNumber() ### (Warning: I can't test the code at the moment, so there may be a typo in the code there. I'll double check tomorrow when I get back home.) Here, we can create an instance of an Enumerator class, and this instance can be "call()"ed as if it were a function. The instance keeps its own set of variables, so it can remember stuff like variable values, so that variables will appear to persist between function calls. If you're familiar with classes, this shouldn't look too bad, but it might be a little weird if you haven't seen classes yet. Please feel free to ask more questions about them, and the people on Tutor will be happy to talk about them. Anyway, hope this helps! From alan.gauld@bt.com Wed May 22 14:02:00 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 22 May 2002 14:02:00 +0100 Subject: [Tutor] Dynamic creation of class instances... Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F5@mbtlipnt02.btlabs.bt.co.uk> > Right now I start out with a list of names, craft a string that > looks like a class instantiation and then exec the sucker. Paul has already answered this based on a dictionary solution. But this is an issue for everyone on the list. Why does this same question come up every month on this list? It has to be one of the top FAQs for this mailing list. It suggests to me that something in the standard tutorials/texts must be suggesting this solution to people. Its such a bizarre solution that it never seems to come up in any of the other fora that I engage with(Delphi, C++, Smalltalk, Java(spit!) ). But on Python it seems like most newbies sooner or later come up with this amazing idea for naming objects using exec. So Why? Comments welcomed from newbies who've been there, or from newbies whpo nearly went there or from exorerienced hackers who might know why it comes up so often? I am seriously puzzled and if I can do anything in my tutor to circumvent it(short of discussing it explicitly!) I will. Alan g. From alan.gauld@bt.com Wed May 22 15:10:39 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 22 May 2002 15:10:39 +0100 Subject: [Tutor] Persistent values in functions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F7@mbtlipnt02.btlabs.bt.co.uk> > I'd like to know if Python supports persistent values > in functions: a variable type that saves its value > when the function returns, and gives the value when > the function is called again. I seem to recall that > you can do this in C. In C you use a local static variable. In modern OO languages you would use a class. It has the additional advantage that you can have multiple instances so it works in a multi threaded environment too, unlike C's strtok() function for example. Simply create a class with an attribute and a method such that the method updates the value on each call. Alan G. From alan.gauld@bt.com Wed May 22 15:21:06 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 22 May 2002 15:21:06 +0100 Subject: [Tutor] OO Python: How to change attributes of just one objec t in alist Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F8@mbtlipnt02.btlabs.bt.co.uk> > about it too much but FWIW I would probably give each student an ID > number and store them all in a dictionary with the ID as the > key. This is a good idea. Someone else suggested using the name as a key - which indirectly you do now - but that won't work if you get two students with the same name in the same class (We had two Graham Watsons in my class at school, and they both joined on the same day mid way thru' term - we thought the teacher had read the same note twice by mistake!) Assigning a unique ID and keeping name as an attribute is much better. You can even auto generate the ID if you like within the constructor. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Wed May 22 15:27:00 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 22 May 2002 15:27:00 +0100 Subject: [Tutor] Doing the Right Thing when converting strings to numb ers Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F9@mbtlipnt02.btlabs.bt.co.uk> > I'd like to convert a string to either a float or an integer > ``intelligently", i.e.: The easy way would be to use eval() All the usual caveats around using eval() (and exec()) apply of course.... def clever_coerce(mystr): return eval(mystr) > > >>> mystring = '5' > >>> mynumber = clever_coerce(mystring) > >>> print mynumber, type(mynumber) > 5 > >>> mystring = '4.9' > >>> mynumber = clever_coerce(mystring) > >>> print mynumber, type(mynumber) > 4.9 > > The string should ideally also be coerced into a float in the event of > it being, e.g. '5.0'. Does such a function exist in the Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From israel@lith.com Wed May 22 15:58:58 2002 From: israel@lith.com (Israel Evans) Date: Wed, 22 May 2002 07:58:58 -0700 Subject: [Tutor] Dynamic creation of class instances... Message-ID: I don't know _exactly_ why I figured that I need this sort of thing, but I believe that it comes from a misunderstanding of how to OOP really works. In my case I wanted to have a situation where a user would end up creating an object of sorts that I would hopefully use later on in the program. I was thinking along the lines of: "How can I use an unknown object later on if I don't know it's name? Everything needs a name right? How can I even make the darn thing without a unique name?" I thought it would be easier to create an instance with some name that the user specified and then introduce that nice little object to whatever object manager thingy-doodle I've crafted to handle such objects than to do it any other way. Actually I couldn't quite see how to handle new objects created by a program. Either by a user or perhaps by some sort of agent. It befuddled me to see how I could make an object without giving it a name. I think a good month bathing in pulped up OOP and Computer Science books would help me to absorb some of what I'm missing. My understanding of programming is rather darn foggy and limited so that was the first best thought as to a solution. I'd love to hear of better ways or be introduced to a couple of really nice books. ~Israel~ -----Original Message----- From: alan.gauld@bt.com [mailto:alan.gauld@bt.com] Sent: 22 May 2002 6:02 AM To: israel@lith.com; tutor@python.org Subject: RE: [Tutor] Dynamic creation of class instances... > Right now I start out with a list of names, craft a string that > looks like a class instantiation and then exec the sucker. Paul has already answered this based on a dictionary solution. But this is an issue for everyone on the list. Why does this same question come up every month on this list? It has to be one of the top FAQs for this mailing list. It suggests to me that something in the standard tutorials/texts must be suggesting this solution to people. Its such a bizarre solution that it never seems to come up in any of the other fora that I engage with(Delphi, C++, Smalltalk, Java(spit!) ). But on Python it seems like most newbies sooner or later come up with this amazing idea for naming objects using exec. So Why? Comments welcomed from newbies who've been there, or from newbies whpo nearly went there or from exorerienced hackers who might know why it comes up so often? I am seriously puzzled and if I can do anything in my tutor to circumvent it(short of discussing it explicitly!) I will. Alan g. From marcolinux@linuxbr.com.br Wed May 22 16:33:07 2002 From: marcolinux@linuxbr.com.br (Marco A. Sousa) Date: Wed, 22 May 2002 12:33:07 -0300 Subject: [Tutor] http through squid In-Reply-To: <20020522071101.17153.2719.Mailman@mail.python.org> References: <20020522071101.17153.2719.Mailman@mail.python.org> Message-ID: <20020522123307.B2611@marcolab.proconet> > > I am trying to do a URL request from behind a firewall. If I understand > it correctly (and I'll use generic symbols here) the proxy server is > x.y.z at port 123. The Squid proxy-caching software is running. I can [SNIP] > > Does anyone have a working script that works in a similar squid/proxy > configuration? > You can try put some environment variables telling about your proxy. It worked for me (linux, python 2.1): import urllib,os os.putenv ('http_proxy','10.15.50.3:3128') dic={'name':'python','email':'python@python.net'} url = urllib.urlopen('http://somesite.net/',urllib.urlencode(dic)) Also take a look at this page: http://www.python.org/doc/lib/module-urllib.html Hope that helps. From terjeja@hotmail.com Wed May 22 16:33:21 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Wed, 22 May 2002 15:33:21 +0000 Subject: [Tutor] functions and errors Message-ID: I am trying to write a program that does several different tasks in Excel. However, before I get there, I have to understand the basics. This is what I have written so far. import win32com.client import win32com.client.dynamic from win32com.client import Dispatch class accountcurrents: #xlApp = Dispatch("Excel.Application") #ex = Dispatch("Extra.System") #xlApp.Visible = 1 #xlApp.Workbooks.Add() #xlBook = xlApp.Workbooks(1) #xlSheet = xlApp.Sheets(1) def __init__(self): print"Hello" def finnxlpolicy(): print"world" The Excel part is just included so I can build further. But, my question is how can I get this to print world? If I type accountcurrents(), it prints Hello. If I try to write accountcurrents.finnxlpolicy() (stands for find policy in Excel, if you are curious) I get this error: Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method finnxlpolicy() must be called with accountcurrents instance as first argument (got nothing instead) If I write n = accountcurrents(), n.finnxlpolicy() I get the following error: Traceback (most recent call last): File "", line 1, in ? TypeError: finnxlpolicy() takes no arguments (1 given) What do I do wrong? Thanks in advance.... _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp. From dman@dman.ddts.net Wed May 22 17:19:26 2002 From: dman@dman.ddts.net (dman) Date: Wed, 22 May 2002 11:19:26 -0500 Subject: [Tutor] functions and errors In-Reply-To: References: Message-ID: <20020522161926.GA4451@dman.ddts.net> --envbJBWh7q8WU6mo Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 22, 2002 at 03:33:21PM +0000, Terje Johan Abrahamsen wrote: | I am trying to write a program that does several different tasks in Excel= .=20 | However, before I get there, I have to understand the basics. This is wha= t=20 | I have written so far. |=20 | class accountcurrents: =2E.. | def finnxlpolicy(): ^^ | print"world" | Traceback (most recent call last): | File "", line 1, in ? | TypeError: unbound method finnxlpolicy() must be called with=20 | accountcurrents instance as first argument (got nothing instead) Did you try to do accountcurrents.finnxlpolicy() ? You can't do that because the method is not really a part of the *class*, but rather a part of *instances of the class*. | If I write n =3D accountcurrents(), n.finnxlpolicy() I get the following= =20 | error: That's the right way to use the class. | Traceback (most recent call last): | File "", line 1, in ? | TypeError: finnxlpolicy() takes no arguments (1 given) |=20 | What do I do wrong? Thanks in advance.... You forgot to include the instance in the parameter list of the method. The corrected class is : class accountcurrents: #... def finnxlpolicy( self ): print"world" -D --=20 Microsoft is to operating systems & security .... .... what McDonald's is to gourmet coo= king =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --envbJBWh7q8WU6mo Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzrxQ4ACgkQO8l8XBKTpRTSwgCfSVy9nwXze/qP9oWzO3HhJSI/ /p4AnR7/0wrrbVhvmt6c3mrVtIJOwULC =mp/s -----END PGP SIGNATURE----- --envbJBWh7q8WU6mo-- From dman@dman.ddts.net Wed May 22 17:26:33 2002 From: dman@dman.ddts.net (dman) Date: Wed, 22 May 2002 11:26:33 -0500 Subject: [Tutor] The use of MailDir for a mail server In-Reply-To: References: Message-ID: <20020522162633.GB4451@dman.ddts.net> --UHN/qo2QbUvPLonB Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 20, 2002 at 12:47:11PM +0000, alex gigh wrote: | Hi; |=20 | I am still trying to write a mail server in Python... I decided that=20 | instead of going for the simple option of creating a file for each user a= nd=20 | append each new message to this file, I will use "MailDir"... Apart from error handling, mbox and maildir are both fairly easy to implement. I think maildir is actually a bit simpler. | the problem is... I searched the web to find an example on how I | could use this (my program is going to be a simple mail server with | pre-defined 2 or 3 users.... ) but couldn't find anything useful. | Can someone give me an example of : |=20 | 1) how I can create these maildirs One way to find this info is to use an existing program and see what it does. Here are some shell (works in bash with gnu utilities) commands to make a maildir "folder" and put a new message in it : mkdir -p the_folder/{new,cur,tmp} cat > the_folder/new/some_unique_id_001 < To: you Date: Wed May 22 11:22:28 CDT 2002 Subject: just a short test message test EOF You can verify that this works by opening the folder with mutt (or any other client). =20 | 2) if i need to put a new message in there... how do I copy a new file in= =20 | there Same way you write any file. Use the "open()" function to open the file for writing and write your data to it. If you already have the data in a file somewhere use the appropriate function in the "shutils" module. =20 | 3) and finally, when delivering messages, how do I get the text from the= =20 | possibly several different files I don't understand this question. How did the text get into multiple files in the first place? A mail message is (normally, who knows if you use weird junk like MS Exchange or Lotus Notes) a single stream of bytes. A file is also a single stream of bytes, it is just connected to the disk. | Also... where exactly can I find the source code for the python libraries= =20 | (namely smtp and rfc822) because I'm not allowed to use these... In the python distribution. It's all there. (http://www.python.org) The "Python Mail System" (http://pythonms.sf.net) project also has useful code for handling maildir and mbox folders (and other stuff). =20 =20 | Many thanks for your time HTH, -D --=20 "...In the UNIX world, people tend to interpret `non-technical user' as meaning someone who's only ever written one device driver." --Daniel Pead =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --UHN/qo2QbUvPLonB Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzrxrkACgkQO8l8XBKTpRQt7wCeMYHq0G8WpCRX6ccD3LEXVo32 Lf8AoJM4DJQKquhnLGzNK77p57Bk/K6a =Mf7I -----END PGP SIGNATURE----- --UHN/qo2QbUvPLonB-- From dman@dman.ddts.net Wed May 22 17:38:39 2002 From: dman@dman.ddts.net (dman) Date: Wed, 22 May 2002 11:38:39 -0500 Subject: ***SA:06.30*** Re: [Tutor] Quick question: Is it more efficient to... In-Reply-To: References: Message-ID: <20020522163839.GC4451@dman.ddts.net> --sHrvAb52M6C8blB9 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, May 21, 2002 at 11:13:06AM +0000, alex gigh wrote: | Hi; |=20 | In my mail server, I'm doing some sort of spam detection where I have a= =20 | kill file which is a list of regular expressions and I have to check that= =20 | the mail doesn't cotain any of these words... This sounds reasonable. | Is it more efficient to (A) check the lines one by one as I receive them = or=20 | (B) save the whole mail in a file and then check the whole mail with the= =20 | kill file... Check the whole file at once. It allows the regex engine to do it's own optimization stuff and reduces the number of times you invoke the regex engine. You still have some more decisions to make : o what will the regexes be matched against? o the whole raw message? o the whole message after MIME decoding? o just certain MIME parts? o all of the above? o some of the above, as specified by the config file? o do you want to allow line-by-line searching or just global searching? if you want line-by-line you may need to traverse the file line-by-line (but double check the re module, it may have a way to do it in one big search) o is the file one big regex or is it a collection of regexes? o if it's a collection, what separates regexes? newlines? o if it is multiple regexes, can you join them together to make one big regex to pass to the regex engine? | I have been told that if I use "pickle" I can do some very efficient | searching... I don't understand that. "pickle" is a way to convert an object to a stream and then reverse that. It isn't made to do text searching or serialize a mail message according to the RFCs. I wouldn't expect the output of pickling your object to be helpful at all in scanning for junk mail. | Which one would be better and why? =20 First make it work and make the code understandable. Then go back and profile it if it is too slow. =20 | Also... which number (i.e. 500) do I send back if: |=20 | (1) The user is unknown or domain name isn't accepted | (2) The mail isn't delivered because contains "unaccepted" word In RFC 821, section 4.2.1 : 550 Requested action not taken: mailbox unavailable [E.g., mailbox not found, no access] Send back a 550 along with an explanatory message. For a real-world example : $ telnet dman.ddts.net smtp Trying 65.107.69.216... Connected to dman.dman.ddts.net. Escape character is '^]'. 220 dman.ddts.net ESMTP Exim 4.04 (#10) Wed, 22 May 2002 11:35:42 -0500 ehlo nowhere 250-dman.ddts.net Hello elijah.iteams.org [65.107.69.197] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250 HELP mail from: 250 OK rcpt to: 250 Accepted data 354 Enter message, ending with "." on a line by itself From: To: Subject: $$$ Make Money Fast $$$ !!! viagra 100% GARANTEE AMAZING FULL REFUND=20 This is not spam =2E 550-Heuristics guessed that this message was spam: 550 hits=3D14.1 required=3D5.0 trigger=3D11.0 (I've got Spamassassin hooked into exim so that it scans messages at SMTP time and rejects spammy looking stuff, but blackholes really spammy looking stuff) HTH, -D --=20 Failure is not an option. It is bundled with the software. =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --sHrvAb52M6C8blB9 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzryY8ACgkQO8l8XBKTpRRjSwCgoyrVerbmJ6hEucj16rlorAn0 NPoAn03GKaWLYoTEbmxKO5Rjec7fXLG9 =FY7B -----END PGP SIGNATURE----- --sHrvAb52M6C8blB9-- From rob@uselesspython.com Wed May 22 17:49:42 2002 From: rob@uselesspython.com (Rob Andrews) Date: Wed, 22 May 2002 11:49:42 -0500 Subject: [Tutor] next article: constructive criticism welcome Message-ID: <3CEBCC26.7020409@uselesspython.com> http://uselesspython.com/JoeUselessWritesAProgram.html Useless now has a freshly drafted article on the process of going from an idea of a program through to having a working application. The target audience for it is programming newbies without the benefit of a Computer Science program. I'm sure it needs work, and would appreciate helpful feedback. Thanks, Rob From idiot1@netzero.net Wed May 22 18:22:59 2002 From: idiot1@netzero.net (kirk 'Deliberatus' Bailey) Date: Wed, 22 May 2002 13:22:59 -0400 Subject: [Tutor] Site updateD Message-ID: <3CEBD3F3.1CA2F240@netzero.net> Come visit! http://www.tinylist.org/ -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ From alan.gauld@bt.com Wed May 22 18:21:21 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 22 May 2002 18:21:21 +0100 Subject: [Tutor] functions and errors Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5FD@mbtlipnt02.btlabs.bt.co.uk> > class accountcurrents: > def __init__(self): > print "Hello" > > def finnxlpolicy(): def finnxlpolicy(self): #<--- Need to have a self argument > print "world" > > how can I get this to print world? > If I write n = accountcurrents(), n.finnxlpolicy() This combination should now work as expected. > TypeError: finnxlpolicy() takes no arguments (1 given) > What do I do wrong? Thanks in advance.... The error is because when you call n.finnxlpolicy() The interpreter sees it as: finnxlpolicy(n) With 'n' used as the "self" in your function definition. Thus you are passing an argument but hads not defined the function to accept any parameters. Python didn't like that. HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From terjeja@hotmail.com Wed May 22 18:55:36 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Wed, 22 May 2002 17:55:36 +0000 Subject: [Tutor] if else Message-ID: I try to use the if else statement. For example here: a = "python" if a = "python" : print "Yes" else : print "No" or a = 1 if a = 1 : print "Yes" else : print "No" But, it doesn't work. When I try to run it, I get the following response: "Failed to run script - syntax error - invalid syntax" What do I do wrong? Thanks in advance, Terje _________________________________________________________________ Join the world’s largest e-mail service with MSN Hotmail. http://www.hotmail.com From paulsid@shaw.ca Wed May 22 19:00:24 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 22 May 2002 12:00:24 -0600 Subject: [Tutor] if else References: Message-ID: <3CEBDCB8.95AF273C@shaw.ca> Terje Johan Abrahamsen wrote: > if a = 1 : > But, it doesn't work. When I try to run it, I get the following response: > "Failed to run script - syntax error - invalid syntax" What do I do wrong? You need to use a double-equals, ==, to "test" a value. This is to clearly differentiate it from = which is used for assignment. So your second example becomes: a = 1 if a == 1 : print "Yes" else : print "No" -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From paulsid@shaw.ca Wed May 22 19:00:30 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 22 May 2002 12:00:30 -0600 Subject: [Tutor] Dynamic creation of class instances... References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F5@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3CEBDCBE.D02C2806@shaw.ca> alan.gauld@bt.com wrote: > > Right now I start out with a list of names, craft a string that > > looks like a class instantiation and then exec the sucker. > Why does this same question come up every month on this list? > It has to be one of the top FAQs for this mailing list. Heh I've noticed that too. Perhaps we need a Tutor FAQ? I'd volunteer to write one except I don't think I've been here long enough yet. > But on Python it seems like most newbies sooner or later come > up with this amazing idea for naming objects using exec. > > So Why? Comments welcomed from newbies who've been there, or > from newbies whpo nearly went there or from exorerienced hackers > who might know why it comes up so often? I admit to having tried this as well when I first realized it could be done. I didn't really need it for anything, I just wanted to see if it was feasible. It didn't take too long for me to see that it wasn't, but it was fun to try. I think Python just makes it too easy to do, and thus very tempting to try to use in practice. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From ATrautman@perryjudds.com Wed May 22 19:04:49 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Wed, 22 May 2002 13:04:49 -0500 Subject: [Tutor] if else Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A29A@CORP_EXCHANGE> Python treats = the same way as C if that help but the way I think about it is: a = 1 means a is assigned the value of one a == 1 a is equal to one in your example a = "python" if a == "python" : print "Yes" else : print "No" will work where a is assigned the string "python" and then is checked if it is equal to "python" happy to have one I can answer Peace Alan -----Original Message----- From: Terje Johan Abrahamsen [mailto:terjeja@hotmail.com] Sent: Wednesday, May 22, 2002 12:56 PM To: tutor@python.org Subject: [Tutor] if else I try to use the if else statement. For example here: a = "python" if a = "python" : print "Yes" else : print "No" or a = 1 if a = 1 : print "Yes" else : print "No" But, it doesn't work. When I try to run it, I get the following response: "Failed to run script - syntax error - invalid syntax" What do I do wrong? Thanks in advance, Terje _________________________________________________________________ Join the world's largest e-mail service with MSN Hotmail. http://www.hotmail.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From flaxeater@yahoo.com Wed May 22 19:15:51 2002 From: flaxeater@yahoo.com (Chad Crabtree) Date: Wed, 22 May 2002 11:15:51 -0700 (PDT) Subject: [Tutor] IP Address Message-ID: <20020522181551.67115.qmail@web11606.mail.yahoo.com> I would like to make a script that Would FTP Post my home computer's IP address to my homepage. However I just cannot figure out how to get the IP i've looked over the Module reference. I am just not seeing it. __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com From dyoo@hkn.eecs.berkeley.edu Wed May 22 19:18:56 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 May 2002 11:18:56 -0700 (PDT) Subject: [Tutor] Dynamic creation of class instances... In-Reply-To: Message-ID: > I'm attempting to dynamically create an unknown number of class > instances and I'm wondering if there is a better way. There is probably a better way. *grin* Your code below does create new instances of your class, but it does something extra: it also uses exec() to create individual variables in the "local namespace" that "hold" those instances: > >>> class Test: > def __init__(self): > pass > > >>> namelist = ["kaya", "felice", "chalma", "frisia"] > > >>> for name in namelist: > thestring = '%s = Test()'%(name) > exec(thestring) > After this code executes, the variables 'kaya', 'felice', 'chamla', and 'frisia' are all initialized to new instances of the Test class. But if you didn't have to worry about the variable names, you can avoid exec() altogether by doing something like this: ### people = {} for name in namelist: people[name] = Test() ### Your class instances won't be directly accessible by name, but you can still get at them by looking them up in this 'people' dictionary. Using a dictionary as a container, to hold all those instances, is probably a better approach anyway. If you allow the outside world to name your variables, there's the potential for really big strangeness. For example, it might be possible for someone to do something like: ### namelist = ["kaya", "felice", "chalma", "frisia", "dir", "int", "float", "str"] ### By using something like a list or dictionary, we can provide kind of name isolation, to keep the names from leaking out into the program itself. But by using exec() injudiciously, there's a big potential for leakage. > Any Ideas? > ps. exec() scares me. exec() is useful, but probably not the best tool for what you're doing. Good luck to you! From stuart@sharedreality.org Wed May 22 19:27:39 2002 From: stuart@sharedreality.org (Stuart Smith) Date: Wed, 22 May 2002 19:27:39 +0100 Subject: [Tutor] IP Address In-Reply-To: <20020522181551.67115.qmail@web11606.mail.yahoo.com> Message-ID: <5.1.0.14.2.20020522192421.00addc98@sharedreality.org> Take a look at the socket module. More specifically, try this: from socket import * gethostbyname(gethostname()) gethostbyname returns an IP address given a hostname... gethostname returns the name of the local machine. -- Stuart Smith At 11:15 22/05/2002 -0700, you wrote: >I would like to make a script that Would FTP Post my >home computer's IP address to my homepage. However I >just cannot figure out how to get the IP i've looked >over the Module reference. I am just not seeing it. From dyoo@hkn.eecs.berkeley.edu Wed May 22 19:38:50 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 May 2002 11:38:50 -0700 (PDT) Subject: [Tutor] IP Address In-Reply-To: <20020522181551.67115.qmail@web11606.mail.yahoo.com> Message-ID: On Wed, 22 May 2002, Chad Crabtree wrote: > I would like to make a script that Would FTP Post my home computer's IP > address to my homepage. However I just cannot figure out how to get the > IP i've looked over the Module reference. I am just not seeing it. Hi Chad, Hmmm... I couldn't find it in the library reference either. However, if you're running on a Unix system, you can use the 'ifconfig' file to read your ip address. For example: ### dyoo@hkn:~$ /sbin/ifconfig eth0 eth0 Link encap:Ethernet HWaddr 00:A0:CC:65:1E:95 inet addr:128.32.138.82 Bcast:128.32.138.255 Mask:255.255.255.0 [extra stuff omitted] ### So it's possible to use Python to run an outside program like ifconfig, and read off the IP address from the program's output. The 'os.popen()' command might be useful for this. I did a quick search, and found the following script: IP Address Change Detection Script: http://opag.ca/resources/code/dhcpSMS.py There was some discussion on writing a Python module that didn't depend on running 'ifconfig' externally on the main Python list a while back: http://mail.python.org/pipermail/python-list/1999-August/008794.html I'm not quite sure on the status of the module; you might want to ask on comp.lang.python to see if someone had the time to write it. Good luck to you! From virketis@fas.harvard.edu Wed May 22 19:52:19 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Wed, 22 May 2002 14:52:19 -0400 Subject: [Tutor] IP Address In-Reply-To: Message-ID: <200205221852.g4MIqOE18385@smtp1.fas.harvard.edu>
 
>if= you're running on a Unix system, you can use the 'ifconfig'= file
>to
>read your ip address.  For= example:

You can do exactly the same on Windows. Here, on XP, we can= do:
 
c:\> ipconfig >> ip_number.txt
 
This produces a file ip_number.txt like so:
 
###
Windows IP Configuration
 
Ethernet adapter Local Area Connection:
 
       = Connection-specific DNS Suffix  . := student.harvard.edu
 
        IP Address. . . .= . . . . . . . . : 140.247.173.24
 
        Subnet Mask . . .= . . . . . . . . : 255.255.255.0
 
        Default Gateway .= . . . . . . . . : 140.247.173.1
###
 
It should not be too hard to parse this file for the= number.
 
Cheers,
 
Pijus
 


--
"Those who can make you believe absurdities
can make you commit atrocities" - Voltaire
From dyoo@hkn.eecs.berkeley.edu Wed May 22 20:03:10 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 May 2002 12:03:10 -0700 (PDT) Subject: [Tutor] Dynamic creation of class instances... In-Reply-To: <3CEBDCBE.D02C2806@shaw.ca> Message-ID: On Wed, 22 May 2002, Paul Sidorsky wrote: > alan.gauld@bt.com wrote: > > > > Right now I start out with a list of names, craft a string that > > > looks like a class instantiation and then exec the sucker. > > > Why does this same question come up every month on this list? > > It has to be one of the top FAQs for this mailing list. People with PHP experience appear to take this approach, if: http://www.onlamp.com/pub/a/php/2001/05/17/php_foundations.html?page=2 http://www.phpbuilder.com/columns/robert20000928.php3 is a indication of what an experienced PHP programmer can do with "variable variables". Yikes. So that may be one source of the question. > Heh I've noticed that too. Perhaps we need a Tutor FAQ? I'd volunteer > to write one except I don't think I've been here long enough yet. Write one up! *grin* > I admit to having tried this as well when I first realized it could be > done. I didn't really need it for anything, I just wanted to see if it > was feasible. It didn't take too long for me to see that it wasn't, but > it was fun to try. I think Python just makes it too easy to do, and > thus very tempting to try to use in practice. The Perl folks also allow this approach of "variable variables". Perl's DBI function "bind_columns()" does this, for example. But it's less of an issue in Perl because it has a separate namespace for variables, and I'm assuming PHP does this as well. That's one of the reasons every Perl scalar variable has those funny dollar signs. Python, on the other hand, treats every value --- even functions --- uniformly as first-class values, so that's why it's not such a hot idea to do "variable variables" in Python, since they can munge up function names. I'm off to the airport, so I'll talk to you later! From dman@dman.ddts.net Wed May 22 20:23:47 2002 From: dman@dman.ddts.net (dman) Date: Wed, 22 May 2002 14:23:47 -0500 Subject: [Tutor] IP Address In-Reply-To: <20020522181551.67115.qmail@web11606.mail.yahoo.com> References: <20020522181551.67115.qmail@web11606.mail.yahoo.com> Message-ID: <20020522192347.GA6293@dman.ddts.net> --azLHFNyN32YCQGCU Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 22, 2002 at 11:15:51AM -0700, Chad Crabtree wrote: | I would like to make a script that Would FTP Post my | home computer's IP address to my homepage. How about using ddts or dyndns to have your computer post it's IP address to a DNS server? Those services provide a client-side daemon that sends packets to the server with your IP address. The server then updates the DNS records so that your hostname points to your current IP address. While it is surely possible to write a program in python to FTP your address somewhere, I think a little bit of shell would be easier. #!/bin/sh # make a temp file for the address TNAME=3D`tempfile` # extract the first IPv4 address of the interface 'eth0' and store it # in the temp file /sbin/ifconfig eth0 \ | grep "inet addr" \ | head -1 \ | sed 's/.*inet addr:\([[:digit:].]\{7,15}\).*/\1/' \ > $TNAME # upload the file echo "put $TNAME my_ip" | ftp theserver.com # clean up rm -f $TNAME This requires that you put your username and password in ~/.netrc so that the ftp program doesn't need to ask you for it. Obviously change the ftp line to use the right server and remote path, and change the ifconfig line if you want to publish a different interface's address. As neat as python is, try writing this program this quickly in it :-). HTH, -D --=20 Trust in the Lord with all your heart and lean not on your own understanding; in all your ways acknowledge Him, and He will make your paths straight. Proverbs 3:5-6 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --azLHFNyN32YCQGCU Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzr8EMACgkQO8l8XBKTpRR7AACdH7dNnTGzgN4m6hsueLPemy2J 3zcAoMuUln47zQWkbwYbxba4WeSZA4ux =DT96 -----END PGP SIGNATURE----- --azLHFNyN32YCQGCU-- From terjeja@hotmail.com Wed May 22 20:21:19 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Wed, 22 May 2002 19:21:19 +0000 Subject: [Tutor] Win32Com Message-ID: I am writing a little porgram that pulls out some info from a cell in Excel. It works great, excepy for when I try to pull out info from a spreadsheet that I want info from. Here is the code: import win32com.client import win32com.client.dynamic from win32com.client import Dispatch import sys class accountcurrents: xlApp = Dispatch("Excel.Application") #ex = Dispatch("Extra.System") xlApp.Visible = 1 xlApp.Workbooks.Add() xlBook = xlApp.Workbooks(1) xlSheet = xlApp.Sheets(1) xlrad = 2 xlpol = "Donald" xlamount = 1.00 xldato = "1/11/11" def __init__(self): print"Hello" def finnxlpolicy(self): accountcurrents.xlrad = accountcurrents.xlrad + 1 accountcurrents.xlpol = accountcurrents.xlSheet.Cells(accountcurrents.xlrad,1).Value if accountcurrents.xlpol == None : print "yes" else: pass If I have a blank spreadsheet, and fill in some values in the A collumn, it works great. However, when I use the spreadsheet that I actually want the info from, it all crashes. The spreadsheet I want the info from looks like this: Policy# Effective Date Amount MCK0259477 11/5/1998 240 MCK0278868 5/27/2001 -572.72 MCK0279107 1/14/2001 -1474.82 and so forth. This errormessage comes: Traceback (most recent call last): File "", line 1, in ? File "C:\Documents and Settings\dsporck\My Documents\Python\accountcurrents\accountcurrents.py", line 23, in finnxlpolicy accountcurrents.xlpol = accountcurrents.xlSheet.Cells(accountcurrents.xlrad,1).Value File "C:\Python22\Lib\site-packages\win32com\client\__init__.py", line 347, in __getattr__ return apply(self._ApplyTypes_, args) File "C:\Python22\Lib\site-packages\win32com\client\__init__.py", line 341, in _ApplyTypes_ return self._get_good_object_(apply(self._oleobj_.InvokeTypes, (dispid, 0, wFlags, retType, argTypes) + args), user, resultCLSID) com_error: (-2146827864, 'OLE error 0x800a01a8', None, None) I use win2k, and newest version of Python, PythonWin and Win32Com. I do not change anything except for the contents of the spreadsheet. Even if I just copy the info into the spreadsheet that normally works. Thanks in advance, Terje _________________________________________________________________ Join the world’s largest e-mail service with MSN Hotmail. http://www.hotmail.com From stuart@sharedreality.org Wed May 22 21:18:11 2002 From: stuart@sharedreality.org (Stuart Smith) Date: Wed, 22 May 2002 21:18:11 +0100 Subject: [Tutor] IP Address In-Reply-To: <20020522192347.GA6293@dman.ddts.net> References: <20020522181551.67115.qmail@web11606.mail.yahoo.com> <20020522181551.67115.qmail@web11606.mail.yahoo.com> Message-ID: <5.1.0.14.2.20020522210650.00b0a810@sharedreality.org> Here's something I just wrote quickly, it works for uploading my IP to my home directory on my web server... from socket import * from ftplib import FTP import os localip = gethostbyname(gethostname()) # get the local IP address ipfile = open('myip','w') ipfile.write(localip) # put the IP into a file ipfile.close() ipfile = open('myip','r') ftp = FTP('your.ftpserver.com') # open an ftp connection to the server ftp.login('username','password') ftp.storlines('STOR myip',ipfile) # upload the file containing the ip ftp.quit() # disconnect ipfile.close() os.remove('myip') # delete the file to tidy up Not the exact functionality as your shell script, but then i've only really been learning Python for a week - I'm unsure of how a machine with multiple assigned IP addresses would be handled. >#!/bin/sh > ># make a temp file for the address >TNAME=`tempfile` > ># extract the first IPv4 address of the interface 'eth0' and store it ># in the temp file >/sbin/ifconfig eth0 \ > | grep "inet addr" \ > | head -1 \ > | sed 's/.*inet addr:\([[:digit:].]\{7,15}\).*/\1/' \ > > $TNAME > ># upload the file >echo "put $TNAME my_ip" | ftp theserver.com > ># clean up >rm -f $TNAME > > >This requires that you put your username and password in ~/.netrc so >that the ftp program doesn't need to ask you for it. Obviously change >the ftp line to use the right server and remote path, and change the >ifconfig line if you want to publish a different interface's address. > >As neat as python is, try writing this program this quickly in it :-). From terjeja@hotmail.com Wed May 22 21:58:31 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Wed, 22 May 2002 20:58:31 +0000 Subject: [Tutor] combine string and integer Message-ID: I have two variables that I want to merge into one based on a condition: def amount(self): if amount > 0: amount = amount else: amount = amount, '-' (or amount = amount * (-1), '-') If the variable amount is a negative number, for example -25, I want this function to remove the - in front of 25, and put it behind it, 25-. I assume amount[1:9] can remove the - in front? Or does the slice notation only work on strings? Otherways I could do the following amount*(-1)? However, the main problem is to get the - to go behind the amount. I have tried amount + "-", amount & "-" and amount, "-" as well as '-'. However, the two first gives me an errormessage. (unnsupported operand for float and string) The last one gives me this result: (-25.0, '-') A list I suppose? However, I want 25- or 25.0-. It doesn't really matter if it becomes a string or an integer. I am going to paste it into a different program.... Thanks in advance, Terje _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From ak@silmarill.org Wed May 22 23:04:55 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 22 May 2002 18:04:55 -0400 Subject: [Tutor] Dynamic creation of class instances... In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F5@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F5@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020522220455.GA8015@ak.silmarill.org> On Wed, May 22, 2002 at 02:02:00PM +0100, alan.gauld@bt.com wrote: > > Right now I start out with a list of names, craft a string that > > looks like a class instantiation and then exec the sucker. > > Paul has already answered this based on a dictionary solution. > > But this is an issue for everyone on the list. > > Why does this same question come up every month on this list? > It has to be one of the top FAQs for this mailing list. > > It suggests to me that something in the standard tutorials/texts > must be suggesting this solution to people. Its such a bizarre > solution that it never seems to come up in any of the other > fora that I engage with(Delphi, C++, Smalltalk, Java(spit!) ). > > But on Python it seems like most newbies sooner or later come > up with this amazing idea for naming objects using exec. > > So Why? Comments welcomed from newbies who've been there, or > from newbies whpo nearly went there or from exorerienced hackers > who might know why it comes up so often? > > I am seriously puzzled and if I can do anything in my tutor to > circumvent it(short of discussing it explicitly!) I will. > > Alan g. > Tutorials start out with variables and instances defined in the namespace, as opposed to being in lists or dictionaries. class Person: def __init__(self, name): self.name = name fred = Person("Fred Krabappel") then it's referenced as fred.name What if you want the program to get the name from raw_input? You intuitively long for something like exec that will do exactly the same operation for the name user entered. When we're learning something new and complicated, we try to take smallest possible steps instead of leaping ahead like "Now I will not only get the name from raw_input but will also store it in a list instead of a var in namespace like I did before". The solution is to touch on this topic in tutorials. Yes, exec seems like a natural here but it's not the best idea because [...]. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From shalehperry@attbi.com Wed May 22 22:12:10 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 22 May 2002 14:12:10 -0700 (PDT) Subject: [Tutor] combine string and integer In-Reply-To: Message-ID: On 22-May-2002 Terje Johan Abrahamsen wrote: > I have two variables that I want to merge into one based on a condition: > > def amount(self): > if amount > 0: > amount = amount > else: > amount = amount, '-' > (or amount = amount * (-1), '-') > > If the variable amount is a negative number, for example -25, I want this > function to remove the - in front of 25, and put it behind it, 25-. > I assume amount[1:9] can remove the - in front? Or does the slice notation > only work on strings? Otherways I could do the following amount*(-1)? > However, the main problem is to get the - to go behind the amount. I have > tried amount + "-", amount & "-" and amount, "-" as well as '-'. However, > the two first gives me an errormessage. (unnsupported operand for float and > string) The last one gives me this result: (-25.0, '-') A list I > suppose? However, I want 25- or 25.0-. It doesn't really matter if it > becomes a string or an integer. I am going to paste it into a different > program.... > if value < 0: char = '-' else: char = '' return "%d%s" % (abs(value), char) From israel@lith.com Wed May 22 22:13:58 2002 From: israel@lith.com (Israel Evans) Date: Wed, 22 May 2002 14:13:58 -0700 Subject: [Tutor] combine string and integer Message-ID: I don't know if this is the best way to do it but it seemed to work for me.. def numbermadness(num): if num < 0: strnum = str(num) # making num into a string neg = strnum[0] # getting the - sign number = strnum[1:len(strnum)]# getting the rest of num num = number + neg # switching stuff around return num # returning num whether it's changed or not. ~Israel~ -----Original Message----- From: Terje Johan Abrahamsen [mailto:terjeja@hotmail.com] Sent: 22 May 2002 1:59 PM To: tutor@python.org Subject: [Tutor] combine string and integer I have two variables that I want to merge into one based on a condition: def amount(self): if amount > 0: amount = amount else: amount = amount, '-' (or amount = amount * (-1), '-') If the variable amount is a negative number, for example -25, I want this function to remove the - in front of 25, and put it behind it, 25-. I assume amount[1:9] can remove the - in front? Or does the slice notation only work on strings? Otherways I could do the following amount*(-1)? However, the main problem is to get the - to go behind the amount. I have tried amount + "-", amount & "-" and amount, "-" as well as '-'. However, the two first gives me an errormessage. (unnsupported operand for float and string) The last one gives me this result: (-25.0, '-') A list I suppose? However, I want 25- or 25.0-. It doesn't really matter if it becomes a string or an integer. I am going to paste it into a different program.... Thanks in advance, Terje _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From israel@lith.com Wed May 22 22:15:37 2002 From: israel@lith.com (Israel Evans) Date: Wed, 22 May 2002 14:15:37 -0700 Subject: [Tutor] combine string and integer Message-ID: Israel---> Oh yeah... I like that better... Sean 'Shaleh' Perry [shalehperry@attbi.com] if value < 0: char = '-' else: char = '' return "%d%s" % (abs(value), char) From shalehperry@attbi.com Wed May 22 22:30:34 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 22 May 2002 14:30:34 -0700 (PDT) Subject: [Tutor] combine string and integer In-Reply-To: Message-ID: > > Sean 'Shaleh' Perry [shalehperry@attbi.com] > if value < 0: > char = '-' > else: > char = '' > > return "%d%s" % (abs(value), char) > "However, the main problem is to get the - to go behind the amount." is from the original mail. When I read that my mind saw "create a string from a template or pattern" and applied the approach I usually use for that idea. Patterns appear in coding, you learn to recognize them (-: From bryce@bembry.org Wed May 22 23:04:38 2002 From: bryce@bembry.org (Bryce Embry) Date: Wed, 22 May 2002 17:04:38 -0500 Subject: [Tutor] Request for Comments Message-ID: <5.1.0.14.0.20020522164630.02e69280@www.bembry.org> This is not a programming related question, but a request for assistance in developing some training materials. Being the fool I can be, I've volunteered to present a two-and-a-half hour session at a state conference this summer for school technology coordinators. My session is supposed to help system administrators start learning to program. I've developed a rather lengthy hand-out / tutorial (26 pages) which I am supposed to submit to the conference folks next week for burning on the official TETA Summer Institute CD-ROM. My goal in the session is to walk through some increasingly difficult programs, adding new skills as we go, until we can build two or three scripts that will be useful to the administrators. We start with "Hello World" and end up with a script to create passwords and save them to a text file, plus a bonus script that edits filenames, and another bonus script that edits text file contents. Obviously I cannot thoroughly cover everything, so I try to give them enough of a foundation that they can build on their own once they leave. So, seeing as this is a rather ambitious project for me, I wanted to solicit some extra "eyes". If anyone has the time or inclination to look through a 26-page introductory tutorial, I'd appreciate any comments you could offer. The text might have a few typographical errors (even though I've combed it three times now) and I'm not the best writer in the world, but what I'm really wanting is comments from Python users on the code, notes and approach in general. The pdf file is at www.bembry.org/tech/python/StartProgramming.pdf If you could email off list I'd appreciate any comments or suggestions. Thank you, Bryce Embry -------------------------------------------------------------------------------------------- "Lord, you establish peace for us. All that we have accomplished you have done for us" -- Isaiah 26:12 From ibis2001@telocity.com Mon May 20 07:28:15 2002 From: ibis2001@telocity.com (Geoffrey Bays) Date: Mon, 20 May 2002 02:28:15 -0400 Subject: [Tutor] OO Python: How to change attributes of just one object in a list Message-ID: <5.1.0.14.2.20020520022147.00a129c0@mail.telocity.com> I am trying to write an OO program in Python to keep track of students in classes of mine. Unfortunately, the changeGrade() method in class Course changes all of the students' grades on the same test to the same grade. I have determined that the for and if clauses work correctly, and have tried defining __eq__() and __del__ in the Student class, writing a changeGrade method in class Student, etc, but none of this does any good. I just want to push student objects onto the studentList and change their grades individually. Any help would be much appreciated. class Student: def __init__(self, name): self.name = name self.record = {} def display(self): print self.name, '\n' for item in self.record.keys(): print item, '\t', self.record[item], print '\n' class Course: def __init__(self,name): self.name = name self.tests = {} self.design() self.studentList = [] def design(self): s = raw_input('Enter graded items for the course separated by commas:\ test = s.split(",") for X in test: self.tests[X] = -1 def display(self): print c.name," " for test in c.tests.keys(): print test,": ",c.tests[test], print '\n' def addStudent(self,name): s = Student(name) s.record = self.tests self.studentList.append(s) def displayCourse(self): for i in range(len(self.studentList)): self.studentList[i].display() def changeGrade(self,studName,test,score): boolean = 0 for i in range(len(self.studentList)): if(self.studentList[i].name == studName ): self.studentList[i].record[test] = score //This is the line that changes all the students grades, not just the one boolean = 1 if (boolean == 0): print "No student of that name found." From char_c@mail.com Wed May 22 13:38:24 2002 From: char_c@mail.com (Charlie Chen) Date: Wed, 22 May 2002 20:38:24 +0800 Subject: [Tutor] Help Me!! Need help with python Message-ID: <20020522123824.46443.qmail@mail.com> Hi, I am trying to search a text file with a specified string,and i am having trouble doing it. I tried with re, and having lots of trouble for example if a text contain strings "abc" it will print out all the string starting with abc. Can you give me some hint on doing this in Python. Thanks Charlie -- _______________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup From roodbaard@earthlink.net Wed May 22 16:47:32 2002 From: roodbaard@earthlink.net (Hans Nowak) Date: Wed, 22 May 2002 11:47:32 -0400 Subject: [Tutor] functions and errors In-Reply-To: Message-ID: <3CEB8554.24977.23840A@localhost> On 22 May 2002, at 15:33, Terje Johan Abrahamsen wrote: > class accountcurrents: > #xlApp = Dispatch("Excel.Application") > #ex = Dispatch("Extra.System") > #xlApp.Visible = 1 > #xlApp.Workbooks.Add() > #xlBook = xlApp.Workbooks(1) > #xlSheet = xlApp.Sheets(1) > > def __init__(self): > print"Hello" > > def finnxlpolicy(): > print"world" You forgot the 'self': def finnxlpolicy(self): print "world" Method definitions should always have at least one argument, usually called "self". See also: http://www.python.org/doc/current/tut/node11.html#SECTION0011400000000000000000 HTH, --Hans Nowak (roodbaard@earthlink.net) http://www.awaretek.com/nowak/ From mikew@screaminet.com Wed May 22 14:05:24 2002 From: mikew@screaminet.com (Mike White) Date: 22 May 2002 19:05:24 +0600 Subject: [Tutor] idle2 error message Message-ID: <1022072724.1277.14.camel@OZ> I get the following error when trying to run idle2 on my Red Hat 7.3 machine: Traceback (most recent call last): File "/usr/lib/python2.2/site-packages/idle/idle.py", line 3, in ? import PyShell File "/usr/lib/python2.2/site-packages/idle/PyShell.py", line 13, in ? from Tkinter import * ImportError: No module named Tkinter Can someone help me get it to work? Mike White From ak@silmarill.org Thu May 23 01:16:09 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 22 May 2002 20:16:09 -0400 Subject: [Tutor] Help Me!! Need help with python In-Reply-To: <20020522123824.46443.qmail@mail.com> References: <20020522123824.46443.qmail@mail.com> Message-ID: <20020523001609.GA9337@ak.silmarill.org> On Wed, May 22, 2002 at 08:38:24PM +0800, Charlie Chen wrote: > Hi, > > I am trying to search a text file with a specified string,and i am having trouble doing it. > I tried with re, and having lots of trouble > for example if a text contain strings "abc" it will print out all the string starting with abc. > > Can you give me some hint on doing this in Python. > Here's an example: >>> s = "some text here" >>> if s.find("here") != -1: print "There is a 'here' in this string." ... There is a 'here' in this string. s.find returns position of found substring. If it's at the beginning, it returns 0. When not found, it gives back -1, so that's what you have to test for. - Andrei > > Thanks > > Charlie > -- > _______________________________________________ > Sign-up for your own FREE Personalized E-mail at Mail.com > http://www.mail.com/?sr=signup > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From dylan.belsey@baesystems.com Thu May 23 01:46:03 2002 From: dylan.belsey@baesystems.com (BELSEY, Dylan) Date: Thu, 23 May 2002 10:16:03 +0930 Subject: [Tutor] Deleting singleton objects Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B9632059@wtntex1.baea.com.au> Hi, I am trying to implement singletons in Python and need to remove them , once I have finished with them, from the namespace for certain functionality within a GUI system. Below is some simplified code of the situation which replicates my problem. The problem is that I can't seem to totally remove the object from the active "dictionary". If I could then this would be indicated by the calling of the __del__() function once the reference counter has reached zero. Since this is not occurring it is obvious that there still exists some reference to the singleton object but I don't know where it is. When I remove the singleton check code within the class and delete the object, I see the __del__() function called. Any ideas? Perhaps I am implementing the singleton incorrectly (but it does seem to work as expected if you call the class twice) and if so let me know. Thanks class hello: __single = None def __init__(self, variable): if hello.__single: raise hello.__single hello.__single = self self.value1 = variable def __del__(self): del self.value1 print "deleting hello object" f = 34 try: g = hello(f) except hello, obj: print """Already exists.""" g = obj print g.value1 del g From jimmy_130@lycos.com Thu May 23 01:58:42 2002 From: jimmy_130@lycos.com (James M Lang) Date: Wed, 22 May 2002 20:58:42 -0400 Subject: [Tutor] How can Python use the head phone jack? Message-ID: OK, what I'm really asking is, is there anyway for Python to convert data into two different sounds (e.g. a high sound for "1" and a low sound for "0") and send it out to the speaker/audio/headphone jack? I was thinking of a way to get rid of or use those old audio tapes and then I thought it'd be really cool to make Python use the ausio tapes for storage, like the Commodore 64. The problem is, as you may have already noticed, I have no idea how to do this, and how much memory can an audio tape hold? ________________________________________________________ Outgrown your current e-mail service? Get a 25MB Inbox, POP3 Access, No Ads and No Taglines with LYCOS MAIL PLUS. http://login.mail.lycos.com/brandPage.shtml?pageId=plus From ak@silmarill.org Thu May 23 02:24:06 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 22 May 2002 21:24:06 -0400 Subject: [Tutor] OO Python: How to change attributes of just one object in a list In-Reply-To: <5.1.0.14.2.20020520022147.00a129c0@mail.telocity.com> References: <5.1.0.14.2.20020520022147.00a129c0@mail.telocity.com> Message-ID: <20020523012406.GA9919@ak.silmarill.org> I thought you asked this question a few days ago and it got answered? On Mon, May 20, 2002 at 02:28:15AM -0400, Geoffrey Bays wrote: > I am trying to write an OO program in Python to keep track of students in > classes of mine. Unfortunately, the changeGrade() method in class Course > changes all of the students' grades on the same test to the same grade. > I have determined that the for and if clauses work correctly, and have > tried defining __eq__() and __del__ in the Student class, writing a > changeGrade method in class Student, etc, but none of this does any good. I > just want to push student objects onto the studentList and change their > grades individually. > Any help would be much appreciated. > > class Student: > def __init__(self, name): > self.name = name > self.record = {} > > def display(self): > print self.name, '\n' > for item in self.record.keys(): print item, '\t', self.record[item], > print '\n' > > class Course: > def __init__(self,name): > self.name = name > self.tests = {} > self.design() > self.studentList = [] > > def design(self): > s = raw_input('Enter graded items for the course separated by commas:\ > test = s.split(",") > for X in test: > self.tests[X] = -1 > > def display(self): > print c.name," " > for test in c.tests.keys(): print test,": ",c.tests[test], > print '\n' > > def addStudent(self,name): > s = Student(name) > s.record = self.tests > self.studentList.append(s) > > def displayCourse(self): > for i in range(len(self.studentList)): > self.studentList[i].display() > > def changeGrade(self,studName,test,score): > boolean = 0 > for i in range(len(self.studentList)): > if(self.studentList[i].name == studName ): > self.studentList[i].record[test] = score //This is the line that > changes all the students grades, not just the one > boolean = 1 > if (boolean == 0): > print "No student of that name found." > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From erikprice@mac.com Thu May 23 04:09:01 2002 From: erikprice@mac.com (Erik Price) Date: Wed, 22 May 2002 23:09:01 -0400 Subject: [Tutor] Dynamic creation of class instances... In-Reply-To: Message-ID: <6E5B0AF6-6DFA-11D6-AF96-00039351FE6A@mac.com> On Wednesday, May 22, 2002, at 10:58 AM, Israel Evans wrote: > "How can I use an unknown object later on if I don't know it's name? > Everything needs a name right? How can I even make the darn thing > without a > unique name?" Don't forget that a single object can go by many names throughout its life in a program. The name is nothing more than a reference to the object itself, which provides you with a convenient "handle" that you can use to attach it to your scripts or to other objects. But the object really doesn't have a proper, unique "name" (at least as far as you are concerned, perhaps to the interpreter there is something else going on entirely). Just make sure that you always have a "handle" on your object instance, in other words, a reference to it. Otherwise it will slip from your grasp like a helium balloon, eaten by the garbage collector. Erik From erikprice@mac.com Thu May 23 04:26:53 2002 From: erikprice@mac.com (Erik Price) Date: Wed, 22 May 2002 23:26:53 -0400 Subject: [Tutor] Dynamic creation of class instances... In-Reply-To: Message-ID: On Wednesday, May 22, 2002, at 03:03 PM, Danny Yoo wrote: > People with PHP experience appear to take this approach, if: > > > http://www.onlamp.com/pub/a/php/2001/05/17/php_foundations.html?page=2 > http://www.phpbuilder.com/columns/robert20000928.php3 > > is a indication of what an experienced PHP programmer can do with > "variable variables". Yikes. So that may be one source of the > question. I did take advantage of variable variables (PHP's equivalent of exec()ing strings of code) for a bit -- the nature of HTTP sort of requires it for generating unique form field names: $data = ""; for ($i = 0; $i < count($items); $i++) { $data .= "\n"; } Now assuming $items = array('apple', 'orange', 'banana'), $data is equal to HTTP doesn't have any means of representing an array per se, so you need to create unique strings to represent each element when you have no idea how many elements there may be in the array. I also use exec quite often in JavaScript. I do it so that I can modify an object's name based on the argument passed to a function, for instance: function chooseInput(inputName) { chosenObject = eval('document.formname.' + inputName + '.value'); if (chosenObject == '') document.write('There is no value in the form field called ' + inputName + '!'); else document.write('The value of the form field called ' + inputName + ' is ' + chosenObject); } The above function is stupid and doesn't even return a value, it's just a subroutine, but it shows how a single function can be used in multiple parts of a JavaScript/HTML document affecting different form names or document objects based on the argument to the function. Note that there is nothing unsafe about the use of exec() or var vars in either the PHP example or the JavaScript example above, since no user input is ever evaluated (the argument to the JavaScript function would be coded into the page by the programmer). And yet each is really needed to perform its task. Erik PS: I stopped using variable variables in PHP when I gave up on hidden form fields for maintaining state, sessions are just way too easy and can store objects very well. From dyoo@hkn.eecs.berkeley.edu Thu May 23 04:40:09 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 22 May 2002 20:40:09 -0700 (PDT) Subject: [Tutor] OO Python: How to change attributes of just one object in a list [repeated message] In-Reply-To: <20020523012406.GA9919@ak.silmarill.org> Message-ID: On Wed, 22 May 2002, Andrei Kulakov wrote: > I thought you asked this question a few days ago and it got > answered? This is my fault: as a List Admin, I went through all the messages that were floating around waiting to be manually verified, and validated anything that looks remotely non-spammy. But I hadn't been keeping up with Tutor for the past few days, so some may have ended up as reposts. Sorry about that! From roodbaard@earthlink.net Thu May 23 04:20:49 2002 From: roodbaard@earthlink.net (Hans Nowak) Date: Wed, 22 May 2002 23:20:49 -0400 Subject: [Tutor] Deleting singleton objects In-Reply-To: <86C3892A0C52D411AF5000A0C9EAA3B9632059@wtntex1.baea.com.au> Message-ID: <3CEC27D1.18117.29E3CA0@localhost> On 23 May 2002, at 10:16, BELSEY, Dylan wrote: > Hi, > I am trying to implement singletons in Python and need to remove > them , once I have finished with them, from the namespace for certain > functionality within a GUI system. Below is some simplified code of the > situation which replicates my problem. The problem is that I can't seem to > totally remove the object from the active "dictionary". If I could then > this would be indicated by the calling of the __del__() function once the > reference counter has reached zero. Since this is not occurring it is > obvious that there still exists some reference to the singleton object but I > don't know where it is. I do. :) It's right here: > class hello: > __single = None You use the class attribute __single to store a reference to the instance made. Not a bad idea, but when you want to delete the singleton entirely, you'll have to set this value again (to None, I guess, for consistency). You'll have to do this by hand, by the way. The __del__ method cannot do this for you, because it's only called if there are no more references to the instance... IOW, as long as __single contains a reference, __del__ isn't called. HTH, --Hans Nowak (roodbaard@earthlink.net) http://www.awaretek.com/nowak/ From dylan.belsey@baesystems.com Thu May 23 04:45:33 2002 From: dylan.belsey@baesystems.com (BELSEY, Dylan) Date: Thu, 23 May 2002 13:15:33 +0930 Subject: [Tutor] Deleting singleton objects Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B963205A@wtntex1.baea.com.au> Thanks :) I suspected so but wasn't previously able to access the attribute outside of the class. I now do so by calling a function within the class that sets this to "None". BTW is there a more efficient or standard way of implementing a singleton in Python, that is a lot "cleaner". Dylan -----Original Message----- From: Hans Nowak [mailto:roodbaard@earthlink.net] Sent: Thursday, 23 May 2002 13:21 To: BELSEY, Dylan Cc: tutor@python.org Subject: Re: [Tutor] Deleting singleton objects On 23 May 2002, at 10:16, BELSEY, Dylan wrote: > Hi, > I am trying to implement singletons in Python and need to remove > them , once I have finished with them, from the namespace for certain > functionality within a GUI system. Below is some simplified code of the > situation which replicates my problem. The problem is that I can't seem to > totally remove the object from the active "dictionary". If I could then > this would be indicated by the calling of the __del__() function once the > reference counter has reached zero. Since this is not occurring it is > obvious that there still exists some reference to the singleton object but I > don't know where it is. I do. :) It's right here: > class hello: > __single = None You use the class attribute __single to store a reference to the instance made. Not a bad idea, but when you want to delete the singleton entirely, you'll have to set this value again (to None, I guess, for consistency). You'll have to do this by hand, by the way. The __del__ method cannot do this for you, because it's only called if there are no more references to the instance... IOW, as long as __single contains a reference, __del__ isn't called. HTH, --Hans Nowak (roodbaard@earthlink.net) http://www.awaretek.com/nowak/ From dman@dman.ddts.net Thu May 23 05:44:07 2002 From: dman@dman.ddts.net (dman) Date: Wed, 22 May 2002 23:44:07 -0500 Subject: [Tutor] Deleting singleton objects In-Reply-To: <86C3892A0C52D411AF5000A0C9EAA3B963205A@wtntex1.baea.com.au> References: <86C3892A0C52D411AF5000A0C9EAA3B963205A@wtntex1.baea.com.au> Message-ID: <20020523044407.GA9892@dman.ddts.net> --YZ5djTAD1cGYuMQK Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, May 23, 2002 at 01:15:33PM +0930, BELSEY, Dylan wrote: =20 | BTW is there a more efficient or standard way of implementing a | singleton in Python, that is a lot "cleaner". Yeah, normally singletons aren't destroyed at all during the lifetime of a program. (see the GoF book) Here's how it is typically done in Python : class _single_class : # whatever the implementation is pass # make the one and only instance _single =3D _single_class() # we don't need the class hanging around to tempt people to misbehave del _single_class # a function to hide the fact that the class is a singleton def single() : return _single This does 3 things : 1) uses underscores to indicate, via convention, private names 2) creates the instance at the module level (since modules exist in python, though C++ and Java lack them) 3) destroys the (easy to get to) handle to the class so that it can't be constructed any more 4) Uses a function to hide the fact that the class is a singleton. This is another area where Python shines -- in C++/Java, instantiating a class does not look like a function call, so this sort of thing can't be done transparently. HTH, -D --=20 Come to me, all you who are weary and burdened, and I will give you rest. Take my yoke upon you and learn from me, for I am gentle and humble in heart, and you will find rest for your souls. For my yoke is easy and my burden is light. Matthew 11:28-30 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --YZ5djTAD1cGYuMQK Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzsc5cACgkQO8l8XBKTpRRtsQCfVtcqTo96SoONo2WZFGB/izAF 1eoAn13sleg5CU1znWilzTn/aBZX/Suz =70H5 -----END PGP SIGNATURE----- --YZ5djTAD1cGYuMQK-- From sarney@bigpond.com Thu May 23 11:35:04 2002 From: sarney@bigpond.com (Sarney) Date: Thu, 23 May 2002 20:35:04 +1000 Subject: [Tutor] triangles Message-ID: <001801c20245$809d8100$5fa836cb@sarney> Hi all, I found this problem at http://www.coolmath.com/triangle.htm How many non-congruent triangles can be constructed in a grid of given size (keeping the verticies at the grid intersections)? For instance there is only one possible triangle in a 2 x 2 grid, eight in a 3 x 3 grid etc. As a newbie, I found it a rewarding exercise. Can anyone suggest improvements? #################### #Determines possible non-congruent triangles in a given grid size n = int(raw_input("How large do you want the square grid to be? (Enter side) ")) # Generate matrix a = [] for x in range(n): for y in range(n): a.append([x,y]) triangles = [] lengths = [] for i in range(1,len(a)): for j in range(1,len(a)): side1 = (a[i][0]**2+a[i][1]**2)**0.5 side2 = (a[j][0]**2+a[j][1]**2)**0.5 side3 = ((a[j][0]-a[i][0])**2 + (a[j][1]-a[i][1])**2)**0.5 sides = [side1,side2,side3] verticies = a[i],a[j] sides.sort() if sides[0] == 0: # rejects coincident verticies continue if a[i][1]*a[j][0] == a[j][1]*a[i][0]: # rejects colinear verticies continue try: lengths.index(sides) except: ValueError triangles.append(verticies) lengths.append(sides) print "There are", len(lengths),"non-congruent triangles possible in a", print n,"x",n,"grid:" for i in range(len(lengths)): print triangles[i],lengths[i] ################# Cheers, Robert From pythontutor@venix.com Thu May 23 12:53:53 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 23 May 2002 07:53:53 -0400 Subject: [Tutor] idle2 error message References: <1022072724.1277.14.camel@OZ> Message-ID: <3CECD851.1090808@venix.com> I had this problem with RedHat 7.1. The "fix" was to rename /usr/bin/python to something else, I used rhpython. Redhat uses Python 1.5.2 for many system scripts. They have linked the old Python as the default in the /usr/bin directory. Python 2.2 installs into /usr/local/bin. While many of the redhat scripts will work with python2.2, some do not. I simply mv rhpython back to python (breaking idle) when I suspect that a script is having difficulty. A better solution would be for redhat to fix their system scripts to depend on a non-standard name (such as rhpython) so that we can upgrade to a newer python without breaking things. Mike White wrote: > I get the following error when trying to run idle2 on my Red Hat 7.3 > machine: > > > > Traceback (most recent call last): > File "/usr/lib/python2.2/site-packages/idle/idle.py", line 3, in ? > import PyShell > File "/usr/lib/python2.2/site-packages/idle/PyShell.py", line 13, in ? > from Tkinter import * > ImportError: No module named Tkinter > > Can someone help me get it to work? > > Mike White > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor@venix.com Thu May 23 12:56:10 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu, 23 May 2002 07:56:10 -0400 Subject: [Tutor] idle2 error message (COntinued) References: <1022072724.1277.14.camel@OZ> Message-ID: <3CECD8DA.1010506@venix.com> I didn't even look at your error messages when I posted before :-( It looks like Tkinter is not installed. Idle depends upon that module. Mike White wrote: > I get the following error when trying to run idle2 on my Red Hat 7.3 > machine: > > > > Traceback (most recent call last): > File "/usr/lib/python2.2/site-packages/idle/idle.py", line 3, in ? > import PyShell > File "/usr/lib/python2.2/site-packages/idle/PyShell.py", line 13, in ? > from Tkinter import * > ImportError: No module named Tkinter > > Can someone help me get it to work? > > Mike White > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From alan.gauld@bt.com Thu May 23 13:02:22 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 May 2002 13:02:22 +0100 Subject: [Tutor] combine string and integer Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C601@mbtlipnt02.btlabs.bt.co.uk> > I have two variables that I want to merge into one based on a > condition: > > def amount(self): > if amount > 0: > amount = amount > else: > amount = amount, '-' > (or amount = amount * (-1), '-') But since you have a self in there I assume this is a method rather than a vanilla function and amount is an attribute? In which case it needs self in front. BUT having a method and attribute with the same name is a bad idea so rename one and make it thus: def amount(self): if self.amt < 0: self.amt *= -1 return self.amt Which gets the modulus(size) of amount. But thats not really what you want.... > function to remove the - in front of 25, and put it behind it, 25-. If amount is an integer you can't do that. Where the '-' appears is a presentation issue that you should solve in your printing code. Python stores the number as a number not a string. > I assume amount[1:9] can remove the - in front? Or does the > slice notation only work on strings? No it works on any sequence type. But numbers are not sequences. However str(amount)[1:9] will indeed strip the first character. But you need to make sure the number is left justified. Using the format operator (%) will do this for you. > However, the main problem is to get the - to go behind the > amount. Thats a display issue. Try something like this: def mod(n): if n < 0: n *= -1 return n if amt < 0: s = "%d-" % mod(amt) else: s = "%d" % amt print s > suppose? However, I want 25- or 25.0-. Since its money you probably want to force two deciomal places too which you can do by using the format characters. See the documentation for the details under %f... Or look at the simple sequences page of my tutor for more info. And the Raw Data page for more about Python data types. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Thu May 23 13:10:53 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 May 2002 13:10:53 +0100 Subject: [Tutor] Help Me!! Need help with python Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C602@mbtlipnt02.btlabs.bt.co.uk> > I am trying to search a text file with a specified string,and > i am having trouble doing it. I assume grep can't be used for some reason? > I tried with re, and having lots of trouble > for example if a text contain strings "abc" it will print out > all the string starting with abc. So what do you want it to do instead? Alan G From alan.gauld@bt.com Thu May 23 13:20:17 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 May 2002 13:20:17 +0100 Subject: [Tutor] How can Python use the head phone jack? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C603@mbtlipnt02.btlabs.bt.co.uk> > OK, what I'm really asking is, is there anyway for Python to > convert data into two different sounds (e.g. a high sound for > "1" and a low sound for "0") and send it out to the > speaker/audio/headphone jack? Yes but its platform dependant. But Python does have sound functions and PyGame has quite sophisticated support based, I believe, on DirectX on Windows > rid of or use those old audio tapes and then I thought it'd > be really cool to make Python use the ausio tapes for > storage, like the Commodore 64. Hmm, That wasn't even cool on the C64! :-) Its a very slow and inefficient way to store data. You ae limited by the frequencies of sound you use and the length of time needed to register the tines on the tape. Thus you can't get much more than about 300 BITS per second. You then have to do all the error handling stuff(checksums, parity etc to make it even half reliable(hah!) so your storage works out about 30 bytes per second. For a C90 cassette thats 90 x 60 x 30 = 160Kbytes But of course you have two sides so its only 80K per side... You can improve it using compression of course but do you really want to go there?! Alan G. From charlie@begeistert.org Thu May 23 15:16:34 2002 From: charlie@begeistert.org (Charlie Clark) Date: Thu, 23 May 2002 14:16:34 +0000 Subject: [Tutor] Getting started with Python In-Reply-To: <20020523115646.31406.35346.Mailman@mail.python.org> References: <20020523115646.31406.35346.Mailman@mail.python.org> Message-ID: <20020523142959.5053.10@bepc.1022149584.fake> >From one Charlie to another! Let's try taking your message as an example >>> s = """I am trying to search a text file with a specified string,and i am having trouble doing it. I tried with re, and having lots of trouble for example if a text contain strings "abc" it will print out all the string starting with abc. Can you give me some hint on doing this in Python""" >>> s.find("abc") 180 # this means abc occurs at the 181st position in the string >>> print s[180:] abc" it will print out all the string starting with abc. Can you give me some hint on doing this in Python. You could easily put this in a loop >>> while 1: ... start = s.find("abc") ... if start > -1: ... print s[start:] ... s = s[start + 3:] ... else: ... break ... abc" it will print out all the string starting with abc. abc. But maybe you just want the word containing the text abc? In this case you would have to start looking for spaces to the left and right of "abc" and what would do with quotes and stuff? If you need some more intelligence than the above example then you should probably use regular expressions. But you should be able to plug them into the above loop. Charlie From alan.gauld@bt.com Thu May 23 13:27:40 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 May 2002 13:27:40 +0100 Subject: [Tutor] Deleting singleton objects Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C604@mbtlipnt02.btlabs.bt.co.uk> > BTW is there a more efficient or standard way of implementing a > singleton in Python, that is a lot "cleaner". I think so. Try a seach on google groups where youl fnd it duscussed(frequently) on comp.lang.python. Also search this list archive on Activestate where (I think it was Danny) did a nice version based on the class __call__() method. It was a while back so I won''t even guess when. Alan G From dyoo@hkn.eecs.berkeley.edu Thu May 23 14:40:31 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 May 2002 06:40:31 -0700 (PDT) Subject: [Tutor] How can Python use the head phone jack? In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C603@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Thu, 23 May 2002 alan.gauld@bt.com wrote: > > OK, what I'm really asking is, is there anyway for Python to convert > > data into two different sounds (e.g. a high sound for "1" and a low > > sound for "0") and send it out to the speaker/audio/headphone jack? > > Yes but its platform dependant. But Python does have sound functions and > PyGame has quite sophisticated support based, I believe, on DirectX on > Windows You can find out more about the pygame library here: http://pygame.org I haven't tried this yet, but you could probably using pygame.sndarray to generate beeps and pauses. You might want to talk with the pygame folks about this. They have a separate mailing list for pygame here: http://www.pygame.org/info.shtml#maillist You can probably grab data from a file, byte by byte, and play the individual bits of each byte. Something like: ### import sys, pygame def playSoundByte(byte): ## Do some beeps here for each bit. Dunno what this will ## look like yet, but it probably involves a little ## bit shifting. pass if __name__ == '__main__': myfile = open(sys.argv[1]) for byte in myfile.read(): playSoundByte(byte) ### I don't quite know how to access the microphone from pygame; try asking on the pygame mailing list for that one. > > rid of or use those old audio tapes and then I thought it'd be really > > cool to make Python use the ausio tapes for storage, like the > > Commodore 64. > > Hmm, That wasn't even cool on the C64! :-) Even so, this sounds like a very fun project, even if it is "impractical". Toy problems are great, in spite of (or because of) their limited practicality: no one else has probably done it yet. *grin* James, go for it! From dyoo@hkn.eecs.berkeley.edu Thu May 23 14:43:58 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 23 May 2002 06:43:58 -0700 (PDT) Subject: [Tutor] Deleting singleton objects In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C604@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Thu, 23 May 2002 alan.gauld@bt.com wrote: > > BTW is there a more efficient or standard way of implementing a > > singleton in Python, that is a lot "cleaner". > > I think so. > > Try a seach on google groups where youl fnd it duscussed(frequently) on > comp.lang.python. > > Also search this list archive on Activestate where (I think it > was Danny) did a nice version based on the class __call__() method. Probably wasn't me, since I still have to start reading Design Patterns. *grin* The Python Cookbook by Activestate has a bunch of Singleton recipes that might be useful: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 Good luck to you! From sk8ter9728@msn.com Thu May 23 15:50:13 2002 From: sk8ter9728@msn.com (Max Sorenson) Date: Thu, 23 May 2002 09:50:13 -0500 Subject: [Tutor] Tkinter PhotoImage widget question Message-ID: My name is Max Sorenson, I am student in Mr.Wilson's computer programing class at Henry Sibley High School. I am in the process of writing a program which uses METAR to get current weather conditions, and Tkinter to display the weather. I am trying to display an image for the wind direction using the PhotoImage widget, but I am having trouble gettting that code right. Here is the error that I am getting Exception in Tkinter callback Traceback (most recent call last): File "C:\PYTHON22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "H:\metarGUI2.py", line 81, in windDirection self.lprintPicture = Label(self.picF, image = self.picture) File "C:\PYTHON22\lib\lib-tk\Tkinter.py", line 2261, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "C:\PYTHON22\lib\lib-tk\Tkinter.py", line 1756, in __init__ self.tk.call( TclError: image "pyimage2" doesn't exist Every time that the program is ran, the "pyimage2" increases. For example, the next time it is run, the error will be "pyimage3" Here is some of the code that appears to be causing the problem: self.outputWind = Tk() self.outputWind.title("Wind Dir.") self.picF = Frame(self.outputWind) self.picture = PhotoImage(file = "north2.gif") self.lprintPicture = Label(self.picF, image = self.picture) self.lprintPicture.pack() self.picF.pack() self.outputWind.pack() Does anybody have any ideas of what may be causing the error, or if there is another way to display a simple image in a Tkinter window. Thanks, Max _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From shalehperry@attbi.com Thu May 23 16:03:05 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu, 23 May 2002 08:03:05 -0700 (PDT) Subject: [Tutor] triangles In-Reply-To: <001801c20245$809d8100$5fa836cb@sarney> Message-ID: >#################### > #Determines possible non-congruent triangles in a given grid size > > n = int(raw_input("How large do you want the square grid to be? (Enter side) > ")) > what if I enter 'Sean'? ># Generate matrix > a = [] > for x in range(n): > for y in range(n): > a.append([x,y]) since the vertices are constants, I would append tuples. a.append((x,y)). Has the advantage of mimicing coordinate notation as well (-: > triangles = [] > lengths = [] > for i in range(1,len(a)): > for j in range(1,len(a)): > side1 = (a[i][0]**2+a[i][1]**2)**0.5 > side2 = (a[j][0]**2+a[j][1]**2)**0.5 > side3 = ((a[j][0]-a[i][0])**2 + (a[j][1]-a[i][1])**2)**0.5 > sides = [side1,side2,side3] > verticies = a[i],a[j] > sides.sort() > if sides[0] == 0: # rejects coincident verticies > continue > if a[i][1]*a[j][0] == a[j][1]*a[i][0]: # rejects colinear verticies > continue > try: > lengths.index(sides) > except: > ValueError > triangles.append(verticies) > lengths.append(sides) > I would implement the body of this loop as a function. Would help clear up the code a bit and if this could be used elsewhere it would enable reuse. From terjeja@hotmail.com Thu May 23 16:07:09 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Thu, 23 May 2002 15:07:09 +0000 Subject: [Tutor] wait() or other pause functions, if any? Message-ID: I would like my program to pause between the running of two functions. Eg: function1() wait 2 seconds function2() This because the functions run other programs, and Python are way faster than the other programs, so I must get them to catch up. I found the function wait() at page: http://www.python.org/dev/doc/devel/lib/condition-objects.html. So I tried wait(2), but get an error that the name wait is not defined. Do I have to import some module with wait? If so which? I don't understand what they mean on the webpage. Where can I find such info? I looked in the Python reference, but that didn't mention the wait function. Thanks in advance, Terje _________________________________________________________________ Join the world’s largest e-mail service with MSN Hotmail. http://www.hotmail.com From bryce@bembry.org Thu May 23 16:11:06 2002 From: bryce@bembry.org (Bryce Embry) Date: Thu, 23 May 2002 10:11:06 -0500 Subject: [Tutor] Tkinter PhotoImage widget question In-Reply-To: Message-ID: <5.1.0.14.0.20020523100324.00b0e270@www.bembry.org> If I understand correctly, the "pyimage2" code is just an internal handle that Tkinter uses for keeping track of the image. When you call PhotoImage, it creates the pyimage object for calling in other portions of the program. The number at the end will increase each time you run the program in a particular session, then reset when you start a new Python session. Your code looks right, it would seem that the program just can't find the file. This may be overly simplistic, but is the file "north2.gif" in the directory where Python is looking? If you are running this in IDLE on a Windows box, then the directory is probably c:\Python21 or something similar. Trying giving the file a complete path and see if it still gives the error. self.picture = PhotoImage(file = "c:\\myimages\\north2.gif") or use os.getcwd() to find out what directory Python is looking in from os import getcwd print getcwd() If neither of these works, let me know and I'll keep hunting. Bryce At 09:50 AM 5/23/2002, you wrote: >My name is Max Sorenson, I am student in Mr.Wilson's computer programing >class at Henry Sibley High School. I am in the process of writing a >program which uses METAR to get current weather conditions, and Tkinter to >display the weather. I am trying to display an image for the wind >direction using the PhotoImage widget, but I am having trouble gettting >that code right. > >Here is the error that I am getting > >Exception in Tkinter callback >Traceback (most recent call last): > File "C:\PYTHON22\lib\lib-tk\Tkinter.py", line 1292, in __call__ > return apply(self.func, args) > File "H:\metarGUI2.py", line 81, in windDirection > self.lprintPicture = Label(self.picF, image = self.picture) > File "C:\PYTHON22\lib\lib-tk\Tkinter.py", line 2261, in __init__ > Widget.__init__(self, master, 'label', cnf, kw) > File "C:\PYTHON22\lib\lib-tk\Tkinter.py", line 1756, in __init__ > self.tk.call( >TclError: image "pyimage2" doesn't exist > >Every time that the program is ran, the "pyimage2" increases. For example, >the next time it is run, the error will be "pyimage3" > >Here is some of the code that appears to be causing the problem: > >self.outputWind = Tk() >self.outputWind.title("Wind Dir.") >self.picF = Frame(self.outputWind) >self.picture = PhotoImage(file = "north2.gif") >self.lprintPicture = Label(self.picF, image = self.picture) >self.lprintPicture.pack() >self.picF.pack() >self.outputWind.pack() > >Does anybody have any ideas of what may be causing the error, or if there >is another way to display a simple image in a Tkinter window. > Thanks, > Max > > >_________________________________________________________________ >Chat with friends online, try MSN Messenger: http://messenger.msn.com > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bryce Embry Geek-Of-All-Trades / Master-Of-None www.bembry.org -------------------------------------------------------------------------------------------------------------------------------------------------------- Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 38117 ^ (901)682-2409 -------------------------------------------------------------------------------------------------------------------------------------------------------- From bryce@bembry.org Thu May 23 16:16:10 2002 From: bryce@bembry.org (Bryce Embry) Date: Thu, 23 May 2002 10:16:10 -0500 Subject: [Tutor] wait() or other pause functions, if any? Message-ID: <5.1.0.14.0.20020523101547.02e84270@www.bembry.org> Try the sleep() function in the time module from time import sleep sleep(0.5) The number in the parentheses is how many seconds you want the program to pause. I'm not familiar with wait() but it sounds like sleep() will fit your needs. Bryce At 10:07 AM 5/23/2002, you wrote: >I would like my program to pause between the running of two functions. Eg: > >function1() >wait 2 seconds >function2() > >This because the functions run other programs, and Python are way faster >than the other programs, so I must get them to catch up. I found the >function wait() at page: >http://www.python.org/dev/doc/devel/lib/condition-objects.html. So I tried >wait(2), but get an error that the name wait is not defined. Do I have to >import some module with wait? If so which? I don't understand what they >mean on the webpage. Where can I find such info? I looked in the Python >reference, but that didn't mention the wait function. > >Thanks in advance, >Terje > >_________________________________________________________________ >Join the world's largest e-mail service with MSN Hotmail. >http://www.hotmail.com > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bryce Embry Geek-Of-All-Trades / Master-Of-None www.bembry.org -------------------------------------------------------------------------------------------------------------------------------------------------------- Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 38117 ^ (901)682-2409 -------------------------------------------------------------------------------------------------------------------------------------------------------- Bryce Embry Geek-Of-All-Trades / Master-Of-None www.bembry.org -------------------------------------------------------------------------------------------------------------------------------------------------------- Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 38117 ^ (901)682-2409 -------------------------------------------------------------------------------------------------------------------------------------------------------- From rob@uselesspython.com Thu May 23 16:20:08 2002 From: rob@uselesspython.com (Rob Andrews) Date: Thu, 23 May 2002 10:20:08 -0500 Subject: [Tutor] wait() or other pause functions, if any? References: Message-ID: <3CED08A8.5080005@uselesspython.com> This may not be what you're looking for, but the time.sleep is handy for a good many things. Here's an example: #!/usr/bin/python # sleeptest.py # import time def sleeptest(): time.sleep(5) print 'I have slept' if __name__ == '__main__': sleeptest() Rob Terje Johan Abrahamsen wrote: > I would like my program to pause between the running of two functions. Eg: > > function1() > wait 2 seconds > function2() > > This because the functions run other programs, and Python are way faster > than the other programs, so I must get them to catch up. I found the > function wait() at page: > http://www.python.org/dev/doc/devel/lib/condition-objects.html. So I > tried wait(2), but get an error that the name wait is not defined. Do I > have to import some module with wait? If so which? I don't understand > what they mean on the webpage. Where can I find such info? I looked in > the Python reference, but that didn't mention the wait function. > > Thanks in advance, > Terje > > _________________________________________________________________ > Join the world's largest e-mail service with MSN Hotmail. > http://www.hotmail.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From virketis@fas.harvard.edu Thu May 23 16:30:27 2002 From: virketis@fas.harvard.edu (Pijus Virketis) Date: Thu, 23 May 2002 11:30:27 -0400 Subject: [Tutor] wait() or other pause functions, if any? In-Reply-To: Message-ID: <200205231530.g4NFUcu11230@smtp3.fas.harvard.edu>
Dear Terje,
 
The function that I usually see used in situations such as= you suggest is sleep(), which is in the time module. I have also= found a wait() function in the Python posix module (http://www.informatik.hu-berlin.de/Them= en/manuals/python/python-texinfo/posix.html). This will use= the underlying OS tools to do the trick, if I understand= correctly. You can't even really import it, but must use the os= module instead to gain access to it. (h= ttp://www.python.org/doc/current/lib/module-posix.html) posix= claims not to work on Macs, and on Windows the wait() function= does not exist, so maybe the time.sleep() is the portable way to= go ...
 
Cheers,
 
Pijus
 
--
"Those who can make you believe absurdities
can make you commit atrocities" - Voltaire
From alan.gauld@bt.com Thu May 23 17:25:07 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 23 May 2002 17:25:07 +0100 Subject: [Tutor] wait() or other pause functions, if any? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C607@mbtlipnt02.btlabs.bt.co.uk> > I would like my program to pause between the running of two > functions. Eg: > > function1() > wait 2 seconds > function2() Try the time.sleep() call instead of wait() > This because the functions run other programs, and Python are > way faster than the other programs, so I must get them to > catch up. I assume you are spawning them as separate processes rather than just issueing a system() call? If you use system Python waits for the program to complete before moving on. Alan G From urnerk@qwest.net Thu May 23 18:37:59 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 23 May 2002 10:37:59 -0700 Subject: [Tutor] triangles In-Reply-To: <001801c20245$809d8100$5fa836cb@sarney> Message-ID: <4.2.0.58.20020523100730.01bc7510@pop3.norton.antivirus> At 08:35 PM 5/23/2002 +1000, Sarney wrote: >Hi all, > >I found this problem at http://www.coolmath.com/triangle.htm >How many non-congruent triangles can be constructed in a grid >of given size (keeping the verticies at the grid intersections)? >For instance there is only one possible triangle in a 2 x 2 grid, >eight in a 3 x 3 grid etc. As a newbie, I found it a rewarding >exercise. Can anyone suggest improvements? Hi Robert -- I think you did a fine job with this. Good insights. Have you written to Karen yet? You could cite your post here by URL (archived at ActiveState). The function below contains a few optimizations of your algorithm that you might be interested in, plus a couple syntax stream-linings (without going overboard): def triangles(n): """ Determines possible non-congruent triangles in a given grid size """ lengths = {} a = [[x,y] for x in range(n) for y in range(n)] # Generate matrix for i in range(1,len(a)): for j in range(1,len(a)): if a[i][1]*a[j][0] == a[j][1]*a[i][0]: continue # reject colinear vertices sides = [(a[i][0]**2+a[i][1]**2), (a[j][0]**2+a[j][1]**2), ((a[j][0]-a[i][0])**2 + (a[j][1]-a[i][1])**2)] sides.sort() if sides[0] == 0: continue # reject coincident vertices lengths[tuple(sides)] = [a[i],a[j]] return len(lengths) In getting distances, I don't bother with square roots, as this is an expensive floating point operation and comparing integers is more precise anyway. Since the goal is merely to find unique 3-distance tuples, leaving them in squared form will not impact the counts. Also, I dispose of colinear points even before bothering with the distance calcs (I like how you check for them -- compare slopes by cross-multiplying). Secondly, rather than search lengths using index, and catching the error (you could have also used find, which returns -1 if not found), I make lengths a dictionary and have the sorted [2nd powered] length-tuple serve as a key. This has the same effect as eliminating duplicates, as reassignment using the same key will not add a new member. It's also considerably faster. Note that I go ahead and assign the vertices as the value, but since I've opted to skip any print listing in this version, that's skippable too (could assign 0 or None just as well -- it's the key that matters here, more than the value). You'll find that the above optimizations significantly add to the speed. I get 1494 for a 10x10 grid in very little time. triangles(20) gives me 26190. Here's a sequence: >>> map(triangles,range(1,31)) [0, 1, 8, 29, 79, 172, 333, 587, 963, 1494, 2228, 3195, 4455, 6050, 8032, 10481, 13464, 17014, 21235, 26190, 31980, 38666, 46388, 55144, 65131, 76449, 89132, 103337, 119184, 136757] If you wanted to do actual distance listings (I doubt that you would, for these bigger grids), computing the roots at the time of printing would be an option, given you already have the 2nd powers as keys. Interesting post. Thanks for sharing. Kirby >#################### > #Determines possible non-congruent triangles in a given grid size > >n = int(raw_input("How large do you want the square grid to be? (Enter side) >")) > ># Generate matrix >a = [] >for x in range(n): > for y in range(n): > a.append([x,y]) >triangles = [] >lengths = [] >for i in range(1,len(a)): > for j in range(1,len(a)): > side1 = (a[i][0]**2+a[i][1]**2)**0.5 > side2 = (a[j][0]**2+a[j][1]**2)**0.5 > side3 = ((a[j][0]-a[i][0])**2 + (a[j][1]-a[i][1])**2)**0.5 > sides = [side1,side2,side3] > verticies = a[i],a[j] > sides.sort() > if sides[0] == 0: # rejects coincident verticies > continue > if a[i][1]*a[j][0] == a[j][1]*a[i][0]: # rejects colinear verticies > continue > try: > lengths.index(sides) > except: > ValueError > triangles.append(verticies) > lengths.append(sides) > >print "There are", len(lengths),"non-congruent triangles possible in a", >print n,"x",n,"grid:" > >for i in range(len(lengths)): > print triangles[i],lengths[i] > >################# > >Cheers, Robert From alex@gabuzomeu.net Thu May 23 18:34:44 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Thu, 23 May 2002 19:34:44 +0200 Subject: [Tutor] Deleting singleton objects In-Reply-To: <20020523152002.19965.37603.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020523192240.00c81770@pop3.norton.antivirus> At 11:20 23/05/2002 -0400, tutor-request@python.org wrote: >From: alan.gauld@bt.com >Subject: RE: [Tutor] Deleting singleton objects >Date: Thu, 23 May 2002 13:27:40 +0100 > > is there a more efficient or standard way of implementing a > > singleton in Python, that is a lot "cleaner". >Also search this list archive on Activestate where (I think it >was Danny) did a nice version based on the class __call__() method. This may be the version Alan refers to. It is very short: class Spam: """Singleton class""" def __call__(self): return self Spam = Spam() if __name__ == "__main__": # Testing toto = Spam() titi = Spam() assert id(toto) == id(titi) Source : posted by Matt Kangas on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 Cheers. Alexandre From Arthur Siegel" Hi all. I am trying to focus on performance issues in this round of refractoring of something I have been working on. In a frequently called section of the code I need to check for bounds - are my coordinates so large that it will screw up the scene display. If so, scale. As I have it currently structured all the bounds checking is in a seperate function at the module top level, and it is automatically called within the "update" function of a class - as part of the recurring update processing. It would probably have been better to test for the bounds condition within the class update function itself rathering than exiting to a function that tests the bounds (and immediately returns if within bounds). My question then is how much am I losing by this? Is the call to the outside function that could to avoided in most cases expensive? In the helping people to help themselves - I have been intimidated from trying to tackle profiling of performance. Is anyone aware of a basic tutorial on this topic? Thanks. Art From kalle@lysator.liu.se Thu May 23 19:09:44 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Thu, 23 May 2002 20:09:44 +0200 Subject: [Tutor] How expensive is a function call In-Reply-To: <003b01c20282$d88d7b30$1b8efea9@Arts> References: <003b01c20282$d88d7b30$1b8efea9@Arts> Message-ID: <20020523180944.GA3823@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Arthur Siegel] > My question then is how much am I losing by this? > Is the call to the outside function that could to avoided > in most cases expensive? Difficult to answer, but generally function calls are expensive in Python. The only way to find out for sure is to try both and see which one is faster, and by how much. > In the helping people to help themselves - I have been > intimidated from trying to tackle profiling of performance. > Is anyone aware of a basic tutorial on this topic? I found chapter 10 of the Python Library Reference helpful. http://python.org/doc/current/lib/profile.html Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE87TBddNeA1787sd0RAvd5AJ9OZvHfNJMRMqwjOOsRaZcWMNsYwwCfVViK S7bNmrimQ3vw3RvNmRSRLsU= =P4W7 -----END PGP SIGNATURE----- From cheshire_cat_sf@yahoo.com Thu May 23 21:50:19 2002 From: cheshire_cat_sf@yahoo.com (Britt Green) Date: Thu, 23 May 2002 13:50:19 -0700 (PDT) Subject: [Tutor] CGI Programming in Python Message-ID: <20020523205019.29145.qmail@web14108.mail.yahoo.com> Hello all, I've been trying to find some good sites for CGI programming in Python. But so far I'm not having much luck. I'm hoping the members of this mailing list can send a few sites my way; sites that are CGI newbie-friendly! :) Thanks! Britt ===== "The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman." __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com From rob@uselesspython.com Thu May 23 23:59:57 2002 From: rob@uselesspython.com (Rob Andrews) Date: Thu, 23 May 2002 17:59:57 -0500 Subject: [Tutor] CGI Programming in Python References: <20020523205019.29145.qmail@web14108.mail.yahoo.com> Message-ID: <3CED746D.70503@uselesspython.com> http://uselesspython.com/tutorials.html <-- The tutorials links page at Useless Python should have a few to get you started. (And I'd appreciate anyone letting me know of tutorials not on the list.) http://uselesspython.com/uselesspython1.html <-- And I put together a really simple CGI that generates a simple response web page based on form input. There's not a demo available at the moment, but the sample code is valid. Books like Programming_Python 2nd ed., Core_Python_Programming, and Python_How_To_Program also have excellent material to draw from. People in the Jackson, Mississippi (USA) area are welcome to take a look at my stack o' Python books, especially if they join the Mississippi Python Interest Group. I wish I had some way of sharing my books with people who aren't local, but until someone fleshes out a PEP for a language enhancement that allows us to break the laws of physics.... Rob http://uselesspython.com Britt Green wrote: > Hello all, > > I've been trying to find some good sites for CGI programming in Python. > But so far I'm not having much luck. I'm hoping the members of this > mailing list can send a few sites my way; sites that are CGI > newbie-friendly! :) > > Thanks! > > Britt > > ===== > "The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman." > > __________________________________________________ > Do You Yahoo!? > LAUNCH - Your Yahoo! Music Experience > http://launch.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From rob@uselesspython.com Fri May 24 00:06:06 2002 From: rob@uselesspython.com (Rob Andrews) Date: Thu, 23 May 2002 18:06:06 -0500 Subject: [Tutor] CGI Programming in Python References: <20020523205019.29145.qmail@web14108.mail.yahoo.com> <3CED746D.70503@uselesspython.com> Message-ID: <3CED75DE.5030704@uselesspython.com> I went ahead and tweaked out a demo to work on the new server for that CGI referenced in my 2nd paragraph. Here's the URL: http://uselesspython.com/testucs1.html Rob Rob Andrews wrote: > http://uselesspython.com/tutorials.html <-- The tutorials links page at > Useless Python should have a few to get you started. (And I'd appreciate > anyone letting me know of tutorials not on the list.) > > http://uselesspython.com/uselesspython1.html <-- And I put together a > really simple CGI that generates a simple response web page based on > form input. There's not a demo available at the moment, but the sample > code is valid. > > Books like Programming_Python 2nd ed., Core_Python_Programming, and > Python_How_To_Program also have excellent material to draw from. People > in the Jackson, Mississippi (USA) area are welcome to take a look at my > stack o' Python books, especially if they join the Mississippi Python > Interest Group. I wish I had some way of sharing my books with people > who aren't local, but until someone fleshes out a PEP for a language > enhancement that allows us to break the laws of physics.... > > Rob > http://uselesspython.com > > Britt Green wrote: > >> Hello all, >> >> I've been trying to find some good sites for CGI programming in Python. >> But so far I'm not having much luck. I'm hoping the members of this >> mailing list can send a few sites my way; sites that are CGI >> newbie-friendly! :) >> >> Thanks! >> >> Britt >> >> ===== >> "The ocean, she is strange and wondrous, filled with animals that >> disturb even a Frenchman." >> >> __________________________________________________ >> Do You Yahoo!? >> LAUNCH - Your Yahoo! Music Experience >> http://launch.yahoo.com >> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From idiot1@netzero.net Fri May 24 05:34:42 2002 From: idiot1@netzero.net (kirk 'Deliberatus' Bailey) Date: Fri, 24 May 2002 00:34:42 -0400 Subject: [Tutor] CGI Programming in Python References: <20020523205019.29145.qmail@web14108.mail.yahoo.com> Message-ID: <3CEDC2E2.E54ACCBC@netzero.net> Then pleaser provide us with a url to it/them. As for cgi, I blush to admit that tinylist contains some, and is VERBOSE in commenting. Britt Green wrote: > > Hello all, > > I've been trying to find some good sites for CGI programming in Python. > But so far I'm not having much luck. I'm hoping the members of this > mailing list can send a few sites my way; sites that are CGI > newbie-friendly! :) > > Thanks! > > Britt > > ===== > "The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman." > > __________________________________________________ > Do You Yahoo!? > LAUNCH - Your Yahoo! Music Experience > http://launch.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ From dman@dman.ddts.net Fri May 24 06:19:31 2002 From: dman@dman.ddts.net (dman) Date: Fri, 24 May 2002 00:19:31 -0500 Subject: [Tutor] CGI Programming in Python In-Reply-To: <20020523205019.29145.qmail@web14108.mail.yahoo.com> References: <20020523205019.29145.qmail@web14108.mail.yahoo.com> Message-ID: <20020524051931.GA19464@dman.ddts.net> --Nq2Wo0NMKNjxTN9z Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, May 23, 2002 at 01:50:19PM -0700, Britt Green wrote: | Hello all, |=20 | I've been trying to find some good sites for CGI programming in Python. | But so far I'm not having much luck. I'm hoping the members of this | mailing list can send a few sites my way; sites that are CGI | newbie-friendly! :) google for CGI. It's pretty much the same in any language. It works like this : o an HTTP request arrives at the web server o it forks and execs your script o when your script is invoked, certain environment variables are set (any of the CGI pages found through google will explain them) o you want to import the 'cgi' (or 'cgilib', whatever it's called) module in your script. It will parse the request and provide you with an object to extract all the form values from. o the rest is just python programming and printing valid HTML on stdout 3 and 4 are the only interesting steps for you, and the cgilib module takes care of the details. The library reference tells you the interface to it. Once you understand how CGI works, take a look at zope to build a non-trivial web application. HTH, -D --=20 Come to me, all you who are weary and burdened, and I will give you rest. Take my yoke upon you and learn from me, for I am gentle and humble in heart, and you will find rest for your souls. For my yoke is easy and my burden is light. Matthew 11:28-30 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --Nq2Wo0NMKNjxTN9z Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjztzWIACgkQO8l8XBKTpRQr5QCfeFDuN8fiIM9iC00JvFDDhJqC LsYAoMNqPBz6lt2bLHSyHvtbXXrYs6qH =55Pj -----END PGP SIGNATURE----- --Nq2Wo0NMKNjxTN9z-- From rob@uselesspython.com Fri May 24 07:53:38 2002 From: rob@uselesspython.com (Rob Andrews) Date: Fri, 24 May 2002 01:53:38 -0500 Subject: [Tutor] yet another Useless article Message-ID: <3CEDE372.5040005@uselesspython.com> http://uselesspython.com/BatteriesIncluded.html is the latest article freshly posted on Useless Python. It's so new I haven't really proofed it yet, and (as usual) submit it for a little constructive criticism. This one discusses Python modules, what they are, how to import them, ways to figure out more about them, etc. I have several ideas on how it could stand improvement, but figure at least a little sleep and some critique can come first. I've started adding these articles to the Tutorial links page for now, as well. Rob http://uselesspython.com From tombraider500@yahoo.co.uk Fri May 24 09:08:14 2002 From: tombraider500@yahoo.co.uk (Richard Gelling) Date: Fri, 24 May 2002 09:08:14 +0100 (GMT Daylight Time) Subject: [Tutor] Classses Message-ID: <3CEDF4EE.000005.42627@default> --------------Boundary-00=_QXVL6RO0000000000000 Content-Type: Text/Plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi,=0D I am reading Alan Gauld and have got a bit stuck.I am up to reading about classes and have typed in his example i.e=0D =0D class Address:=0D def _init_(self,Hs,Town,Zip)=0D self.Hs_Number=3DHs=0D self.Street=3DSt=0D self.Town=3DTown=0D self.Zip_Code=3DZip=0D =0D Which appears to work fine,however when type in the second part ie=0D =0D addr=3DAddress(7,"High St.","Anytown","12345")=0D =0D I get the error :=0D =0D Traceback (most recent call last):=0D File "", line 1, in ?=0D TypeError: this constructor takes no arguments=0D =0D Could someone explain what is going wrong here.I am unable to see what i = am doing wrong.I have typed it in exactly as it is in the book and Have trie= d it on 2 working machines.I would be most grateful if someone could enligh= ten me,As i dont really want to continue until i see what i am doing wrong.=0D =0D =0D Thanks a lot =0D R.Gelling=0D =0D Registered Linux User : 256848 --------------Boundary-00=_QXVL6RO0000000000000 Content-Type: Text/HTML; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
I am reading Alan Gauld and have got a bit stuck.I am up to re= ading=20 about classes and have typed in his example i.e
 
class Address:
           def=20 _init_(self,Hs,Town,Zip)
       =20          =20 self.Hs_Number=3DHs
            =  =20     self.Street=3DSt
           =20       self.Town=3DTown
           =20       self.Zip_Code=3DZip
 
Which appears to work fine,however when type in the second par= t=20 ie
 
addr=3DAddress(7,"High St.","Anytown","12345")
 
I get the error :
 
Traceback (most recent call last):
  File "<interac= tive=20 input>", line 1, in ?
TypeError: this constructor takes no=20 arguments
 
Could someone explain what is going wrong here.I am unable to = see=20 what i am doing wrong.I have typed it in exactly as it is in the bo= ok and=20 Have tried it on 2 working machines.I would be most grateful if som= eone=20 could enlighten me,As i dont really want to continue until i see wh= at i am=20 doing wrong.
 
 
Thanks a lot
R.Gelling
 
Registered Linux User : 256848
=09 =09 =09 =09 =09 =09 =09
--------------Boundary-00=_QXVL6RO0000000000000-- _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From its_steevo@hotmail.com Fri May 24 09:13:41 2002 From: its_steevo@hotmail.com (steve king) Date: Fri, 24 May 2002 09:13:41 +0100 Subject: [Tutor] editing a file Message-ID: Hello everyone, the help I had last time from the tutors was so good I need another fix :-) Ok I have worked out how to read and write files (its not that hard after all). But now I need to be able to edit these files. This is the situation: In a config file I have the following: [Main] AAA= BBB= CCC= DDD= What I want to be able to do is insert another string like "EEE=" between,say, "BBB=" and "CCC=" or anywhere in the file. How do I do this? I know there is a function called seek() but the documentation is a little sparse. _________________________________________________________________ Join the world’s largest e-mail service with MSN Hotmail. http://www.hotmail.com From ak@silmarill.org Fri May 24 09:19:46 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 24 May 2002 04:19:46 -0400 Subject: [Tutor] Classses In-Reply-To: <3CEDF4EE.000005.42627@default> References: <3CEDF4EE.000005.42627@default> Message-ID: <20020524081946.GA1417@ak.silmarill.org> On Fri, May 24, 2002 at 09:08:14AM +0100, Richard Gelling wrote: > Hi, > I am reading Alan Gauld and have got a bit stuck.I am up to reading about > classes and have typed in his example i.e > > class Address: > def _init_(self,Hs,Town,Zip) > It should be __init__, with four underlines (you have two). > self.Hs_Number=Hs > self.Street=St > self.Town=Town > self.Zip_Code=Zip > > Which appears to work fine,however when type in the second part ie > > addr=Address(7,"High St.","Anytown","12345") > > I get the error : > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: this constructor takes no arguments > > Could someone explain what is going wrong here.I am unable to see what i am > doing wrong.I have typed it in exactly as it is in the book and Have tried > it on 2 working machines.I would be most grateful if someone could enlighten > me,As i dont really want to continue until i see what i am doing wrong. > > > Thanks a lot > R.Gelling > > Registered Linux User : 256848 -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ak@silmarill.org Fri May 24 09:30:49 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 24 May 2002 04:30:49 -0400 Subject: [Tutor] editing a file In-Reply-To: References: Message-ID: <20020524083049.GA1547@ak.silmarill.org> On Fri, May 24, 2002 at 09:13:41AM +0100, steve king wrote: > Hello everyone, the help I had last time from the tutors was so good I need > another fix :-) > > Ok I have worked out how to read and write files (its not that hard after > all). But now I need to be able to edit these files. This is the situation: > > In a config file I have the following: > > [Main] > AAA= > BBB= > CCC= > DDD= > > What I want to be able to do is insert another string like "EEE=" > between,say, "BBB=" and "CCC=" or anywhere in the file. How do I do this? I > know there is a function called seek() but the documentation is a little > sparse. > Well, if it can be anywhere in the file, append it at the end. If you really want to insert it in between other lines, read all lines and then write them out again, inserting it as you reach the right place. By the way, look at configparser module. > > > > _________________________________________________________________ > Join the world?s largest e-mail service with MSN Hotmail. > http://www.hotmail.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From alan.gauld@bt.com Fri May 24 09:39:55 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 24 May 2002 09:39:55 +0100 Subject: [Tutor] How expensive is a function call Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C60F@mbtlipnt02.btlabs.bt.co.uk> > My question then is how much am I losing by this? Probably not much but performance is a funny thing. Only the profiler will really tell you. > In the helping people to help themselves - I have been > intimidated from trying to tackle profiling of performance. > Is anyone aware of a basic tutorial on this topic? There is pretty good guidance in the documentation. Its really pretty straighforward. Try it, if you get stuck ask. Its probably the easiest way. If you have Programming Python it has a chapter on using the profiler too. Alan g From alan.gauld@bt.com Fri May 24 09:47:26 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 24 May 2002 09:47:26 +0100 Subject: [Tutor] Classses Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C610@mbtlipnt02.btlabs.bt.co.uk> > I am reading Alan Gauld I wondered what that strange sensation was... ;-) > class Address:=0D > def _init_(self,Hs,Town,Zip)=0D > self.Hs_Number=3DHs=0D > self.Street=3DSt=0D > self.Town=3DTown=0D > self.Zip_Code=3DZip=0D Thats two underscores each end of init, not one. This is a common convention in Python for 'magic' function names. There are a couple of footnotes in the book but if I ever do a 2nd edition I'll elevate them to the main text since you aren't the first to miss them! > TypeError: this constructor takes no arguments=0D This is because Python doesn't recognise your init as a constructor so is using the default one which, as it says, takes no arguments... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alex@gabuzomeu.net Fri May 24 10:07:18 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Fri, 24 May 2002 11:07:18 +0200 Subject: [Tutor] Classses In-Reply-To: <20020524080904.15143.33316.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020524105938.00e32d30@pop3.norton.antivirus> Hi Richard, At 04:09 24/05/2002 -0400, tutor-request@python.org wrote: >Date: Fri, 24 May 2002 09:08:14 +0100 (GMT Daylight Time) >From: "Richard Gelling" >Subject: [Tutor] Classses >I am reading Alan Gauld and have got a bit stuck.I am up to reading about >classes and have typed in his example i.e > >class Address: > def _init_(self,Hs,Town,Zip) You need to use double underscores. In Python, special method names are wrapped in double underscores. And you need a colon at the end of the line (maybe it was included in your code; I received a garbled message). def __init__(self, Hs, Town, Zip): > self.Hs_Number=Hs > self.Street=St > self.Town=Town > self.Zip_Code=Zip >TypeError: this constructor takes no arguments The interpreter did not recognise your "__init__" as a valid constructor; hence it used a default one with no arguments. Cheers. Alexandre From alex@gabuzomeu.net Fri May 24 10:09:10 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Fri, 24 May 2002 11:09:10 +0200 Subject: [Tutor] How expensive is a function call In-Reply-To: <20020524080904.15143.33316.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020524110813.00e32e60@pop3.norton.antivirus> Hi Arthur, At 04:09 24/05/2002 -0400, tutor-request@python.org wrote: >From: "Arthur Siegel" >Date: Thu, 23 May 2002 13:54:11 -0400 >Subject: [Tutor] How expensive is a function call I am trying to focus on performance issues >in this round of refractoring of something >I have been working on. > >In a frequently called section of the code I need >to check for bounds - are my coordinates so >large that it will screw up the scene display. >If so, scale. > >As I have it currently structured all the bounds checking >is in a seperate function at the module top level, and it is >automatically called within the "update" function of >a class - as part of the recurring update processing. > >It would probably have been better to test for the >bounds condition within the class update function >itself rathering than exiting to a function that tests the >bounds (and immediately returns if within bounds). > >My question then is how much am I losing by this? >Is the call to the outside function that could to avoided >in most cases expensive? > >In the helping people to help themselves - I have been >intimidated from trying to tackle profiling of performance. >Is anyone aware of a basic tutorial on this topic? From alex@gabuzomeu.net Fri May 24 10:11:19 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Fri, 24 May 2002 11:11:19 +0200 Subject: [Tutor] How expensive is a function call Message-ID: <4.3.2.7.2.20020524110926.00e139d0@pop3.norton.antivirus> [Apologies for the previous uncomplete message. I hit the wrong shortcut.] At 04:09 24/05/2002 -0400, tutor-request@python.org wrote: >From: "Arthur Siegel" >Date: Thu, 23 May 2002 13:54:11 -0400 >Subject: [Tutor] How expensive is a function call > I am trying to focus on performance issues >in this round of refractoring of something >I have been working on. You may be interested in this resource: http://manatee.mojam.com/~skip/python/fastpython.html Cheers. Alexandre From dyoo@hkn.eecs.berkeley.edu Fri May 24 14:27:45 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 May 2002 06:27:45 -0700 (PDT) Subject: [Tutor] yet another Useless article In-Reply-To: <3CEDE372.5040005@uselesspython.com> Message-ID: On Fri, 24 May 2002, Rob Andrews wrote: > http://uselesspython.com/BatteriesIncluded.html is the latest article > freshly posted on Useless Python. It's so new I haven't really proofed > it yet, and (as usual) submit it for a little constructive criticism. Looks good! Are there other articles that you're planning on writing? Another interesting module that could be used to show how modules are neat might be one of the cryptographic hashing modules like 'md5', since it's something that packages some really complex stuff in a tidy package. One pitfall I've run into before is that, sometimes, I name one of my own modules something that's in the Standard Library. It might be good to explain that Python files in one's directory are also 'modules' that Python can import. From rob@uselesspython.com Fri May 24 14:54:09 2002 From: rob@uselesspython.com (Rob Andrews) Date: Fri, 24 May 2002 08:54:09 -0500 Subject: [Tutor] yet another Useless article References: Message-ID: <3CEE4601.8030508@uselesspython.com> Danny Yoo wrote: > > On Fri, 24 May 2002, Rob Andrews wrote: > > >>http://uselesspython.com/BatteriesIncluded.html is the latest article >>freshly posted on Useless Python. It's so new I haven't really proofed >>it yet, and (as usual) submit it for a little constructive criticism. >> > > Looks good! Are there other articles that you're planning on writing? > I actually hope to add as many of these articles as possible to Useless Python, since the whole point of the site is to encourage people to start banging out code any way they can. Sometimes I set out to write about a particular subject (like the Jython/Swing piece), and sometimes I just start writing and see what comes of it. So other than the fact that I'd like to do more Jython-oriented material, I have no idea what's coming up next. Also, these articles are part of my own learning process. You can learn a lot very quickly by trying to put it into words that someone else will understand. And trying to talk about these things in words that even someone like ME will understand is a special effort indeed! Of course, part of my subconscious is also dwelling on the website and how great it would be if more tutorials and learning-based articles were collected in one central website. I'm very far from a Python guru, but I can honestly say that the process of learning Python is one of the great joys of my adult life, and who doesn't want to share their joy? > > Another interesting module that could be used to show how modules are neat > might be one of the cryptographic hashing modules like 'md5', since it's > something that packages some really complex stuff in a tidy package. > I haven't messed with the crypto modules yet, just because I keep needing to sleep every now and again. Of course, anyone could contribute such examples for the site. Format isn't a big deal, since I can always slap some XHTML around just about anything. (I'm not anti-proud of some of my little bits of wizardry in the web arena, like managing to actually get whitespace to appear in a browser window! heh) > > One pitfall I've run into before is that, sometimes, I name one of my own > modules something that's in the Standard Library. It might be good to > explain that Python files in one's directory are also 'modules' that > Python can import. > I did hint at this without stating it in so many words. It's on my list of things to go back and say, but haven't found all the right words for yet. Thanks, Rob From Szilard" <3CEE4601.8030508@uselesspython.com> Message-ID: <029601c2032b$5711da20$ca65c1cf@easyrider> Hello Everybody, Is there any moria or rogue like game written in python? Szilard From dyoo@hkn.eecs.berkeley.edu Fri May 24 16:14:54 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 May 2002 08:14:54 -0700 (PDT) Subject: [Tutor] Moria In-Reply-To: <029601c2032b$5711da20$ca65c1cf@easyrider> Message-ID: On Fri, 24 May 2002, Szilard wrote: > Hello Everybody, > Is there any moria or rogue like game written in python? Hi Szilard, Check Pangband, which is a rogue-like game that's extendible with Python: http://thangorodrim.angband.org/pangband.html I haven't played this (I'm too busy with Nethack as it is... *grin*) but it looks interesting enough. Another noteworthy game that's in development is the Arianne RPG engine, which is on Sourceforge.net: http://sourceforge.net/projects/arianne/ Hope this helps! From jeff@ccvcorp.com Fri May 24 17:56:48 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 24 May 2002 09:56:48 -0700 Subject: [Tutor] Classses References: <3CEDF4EE.000005.42627@default> Message-ID: <3CEE70D0.5F8F7358@ccvcorp.com> Richard Gelling wrote: > class Address:> def _init_(self,Hs,Town,Zip)> self.Hs_Number=Hs> self.Street=St> self.Town=Town> self.Zip_Code=Zip>> Which appears to work fine,however when type in the second part ie>> addr=Address(7,"High St.","Anytown","12345")> [...] Others have already pointed out your problem with _init_ versus __init__, but I wanted to mention that you've got another bug lurking here. In your constructor, you have the line "self.Street = St" ... but you don't have St in your argument list! So, when you fix your underscores and run this again, you'll still get an error, saying that the constructor takes exactly four arguments (five given). Jeff Shannon Technician/Programmer Credit International From israel@lith.com Fri May 24 18:00:33 2002 From: israel@lith.com (Israel Evans) Date: Fri, 24 May 2002 10:00:33 -0700 Subject: [Tutor] Difficulty with file.writelines() Message-ID: This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C20344.871F0590 Content-Type: text/plain Hello everyone.. I'm attempting to see if a file has a particular group of lines, and move them to the end. If the file doesn't have this group, I'd like to add a basic version of that group to the end anyways. The problem I'm having is when the file doesn't have the group of lines I'm looking for. It seems that my file.writelines() down at the end of the function in the last else: block is overwriting the whole file with the little group. What Am I missing? ###--------------------------### import re, os, os.path def move_empty(fxf_filename, fxdir=r'C:\Dev\Tron\BUILD\Game\ClientFX'): fxfilepath = os.path.join(fxdir, fxf_filename) fxfile = open(fxfilepath, 'r') fxfile.seek(0) empty = re.compile("GroupName:.*_empty") matchlist = [] matchcount = 0 tempfile = open(os.path.join(fxdir, 'temp.fxf'), 'w') for line in fxfile.readlines(): if empty.search(line): matchlist.append(line) print matchlist matchcount = 2 elif matchcount > 0: matchlist.append(line) matchcount = matchcount - 1 print matchlist, matchcount else: tempfile.writelines(line) if matchlist != []: for line in matchlist: tempfile.writelines(line) print line else: # figure out why this is erasing everything else and writing # only the empty_group. filename = fxf_filename.split('.') name = filename[0].upper() empty_group = '''\tGroupName: %s_empty\n\tFxInGroup: 0\n\tPhase: 10000\n'''%(name) tempfile.writelines(empty_group) tempfile.close() ###-------------------------------------### Thanks for any help... ~Israel~ ------_=_NextPart_001_01C20344.871F0590 Content-Type: text/html Content-Transfer-Encoding: quoted-printable

 

Hello everyone..   I'm attempting to see if = a file has a particular group of lines, and move them to the end.  If the file doesn't have this group, I'd like to add a basic version of that group to the end anyways.  The problem I'm having is when the file doesn't have the group of lines I'm looking for.  It seems that my = file.writelines() down at the end of the function in the last else: block is overwriting = the whole file with the little group.  What Am I = missing?

 

###--------------------------###

import= re, os, os.path

 

def move_empty(fxf_filename, fxdir=3Dr'C:\Dev\Tron\BUILD\Game\ClientFX'):

       &nbs= p;    fxfilepath =3D os.path.join(fxdir, fxf_filename)

       &nbs= p;    fxfile =3D open(fxfilepath, 'r')

       &nbs= p;    fxfile.seek(0)

       &nbs= p;    empty =3D re.compile("GroupName:.*_empty")=

       &nbs= p;    matchlist =3D = []

       &nbs= p;    matchcount =3D = 0

       &nbs= p;    tempfile =3D = open(os.path.join(fxdir, = 'temp.fxf'), 'w')

       &nbs= p;    for line in fxfile.readlines():

       &nbs= p;           &nbs= p;    if empty.search(line):

       &nbs= p;           &nbs= p;           &nbs= p;    matchlist.append(line)

       &nbs= p;           &nbs= p;           &nbs= p;    print matchlist

       &nbs= p;           &nbs= p;           &nbs= p;    matchcount =3D = 2

       &nbs= p;           &nbs= p;    elif matchcount > 0:

       &nbs= p;           &nbs= p;           &nbs= p;    matchlist.append(line)

       &nbs= p;           &nbs= p;           &nbs= p;    matchcount =3D matchcount - 1

       &nbs= p;           &nbs= p;           &nbs= p;    print matchlist, matchcount

       &nbs= p;           &nbs= p;    else: tempfile.writelines(line)=

       &nbs= p;    if matchlist !=3D = []:

       &nbs= p;           &nbs= p;    for line in matchlist:

       &nbs= p;           &nbs= p;           &nbs= p;    tempfile.writelines(line)

       &nbs= p;           &nbs= p;           &nbs= p;    print line

       &nbs= p;    else:   = # figure out why this is erasing everything else and = writing

       &nb= sp;        # only the empty_group.       &nb= sp; 

       &nbs= p;           &nbs= p;    filename =3D fxf_filename.split('.')

       &nbs= p;           &nbs= p;    name =3D = filename[0].upper()

       &nbs= p;           &nbs= p;    empty_group =3D '''\tGroupName: %s_empty\n\tFxInGroup: 0\n\tPhase: = 10000\n'''%(name)

       &nbs= p;           &nbs= p;    tempfile.writelines(empty_group)

       &nbs= p;    tempfile.close()

 

###-------------------------------------###

 

Thanks for any help...

 

 

~Israel<= font size=3D2 face=3D"Courier New">~

 

------_=_NextPart_001_01C20344.871F0590-- From jeff@ccvcorp.com Fri May 24 18:04:18 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 24 May 2002 10:04:18 -0700 Subject: [Tutor] Classses Message-ID: <3CEE7292.46F49426@ccvcorp.com> Oops, my mailer mangled the quoting on that. Here's the properly formatted version... -------- Original Message -------- Subject: Re: [Tutor] Classses Date: Fri, 24 May 2002 09:56:48 -0700 From: Jeff Shannon To: Tutor@python.org Richard Gelling wrote: > class Address: > def _init_(self,Hs,Town,Zip) > self.Hs_Number=Hs > self.Street=St > self.Town=Town > self.Zip_Code=Zip > > Which appears to work fine,however when type in the second part ie > > addr=Address(7,"High St.","Anytown","12345") > [...] Others have already pointed out your problem with _init_ versus __init__, but I wanted to mention that you've got another bug lurking here. In your constructor, you have the line "self.Street = St" ... but you don't have St in your argument list! So, when you fix your underscores and run this again, you'll still get an error, saying that the constructor takes exactly four arguments (five given). Jeff Shannon Technician/Programmer Credit International From bryce@bembry.org Fri May 24 18:50:04 2002 From: bryce@bembry.org (Bryce Embry) Date: Fri, 24 May 2002 12:50:04 -0500 Subject: [Tutor] Difficulty with file.writelines() In-Reply-To: Message-ID: <5.1.0.14.0.20020524123056.02e78a80@www.bembry.org> --=====================_363902874==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed Howdy, It looks like your problem stems from the difference in opening a file in "write" mode and opening a file in "append" mode. By default, write mode will automatically overwrite any text currently in the file whenever you write to the file. This works fine in your code when the desired text is already there, since it just writes the text in again. But when the text is not already there, you do not have the program write all the text again. It just overwrites everything currently in the file with the text you desired. You could fix this by using "append" mode when you open the file, so that the line read: tempfile = open(os.path.join(fxdir, 'temp.fxf'), 'a') (changed the "w" for an "a"). Or you could just change the code so it writes the whole text in when the matchlist is empty. Here's one way to that might work. I haven't tested it, but maybe it will help: --- import re, os, os.path def move_empty(fxf_filename, fxdir=r'C:\Dev\Tron\BUILD\Game\ClientFX'): fxfilepath = os.path.join(fxdir, fxf_filename) fxfile = open(fxfilepath, 'r') fxfile.seek(0) empty = re.compile("GroupName:.*_empty") matchlist = [] matchcount = 0 tempfile = open(os.path.join(fxdir, 'temp.fxf'), 'w') fxfile_text = fxfile.readlines() for line in fxfile_text: if empty.search(line): matchlist.append(line) print matchlist matchcount = 2 elif matchcount > 0: matchlist.append(line) matchcount = matchcount - 1 print matchlist, matchcount else: tempfile.writelines(line) if matchlist != []: for line in matchlist: tempfile.writelines(line) print line else: # figure out why this is erasing everything else and writing # only the empty_group. filename = fxf_filename.split('.') name = filename[0].upper() empty_group = fxfile_text empty_group_addition = '''\tGroupName: %s_empty\n\tFxInGroup: 0\n\tPhase: 10000\n'''%(name) empty_group.append(empty_group_addition) tempfile.writelines(empty_group) tempfile.close() Hope that helps, Bryce At 12:00 PM 5/24/2002, you wrote: > > >Hello everyone.. I'm attempting to see if a file has a particular group >of lines, and move them to the end. If the file doesn't have this group, >I'd like to add a basic version of that group to the end anyways. The >problem I'm having is when the file doesn't have the group of lines I'm >looking for. It seems that my file.writelines() down at the end of the >function in the last else: block is overwriting the whole file with the >little group. What Am I missing? > > > >###--------------------------### > >import re, os, os.path > > > >def move_empty(fxf_filename, fxdir=r'C:\Dev\Tron\BUILD\Game\ClientFX'): > > fxfilepath = os.path.join(fxdir, fxf_filename) > > fxfile = open(fxfilepath, 'r') > > fxfile.seek(0) > > empty = re.compile("GroupName:.*_empty") > > matchlist = [] > > matchcount = 0 > > tempfile = open(os.path.join(fxdir, 'temp.fxf'), 'w') > > for line in fxfile.readlines(): > > if empty.search(line): > > matchlist.append(line) > > print matchlist > > matchcount = 2 > > elif matchcount > 0: > > matchlist.append(line) > > matchcount = matchcount - 1 > > print matchlist, matchcount > > else: tempfile.writelines(line) > > if matchlist != []: > > for line in matchlist: > > tempfile.writelines(line) > > print line > > else: # figure out why this is erasing everything else and > writing > > # only the empty_group. > > filename = fxf_filename.split('.') > > name = filename[0].upper() > > empty_group = '''\tGroupName: > %s_empty\n\tFxInGroup: 0\n\tPhase: 10000\n'''%(name) > > tempfile.writelines(empty_group) > > tempfile.close() > > > >###-------------------------------------### > > > >Thanks for any help... > > > > > >~Israel~ > > Bryce Embry Geek-Of-All-Trades / Master-Of-None www.bembry.org -------------------------------------------------------------------------------------------------------------------------------------------------------- Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 38117 ^ (901)682-2409 -------------------------------------------------------------------------------------------------------------------------------------------------------- --=====================_363902874==_.ALT Content-Type: text/html; charset="us-ascii" Howdy,

It looks like your problem stems from the difference in opening a file in "write" mode and opening a file in "append" mode.  By default, write mode will automatically overwrite any text currently in the file whenever you write to the file.  This works fine in your code when the desired text is already there, since it just writes the text in again.  But when the text is not already there, you do not have the program write all the text again.  It just overwrites everything currently in the file with the text you desired.

You could fix this by using "append" mode when you open the file, so that the line read:
        tempfile = open(os.path.join(fxdir, 'temp.fxf'), 'a')
(changed the "w" for an "a").  Or you could just change the code so it writes the whole text in when the matchlist is empty. 

Here's one way to that might work.  I haven't tested it, but maybe it will help:

---
<revised code>

import re, os, os.path

 

def move_empty(fxf_filename, fxdir=r'C:\Dev\Tron\BUILD\Game\ClientFX'):

            fxfilepath = os.path.join(fxdir, fxf_filename)

            fxfile = open(fxfilepath, 'r')

            fxfile.seek(0)

            empty = re.compile("GroupName:.*_empty")

            matchlist = []

            matchcount = 0

            tempfile = open(os.path.join(fxdir, 'temp.fxf'), 'w')

            fxfile_text = fxfile.readlines()

            for line in fxfile_text:

                        if empty.search(line):

                                    matchlist.append(line)

                                    print matchlist

                                    matchcount = 2

                        elif matchcount > 0:

                                    matchlist.append(line)

                                    matchcount = matchcount - 1

                                    print matchlist, matchcount

                        else: tempfile.writelines(line)

            if matchlist != []:

                        for line in matchlist:

                                    tempfile.writelines(line)

                                    print line

            else:   # figure out why this is erasing everything else and writing

                # only the empty_group.
                      
                        filename = fxf_filename.split('.')

                        name = filename[0].upper()

                        empty_group = fxfile_text

                        empty_group_addition = '''\tGroupName: %s_empty\n\tFxInGroup: 0\n\tPhase: 10000\n'''%(name)

                        empty_group.append(empty_group_addition)

                        tempfile.writelines(empty_group)

            tempfile.close()
</revised code>


Hope that helps,
Bryce

At 12:00 PM 5/24/2002, you wrote:

 

Hello everyone..   I'm attempting to see if a file has a particular group of lines, and move them to the end.  If the file doesn't have this group, I'd like to add a basic version of that group to the end anyways.  The problem I'm having is when the file doesn't have the group of lines I'm looking for.  It seems that my file.writelines() down at the end of the function in the last else: block is overwriting the whole file with the little group.  What Am I missing?

 

###--------------------------###

import re, os, os.path

 

def move_empty(fxf_filename, fxdir=r'C:\Dev\Tron\BUILD\Game\ClientFX'):

            fxfilepath = os.path.join(fxdir, fxf_filename)

            fxfile = open(fxfilepath, 'r')

            fxfile.seek(0)

            empty = re.compile("GroupName:.*_empty")

            matchlist = []

            matchcount = 0

            tempfile = open(os.path.join(fxdir, 'temp.fxf'), 'w')

            for line in fxfile.readlines():

                        if empty.search(line):

                                    matchlist.append(line)

                                    print matchlist

                                    matchcount = 2

                        elif matchcount > 0:

                                    matchlist.append(line)

                                    matchcount = matchcount - 1

                                    print matchlist, matchcount

                        else: tempfile.writelines(line)

            if matchlist != []:

                        for line in matchlist:

                                    tempfile.writelines(line)

                                    print line

            else:   # figure out why this is erasing everything else and writing

                # only the empty_group.         

                        filename = fxf_filename.split('.')

                        name = filename[0].upper()

                        empty_group = '''\tGroupName: %s_empty\n\tFxInGroup: 0\n\tPhase: 10000\n'''%(name)

                        tempfile.writelines(empty_group)

            tempfile.close()

 

###-------------------------------------###

 

Thanks for any help...

 

 

~Israel~

 


Bryce Embry
Geek-Of-All-Trades / Master-Of-None

www.bembry.org
--------------------------------------------------------------------------------------------------------------------------------------------------------
Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 38117 ^ (901)682-2409
--------------------------------------------------------------------------------------------------------------------------------------------------------
--=====================_363902874==_.ALT-- From rob@uselesspython.com Fri May 24 19:40:22 2002 From: rob@uselesspython.com (Rob Andrews) Date: Fri, 24 May 2002 13:40:22 -0500 Subject: [Tutor] OT-ish: [Fwd: Answer to challenge: CPAN Script shroud re-written in python :-)] Message-ID: <3CEE8916.7090101@uselesspython.com> This is one of the most amusing contributions anyone has made to Useless Python to date, and I feel wickedly compelled to pass it on for those who get the joke. And for the author's punishment and reward, I'll publish it on Useless pretty much as is (with maybe a *just kidding* in a comment or something). Rob -------- Original Message -------- Subject: Answer to challenge: CPAN Script shroud re-written in python :-) Date: Fri, 24 May 2002 19:19:54 +0100 From: "Donald McCarthy" To: I read your challenge from http://uselesspython.com/pythonchallenge.html: Visit the archive of scripts on CPAN (not the modules, unless you really aim to impress us) and re-write some of them in Python. And found the CPAN script shroud: 'shroud' is a script that will transform perl code into virtually unreadable text, while retaining the full functionality of that code. It is used to shroud the source code of commercial perl programs. More information is available from the POD documentation within the script and from this URL: http://www.craic.com/resources/tech_notes/tech_note_2.html (http://www.cpan.org/authors/id/C/CR/CRAIC/shroud-1.0) From the Description I wrote this: Shroud.py import sys sys.stdin.write(sys.stdin.read()) Should do the job :-) Paddy McCarthy. From dman@dman.ddts.net Fri May 24 20:11:42 2002 From: dman@dman.ddts.net (dman) Date: Fri, 24 May 2002 14:11:42 -0500 Subject: [Tutor] Dynamic creation of class instances... In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F5@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C5F5@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020524191142.GA24474@dman.ddts.net> --yrj/dFKFPuw6o+aM Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 22, 2002 at 02:02:00PM +0100, alan.gauld@bt.com wrote: | > Right now I start out with a list of names, craft a string that=20 | > looks like a class instantiation and then exec the sucker. =20 |=20 | Paul has already answered this based on a dictionary solution. |=20 | But this is an issue for everyone on the list. |=20 | Why does this same question come up every month on this list? | It has to be one of the top FAQs for this mailing list. I was noticing the same thing. | It suggests to me that something in the standard tutorials/texts=20 | must be suggesting this solution to people. Its such a bizarre | solution that it never seems to come up in any of the other=20 | fora that I engage with(Delphi, C++, Smalltalk, Java(spit!) ). |=20 | But on Python it seems like most newbies sooner or later come=20 | up with this amazing idea for naming objects using exec. |=20 | So Why? Comments welcomed from newbies who've been there, or=20 | from newbies whpo nearly went there or from exorerienced hackers=20 | who might know why it comes up so often? My hypothesis is that the people asking these questions haven't used C, C++, Java, Delphi or Smalltalk. I don't know Delphi or Smalltalk, but in C/C++/Java (and Eiffel and Lisp) you can't create variables at runtime. In those environments, data structures and containers are introduced fairly early on. I think that as newbies work through python they come across 'exec' before they understand containers and how to use them. They fail to observe that the local namespace is just another container, though it is special in the way objects are inserted into and extracted from it. =20 | I am seriously puzzled and if I can do anything in my tutor to | circumvent it(short of discussing it explicitly!) I will. Go ahead and discuss it explicitly. Also be sure and give a thorough introduction to containers and when/where/why/how to use them. (I'm saying this in general, I don't know how well or how poorly your book does this already) -D --=20 He who finds a wife finds what is good and receives favor from the Lord. Proverbs 18:22 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --yrj/dFKFPuw6o+aM Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzukG4ACgkQO8l8XBKTpRRDsgCeKDeEc7vnxsKiyuryhzYLrVK7 D+MAoI0z6o59CfSY1oP44CXf+e+bu3Gi =5s7c -----END PGP SIGNATURE----- --yrj/dFKFPuw6o+aM-- From bryce@bembry.org Fri May 24 20:55:34 2002 From: bryce@bembry.org (Bryce Embry) Date: Fri, 24 May 2002 14:55:34 -0500 Subject: [Tutor] Dynamic creation of class instances... Message-ID: <5.1.0.14.0.20020524145502.02e94830@www.bembry.org> Howdy, I'm one of the folks who asked a question along the lines of dynamic class creation. Coming from a very limited programming background I don't have a strong grasp of OOP, and I haven't had to do any work in a language where all variables must be declared before use (ala C++). I asked the question largely because of my understanding (or misunderstanding) of classes and OOP. I think this misconception comes from the examples of classes given in a lot of texts. The examples given in most of the introductory texts are fairly shallow and leave the impression to newbies like me that a class is something you define generically so that you can create specific instances of it at runtime. So, I define a generic "snake" class, and then the user can specify more details about his snake named "Slytherin" and we'll save that as a new instance of the class at runtime. Or I define a generic bank account class, and each user will create his own instance of the bank account at runtime. This was my concept for a while, and I'm only now starting to move beyond it. Newbie programmers have heard a lot about OOP and are anxious to be "in the know" and use it. Introductory texts cover classes, but their examples are necessarily short, often very artificial, and thereby give a wrong impression. As I learn more about classes it seems that the programs / scripts that I have been writing are just too simplistic to really use classes. I can see that they would be very useful in a larger project, but for my dinky 100-line codes, it just seems that classes are not quite as practical. I realize there may be some dinky codes that could benefit from OOP and classes, but I guess I just haven't gotten there quite yet. I think OOP was one of my first hang-ups with a lot of the Tkinter tutorials, too. Most of the tutorials made their GUI programs using classes, but only had one instance of the class. I don't understand how that's an improvement. I understand how a Label() is a subclass of a Widget(), but I don't understand why I have to create a class just to make a GUI. I guess that's why I wrote my own tutorial without using classes for Tkinter. I guess my suggestion, then, is to work on the introductions to OOP and classes. I read quite a few of them when I was trying to figure out classes (Alan Gauld's, Lutz and Ascher's, Deitel's, DevShed's, and a few others) and I still didn't quite get it. I really wanted to get it, though, so I could be a cool programmer and use OOP. I've started working through some of the recommended reading posted a couple months ago, though, and I realize that I can be a cool programmer even if I just use functional programming most of the time. I like that. I grok functional programming. Also, contrary to what a number of folks have suggested, I was not led to the dark side via the exec() function. This function is not really covered in beginning tutorials and I had not heard about it until folks on this list mentioned it. I doubt that it is the primary culprit leading folks down the slippery slope of dynamic class creation. I would tend to blame the examples of OOP in texts. Well, those are my thoughts. Hopefully they're worth the paper their printed on. Bryce Embry Bryce Embry Geek-Of-All-Trades / Master-Of-None www.bembry.org -------------------------------------------------------------------------------------------------------------------------------------------------------- Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 38117 ^ (901)682-2409 -------------------------------------------------------------------------------------------------------------------------------------------------------- From dman@dman.ddts.net Fri May 24 22:47:27 2002 From: dman@dman.ddts.net (dman) Date: Fri, 24 May 2002 16:47:27 -0500 Subject: FW: Re: [Tutor] Dynamic creation of class instances... Message-ID: <20020524214727.GA25573@dman.ddts.net> --UugvWAfsgieZRqgk Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable This was sent off-list, but looks like it should be on-list :-). ----- Forwarded message from Bryce Embry ----- | From: Bryce Embry | To: dman | Subject: Re: [Tutor] Dynamic creation of class instances... | Date: Fri, 24 May 2002 14:39:37 -0500 |=20 | Howdy, | I'm one of the folks who asked a question along the lines of dynamic clas= s=20 | creation. Coming from a very limited programming background I don't have= a=20 | strong grasp of OOP, and I haven't had to do any work in a language where= =20 | all variables must be declared before use (ala C++). I asked the questio= n=20 | largely because of my understanding (or misunderstanding) of classes and= =20 | OOP. |=20 | I think this misconception comes from the examples of classes given in a= =20 | lot of texts. The examples given in most of the introductory texts are= =20 | fairly shallow and leave the impression to newbies like me that a class i= s=20 | something you define generically so that you can create specific instance= s=20 | of it at runtime. So, I define a generic "snake" class, and then the us= er=20 | can specify more details about his snake named "Slytherin" and we'll save= =20 | that as a new instance of the class at runtime. Or I define a generic ban= k=20 | account class, and each user will create his own instance of the bank=20 | account at runtime. This was my concept for a while, and I'm only now=20 | starting to move beyond it. Newbie programmers have heard a lot about OOP= =20 | and are anxious to be "in the know" and use it. Introductory texts cover= =20 | classes, but their examples are necessarily short, often very artificial,= =20 | and thereby give a wrong impression. |=20 | As I learn more about classes it seems that the programs / scripts that I= =20 | have been writing are just too simplistic to really use classes. I can s= ee=20 | that they would be very useful in a larger project, but for my dinky=20 | 100-line codes, it just seems that classes are not quite as practical. I= =20 | realize there may be some dinky codes that could benefit from OOP and=20 | classes, but I guess I just haven't gotten there quite yet. |=20 | I think OOP was one of my first hang-ups with a lot of the Tkinter=20 | tutorials, too. Most of the tutorials made their GUI programs using=20 | classes, but only had one instance of the class. I don't understand how= =20 | that's an improvement. I understand how a Label() is a subclass of a=20 | Widget(), but I don't understand why I have to create a class just to mak= e=20 | a GUI. I guess that's why I wrote my own tutorial without using classes= =20 | for Tkinter. |=20 | I guess my suggestion, then, is to work on the introductions to OOP and= =20 | classes. I read quite a few of them when I was trying to figure out=20 | classes (Alan Gauld's, Lutz and Ascher's, Deitel's, DevShed's, and a few= =20 | others) and I still didn't quite get it. I really wanted to get it,=20 | though, so I could be a cool programmer and use OOP. I've started workin= g=20 | through some of the recommended reading posted a couple months ago, thoug= h,=20 | and I realize that I can be a cool programmer even if I just use function= al=20 | programming most of the time. I like that. I grok functional programmin= g. |=20 | Also, contrary to what a number of folks have suggested, I was not led to= =20 | the dark side via the exec() function. This function is not really cover= ed=20 | in beginning tutorials and I had not heard about it until folks on this= =20 | list mentioned it. I doubt that it is the primary culprit leading folks= =20 | down the slippery slope of dynamic class creation. I would tend to blam= e=20 | the examples of OOP in texts. |=20 | Well, those are my thoughts. Hopefully they're worth the paper their=20 | printed on. |=20 | Bryce Embry |=20 |=20 | "Lord, you establish peace for us. | All that we have accomplished | you have done for us" -- Isaiah 26:12 ----- End forwarded message ----- --=20 Pleasant words are a honeycomb, sweet to the soul and healing to the bones. Proverbs 16:24 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --UugvWAfsgieZRqgk Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzutO8ACgkQO8l8XBKTpRQhOQCfQfI0KSL2IV53w5Tg9HbuUODf L3YAoLuihUD0d/K7nVUIiFN3f6JsethQ =dWmj -----END PGP SIGNATURE----- --UugvWAfsgieZRqgk-- From dominic.fox" Message-ID: <000b01c2036f$29cab980$8bd5ff3e@tinypc> Hi all, After some playing around, I came up with the following as a way of doing matrix multiplications using the list comprehension syntax. def MatrixMultiply(first, second): def sum(list): def add(x, y): return x + y return reduce(add, list) def allRows(matrix): return range(len(matrix)) def allCols(matrix): return range(len(matrix[0])) return ([[sum([first[sourcerow][sourcecol] * second[sourcecol][targetcol] for sourcecol in allCols(first)]) for targetcol in allCols(second)] for sourcerow in allRows(first)]) It assumes that a matrix is defined as a list of lists with each embedded list representing a row, and each item in each embedded list representing a cell: e.g. [[1, 0], [0, 1]] for an identity matrix. It seems to work fine, but it's a bit of a horror - syntactically convoluted and not terribly readable. Does anyone know of a cleaner and nicer way of saying the same thing? Dominic --> Nobody knows the trouble you've seen / walking from your desk to the staff canteen <-- homepage: http://www.geocities.com/domfox From shalehperry@attbi.com Fri May 24 23:12:08 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri, 24 May 2002 15:12:08 -0700 (PDT) Subject: [Tutor] List comprehensions & matrix multiplication In-Reply-To: <000b01c2036f$29cab980$8bd5ff3e@tinypc> Message-ID: > > def MatrixMultiply(first, second): > def sum(list): > def add(x, y): return x + y > return reduce(add, list) import operator return reduce(operator.add, list) From pythontutor@venix.com Fri May 24 23:31:27 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Fri, 24 May 2002 18:31:27 -0400 Subject: [Tutor] Dynamic creation of class instances... References: <20020521222945.GA1339@ak.silmarill.org> Message-ID: <3CEEBF3F.2090607@venix.com> Since this topic is still continuing, I'll toss in my two cents. The more conventional languages require that variables get declared before they are used. People have no chance to create names on the fly. The other extreme includes scripting languages with "macro" abilities where variables can hold the names of other variables (${$name}). Python allows the creation of variable names, but you can't save a new name in another variable - macro style. You have to save it in a container: a class, dictionary, or list. I think a beginner can reach a stage where they are ready to create variables dynamically, but haven't gotten comfortable with the containers. They grope for some non-container to hold the newly created variable name so that they can just start using it. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo@hkn.eecs.berkeley.edu Sat May 25 03:02:50 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 24 May 2002 19:02:50 -0700 (PDT) Subject: [Tutor] List comprehensions & matrix multiplication In-Reply-To: <000b01c2036f$29cab980$8bd5ff3e@tinypc> Message-ID: On Fri, 24 May 2002, dominic.fox wrote: > After some playing around, I came up with the following as a way of > doing matrix multiplications using the list comprehension syntax. > > def MatrixMultiply(first, second): > def sum(list): > def add(x, y): return x + y > return reduce(add, list) This sum() function is useful enough that it might be good to pull it out as an independent function. I think doing nested list comprehensions might be overdoing things. It's a little hard for me to disentangle them mentally. For variety, here's another version of matrix multiplication that enlists the use of list comprehensions. Dunno if it's "easier" to understand, since it's a different approach: *** Spoiler space ahead *** ### >>> def columnSlice(matrix, i): ... return [row[i] for row in matrix] ... >>> def rowSlice(matrix, i): ... return matrix[i] ... >>> def dot(vector1, vector2): ... return sum([a * b for (a,b) in zip(vector1, vector2)]) ... >>> def MatrixMultiply(first, second): ... result = [[0 for j in allCols(second)] for i in allRows(first)] ... for i in allRows(first): ... for j in allCols(second): ... result[i][j] = dot(rowSlice(first, i), ... columnSlice(second, j)) ... return result ... ... >>> MatrixMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]) [[19, 22], [43, 50]] >>> MatrixMultiply([[1, 2], [3, 4], [5, 6]], [[7], [8]]) [[23], [53], [83]] ### Hope this helps! From mpeters@mac.com Sat May 25 05:30:05 2002 From: mpeters@mac.com (Michael A. Peters) Date: Fri, 24 May 2002 21:30:05 -0700 Subject: [Tutor] buck newbie Message-ID: <20020524213005.1dbf0223.mpeters@mac.com> Howdie all- I'll be coding my first python script. It's to perform a simple function, but I'd be eager to look at any code that does a similar thing. Basically, upon launch it is to attempt to download a txt file off the net. If fail, it should retry every 10 minutes for 5 hors 50 minutes. I assume an idle or sleep statement can accomplish that- basically, until success or time = blah do Anyway- the meet of the app is that (assuming it gets the text file) it needs to read each line of the text file and extract the reletaive info (it's tab deliminated to something equivalent to the unix command cut will suffice) and then feed the info into a MySQL database. there are two fields- a username and a team number. They are not unique in the database, but there is only one username associated with each team. So when it has the username and team, it needs to find the unique identifier associated with that unique pairing. If the unique pairing does not exist, it needs to add a row to the database and then return the unique identifier (auto increment) that is now associated with the pair. Then with that unique key- insert the data into the database. ANYWAY- I would love some pointers to some code demonstrating how to use MySQL with Python. I have Python 2.2.1 and the MySQL-python-0.9.2b2 package installed. I also have a couple good books on Python- but they don't cover database connectivity. Thanks for any help! From stuart@sharedreality.org Sat May 25 06:02:25 2002 From: stuart@sharedreality.org (Stuart Smith) Date: Sat, 25 May 2002 06:02:25 +0100 Subject: [Tutor] List comprehensions & matrix multiplication In-Reply-To: <000b01c2036f$29cab980$8bd5ff3e@tinypc> References: <20020521134109.1109.41894.Mailman@mail.python.org> Message-ID: <5.1.0.14.2.20020525055101.00a9a750@sharedreality.org> For matrix multiplication and a whole lot more, I'd use the Numeric module, http://sourceforge.net/projects/numpy this provides a matrixmultiply(a,b) method so you can replace your code with just: import Numeric At 23:05 24/05/2002 +0100, you wrote: >Hi all, > >After some playing around, I came up with the following as a way of doing >matrix multiplications using the list comprehension syntax. > >def MatrixMultiply(first, second): > def sum(list): > def add(x, y): return x + y > return reduce(add, list) > def allRows(matrix): return range(len(matrix)) > def allCols(matrix): return range(len(matrix[0])) > return ([[sum([first[sourcerow][sourcecol] * >second[sourcecol][targetcol] > for sourcecol in allCols(first)]) > for targetcol in allCols(second)] > for sourcerow in allRows(first)]) > >It assumes that a matrix is defined as a list of lists with each embedded >list representing a row, and each item in each embedded list representing a >cell: e.g. [[1, 0], [0, 1]] for an identity matrix. It seems to work fine, >but it's a bit of a horror - syntactically convoluted and not terribly >readable. Does anyone know of a cleaner and nicer way of saying the same >thing? From urnerk@qwest.net Sat May 25 09:03:39 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 25 May 2002 01:03:39 -0700 Subject: [Tutor] List comprehensions & matrix multiplication In-Reply-To: <000b01c2036f$29cab980$8bd5ff3e@tinypc> References: <20020521134109.1109.41894.Mailman@mail.python.org> Message-ID: <4.2.0.58.20020525004939.01c2eac0@pop3.norton.antivirus> > >It assumes that a matrix is defined as a list of lists with >each embedded list representing a row, and each item in each >embedded list representing a cell: e.g. [[1, 0], [0, 1]] for >an identity matrix. It seems to work fine, but it's a bit of >a horror - syntactically convoluted and not terribly readable. >Does anyone know of a cleaner and nicer way of saying the same >thing? > >Dominic You might want to define a Matrix class with multiplication one of the methods. Then have m.row(i) and m.column(i) methods as well, which your multiplication method can take advantage of. Here's my method, which might be improve with more list comprehensions. def __mul__(self,other): """ Return self * other matrix (Cayley multiplication) or elements of self * a constant """ if isinstance(other,Matrix) or isinstance(other,Sqmatrix): newdata=[] for i in range(self.n): newdata.append([0]*other.m) for j in range(other.m): newdata[i][j] = reduce(add, map(mul,self.row(i),other.column(j))) else: newdata = [] for row in self.rows: newdata.append([x*other for x in row]) In action: >>> from mathobjects import * >>> n = Sqmatrix([[1,2],[3,-1]]) >>> n**3 # times itself 3 times [7, 14] [21, -7] >>> n [1, 2] [3, -1] >>> n.inverse() [0.14285714285714285, 0.2857142857142857] [0.42857142857142855, -0.14285714285714285] >>> n*n.inverse() [1.0, 0.0] [0.0, 1.0] Also does simple scaler multiplication: >>> n*3 [3, 6] [9, -3] Kirby From magnusk2@telia.com Sat May 25 13:17:43 2002 From: magnusk2@telia.com (Magnus Käck) Date: Sat, 25 May 2002 14:17:43 +0200 Subject: [Tutor] MVC Python Gnome Message-ID: <20020525141743.4d6b5223.magnusk2@telia.com> Hi all, I would like to develop programs with MVC design pattern, Python and Gnome. Anybody with links to good examples and documentation? Magnus From dominic.fox" Message-ID: <002901c203f7$13baa640$8bd5ff3e@tinypc> Danny Yoo wrote: > I think doing nested list comprehensions might be overdoing things. It's > a little hard for me to disentangle them mentally. Yes, that's my feeling about it too - it's too syntactically compressed. Nested list comprehensions make a certain amount of sense to me, as a one-time dabbler in emacs Lisp, but repeatedly nesting them leads to a whole load of operations being bundled together into a single heavily-bracketed expression, which is not often a good idea. I was looking for a way to unbundle them, much like what you supplied a little further down in your post. I'll keep trying and see if I can come up with something still more elegant! Kirby Urner suggested building a matrix class with its own "multiply" method, which would also enable some operator overloading. That was where I was going next... thanks, Dominic From urnerk@qwest.net Sat May 25 19:09:54 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 25 May 2002 11:09:54 -0700 Subject: [Tutor] Re: New Kind of Science (Wolfram) In-Reply-To: <4.2.0.58.20020522121931.01bb43c0@pop3.norton.antivirus> References: <20020522110320.GA7559@st-annes.oxford.ac.uk> Message-ID: <4.2.0.58.20020525102920.01c58470@pop3.norton.antivirus> I recently got my copy of Stephan Wolfram's new book, 'A New Kind of Science' (2002) which focuses on complexity using computer expriments with cellular automata, ala the Game of Life (but the rules are often even simpler). The early part of the book focuses on grids populated according to simple rules, starting from a top row with just one black cell (the rest white) and working downward. Cells are considered in groups of 3, with the cell directly below the middle one turning white or black based on the mapping rule, i.e. based on how a given combination of 3 (white or black = 8 possibilities) gives a next generation cell in the next row. For example, rule 30 looks like this: >>> import nks >>> p = nks.Pattern(30) >>> p.sayrule() 111 --> 0 110 --> 0 101 --> 0 100 --> 1 011 --> 1 010 --> 1 001 --> 1 000 --> 0 The combinations on the left are fixed (always the same 8 in that order) whereas the string of 0s and 1s defines a unique binary number from 0 to 255. If I fill with 0s to 8 positions, and ask for 30 in binary, I get: >>> nks.base2(30,8) '00011110' ...which is the same rule as above. So if in the top row you had 20 whites plus a middle black: >>> p = nks.Pattern(30,width=20) >>> p.gen '000000000010000000000' Then successive rows would be: >>> p.next() '000000000111000000000' and: >>> p.next() '000000001100100000000' Complexity comes in with some rules (including 30) in a dramatic fashion, whereas other rules give terminal, static results, or an expanding fractal of nested, self-similar patterns (which we might consider complex, yet here the term is reserved for more unpredictable, more apparently random patterns). The beginning of the generation process of rule 30 is depicted here: http://www.inetarena.com/~pdx4d/ocn/graphics/nks30a.png and after a few more rows: http://www.inetarena.com/~pdx4d/ocn/graphics/nks30b.png and finally (to a lot more rows): http://www.inetarena.com/~pdx4d/ocn/graphics/nks30c.png This last picture is the default output of: >>> import nks >>> p = nks.Pattern(30) >>> p.run() (I have the user then manually opening Povray to render nks30.pov -- an automated render invoked from within Python would be another option (but I like to tweak settings and re-render, so manual is better)). It turns out the Wolfram has been exploiting the randomness in this pattern to serve as a random number generator for Mathematica all this time (pg. 317). So, the pictures above come from using my usual Python + Povray combo. Another approach would be to populate pixels directly using PIL or some similar set of tools. But I wanted quick results through recycling existing code I've already written. Another side effect is we get little spheres in place of the flat squares used in Wolfram's book. That's OK. The patterns are what's important. I basically just use literal strings of 0s and 1s to generate the pictures. I don't keep a whole grid in memory -- each successive row overwrites the one before, so there's only the previous row and the next one to mess with at any given time. The Pattern object accepts any rule from 0 to 255 as input and the run() method creates the Povray file to 388 generations (the default). The first draft of my source code is at: http://www.inetarena.com/~pdx4d/ocn/python/nks.py Note dependencies on povray.py and coords.py -- both posted in the same subdirectory. And of course you need Povray, available from http://www.povray.org/ Kirby From pobrien@orbtech.com Sat May 25 19:19:00 2002 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Sat, 25 May 2002 13:19:00 -0500 Subject: [Tutor] RE: [Edu-sig] Re: New Kind of Science (Wolfram) In-Reply-To: <4.2.0.58.20020525102920.01c58470@pop3.norton.antivirus> Message-ID: [Kirby Urner] > > I recently got my copy of Stephan Wolfram's new book, > 'A New Kind of Science' (2002) which focuses on complexity > using computer expriments with cellular automata, ala > the Game of Life (but the rules are often even simpler). > > [Examples snipped] Cool stuff. This book is on my wish list. How do you like the book overall? And is it relatively easy to translate into Python code, such as the examples you gave? --- Patrick K. O'Brien Orbtech From urnerk@qwest.net Sat May 25 20:06:11 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 25 May 2002 12:06:11 -0700 Subject: [Tutor] RE: [Edu-sig] Re: New Kind of Science (Wolfram) In-Reply-To: References: <4.2.0.58.20020525102920.01c58470@pop3.norton.antivirus> Message-ID: <4.2.0.58.20020525115527.01c69760@pop3.norton.antivirus> > >Cool stuff. This book is on my wish list. How do you like the >book overall? I like that it's written for a broad audience and doesn't assume much specialized knowledge, except maybe in the notes section. It's quite a thick tome -- about 1200 pages not including the index. Lots of illustrations and diagrams (b&w or grayscale). The organization is meticulous, with lots of specific citations to page numbers >And is it relatively easy to translate into Python code, such as the >examples you gave? The examples I gave are the simplest, but are also core/critical. You can get fancier of course, and Python'd be up to the task, although Wolfram is understandably focussed on Mathematica as his implementation system of choice. Kirby From cheshire_cat_sf@yahoo.com Sat May 25 22:41:24 2002 From: cheshire_cat_sf@yahoo.com (Britt Green) Date: Sat, 25 May 2002 14:41:24 -0700 (PDT) Subject: [Tutor] Another CGI question Message-ID: <20020525214124.54124.qmail@web14106.mail.yahoo.com> Thanks to everyone who gave me advice on starting some CGI programming in Python. You've all been very helpful. I did have another question that I've been unable to find the answer to. Suppose my web page has check boxes. A visitor selects multiple check boxes. What does the Python code look like that would return multiple values? So far I've only been able to find examples for things like radiobuttons and text fields. Both of those return a single value. Thanks! Britt ===== "The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman." __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From sheila@thinkspot.net Sat May 25 22:48:33 2002 From: sheila@thinkspot.net (Sheila King) Date: Sat, 25 May 2002 14:48:33 -0700 Subject: [Tutor] Another CGI question In-Reply-To: <20020525214124.54124.qmail@web14106.mail.yahoo.com> Message-ID: On Sat, 25 May 2002 14:41:24 -0700 (PDT), Britt Green wrote: > Thanks to everyone who gave me advice on starting some CGI > programming in Python. You've all been very helpful. > > > I did have another question that I've been unable to find the > answer to. Suppose my web page has check boxes. A visitor selects > multiple check boxes. What does the Python code look like that > would return multiple values? So far I've only been able to find > examples for things like radiobuttons and text fields. Both of > those return a single value. Try this: for field in form.keys(): value = form[field] if type(value) is type([]): valueList = value value ="" for item in valueList: value = value + item.value + '\n' else: value = value.value Good luck, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org From dman@dman.ddts.net Sat May 25 23:50:44 2002 From: dman@dman.ddts.net (dman) Date: Sat, 25 May 2002 17:50:44 -0500 Subject: [Tutor] Another CGI question In-Reply-To: <20020525214124.54124.qmail@web14106.mail.yahoo.com> References: <20020525214124.54124.qmail@web14106.mail.yahoo.com> Message-ID: <20020525225044.GA31959@dman.ddts.net> --BXVAT5kNtrzKuDFl Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, May 25, 2002 at 02:41:24PM -0700, Britt Green wrote: | Thanks to everyone who gave me advice on starting some CGI programming | in Python. You've all been very helpful. |=20 | I did have another question that I've been unable to find the answer | to. Suppose my web page has check boxes. A visitor selects multiple | check boxes. What does the Python code look like that would return | multiple values? So far I've only been able to find examples for things | like radiobuttons and text fields. Both of those return a single value. Checkboxes don't return multiple values. Here's what I mean -- Suppose you have this form :

Box1 Box2
This form has 2 independent elements, one is named "box1" and can either be set or unset, the other is named "box2" and can be set or unset. Unfortunately, when a checkbox is unset it "doesn't exist" (IIRC). Here's how you can check them (untested) : import cgi # here's where the details of parsing the arguments from the client # are taken care of! thus the details are unimportant to you the_form =3D cgi.FieldStorage() if the_form.has_key( "box1" ) : print "Box1 was selected!" else ; print "Box1 was NOT selected!" if the_form.has_key( "box2" ) : print "Box2 was selected!" else ; print "Box2 was NOT selected!" -D --=20 How to shoot yourself in the foot with Java: You find that Microsoft and Sun have released incompatible class libraries both implementing Gun objects. You then find that although there are plenty of feet objects implemented in the past in many other languages, you cannot get access to one. But seeing as Java is so cool, you don't care and go around shooting anything else you can find. (written by Mark Hammond) =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --BXVAT5kNtrzKuDFl Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzwFUQACgkQO8l8XBKTpRR56gCeLawDB6Cdjh+qVjI2FtyUrVMO ElQAoLfkJyoMxIePwRE4wF/kjXFdygm3 =TqGt -----END PGP SIGNATURE----- --BXVAT5kNtrzKuDFl-- From tim@johnsons-web.com Sun May 26 19:10:13 2002 From: tim@johnsons-web.com (Tim Johnson) Date: Sun, 26 May 2002 10:10:13 -0800 Subject: [Tutor] More CGI questions/incremental output Message-ID: <20020526181013.GT23144@johnsons-web.com> Hello All: Python CGI Newbie here. Using python2.1 on RH linux 7.2, target is both linux and Windows 98. I have written a series of CGI scripts in python that will run on both a remote server and on a local machine. The scripts will handle a large number processes that may take some time. And they are meant to report a number of details back to the user and I would prefer that to be incremental. Here's my problem: Content sent back from the CGI script appears all at once, I don't see anything at all until the process finishes. I've done other CGI programming (using Rebol, C,C++, etc) and have observed output incrementally, as I would desire it. What can I do to see an incremental output from my Python script? (I am just using print to write to stdout now) TIA -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From dman@dman.ddts.net Sun May 26 22:00:21 2002 From: dman@dman.ddts.net (dman) Date: Sun, 26 May 2002 16:00:21 -0500 Subject: [Tutor] More CGI questions/incremental output In-Reply-To: <20020526181013.GT23144@johnsons-web.com> References: <20020526181013.GT23144@johnsons-web.com> Message-ID: <20020526210020.GA4331@dman.ddts.net> --+HP7ph2BbKc20aGI Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, May 26, 2002 at 10:10:13AM -0800, Tim Johnson wrote: | Hello All: Python CGI Newbie here. | Using python2.1 on RH linux 7.2, target is both | linux and Windows 98. |=20 | I have written a series of CGI scripts in python that | will run on both a remote server and on a local machine. |=20 | The scripts will handle a large number processes that may | take some time. And they are meant to report a number of | details back to the user and I would prefer that to be | incremental. |=20 | Here's my problem: Content sent back from the CGI script | appears all at once, I don't see anything at all until=20 | the process finishes. Yeah, that's part of how HTTP tends to work. | I've done other CGI programming (using Rebol, C,C++, etc) | and have observed output incrementally, as I would desire it. With the same web browser? What about IO buffering? =20 | What can I do to see an incremental output from my Python | script? (I am just using print to write to stdout now) One possiblity, that also depends on your server's platform, the web server used, the CGI implementation in the web server and the client's browser (IOW not reliable by any means) is to disable python's IO buffering. Run python with '-u' to disable buffering of stdout. The way "progress" is really done with HTTP is to send back a complete response that includes a redirect to your real processor. For an example of how this looks to the user go to orbitz.com and execute a search. The first CGI script sends back that "we are processing the query" page which redirects to the second CGI script that does the actual (long) search and returns the results. The animation is done via a .gif image. HTH, -D --=20 Even youths grow tired and weary, and young men stumble and fall; but those who hope in the Lord=20 will renew their strength. They will soar on wings like eagles; they will run and not grow weary, they will walk and not be faint. Isaiah 40:31 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --+HP7ph2BbKc20aGI Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzxTOQACgkQO8l8XBKTpRREewCfVCRomp9Q9rNGi1boB+ZnFcvw p44AoJ7EAA06qURqogUVtBKe9aeyN8xE =WprG -----END PGP SIGNATURE----- --+HP7ph2BbKc20aGI-- From idiot1@netzero.net Mon May 27 05:27:00 2002 From: idiot1@netzero.net (kirk 'Deliberatus' Bailey) Date: Mon, 27 May 2002 00:27:00 -0400 Subject: [Tutor] archive reader improved(?) Message-ID: <3CF1B594.3DCD930A@netzero.net> I realized that one may care to read the full raw code for the links in footers, and be able to read the address in the headers when it is included in , so I dexided to include some non html in the web page- and still force auto word arap- so I indlluded it as a preloaded text in a text area form with no actions or buttons. This is experimental, but feel free to examine the results- and please, email me with comments and constuctive criticism. -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ From idiot1@netzero.net Mon May 27 05:32:20 2002 From: idiot1@netzero.net (kirk 'Deliberatus' Bailey) Date: Mon, 27 May 2002 00:32:20 -0400 Subject: [Tutor] OOPS Message-ID: <3CF1B6D4.4BDC13D0@netzero.net> sorry about the spelling errors and/or typos, it's kinda late, and I have been repairing the house and running errands all day. -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ From idiot1@netzero.net Mon May 27 05:51:31 2002 From: idiot1@netzero.net (kirk 'Deliberatus' Bailey) Date: Mon, 27 May 2002 00:51:31 -0400 Subject: [Tutor] [Fwd: #074 Hummer] Message-ID: <3CF1BB53.F7642A31@netzero.net> Gents, the lead article is why I am forwarding this yo y'all; this is a sample of government foolishness at it's worst. WE ARE CRIMINALS NOW. -------- Original Message -------- Subject: #074 Hummer Date: Sun, 26 May 2002 23:59:56 EDT From: StuLucas@aol.com To: StuLucas@aol.com #074 [Truth remains funnier than fiction, hence the recent crop of JarryL's (MA) Bonehead Awards (the first with redeeming merit. USians take note/action)] ......................................... Wouldn't it be really stupid if the U.S Patent and Trademark office awarded someone a patent which says that using text and graphics on a commercial website is a new and unique use and that any company that has text and graphics on their website should now pay a licensing fee? And wouldn't it be just as stupid if they awarded a patent to someone which says that using a website to conduct business is a new use and that websites should now start paying licensing fees to do this? I've got bad news for my fellow Americans. Your government IS this stupid. The U.S. Patent and Trademark office has awarded patents 5,576,951 and 6,289,319 to PanIP Corporation giving them these exclusive rights. And PanIP has not wasted any time filing lawsuits against 11 small companies to set a precedent from which to launch other suits. PanIP wants $30,000 from each site, something considered by these sites to be extortion. According to so others do not get burdened. Our hero "DICKSON SUPPLY CO INC" (http://www.dicksonsupply.com ). is one of the unfortunate companies named in the suit, a protracted patent battle would cost them about $1 million so from a business perspective it would be cheaper to pay the $30,000. But PanIP picked the wrong company. Dickson feels they have an obligation to society to bury these patents and will fight PanIP in court. They are trying to pool legal resources with the other 10 named companies in the suit. Are you fed up with this stuff? Spread the word and if you are an American, contact your government representatives. PanIP pulled their website, probably to avoid hearing from enraged people. You can get more information about the lawsuits from http://panipcase.homeip.net ------------------------------------ Bonehead award two, a "too dumb to be a criminal" bonehead award goes to accused carjacker Amandeo Salguero of Albuquerque, NM, who called the victim to ask how to hook up the car's stereo amplifier, according to police who got Salguero's phone number from the caller ID display and found that he lived across the street from the man he stole the car from. (http://shorterlink.com/?KMZF4J ------------------------------------------------- A good thing or is it government going too far? A woman in the UK was jailed for 60 days because of her daughter's excessive truancy even though the woman was unaware that her two daughters, 13 and 15, were not showing up at school. And what says the woman's 25-year-old daughter? "It's a harsh lesson for them to learn," she said. "There must be another way of teaching kids a lesson without locking their mother up. They realize they have done wrong and they are going back to school." And what says the 15 year-old daughter? "It wasn't right my mum has been punished for something I did." (UK Telegraph 14-May-02) ........................................................ Bonehead award four, a "government as good as it gets" bonehead award goes to the Swaziland government which, it has been learned, has been running their international airport for the past 18 months with no control tower, no radar system, no baggage screening, no instruments to record wind velocity and direction and hardly any lights for nighttime landings, so pilots have to land by memory, because the airport was struck by lightening 18 months ago and electricity still hasn't been restored. (http://shorterlink.com/?6IIA7S) ............................................................ The last Bonehead award goes to the National Republican Congressional Committee for naming a Democrat as "Republican of the Year" and then asking the guy to pay the bill for it, in case you wondered about how much they check into the background of those they honor and what they expect in return. The NRCC has no explanation for the mix-up but extended an invitation to California city councilman Tom Palmeri, the esteemed winner, to switch sides. (http://www.boston.com/news/daily/21/odds_republican.htm) .................................................. [And Jerry throws in this candidate for a Darwin Award:] ...To a Green Bay Wisconsin man who, for some sort of sex jolly, handed his wife a shotgun and told her to point it at his scrotum and shoot, which she did. He thought the gun wasn't loaded. He's in critical condition . and out of the gene pool. ============================ [And let's include this item from RandyC (CO)...] ............................................... WHODUNIT: Deputies at the Livingston County (Mich.) Jail were a tad suspicious when Heather Rau Quigley, 19, arrived at 3:15 in the morning to present an order for the release of her 36-year-old husband. The documents had the word "tendered" spelled wrong, and calculated a 10 percent posting on the $10,000 bond as $500. Deputies arrested her on charges of forging official documents and attempting to aid and abet a jail escape. Quigley is being held on $25,000 bond, but since there was no evidence her husband was involved, he has been released. (Ann Arbor News) ...[Wife writes writ wrong, ward witnesses warrant; woman winds up awaiting waterloo while wiseguy walks]. ===================================== [Off a Portland OR newspaper) Jerry L sends.....] Here are some re-invented words created by making small changes to create a new word with a new definition. · Glockoma: Causes a blind eye to be turned to the anti- hand-gun problem in America. · Gangreenspan: A constriction of the money supply leading to necrosis of the economy. · Irritable Powell Syndrome: A disease of the Colin, causing meddlesomeness. · Congresstipation: The inability to eliminate waste in our federal government. · Scaliasis: Curvature of the spine that forces the patient to lean far to the right. · Gingrichitis: A gum infection caused by biting off more than you can chew. · Loopus: Shriveling of ego caused by being left out of important meetings. · Starlet Fever: A compulsion to invite celebrities to testify at congressional hearings. · Postnasal Tripp: Compulsive snooping, even after rhino-plasty. · Soft issue damage: Slippage in the polls over a minor policy matter. · Nymphoma: Unnatural attraction to interns. · Barry-Barry: An unmitigated nerve disease. (The Edge (The Oregonian)) =============================== [More redeeming merit, of sorts. NealO (NJ) writes"] ........................................................ A British complaint letter (Well, who knows if it's real or not. But you can file it away i n your personal suggestion box in case you ever need to compose such a letter! to YOUR phone/cable.co/IRS/etc. The British do have a way with words. A real-life customer complaint letter sent to NTL, their Telephone co.... ) "Dear Cretins, I have been an NTL customer since 9th July 2001, when I signed up for your 3-in-one deal for cable TV, cable modem, and telephone. During this three-month period I have encountered inadequacy of service which I had not previously considered possible, as well as ignorance and stupidity of monolithic proportions. Please allow me to provide specific details, so that you can either pursue your professional prerogative, and seek to rectify these difficulties - or more likely (I suspect) so that you can have some entertaining reading material as you while away the working day smoking B&H and drinking vendor-coffee on the bog in your office: My initial installation was canceled without warning, resulting in my spending an entire Saturday sitting on my fat arse waiting for your technician to arrive. When he did not arrive, I spent a further 57 minutes listening to your infuriating hold music, and the even more annoying Scottish robot woman telling me to look at your helpful website.... HOW? I alleviated the boredom by playing with my testicles for a few minutes - an activity at which you are no-doubt both familiar and highly adept. The rescheduled installation then took place some two weeks later, although the technician did forget to bring a number of vital tools - such as a drill-bit, and his cerebrum. Two weeks later, my cable modem had still not arrived. After 15 telephone calls over 4 weeks my modem arrived... six weeks after I had requested it, and begun to pay for it. I estimate your internet servers downtime is roughly 35%... hours between about 6pm -midnight, Mon-Fri, and most of the weekend. I am still waiting for my telephone connection. I have made 9 calls on my mobile to your no-help line, and have been unhelpfully transferred to a variety of disinterested individuals, who are it seems also highly skilled bollock jugglers. I have been informed that a telephone line is available (and someone will call me back); that I will be transferred to someone who knows whether or not a telephone line is available (and then been cut off); that I will be transferred to someone (and then been redirected to an answer machine informing me that your office is closed); that I will be transferred to someone and then been redirected to the irritating Scottish robot woman...and several other variations on this theme. Doubtless you are no-longer reading this letter, as you have at least a thousand other dissatisfied customers to ignore, and also another one of those crucially important testicle- moments to attend to. Frankly I don't care, it's far more satisfying as a customer to voice my frustrations in print than to shout them at your unending hold music. Forgive me, therefore, if I continue. I thought BT were shit, that they had attained the holy piss-pot of god-awful customer relations, that no one, anywhere, ever, could be more disinterested, less helpful or more obstructive to delivering service to their customers. That's why I chose NTL, and because, well, there isn't anyone else is there? How surprised I therefore was, when I discovered to my considerable dissatisfaction and disappointment what a useless shower of bastards you truly are. You are sputum-filled pieces of distended rectum - incompetents of the highest order. British Telecom - wankers though they are - shine like brilliant beacons of success, in the filthy puss-filled mire of your seemingly limitless inadequacy. Suffice to say that I have now given up on my futile and foolhardy quest to receive any kind of service from you. I suggest that you cease any potential future attempts to extort payment from me for the services which you have so pointedly and catastrophically failed to deliver- any such activity will be greeted initially with hilarity and disbelief - quickly be replaced by derision, and even perhaps bemused rage. I enclose two small deposits, selected with great care from my cats litter tray, as an expression of my utter and complete contempt for both you and your pointless company. I sincerely hope that they have not become desiccated during transit - they were satisfyingly moist at the time of posting, and I would feel considerable disappointment if you did not experience both their rich aroma and delicate texture. Consider them the very embodiment of my feelings towards NTL, and its worthless employees. Have a nice day - may it be the last in your miserable short life, you irritatingly incompetent and infuriatingly unhelpful bunch of twats." [Or... read for the last word... "twits"] ====================================== [JimG (NJ) sends this hot item....] ....................................................... Sweaty palms Once upon a time there lived a king. The king had a beautiful daughter, the princess. But there was a problem. Everything the princess touched would melt. No matter what; metal, wood, stone, anything she touched would melt. Because of this, men were afraid of her. Nobody would dare marry her. The king despaired. What could he do to help his daughter? He consulted his wizards and magicians. One wizard told the king, "If your daughter touches one thing that does not melt in her hands, she will be cured." The king was overjoyed and came up with a plan. The next week, he held a competition. Any man that could bring his daughter an object that would not melt would marry her and inherit the king's wealth. Three young princes took up the challenge. The first prince brought a sword of the finest steel. But alas, once the princess touched it, it melted. The prince went away sadly. The second prince brought diamonds. He thought diamonds are the hardest substance in the world and would not melt. But alas, once the princess touched them, they melted. He too was sent away disappointed. The third prince approached. He told the princess, "Put your hand in my pocket and feel what is in there." The princess did as she was told, though she turned red.  She felt something hard. She held it in her hand. And it did not melt!!! The king was overjoyed. Everybody in the kingdom was overjoyed. And the third prince married the princess and they both lived happily ever after. Question: What was in the prince's pants? M&M's of course. They melt in your mouth, not in your hand. What were YOU thinking? ================================== [PaulA (TX) and this hellish political tale, plus.] ........................................................ Hell Right Across the Street A politician awoke in a hospital bed after a complicated operation, and found that the curtains were drawn around him. Alarmed, he nervously asked: "Why are the curtains closed? Is it night?" A nurse replied: "No, it is just that there is a fire across the street, and we didn't want you waking up and thinking that the operation to save your life was unsuccessful." .............................................. Fire and Water A doctor vacationing on the Riviera met an old lawyer friend and asked him what he was doing there. The lawyer replied: "Remember that lousy real estate I bought? Well, it caught fire, so here I am with the fire insurance proceeds. What are you doing here?" The doctor replied: "Remember that lousy real estate I had in Mississippi? Well, the river overflowed, and here I am with the flood insurance proceeds." The lawyer looked puzzled. He then asked the question that was troubling him: "Tell me! How do you start a flood?" [Plus this variant...] Earth, Air, Fire and Water Three somewhat unsuccessful business tycoons accidentally met on the beach in Hawaii. After a string of small talk. They began to inquire as to the fortunes of the other two. The first volunteered by saying: "I know you're both wondering how I got here. That tailor shop was an unqualified LOOSER FIRST CLASS. Well, to answer the question that is haunting you, that place was in a flood zone. However, a tornado came through a wiped it out. The insurance proceeds brought me here. I haven't decided whether or not to rebuild and re-open." The second one took the cue and started off: "Well, that liquor store was a CERTIFIED DOG. The plumbing started leaking and just got progressively worse every week. However, heavy rains came unexpectedly and washed it away. The insurance payoff was the appropriate end to my story." The third knew it was his turn. He related his story: "Well, you both know that small cleaners never did make enough to support me. The night it burned was really my lucky night. After the insurance settlement, I decided it was time for a well earned vacation." They all congratulated each other for having the foresight to carry excess property hazard insurance. But then after a moment of lull in the conversation, the dry cleaners owner asked the tailor:\ Tell me Larry, how do you start a tornado?" =================================== [Jet___ (TX) sends this pair] ............................................ The Pope was finishing his sermon. He finished with the Latin phrase, "Tuti Hominous" - Blessed be mankind. A women's rights group approached the Pope the next day. They commented that the Pope blessed all mankind, but not womankind. So the next day, after his sermon, the Pope concluded by saying, "Tuti Hominous et tuti Feminous" - Blessed be mankind and womankind. The next day, a gay-rights group approached the Pope. They said that they noticed that he blessed mankind and womankind, and asked if he could also bless 'gay' people. The Pope said, 'Yes.' The next day, he concluded his sermon with "Tuti Homenous et Tuti Feminous et Tuti Fruity." .................................................. Just as a young man was about to get a chest XRay, the equipment slipped and his pelvic region was XRay'd instead. "Oh, no! cried the lab technician." Your reproductive organs just received a dose of radiation!" "What does that mean?" asked the now worried young man. "It's serious," replied the technician. "All your children will be lawyers!" ============================= [Paul =A (TX, again) responds with this'n] ................................................ How lawyers think for success A man went to his lawyer and explained his problem him. Specifically he said: "My neighbor owes me $500 and he doesn't want to pay up. What should I do?" The first question the lawyer asked was: "Do you have any proof?" The prospective client replied: Nope!" "Okay, then write him a letter asking him for the $2500 he owes you!" "But it's only $500," the man replied. "Exactly! That's what he'll say in the letter back to you. We can use that as proof that we need to nail him." ................................................... You Know You're Working Tooo Hard, if... You explain to your bank manager that you prefer to think of yourself as "highly leveraged" as opposed to "in debt". You refer to your significant other as "my co-CEO." You can explain to somebody the difference between "re-engineering", "down-sizing", "right-sizing", and "firing people's asses". You feel sorry for Dilbert's boss. You account for your tuition as a capital expenditure instead of an expense. You believe you never have any problems in your life, just "issues" and "improvement opportunities.". You use the term "value-added" without falling down laughing. You give constructive feedback to your dog. ==================================== [Finally, today's golf joke from JimS (NJ)] .................................................... 2 Terrible Lady Golfers Two guys are trying to get in a quick eighteen holes, but there are two terrible lady golfers in front of them hitting the ball everywhere but where it's supposed to go. The first guy says, "Why don't you go over and ask if we can play through?" The second guy gets about halfway there, turns around and comes back. The first guy asks, "What's wrong?" He says, "One of them is my wife, and the other one is my mistress." The first guy says, "That could be a problem. I'll go." He gets about halfway there and he turns and comes back, too. The second guy says, "What's wrong?" The first guy replies, "Small world." ==================================== [And as a kicker....] What's the difference between a fish and a horny bear? A fish mucks around a fountain. (Richard Lederer) ========================== Happy Memorial Day to all, and that'sa 'nuff fer now... Stu] #074 From sarmstrong13@mac.com Mon May 27 05:54:50 2002 From: sarmstrong13@mac.com (SA) Date: Sun, 26 May 2002 23:54:50 -0500 Subject: [Tutor] Newbie question. Message-ID: I'm trying to use the os.listdir module to list a directory and then store that output to a list. I'm probably doing this wrong: X = listdir(/) I get an invalid syntax error. How do I accomplish this? Sorry if this question is too newbyish. Thanks. SA From kojo@hal-pc.org Mon May 27 06:09:30 2002 From: kojo@hal-pc.org (Kojo Idrissa) Date: Mon, 27 May 2002 00:09:30 -0500 Subject: [Tutor] Structure Theorem and OOProgramming Message-ID: <5.1.0.14.0.20020526234359.00ade5e0@mail.hal-pc.org> --=====================_7902573==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed Ok, here's question about approaches to programming. I've read a bit about the Structured Programming Language Paradigm/ Structure Theorem (Any computer program can be built up by combing three fundamental constructs [Sequence/Selection/Repetition] in various ways). It seems like a good way to introduce a couple of friends who are new to programming to the idea of how to program. My question is, does this Paradigm/Theorem only map well to "procedural" languages, or will it work well with an OO approach as well? I can see all three of the constructs in Python, and it seems that in Python you'd be putting those constructs to work on Objects, but I'm no expert. I don't want to get a friend started down a "limited" path, or give them bad info at the beginning. I'm sure they'll both want to work in OO languages over the longer term. Let me know what you think, **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** --=====================_7902573==_.ALT Content-Type: text/html; charset="us-ascii" Ok, here's question about approaches to programming.

I've read a bit about the Structured Programming Language Paradigm/ Structure Theorem (Any computer program can be built up by combing three fundamental constructs [Sequence/Selection/Repetition] in various ways).  It seems like a good way to introduce a couple of friends who are new to programming to the idea of how to program.

My question is, does this Paradigm/Theorem only map well to "procedural" languages, or will it work well with an OO approach as well?  I can see all three of the constructs in Python, and it seems that in Python you'd be putting those constructs to work on Objects, but I'm no expert.  I don't want to get a friend started down a "limited" path, or give them bad info at the beginning.  I'm sure they'll both want to work in OO languages over the longer term.

Let me know what you think,

****************************
Kojo Idrissa
 
kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
**************************** --=====================_7902573==_.ALT-- From virketis@post.harvard.edu Mon May 27 06:11:33 2002 From: virketis@post.harvard.edu (Pijus Virketis) Date: Mon, 27 May 2002 01:11:33 -0400 Subject: [Tutor] Newbie question. In-Reply-To: Message-ID: <200205270512.g4R5C1Z05888@smtp4.fas.harvard.edu>

Hi SA,
 
>I'm trying to use the os.listdir= module to list a directory and then
>store
>that output to a list. I'm probably= doing this wrong:
>X =3D listdir(/)

A quick note: I assume that you have imported the os module= with "from os import *", seeing that you don't need to= qualify the call to listdir(). I suggest that you instead= do:
 
>>> import os
>>> path_list =3D os.listdir("/") # note= the quotes!
 
So, the problem was that the listdir() function was= expecting a string argument, i.e. "/" rather than just= / that you passed to it.
As for the import issue, "from foo import *" is= dangerous, because if you had written your own function baz(),= and another function with the same name existed in the foo= module, then your baz() would get clobbered in the namespace. If= you do "import foo", then your baz() and foo.baz() do= not interfere.
 
Cheers,
 
Pijus
From ak@silmarill.org Mon May 27 06:21:15 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 27 May 2002 01:21:15 -0400 Subject: [Tutor] Newbie question. In-Reply-To: References: Message-ID: <20020527052115.GA28374@ak.silmarill.org> On Sun, May 26, 2002 at 11:54:50PM -0500, SA wrote: > I'm trying to use the os.listdir module to list a directory and then store > that output to a list. I'm probably doing this wrong: > X = listdir(/) > > I get an invalid syntax error. > > How do I accomplish this? Sorry if this question is too newbyish. > > Thanks. > SA > > >>> os.listdir("/etc/X11") >>> ['Xsession.options', 'Xresources', 'Xserver', 'rstart', >>> 'XF86Config', 'xserver', >>> It has to be a string containing path to the dir to be listed. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From jkessel@sas.upenn.edu Mon May 27 07:15:36 2002 From: jkessel@sas.upenn.edu (Joe Kessel) Date: Sun, 26 May 2002 23:15:36 -0700 Subject: [Tutor] Help with Temperature Program Message-ID: <000801c20545$eaf4f6c0$e66d7ba5@oemcomputer> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C2050B.3E29C860 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi Listserve, Im very new to programming and python. I need to write a simple program = that extracts the current temperature off weather.com. If anyone is = willing to give me some basic instructions, I would appreciate it. Thanks, Joe ------=_NextPart_000_0005_01C2050B.3E29C860 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi Listserve,
 
Im very new to programming and = python.  I need=20 to write a simple program that extracts the current temperature off=20 weather.com.  If anyone is willing to give me some basic = instructions, I=20 would appreciate it.
 
Thanks,
 
Joe
------=_NextPart_000_0005_01C2050B.3E29C860-- From dyoo@hkn.eecs.berkeley.edu Mon May 27 07:11:40 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 26 May 2002 23:11:40 -0700 (PDT) Subject: [Tutor] Newbie question. [primitive operations / scheme tangent] In-Reply-To: <200205270512.g4R5C1Z05888@smtp4.fas.harvard.edu> Message-ID: On Mon, 27 May 2002, Pijus Virketis wrote: > >I'm trying to use the os.listdir module to list a directory and then > >store > >that output to a list. I'm probably doing this wrong: > >X = listdir(/) > > A quick note: I assume that you have imported the os module with "from os import > *", seeing that you don't need to qualify the call to listdir(). I suggest that > you instead do: > > >>> import os > >>> path_list = os.listdir("/") # note the quotes! > > > So, the problem was that the listdir() function was expecting a string > argument, i.e. "/" rather than just / that you passed to it. Hi SA, hope things are going well! Another reason why: x = listdir(/) doesn't quite work is that '/' is the symbol for division. Just as '+' and '-' stand for addition and subtraction, Python uses '/' for division. Let's see what happens with Python when we try putting those mathy operations standalone in an interactive interpreter: ### >>> + File "", line 1 + ^ SyntaxError: invalid syntax >>> / File "", line 1 / ^ SyntaxError: invalid syntax ### In these cases, Python flags each as a "syntax error" because it's assuming that we've forgotten to say what to do WHICH by WHAT. These are formally called "binary" operators because they always need to have something on the left and right sides of them for Python to make sense out of them: ### >>> 14 / 2 7 ### and if we leave the left and right sides out, we get a syntax error. Let's see what happens when we try to say 'x = listdir(/)': ### >>> x = listdir(/) File "", line 1 x = listdir(/) ^ SyntaxError: invalid syntax ### So the interpreter actually zeroes in on the division symbol: it just looks so weird to Python that it just points its finger right on it! *grin* If you try the interactive interpreter on suspicious lines, you may find it useful while you're trying out new things. It's not perfect, but it can be helpful. [Random, offtopic note: this situation is different from the Scheme programming language, where even '+ and '- can be used standalone. For example, it's possible to say something like this in Scheme: ;;; dyoo@coffeetable:~$ guile guile> + # guile> (define (apply-with-42-and-24 function) (function 42 24)) guile> (apply-with-42-and-24 +) 66 guile> (apply-with-42-and-24 -) 18 guile> (apply-with-42-24 /) 1.75 ;;; Sorry, I just had to go off-tangent for a moment. *grin*] Anyway, good luck! If you have more questions, please feel free to ask! From dyoo@hkn.eecs.berkeley.edu Mon May 27 07:16:50 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 26 May 2002 23:16:50 -0700 (PDT) Subject: [Tutor] Newbie question. [primitive operations / scheme tangent] In-Reply-To: Message-ID: > [Random, offtopic note: this situation is different from the Scheme > programming language, where even '+ and '- can be used standalone. For > example, it's possible to say something like this in Scheme: > > ;;; > dyoo@coffeetable:~$ guile > guile> + > # > guile> (define (apply-with-42-and-24 function) > (function 42 24)) > guile> (apply-with-42-and-24 +) > 66 > guile> (apply-with-42-and-24 -) > 18 > guile> (apply-with-42-24 /) > 1.75 > ;;; > > Sorry, I just had to go off-tangent for a moment. *grin*] And I also cut-and-pasted wrong... again. *sigh* That last example: ;;; guile> (apply-with-42-24 /) 1.75 ;;; should have been: ;;; guile> (apply-with-42-and-24 /) 1.75 ;;; Sorry about the confusion! From shalehperry@attbi.com Mon May 27 08:20:55 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon, 27 May 2002 00:20:55 -0700 (PDT) Subject: [Tutor] Structure Theorem and OOProgramming In-Reply-To: <5.1.0.14.0.20020526234359.00ade5e0@mail.hal-pc.org> Message-ID: On 27-May-2002 Kojo Idrissa wrote: > Ok, here's question about approaches to programming. > > I've read a bit about the Structured Programming Language Paradigm/ > Structure Theorem (Any computer program can be built up by combing three > fundamental constructs [Sequence/Selection/Repetition] in various > ways). It seems like a good way to introduce a couple of friends who are > new to programming to the idea of how to program. > well that simplification is true. Even with objects you have to keep track of them, choose one to deal with, etc. From shalehperry@attbi.com Mon May 27 08:27:38 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon, 27 May 2002 00:27:38 -0700 (PDT) Subject: [Tutor] Help with Temperature Program In-Reply-To: <000801c20545$eaf4f6c0$e66d7ba5@oemcomputer> Message-ID: On 27-May-2002 Joe Kessel wrote: > Hi Listserve, > > Im very new to programming and python. I need to write a simple program that > extracts the current temperature off weather.com. If anyone is willing to > give me some basic instructions, I would appreciate it. > > Thanks, > > Joe perhaps if you asked a specific question we could help you better. From alex@gabuzomeu.net Mon May 27 09:38:39 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 27 May 2002 10:38:39 +0200 Subject: [Tutor] Newbie question. In-Reply-To: <20020527045502.2679.56273.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020527103444.00ad5f00@pop3.norton.antivirus> Hi, At 00:55 27/05/2002 -0400, tutor-request@python.org wrote: >Date: Sun, 26 May 2002 23:54:50 -0500 >From: SA >Subject: [Tutor] Newbie question. >I'm trying to use the os.listdir module to list a directory and then store >that output to a list. I'm probably doing this wrong: >X = listdir(/) > >I get an invalid syntax error. Yes, you need to enclose the path in quotes or to store it in a variable first. Eg.: import os os.listdir("/") # or thePath = "/" os.listdir(thePath) Cheers. Alexandre From thomas.jacobsen@sveg.se.sykes.com Mon May 27 11:34:34 2002 From: thomas.jacobsen@sveg.se.sykes.com (Thomas Jacobsen) Date: Mon, 27 May 2002 12:34:34 +0200 Subject: [Tutor] refresh-function Message-ID: Hi, I have a program that needs a function that is running in a "while 1:" loop, that runs with an interval, while other parts of the program is running. I was thinking of start the function in a thread, and use a time.sleep method, so the whole program doesn't sleep, but i don't know if this is the right/best way to do it. Any suggestions? Thomas "Knowledge is of two kinds. We know a subject ourselves, or we know where we can find information on it." -- Samuel Johnson From rnd@onego.ru Mon May 27 11:38:13 2002 From: rnd@onego.ru (Roman Suzi) Date: Mon, 27 May 2002 14:38:13 +0400 (MSD) Subject: [Tutor] Structure Theorem and OOProgramming In-Reply-To: Message-ID: On Mon, 27 May 2002, Sean 'Shaleh' Perry wrote: > On 27-May-2002 Kojo Idrissa wrote: > > Ok, here's question about approaches to programming. > > > > I've read a bit about the Structured Programming Language Paradigm/ > > Structure Theorem (Any computer program can be built up by combing three > > fundamental constructs [Sequence/Selection/Repetition] in various > > ways). It seems like a good way to introduce a couple of friends who are > > new to programming to the idea of how to program. > > > > well that simplification is true. Even with objects you have to keep > track of them, choose one to deal with, etc. Structured programming (SP) and OOP aren't competitors. OOP is based on SP. However, subroutines (functions) are usually added to those three fundamental structures and that is one step closer to OOP. In fact, basic algorithmic structures can emulate object orientation. As assembler language with GOTO can emulate structured programming. This means, it is absolutely necessary to know SP to be able to do OOP properly. Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru - From hernan@orgmf.com.ar Mon May 27 12:40:23 2002 From: hernan@orgmf.com.ar (Hernan Martinez Foffani) Date: Mon, 27 May 2002 13:40:23 +0200 Subject: [Tutor] RE: Newbie question. In-Reply-To: <20020527045502.2679.56273.Mailman@mail.python.org> Message-ID: > I'm trying to use the os.listdir module to list a directory and then store > that output to a list. I'm probably doing this wrong: > X = listdir(/) I it wasn't answered yet... Just do: >>> import os >>> os.listdir("/") ['.idlerc', ..., 'Windows Update Setup Files', 'WINNT'] >>> -Hernan From alan.gauld@bt.com Mon May 27 12:58:16 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 27 May 2002 12:58:16 +0100 Subject: [Tutor] Dynamic creation of class instances... Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C61A@mbtlipnt02.btlabs.bt.co.uk> > I'm one of the folks who asked a question along the lines of > dynamic class creation. Thanks for replying. > I think this misconception comes from the examples of classes > given in a lot of texts. That's what I figured must be wrong but I can't quite see how. The Python OOP intros are very similar to the Delphi/C++/Smalltalk intros I've seen but for somer reason its not an issue. Thinking about it the *requirement* to create variable names before using them in those languages probably is the reason. > The examples given in most of the introductory > texts are fairly shallow and leave the impression to newbies > like me that a class is something you define generically so > that you can create specific instances of it at runtime. Which is true. > So, I define a generic "snake" class, and then the user > can specify more details about his snake named "Slytherin" > and we'll save that as a new instance of the class at runtime. Which is also fine. It seems that the problem lies in the beginner feeling some need to name the *variable* that he uses to reference the new snake with the same name that is stored as an *attribute* of the snake. Now why would that be? > account class, and each user will create his own instance of the bank > account at runtime. This was my concept for a while, and I'm only now > starting to move beyond it. Not sure what you mean by move beyond it. Its absolutely correct! > As I learn more about classes it seems that the programs / > scripts that I have been writing are just too simplistic to really use > classes. That may well be the case. I deliberately left OO as an advanced topic because I didn't want newbies trying to walk before they could run! > that they would be very useful in a larger project, but for my dinky > 100-line codes, it just seems that classes are not quite as practical. 100 lines is probably about where they do start to be useful but for 10-50 lines of code programs I hardly ever define classes. > I think OOP was one of my first hang-ups with a lot of the Tkinter > tutorials, too. Most of the tutorials made their GUI programs using > classes, but only had one instance of the class. Having one instance is fine. But in GUI land using classes from the beginning is probably a good idea since it does lead to a more organised way of working that helps a lot when you get to bigger projects. And in GUI bigger is anything beyond trivial! > that's an improvement. I understand how a Label() is a subclass of a > Widget(), but I don't understand why I have to create a class > just to make a GUI. Its the mental model concept. Your GUI consists of a window. A window is an object. Therefore define the window as a class that is used as a container for the other widgets inside it. > I guess that's why I wrote my own tutorial without > using classes for Tkinter. Thats how raw Tk works too but it can get cluttered very quickly. Thats why my Tkinter intro starts off procedurally but quickly introduces classes. > I guess my suggestion, then, is to work on the introductions > to OOP and classes. Yep, I think so. The question is what aspect will change the perception that objects need to be named the same as their attributes....? > realize that I can be a cool programmer even if I just use functional > programming most of the time. I like that. I grok functional > programming. Hmm, I suspect you mean procedural programming (or imperative programming) Functional programming is very cool but if you are using Tkinter you almost certainly aint using FP :-) But splitting hairs on terminology aside, you are right. Imperative programming was the main style for over 30 years and many cool systems are still written like that(Linux say...) > the dark side via the exec() function. This function is not > really covered in beginning tutorials Thats why I am puzzled as to how so many pick up on it. Virtually non of the intros (web or paper) mention exec(). > Well, those are my thoughts. Hopefully they're worth the paper their > printed on. Indeed, and the bandwidth they consume. Thanks for sharing them. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon May 27 14:41:54 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 27 May 2002 14:41:54 +0100 Subject: [Tutor] Newbie question. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C61B@mbtlipnt02.btlabs.bt.co.uk> > I'm trying to use the os.listdir module to list a directory So you need to import os: import os And reference it when using listdir(): os.listdir() > and then store that output to a list. > I'm probably doing this wrong: > import os X = os.listdir("/") # and the path should be a string > How do I accomplish this? Sorry if this question is too newbyish. Nothing is too newbyish for this list... Alan g. From lha2@columbia.edu Mon May 27 14:50:51 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Mon, 27 May 2002 09:50:51 -0400 Subject: [Tutor] Help with Temperature Program References: Message-ID: <3CF239BB.324D841@mail.verizon.net> Sean 'Shaleh' Perry wrote: > > On 27-May-2002 Joe Kessel wrote: > > Hi Listserve, > > > > Im very new to programming and python. I need to write a simple program that > > extracts the current temperature off weather.com. If anyone is willing to > > give me some basic instructions, I would appreciate it. > > > > Thanks, > > > > Joe > > perhaps if you asked a specific question we could help you better. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor You need a few things. First, learn files. Once you know files, you need to import urllib filename = urllib.urlretrieve("http://www.weather.com/weather/local/XXXXX") (except that that all goes on the same line--hopefully that won't autowrap on me) (where XXXXX is your zip code) filename is a tuple with two components; the 0th is the location of the file, and the second is a mimetools.Message, which I have no idea how to use. so you can thefile = open(filename[0], 'r') and then currentline = thefile.readline() until you see text like "insert current temp" or "insert forecast text" (look at the raw text file, and you'll understand what I mean) and you can pluck the relevant information out of those lines. DO NOT expect your temperature to always be a number; sometimes it will be "N/A". good luck. Don't know if that was basic; you have a relatively complicated task for a "first time programming" type thing. From wilson@visi.com Mon May 27 15:34:28 2002 From: wilson@visi.com (Tim Wilson) Date: Mon, 27 May 2002 09:34:28 -0500 Subject: [Tutor] Help with Temperature Program In-Reply-To: <000801c20545$eaf4f6c0$e66d7ba5@oemcomputer> References: <000801c20545$eaf4f6c0$e66d7ba5@oemcomputer> Message-ID: <20020527143428.GA945@isis.visi.com> On Sun, May 26, 2002 at 11:15:36PM -0700, Joe Kessel wrote: > > Im very new to programming and python. I need to write a simple program that extracts the current temperature off weather.com. If anyone is willing to give me some basic instructions, I would appreciate it. Hi Joe, You'll want to use the urllib2 module for this. It allows you to read data from a URL pretty much like a file on your local system (it will even read URLs on your local system). I did an assignment like this with my students this year, but we used the National Weather Service's METAR system. There are METAR stations at airports all around the country. You can read more about that assignment at http://www.isd197.org/sibley/cs/icp/assignments/weather_html The advantage of the METAR data is that it's easily parsable. The hardest part of used weather.com's data, I suspect, will be finding and reading the temperature from a Web page that will probably change frequently. Here's a sample session that shows how to read a URL: wilson@copland:~$ python Python 2.1.2 (#1, Jan 18 2002, 18:05:45) [GCC 2.95.4 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import urllib2 >>> metar = urllib2.urlopen('ftp://weather.noaa.gov/data/observations/metar/stations/KSGS.TXT') >>> data = metar.read() >>> print data 2002/05/27 14:17 KSGS 271417Z AUTO 00000KT 10SM CLR 18/13 A2997 RMK AO2 LTG DSNT E >>> You can split the resulting string and start parsing. Good luck. -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.com W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From alex@gabuzomeu.net Mon May 27 15:45:11 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 27 May 2002 16:45:11 +0200 Subject: [Tutor] Help with Temperature Program In-Reply-To: <20020527135301.1677.54627.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020527161754.00c83d40@pop3.norton.antivirus> Hi Joe, At 09:53 27/05/2002 -0400, you wrote: >From: "Joe Kessel" >Date: Sun, 26 May 2002 23:15:36 -0700 >Subject: [Tutor] Help with Temperature Program >Im very new to programming and python. I need to write a simple >program that extracts the current temperature off weather.com. If anyone >is willing to give me some basic instructions, I would appreciate it. OK, here are suggestions to get you started. 1) First, if you haven't already done so, go through the tutorial so that you can pick up the basics: http://www.python.org/doc/current/tut/tut.html See also: http://www.python.org/doc/Newbies.html 2) Then, try retrieving the text content of the Web page you're interested in. To access a Web page, you can use the "urllib" module. Eg. import urllib theURL = """http://www.weather.com/weather/local/FRXX0076?y=10&x=8""" # Access the page thePage = urllib.urlopen(theURL) # Store the page content in a variable pageText = thePage.read() # Close the page object thePage.close() 3) Then, try to extract the data you're interested in from the page. To extract data from the page text you downloaded, one solution is using regular expressions (the "re" module). You may find them a tad complex, but they offer a lot of flexibility. If you want to use regular expressions, take a look at this tutorial: http://py-howto.sourceforge.net/regex/regex.html If you're stuck, let us know and we'll try to help. Cheers. Alexandre From alan.gauld@bt.com Mon May 27 15:55:37 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 27 May 2002 15:55:37 +0100 Subject: [Tutor] Structure Theorem and OOProgramming Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C61C@mbtlipnt02.btlabs.bt.co.uk> > I've read a bit about the Structured Programming Language > Paradigm/ Structure Theorem (Any computer program can be > built up by combing three fundamental constructs > [Sequence/Selection/Repetition] in various ways). Thats the basis of my web tutor(and especially the book). It looks at each of the three constructs (plus a fourth: modularization) > My question is, does this Paradigm/Theorem only map well > to "procedural" languages, or will it work well with an > OO approach as well? The methods within an object are still just procedures so it applies at that level. The OO bits are just another form of module so provided tyou include modularization as a fourth construct it works fine. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From vikramoberoi" repected sir, i wan't to learn all about hacking and cracking ...can u help me vikram _________________________________________________________ Click below to visit monsterindia.com and review jobs in India or Abroad http://monsterindia.rediff.com/jobs From tim@johnsons-web.com Mon May 27 17:32:32 2002 From: tim@johnsons-web.com (Tim Johnson) Date: Mon, 27 May 2002 08:32:32 -0800 Subject: [Tutor] More CGI questions/incremental output In-Reply-To: <20020526210020.GA4331@dman.ddts.net> References: <20020526181013.GT23144@johnsons-web.com> <20020526210020.GA4331@dman.ddts.net> Message-ID: <20020527163232.GY23144@johnsons-web.com> resent: NOTE: the -u option was what I was looking for. Many thanks to dman. -tj- * dman [020526 12:56]: > On Sun, May 26, 2002 at 10:10:13AM -0800, Tim Johnson wrote: > > Yeah, that's part of how HTTP tends to work. > > | I've done other CGI programming (using Rebol, C,C++, etc) > | and have observed output incrementally, as I would desire it. Hi dman: > With the same web browser? Yes. I do cgi all the time with C/C++ and rebol.... depending on the nature of the content, I'm used to seeing text statements displayed as they are written to stdout from my rebol scripts result vary, of course, I won't see an table until all code for it is sent to the browser, but I do see simple text output. > What about IO buffering? > | What can I do to see an incremental output from my Python > | script? (I am just using print to write to stdout now) > > One possiblity, that also depends on your server's platform, the web > server used, the CGI implementation in the web server and the client's > browser (IOW not reliable by any means) is to disable python's IO > buffering. Run python with '-u' to disable buffering of stdout. That I did try just now. Didn't see a difference in that run, but will follow that track a bit. Thanks.. > The way "progress" is really done with HTTP is to send back a complete > response that includes a redirect to your real processor. Of course, will be using redirect tages for discrete stages.... > For an > example of how this looks to the user go to orbitz.com and execute a > search. The first CGI script sends back that "we are processing the > query" page which redirects to the second CGI script that does the > actual (long) search and returns the results. The animation is done > via a .gif image. Do let me give you an example of a cgi script in a language that I'm more familiar with: A rebol CGI script interfaces with MySql and builds and indexes a large number of tables. At least a 100 SQL commands are issued. As each command is issued, a line of text is is sent to stdout. It's difficult to tell exactly, because process are fairly quick, but my browser is giving me back at least several lines at once, if not one at a time. At that is on the same browser, web server and os. I will investigate the -u option further (and in fact, will be using redirection). Thanks for the explanation, and I hope to hear futher comments. Regards :-) -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From dyoo@hkn.eecs.berkeley.edu Mon May 27 18:42:04 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 27 May 2002 10:42:04 -0700 (PDT) Subject: [Tutor] hacking and cracking In-Reply-To: <20020527161010.7236.qmail@webmail7.rediffmail.com> Message-ID: On 27 May 2002, vikramoberoi wrote: > repected sir, i wan't to learn all about hacking and cracking ...can u > help me Dear vikramoberoi, We can't help you on this one, sorry. We help show each other interesting ways of Python programming, but we're not interested in intruding into other people's systems. We're just too busy figuring out how to keep our own systems together. You may have seen this link already, but just in case, see: http://www.tuxedo.org/~esr/faqs/hacker-howto.html#WHAT_IS for an explanation why we don't encourage 'cracking'. But if you're still wanting to do this, your best bet is to try the 'alt.2600' newsgroup. From dman@dman.ddts.net Mon May 27 21:26:34 2002 From: dman@dman.ddts.net (dman) Date: Mon, 27 May 2002 15:26:34 -0500 Subject: [Tutor] refresh-function In-Reply-To: References: Message-ID: <20020527202634.GA13966@dman.ddts.net> --KsGdsel6WgEHnImy Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 27, 2002 at 12:34:34PM +0200, Thomas Jacobsen wrote: | Hi, |=20 | I have a program that needs a function that is running in a "while 1:" lo= op, | that runs with an interval, while other parts of the program is running.= =20 | I was thinking of start the function in a thread, and use a time.sleep | method, so the whole program doesn't sleep, but i don't know if this is t= he | right/best way to do it. That sounds like a good idea, as long as sleeping for a specific amount of time is how "interval" is defined for your function. Especially when using threads, you should be sure and understand the Lock and Event classes from the threading module. Depending on your application, it may be better to use those instead of sleep(). HTH, -D --=20 How to shoot yourself in the foot with Java: You find that Microsoft and Sun have released incompatible class libraries both implementing Gun objects. You then find that although there are plenty of feet objects implemented in the past in many other languages, you cannot get access to one. But seeing as Java is so cool, you don't care and go around shooting anything else you can find. (written by Mark Hammond) =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --KsGdsel6WgEHnImy Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzylnoACgkQO8l8XBKTpRS+vwCaAnHNIycJXqeSI3a6xukgwaGG mIYAoK03vtT+/VPunkzQEbfNnYPiRzdB =DD3q -----END PGP SIGNATURE----- --KsGdsel6WgEHnImy-- From bigal@geosci.uchicago.edu Mon May 27 22:02:53 2002 From: bigal@geosci.uchicago.edu (Alistair McGowan) Date: Mon, 27 May 2002 16:02:53 -0500 Subject: [Tutor] Importing file data into Python arrays Message-ID: --============_-1189589119==_============ Content-Type: multipart/alternative; boundary="============_-1189589119==_ma============" --============_-1189589119==_ma============ Content-Type: text/plain; charset="us-ascii" ; format="flowed" Dear Python Wranglers, Being of a scientific bent, I need to handle data in arrays to do things like resampling and general calculations. I am used to BASIC arrays which I can read data into from other files with no problem. However, I am being defeated by the Python readline(s) for file import. I can do things within Python OK, such as the example below lifted from a help page and modified. import array arr=[] for i in range(5): arr.append([]) for j in range(10): arr[i].append(i*j*2) print arr[:] s = arr [4] a = s[1] b = s[2] print a-b And I can splice away and reassign values fine. However, when I try to read in data from a file as shown below, I end up with the lines, which I can't manipulate. import array arr=[] inp = open ("dat.txt","r") #read line into array for line in inp.readlines(): arr.append(line) print arr [0:3] which gives ['1 2 3\n', '4 5 6\n', '7 8 9'] as output I have tried using the suggested num = int(string), but I the "/n" can't be dealt with from the space delimited simple text file I am using to test this, which is appended to this mail. I have consulted my Python Essential Reference, but I am failing to see the way to deal with this. Thanks in advance. Cheers, Al --============_-1189589119==_ma============ Content-Type: text/enriched; charset="us-ascii" Dear Python Wranglers, Being of a scientific bent, I need to handle data in arrays to do things like resampling and general calculations. I am used to BASIC arrays which I can read data into from other files with no problem. However, I am being defeated by the Python readline(s) for file import. I can do things within Python OK, such as the example below lifted from a help page and modified. Genevaimport array arr=[] for i in range(5): arr.append([]) for j in range(10): arr[i].append(i*j*2) print arr[:] s = arr [4] a = s[1] b = s[2] print a-b And I can splice away and reassign values fine. However, when I try to read in data from a file as shown below, I end up with the lines, which I can't manipulate. Genevaimport array arr=[] inp = open ("dat.txt","r") #read line into array for line in inp.readlines(): arr.append(line) print arr [0:3] which gives ['1 2 3\n', '4 5 6\n', '7 8 9'] as output I have tried using the suggested num = int(string), but I the "/n" can't be dealt with from the space delimited simple text file I am using to test this, which is appended to this mail. I have consulted my Python Essential Reference, but I am failing to see the way to deal with this. Thanks in advance. Cheers, Al --============_-1189589119==_ma============-- --============_-1189589119==_============ Content-Id: Content-Type: text/plain; name="dat.txt"; charset="us-ascii" Content-Disposition: attachment; filename="dat.txt" ; modification-date="Mon, 27 May 2002 13:42:36 -0500" 1 2 3 4 5 6 7 8 9 --============_-1189589119==_============ Content-Type: text/plain; charset="us-ascii" Alistair J. McGowan Department of Geophysical Sciences, University of Chicago Chicago IL 60637 Phone: 773-955-4040 x5-1170 Fax: 773-702-9505 "Hope is a duty from which paleontologists are exempt." David Quammen --============_-1189589119==_============-- From yduppen@xs4all.nl Mon May 27 22:24:06 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Mon, 27 May 2002 23:24:06 +0200 Subject: [Tutor] Importing file data into Python arrays In-Reply-To: References: Message-ID: <200205272124.g4RLNxQM057297@smtpzilla1.xs4all.nl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > However, when I try to read in data from a file as shown below, I end > up with the lines, which I can't manipulate. > > import array > arr=[] > inp = open ("dat.txt","r") > #read line into array > for line in inp.readlines(): > arr.append(line) > print arr [0:3] > which gives > > ['1 2 3\n', '4 5 6\n', '7 8 9'] > > as output In the following I'll just assume you want the output [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Readline returns strings (such as '1 2 3\n'). Luckily, it is easy to convert this string to a list of numbers. >>> line = "1 2 3\n" >>> line '1 2 3\n' First, the string needs to be splitted into its number parts. This is done using the split function. >>> line.split() ['1', '2', '3'] The split function can also takes other arguments, which is great if you have for example a comma separated input. Of course, in that case you need to to trim the trailing whitespace (newline) >>> commaline = "1,2,3\n" >>> commaline '1,2,3\n' >>> commaline.strip() '1,2,3' >>> commaline.strip().split(",") ['1', '2', '3'] But I digress. In any case, you still have a number of strings. That's where the map function comes in handy. >>> map(int, line.split()) [1, 2, 3] This applies the int() function on every element in your list, resulting in a new list containing the converted values. So your total program would look like: arr=[] inp = open ("dat.txt","r") #read line into array for line in inp.readlines(): numbers = map(int, line.split()) arr.append(numbers) print arr [0:3] Note: this only works with Python 2.0 or higher. For Python 1.5 you need to import the string module import string ... numbers = map(int, string.split(line)) YDD - -- .sigmentation Fault -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE88qP2LsKMuCf5EdwRAli6AKDzDOmem1ANhN2KiXME6YDHAEHdfwCgrpk9 bNhzoN9Mgl9Q9daVNNf9izM= =REan -----END PGP SIGNATURE----- From kalle@lysator.liu.se Mon May 27 22:31:00 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Mon, 27 May 2002 23:31:00 +0200 Subject: [Tutor] Importing file data into Python arrays In-Reply-To: References: Message-ID: <20020527213100.GA2904@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Alistair McGowan] > import array For the examples you have shown, there is no need to import array. You are using lists, a basic datatype in Python. The array module, documented at http://python.org/doc/current/lib/module-array.html might be of interest to you anyway, as well as the numeric python extensions at http://www.pfdubois.com/numpy/ . > However, when I try to read in data from a file as shown below, I > end up with the lines, which I can't manipulate. You will have to manipulate the lines a bit to go from strings to integers. How to do this depends on what you want. If you want a nested list like [[1, 2, 3], [4, 5, 6], [7, 8, 9]] something like this should work: arr = [] inp = open ("dat.txt","r") #read line into array for line in inp.readlines(): # add a new sublist arr.append([]) # loop over the elemets, split by whitespace for i in line.split(): # convert to integer and append to the last # element of the list arr[-1].append(int(i)) To get a flat list like [1, 2, 3, 4, 5, 6, 7, 8, 9] this might do: arr = [] inp = open ("dat.txt","r") #read line into array for line in inp.readlines(): # loop over the elemets, split by whitespace for i in line.split(): # convert to integer and append to the list arr.append(int(i)) Hope this helps. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE88qWMdNeA1787sd0RAplBAJ4wvzXzWLaS2n46kIZi8FSe3nRVbgCgu3lF tb96o7nErPGBzx6dROjQj0M= =7/cM -----END PGP SIGNATURE----- From urnerk@qwest.net Mon May 27 22:53:13 2002 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 27 May 2002 14:53:13 -0700 Subject: [Tutor] Importing file data into Python arrays In-Reply-To: Message-ID: <4.2.0.58.20020527144919.00d30e10@pop3.norton.antivirus> You can also hand your strings to something like: def getdata(strdata): return [eval(i) for i in strdata.split()] >>> getdata('1.2 7e6 -1 10.39\n') [1.2, 7000000.0, -1, 10.390000000000001] People like to warn against eval(), but if it's your program written for you on your computer, go right ahead. So many of these anti-eval() arguments boil down to reasoning like: one shouldn't be allowed to use knives, because one might cut one's own wrists (or throat) with them. That argument only makes sense if you presume a self-destructive programmer (or a completely inept one), in which case there a many more direct ways to wreak havoc. Kirby From Fox33me@aol.com Mon May 27 23:03:02 2002 From: Fox33me@aol.com (Fox33me@aol.com) Date: Mon, 27 May 2002 18:03:02 EDT Subject: [Tutor] hi Message-ID: <7a.276d9830.2a240716@aol.com> All im basically asking is if someone could explain to me how to use def and when to use it. also how to use modules and when to use them. thank you From emil@lysator.liu.se Tue May 28 01:06:40 2002 From: emil@lysator.liu.se (Emil Styrke) Date: Tue, 28 May 2002 02:06:40 +0200 Subject: [Tutor] hi In-Reply-To: <7a.276d9830.2a240716@aol.com> References: <7a.276d9830.2a240716@aol.com> Message-ID: <20020528020639.B18999@moghedien.lysator.liu.se> Hi, Have a look at the python tutorial at http://www.python.org/doc/current/tut/tut.html , in particular sections 4.6 and 6. If you have any further questions, don't hesitate to ask! /Emil [Fox33me@aol.com] > All im basically asking is if someone could explain to me how to use def and > when to use it. also how to use modules and when to use them. > > thank you > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From David@snowcrash.co.uk Tue May 28 09:21:31 2002 From: David@snowcrash.co.uk (David) Date: Tue, 28 May 2002 09:21:31 +0100 Subject: [Tutor] Com & Python Message-ID: <000001c20620$ad8acc70$6500000a@goodweather.co.uk> Looking for any pointers on working with some com objects! Specifically I am writing a script which manages a com object developed by citrix to allow management of a citrix metaframe farm! Problem is I have code in python which can do basic things with the object but I'm having problems when it returns a collection object I want to iterate through...can seem to get anywhere; bummer is I have working code in vbscript but that lets me down in other areas hence why I wanted to use python... Python excerpt: MetaFrameWinFarmObject = 1 MetaFrameWinAppObject = 3 MFWinAppDesktop = 8 #this is test for citrix com stuff objFarm = win32com.client.Dispatch("MetaFrameCOM.MetaFrameFarm") objFarm.Initialize(MetaFrameWinFarmObject) if objFarm.WinFarmObject.IsCitrixAdministrator == 0: print "not a citrix admin" objApplication = objFarm.GetApplication(MetaFrameWinAppObject, "Applications\Notepad") print "before load data" print objApplication.EnableApp objApplication.LoadData(1) #this is required to load data to this object print "after load data " print objApplication.EnableApp print " now try changing things" objApplication.EnableApp=1 objApplication.SaveData() #this is required to commit changes to this object #print new value print objApplication.EnableApp #works ok up to here - sets the above values correctly #At this point can't work out how to get data out of this collections object!!!!!... ??? objApplication.Sessions ???? Have tried just printing it doing for x in objApplication.Sessions And just get error's Just wondering if I'm being really thick and missing some obvious about working with com collections? Working vscript (much of this taken from citrix sdk) Dim theFarm2 'this is a citrix farm object used to kill users Dim bApplication 'this is a citrix app object used to kill users Dim aSession 'individual session within the collection for user logoff Dim bSession 'individual session within the collection for user message ' Create MetaFrameFarm object Set theFarm2 = CreateObject("MetaFrameCOM.MetaFrameFarm") if Err.Number<> 0 Then ' Display the Error that occured ' WScript.Echo "Can't create MetaFrameFarm object when getting status" ' WScript.Echo "(" & Err.Number & ") " & Err.Description ' WScript.Echo "" WScript.Quit Err.Number End if ' Initialize the farm object. theFarm2.Initialize(MetaFrameWinFarmObject) if Err.Number<> 0 Then ' Display the Error that occured ' WScript.Echo "Can't Initialize MetaFrameFarm object when getting status" ' WScript.Echo "(" & Err.Number & ") " & Err.Description ' WScript.Echo "" WScript.Quit Err.Number End if ' Are you Citrix Administrator? if theFarm2.WinFarmObject.IsCitrixAdministrator = 0 then ' WScript.Echo _ ' "You must be a Citrix administrator to run this application when getting status" ' WScript.Echo "" WScript.Quit 0 End If ' Print out the farm name. 'WScript.Echo "MetaFrame Farm Name (when getting status): " & theFarm2.FarmName ' MetaFrameApplication object. Set bApplication = theFarm2.GetApplication(MetaFrameWinAppObject, strAppDN) if Err.Number<> 0 Then ' Display the Error that occured ' WScript.Echo "Can't get application object when getting status" ' WScript.Echo "(" & Err.Number & ") " & Err.Description ' WScript.Echo "" WScript.Quit Err.Number End if 'refresh data for the application object bApplication.LoadData(TRUE) 'Send user logoff warning For Each bSession In bApplication.Sessions if Err.Number<> 0 Then ' Display the Error that occured ' WScript.Echo "Can't enumerate sessions to message users" ' WScript.Echo "(" & Err.Number & ") " & Err.Description ' WScript.Echo "" WScript.Quit Err.Number End if 'logoff user without waiting for the disconnect to finish bSession.sendMessage _ bSession.ServerName, bSession.SessionID, _ bSession.UserName, bSession.ClientName, _ "Point of Sale", _ strWarningTxt, _ 0, _ 5000, _ 0 Next 'refresh data for the application object bApplication.LoadData(TRUE) 'Kill All Users For Each aSession In bApplication.Sessions if Err.Number<> 0 Then ' Display the Error that occured ' WScript.Echo "Can't enumerate sessions to kill users" ' WScript.Echo "(" & Err.Number & ") " & Err.Description ' WScript.Echo "" WScript.Quit Err.Number End if ' WScript.Echo "ServerName: " & aSession.ServerName &_ ' ", SessionName: " & aSession.SessionName &_ ' ", SessionID: " & CStr(aSession.SessionID) &_ ' ", User: " & aSession.UserName &_ ' ", Client Name: " & aSession.ClientName 'logoff user without waiting for the disconnect to finish aSession.logoff false Next From stuart_clemons@us.ibm.com Tue May 28 16:08:53 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Tue, 28 May 2002 11:08:53 -0400 Subject: [Tutor] Python from WINNT command line question Message-ID: --0__=0ABBE154DFC1D3F68f9e8a93df938690918c0ABBE154DFC1D3F6 Content-type: text/plain; charset=US-ASCII Hi: Python 2.2 is installed in f:\ptython22, as are my .py program files. I can run my programs with no problem from the f:\python22 directory. However, when I try to run them from another drive\directory, I get a "can't open file foo.py" error. I tried setting the path and PYTHONPATH environment as shown below. What do I need to do to make this work ? Thanks, E:\WINNT4>path PATH=f:\python22;f:\python22\lib E:\WINNT4>set PYTHONPATH PYTHONPATH=f:\python22\lib E:\WINNT4>f:\python22\python foo.py f:\python22\python: can't open file 'foo.py' E:\WINNT4> --0__=0ABBE154DFC1D3F68f9e8a93df938690918c0ABBE154DFC1D3F6 Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Hi:

Python 2.2 is installed in f:\ptython22, as are my .py program files. I can run my programs with no problem from the f:\python22 directory.

However, when I try to run them from another drive\directory, I get a "can't open file foo.py" error.

I tried setting the path and PYTHONPATH environment as shown below.

What do I need to do to make this work ? Thanks,


E:\WINNT4>path
PATH=f:\python22;f:\python22\lib

E:\WINNT4>set PYTHONPATH
PYTHONPATH=f:\python22\lib

E:\WINNT4>f:\python22\python foo.py

f:\python22\python: can't open file 'foo.py'

E:\WINNT4> --0__=0ABBE154DFC1D3F68f9e8a93df938690918c0ABBE154DFC1D3F6-- From rob@uselesspython.com Tue May 28 16:23:16 2002 From: rob@uselesspython.com (Rob Andrews) Date: Tue, 28 May 2002 10:23:16 -0500 Subject: [Tutor] Jython_Essentials comments Message-ID: <3CF3A0E4.8010601@uselesspython.com> I picked up Jython_Essentials the other day and read what I could of it during the occasional free moment over the weekend. I'm so impressed with what I've read so far that I wanted to mention it. Its primary audience seems to be Java coders new to Python/Jython, but it's of value to Python programmers as well. In fact, I'd say that anyone who really does Jython programming should seriously consider grabbing a copy. It covers a wide range of core topics from the standpoint of Python, Jython, and Java. Because of the way these comparisons are meted out, this book is expanding my understanding of Object-Oriented Programming more than anything else I've run across. FYI and Happy Tuesday, Rob http://uselesspython.com From stuart_clemons@us.ibm.com Tue May 28 16:52:07 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Tue, 28 May 2002 11:52:07 -0400 Subject: [Tutor] re: Python from WINNT command line question Message-ID: --0__=0ABBE154DFC5671A8f9e8a93df938690918c0ABBE154DFC5671A Content-type: text/plain; charset=US-ASCII Hi all: I think figured out my solution. While this didn't work: E:\WINNT4>f:\python22\python foo.py f:\python22\python: can't open file 'foo.py' This worked (though I'm not sure why): E:\WINNT4>f:\python22\foo.py - Stuart ---------------------- Forwarded by Stuart Clemons/Westford/IBM on 05/28/2002 12:03 PM --------------------------- Stuart Clemons 05/28/2002 11:08 AM To: tutor@python.org cc: Subject: Python from WINNT command line question Hi: Python 2.2 is installed in f:\ptython22, as are my .py program files. I can run my programs with no problem from the f:\python22 directory. However, when I try to run them from another drive\directory, I get a "can't open file foo.py" error. I tried setting the path and PYTHONPATH environment as shown below. What do I need to do to make this work ? Thanks, E:\WINNT4>path PATH=f:\python22;f:\python22\lib E:\WINNT4>set PYTHONPATH PYTHONPATH=f:\python22\lib E:\WINNT4>f:\python22\python foo.py f:\python22\python: can't open file 'foo.py' E:\WINNT4> --0__=0ABBE154DFC5671A8f9e8a93df938690918c0ABBE154DFC5671A Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Hi all:

I think figured out my solution.

While this didn't work:

E:\WINNT4>f:\python22\python foo.py

f:\python22\python: can't open file 'foo.py'

This worked (though I'm not sure why):

E:\WINNT4>f:\python22\foo.py

- Stuart

---------------------- Forwarded by Stuart Clemons/Westford/IBM on 05/28/2002 12:03 PM ---------------------------

To: tutor@python.org
cc:
Subject: Python from WINNT command line question

Hi:

Python 2.2 is installed in f:\ptython22, as are my .py program files. I can run my programs with no problem from the f:\python22 directory.

However, when I try to run them from another drive\directory, I get a "can't open file foo.py" error.

I tried setting the path and PYTHONPATH environment as shown below.

What do I need to do to make this work ? Thanks,


E:\WINNT4>path
PATH=f:\python22;f:\python22\lib

E:\WINNT4>set PYTHONPATH
PYTHONPATH=f:\python22\lib

E:\WINNT4>f:\python22\python foo.py

f:\python22\python: can't open file 'foo.py'

E:\WINNT4>

--0__=0ABBE154DFC5671A8f9e8a93df938690918c0ABBE154DFC5671A-- From alan.gauld@bt.com Tue May 28 17:11:42 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 28 May 2002 17:11:42 +0100 Subject: [Tutor] Importing file data into Python arrays Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C624@mbtlipnt02.btlabs.bt.co.uk> > import array > arr=[] > inp = open ("dat.txt","r") > #read line into array > for line in inp.readlines(): > arr.append(line) You'd be as well to just copy readlines into arr... readlines returns a list. However I think you want to strip the line: line = line.strip() # get rid of \n arr.append(line) > print arr [0:3] > ['1 2 3\n', '4 5 6\n', '7 8 9'] So your lines consist of 3 numbers? Are you trying to read in an array of single digits or an array of arrays each with 3 digits? Assuming the former try this: for line in f.readlines(): line = line.strip() # get rid of \n nums = line.split() # separate the characters nums = map(int,nums) # convert to integers for n in nums: arr.append(n) # add to your array If you want an (nx3) array just change the last line to arr.append(nums) I suspect there are cleverer ways of doing this with less code but the above should be clear? > num = int(string), but I the "/n" can't be dealt with Either string.strip() or string[:-1] will remove the newline character. HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From stuart_clemons@us.ibm.com Tue May 28 17:15:01 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Tue, 28 May 2002 12:15:01 -0400 Subject: [Tutor] Another Python from WINNT command line question Message-ID: --0__=0ABBE154DFCB88D58f9e8a93df938690918c0ABBE154DFCB88D5 Content-type: text/plain; charset=US-ASCII OK, I can run my program, foo.py, from any NT command line like this. c:\>f:\python22\foo.py which returns, "this is foo" So, now I want to pipe the output of foo.py to a file, spam.txt. So I use this command line: c:\>f:\python22\foo.py > spam.txt What happens is that spam.txt is created, but it is empty (it should contain "this is foo") If I run my program, foo.py, from the python directory and pipe it, it directs the output to the spam.txt file correctly. f:\python22> foo.py > spam.txt f:\python22> type spam.txt this is foo What do I need to do to redirect output when I run my python program from the non-Python installed directory ? Thanks, - Stuart ---------------------- Forwarded by Stuart Clemons/Westford/IBM on 05/28/2002 12:16 PM --------------------------- Stuart Clemons 05/28/2002 11:52 AM To: tutor@python.org cc: Subject: re: Python from WINNT command line question Hi all: I think figured out my solution. While this didn't work: E:\WINNT4>f:\python22\python foo.py f:\python22\python: can't open file 'foo.py' This worked (though I'm not sure why): E:\WINNT4>f:\python22\foo.py - Stuart ---------------------- Forwarded by Stuart Clemons/Westford/IBM on 05/28/2002 12:03 PM --------------------------- Stuart Clemons 05/28/2002 11:08 AM To: tutor@python.org cc: Subject: Python from WINNT command line question Hi: Python 2.2 is installed in f:\ptython22, as are my .py program files. I can run my programs with no problem from the f:\python22 directory. However, when I try to run them from another drive\directory, I get a "can't open file foo.py" error. I tried setting the path and PYTHONPATH environment as shown below. What do I need to do to make this work ? Thanks, E:\WINNT4>path PATH=f:\python22;f:\python22\lib E:\WINNT4>set PYTHONPATH PYTHONPATH=f:\python22\lib E:\WINNT4>f:\python22\python foo.py f:\python22\python: can't open file 'foo.py' E:\WINNT4> --0__=0ABBE154DFCB88D58f9e8a93df938690918c0ABBE154DFCB88D5 Content-type: text/html; charset=US-ASCII Content-Disposition: inline

OK,

I can run my program, foo.py, from any NT command line like this.

c:\>f:\python22\foo.py

which returns, "this is foo"

So, now I want to pipe the output of foo.py to a file, spam.txt. So I use this command line:

c:\>f:\python22\foo.py > spam.txt

What happens is that spam.txt is created, but it is empty (it should contain "this is foo")

If I run my program, foo.py, from the python directory and pipe it, it directs the output to the spam.txt file correctly.

f:\python22> foo.py > spam.txt
f:\python22> type spam.txt
this is foo

What do I need to do to redirect output when I run my python program from the non-Python installed directory ?

Thanks,

- Stuart
---------------------- Forwarded by Stuart Clemons/Westford/IBM on 05/28/2002 12:16 PM ---------------------------

To: tutor@python.org
cc:
Subject: re: Python from WINNT command line question

Hi all:

I think figured out my solution.

While this didn't work:

E:\WINNT4>f:\python22\python foo.py

f:\python22\python: can't open file 'foo.py'

This worked (though I'm not sure why):

E:\WINNT4>f:\python22\foo.py

- Stuart

---------------------- Forwarded by Stuart Clemons/Westford/IBM on 05/28/2002 12:03 PM ---------------------------

To: tutor@python.org
cc:
Subject: Python from WINNT command line question

Hi:

Python 2.2 is installed in f:\ptython22, as are my .py program files. I can run my programs with no problem from the f:\python22 directory.

However, when I try to run them from another drive\directory, I get a "can't open file foo.py" error.

I tried setting the path and PYTHONPATH environment as shown below.

What do I need to do to make this work ? Thanks,


E:\WINNT4>path
PATH=f:\python22;f:\python22\lib

E:\WINNT4>set PYTHONPATH
PYTHONPATH=f:\python22\lib

E:\WINNT4>f:\python22\python foo.py

f:\python22\python: can't open file 'foo.py'

E:\WINNT4>



--0__=0ABBE154DFCB88D58f9e8a93df938690918c0ABBE154DFCB88D5-- From alan.gauld@bt.com Tue May 28 17:17:39 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 28 May 2002 17:17:39 +0100 Subject: [Tutor] Importing file data into Python arrays Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C625@mbtlipnt02.btlabs.bt.co.uk> > So many of these anti-eval() arguments boil down to > reasoning like: one shouldn't be allowed to use knives, > because one might cut one's own wrists (or throat) > with them. No, its more like you shouldn't keep guns lying around coz somebody else might get their hands on it and shoot you... Consider the case where somebody presents a file containing something like "open('autoexec.bat','w')" The eval() will duly evaluate that to a file object and in the process wipe autoexec.bat (or any other system file you care to name!). > That argument only makes sense if you presume a > self-destructive programmer (or a completely inept > one), in which case there a many more direct ways > to wreak havoc. Its not usually the programmer we worry about but the end users of our programs. Alan g From alan.gauld@bt.com Tue May 28 17:22:21 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 28 May 2002 17:22:21 +0100 Subject: [Tutor] hi Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C626@mbtlipnt02.btlabs.bt.co.uk> > All im basically asking is if someone could explain to me how > to use def and when to use it. also how to use modules and > when to use them. Hi again, I sent you a direct email this morning hopefully you've now received it and it makes sense. Tutor is a good place to ask for alternative (maybe clearer!) answers than I can give, but you do need to be a bit more specific. What exactly don't you understand about def? Is it the syntax or the purpose? Is it the concept of functions/modules? The more specific the question the better chance of getting the right answer. OTOH, If you are completely puzzled then maybe a general answer will lead to more specific issues later. I won't repeat my earlier mail here (it was long) but if you still have questions please come back to us. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Tue May 28 17:27:51 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 28 May 2002 17:27:51 +0100 Subject: [Tutor] Python from WINNT command line question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C627@mbtlipnt02.btlabs.bt.co.uk> > Python 2.2 is installed in f:\ptython22, as are my .py > program files. I > E:\WINNT4>path > PATH=f:\python22;f:\python22\lib So this means you don't need the full path when calling python itself > E:\WINNT4>set PYTHONPATH > PYTHONPATH=f:\python22\lib And thismeans you can import your files into python scripts located elsewhee. > E:\WINNT4>f:\python22\python foo.py But foo.py is not visible because its in your python directory... Try: E:\WINNT4>python f:\python22\foo.py instead. This uses the PATYH to call Python. The explicit path to tell python where the top level script is and foo.py then uses PYTHONPATH to find the files it imports. Hopefully that makes sense(and works!) Alan G. From dman@dman.ddts.net Tue May 28 17:13:08 2002 From: dman@dman.ddts.net (dman) Date: Tue, 28 May 2002 11:13:08 -0500 Subject: [Tutor] Com & Python In-Reply-To: <000001c20620$ad8acc70$6500000a@goodweather.co.uk> References: <000001c20620$ad8acc70$6500000a@goodweather.co.uk> Message-ID: <20020528161308.GC26083@dman.ddts.net> --FsscpQKzF/jJk6ya Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, May 28, 2002 at 09:21:31AM +0100, David wrote: | Looking for any pointers on working with some com objects! I haven't done any more with COM than "hello world", but maybe something here will help you figure it out : | Problem is I have code in python which can do basic things with the | object but I'm having problems when it returns a collection object I | want to iterate through...can seem to get anywhere; bummer is I have | working code in vbscript but that lets me down in other areas hence why | I wanted to use python... |=20 |=20 | Python excerpt: =20 | #works ok up to here - sets the above values correctly | # At this point can't work out how to get data out of this | # collections object!!!!!... ??? objApplication.Sessions ???? | # Have tried just printing it doing=20 | for x in objApplication.Sessions | # And just get error's You should always include the exact error message you receive. There are many many things that can cause "errors", and it helps to not have to guess. Anyways, my guess is that the COM object you are using doesn't follow the interface python requires for a "for" loop. Which version of python are you using? These semantics changed a bit in 2.2. Prior to python 2.2 here is the equivalent code that python effectively uses to implement a "for" loop :=20 _index =3D 0 while 1 : try : x =3D objApplication.Sessions[_index] except IndexError : # end of the list, stop now break _index +=3D 1 This means that the object must support indexing or else it can't be used in a python 'for' loop. My guess is that if you write objApplication.Sessions[0] you'll get the same errors, but I'd need to see the error message to be sure. In python 2.2 and beyond, python first tries the new iterator protocol but falls back to the old mechanism for backwards compatibility. The iterator protocol basically works like this : # get an iterator from the object _iter =3D iter( objApplication.Sessions ) while 1 : try : x =3D _iter.next() except StopIteration : # this means we're done break | Just wondering if I'm being really thick and missing some obvious about | working with com collections? | Working vscript | For Each bSession In bApplication.Sessions How does VB handle a "For" loop? (I've never done VB programming) I think this is the key to solving your problem. If you can find out how VB implements a for loop then you'll know the interface to use to iterate over your object. For example, Java 1.1 collections use the "Enumerator" interface for iteration. That interface is rather similar to python's iterator interface, except that the java language has no direct support for it (thus you _have_ to write the equivalent "while" loop with all the associated boilerplate code). If you try and use a python for loop (eg through jython) it won't work. HTH, -D --=20 Pride only breeds quarrels, but wisdom is found in those who take advice. Proverbs 13:10 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --FsscpQKzF/jJk6ya Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzzrJQACgkQO8l8XBKTpRSBBACeLa55cn8P78WsJKz0WpxeoycN u/8AniApE5sjCZzQPvPp6ALEOI74JUau =bJlC -----END PGP SIGNATURE----- --FsscpQKzF/jJk6ya-- From alan.gauld@bt.com Tue May 28 17:31:52 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 28 May 2002 17:31:52 +0100 Subject: [Tutor] re: Python from WINNT command line question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C628@mbtlipnt02.btlabs.bt.co.uk> > I think figured out my solution. > This worked (though I'm not sure why): > E:\WINNT4>f:\python22\foo.py This worked because you provided the full path to the .py file and windows file associations told it to run python to execute the file. Since the path to python is set as part of the association it knows how to find python. This exactly the same(*) as when you double click the foo.py file in explorer. (*)ISTR Tim Peters once explaining a subtle difference between how Exploder does it and how DOS does it but the basic principle is the same... Alan G From dyoo@hkn.eecs.berkeley.edu Tue May 28 18:01:29 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 May 2002 10:01:29 -0700 (PDT) Subject: [Tutor] Com & Python In-Reply-To: <000001c20620$ad8acc70$6500000a@goodweather.co.uk> Message-ID: On Tue, 28 May 2002, David wrote: > Looking for any pointers on working with some com objects! Hi David, I'm not sure if many of us here are familiar with Win32/COM stuff. If you don't get a good answer from us, you may want to email the python-win32 list on this one. Here's their link: http://mail.python.org/mailman/listinfo/python-win32 > print objApplication.EnableApp > #works ok up to here - sets the above values correctly > #At this point can't work out how to get data out of this collections > object!!!!!... > ??? objApplication.Sessions ???? > Have tried just printing it doing > for x in objApplication.Sessions > And just get error's If you can report on the error message as well, that will be helpful for people, since it might give a hint why the approach isn't quite working. There are two potential errors I can think might happen at this point: AttributeError --- it doesn't know 'objApplication.Sessions'. Perhaps the variable has a different name. TypeError --- 'objApplication.Sessions' isn't a Python sequence. (Dunno what to do in this case.) If you can tell us which one of the errors pops up, we might be able to hunt down more information about this. Anyway, good luck! From dman@dman.ddts.net Tue May 28 22:57:16 2002 From: dman@dman.ddts.net (dman) Date: Tue, 28 May 2002 16:57:16 -0500 Subject: [Tutor] Importing file data into Python arrays In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C624@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C624@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020528215716.GA31554@dman.ddts.net> --EeQfGwPcQSOJBaQU Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, May 28, 2002 at 05:11:42PM +0100, alan.gauld@bt.com wrote: =2E.. =20 | nums =3D map(int,nums) # convert to integers | for n in nums: arr.append(n) # add to your array Since nums and arr are both lists this can be shortened to arr.extend( nums ) # add to your array | I suspect there are cleverer ways of doing this with=20 | less code but the above should be clear? Now that you mention it, how about : for line in f.xreadlines(): arr.extend( [ int(n) for n in line.strip().split() ] ) ? if you're using python 2.2 you can get away with for line in f : as the first line. (In v2.2, file objects support the iterator protocol, and the 'for' implementation uses it) This is an attempt to achieve compactness, not readability. IMO it would be better to use some temp variables and multiple lines in production code, such as Alan presented (but use extend() rather than the equivalent loop). -D --=20 Many are the plans in a man's heart, but it is the Lord's purpose that prevails. Proverbs 19:21 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --EeQfGwPcQSOJBaQU Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjzz/TwACgkQO8l8XBKTpRTCfgCgxvFF+StEjZ0HmVsiuKTUq/y1 lp8AnjDMd4XzEDmfakRa15/WRUiguWuI =NeL+ -----END PGP SIGNATURE----- --EeQfGwPcQSOJBaQU-- From phthenry@earthlink.net Tue May 28 22:00:31 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue, 28 May 2002 17:00:31 -0400 Subject: [Tutor] Help with Temperature Program Message-ID: <20020528170030.L16955@localhost.localdomain> Wow, this advice is neat! I an see myself using this. I would never have known how to do this without this message. I try to look at most of the messages on this mailing list, and have picked up some good advice. Paul ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From chrisl@frodo.thethirdsector.com Wed May 29 01:38:00 2002 From: chrisl@frodo.thethirdsector.com (Chris Lott) Date: Tue, 28 May 2002 16:38:00 -0800 Subject: [Tutor] Help me Be Pythonic Message-ID: <027e01c206a9$16b64980$847c97d0@thethirdsector.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I have started to learn Python and written my first little app that takes a file of names (or a list on the command line) and checks to see which of the .com/.org/.net/.info domains are available using urllib to grab data from web forms. However, my code is very procedural. No functions and no objects of my own. In pseudo code, how can I think about this task like a python programmer. Would I have a urlcheck object that was passed the data and checked for different types? What's the pythonic way to: open file or command line arguments check url for .com if text found print "succes" else print "unavailable" check url for .org if text found print "succes" else print "unavailable" etc? c -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (MingW32) - GPGshell v2.30 Comment: Key ID: 0x51046CFD iD8DBQE89CLk1oth6FEEbP0RAmMAAJ9n6hFJsBIo7K12ct5mwHAG8tlpMACff5BI rZr6OR2br+PeSAayUtYucL0= =0Fyc -----END PGP SIGNATURE----- From chrisl@frodo.thethirdsector.com Wed May 29 01:57:16 2002 From: chrisl@frodo.thethirdsector.com (Chris Lott) Date: Tue, 28 May 2002 16:57:16 -0800 (AKDT) Subject: [Tutor] separating logic from html in web apps Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 What programming I know has largely been in Cold Fusion, PHP and Perl for system admin type tasks and some basic form CGI.I have repeatedly been told how desirable it is to use a programming language like Perl or Python that allows one to separate code from HTML in web applications. This is very counter-intuitive to me (probably because of the tools I learned with). For example, let's say that I have a db and I want to publish it in five different formats for HTML, XML, WAP, RDF and who knows what else. In the PHP way, I would have five different templates, or one template with five conditional blocks, each of which output one of these versions. What would I save using Python and CGI or mod_python? I still have to have five different conditional blocks or objects or something to create the output, I've lost the utility to edit HTML in an editor (which is nice occasionally) or to validate the code as it sits, and I have to go through the process of escaping special characters for all of my HTML output... I don't get why it is better except in THEORY. But many things in theory don't prove to be so in the real world. I am sure this is just a misunderstanding on my part! c -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: PGP Signed/Encrypted for Authentication/Privacy iD8DBQE89Cdy1oth6FEEbP0RAtYpAJ9aOsqeWIVD7h1mnkE4RrJryxsBLwCfS9V7 GzJp5s0oTITjFGSwiWTFrk8= =V9A+ -----END PGP SIGNATURE----- From shalehperry@attbi.com Wed May 29 02:44:17 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 28 May 2002 18:44:17 -0700 (PDT) Subject: [Tutor] Help me Be Pythonic In-Reply-To: <027e01c206a9$16b64980$847c97d0@thethirdsector.com> Message-ID: > > In pseudo code, how can I think about this task like a python > programmer. Would I have a urlcheck object that was passed the > data and checked for different types? What's the pythonic way > to: > > open file or command line arguments > check url for .com > if text found print "succes" > else print "unavailable" > check url for .org > if text found print "succes" > else print "unavailable" > for name on command line: for type in (com, net, org): if name_exists('name.type'): print yes else: print no def name_exists(name): do stuff here is pseudo code of how I would approach it. From ak@silmarill.org Wed May 29 02:54:02 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Tue, 28 May 2002 21:54:02 -0400 Subject: [Tutor] Help me Be Pythonic In-Reply-To: <027e01c206a9$16b64980$847c97d0@thethirdsector.com> References: <027e01c206a9$16b64980$847c97d0@thethirdsector.com> Message-ID: <20020529015402.GA10271@ak.silmarill.org> On Tue, May 28, 2002 at 04:38:00PM -0800, Chris Lott wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I have started to learn Python and written my first little app > that takes a file of names (or a list on the command line) and > checks to see which of the .com/.org/.net/.info domains are > available using urllib to grab data from web forms. > > However, my code is very procedural. No functions and no objects > of my own. > > In pseudo code, how can I think about this task like a python > programmer. Would I have a urlcheck object that was passed the > data and checked for different types? What's the pythonic way > to: > > open file or command line arguments > check url for .com > if text found print "succes" > else print "unavailable" > check url for .org > if text found print "succes" > else print "unavailable" > You could do: for top_lev_domain in (".com", ".org" ...): print top_lev_domain if text found print "success" else print "unavailable" Furthermore, you could wrap some code in a function. For instance: def is_available(domain): [check if domain is avaiable] if yes: return 1 else: return 0 Once you do that, you may use this function from a different program simply by doing: import module; module.is_available(domain) - Andrei > etc? > > c > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.0.7 (MingW32) - GPGshell v2.30 > Comment: Key ID: 0x51046CFD > > iD8DBQE89CLk1oth6FEEbP0RAmMAAJ9n6hFJsBIo7K12ct5mwHAG8tlpMACff5BI > rZr6OR2br+PeSAayUtYucL0= > =0Fyc > -----END PGP SIGNATURE----- > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From kevinchristy@socal.rr.com Wed May 29 03:02:08 2002 From: kevinchristy@socal.rr.com (Kevin Christy) Date: Tue, 28 May 2002 19:02:08 -0700 Subject: [Tutor] Web client in Python In-Reply-To: Message-ID: Dear folks: I visit a website frequently that requires a login each time I enter it. Typically, I log in, navigate to the search page, and input a search term. The results are then displayed on a page. I'd like to automate the whole process and redirect the output to a tab-delimited file for ease of manipulation. Is there a way that you know of to "log" my session so that I can see what actually happens behind the scenes (in other words, what the browser and server are passing back and forth to each other)? That would help me automate the process. Thanks! Kevin From erikprice@mac.com Wed May 29 03:31:48 2002 From: erikprice@mac.com (Erik Price) Date: Tue, 28 May 2002 22:31:48 -0400 Subject: [Tutor] Web client in Python In-Reply-To: Message-ID: <39B8E9E9-72AC-11D6-9CD6-00039351FE6A@mac.com> On Tuesday, May 28, 2002, at 10:02 PM, Kevin Christy wrote: > Is there a way that you know of to "log" my session so that I can see > what > actually happens behind the scenes (in other words, what the browser and > server are passing back and forth to each other)? That would help me > automate the process. Thanks! If you are using Unix (/Linux/OSX), there are two programs that are available to do exactly this: tcpdump (captures summary of TCP packets) and tcpflow (captures the actual data those packets are carrying -- inotherwords, probably more useful to what you want to do). It's pretty cool, you can just sit there and monitor port 80 on your (or actually anyone else's) machine, or any other port, or redirect it to a file, etc. Very very instructive in showing exactly what HTTP messages are being passed along (GET/POST/COOKIE vars, etc) during your browser session. Can be used for Dark purposes, do not abuse this knowledge. Search google for a download. There is no doubt an equivalent program for Win systems if that is your preferred poison, do some hunting. Erik From kauphlyn@speakeasy.org Wed May 29 04:20:27 2002 From: kauphlyn@speakeasy.org (Daniel Coughlin) Date: Tue, 28 May 2002 20:20:27 -0700 (PDT) Subject: [Tutor] Web client in Python In-Reply-To: <39B8E9E9-72AC-11D6-9CD6-00039351FE6A@mac.com> Message-ID: And if you are using windows you can use Ethereal for the same purposes. http://www.ethereal.com Usually you dont need to do all that, though. Look at the the page source for your login page. There is probably an html form on that page that has input tags such as . If you are lucky, you can get away with using urllib like so: import urllib #note the field names are probably not named 'username' and 'password' data = urllib.urlencode('username':'yourusername', 'password':'yourpassword') urlfile = urllib.urlopen('http://www.yourdomain.com',data) html = urlfile.readlines() html will now be a list of lines of page source returned after you post your username and password. Now if your site uses cookie based authentication, it will be a little trickier. You will need to extract the cookie from the headers returned in the section above using a command like this cookie = urlfile.headers.getheader("set-cookie") Then add this to the headers of future requests using the urllib2 module. Hope this helps, Daniel On Tue, 28 May 2002, Erik Price wrote: > > On Tuesday, May 28, 2002, at 10:02 PM, Kevin Christy wrote: > > > Is there a way that you know of to "log" my session so that I can see > > what > > actually happens behind the scenes (in other words, what the browser and > > server are passing back and forth to each other)? That would help me > > automate the process. Thanks! > > If you are using Unix (/Linux/OSX), there are two programs that are > available to do exactly this: tcpdump (captures summary of TCP packets) > and tcpflow (captures the actual data those packets are carrying -- > inotherwords, probably more useful to what you want to do). > > It's pretty cool, you can just sit there and monitor port 80 on your (or > actually anyone else's) machine, or any other port, or redirect it to a > file, etc. Very very instructive in showing exactly what HTTP messages > are being passed along (GET/POST/COOKIE vars, etc) during your browser > session. > > Can be used for Dark purposes, do not abuse this knowledge. Search > google for a download. There is no doubt an equivalent program for Win > systems if that is your preferred poison, do some hunting. > > > Erik > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Wed May 29 06:32:06 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 May 2002 22:32:06 -0700 (PDT) Subject: [Tutor] Help me Be Pythonic [fileinput / find() and boundary conditions] In-Reply-To: <027e01c206a9$16b64980$847c97d0@thethirdsector.com> Message-ID: On Tue, 28 May 2002, Chris Lott wrote: > In pseudo code, how can I think about this task like a python > programmer. Would I have a urlcheck object that was passed the data and > checked for different types? What's the pythonic way to: > > open file or command line arguments ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Perl uses some magic symbol to do this (I think it was '<>', but I need to double check). In Python, this functionality is in the 'fileinput' module: http://www.python.org/doc/lib/module-fileinput.html and it allows us to easily take stuff from either standard input or from the files listed in command line arguments. Let's take a look at the rest of the pseudocode: > check url for .com > if text found print "succes" > else print "unavailable" > check url for .org > if text found print "succes" > else print "unavailable" Hmmm... if we use 'fileinput', our code skeleton might look something like this: ### import fileinput for url in fileinput.input(): if url.find('.com') >= 0: print "success" else: print "unavailable" if url.find('.org') >= 0: print "success" else: print "unavailable" ### This has the potential of printing "unavailable" twice, so we may want to think if this is what we really want. Otherwise, the pseudocode and the Python code actually turn out to be pretty darn close. *grin* One side note for people new to string find()ing: One oddity about the code above is that we're doing a '>=' check. That is, it's not just positive numbers that we're looking out for, but also zero! In technical terms, we're checking for a "non-negative" value, and it might seem funny why. Does it matter? The reason for this is because find() will return -1 if it can't find the string we're looking for. For example, if we play around with find() in the interactive interpreter: ### >>> 'supercalifragilisticexpialidocious'.find('ice') 18 >>> 'supercalifragilisticexpialidocious'.find('cream') -1 >>> 'supercalifragilisticexpialidocious'.find('super') 0 ### we can see that 0 is a perfectly good value for find(). I have a question: why does the program focus on '.com' and '.org' addresses? Talk to you later! From dyoo@hkn.eecs.berkeley.edu Wed May 29 06:41:24 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 May 2002 22:41:24 -0700 (PDT) Subject: [Tutor] Web client in Python In-Reply-To: Message-ID: On Tue, 28 May 2002, Kevin Christy wrote: > Dear folks: > > I visit a website frequently that requires a login each time I enter it. > Typically, I log in, navigate to the search page, and input a search term. Sounds like you're thinking of writing a web robot. Interesting project! It's very possible that the server sends off a cookie to your computer, so that it can keep track of the login stuff. The 'Cookie' module is pretty good at keeping this information, and you might find it useful: http://python.org/doc/lib/module-Cookie.html Another module that you might find useful is the httplib library, which allows your Python to communicate to a server as if it were a web browser. http://python.org/doc/lib/module-httplib.html http://python.org/doc/lib/httplib-examples.html With these two modules, I think it's possible to cook something up to allow your program to work. > Is there a way that you know of to "log" my session so that I can see what > actually happens behind the scenes (in other words, what the browser and > server are passing back and forth to each other)? That would help me > automate the process. Thanks! This one I'm not quite so sure about. Good luck to you! From shalehperry@attbi.com Wed May 29 06:54:51 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 28 May 2002 22:54:51 -0700 (PDT) Subject: [Tutor] Help me Be Pythonic [fileinput / find() and bounda In-Reply-To: Message-ID: > > The reason for this is because find() will return -1 if it can't find the > string we're looking for. For example, if we play around with find() in > the interactive interpreter: > so why not do: if find() != -1? From dyoo@hkn.eecs.berkeley.edu Wed May 29 07:19:35 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 28 May 2002 23:19:35 -0700 (PDT) Subject: [Tutor] Help me Be Pythonic [logic and readability] In-Reply-To: Message-ID: On Tue, 28 May 2002, Sean 'Shaleh' Perry wrote: > > The reason for this is because find() will return -1 if it can't find > > the string we're looking for. For example, if we play around with > > find() in the interactive interpreter: > > > > so why not do: > > > if find() != -1? Hi Sean, This also works well. Since find() returns either '-1' if it can't find the target string, or something else (the position) if it does find something, we can compose the logic in several ways that'll work. I feel that the important part is to be consistant; it would probably not be a good thing to do it one way, and then switch over to the other, at least, not without good reasons. What I mean is that something like: ### for url in fileinput.input(): if url.find('.com') >= 0: print "success" else: print "unavailable" if url.find('.org') != -1: print "success" else: print "unavailable" ### would look a little off to me. Even though the logic is impeccable, the different process toward getting at it is somewhat jarring, at least to my eyes. Even "worse" from a (subjective) consistancy standpoint might be: ### for url in fileinput.input(): if url.find('.com') >= 0: print "success" else: print "unavailable" if url.find('.org') == -1: print "unavailable" else: print "success" ### ... Although it does have a certain... symmetry to it... still, I don't like it! It just feels like it... "bounces" to me, in a way that it doesn't need to. At least in Python, I like code to flow quietly. These are purely subjective, irrational terms, but that's just how it feels to me. *grin* Talk to you later! From alex@gabuzomeu.net Wed May 29 09:49:09 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Wed, 29 May 2002 10:49:09 +0200 Subject: [Tutor] separating logic from html in web apps In-Reply-To: <20020529014549.2133.67253.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020529102557.00d8f6e0@pop3.norton.antivirus> Hello Chris, At 21:45 28/05/2002 -0400, you wrote: >Date: Tue, 28 May 2002 16:57:16 -0800 (AKDT) >From: Chris Lott >Subject: [Tutor] separating logic from html in web apps >What programming I know has largely been in Cold Fusion, PHP and Perl >for system admin type tasks and some basic form CGI.I have repeatedly >been told how desirable it is to use a programming language like Perl >or Python that allows one to separate code from HTML in web >applications. I'm writing a Web app as a learning project; in this app, I try to put as little logic as possible in the HTML templates. Basically, I prepare data as much as possible at the Python level and I use templates for display only. These templates may still contain loops and conditions. I use the Cheetah Python templating system: http://www.cheetahtemplate.org/ >For example, let's say that I have a db and I want to publish it in >five different formats for HTML, XML, WAP, RDF and who knows what >else. In the PHP way, I would have five different templates, or one >template with five conditional blocks, each of which output one of >these versions. I would also use 5 different templates and customize data as much as possible at the Python level. Also, with an object-oriented templating system, you might try and write a general template and specialize it through inheritance. >I still have to have five different conditional blocks or objects or >something to create the output, I've lost the utility to edit HTML in an editor >(which is nice occasionally) If you use templates, you can edit HTML in text editors and possibly in WYSIWYG editors. However, I would store as little logic as possible in the HTML code. For instance, I would not store data access code, SQL queries code, etc. right in the HTML pages. I'm not sure how it is usually done in PHP. Still, I find it complex to fully separate logic and HTML. In some case, it's easier to generate HTML from Python, instead of inserting values in HTML templates. In my app, I ended up doing both. Ideas are welcome. Cheers. Alexandre From alex@gabuzomeu.net Wed May 29 10:04:26 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Wed, 29 May 2002 11:04:26 +0200 Subject: [Tutor] Help me Be Pythonic In-Reply-To: <20020529014549.2133.67253.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020529105446.00d6f380@pop3.norton.antivirus> At 21:45 28/05/2002 -0400, you wrote: >From: "Chris Lott" >Date: Tue, 28 May 2002 16:38:00 -0800 >Subject: [Tutor] Help me Be Pythonic >I have started to learn Python and written my first little app >that takes a file of names (or a list on the command line) and >checks to see which of the .com/.org/.net/.info domains are >available using urllib to grab data from web forms. >In pseudo code, how can I think about this task like a python >programmer. Would I have a urlcheck object that was passed the >data and checked for different types? I would use a URLChecker class that is passed data. You might pass it a name and a list of types to check. I would probably use two classes: a Checker (that carries out the actual checks) and a CheckerApp (that drives checks using the first class and print out results). Cheers. Alexandre From mike@lamertz.net Wed May 29 11:09:43 2002 From: mike@lamertz.net (Michael Lamertz) Date: Wed, 29 May 2002 12:09:43 +0200 Subject: [Tutor] separating logic from html in web apps In-Reply-To: References: Message-ID: <20020529100943.GA30823@lamertz.net> On Tue, May 28, 2002 at 04:57:16PM -0800, Chris Lott wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > What programming I know has largely been in Cold Fusion, PHP and Perl > for system admin type tasks and some basic form CGI.I have repeatedly > been told how desirable it is to use a programming language like Perl > or Python that allows one to separate code from HTML in web > applications. Separating the content from the presentation is a design decision, and not really dependend of the underlying language. > This is very counter-intuitive to me (probably because of the tools I > learned with). Different thinking perhaps, but not counter-intuitive. Look below... > For example, let's say that I have a db and I want to publish it in > five different formats for HTML, XML, WAP, RDF and who knows what > else. In the PHP way, I would have five different templates, or one > template with five conditional blocks, each of which output one of > these versions. And here's the point: Imagine modifying your database model. Now you have to update 5 sections of code. Besides of that, all your pages are a mess since they contain code blocks for 5 different languages. Once you start figuring out the common parts of a page * Process query * Fetch data from database * Manage usersession * Whatelse... which are completely independend of the media you're viewing, you can pull that functionality out of your pages and encapsule it somewhere else. Now you have common code that needs only to be modified at one spot if anything changes in your concepts. Now, if you're using a more or less strong templating system - of which are a vast variety available for all kind of languages - the only thing left to do is to tell it which template to feed the data into and you're done. > What would I save using Python and CGI or mod_python? I still have to > have five different conditional blocks or objects or something to > create the output, I've lost the utility to edit HTML in an editor > (which is nice occasionally) or to validate the code as it sits, and I > have to go through the process of escaping special characters for all > of my HTML output... Nope, you're still thinking in mixing code and HTML. First you had code embedded in HTML - the PHP-Way (tm) - now you just want to turn this around, but that's not what's meant here. The code really does only the thing that needs to be done in code: * Calculations * Database access * Session management * ... All the rest is done in a template system. Since you already know PHP, think of it like this (Caveman's approach to templating): Put all your preparation code into an include file which you load at the beginning of each page. Then try to do as much in plain HTML as you can, with the exception of stuff like loops and variable insertion. If you feel the need to program more complex stuff put that again into the include file, since you most likely will need it for the other output formats too. > I don't get why it is better except in THEORY. But many things in > theory don't prove to be so in the real world. I am sure this is just > a misunderstanding on my part! Perhaps I've made it a bit clearer? PS: I intentionally avoided python here since your problem is IMO completely generic and language independend. Give it a try with the tools you're used. If you feel you have grasped the concept and still think you need to change the framework take a look at options like Perl and Python... -- If we fail, we will lose the war. Michael Lamertz | +49 221 445420 / +49 171 6900 310 Nordstr. 49 | mike@lamertz.net 50733 Cologne | http://www.lamertz.net Germany | http://www.perl-ronin.de From adi.clepcea@sysrom.ro Wed May 29 12:48:29 2002 From: adi.clepcea@sysrom.ro (Adi Clepcea) Date: Wed, 29 May 2002 14:48:29 +0300 (E. Europe Daylight Time) Subject: [Tutor] MDI Message-ID: <3CF4C00D.000005.01148@adi-clepcea> --------------Boundary-00=_TGFV6RO0000000000000 Content-Type: Text/Plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, Is it possible to create a MDI window in Python using Tkinter? TIA Adi --------------Boundary-00=_TGFV6RO0000000000000 Content-Type: Text/HTML; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
Is it possible to create a MDI window in Python using Tkinter?=
TIA
Adi
=09 =09 =09 =09 =09 =09 =09
_________________________________________________
IncrediMail - Email has finally= =20 evolved -
Click=20 Here
--------------Boundary-00=_TGFV6RO0000000000000-- From pythontutor@venix.com Wed May 29 13:46:52 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 29 May 2002 08:46:52 -0400 Subject: [Tutor] Web client in Python References: Message-ID: <3CF4CDBC.4040405@venix.com> (For those of us who keep these messages sorted by thread, it is best to use a new message for a new thread. A reply goes to the existing thread.) Python Web programming includes a short sample program called: proxysample.py It is based mostly on the asynchat module. It mostly does what you want. It does not understand HTTP and attempts to use '\n' as an end of buffer indicator (since it doesn't know how to read the HTTP size header). So long as you are dealing with text it will be quite useable. You can download it from: http://pydish.holdenweb.com/pwp/ Python Web Programming: Home Page I spent some time writing my own little proxy to do just what you want using the CGIHTTPServer module and urllib. I can't find it now :-( Kevin Christy wrote: > Dear folks: > > I visit a website frequently that requires a login each time I enter it. > Typically, I log in, navigate to the search page, and input a search term. > The results are then displayed on a page. I'd like to automate the whole > process and redirect the output to a tab-delimited file for ease of > manipulation. > > Is there a way that you know of to "log" my session so that I can see what > actually happens behind the scenes (in other words, what the browser and > server are passing back and forth to each other)? That would help me > automate the process. Thanks! > > Kevin > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From kevinchristy@socal.rr.com Wed May 29 14:44:21 2002 From: kevinchristy@socal.rr.com (Kevin Christy) Date: Wed, 29 May 2002 06:44:21 -0700 Subject: [Tutor] Web client in Python In-Reply-To: Message-ID: Thanks to all who responded. I will post the code once it gets the job done; I am not getting successful logins, perhaps because of the cookie issue. The HTTP server is generating a hidden, temporary session ID code that may be the problem. Kevin > On Tuesday, May 28, 2002, at 10:02 PM, Kevin Christy wrote: > > > Is there a way that you know of to "log" my session so that I can see > > what > > actually happens behind the scenes (in other words, what the browser and > > server are passing back and forth to each other)? That would help me > > automate the process. Thanks! > > If you are using Unix (/Linux/OSX), there are two programs that are > available to do exactly this: tcpdump (captures summary of TCP packets) > and tcpflow (captures the actual data those packets are carrying -- > inotherwords, probably more useful to what you want to do). > > It's pretty cool, you can just sit there and monitor port 80 on your (or > actually anyone else's) machine, or any other port, or redirect it to a > file, etc. Very very instructive in showing exactly what HTTP messages > are being passed along (GET/POST/COOKIE vars, etc) during your browser > session. > > Can be used for Dark purposes, do not abuse this knowledge. Search > google for a download. There is no doubt an equivalent program for Win > systems if that is your preferred poison, do some hunting. > > > Erik > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From shendric@arches.uga.edu Wed May 29 16:56:24 2002 From: shendric@arches.uga.edu (shendric@arches.uga.edu) Date: Wed, 29 May 2002 10:56:24 -0500 Subject: [Tutor] Bindings in Tkinter Message-ID: <1022684184.smmsdV1.1.1@mail.arches.uga.edu> Hello, I'm having difficulty with bindings, but I'm not real sure what I'm doing wrong. The following is a small bit of code that is part of a larger app that I'm working on. The idea is to simply bind the key to a little printing function, but it does nothing at all. The larger app actually contains things within the frames that are created, but I left them out of this for convenience and brevity. Any ideas? Sean Hendricks from Tkinter import * import Pmw class VTrans: def __init__(self, master): self.master = master self.frame = Frame(master) self.frame.top = Frame(master) self.frame.bottom = Frame(master) self.frame.top.pack(side=TOP, fill=X) self.frame.bottom.pack(side=TOP) self.frame.pack() self.getBindings() def doStuff(self, event=None): print "I am the very model of a ..." def getBindings(self): self.frame.top.bind('', self.doStuff) if __name__ == "__main__": root = Tk() root.title('Test') Pmw.initialise() main = VTrans(root) root.mainloop() From alex@gabuzomeu.net Wed May 29 17:44:09 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Wed, 29 May 2002 18:44:09 +0200 Subject: [Tutor] Web client in Python In-Reply-To: <20020529160012.14853.42592.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020529183339.00c5d7f0@pop3.norton.antivirus> Hi Kevin, At 12:00 29/05/2002 -0400, you wrote: >From: "Kevin Christy" >Subject: RE: [Tutor] Web client in Python >Date: Wed, 29 May 2002 06:44:21 -0700 > >Thanks to all who responded. I will post the code once it gets the job >done; I am not getting successful logins, perhaps because of the cookie >issue. The HTTP server is generating a hidden, temporary session ID code >that may be the problem. If the site uses cookies to store the temporary session ID, these resources might be useful: 1) "Cookie Spy": it's a free Internet Explorer plug-in that displays cookie values while browsing. It helped me work around a similar login issue. I don't have a URL, but the developer is called Konstantin Boukreev (konstantin@mail.primorye.ru). 2) "clientcookie": this is a Python module. From my snippets: Clientcookie is a Python module for handling cookies on the client side, useful for accessing web sites that require cookies to be set, and returned later. It is a port of Gisle Aas' Perl module HTTP::Cookies, from the libwww-perl library. Both RFC2965 and Netscape cookies are supported. import ClientCookie import urllib2 request = urllib2.Request("http://www.acme.com/") # note we're using the urlopen from ClientCookie, not urllib2 result = ClientCookie.urlopen(request) # let's say this next request requires a cookie that was set in result request2 = urllib2.Request("http://www.acme.com/flying_machines.html") result2 = ClientCookie.urlopen(request2) http://wwwsearch.sourceforge.net/ClientCookie Cheers. Alexandre From rickp@telocity.com Wed May 29 17:40:08 2002 From: rickp@telocity.com (Rick Pasotto) Date: Wed, 29 May 2002 12:40:08 -0400 Subject: [Tutor] Bindings in Tkinter In-Reply-To: <1022684184.smmsdV1.1.1@mail.arches.uga.edu> References: <1022684184.smmsdV1.1.1@mail.arches.uga.edu> Message-ID: <20020529164008.GK21236@tc.niof.net> A couple of points but not necessarily a solution. 1) The window your code produces is too small to see. :-) 2) The widget has to be active for the bindings to work so you can't bind to a widget that is completely covered by other widgets (or too small to make active using the mouse). 3) Try some other binding. After some minor changes I got your code to work with but not with . On Wed, May 29, 2002 at 10:56:24AM -0500, shendric@arches.uga.edu wrote: > Hello, > > I'm having difficulty with bindings, but I'm not real sure what I'm > doing wrong. The following is a small bit of code that is part of a > larger app that I'm working on. The idea is to simply bind the > key to a little printing function, but it does > nothing at all. > > The larger app actually contains things within the frames that are > created, but I left them out of this for convenience and brevity. > > Any ideas? > > Sean Hendricks > > > from Tkinter import * > import Pmw > > class VTrans: > def __init__(self, master): > self.master = master > self.frame = Frame(master) > self.frame.top = Frame(master) > self.frame.bottom = Frame(master) > self.frame.top.pack(side=TOP, fill=X) > self.frame.bottom.pack(side=TOP) > self.frame.pack() > self.getBindings() > > def doStuff(self, event=None): > print "I am the very model of a ..." > > def getBindings(self): > self.frame.top.bind('', self.doStuff) > > if __name__ == "__main__": > root = Tk() > root.title('Test') > Pmw.initialise() > main = VTrans(root) > root.mainloop() -- "Drawing on my fine command of language, I said nothing." -- Mark Twain Rick Pasotto rickp@telocity.com http://www.niof.net From shendric@arches.uga.edu Wed May 29 19:52:12 2002 From: shendric@arches.uga.edu (shendric@arches.uga.edu) Date: Wed, 29 May 2002 13:52:12 -0500 Subject: [Tutor] Bindings in Tkinter Message-ID: <1022694732.smmsdV1.1.1@mail.arches.uga.edu> >A couple of points but not necessarily a solution. > >1) The window your code produces is too small to see. :-) Yeah, since I was just testing it, I didn't bother to make it visible. Ah, well. > >2) The widget has to be active for the bindings to work so you can't >bind to a widget that is completely covered by other widgets (or too >small to make active using the mouse). > >3) Try some other binding. After some minor changes I got your code to >work with but not with . Ok, so I changed the binding to , and made the frame bigger, and it works, but I still can't get it to work with any of the keystroke bindings, only the mouse. Or, at least not with , the - family, or . Seems odd to me. Sean > >On Wed, May 29, 2002 at 10:56:24AM -0500, shendric@arches.uga.edu wrote: >> Hello, >> >> I'm having difficulty with bindings, but I'm not real sure what I'm >> doing wrong. The following is a small bit of code that is part of a >> larger app that I'm working on. The idea is to simply bind the >> key to a little printing function, but it does >> nothing at all. >> >> The larger app actually contains things within the frames that are >> created, but I left them out of this for convenience and brevity. >> >> Any ideas? >> >> Sean Hendricks >> >> >> from Tkinter import * >> import Pmw >> >> class VTrans: >> def __init__(self, master): >> self.master = master >> self.frame = Frame(master) >> self.frame.top = Frame(master) >> self.frame.bottom = Frame(master) >> self.frame.top.pack(side=TOP, fill=X) >> self.frame.bottom.pack(side=TOP) >> self.frame.pack() >> self.getBindings() >> >> def doStuff(self, event=None): >> print "I am the very model of a ..." >> >> def getBindings(self): >> self.frame.top.bind('', self.doStuff) >> >> if __name__ == "__main__": >> root = Tk() >> root.title('Test') >> Pmw.initialise() >> main = VTrans(root) >> root.mainloop() > >-- >"Drawing on my fine command of language, I said nothing." > -- Mark Twain > Rick Pasotto rickp@telocity.com http://www.niof.net > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > ---------End of Included Message---------- From chrisl@frodo.thethirdsector.com Wed May 29 19:26:21 2002 From: chrisl@frodo.thethirdsector.com (Chris Lott) Date: Wed, 29 May 2002 10:26:21 -0800 Subject: [Tutor] separating logic from html in web apps References: <20020529100943.GA30823@lamertz.net> Message-ID: <005101c2073e$554f43a0$5a01a8c0@TRS80> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > Perhaps I've made it a bit clearer? > > PS: I intentionally avoided python here since your problem is IMO > completely generic and language independend. Give it a try with the > tools you're used. If you feel you have grasped the concept and still > think you need to change the framework take a look at options like Perl > and Python... Yes... this is what I already do in PHP. I keep most of my code and functions in exsternal files, including them as needed. However I can't do this in Python (so far) because I don't know of a templating system where I can put ANY code in my HTML, so I have to spit out all of the HTML from my Python scripts. I guess I need to look for some kind of templating system, though it seems like many python people build web apps just fine without them, which is what I am trying to understand. I think :) c -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (MingW32) - GPGshell v2.30 iD8DBQE89R1A1oth6FEEbP0RAlAzAJ47vCh1HDAoBLk6vBmJ3JsmNP6tFQCgzjkS VPnDKfK+Smw66337HU+If2E= =o+Ew -----END PGP SIGNATURE----- From bryce@bembry.org Wed May 29 19:46:44 2002 From: bryce@bembry.org (Bryce Embry) Date: Wed, 29 May 2002 13:46:44 -0500 Subject: [Tutor] Bindings in Tkinter In-Reply-To: <1022684184.smmsdV1.1.1@mail.arches.uga.edu> Message-ID: <5.1.0.14.0.20020529133523.02d2de98@www.bembry.org> Howdy, Not sure if this is the answer, but thought I'd suggest it at least. In order for the keystroke bindings to work, the frame in question has to have the program focus. When using a mouse button click, the button click moves the focus to the frame automatically. For keystrokes to be bound, the widget has to have the focus before the button is pressed. Try binding the keystroke commands to the root / master widget and see if that works (i.e. self.master.bind('', self.doStuff)). There's also a way to make the frame take focus, but I've never tried it. From the notes I have, it looks like you just set the option "takefocus = 1" to the frame widget, i.e. self.frame.top = Frame(master, takefocus = 1). There are also some focus methods available that might help, but I'm not very familiar with them either. Hope something in there helps. Bryce At 10:56 AM 5/29/2002, you wrote: >Hello, > >I'm having difficulty with bindings, but I'm not real sure what I'm >doing wrong. The following is a small bit of code that is part of a >larger app that I'm working on. The idea is to simply bind the > key to a little printing function, but it does >nothing at all. > >The larger app actually contains things within the frames that are >created, but I left them out of this for convenience and brevity. > >Any ideas? > >Sean Hendricks > > >from Tkinter import * >import Pmw > >class VTrans: > def __init__(self, master): > self.master = master > self.frame = Frame(master) > self.frame.top = Frame(master) > self.frame.bottom = Frame(master) > self.frame.top.pack(side=TOP, fill=X) > self.frame.bottom.pack(side=TOP) > self.frame.pack() > self.getBindings() > > def doStuff(self, event=None): > print "I am the very model of a ..." > > def getBindings(self): > self.frame.top.bind('', self.doStuff) > >if __name__ == "__main__": > root = Tk() > root.title('Test') > Pmw.initialise() > main = VTrans(root) > root.mainloop() > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bryce Embry Geek-Of-All-Trades / Master-Of-None www.bembry.org -------------------------------------------------------------------------------------------------------------------------------------------------------- Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 38117 ^ (901)682-2409 -------------------------------------------------------------------------------------------------------------------------------------------------------- From terjeja@hotmail.com Wed May 29 21:03:39 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Wed, 29 May 2002 20:03:39 +0000 Subject: [Tutor] Rounding Message-ID: I am trying to use the round() function. But, it doesn't give me the answers I want: >>>g = 44.444444 >>>g 44.444443999999997 >>>round(g,2) 44.439999999999998 >>>round(g,9) 44.444443999999997 >>>round(g, 2) 44.439999999999998 >>>round(3333.33333, 2) 3333.3299999999999 >>>round(12.345) 12.0 >>>round(12.345, 2) 12.35 >>>round(43.43445353, 2) 43.43 >>>g 44.444443999999997 >>>round(g, 2) 44.439999999999998 Sometimes it works as I want it to work. Other times it doesn't. And why did g become 44.444443999999997, instead of 44.444444 as I typed it in as in the beginning? Can anyone explain for me? Thanks in advance, Terje _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx From dman@dman.ddts.net Wed May 29 22:39:41 2002 From: dman@dman.ddts.net (dman) Date: Wed, 29 May 2002 16:39:41 -0500 Subject: [Tutor] separating logic from html in web apps In-Reply-To: <005101c2073e$554f43a0$5a01a8c0@TRS80> References: <20020529100943.GA30823@lamertz.net> <005101c2073e$554f43a0$5a01a8c0@TRS80> Message-ID: <20020529213941.GA30684@dman.ddts.net> --LZvS9be/3tNcYl/X Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 29, 2002 at 10:26:21AM -0800, Chris Lott wrote: =2E.. | Yes... this is what I already do in PHP. I keep most of my code | and functions in exsternal files, including them as needed. | However I can't do this in Python (so far) because I don't know | of a templating system where I can put ANY code in my HTML, Zope's TAL (which is also available separate from zope) Python Server Pages (PSP) Quixote | so I have to spit out all of the HTML from my Python scripts. That's one way, if you want to use the python parser for your "templates". You could create a template parser (and with it your own template language) for expanding various constructs (eg loops and variables) embedded in HTML. That's all a template is, anyways -- some data with special markers, the markers are replaced by a processor and the result is spit out. This is what the Zope Page Template (TAL) authors did. | I guess | I need to look for some kind of templating system, Yeah, go do that! :-) | though it | seems like many python people build web apps just fine without | them, Sure some do. PHP people do the same thing. And Perl people. And C people. You can even use ASM or raw machine code to write CGI "scripts". I recommended using tools that provide as high-level a view of the system as possible. | which is what I am trying to understand. I think :) HTH, -D --=20 In his heart a man plans his course, but the Lord determines his steps. Proverbs 16:9 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --LZvS9be/3tNcYl/X Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjz1Sp0ACgkQO8l8XBKTpRQzPgCgipMx6k3SeIWsrP5aDSf6/gBl FP0An0gPGOfsDOSX8GsExS13xohx4Kbr =HGMW -----END PGP SIGNATURE----- --LZvS9be/3tNcYl/X-- From dman@dman.ddts.net Wed May 29 22:41:52 2002 From: dman@dman.ddts.net (dman) Date: Wed, 29 May 2002 16:41:52 -0500 Subject: [Tutor] Rounding In-Reply-To: References: Message-ID: <20020529214152.GB30684@dman.ddts.net> --gatW/ieO32f1wygP Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 29, 2002 at 08:03:39PM +0000, Terje Johan Abrahamsen wrote: | I am trying to use the round() function. But, it doesn't give me the=20 | answers I want: Do a google search for "binary floating point" or "IEEE 754" or something along those lines. Also try writing out 1/3 in decimal *exactly*, not an approximation, using pencil and paper. The problem is finite precision. If you're lucky you might get a nice dissertation from Tim Peters on the topice :-). -D --=20 The Consultant's Curse: When the customer has beaten upon you long enough, give him what he asks for, instead of what he needs. This is very strong medicine, and is normally only required once. =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --gatW/ieO32f1wygP Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjz1SyAACgkQO8l8XBKTpRQkfgCgrNLuj4nOjA2D9JZsdd4rtVfe hrAAoJC58grg80iEDKKj2itapO7gTNjg =JfDW -----END PGP SIGNATURE----- --gatW/ieO32f1wygP-- From terjeja@hotmail.com Wed May 29 22:37:26 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Wed, 29 May 2002 21:37:26 +0000 Subject: [Tutor] float & string Message-ID: I have a floating number (240.00) that I want to make into a string, so I can add a character to the end of it. But, the string doesn't become 240.00, but 240.000000. How can I make sure that the string stays like a dollar amount? Thanks in advance, Terje ------ Here is a part of the code: a = accountcurrents.xlamount # the stringvar with the dollar amount. accountcurrents.xlamount = string.atof(a) #conv to float round(accountcurrents.xlamount, 2) #round to 2 digits if accountcurrents.xlamount < 0: #if negative add '-' behind char = '-' else: char = '' accountcurrents.xlamount = "%f%s" % (abs(accountcurrents.xlamount), char) #here the - gets added, and it becomes a string _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx From pythontutor@venix.com Wed May 29 22:51:56 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 29 May 2002 17:51:56 -0400 Subject: [Tutor] float & string References: Message-ID: <3CF54D7C.2030302@venix.com> > accountcurrents.xlamount = "%.2f%s" % (abs(accountcurrents.xlamount), char) #here the - gets added, and it becomes a string %.2f will show two decimal places You may not need to use round depending upon what else happens to xlamount. Terje Johan Abrahamsen wrote: > I have a floating number (240.00) that I want to make into a string, so > I can add a character to the end of it. But, the string doesn't become > 240.00, but 240.000000. How can I make sure that the string stays like a > dollar amount? > > Thanks in advance, > Terje > > ------ > Here is a part of the code: > > a = accountcurrents.xlamount # the stringvar with the dollar amount. > accountcurrents.xlamount = string.atof(a) #conv to float > round(accountcurrents.xlamount, 2) #round to 2 digits > if accountcurrents.xlamount < 0: #if negative add '-' behind > char = '-' > else: > char = '' > > accountcurrents.xlamount = "%f%s" % > (abs(accountcurrents.xlamount), char) #here the - gets added, and it > becomes a string > > _________________________________________________________________ > MSN Photos is the easiest way to share and print your photos: > http://photos.msn.com/support/worldwide.aspx > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From ATrautman@perryjudds.com Wed May 29 23:33:55 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Wed, 29 May 2002 17:33:55 -0500 Subject: [Tutor] Newbie class question Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A2B1@CORP_EXCHANGE> All, I am very frustrated so please bear with me: I assume my problem is with the way classes interact in Python. My project uses tree layers of identical objects using the instantion name to differentiate them. The lowest class is color which is the most basic node consisting of data elements and get functions. They are also private so entry can be controlled. There are 4 of these colors in a class side which also breaks down the source file into the color info There are then 4 sides in a larger unit which sort the data and pass it to the side for processing The problem occurs at the highest level the 4 side do not appear unique. If I only fill one of the sides with four colours worth of data when I ask for the elements that have been stored all 4 sides say they have the same data. I have checked and the file converter is only being called once on the correct side. That is why I conclude that I must not know something about the way python handles data in classes and somehow these objects are not being kept separate. This is the class which appear to be interacting but I'm not sure at this point class Side: __filesadded = 0 K = pjColour.Colour('Black') C = pjColour.Colour('Cyan') M = pjColour.Colour('Magenta') Y = pjColour.Colour('Yellow') def __init__(self): __filesadded = 0 Thank for all your help Alan From shalehperry@attbi.com Wed May 29 23:39:00 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 29 May 2002 15:39:00 -0700 (PDT) Subject: [Tutor] Newbie class question In-Reply-To: <75EDF89FDE81D511840D00A0C9AD25DD0261A2B1@CORP_EXCHANGE> Message-ID: > > This is the class which appear to be interacting but I'm not sure at this > point > > class Side: > __filesadded = 0 > K = pjColour.Colour('Black') > C = pjColour.Colour('Cyan') > M = pjColour.Colour('Magenta') > Y = pjColour.Colour('Yellow') > > def __init__(self): > __filesadded = 0 > when you define a variable at the top of a class you make it global to all instances of the class (like a static variable in C++). From BobH@hslda.org Tue May 28 15:32:39 2002 From: BobH@hslda.org (Bob Hicks) Date: Tue, 28 May 2002 10:32:39 -0400 Subject: [Tutor] BOUNCE an e-mail Message-ID: I have a pop3 reader (actually found is a better term). I want to change it so that I can do a "bounce" for unwanted e-mails. I do not specifically see this in the RFC nor POPLIB. What would be the steps to do so? From dyoo@hkn.eecs.berkeley.edu Thu May 30 00:29:00 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 29 May 2002 16:29:00 -0700 (PDT) Subject: [Tutor] Rounding In-Reply-To: <20020529214152.GB30684@dman.ddts.net> Message-ID: On Wed, 29 May 2002, dman wrote: > On Wed, May 29, 2002 at 08:03:39PM +0000, Terje Johan Abrahamsen wrote: > | I am trying to use the round() function. But, it doesn't give me the > | answers I want: > > Do a google search for "binary floating point" or "IEEE 754" or > something along those lines. Also try writing out 1/3 in decimal Python doesn't have an official "rational" type yet, so it opts to represent fractions in a convenient-but-inexact "floating point" representation. The official Python tutorial mentions floating point in its appendix B: http://www.python.org/doc/tut/node14.html and offers some ways of working with it. Hope this helps! From dylan.belsey@baesystems.com Thu May 30 00:55:25 2002 From: dylan.belsey@baesystems.com (BELSEY, Dylan) Date: Thu, 30 May 2002 09:25:25 +0930 Subject: [Tutor] Bindings in Tkinter Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B963206E@wtntex1.baea.com.au> As Bryce suggested, there are other focus methods available. The one that I have been using is an inherited common widget method called 'focus_set()'. You could try 'self.frame.top.focus_set()'. However according to the literature (Python and Tkinter Programming - John E. Grayson) "this method resets the input focus for the widget's display to 'self'" only "if the application currently has the input focus on the widget's display". If the input focus is not on the widget's display then the 'focus_set()' op is "remembered" and will be put into affect when the input focus does change to the widget's display. Hope this helps. -----Original Message----- From: shendric@arches.uga.edu [mailto:shendric@arches.uga.edu] Sent: Thursday, 30 May 2002 01:56 To: Python Tutor Subject: [Tutor] Bindings in Tkinter Hello, I'm having difficulty with bindings, but I'm not real sure what I'm doing wrong. The following is a small bit of code that is part of a larger app that I'm working on. The idea is to simply bind the key to a little printing function, but it does nothing at all. The larger app actually contains things within the frames that are created, but I left them out of this for convenience and brevity. Any ideas? Sean Hendricks from Tkinter import * import Pmw class VTrans: def __init__(self, master): self.master = master self.frame = Frame(master) self.frame.top = Frame(master) self.frame.bottom = Frame(master) self.frame.top.pack(side=TOP, fill=X) self.frame.bottom.pack(side=TOP) self.frame.pack() self.getBindings() def doStuff(self, event=None): print "I am the very model of a ..." def getBindings(self): self.frame.top.bind('', self.doStuff) if __name__ == "__main__": root = Tk() root.title('Test') Pmw.initialise() main = VTrans(root) root.mainloop() _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From pydan@danshafer.com Thu May 30 03:21:12 2002 From: pydan@danshafer.com (Dan Shafer) Date: Wed, 29 May 2002 19:21:12 -0700 Subject: [Tutor] Why NOT to Use Python? Message-ID: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> I'm working on a Python article for CNET. They want me to provide pros and cons for choosing Python in creating a Web-based enterprise-type application where enterprise is defined as meaning lots of simultaneous users. Pros I got. Cons I don't got. Any thoughts either way? Comparing to Java and C# and .NET strategies is probably the order of the day, although I'm open to ideas that don't fit that box. From rob@uselesspython.com Thu May 30 03:36:54 2002 From: rob@uselesspython.com (Rob Andrews) Date: Wed, 29 May 2002 21:36:54 -0500 Subject: [Tutor] Why NOT to Use Python? References: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> Message-ID: <3CF59046.8090206@uselesspython.com> Java Server Pages (JSP) are a good argument for Java in the enterprise. Python doesn't really seem to have a single obvious *killer* approach to production of Python Server Pages that quite compares with JSP. In fact, Java seems to have a rather healthy set of enterprise tools that a team of team of developers can use in consistent and predictable ways. And when you are dealing with "lots of simultaneous users" you often find yourself dealing with a large development staff. Java can also present certain performance/speed advantages under many realistic circumstances. Of course, it's not always an either/or situation. Python/Jython may be used for rapid prototyping and to get the product to production status before the competition does. Jython also presents the option of creating 100% pure Java .class files, which addresses performance and other issues out-of-hand. It makes a good deal of sense to consider Python/Jython development in tandem with Java development in the enterprise because of the rapid development time and maintainability. These aren't the only good reasons to do so, of course. Jython, after all, makes available the libraries of both Java AND Python! This is nothing to be sniffed at. Rob Andrews http://uselesspython.com Dan Shafer wrote: > I'm working on a Python article for CNET. They want me to provide pros > and cons for choosing Python in creating a Web-based enterprise-type > application where enterprise is defined as meaning lots of simultaneous > users. > > Pros I got. Cons I don't got. > > Any thoughts either way? > > Comparing to Java and C# and .NET strategies is probably the order of > the day, although I'm open to ideas that don't fit that box. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From phthenry@earthlink.net Thu May 30 03:43:30 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Wed, 29 May 2002 22:43:30 -0400 Subject: [Tutor] Why NOT to Use Python? In-Reply-To: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> References: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> Message-ID: <20020529224330.C6147@localhost.localdomain> On Wed, May 29, 2002 at 07:21:12PM -0700, Dan Shafer wrote: > Pros I got. Cons I don't got. > > Any thoughts either way? > > Comparing to Java and C# and .NET strategies is probably the order of the > day, although I'm open to ideas that don't fit that box. > > I'm new to python, though that could make my opinions different and perhaps unique when compared with an old pro. I learned perl first, and switched to python because I wanted a language with better object oriented support. I also wanted to parse xml data, and I was told python was much better for this task than perl. So far, I think python is *much* better than perl. In fact, I would tell anybody learning perl this: "Don't bother. Python can do everything perl can, but the code is much more readable and easier to maintain. Okay, now for the cons. I think when you evaluate a language, you shouldn't just look at how easy it is to use. You need to determine how many people use it, and how good the documentation is for it. While a lot of people do use python, more people use perl. This is a plus, because when you get stuck, you are much more likely to get an answer. (Though I am sure this mailing list could probably handle any question.) Also, when you run across example on mailing list for doing tasks (such as making a back up script), you are more likely to see the example in perl. As a python user, you have to translate this code to python. But even more important than the user-base is the documentation. After I learned perl and before I switched to python, I played with java. I think most people would agree that python is easier to use than java. However, java is far superior in the amount of great documentation available. For example, I have not found a single tutorial on the web on using DOM with python. There is one (recent) book on this topic. In fact, when I asked for tutorials on another python mailing list (sig), I was referred to java tutorials! Last is the libraries available. The library for parsing xml is PYxml, and is in version .7. In other words, it is not fully mature. In contrast, the libraries for java are very, mature. And did I mention that there is better documentation for parsing xml with java than for xml? Yes, but this point can't be said enough. Good documentation can save you weeks of slogging though what turn out to be simple problems. I hope this helps Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From chrisl@frodo.thethirdsector.com Thu May 30 05:54:17 2002 From: chrisl@frodo.thethirdsector.com (Chris Lott) Date: Wed, 29 May 2002 20:54:17 -0800 Subject: [Tutor] Why NOT to Use Python? References: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> <20020529224330.C6147@localhost.localdomain> Message-ID: <00cf01c20796$0d95b8c0$5a01a8c0@TRS80> All in my beginner's opinion and mostly relating to perl because that's what I've used lately: perl one-liners are pretty cool... python doesn't give as much flexibility in this regard due to the syntax perl's documentation is more extensive for raw speed, C is going to outperform python, but I wouldn't make too much of that since it ignores too much gray area in an apparently complicated issue if you go looking for programs, particularly web applications, you are going to find a whole lot of perl and not as much python. I recently went looking for good weblog software and the top candidates were perl. Most CGI scripts you might want to mangle are perl regexps seem more integrated into perl, at least so far c From shalehperry@attbi.com Thu May 30 06:30:50 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 29 May 2002 22:30:50 -0700 (PDT) Subject: [Tutor] Why NOT to Use Python? In-Reply-To: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> Message-ID: On 30-May-2002 Dan Shafer wrote: > I'm working on a Python article for CNET. They want me to provide pros and > cons for choosing Python in creating a Web-based enterprise-type > application where enterprise is defined as meaning lots of simultaneous > users. > > Pros I got. Cons I don't got. > > Any thoughts either way? > > Comparing to Java and C# and .NET strategies is probably the order of the > day, although I'm open to ideas that don't fit that box. > As a contracter I find that writing python code makes me less money because I write it in less time and need to do less maintenance down the road. Definately a con in my book (-: From dman@dman.ddts.net Thu May 30 06:42:04 2002 From: dman@dman.ddts.net (dman) Date: Thu, 30 May 2002 00:42:04 -0500 Subject: [Tutor] float & string In-Reply-To: References: Message-ID: <20020530054204.GB3672@dman.ddts.net> --8P1HSweYDcXXzwPJ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 29, 2002 at 09:37:26PM +0000, Terje Johan Abrahamsen wrote: | I have a floating number | dollar amount? BAD BAD BAD. Never use floating point numbers for currency. The approximation (necessitated by finite precision) will cause "inaccuracies" in the amounts your software computes. Instead store all currency amounts in (eg for US or Canada) cents rather than dollars. Displaying the number as "$240.00" on screen is wholly different from the internal storage. For example : def cheesy_money_print( amt ) :=20 """ note that better libraries exist for doing this """ dollars =3D int( amt / 100.0 ) # pull out the dollars part cents =3D amt - (dollars*100) # pull out the cents part s =3D "$%d.%.2d" % ( dollars , cents ) return s >>> cheesy_money_print( 24000 ) '$240.00' I call this formatter "cheesy" because it assumes that the local currency designator is '$' and doesn't really do any error or sanity checking or anything like that. It also assumes that you want 2 decimal places in the currency. A better choice is to use a locales library to format the strings according to the user's locale settings. HTH, -D --=20 Q: What is the difference betwee open-source and commercial software? A: If you have a problem with commercial software you can call a phone number and they will tell you it might be solved in a future version. For open-source sofware there isn't a phone number to call, but you get the solution within a day. =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --8P1HSweYDcXXzwPJ Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjz1u6wACgkQO8l8XBKTpRStwQCffr805Bcy2l8+Tdr9A+tBsMgx KwgAn0bs8akSSjCExR67rqqpVIbitSh5 =+OuJ -----END PGP SIGNATURE----- --8P1HSweYDcXXzwPJ-- From dman@dman.ddts.net Thu May 30 06:35:14 2002 From: dman@dman.ddts.net (dman) Date: Thu, 30 May 2002 00:35:14 -0500 Subject: [Tutor] BOUNCE an e-mail In-Reply-To: References: Message-ID: <20020530053514.GA3672@dman.ddts.net> --GvXjxJ+pjyke8COw Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, May 28, 2002 at 10:32:39AM -0400, Bob Hicks wrote: | I have a pop3 reader (actually found is a better term). I want to change | it so that I can do a "bounce" for unwanted e-mails. I do not | specifically see this in the RFC nor POPLIB. |=20 | What would be the steps to do so? First, do you have access to the Envelope Sender? This is NOT the address(es) in the From: header. If you don't, then you're going to be treading on dangerous ground (and you could get flamed or added to some people's killfiles). If you do have that information, then proceed. POP can't "bounce" because a "bounce" is an SMTP thing (it involves sending messages, not reading them). So in order to formulate a bounce message you need to create a new message. The recommended format is given in RFC 1894. Use the 'email' module to assemble your MIME-encoded DSN (Delivery Status Notification; though in some ways it's not really "Delivery Status", per se). Use your own address as the From: address[1] and the orginal message's envelope sender as the To: address.=20 Once you've created the message using the 'email' module, serialize it and pipe it to your local MTA (often /usr/sbin/sendmail or /usr/lib/sendmail) using "<>" as the envelope sender (requied for DSN, see RFC 2821 and 821) and the envelope sender from the original message as the envelope recipient. If you don't understand the difference between the envelope and the message headers then don't attempt to do this -- the result could be misdirected email and very annoyed (at the least) sysadmins. People get enough junk as it is without misbehaving (though well-intentioned) software adding to it. Oh, and if you're trying to bounce spam messages, don't even try. The sender (and usually From:) addresses are almost always forged. If it happens to be a real address then you'll just be annoying (and DDoSing) some poor innocent person. HTH, -D 1: I think this is a reasonable choice since the message really isn't originating from your ISP's mail server (in which case it would be Mailer-Daemon@...). --=20 If your life is a hard drive, Christ can be your backup. =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --GvXjxJ+pjyke8COw Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjz1uhIACgkQO8l8XBKTpRR9RwCfZYslKdMqNSf9/1lxaqMFCqee 2LIAn1vhaDDuHON7IZ8PqjdTr8V71GLi =Ikdx -----END PGP SIGNATURE----- --GvXjxJ+pjyke8COw-- From ATrautman@perryjudds.com Thu May 30 14:07:23 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Thu, 30 May 2002 08:07:23 -0500 Subject: [Tutor] Why NOT to Use Python? Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A2B4@CORP_EXCHANGE> Dan Shafer wrote: > I'm working on a Python article for CNET. They want me to provide pros > and cons for choosing Python in creating a Web-based enterprise-type > application where enterprise is defined as meaning lots of simultaneous > users. > > Pros I got. Cons I don't got. Hate to add another pro but I chose Python because I never learned AWK or other older UNIX and the lack of symbols in Python vs. Perl was a big factor in choosing Python. Anybody with an object programming background can read Python code without effort vs. Perl with its _ and $ signs. > > Any thoughts either way? The two biggest weaknesses to me are the difficult to use documentation and the difficulty of finding fairly polished apps/scripts that can be examined for structure and technique. Books generally aren't complex enough to show a fully functional package. C++, JAVA and Perl have a lot of really good examples that are well formed and documented. Alan > > Comparing to Java and C# and .NET strategies is probably the order of > the day, although I'm open to ideas that don't fit that box. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From Nicole.Seitz@urz.uni-hd.de Thu May 30 17:34:41 2002 From: Nicole.Seitz@urz.uni-hd.de (Nicole Seitz) Date: Thu, 30 May 2002 16:34:41 +0000 Subject: [Tutor] A very simple question Message-ID: <200205301634.41206.Nicole.Seitz@urz.uni-hd.de> Hi there! I'd like to write a function that gets a list , checks if there are only=20 strings in the list starting with a lowercase letter and then returns 1 i= f=20 only lowercase, 0 if not. How can I do that? example list: myList =3D [ "abc", "def", "Cde"] If I write: def checkIfOnlyLower(list): for item in list: if item[0].islower(): return 1 else: return 0 the function will return 1 as soon as it comes to the first string starti= ng=20 with a lowercase letter.But that's not what I want. Hope you can help me. Thanks in advance. Nicole From python@rcn.com Thu May 30 15:51:20 2002 From: python@rcn.com (Raymond Hettinger) Date: Thu, 30 May 2002 10:51:20 -0400 Subject: [Tutor] A very simple question References: <200205301634.41206.Nicole.Seitz@urz.uni-hd.de> Message-ID: <001f01c207e9$76e6b240$8de97ad1@othello> def checkIfOnlyLower(list): for item in list: if not item[0].islower(): return 0 return 1 Raymond Hettinger ----- Original Message ----- From: "Nicole Seitz" To: Sent: Thursday, May 30, 2002 12:34 PM Subject: [Tutor] A very simple question Hi there! I'd like to write a function that gets a list , checks if there are only strings in the list starting with a lowercase letter and then returns 1 if only lowercase, 0 if not. How can I do that? example list: myList = [ "abc", "def", "Cde"] If I write: def checkIfOnlyLower(list): for item in list: if item[0].islower(): return 1 else: return 0 the function will return 1 as soon as it comes to the first string starting with a lowercase letter.But that's not what I want. Hope you can help me. Thanks in advance. Nicole _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dman@dman.ddts.net Thu May 30 16:50:08 2002 From: dman@dman.ddts.net (dman) Date: Thu, 30 May 2002 10:50:08 -0500 Subject: [Tutor] xml parsers and java (was Re: Why NOT to Use Python?) In-Reply-To: <20020529224330.C6147@localhost.localdomain> References: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> <20020529224330.C6147@localhost.localdomain> Message-ID: <20020530155008.GA10741@dman.ddts.net> --GvXjxJ+pjyke8COw Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 29, 2002 at 10:43:30PM -0400, Paul Tremblay wrote: =20 | Last is the libraries available. The library for parsing xml is | PYxml, and is in version .7. Actually, there are quite a few xml parsing libraries for use with python. The most common one is 'expat'. It's a small and fast parser written in C by James Clark and wrapped with python bindings. I think 'libxml' (from the GNOME project) is also wrapped. | In other words, it is not fully mature. I think expat is quite mature. I'd even say it's more mature than the Java xml parsers. | In contrast, the libraries for java are very, mature. FYI Python is much older than java. Python appeared in public in the early '90s (around '91 I think). Java 1.0 didn't appear until around '95 or '96. Then Sun changed the core langauge for 1.1 (inner classes (which are quite essential for event-driven programming in java), etc) and changed the standard library for "java2" (jdk >=3D 1.2). In comparison, python's core language facillities haven't changed much since early releases. The extra features like list comprehensions are really just syntax sugar and aren't really needed (unlike java's inner classes). Sun really hyped up java almost a decade ago, but didn't live up to the hype. Go check out the (free) xml parsers for java. You'll find that xerces (from the apache group) is the best one, but xerces2 became stable only a couple months ago. It is a complete rewrite of xerces1. crimson and openxml seem to be dead. (crimson is because sun dropped it and switched to officially supporting xerces). | And did I mention that there is better documentation for parsing xml | with java than for xml? Both java and xml have way too much hype around them. If you're looking to publish a book, then saying "java", "xml", "web enabled" and "enterprise" will get you there. | Good documentation can save you weeks of slogging though what | turn out to be simple problems. True. My perspective comes from working with java quite a bit (school and work) and seeing the limitations of it and how the stories about it (from marketeers) often don't convey what's really going on. I've also worked on the XML parsing part of a commercial product, so I know a bit about the various options there. -D --=20 Come to me, all you who are weary and burdened, and I will give you rest. Take my yoke upon you and learn from me, for I am gentle and humble in heart, and you will find rest for your souls. For my yoke is easy and my burden is light. Matthew 11:28-30 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --GvXjxJ+pjyke8COw Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjz2SjAACgkQO8l8XBKTpRSFiACeIEgboti0mwPy/njx8Cj0GTyj uE0AoMAHfOGRqS1Ak14f6nrAB7rYtfAm =UbCR -----END PGP SIGNATURE----- --GvXjxJ+pjyke8COw-- From urnerk@qwest.net Thu May 30 13:55:45 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 30 May 2002 08:55:45 -0400 Subject: [Tutor] A very simple question In-Reply-To: <001f01c207e9$76e6b240$8de97ad1@othello> References: <200205301634.41206.Nicole.Seitz@urz.uni-hd.de> <001f01c207e9$76e6b240$8de97ad1@othello> Message-ID: <200205300855.45929.urnerk@qwest.net> On Thursday 30 May 2002 10:51 am, Raymond Hettinger wrote: > def checkIfOnlyLower(list): > for item in list: > if not item[0].islower(): > return 0 > return 1 > > Raymond Hettinger Good answer, except avoid using 'list', a builtin type name, as the=20 name of a variable. Likewise don't use int, float, str or dict as=20 variable names (I realize Raymond is following the original=20 example closely to show the similarities, as well as differences). A more complicated example would be: def checklower(thelist): =09from operator import add =09return len(thelist)=3D=3Dreduce(add,[i[0].islower() for i in thelist]) =2E..but Raymond's is better, for one because it stops when the first non-lower is encountered. Kirby From dman@dman.ddts.net Thu May 30 17:19:50 2002 From: dman@dman.ddts.net (dman) Date: Thu, 30 May 2002 11:19:50 -0500 Subject: [Tutor] Why NOT to Use Python? In-Reply-To: <3CF59046.8090206@uselesspython.com> References: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> <3CF59046.8090206@uselesspython.com> Message-ID: <20020530161950.GB10741@dman.ddts.net> --8P1HSweYDcXXzwPJ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 29, 2002 at 09:36:54PM -0500, Rob Andrews wrote: | Java Server Pages (JSP) are a good argument for Java in the enterprise.= =20 Mixing presentation and logic is just asking for a maintenance nightmare later on. | Python doesn't really seem to have a single obvious *killer* approach to= =20 | production of Python Server Pages that quite compares with JSP. Zope. Have you actually used J2EE (servlets, JSP, EJBs)? I had to for a school project. By comparison zope is trivial! =20 | In fact, Java seems to have a rather healthy set of enterprise tools=20 | that a team of team of developers can use in consistent and predictable= =20 | ways. And when you are dealing with "lots of simultaneous users" you=20 | often find yourself dealing with a large development staff. Is this article targeted at personal / free projects or commercial projects? Sun provides a J2EE implementation for "free", but the license says you can't use it in production (because they only intend it as a reference implementation and want you to buy a production-quality j2ee environment from a commercial vendor). For me the cost of the tools is a real drag (I tend to work in very-low-budget situations). =20 | Java can also present certain performance/speed advantages under many=20 | realistic circumstances. Can you give any examples? I've found python to usually be faster and certainly more conservative in memory usage (unless you write pathological code). | Of course, it's not always an either/or situation. Python/Jython may be= =20 | used for rapid prototyping and to get the product to production status=20 | before the competition does. | Jython also presents the option of creating=20 | 100% pure Java .class files, which addresses performance and other=20 | issues out-of-hand. That doesn't really help performance. Take a look at the java source for that sometime. Basically jythonc just generates some valid java code that feeds python source to the jython interpreter. I think it cuts out a little overhead, but not much, since you still need the whole jython interpreter to run your app. Some preliminary pystone comparisions showed jython, on jdk 1.4, to be faster than cpython. Supposedly that's due to Sun fixing the performance of reflection. | It makes a good deal of sense to consider=20 | Python/Jython development in tandem with Java development in the=20 | enterprise because of the rapid development time and maintainability.=20 Agreed. | These aren't the only good reasons to do so, of course. Jython, after=20 | all, makes available the libraries of both Java AND Python! This is=20 | nothing to be sniffed at. Jython doesn't provide all the python libs. The most notable exceptions are libs that depend on a C extension, or ones that need the 'os' module (java is rather sparse on providing the facilities need to finish implementing the os module). (I've done quite a bit of work with jython too, and even used it for some protoype and testing work in a java project) | Dan Shafer wrote: |=20 | >I'm working on a Python article for CNET. They want me to provide pros= =20 | >and cons for choosing Python in creating a Web-based enterprise-type=20 | >application where enterprise is defined as meaning lots of simultaneous= =20 | >users. | > | >Pros I got. Cons I don't got. o Global Interpreter Lock Threads in python need to acquire the GIL in quite a few ways. That limits the effectivness of multithreading your python app. In particular it can result in degraded performarnce on a multi-processor system. ex: Consider one thread on one CPU and one on another. Due to the GIL, one CPU is blocked waiting for the other to release it. ex: Multiple threads on a uniprocessor system. If the system (kernel or python) tries to context-switch too frequently you'll waste time switching contex just to be denied the GIL. These are things often discussed by the zope community when new people ask about performance in a heavily loaded environment. Note that this con can be avoided if the traditional model of using multiple single-threaded processes and IPC is used in place of threading (each process has a separate GIL). With zope this can (at least partly) be achieved using ZEO. o "Slow" Python is interpreted. As such it has overhead and is "slow". So is Java and .NET. If you need really high performance you'll need something lighterweight in C or C++ and that can really take advantage of multiprocessor systems. (note: all the usual caveats regarding quality of the code and development effort apply) In particular, zope is kinda slow. Typical solutions include caching with apache or squid in front of the zope server and storing static stuff (like images) on disk and served by apache. o Marketing Hype There isn't any. This is a con if you are trying to sell your idea to management or other non-techie type people. The words "java", ".NET", "xml", "web", and "enterprise" all sound good to non-techs. They can help you sell an idea even if the idea isn't all that great. Also consider Venture Capital (if you're a commercial entity). o Commercial Support This may or may not be relevant. There isn't nearly as many companies (dot-coms and otherwise) supporting python as there are those jumping on the java/xml/web/enterprise bandwagon. This means it is often easier to find some sort of commercial product with "java" or "enterprise" in it somewhere, but much harder to find python ones. Again, venture capital may be a factor. | >Any thoughts either way? There really aren't a whole lot of substantive cons to python, IMO, apart from the in-process concurrency limits. =20 | >Comparing to Java and C# and .NET strategies is probably the order of=20 | >the day, although I'm open to ideas that don't fit that box. C# : MS-only. Ximian is working on that, though. =2ENET : MS-only. Also python plugs into the .NET framework (or so I've heard), which means if you want to stick with MS platforms you can use python and .NET. (who runs a high-availability or high-reliability site on Windows anyways?) Java : More hype than substance. To close to C (low-level) in treatment of I/O and other constructs and common operations for my liking. Actually works better on windows than unix. (eg Try generating images on-the-fly using java on a headless unix system. You can't. Sun's AWT implementation requires an X server to connect to.) Based on my experiences with a variety of systems and environments, I would choose python over the other alternatives mentioned here. HTH, -D --=20 Pride goes before destruction, a haughty spirit before a fall. Proverbs 16:18 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --8P1HSweYDcXXzwPJ Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjz2USYACgkQO8l8XBKTpRTJfQCeI0O526YLD5fHnrNZXdfIf/ga 7BIAn06xpv/Va78W4TaVtd09b/GAoSn8 =s/Fh -----END PGP SIGNATURE----- --8P1HSweYDcXXzwPJ-- From urnerk@qwest.net Thu May 30 15:04:49 2002 From: urnerk@qwest.net (Kirby Urner) Date: Thu, 30 May 2002 10:04:49 -0400 Subject: [Tutor] Cool Konqueror feature for displaying Python code (question) Message-ID: <200205301004.49355.urnerk@qwest.net> I was just pulling up some .py files on the Konqueror web browser 3.0.1=20 e.g. http://www.inetarena.com/~pdx4d/ocn/python/nks.py and noticing that they display with color-coded syntax e.g. red text=20 between triple quotes. However, the colorizing seems a bit inconsistent=20 in than range and len are colorized (brown), but def, for, while, return,= =20 if, elif, else are not. Integers show up in blue, turning purple after t= he=20 decimal (meaning bi-color floats). The keyword self appears in green. I think this is an interesting development, and would obviate the need to post .html versions of .py files (which is what I currently do) but I won= der if the underlying code in Konqueror really knows much about Python, given the apparent wierdness of the colorsizing. =20 It'd seem a difficult challenge to really pay close attention to all thos= e languages, unless it had some way to leverage existing syntax modules,=20 like we have with emacs or vi. In any case, even what colorizing there is makes the code more readable imo. Kirby From brian@coolnamehere.com Thu May 30 11:08:22 2002 From: brian@coolnamehere.com (Brian Wisti) Date: Thu, 30 May 2002 10:08:22 +0000 (UTC) Subject: [Tutor] Cool Konqueror feature for displaying Python code (question) In-Reply-To: <200205301004.49355.urnerk@qwest.net> Message-ID: Yup, it's a cool feature. I think it's the KDE editor being embedded in the browser view, though, rather than Konqueror itself knowing anything about Python. Still, it's neat :-) Brian On Thu, 30 May 2002, Kirby Urner wrote: > > I was just pulling up some .py files on the Konqueror web browser 3.0.1 > e.g. http://www.inetarena.com/~pdx4d/ocn/python/nks.py > > and noticing that they display with color-coded syntax e.g. red text > between triple quotes. However, the colorizing seems a bit inconsistent > in than range and len are colorized (brown), but def, for, while, return, > if, elif, else are not. Integers show up in blue, turning purple after the > decimal (meaning bi-color floats). The keyword self appears in green. > > I think this is an interesting development, and would obviate the need to > post .html versions of .py files (which is what I currently do) but I wonder > if the underlying code in Konqueror really knows much about Python, > given the apparent wierdness of the colorsizing. > > It'd seem a difficult challenge to really pay close attention to all those > languages, unless it had some way to leverage existing syntax modules, > like we have with emacs or vi. > > In any case, even what colorizing there is makes the code more readable > imo. > > Kirby > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- | Brian Wisti | brian@coolnamehere.com | http://www.coolnamehere.com/ | "All you need in life is ignorance and confidence, then | success is sure." -- Mark Twain From israel@lith.com Thu May 30 18:07:36 2002 From: israel@lith.com (Israel Evans) Date: Thu, 30 May 2002 10:07:36 -0700 Subject: [Tutor] starting a python script by dropping a file onto it? Message-ID: This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C207FC.7F1EE29E Content-Type: text/plain Hello there, I was wondering about easy ways for people to start a little python script I've made. There are a couple of options available that I can think of: Drag and drop- I don't know how this would work. What sort of information is passed to a python program when something is dropped on it? How can I take advantage of it? Is it something like sys.argv[0]? Other Program's command line- I'm planning on using this python program with an Editor written in C that I don't have access to. I do have a command line field which is used to pass parameters to another program that this Editor program launches. Is it possible to sneak something into that command line that launches my python program before the other one? Anything else- The problem I'm fixing is a workaround for some bug in the program that gets launched by the Editor which causes it to misunderstand some of the files the editor creates. It's an annoyance that doesn't take a whole lot of time to work around, but I have to do it every time I add a new entry to whatever the editor is working on. I'd like to make using this python script take less time than the workaround. Otherwise I might just as well use the workaround. I'm using windows 2000. Thanks for any ideas! ~Israel~ ------_=_NextPart_001_01C207FC.7F1EE29E Content-Type: text/html Content-Transfer-Encoding: quoted-printable

 

Hello there, I was wondering about easy ways for = people to start a little python script I've made.

 

There are a couple of options available that I can = think of:

 

Drag and drop-

       &nbs= p;    I don't know how this would work.  What sort of information is passed to a python program when = something is dropped on it?  How can I = take advantage of it?  Is it = something like sys.argv[0]?

 

Other Program's command = line-

       &nbs= p;    I'm planning on using this python program with an Editor written in C that = I don't have access to.  I do have = a command line field which is used to pass parameters to another program that = this Editor program launches.  Is it = possible to sneak something into that command line that launches my python program = before the other one?

 

Anything else-

       &nbs= p;    The problem I'm fixing is a workaround for some bug in the program that = gets launched by the Editor which causes it to misunderstand some of the = files the editor creates.  It's an annoyance that doesn't take a whole lot of time to work around, but I have to do it every time I add a new entry to whatever the editor is = working on.  I'd like to make using this = python script take less time than the workaround.  Otherwise I might just as well use the = workaround.

 

I'm using windows 2000.

 

Thanks for any ideas!

 

 

 

~Israel<= font size=3D2 face=3D"Courier New">~

 

------_=_NextPart_001_01C207FC.7F1EE29E-- From terjeja@hotmail.com Thu May 30 18:17:01 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Thu, 30 May 2002 17:17:01 +0000 Subject: [Tutor] Wait Message-ID: I have written a program that does 4 processes. 1) Find an amount/policy in Excel. 2) Find the same policy in an AS/400 display. 3) Formats the amount 4) Writes the amount into the AS/400. However, the problem is that the python program is way faster than the AS/400 display. So, when the AS/400 is finished, the Python is several steps ahead. How can I get it to wait until it is done? I am currently using the sys.sleep() function. But, to add a 2 second break everywhere makes it very slow. Especially since most of the time 0.2 second break would probably be enough, but in special occations it takes longer. And, if you multiply by about 50000 policies, and about 10 sleeps for each policy to be on the safe side, everything takes very long... Thanks in advance, Terje _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx From michael.williams@st-annes.oxford.ac.uk Thu May 30 18:20:38 2002 From: michael.williams@st-annes.oxford.ac.uk (Michael Williams) Date: Thu, 30 May 2002 18:20:38 +0100 Subject: [Tutor] Cool Konqueror feature for displaying Python code (question) In-Reply-To: <200205301004.49355.urnerk@qwest.net> References: <200205301004.49355.urnerk@qwest.net> Message-ID: <20020530172038.GA22323@st-annes.oxford.ac.uk> On Thu, May 30, 2002 at 10:04:49AM -0400, Kirby Urner wrote: > and noticing that they display with color-coded syntax e.g. red text > between triple quotes. However, the colorizing seems a bit inconsistent > in than range and len are colorized (brown), but def, for, while, return, > if, elif, else are not. Integers show up in blue, turning purple after the > decimal (meaning bi-color floats). The keyword self appears in green. Is this not becuase def, elif, if, etc. are Python keywords and range and len are functions? -- Michael From lkvam@venix.com Thu May 30 14:09:43 2002 From: lkvam@venix.com (Lloyd Kvam) Date: Thu, 30 May 2002 09:09:43 -0400 Subject: [Tutor] Why NOT to Use Python? References: <5.1.0.14.0.20020529192029.0289cbf8@mail.hurrah.com> Message-ID: <3CF62497.8090106@venix.com> Some CONS: No CPAN performance issues (see http://www.norvig.com/Lisp-retro.html ) no one gets rich selling Python so it doesn't get much marketing support Python is still my default language choice. Programming is once again FUN! Dan Shafer wrote: > I'm working on a Python article for CNET. They want me to provide pros > and cons for choosing Python in creating a Web-based enterprise-type > application where enterprise is defined as meaning lots of simultaneous > users. > > Pros I got. Cons I don't got. > > Any thoughts either way? > > Comparing to Java and C# and .NET strategies is probably the order of > the day, although I'm open to ideas that don't fit that box. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From faure@kde.org Thu May 30 18:15:47 2002 From: faure@kde.org (David Faure) Date: Thu, 30 May 2002 19:15:47 +0200 Subject: [Tutor] Cool Konqueror feature for displaying Python code (question) In-Reply-To: References: Message-ID: <200205301915.47783.faure@kde.org> On Thursday 30 May 2002 12:08, Brian Wisti wrote: > Yup, it's a cool feature. I think it's the KDE editor being embedded in > the browser view, though, rather than Konqueror itself knowing anything > about Python. > > Still, it's neat :-) Yes, it's the Kate part being embedded by Konqueror. This shows the power of KParts ;-) -- David FAURE, david@mandrakesoft.com, faure@kde.org http://people.mandrakesoft.com/~david/ Contributing to: http://www.konqueror.org/, http://www.koffice.org/ KDE, Making The Future of Computing Available Today From dyoo@hkn.eecs.berkeley.edu Thu May 30 18:37:31 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 30 May 2002 10:37:31 -0700 (PDT) Subject: [Tutor] A very simple question In-Reply-To: <200205301634.41206.Nicole.Seitz@urz.uni-hd.de> Message-ID: > I'd like to write a function that gets a list , checks if there are only > strings in the list starting with a lowercase letter and then returns 1 > if only lowercase, 0 if not. How can I do that? Hi Nicole, Let's take a look at what you have: > def checkIfOnlyLower(list): > for item in list: > if item[0].islower(): > return 1 > else: > return 0 > > the function will return 1 as soon as it comes to the first string starting > with a lowercase letter.But that's not what I want. Very true, checkifOnlyLower() thinks that it knows the answer too quickly. Take a closer look at the loop: ### for item in list: if item[0].islower(): return 1 else: return 0 ### A simple approach of debugging a program is to "trace" it out --- that is, go through the motions on a piece of paper and try simulating what the computer will do. Good luck to you! From terjeja@hotmail.com Thu May 30 20:39:17 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Thu, 30 May 2002 19:39:17 +0000 Subject: [Tutor] Date in Excel (Win32Com) Message-ID: I use Win32Com to move info from Excel to an AS/400 system. I need to check that the dates corespond in the two systems. In AS/400 I would use this to pick up the value: ex = accountcurrents.ex.ActiveSession.Screen.GetString(14, 15, 8) then if I type: >>>ex I get: u'10/30/00' However, when I do the same in Excel: xl = accountcurrents.xlSheet.Cells(9,2).Value And type: >>>xl I get: