From tj_ogrady@yahoo.com Sun Jul 1 04:32:08 2001 From: tj_ogrady@yahoo.com (TJ O'Grady) Date: Sat, 30 Jun 2001 20:32:08 -0700 (PDT) Subject: [Tutor] Python newbie Message-ID: <20010701033208.13634.qmail@web11608.mail.yahoo.com> Hi, I just finished my first python program. It does what I like, but I was wondering if there was a way to make it cleaner. At some point I'd like to make web pages totally customizeable based on initial user input, and the way I have it now would make for an unattractive script. Oh, and if anyone knows of a good place to find information on maintaining information from page to page, I would appreciate it the information. #!/usr/bin/python import cgi form = cgi.SvFormContentDict() fields=form.keys() print "Content-type: text/html" print print "" print "form handling at it's finest" print "" print "

Let's See What Happens


" print "

Welcome," print form["name"] print "To our web page, and thanks for stopping by. Come again Soon" __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From jparlar@home.com Sun Jul 1 05:45:27 2001 From: jparlar@home.com (Jay Parlar) Date: Sun, 01 Jul 2001 00:45:27 -0400 Subject: [Tutor] WWW::Search for Python Message-ID: <20010701044623.OMMM12854.femail16.sdc1.sfba.home.com@jparlar> Has anyone seen anything along the lines of Perl's WWW::Search, but for Python? For my current project, I need to be able to hit multiple search engines for results, but writing code for each engine is proving quite tedious. Any help would be greatly appreciated. Jay P. From rob@jam.rr.com Sun Jul 1 05:50:35 2001 From: rob@jam.rr.com (Rob Andrews) Date: Sat, 30 Jun 2001 23:50:35 -0500 Subject: [Tutor] commenting code well Message-ID: My code comments are often weak, if existent. What is good practice for commenting code? Rob "Perl is worse than Python because people wanted it worse." Larry Wall (Creator of Perl), 14 Oct 1998 Useless Python: http://www.lowerstandard.com/python/ From r.b.rigilink@chello.nl Sun Jul 1 06:54:13 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Sun, 01 Jul 2001 07:54:13 +0200 Subject: [Tutor] commenting code well References: Message-ID: <3B3EBB05.ED8D855E@chello.nl> Rob Andrews wrote: > > My code comments are often weak, if existent. What is good practice for > commenting code? > Well, not having (many) comments in your code may actually be what you should aim for. I try to use comments only for: 1. Explaining non-obvious algorithms 2. Notes to myself, usually of the form '# XXX Improve this' The ultimate goal is of course to remove these (yes, 1 too)... The most important rules of comments are: 1. Bad or inconsistent comments are worse than no comments at all. 2. Redundant comments are redundant. And, specific to Python: 3. Comments are for programmers, put info for users in doc strings. I use the following 'tricks' to avoid writing comments. - use descriptive names for variables, functions, etc. - try not to be clever, do the obvious thing - write good doc-strings Now, my problem is writing good doc strings... Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From rnd@onego.ru Sun Jul 1 06:43:07 2001 From: rnd@onego.ru (Roman Suzi) Date: Sun, 1 Jul 2001 09:43:07 +0400 (MSD) Subject: [Tutor] Python newbie In-Reply-To: <20010701033208.13634.qmail@web11608.mail.yahoo.com> Message-ID: On Sat, 30 Jun 2001, TJ O'Grady wrote: >Hi, > >I just finished my first python program. It does what >I like, but I was wondering if there was a way to make >it cleaner. At some point I'd like to make web pages >totally customizeable based on initial user input, and >the way I have it now would make for an unattractive >script. Oh, and if anyone knows of a good place to >find information on maintaining information from page >to page, I would appreciate it the information. You could use multiline """ ... """ to write HTML into: #!/usr/bin/python import cgi form = cgi.SvFormContentDict() fields=form.keys() print """Content-type: text/html form handling at it's finest

Let's See What Happens


Welcome, %(name)s

To our web page, and thanks for stopping by. Come again Soon """ % form Plus probably you need to supply defaults in case user has not supplied anything: try: print ... except KeyError: print """ who are you? what is your color?""" ALso, frequently user input need to be checked for security. For example, user could include malicious javascript or something like that and spoil you page completely. Probably replacing "<" and ">" into < > is good idea. Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ _/ Sunday, July 01, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "DEVICE=EXXON.SYS may mess up your environment" _/ From pursang@bigpond.com Sun Jul 1 17:50:17 2001 From: pursang@bigpond.com (John Murray) Date: Sun, 1 Jul 2001 16:50:17 +0000 Subject: [Tutor] commenting code well In-Reply-To: References: Message-ID: <01070116501700.02495@localhost.localdomain> On Sunday 01 July 2001 04:50, you wrote: > My code comments are often weak, if existent. What is good practice for > commenting code? > > Rob Hi Rob, You might be interested in this article at http://freshmeat.net/articles/view/238/ John From rnd@onego.ru Sun Jul 1 08:02:06 2001 From: rnd@onego.ru (Roman Suzi) Date: Sun, 1 Jul 2001 11:02:06 +0400 (MSD) Subject: [Tutor] commenting code well Message-ID: On Sat, 30 Jun 2001, Rob Andrews wrote: >My code comments are often weak, if existent. What is good practice for >commenting code? Probably this could help: http://www.python.org/doc/essays/styleguide.html >Rob Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ _/ Sunday, July 01, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "DEVICE=EXXON.SYS may mess up your environment" _/ From bren@europe.nl.com Sun Jul 1 11:43:35 2001 From: bren@europe.nl.com (Brendon) Date: Sun, 1 Jul 2001 12:43:35 +0200 Subject: [Tutor] PyQT's signals and slots Message-ID: <01070112433500.00494@yatsu> back again with more questions :) i've decided to try my luck with PyQT for UI design. i'm trying to understand PyQT's signals and slots mechanism, but due to the lack of good examples i've haven't got very far. what puzzles me is how do i create a slot. my guess is that you create a member function which also serves as a slot name, and when a signal is picked up the function is invoked, correct? say we have a button: class MyWidget(QWidget): def __init__(self, parent = None, name = None): buttonConnect = QPushButton("Connect", self) buttonConnect.show() self.buttonConnect.connect(self.buttonConnect, SIGNAL("conJ()"), ???? def conJ(): # open a new window [still have to figure that out] where the "????" are what should be given? i'd have thought "self" but i'm not sure. Brendon -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From bren@europe.nl.com Sun Jul 1 12:23:27 2001 From: bren@europe.nl.com (Brendon) Date: Sun, 1 Jul 2001 13:23:27 +0200 Subject: [Tutor] PyQT's signals and slots *correction In-Reply-To: <01070112433500.00494@yatsu> References: <01070112433500.00494@yatsu> Message-ID: <01070112551701.00494@yatsu> On Sunday 01 July 2001 12:43, you wrote: > back again with more questions :) > > i've decided to try my luck with PyQT for UI design. i'm trying to > understand PyQT's signals and slots mechanism, but due to the lack of good > examples i've haven't got very far. > self.buttonConnect.connect(self.buttonConnect, SIGNAL("clicked()"), ????, SLOT("conJ()") def conJ(): From rob@jam.rr.com Sun Jul 1 14:21:43 2001 From: rob@jam.rr.com (Rob Andrews) Date: Sun, 1 Jul 2001 08:21:43 -0500 Subject: [Tutor] commenting code well In-Reply-To: <5.1.0.14.0.20010701004836.00ad8608@Pop3.norton.antivirus> Message-ID: -----Original Message----- From: Kojo Idrissa [mailto:kojo@hal-pc.org] Sent: Sunday, July 01, 2001 1:16 AM To: Rob Andrews Subject: Re: [Tutor] commenting code well > Now, I have a question for the group, related to my verbose commenting style. At what point do lines of commentary begin > to impact program performance, if at all? If I remember correctly, in C, the comment lines are completly ignored by the > compiler, so there's no problem. But if I have a short program and the comments are longer than the program, does that > become a problem in some languages? I'm working on a "Personal Version Calculator" right now that "works" in 4 lines and > in the end may be less than 100 lines long (depends on how much other functionality I add). My 'comments' are, like, 3 > times the length of the program at this point. When doe that become a problem if ever? I could be quite wrong on this, at least in some technical details, but I'll reveal my ignorance if it turns out to be such. If you add 300 pages of comments to your 20-line obfuscated "hello world" script, it might take a bit of time for all this to be read when the Python interpreter first reads your obfuscatedhi.py file. But when it's done, it will create obfuscatedhi.pyc, which is the interpreted version. This file contains only bytecode, which is comment-free. As long as this .pyc file is more recent than your .py file of the same name, this is the one which will be executed (after the first time you run obfuscatedhi.py). So if extremely heavy comments slow down your program, it should only do it the first time. I could be wrong, Rob Useless Python: Aw, heck, we love you! http://www.lowerstandard.com/python/ From jason@oppel.net Sun Jul 1 14:33:16 2001 From: jason@oppel.net (Jason Oppel) Date: Sun, 01 Jul 2001 09:33:16 -0400 Subject: [Tutor] commenting code well References: Message-ID: <3B3F269C.C3DB8312@oppel.net> I found Guido's style guide pretty useful (and there's a section on commenting code)... www.python.org/doc/essays/styleguide.html I can't seem to get to the site right now so here's the Google cache: http://www.google.com/search?q=cache:WT_2WNCwwtE:www.python.org/doc/essays/styleguide.html+&hl=en Thanks for whomever posted this a while ago. It was really helpful! -Jason Rob Andrews wrote: > > My code comments are often weak, if existent. What is good practice for > commenting code? > > Rob > > "Perl is worse than Python because people wanted it worse." Larry Wall > (Creator of Perl), 14 Oct 1998 > Useless Python: http://www.lowerstandard.com/python/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From allan.crooks@btinternet.com Sun Jul 1 14:26:17 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Sun, 01 Jul 2001 14:26:17 +0100 Subject: [Tutor] commenting code well Message-ID: Rob, > My code comments are often weak, if existent. What is good practice for > commenting code? As well as the useful advice given here, I also tend to put comments where I have created one solution for a function and then rewritten it due to some bug / inefficiency. I explain in the code why it is doing it this way, and perhaps why not in a more obvious way. And I have in the past come across sections of my code and thought "why don't I improve it by doing it this way", and the comments have prevented me making the same mistake. Before Python, I used to code in Java a lot, and I obeyed the Javadoc convention. But for methods which were simple get / set methods, this used to be overkill, since they didn't really need comments, they were self-explanatory. So any comment things if they are of any use. It helps if you attempt to document it for someone who has no real idea what the code does (i.e. miss out the obvious things, explain the not-so-apparent things) For docstrings of functions, I'd document what it does, and document any behaviour that may not be readily apparent (e.g. raising an exception if a certain combination of parameters are provided). I'd have to agree that the freshmeat article is fairly useful, so I would look at that. :) Allan. From kojo@hal-pc.org Sun Jul 1 14:52:31 2001 From: kojo@hal-pc.org (Kojo Idrissa) Date: Sun, 01 Jul 2001 08:52:31 -0500 Subject: [Tutor] commenting code well Message-ID: <5.1.0.14.0.20010701085140.00ae2858@Pop3.norton.antivirus> --=====================_148109730==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed I just realized I forgot to send this to the list...it only went to Rob... Hey! A question I can answer! I think... Well, in my view there are two types of, or approaches to, comments, depending on the environment you're working in. First, the "I'm writing this program so that it can be given to someone I don't know and will probably never meet, but needs to be able to extend/work with this piece of code" style. This style could be seen as overly verbose, but it's designed to let another person understand exactly what you've done and why, without the benefit of you being around/alive/sane, whatever. Information to include: * Why this program was being written (what's the problem?) * How this program is being written (how did I choose to solve said problem?) This sort of thing would go at the beginning of the program, with more detail in the code at specific functions/modules etc, to explain what those sections of code are doing and why. It's also good to include commentary on how different sections of code connect i.e., "#After Module 1 returns the time.localtime tuple converted to hex, Module 2 prints those hex values to a web page"). The key here is all language used in comments is written for an outsider. Someone with a basic knowledge of the language(s) in question (programming and comment) should be able to 'read' the code. I guess this is my heavily watered-down version of Literate Programming. The Second Style would be the "I'm writing a practice program". Similar to the style above, but it allows you to use language that will be more self-referential (including notes to yourself, etc.). Less polished, and the comments may even contain design decisions you made as you went along (I find this helpful in the learning process). Note: I write fiction and I use this style to document what I write and why. It's probably more verbose than most programming comment styles, but as I go into my next phase of education, I've decided to take the approach that I am a writer. Sometimes I write in English, sometimes Python, sometimes [other languages I'll learn along the way], and in some cases I need to mix and match, depending on the job. It may seem a bit heavy-handed to some, but it allows me to work on my writing, and makes it a lot easier to understand anything I've written months later, regardless of the language I use. Now, I have a question for the group, related to my verbose commenting style. At what point do lines of commentary begin to impact program performance, if at all? If I remember correctly, in C, the comment lines are completly ignored by the compiler, so there's no problem. But if I have a short program and the comments are longer than the program, does that become a problem in some languages? I'm working on a "Personal Version Calculator" right now that "works" in 4 lines and in the end may be less than 100 lines long (depends on how much other functionality I add). My 'comments' are, like, 3 times the length of the program at this point. When doe that become a problem if ever? I guess I like Knuth's idea of Literate Programming. It appeals to the writer in my, but I haven't gotten around to using an actual tools for it. I'm just sort of making up my own version. Anyway, Rob, that's my US $.02...add all the commentary your fingers can stand to bang out, so long as they are explaining something about how and why the program works. At 11:50 PM 6/30/2001 -0500, you wrote: >My code comments are often weak, if existent. What is good practice for >commenting code? > >Rob > >"Perl is worse than Python because people wanted it worse." Larry Wall >(Creator of Perl), 14 Oct 1998 >Useless Python: http://www.lowerstandard.com/python/ > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** --=====================_148109730==_.ALT Content-Type: text/html; charset="us-ascii" I just realized I forgot to send this to the list...it only went to Rob...

Hey!  A question I can answer! I think...

Well, in my view there are two types of, or approaches to, comments, depending on the environment you're working in.

First, the "I'm writing this program so that it can be given to someone I don't know and will probably never meet, but needs to be able to extend/work with this piece of code" style.  This style could be seen as overly verbose, but it's designed to let another person understand exactly what you've done and why, without the benefit of you being around/alive/sane, whatever.  Information to include:
  • Why this program was being written (what's the problem?)
  • How this program is being written (how did I choose to solve said problem?)
This sort of thing would go at the beginning of the program, with more detail in the code at specific functions/modules etc, to explain what those sections of code are doing and why.  It's also good to include commentary on how different sections of code connect i.e., "#After Module 1 returns the time.localtime tuple converted to hex, Module 2 prints those hex values to a web page").  The key here is all language used in comments is written for an outsider.  Someone with a basic knowledge of the language(s) in question (programming and comment) should be able to 'read' the code.  I guess this is my heavily watered-down version of Literate Programming.


The Second Style would be the "I'm writing a practice program".  Similar to the style above, but it allows you to use language that will be more self-referential (including notes to yourself, etc.).  Less polished, and the comments may even contain design decisions you made as you went along (I find this helpful in the learning process).

Note: I write fiction and I use this style to document what I write and why.  It's probably more verbose than most programming comment styles, but as I go into my next phase of education, I've decided to take the approach that I am a writer.  Sometimes I write in English, sometimes Python, sometimes [other languages I'll learn along the way], and in some cases I need to mix and match, depending on the job.  It may seem a bit heavy-handed to some, but it allows me to work on my writing, and makes it a lot easier to understand anything I've written months later, regardless of the language I use.

Now, I have a question for the group, related to my verbose commenting style.  At what point do lines of commentary begin to impact program performance, if at all?  If I remember correctly, in C, the comment lines are completly ignored by the compiler, so there's no problem.  But if I have a short program and the comments are longer than the program, does that become a problem in some languages?  I'm working on a "Personal Version Calculator" right now that "works" in 4 lines and in the end may be less than 100 lines long (depends on how much other functionality I add).  My 'comments' are, like, 3 times the length of the program at this point.  When doe that become a problem if ever?

I guess I like Knuth's idea of Literate Programming.  It appeals to the writer in my, but I haven't gotten around to using an actual tools for it.  I'm just sort of making up my own version.

Anyway, Rob, that's my US $.02...add all the commentary your fingers can stand to bang out, so long as they are explaining something about how and why the program works.

At 11:50 PM 6/30/2001 -0500, you wrote:
My code comments are often weak, if existent. What is good practice for
commenting code?

Rob

"Perl is worse than Python because people wanted it worse." Larry Wall
(Creator of Perl), 14 Oct 1998
Useless Python: http://www.lowerstandard.com/python/


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

****************************
Kojo Idrissa
 
kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
**************************** --=====================_148109730==_.ALT-- From bill-bell@bill-bell.hamilton.on.ca Sun Jul 1 15:14:18 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Sun, 1 Jul 2001 10:14:18 -0400 Subject: [Tutor] Re: commenting code well In-Reply-To: Message-ID: <3B3EF7FA.5440.2E1884B@localhost> > My code comments are often weak, if existent. What is good practice > for commenting code? Chapter 19, "Self-Documenting Code" (I think) in Steve McConnell's "Code Complete" (MS press) covers this topic very well. Bill From reklama@publicist.com Sun Jul 1 16:22:22 2001 From: reklama@publicist.com (E-Mail Reklama) Date: Sun, 1 Jul 2001 19:22:22 +0400 Subject: [Tutor] =?windows-1251?Q?E-mail_-__=F0=E5=EA=EB=E0=EC=E0?= Message-ID: <73122001701152222235@publicist.com> Здравствуйте! В период летнего затишья на рынке вы можете колоссально оживить свои продажи, в отличие от своих конкурентов. Для этого закажите электронную рассылку Вашей рекламной информации по различным спискам адресов (от 30тыс. до 1млн., как по Москве, так и по всей России и СНГ). Соотношение стоимость/отдача при этом будет самое низкое. Мы профессионально занимаемся электронными рассылками 4 года. Наши постоянные клиенты - крупнейшие известные компании, которые давно поняли, что эффективность e-mail рассылок из-за широты охвата аудитории соизмерима лишь с рекламой на центральном телевидении! Клиенты, заказавшие рассылку один раз, обращаются к нам снова и снова. Сейчас многие продают списки e-mail адресов, но практически никто из их покупателей (как, кстати, и сами продавцы) не может в дальнейшем правильно ими воспользоваться, так как не имеет опыта и достаточных мощностей для действительно крупномасштабных рассылок. В лучшем случае, они успевают разослать только небольшие количества писем, при этом портя себе имидж и приобретая проблемы со своими провайдерами. Мы знаем все про e-mail рекламу и имеем все для того, чтобы ЗАВАЛИТЬ ВАС ЗАКАЗАМИ на ваши услуги или продукцию. Это большой парк производительнейших компьютеров и высокоскоростные каналы доступа в Интернет в московских офисах, собственные почтовые smtp-сервера за рубежом, а также собственные эксклюзивные наработки и ноу-хау в этой области. Мы умеем делать рассылки так, что это никак не повредит вашему имиджу. Если вы заинтересованны в рассылках и хотите получить от нас более полную информацию, пришлите запрос в произвольной форме в теле письма, нажав в своей почтовой программе "Ответить", или на ссылку: reklama@publicist.com. При этом в поле "Тема сообщения" обязательно укажите: "рассылка". From dyoo@hkn.eecs.berkeley.edu Sun Jul 1 19:07:31 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 1 Jul 2001 11:07:31 -0700 (PDT) Subject: [Tutor] parsing? In-Reply-To: <3B3BC7A3.84AC7A66@chello.nl> Message-ID: On Fri, 29 Jun 2001, Roeland Rengelink wrote: > > I'm tying to make something that can read some values and functions > from a file > and then use these to create a parametric surface in > triangles to be rendered > by POV-Ray. The triangle generation isn't > the problem, but reading the > functions into the program. > > > Unfortunately, in general this is not trivial. > > > Presumably, the file you read contains statements in some kind of > programming language. It is certainly possible to build a parser in > Python for that language which then allows you to execute those > statements in Python, as it were. This is not easy, and may not be the > right solution anyway. It sounds like something that dealt with rexec would be a good Useless Python challenge; an example might make it easier to adjust it to do parameteric surface stuff. Here's an idea for such a challenge: It'd be great if we had a program that acts like a numerical integrator. We'd be able to give this program some function, and have it do something that a TI calculator might be able to do. If we put on our "wishing makes it so" cap, we can imagine that running Integrator might look like this: ### [dyoo@einfall] ./Integrator.py Hello, I'm a simple numerical integrator. For help, please type 'help' at the prompt. > help Hello, this is the help file for Integrator. Here are a list of commands you can do with me: 'list' --- print out a list of functions we can integrate 'integrate([function], [left-point], [right-point])' --- Return the numerical integration of a particular function, starting from the left-point to the right-point. 'load([file])' --- Load a function into the integrator. 'help' --- You're looking at it. 'quit' --- you'll need to quit. > load('FyMathFunction.py') # Let's pretend that we have an # MyMathFunction.py that # contains a one-argument function. Ok, I've loaded MyMathFunction(). > list [MyMathFunction] > integrate(MyMathFunction, 0, 10) 42 ### The MyMathFunction.py file itself would contain something like: ### def MyMathFunction(x): return 4.2 ### but of course, Integrator.py should be able to handle more interesting functions. I don't think I have time to write this at the moment, but perhaps someone else can work on this one. From alan.gauld@bt.com Sun Jul 1 19:40:46 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 1 Jul 2001 19:40:46 +0100 Subject: [Tutor] General Programming Question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D892@mbtlipnt02.btlabs.bt.co.uk> > On Friday 29 June 2001 04:39, alan.gauld@bt.com wrote: > but I'd never recommend SICP as a first book on programming. > > What would you recommend? My own of course! :-) Or Ivan Lanningham's "24 hour" book Or a Manning Publications beginners book on Perl. I've forgotten the name but its the closest published book that I've seen to mine in that it explains the concepts pretty well. I just have serious doubts about the suitability of Perl as a first language... Alan G http://www.crosswinds.net/~agauld/ From alan.gauld@bt.com Sun Jul 1 19:45:56 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 1 Jul 2001 19:45:56 +0100 Subject: [Tutor] OOP with Tk/Tkinter Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D893@mbtlipnt02.btlabs.bt.co.uk> > I'm not sure where to go next. I want to learn more about GUI object > orientated programming with Tk/Tkinter. I've only be able to find two > tutorials for Tk/Tkinter and both were not OO. Hmm, The "official" tutor and reference by F/ is OO so far as I recall. Thats how I learnt Tkinter and altho its still not complete it does offer a good intro. Graysons book is a good reference but a terrible tutorial. The new Programming Python book by Mark Lutz seems to have a fair bit of Tkinter stuff and his older version certainly used an OO approach. Have you been thru all the stuff on the Tkinter section of the python.org website? Alan G From alan.gauld@bt.com Sun Jul 1 19:52:53 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 1 Jul 2001 19:52:53 +0100 Subject: [Tutor] General Programming Question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D894@mbtlipnt02.btlabs.bt.co.uk> > alan> it addresses the basics of programming - I/O is barely > alan> touched on for example. > > But, programming is not about I/O. Implementation is about I/O. > Programming is about designing solutions to problems. Hmm, I think thats where we have a philosophical difference. To me programming is about instructing a computer to perform tasks. How I perform the task is design and a separate discipline. Thus I/O is very much a part of programming, if you can't talk to the user or open files you can't create any kind of useful program... Now the specifics of which commands you use to open a file etc, thats implementation dependant but the principles behind it - streams, cursors, buffers etc are all fundamental programming concepts. IMHO of course :-) Alan G From alan.gauld@bt.com Sun Jul 1 19:56:30 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 1 Jul 2001 19:56:30 +0100 Subject: [Tutor] Language truce Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D895@mbtlipnt02.btlabs.bt.co.uk> TimP> All true. Hard going for a beginner, though! SICP is really about TimP> "Computer Science" more than *programming*. Now that is very true. As a CS book its excellent - but badly named :-) Alan G From alan.gauld@bt.com Sun Jul 1 20:00:10 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 1 Jul 2001 20:00:10 +0100 Subject: [Tutor] Language truce Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D896@mbtlipnt02.btlabs.bt.co.uk> > The only class that hurt worse (in terms of brain frying) was > probably Modeling and Simulation. Haha! I sympathise. i took simulation in my final year at college and didn't understand it till about 3 years later! - I actually started using it - with tool support! Thankfully I've now forgotten all about Guassian analysis and Stochastic methods... I hope! :-) Alan g From bren@europe.nl.com Sun Jul 1 20:15:34 2001 From: bren@europe.nl.com (Brendon) Date: Sun, 1 Jul 2001 21:15:34 +0200 Subject: [Tutor] OOP with Tk/Tkinter In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D893@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20751D893@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <01070121153404.00494@yatsu> On Sunday 01 July 2001 20:45, you wrote: > > I'm not sure where to go next. I want to learn more about GUI object > > orientated programming with Tk/Tkinter. I've only be able to find two > > tutorials for Tk/Tkinter and both were not OO. > > Hmm, The "official" tutor and reference by F/ is OO so far as I recall. > Thats how I learnt Tkinter and altho its still not complete it does > offer a good intro. > > Graysons book is a good reference but a terrible tutorial. > > The new Programming Python book by Mark Lutz seems to have a fair bit of > Tkinter stuff and his older version certainly used an OO approach. > > Have you been thru all the stuff on the Tkinter section of the > python.org website? I was going to, honest ;) python.org seemed to be down most of the day (GMT -1 starting this morning at 9 am to atleast 5 pm) so i wasn't able to even if i wanted to. PyQT works for me :) Brendon -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From alan.gauld@bt.com Sun Jul 1 20:10:15 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 1 Jul 2001 20:10:15 +0100 Subject: [Tutor] commenting code well Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D897@mbtlipnt02.btlabs.bt.co.uk> > My code comments are often weak, if existent. What is good > practice for commenting code? First the obligatory plug: http://www.crosswinds.net/~agauld in the more sequences and style sections there is guidance. The general rule is: Think "why" rather than "what" - explain the purpose of the code not how it works. The exception being where you use a particularly obscure algorithm or dense code. Then explain how and why... and of poss give a reference for the algorithm. Normally put comments before a function and at the top of a file but in Python make those doc strings instead. Think of the audience - somebody(maybe yourself!) trying to understand what and how the code functions. HTH, Alan g From alan.gauld@bt.com Sun Jul 1 20:18:20 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 1 Jul 2001 20:18:20 +0100 Subject: [Tutor] Re: commenting code well Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D898@mbtlipnt02.btlabs.bt.co.uk> > > My code comments are often weak, if existent. What is good practice > > for commenting code? > > Chapter 19, "Self-Documenting Code" (I think) in Steve McConnell's > "Code Complete" (MS press) covers this topic very well. Gosh yes, I'd forgotten about that but Code Complete covers comments very well - along with just about every other aspect of writing code! Alan G From bsass@freenet.edmonton.ab.ca Sun Jul 1 20:52:40 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sun, 1 Jul 2001 13:52:40 -0600 (MDT) Subject: [Tutor] commenting code well In-Reply-To: Message-ID: On Sat, 30 Jun 2001, Rob Andrews wrote: > My code comments are often weak, if existent. What is good practice for > commenting code? Don't, unless the code can't speak for itself. - Bruce From bsass@freenet.edmonton.ab.ca Sun Jul 1 23:01:59 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sun, 1 Jul 2001 16:01:59 -0600 (MDT) Subject: [Tutor] commenting code well In-Reply-To: <5.1.0.14.0.20010701085140.00ae2858@Pop3.norton.antivirus> Message-ID: On Sun, 1 Jul 2001, Kojo Idrissa wrote: > I just realized I forgot to send this to the list...it only went to Rob... Thanks for sending it to the list. I gave Rob my knee-jerk answer, but wanted to go on 'cause there are always bits that need commenting on which are related to the program but kinda OT in the code itself... <...> > I guess I like Knuth's idea of Literate Programming. It appeals to the > writer in my, but I haven't gotten around to using an actual tools for > it. I'm just sort of making up my own version. ...and I think literate programming techniques are the ideal thing for this task. Code is code and docs are docs, LP lets you keep them together and interconvert as is appropriate. I'd suggest LyX + noweb as a nice, easy to wrap your head around, way to get a look at LP (unix and win, for sure); but the idea is simple enough to code up that _anyone_ can play with the source -> prgfiles conversion (and has, now you know why the message is long :). > Now, I have a question for the group, related to my verbose commenting > style. At what point do lines of commentary begin to impact program > performance, if at all? <...> Hmmm, #'s and TQS's (""", ''') are treated differently, maybe even depending on where they sit in the code. Generally, when moving from .py's to .pyo's, #'s disappear first, docstrings last. I'm not worried about it much because, usually, all of my verbose commenting goes into "doc chunks", which get filtered out when the .py is created. WARNING: LP style code markup ahead... ...but I have refrained from messing with the order of things, so it should be easy to cut'n'paste or edit, if you feel so inclined. Do "notangle /path/to/saved.mes > lpmail.py" if you have noweb installed. History: I wrote this at the same time Rob was working on his plans for Useless, triggered by the same discussion (Rob, you may remember an email from me at that time, this is the first part of what I was babbling about ;). I almost turned it into a LP and sent it to the list (when it started to grow the getops stuff and other bits you expect a released program to have), but never carried through so it is unfinished in that respect (at least ;). Note: I wrote the core in short order (in a linear, go-with-the-flow kinda style), added a few bells and whistles, but got side-tracked checking out the os.system and os.exec* stuff (and then a whole bunch of other things) so it didn't get a cleanup. The code is tested (I read the contents of /usr/bin/lpmail into the message and added the markup), and I have it hooked up as a display filter for Pine (keying on "lpmail: " in column 1 of a line). In fact, I need this line to trigger the thing... lpmail: lpmail.py Known Bugs: A single "@" in column 1 will always start a doc chunk, there is no "@@" work-around like with noweb. I hope the code speaks for itself. <<*>>= #!/usr/bin/env python """Tangle an lpmail message or noweb style LP file. LPMail will extract a specific code chunk from a noweb formatted literate program, or from an LP file containing an "lpmail:" header which lists which chunks to extract, a filename for the default (named "*") chunk, or both. See "lpmail -h" for use information. """ import sys, os, getopt, re, string BaseName = os.path.basename # some file specific information PRGNAME = BaseName(sys.argv[0]) VERSION = "0.0.0alpha0" LASTUPDATE = "Feb 14, 2001" AUTHOR = [("Bruce Sass", "bsass@freenet.edmonton.ab.ca", "Primary author")] CONTRIBUTOR = [("Python Tutor Mailing List", "tutor@python.org", "many bits and pieces")] # -- system stuff # --------------- # Default buffer size for I/O DEFBUFSIZE = -1 # -1 = use system defaults # permitted process creation methods EXEC_types = ["execv", "system"] # default method used to fire up the IDE, EXEC_method = "system" # available development environments # - maybe autogenerate, eh. IDE_types = ["emacs", "gnuclient", "idle", "jed", "xemacs", "xjed"] # where the ide_command executable is located, :-/ IDE_EXEC_PREFIX = "/usr/bin/" # default IDE command string, "false" for no command IDE_command = "" # -- program-system interactions # ------------------------------ # flags no_fsWriting = 0 # "true" redirects all filesystem writes to stdout in_Prg_Chunk = 0 # "true" if we are in a program chunk do_Default_Out = 1 # "true" if default chunk should be sent to stdout be_Quiet = 1 # "true" supresses all messages except -h and -v. IDE_in_background = 0 # "true" runs the IDE in the background, # probably what you want for a GUI system # just in case it is necessary to limit the size of these... r_BufSize = DEFBUFSIZE # read buffer w_BufSize = DEFBUFSIZE # write buffer # -- program stuff # ---------------- # regular expressions pseudo_header = re.compile("^lpmail:(.*)") prg_chunk_header = re.compile("^<<.*>>=$") doc_chunk_header = re.compile("^@$") embedded_chunk_header = re.compile('^(\s*)(<<)(.*)(>>)$') first_word_template = re.compile('^(\S+)( *)(.*)') # variables chunks = {} # {name:[,...],...} linecount = 0 # where we are in the source file header_args = [] # list of pseudo-header arguments rootname = '' # chunk name passed with the -R (--Root) option # some definitions def usage(): print """ Synopsis: lpmail [options] sourcefilename Options: -h, --help display this message --default-out=<0|1> flag if default chunk should be output; 1 is yes, 0 is no (default 1) -I, --IDE= specify IDE command (no default) --background-IDE=<0|1> 0 means the IDE will run run in the foreground, 1 for in the background (default 0) -R , --Root= extract "chunkname" to stdout -s, --stdout only output to stdout -v, --version display program information """ print " Recognized IDEs:", string.join(IDE_types) print """ How it works: - lpmail extracts all the code chunks - if the -R option has not been used and a default chunk exists (named "*"), it is sent to stdout - if the -R option has been used, - its argument is the root chunk's name otherwise - all chunks named in the lpmail header are root chunks (names without a chunk get the default chunk, if it exists, otherwise a message is sent to stderr) - root chunks are sent to a like named file or stdout - only if an IDE is requested, writing to the file system is allowed, and there are names in the lpmail header, is the IDE is fired up. """ def printcontacts(contactlist, header=""): print "%s: %s <%s>" % (header, contactlist[0]) for name, emailaddr, description in contactlist[1:]: print ", %s <%s> - %s" % (name, emailaddr, description), print "." def version(): """Display program information.""" print PRGNAME + "-" + str(VERSION) print "Updated:", LASTUPDATE printcontacts(AUTHOR, "Author(s)") printcontacts(CONTRIBUTOR, "Contributor(s)") def fatalerror(detail=None): """Look at an exception, then exit.""" if detail and not be_Quiet: sys.stderr.write(PRGNAME + ": " + str(detail) + "\n") sys.exit(1) class PChunk: """A program chunk... ...has the following attributes and methods: start - source file line number the chunk header is on end - line number of chunk terminating "@" symbol lines[] - one string for each line between "<<...>>=" and "@" size() - returns end - start - 1 complete() - returns 1 if the chunk is complete, otherwise 0. Note: A chunk is incomplete if either the "start" or "end" are None, or the self.size() does not agree with len(self.lines). """ def __init__(self, chunkstart=None, chunklang=""): """Define "start", "end", number of "lines" and "language".""" self.start = chunkstart self.end = None self.lines = [] self.language = chunklang def __len__(self): """Number of lines in the chunk.""" return len(self.lines) def __str__(self): """Concatenate and return the lines in the chunk.""" return string.join(self.lines) __repr__ = __str__ def size(self): """Convenience function for (x.end - x.start - 1).""" return self.end - self.start - 1 def complete(): if self.size() == self.__len__(): return 1 return 0 @ Just to keep it on the topic of commenting in programs... I would say the following comment is OK, it distinguishes between major sections in the source: # -- start doing something... # --------------------------- This next guy is redundant, and should be replaced with a big long philosophical discussion of why the command line for this program is structured the way it is... of course it should never appear in the actual program file, imo. # ...the command line You all are getting the hang of the markup, eh? <<*>>= try: opts, args = getopt.getopt(sys.argv[1:], "hI:R:sv", ["help", "IDE=", "Root=", "stdout", "version", "exec-method=", "default-out=", "background-IDE="]) except getopt.GetoptError, detail: if not be_Quiet: sys.stderr.write(PRGNAME + str(detail) + "\n") usage() sys.exit(2) for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-I", "--IDE"): try: if BaseName(first_word_template.match(a).group(1)) in IDE_types: IDE_command = a except: pass elif o in ("-R", "--Root"): rootname = a do_Default_Out = 0 elif o in ("-s", "--stdout"): no_fsWriting = 1 elif o in ("--default-out",): if a: do_Default_Out = 1 else: do_Default_Out = 0 elif o in ("-v", "--version"): version() sys.exit() elif o in ("--exec-method",): if a in EXEC_types: EXEC_method = a elif o in ("--background-IDE",): if a: IDE_in_background = 1 else: IDE_in_background = 0 # ...handle some show stoppers if args: SRCFILE = args[0] else: if not be_Quiet: sys.stderr.write(PRGNAME + ": not enough arguments!!\n") usage() sys.exit(2) try: lpfile = open(SRCFILE, 'r', r_BufSize) except IOError, detail: fatalerror(detail) @ # ...figure out what we have in the way of chunks # The stuff in the try-except else clause could be part of the # __init__ of class LPFile; a collection of LPFile instances # would make up an LPDoc [probably where I'm headed next!]. <<*>>= while 1: try: line = lpfile.readline() except IOError, detail: if not be_Quiet: sys.stderr.write(PRGNAME + ": failed reading a line!!\n") lpfile.close() fatalerror(detail) else: # hmmm, extracting a bunch of independent groups... # ...is that a candidate for "threaded" code? linecount = linecount + 1 if prg_chunk_header.match(line): in_Prg_Chunk = 1 name = line[2:-4] if chunks.has_key(name): chunks[name].append(PChunk(linecount)) else: chunks[name] = [PChunk(linecount)] elif doc_chunk_header.match(line): if in_Prg_Chunk: chunks[name][len(chunks[name])-1].end = linecount in_Prg_Chunk = 0 elif pseudo_header.match(line) and not header_args: header_args = string.split(pseudo_header.match(line).group(1)) elif line == '': break elif in_Prg_Chunk: chunks[name][len(chunks[name])-1].lines.append(line) # ...sanity check time if in_Prg_Chunk: if not be_Quiet: sys.stderr.write(PRGNAME + ": EOF before program chunk finished!\n") chunks[name][len(chunks[name])-1].end = linecount in_Prg_Chunk = 0 if not chunks: fatalerror("Didn't find any chunks of code!!") lpfile.close() @ # we have a bunch of chunks stashed away by name in a dictionary, # and we may or may not have a list of files in "filenames"; some of the # stuff that can be done (in way of fixes, extensions, projects, ...): # - fix up PChunk, so you can: str(), "+", etc. # - extend to keep track of doc chunks (DChunk) # - keep track of doc chunk text types (plain, SGML, LaTeX, TROFF, etc.) # - rewrite in a less linear manner # - implement a stream mode(s) # - use a proper class based error handling subsystem # - figure out which chunks to include in the text and which to externalize # when pretty printing or archiving # - develop pretty printing routines # - figure out how to handle incomplete chunks automatically, # so you can email pieces of a program around # -- a prog that works with LPDoc-s # - develop an LPDoc <--> RCS/CVS/etc. interface # - develop an LPDoc editor # - add LPMail/LPDoc support to IDLE # - develop a complete set of Literate Programming tools <<*>>= # - generate all files represented in "chunks" def writechunklines(chunklist, file, istring): """Write the lines of a chunk to a file""" for chunk in chunklist: for line in chunk.lines: if embedded_chunk_header.match(line): indent, chunkname = embedded_chunk_header.match(line).group(1, 3) writechunklines(chunks[chunkname], file, indent + istring) else: file.write(istring + line) def chunkout(chunklist, filename): """Output a chunk sequence to a file or stdout.""" try: if filename == '*stdout*' or no_fsWriting: file = sys.stdout else: file = open(filename, 'w', w_BufSize) except IOError, detail: fatalerror(detail) else: writechunklines(chunklist, file, '') # this feels like a hack, is there a better way? if not (filename == '*stdout*' or no_fsWriting): file.close() if chunks.has_key('*') and do_Default_Out: chunkout(chunks['*'], '*stdout*') @ # If we have a "rootname", then the "-R" option was given and there is no # need to look at the other chunks; otherwise the chunks listed in filenames # are output. This 'process everything, then see what should be done' # scheme is ok for small LPs, but too inefficient if a small chunk is being # extracted from a larger work. <<*>>= if rootname: try: chunkout(chunks[rootname], '*stdout*') except NameError, detail: if not be_Quiet: sys.stderr.write(PRGNAME + "Can't process the root chunk!: " + rootname + "\n") sys.stderr.write(PRGNAME + "error: " + str(detail) + "\n") else: for name in header_args: if chunks.has_key(name) and name != "*": chunkout(chunks[name], name) elif chunks.has_key('*'): chunkout(chunks['*'], name) else: if not be_Quiet: sys.stderr.write(PRGNAME + "Couldn't find a chunk called: " + name +"!\n") @ # now that files are available, some possibilities are: # - score incoming progs based on their performance under rexec, # in a chroot jail :) # - append original file with script "scores" and resend, archive, etc. <<*>>= # - fire up IDLE, EMACS, etc. if IDE_command and EXEC_method and header_args and not no_fsWriting: # this is used as the last option for some exec methods, # - a unix hack? IDE_bkgnding_string = ">/dev/null 2>&1 &" try: IDE_args = [IDE_command] + header_args.remove('*') except ValueError, detail: #print "--|" + str(header_args) + "|--.remove('*') raised a ValueError:", detail IDE_args = [IDE_command] + header_args #print "IDE_{EXEC_PREFIX, args, bkgnding_string}:", #print IDE_EXEC_PREFIX, IDE_args, IDE_bkgnding_string rcode = None if EXEC_method == "system": if IDE_in_background: IDE_args.append(IDE_bkgnding_string) #print "--|" + IDE_EXEC_PREFIX + string.join(IDE_args) + "|--" rcode = os.system(IDE_EXEC_PREFIX + string.join(IDE_args)) elif EXEC_method == "execv": IDE_args[0], opts = first_word_template.match(IDE_args[0]).group(1,3) IDE_args.insert(1, opts) print "--|" + IDE_EXEC_PREFIX + IDE_args[0] + "|-- :", IDE_args #rcode = os.execv(IDE_EXEC_PREFIX + ide_args[0], ide_args) #print "IDE finished with return code:", rcode @ Have fun. - Bruce From camartin@snet.net Mon Jul 2 03:35:38 2001 From: camartin@snet.net (Cliff Martin) Date: Sun, 01 Jul 2001 22:35:38 -0400 Subject: [Tutor] Using sys.argv[] Message-ID: <3B3FDDF9.615E72B0@snet.net> To all: I have a program that I use regularly. (I'm using Linux , kernel 2.4.0 with Python 2.0) It's format is from the command line, Mathprogram inputfilename outputfilename. Inputfilename has the detailed information that the program operates on. I want to write a script to do this for me and let me decide the input files to use from the command line (I intend to make this more complicated later). I wrote a simple script that used os.system("Mathprogram inputfilename outputfilename"). This worked well. But when I tried to use sys.argv[ ] to set the file names from the command line it couldn't open the input filename to read. The code looks like #! /usr/bin/python import os import sys os.system("Mathprogram sys.argv[1] sys.argv[2]") Then from the command line I run python scrfaim.py inputfilename outputfilename and I get the error "error opening sys.argv[1] for reading". So what am I doing wrong. It seems a straightforward enough function that I must be using sys.argv wrong. By the way my paths etc. seem to be setup correctly. Thanks in advance Cliff From rick@niof.net Mon Jul 2 04:32:57 2001 From: rick@niof.net (Rick Pasotto) Date: Sun, 1 Jul 2001 23:32:57 -0400 Subject: [Tutor] Using sys.argv[] In-Reply-To: <3B3FDDF9.615E72B0@snet.net> Message-ID: <20010701233257.C406@tc.niof.net> On Sun, Jul 01, 2001 at 10:35:38PM -0400, Cliff Martin wrote: > > #! /usr/bin/python > > import os > import sys > os.system("Mathprogram sys.argv[1] sys.argv[2]") The following should work: import os import sys os.system("Mathprogram %s %s" % (sys.argv[1],sys.argv[2])) -- Start with the idea that society is contrary to Nature; devise contrivances to which humanity can be subjected; lose sight of the fact that humanity has its motive force within itself; consider men as base raw materials; propose to impart to them movement at will, feeling and life, set oneself up apart, immeasurably above the human race -- these are the common practices of the social planners. The plans differ; the planners are all alike... -- Frйdйric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From wilson@visi.com Mon Jul 2 05:20:24 2001 From: wilson@visi.com (Timothy Wilson) Date: Sun, 1 Jul 2001 23:20:24 -0500 (CDT) Subject: [Tutor] please critique my OOP Message-ID: Hey everyone, I've been doing some reading on OOA, OOD, and OOP lately and I've gone back to the random student group assignment program that I wrote a while back. I reworked it a bit and I think it's quite a bit clearer. I'd appreciate it if some of the more experienced persons on this list would give it a look and offer critiques. I'm especially interested in OOP issues here. My previous effort had all of the group assignment logic in one of the Teacher class's methods. I've removed that in this version and it's quite a bit simpler as a result. Have I sinned? :-) Once I feel like this is a reasonably good example of OOP I promise to write up a How-To describing the thought processes that led me do it this way. I know this is a very simple program, but as an OOP beginner, I haven't found a lot of examples of simple OO programs that describe how to get started. Here's the code and a sample run: --snip-- #!/usr/bin/env python ################################################################ # # # mkgrp.py by Tim Wilson # # Assign a class of students randomly to a series of groups. # # # # # July, 2001 # # # ################################################################ import string, random class Teacher: def __init__(self, name): self.name = name self.roster = [] self.unassigned = [] self.groupList = [] def __str__(self): return "%s has %s students." % (self.name, len(self.roster)) def addStudent(self, ln, fn, gender): newStudent = Student(ln, fn, gender) self.roster.append(newStudent) self.unassigned.append(newStudent) def loadFromFile(self, filename): """ File format has one student per line in the form: lastname, firstname, gender For example: van Rossum,Guido,M """ file = open(filename, 'r') studentList = file.readlines() for i in studentList: studentRecord = string.split(i, ',') self.addStudent(studentRecord[0], \ studentRecord[1], studentRecord[2][:-1]) #remove '\012' def printStudentRoster(self): for student in self.roster: print student def printGroupList(self): for group in self.groupList: print group.name class Student: def __init__(self, ln, fn, gender): self.ln = ln self.fn = fn self.gender = gender def __str__(self): return "%s %s" % (self.fn, self.ln) class Group: def __init__(self, name): self.name = name self.groupMembers = [] def printGroup(self): for student in self.groupMembers: print student def addStudent(self, student): self.groupMembers.append(student) if __name__ == '__main__': teacherName = raw_input('Your name? ') teacher = Teacher(teacherName) classList = raw_input('Class file? ') teacher.loadFromFile(classList) print teacher numGroups = raw_input('How many groups? ') for i in range(int(numGroups)): group = Group(i+1) teacher.groupList.append(group) while len(teacher.unassigned) != 0: for group in teacher.groupList: if len(teacher.unassigned) == 0: break else: selectedStudent = random.choice(teacher.unassigned) group.addStudent(selectedStudent) teacher.unassigned.remove(selectedStudent) print for group in teacher.groupList: print "Group %s" % group.name print "======" + len(str(group.name))*'=' group.printGroup() print --snip-- [wilson@einstein python]$ python mkgrp.py Your name? Wilson Class file? class.dat Wilson has 17 students. How many groups? 4 Group 1 ======= Marie Curie Tim Wilson Jenny Lange James Watt Ryan Carlson Group 2 ======= Ryan Carlson Craig Skalicky Richard Feynman John Kelly Group 3 ======= Guido van Rossum Lise Meitner Albert Einstein Mark Dockin Group 4 ======= Greg Schmidt Pat Killian Joe Blow Lawrence Cannon -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.org W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From joejava@dragoncat.net Mon Jul 2 05:28:06 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Mon, 2 Jul 2001 00:28:06 -0400 Subject: [Tutor] please critique my OOP References: Message-ID: <003f01c102af$6a8be550$2da2d6d1@joeltklrijxxms> > I've been doing some reading on OOA, OOD, and OOP lately and I've gone back > to the random student group assignment program that I wrote a while back. I > reworked it a bit and I think it's quite a bit clearer. I'd appreciate it if > some of the more experienced persons on this list would give it a look and > offer critiques. I'm especially interested in OOP issues here. I'll let others better skilled to critique your OOP code but I had to interject with a quesiton, What is OOA and OOD? Joel From kojo@hal-pc.org Mon Jul 2 05:29:15 2001 From: kojo@hal-pc.org (Kojo Idrissa) Date: Sun, 01 Jul 2001 23:29:15 -0500 Subject: [Tutor] please critique my OOP In-Reply-To: <003f01c102af$6a8be550$2da2d6d1@joeltklrijxxms> References: Message-ID: <5.1.0.14.0.20010701232851.00ad8ef0@Pop3.norton.antivirus> --=====================_200475228==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed Object Oriented Analysis and Design At 12:28 AM 7/2/2001 -0400, Joel Ricker wrote: > > I've been doing some reading on OOA, OOD, and OOP lately and I've gone >back > > to the random student group assignment program that I wrote a while back. >I > > reworked it a bit and I think it's quite a bit clearer. I'd appreciate it >if > > some of the more experienced persons on this list would give it a look and > > offer critiques. I'm especially interested in OOP issues here. > >I'll let others better skilled to critique your OOP code but I had to >interject with a quesiton, What is OOA and OOD? > >Joel > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** --=====================_200475228==_.ALT Content-Type: text/html; charset="us-ascii" Object Oriented Analysis and Design

At 12:28 AM 7/2/2001 -0400, Joel Ricker wrote:

> I've been doing some reading on OOA, OOD, and OOP lately and I've gone
back
> to the random student group assignment program that I wrote a while back.
I
> reworked it a bit and I think it's quite a bit clearer. I'd appreciate it
if
> some of the more experienced persons on this list would give it a look and
> offer critiques. I'm especially interested in OOP issues here.

I'll let others better skilled to critique your OOP code but I had to
interject with a quesiton, What is OOA and OOD?

Joel



_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

****************************
Kojo Idrissa
 
kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
**************************** --=====================_200475228==_.ALT-- From steve@purestfeeling.net Mon Jul 2 05:30:25 2001 From: steve@purestfeeling.net (steve@purestfeeling.net) Date: Sun, 1 Jul 2001 22:30:25 -0600 (MDT) Subject: [Tutor] 1.52 vs 2.1. Problems? Message-ID: Greetings friends. My name's Steve and I'm a pythonaholic. At least a wannabe Pythonaholic anyway:) Okay, here's the deal. I'm trying to learn Python. I have 2.1 on my main machine, but on my laptop I only have 1.52 because I can't fit the source for 2.1 on there and compile it due to hard drive space and not being able to find a suitable Debian package for Slink. Anyway, my question is this. I do a lot of playing on the laptop. Am I going to encounter anything major by learning with 1.52 on the laptop then trying to use 2.1? Just want to know if anything fundamental is different since all the docs I have are for 1.52, and I don't want to spend my time learning stuff that is obsolete now. If I'm going to fail to learn, I at least want to fail to learn something current:) (Have a great degree of trouble getting programming languages to stay in my head.) Hope that all makes sense. It's been a long day. Thanks -- Steve - Editor - www.formulaoneupdate.com ------------------------------------------------------------------- From deirdre@deirdre.net Mon Jul 2 06:14:21 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Sun, 1 Jul 2001 22:14:21 -0700 Subject: [Tutor] 1.52 vs 2.1. Problems? In-Reply-To: References: Message-ID: >Okay, here's the deal. I'm trying to learn Python. I have 2.1 on my main >machine, but on my laptop I only have 1.52 because I can't fit the source >for 2.1 on there and compile it due to hard drive space and not being able >to find a suitable Debian package for Slink. You can update it to Python 2.x (but only if you CAN fit the source on). The way to build a debian package, in short: Download the source tarball, the patch tarball and the .dsc file (the manifest) from the Debian site (see URL below) Then, do the following: dpkg-source -x _.dsc cd -/ debian/rules build make install For Python 2.07, these files can be found at: http://packages.debian.org/testing/interpreters/python2-base.html >Anyway, my question is this. I do a lot of playing on the laptop. Am I >going to encounter anything major by learning with 1.52 on the laptop then >trying to use 2.1? Just want to know if anything fundamental is different >since all the docs I have are for 1.52, and I don't want to spend my time >learning stuff that is obsolete now. If I'm going to fail to learn, I at >least want to fail to learn something current:) (Have a great degree of >trouble getting programming languages to stay in my head.) No, for the most part they're the same. Just stick to stuff in 1.52 and you'll be fine. -- _Deirdre Stash-o-Matic: http://weirdre.com http://deirdre.net "Cannot run out of time.... Is infinite time. You... are finite.... Zathrus... is finite. This... is wrong tool!" -- Zathrus From r.b.rigilink@chello.nl Mon Jul 2 08:00:22 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Mon, 02 Jul 2001 09:00:22 +0200 Subject: [Tutor] please critique my OOP References: Message-ID: <3B401C06.2ED94F58@chello.nl> Hi Timothy, I'll give it a shot. There are a lot of points, but I think your basic design is solid, and you have a working program. You should consider any improvements I suggest here as minor tweaks. Timothy Wilson wrote: > > Hey everyone, > > I've been doing some reading on OOA, OOD, and OOP lately and I've gone back > to the random student group assignment program that I wrote a while back. I > reworked it a bit and I think it's quite a bit clearer. I'd appreciate it if > some of the more experienced persons on this list would give it a look and > offer critiques. I'm especially interested in OOP issues here. > > My previous effort had all of the group assignment logic in one of the > Teacher class's methods. I've removed that in this version and it's quite a > bit simpler as a result. Have I sinned? :-) > Some general remarks: The assignment logic is now in main(), I don't think it belongs there. My first guess is it does indeed belong in Teacher. Teacher addStudent takes fn,ln,gender as argument, I think it should take a student as argument. Teacher has an addStudent method, but not an addGroup method The loadFromFile looks awkward. I would probably make this a separate function returning a list of student. I would certainly create the Student instances within this function de loadFromFile(filename): result = [] for line in open(filename).readlines(): fn, ln, gender = line.split(',') # the strip()s take care of all whitespace student = Student(fn.strip(), ln.strip(), gender.strip()) result.append(student) return result A wild idea. Shouldn't there be Class class. A class (in the schoool sense) HAS_A teacher and HAS_A list of students, and HAS_A list of groups. Also: consider deriving group from UserList Some additional comments in the code > Once I feel like this is a reasonably good example of OOP I promise to write > up a How-To describing the thought processes that led me do it this way. I > know this is a very simple program, but as an OOP beginner, I haven't found > a lot of examples of simple OO programs that describe how to get started. > It's what I hate about all the OOA and OOD books, they go to great lengths explaining how the OO analysis and design will really help making programming easier, but then they rarely bother to actually code up complete examples that show this. > Here's the code and a sample run: > > --snip-- > #!/usr/bin/env python > > ################################################################ > # # > # mkgrp.py by Tim Wilson # > # Assign a class of students randomly to a series of groups. # > # > # # > # July, 2001 # > # # > ################################################################ > > import string, random > > class Teacher: > def __init__(self, name): > self.name = name > self.roster = [] > self.unassigned = [] self.unassigned is part of the assignment logic. In your design it doesn't belong here. > self.groupList = [] > > def __str__(self): > return "%s has %s students." % (self.name, len(self.roster)) > > def addStudent(self, ln, fn, gender): > newStudent = Student(ln, fn, gender) > self.roster.append(newStudent) > self.unassigned.append(newStudent) > > def loadFromFile(self, filename): > """ > File format has one student per line in the form: > > lastname, firstname, gender > > For example: > > van Rossum,Guido,M > """ > > file = open(filename, 'r') > studentList = file.readlines() > for i in studentList: > studentRecord = string.split(i, ',') > self.addStudent(studentRecord[0], \ > studentRecord[1], studentRecord[2][:-1]) #remove '\012' > > def printStudentRoster(self): > for student in self.roster: > print student > > def printGroupList(self): > for group in self.groupList: > print group.name group.printGroup() > > > class Student: > def __init__(self, ln, fn, gender): > self.ln = ln > self.fn = fn > self.gender = gender Minor nit: why not lastname and firstname, in stead of ln, fn? > > def __str__(self): > return "%s %s" % (self.fn, self.ln) > > class Group: > def __init__(self, name): > self.name = name > self.groupMembers = [] > > def printGroup(self): > for student in self.groupMembers: > print student > > def addStudent(self, student): > self.groupMembers.append(student) > > if __name__ == '__main__': > teacherName = raw_input('Your name? ') > teacher = Teacher(teacherName) > classList = raw_input('Class file? ') > teacher.loadFromFile(classList) > print teacher > numGroups = raw_input('How many groups? ') > for i in range(int(numGroups)): > group = Group(i+1) > teacher.groupList.append(group) teacher.addGroup(group) > while len(teacher.unassigned) != 0: > for group in teacher.groupList: > if len(teacher.unassigned) == 0: > break > else: > selectedStudent = random.choice(teacher.unassigned) > group.addStudent(selectedStudent) > teacher.unassigned.remove(selectedStudent) You could remove the while loop, the break takes care of empty unassigned lists. > print > for group in teacher.groupList: > print "Group %s" % group.name > print "======" + len(str(group.name))*'=' > group.printGroup() > print If this is how you print a Group list why isn't this in Teacher.prinGroupList Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From SBrunning@trisystems.co.uk Mon Jul 2 08:51:21 2001 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Mon, 2 Jul 2001 08:51:21 +0100 Subject: [Tutor] URLs for urllib.urlopen Message-ID: <31575A892FF6D1118F5800600846864D78BDF3@intrepid> > From: Danny Yoo [SMTP:dyoo@hkn.eecs.berkeley.edu] > Very strange! This seems to work for me, trailing slash or not. Can you > check to see if that error happens again? Does anyone else know what > would cause the above? Danny, Hmmm. It's definitely happening - but only at work. It works fine at home. It also happens to other people at my office too - I reckon that the proxy is up to something. Sorry to confuse everyone. Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From bsass@freenet.edmonton.ab.ca Mon Jul 2 09:08:34 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Mon, 2 Jul 2001 02:08:34 -0600 (MDT) Subject: [Tutor] PyQT's signals and slots *correction In-Reply-To: <01070112551701.00494@yatsu> Message-ID: On Sun, 1 Jul 2001, Brendon wrote: > On Sunday 01 July 2001 12:43, you wrote: > > back again with more questions :) > > > > i've decided to try my luck with PyQT for UI design. i'm trying to > > understand PyQT's signals and slots mechanism, but due to the lack of good > > examples i've haven't got very far. > > > self.buttonConnect.connect(self.buttonConnect, SIGNAL("clicked()"), ????, > SLOT("conJ()") ??? = the object with the SLOT, which itself is just a method (as you surmised) However, I think what you want is... self.connect(self.buttonConnect, PYSIGNAL("clicked()"), self.conJ) i.e., the widget connects the buttons "clicked" signal to the widgets's conJ method. It is a PYSIGNAL because you are connecting between your own objects, not to Qt. If your button was (say) a "quit" button (needed to signal the app), the connect() would have the fourth argument, and look like... self.connect(self.buttonConnect,SIGNAL('clicked()'),qApp,SLOT('quit()')) ...or so I gathered from translating the Qt tutorials into PyQt (awhile ago, and I haven't played with it much since, so don't be too surprised if I steered you wrong :) - Bruce From hanna@chagford.com Mon Jul 2 18:20:09 2001 From: hanna@chagford.com (Hanna Joo) Date: Mon, 2 Jul 2001 10:20:09 -0700 Subject: [Tutor] wxPython - how to 'focus'? Message-ID: <000901c1031b$4437ea40$0100007f@localdomain> Hello all I am trying to build in 'LostFocus' and 'GotFocus' (Visual Basic terms, I think) into my simple wxPython program. So far, I managed to find two entries on events re 'Focus': -- EVT_SET_FOCUS and EVT_KILL_FOCUS there are a few other methods from wxWindow class: onSetFocus and OnKillFocus. What I want to do is quite simple. I want the second textbox to set its value when the first textbox loses focus. from wxPython.wx import * class Frame1(wxFrame): def __init__(self, parent, ID,title, pos, size): wxFrame.__init__(self, parent, ID, title, pos, size) self.panel1 = wxPanel(self, -1) self.tbox1 = wxTextCtrl(size = wxSize(224, 21), value = '', pos = wxPoint(208, 48), parent = self.panel1, name = 'tbox1', style = wxTE_PROCESS_TAB,id = 100) self.tbox2 = wxTextCtrl(size = wxSize(224,21), value = '', pos = wxPoint(208,88),parent = self.panel1, name = 'tbox2', style = wxTE_PROCESS_TAB, id = 101) self.text1 = wxStaticText(label = 'Hello1', id = -1, parent = self.panel1, name = 'text1', size = wxSize(88, 24), style = 0, pos = wxPoint( 56, 48)) self.text2 = wxStaticText(label = 'Hello2', id = -1, parent = self.panel1, name = 'text2', size = wxSize(88, 24), style = 0, pos = wxPoint( 56, 88)) button1 = wxButton(self.panel1, 1001, "See what happens!!") button1.SetPosition(wxPoint(200, 140)) EVT_SET_FOCUS(self,self.Focus_tbox1) ==> this hangs my machine completely if I pass (self, 100 (id of textbox1), self.Focus_tbox1), it complains that there are too many arguments. EVT_BUTTON(self, 1001,self.Button_down) def Focus_tbox1(self, event): self.tbox2.SetValue("My Text") def Button_down(self, event): self.Destroy() class MyApp(wxApp): def OnInit(self): self.frame = Frame1(NULL, -1, "Focus Testing....", wxDefaultPosition, wxSize(550,230)) self.frame.Show(true) return true app = MyApp(0) app.MainLoop() Do I have to instantiate my own event such as My_EVT= wxFocusEvent.wxFocusEvent(EVT_SET_FOCUS, Tbox1.NoFocus)? Hm, that doesn't work... mmmm any help please? A second question... If I run this app, the first time I can enter down to the button. After having gone down to the button, enter does not allow me to go to the next field anymore. Only tab moves the cursor to the next control. I wonder why this is so... From bren@europe.nl.com Mon Jul 2 12:08:42 2001 From: bren@europe.nl.com (Brendon) Date: Mon, 2 Jul 2001 13:08:42 +0200 Subject: [Tutor] PyQT's signals and slots *correction In-Reply-To: References: Message-ID: <01070213084205.00494@yatsu> On Monday 02 July 2001 10:08, you wrote: > On Sun, 1 Jul 2001, Brendon wrote: > > On Sunday 01 July 2001 12:43, you wrote: > > > > self.buttonConnect.connect(self.buttonConnect, SIGNAL("clicked()"), > > ????, SLOT("conJ()") > > ??? = the object with the SLOT, > which itself is just a method (as you surmised) > > However, I think what you want is... > > self.connect(self.buttonConnect, PYSIGNAL("clicked()"), self.conJ) > > i.e., the widget connects the buttons "clicked" signal to the > widgets's conJ method. It is a PYSIGNAL because you are connecting > between your own objects, not to Qt. unless it was created in the class of a custom QT widget, correct? it seems to work fine with "SIGNAL". > If your button was (say) a "quit" button (needed to signal the app), > the connect() would have the fourth argument, and look like... > > self.connect(self.buttonConnect,SIGNAL('clicked()'),qApp,SLOT('quit()')) > > ...or so I gathered from translating the Qt tutorials into PyQt > (awhile ago, and I haven't played with it much since, so don't be > too surprised if I steered you wrong :) which was what i ve been using to learn PyQT, it's a small world ;) Brendon -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From bren@europe.nl.com Mon Jul 2 12:13:09 2001 From: bren@europe.nl.com (Brendon) Date: Mon, 2 Jul 2001 13:13:09 +0200 Subject: [Tutor] when to use "self." Message-ID: <01070213130906.00494@yatsu> i suppose it has to be used if you need to access a widget because you have to call it somehow and doing so without the 'self.' would call a local function. erm, right? heh. are there any short docs on this? Brendon -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From aschmidt@nv.cc.va.us Mon Jul 2 12:37:43 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Mon, 2 Jul 2001 07:37:43 -0400 Subject: [Tutor] re: Python IVR work? Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090688C104@novamail1.nv.cc.va.us> Given Python's strong XML tools, I'm sure that www.TellMe.com could easily be tied into Python. Pick up the phone and try it: 1-800-555-TELL Hard to explain but worth a look for any developers. We are looking to tie it in very soon to Zope. Should be interesting. Allen -----Original Message----- From: Mike Lange [mailto:MLange@atmedicausa.com] Sent: Thursday, June 28, 2001 12:23 PM To: tutor@python.org Subject: [Tutor] re: Python IVR work? Does anyone know of a module or any work out there using Python to implement IVR (Interactive Voice Response or something along those lines) ? Thanks, Mike Lange Atmedica USA LLC. mlange@atmedicausa.com Phone: 801-517-6944 Fax: 801-517-6990 "What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more." -Alan J. Perlis From allan.crooks@btinternet.com Mon Jul 2 15:57:34 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Mon, 02 Jul 2001 15:57:34 +0100 Subject: [Tutor] when to use "self." Message-ID: > i suppose it has to be used if you need to access a widget because you have > to call it somehow and doing so without the 'self.' would call a local > function. erm, right? heh. > > are there any short docs on this? Maybe I'm missing something here, but it depends upon your understanding of "self". You need to use it to define object methods... but you do understand what classes do, don't you? OK, I'm definitely missing something here. :) Just let us know if you understand about classes and then we can move on from there... Allan. From bren@europe.nl.com Mon Jul 2 16:18:13 2001 From: bren@europe.nl.com (Brendon) Date: Mon, 2 Jul 2001 17:18:13 +0200 Subject: [Tutor] when to use "self." In-Reply-To: References: Message-ID: <01070217181300.18714@yatsu> On Monday 02 July 2001 16:57, you wrote: > > i suppose it has to be used if you need to access a widget because you > > have to call it somehow and doing so without the 'self.' would call a > > local function. erm, right? heh. > > > > are there any short docs on this? > > Maybe I'm missing something here, but it depends upon your understanding of > "self". > > You need to use it to define object methods... but you do understand what > classes do, don't you? > > OK, I'm definitely missing something here. :) Just let us know if you > understand about classes and then we can move on from there... > just another thing i need to get used to i'm guessing :) yes, i know about classes. perhaps i'm just confused. when defining a class and giving it some widgets, methods (hum, why not just call them functions?.. grr) and data they all need to be perceded by 'self.' with exception of methods (only a call to one) and variables used internally, non? i think i saw an example where this was not the case, hence the confusion. -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From NHYTRO@compuserve.com Mon Jul 2 16:18:32 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Mon, 2 Jul 2001 11:18:32 -0400 Subject: [Tutor] GUI toolkit decision Message-ID: <200107021119_MC3-D7E0-BB1D@compuserve.com> Hi guys! could someone point me to an URL where I can read the pros and cons, diffrences or advantages of Tkinter over WxWindows or vice-versa? I=B4m a= bit confused at the moment . I would like to develop standalone GUI applicati= on executables for The Win32 and Linux platform. Thanks for your anticipated help Sharriff = = From deirdre@deirdre.net Mon Jul 2 17:10:05 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Mon, 2 Jul 2001 09:10:05 -0700 Subject: [Tutor] GUI toolkit decision In-Reply-To: <200107021119_MC3-D7E0-BB1D@compuserve.com> References: <200107021119_MC3-D7E0-BB1D@compuserve.com> Message-ID: >could someone point me to an URL where I can read the pros and cons, >diffrences or advantages of Tkinter over WxWindows or vice-versa? I=B4m a b= it >confused at the moment . I would like to develop standalone GUI application >executables for The Win32 and Linux platform. Tkinter would also run on Macintosh. As far as looks go, Tkinter is imho the ugliest of interfaces, but I understand wxWindows is closer to the Windows "look." You might also consider Gtk+ -- I know there's support for it on Windows, but not sure how good that is (not being a Windows user). -- _Deirdre Stash-o-Matic: http://weirdre.com http://deirdre.net "Cannot run out of time.... Is infinite time. You... are finite.... Zathrus... is finite. This... is wrong tool!" -- Zathrus From deirdre@deirdre.net Mon Jul 2 17:15:33 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Mon, 2 Jul 2001 09:15:33 -0700 Subject: [Tutor] when to use "self." In-Reply-To: <01070217181300.18714@yatsu> References: <01070217181300.18714@yatsu> Message-ID: At 5:18 PM +0200 7/2/01, Brendon wrote: >perhaps i'm just confused. when defining a class and giving it some widgets, >methods (hum, why not just call them functions?.. grr) To prevent confusion. A function can be called by anyone. A method is a function specific to a class and can be called only in the context of that class. Think of the class variables as "things it has" and the methods as "things it does." >and data they all need >to be perceded by 'self.' with exception of methods (only a call to one) and >variables used internally, non? Yes. -- _Deirdre Stash-o-Matic: http://weirdre.com http://deirdre.net "Cannot run out of time.... Is infinite time. You... are finite.... Zathrus... is finite. This... is wrong tool!" -- Zathrus From allan.crooks@btinternet.com Mon Jul 2 17:18:54 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Mon, 02 Jul 2001 17:18:54 +0100 Subject: [Tutor] when to use "self." Message-ID: > just another thing i need to get used to i'm guessing :) > > yes, i know about classes. > > perhaps i'm just confused. when defining a class and giving it some widgets, > methods (hum, why not just call them functions?.. grr) and data they all need > to be perceded by 'self.' with exception of methods (only a call to one) and > variables used internally, non? > > i think i saw an example where this was not the case, hence the confusion. Ahh, now it makes a lot more sense now. :) Regarding methods ("why not call them functions"), it's because you are invoking a function which is attached to an object. Some OO king in the past must have come up with the name, and this is his legacy to us. :) In your initial message, I wasn't entirely sure that whether the full-stop after "self" was intentional or not. So when do you use "self." ? Whenever you are referring to the attributes of objects. Let me make a quick class for example's sake. :) >>> class Thing: .. .. def __init__(self, val): .. self.x = val .. .. def changeX (self, val): .. self.x = val .. .. def mutateX (self, val): .. x = val .. .. def plaid (self): .. print "Buy Plaid's Double Figure album right now." .. .. def plaid_one (self): .. self.plaid() .. .. def plaid_two (self): .. Thing.plaid(self) .. .. def plaid_three (self): .. plaid() .. >>> t = Thing(20) >>> print t.x 20 >>> t.changeX(30) >>> print t.x 30 >>> t.mutateX(40) >>> print t.x 30 >>> t.plaid() Buy Plaid's Double Figure album right now. >>> t.plaid_one() Buy Plaid's Double Figure album right now. >>> t.plaid_two() Buy Plaid's Double Figure album right now. >>> t.plaid_three() Traceback (most recent call last): File "", line 1, in ? File "", line 22, in plaid_three NameError: global name 'plaid' is not defined >>> And before you ask, no, I'm not in any way involved with Plaid, I'm only a fan who wants to spread the word. :) So let's take the first part of the class. .. def __init__(self, val): .. self.x = val .. .. def changeX (self, val): .. self.x = val .. .. def mutateX (self, val): .. x = val >>> t = Thing(20) >>> print t.x 20 >>> t.changeX(30) >>> print t.x 30 >>> t.mutateX(40) >>> print t.x 30 Now when we create a thing object, we assign the value provided in the call to the actual instance (self) of a Thing object. Now when we run changeX, we have to qualify the x as "self.x". When we run mutateX, it doesn't change the value in self, because "x" is a variable in the namespace of the method itself. But we want to modify the value in the namespace of the newly created Thing object, so we HAVE to qualify the x with self. This is a little confusing to people who have programmed in Java initially (e.g me :)). The equivalent Java code is: public void changeX (int value) { this.x = value; } And this is the same too: public void changeX (int value) { x = value; } But that's because namespaces work differently to Python's. So in other words, you NEED to put "self." before you refer to a variable that's attached to an object. Now the part regarding methods: .. def plaid (self): .. print "Buy Plaid's Double Figure album right now." .. .. def plaid_one (self): .. self.plaid() .. .. def plaid_two (self): .. Thing.plaid(self) .. .. def plaid_three (self): .. plaid() .. >>> t.plaid() Buy Plaid's Double Figure album right now. >>> t.plaid_one() Buy Plaid's Double Figure album right now. >>> t.plaid_two() Buy Plaid's Double Figure album right now. >>> t.plaid_three() Traceback (most recent call last): File "", line 1, in ? File "", line 22, in plaid_three NameError: global name 'plaid' is not defined >>> Now the first method ("plaid") is a shameless plug. The second method ("plaid_one") calls the first one using self. So it will invoke the method attached to the object instance (so if we override the definition of "plaid", it will do something else). The third method ("plaid_two") is invoking the definition of "plaid" that is defined in the Thing class. So even if we supply an instance of Thing which is it is overridden, it will still advertise the album. :) So we come to the fourth method ("plaid_three"). We attempt to invoke it, but it doesn't work, since "plaid" doesn't exist in the local, global or builtin namespaces. So, plaid_one searches in the object's ("self") name space. plaid_two searches in the namespace of "Thing". plaid_three searches in the local ("plaid_three") name space, global namespace and then the builtin namespace, and then fails. So that should make things clearer. Apologies if parts of this message doesn't make sense, I've got too many distractions. :) So whatever you read about not using "self." is a complete lie. :) Allan. From ak@silmarill.org Mon Jul 2 17:25:31 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Mon, 02 Jul 2001 12:25:31 -0400 Subject: [Tutor] when to use "self." In-Reply-To: <"from bren"@europe.nl.com> References: <01070217181300.18714@yatsu> Message-ID: <20010702122531.A4893@sill.silmarill.org> On Mon, Jul 02, 2001 at 05:18:13PM +0200, Brendon wrote: > On Monday 02 July 2001 16:57, you wrote: > > > i suppose it has to be used if you need to access a widget because you > > > have to call it somehow and doing so without the 'self.' would call a > > > local function. erm, right? heh. > > > > > > are there any short docs on this? > > > > Maybe I'm missing something here, but it depends upon your understanding of > > "self". > > > > You need to use it to define object methods... but you do understand what > > classes do, don't you? > > > > OK, I'm definitely missing something here. :) Just let us know if you > > understand about classes and then we can move on from there... > > > > just another thing i need to get used to i'm guessing :) > > yes, i know about classes. > > perhaps i'm just confused. when defining a class and giving it some widgets, > methods (hum, why not just call them functions?.. grr) and data they all need > to be perceded by 'self.' with exception of methods (only a call to one) and > variables used internally, non? > > i think i saw an example where this was not the case, hence the confusion. Read tutorial(s) about classes. > -- > > "if we live by an "eye for an eye and a tooth for a tooth"...before long, > the whole world will be blind and toothless." > --Tevye, Fiddler on the Roof > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From bren@europe.nl.com Mon Jul 2 17:49:51 2001 From: bren@europe.nl.com (Brendon) Date: Mon, 2 Jul 2001 18:49:51 +0200 Subject: [Tutor] when to use "self." In-Reply-To: <20010702122531.A4893@sill.silmarill.org> References: <01070217181300.18714@yatsu> <20010702122531.A4893@sill.silmarill.org> Message-ID: <01070218495101.18714@yatsu> > > perhaps i'm just confused. when defining a class and giving it some > > widgets, methods (hum, why not just call them functions?.. grr) and data > > they all need to be perceded by 'self.' with exception of methods (only a > > call to one) and variables used internally, non? > > > > i think i saw an example where this was not the case, hence the > > confusion. > > Read tutorial(s) about classes. will do :) -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From bren@europe.nl.com Mon Jul 2 17:51:43 2001 From: bren@europe.nl.com (Brendon) Date: Mon, 2 Jul 2001 18:51:43 +0200 Subject: [Tutor] when to use "self." In-Reply-To: References: Message-ID: <01070218514302.18714@yatsu> > > perhaps i'm just confused. when defining a class and giving it some > > widgets, methods (hum, why not just call them functions?.. grr) and data > > they all need to be perceded by 'self.' with exception of methods (only a > > call to one) and variables used internally, non? > > > > i think i saw an example where this was not the case, hence the > > confusion. > > Ahh, now it makes a lot more sense now. :) > > Regarding methods ("why not call them functions"), it's because you are > invoking a function which is attached to an object. Some OO king in the > past must have come up with the name, and this is his legacy to us. :) > > So that should make things clearer. > yup, i think i get it now. cheers :) -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From wilson@visi.com Mon Jul 2 18:11:09 2001 From: wilson@visi.com (Timothy Wilson) Date: Mon, 2 Jul 2001 12:11:09 -0500 (CDT) Subject: [Tutor] please critique my OOP In-Reply-To: <3B401C06.2ED94F58@chello.nl> Message-ID: On Mon, 2 Jul 2001, Roeland Rengelink wrote: > Timothy Wilson wrote: > > I've been doing some reading on OOA, OOD, and OOP lately and I've gone back > > to the random student group assignment program that I wrote a while back. I > > reworked it a bit and I think it's quite a bit clearer. I'd appreciate it if > > some of the more experienced persons on this list would give it a look and > > offer critiques. I'm especially interested in OOP issues here. > > Some general remarks: > > Teacher addStudent takes fn,ln,gender as argument, I think it should > take a student as argument. Thanks for the comments. Very helpful! I'm trying to make addStudent as generic as possible so that the student information can come form different sources. For example, I've coded this so that the students come from a file. The loadFromFile method calls the addStudent method to actually instantiate the student objects. Is this a reasonable thing to do? > Teacher has an addStudent method, but not an addGroup method Fixed. > A wild idea. Shouldn't there be Class class. A class (in the schoool > sense) HAS_A teacher and HAS_A list of students, and HAS_A list of > groups. Also: consider deriving group from UserList I thought about it. How would that be better? Here's a copy of the code again in case someone missed it the first time. (Doesn't include any changes yet.) --snip-- #!/usr/bin/env python ################################################################ # # # mkgrp.py by Tim Wilson # # Assign a class of students randomly to a series of groups. # # # # # July, 2001 # # # ################################################################ import string, random class Teacher: def __init__(self, name): self.name = name self.roster = [] self.unassigned = [] self.groupList = [] def __str__(self): return "%s has %s students." % (self.name, len(self.roster)) def addStudent(self, ln, fn, gender): newStudent = Student(ln, fn, gender) self.roster.append(newStudent) self.unassigned.append(newStudent) def loadFromFile(self, filename): """ File format has one student per line in the form: lastname, firstname, gender For example: van Rossum,Guido,M """ file = open(filename, 'r') studentList = file.readlines() for i in studentList: studentRecord = string.split(i, ',') self.addStudent(studentRecord[0], \ studentRecord[1], studentRecord[2][:-1]) #remove '\012' def printStudentRoster(self): for student in self.roster: print student def printGroupList(self): for group in self.groupList: print group.name class Student: def __init__(self, ln, fn, gender): self.ln = ln self.fn = fn self.gender = gender def __str__(self): return "%s %s" % (self.fn, self.ln) class Group: def __init__(self, name): self.name = name self.groupMembers = [] def printGroup(self): for student in self.groupMembers: print student def addStudent(self, student): self.groupMembers.append(student) if __name__ == '__main__': teacherName = raw_input('Your name? ') teacher = Teacher(teacherName) classList = raw_input('Class file? ') teacher.loadFromFile(classList) print teacher numGroups = raw_input('How many groups? ') for i in range(int(numGroups)): group = Group(i+1) teacher.groupList.append(group) while len(teacher.unassigned) != 0: for group in teacher.groupList: if len(teacher.unassigned) == 0: break else: selectedStudent = random.choice(teacher.unassigned) group.addStudent(selectedStudent) teacher.unassigned.remove(selectedStudent) print for group in teacher.groupList: print "Group %s" % group.name print "======" + len(str(group.name))*'=' group.printGroup() print --snip-- -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.org W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From bren@europe.nl.com Mon Jul 2 19:52:25 2001 From: bren@europe.nl.com (Brendon) Date: Mon, 2 Jul 2001 20:52:25 +0200 Subject: [Tutor] sockets Message-ID: <01070220522503.18714@yatsu> with the following code: import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) loginPacket = '' s.send(loginPacket) data = s.recv(1024) s.close() print "Recieved", data ---- i get the error message: s.send(loginPacket) socket.error: (32, 'Broken pipe'). any clue what i'm doing wrong? -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From dsh8290@rit.edu Mon Jul 2 19:56:37 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 2 Jul 2001 14:56:37 -0400 Subject: [Tutor] Language truce In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Thu, Jun 28, 2001 at 02:20:58PM -0700 References: <200106281940.f5SJeV801515@cecilia.trollope.org> Message-ID: <20010702145637.A22795@harmony.cs.rit.edu> On Thu, Jun 28, 2001 at 02:20:58PM -0700, Danny Yoo wrote: | One reason that 'for/in' might be preferred is because we are guaranteed | that the loop will always terminate: there can only be a finite number of | elements in a list. That's one big advantage of a loop construct that | goes along elements --- theoretically, we'll never get into infinite | loops. Almost. l = range( 1 ) for i in l : print l l.append( i+1 ) Don't do this! It's just as bad in C or any other language -- mutating a collection while iterating over it is just a bad idea. -D From dsh8290@rit.edu Mon Jul 2 20:01:44 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 2 Jul 2001 15:01:44 -0400 Subject: [Tutor] GUI toolkit decision In-Reply-To: ; from deirdre@deirdre.net on Mon, Jul 02, 2001 at 09:10:05AM -0700 References: <200107021119_MC3-D7E0-BB1D@compuserve.com> Message-ID: <20010702150144.B22795@harmony.cs.rit.edu> On Mon, Jul 02, 2001 at 09:10:05AM -0700, Deirdre Saoirse Moen wrote: | >could someone point me to an URL where I can read the pros and cons, | >diffrences or advantages of Tkinter over WxWindows or vice-versa? I=B4= m a bit Do some searches of the comp.lang.python archives on google. GUI Toolkits are discussed periodically. | >confused at the moment . I would like to develop standalone GUI applic= ation | >executables for The Win32 and Linux platform. |=20 | Tkinter would also run on Macintosh. As far as looks go, Tkinter is | imho the ugliest of interfaces,=20 I agree that Tkinter is ugly. | but I understand wxWindows is closer to the Windows "look." You If you are on MS Windows it is -- wxWindows is a set of wrappers around the native toolkit that provide a consistent API. If you are on unix wxWindows looks like GTK or Motif (depending on which you installed). As I understand it there are also Mac and BeOS ports in progress. | might also consider Gtk+ -- I know there's support for it on | Windows, but not sure how good that is (not being a Windows user). I really like GTK+. The GIMP works quite well on windows, but I haven't tried any other gtk apps that have been ported. Glade and libglade are great for RAD development. There is also Qt. -D From bsass@freenet.edmonton.ab.ca Mon Jul 2 20:49:47 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Mon, 2 Jul 2001 13:49:47 -0600 (MDT) Subject: [Tutor] PyQT's signals and slots *correction In-Reply-To: <01070213084205.00494@yatsu> Message-ID: On Mon, 2 Jul 2001, Brendon wrote: > On Monday 02 July 2001 10:08, you wrote: > > On Sun, 1 Jul 2001, Brendon wrote: > > > On Sunday 01 July 2001 12:43, you wrote: > > > > > > self.buttonConnect.connect(self.buttonConnect, SIGNAL("clicked()"), > > > ????, SLOT("conJ()") > > > > ??? = the object with the SLOT, > > which itself is just a method (as you surmised) > > > > However, I think what you want is... > > > > self.connect(self.buttonConnect, PYSIGNAL("clicked()"), self.conJ) > > > > i.e., the widget connects the buttons "clicked" signal to the > > widgets's conJ method. It is a PYSIGNAL because you are connecting > > between your own objects, not to Qt. > > unless it was created in the class of a custom QT widget, correct? it seems > to work fine with "SIGNAL". Sounds reasonable. <...> > > ...or so I gathered from translating the Qt tutorials into PyQt > > (awhile ago, and I haven't played with it much since, so don't be > > too surprised if I steered you wrong :) > > which was what i ve been using to learn PyQT, it's a small world ;) ...with few resources atm. Maybe have a look at... http://stage.linuxports.com/pyqt/book1.htm It is a pre-release of Boudewijn Rempt's PyQt book, and he is looking for comments... mailto:bsarempt@xs4all.nl - Bruce From allan.crooks@btinternet.com Mon Jul 2 21:05:42 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Mon, 02 Jul 2001 21:05:42 +0100 Subject: [Tutor] sockets Message-ID: > with the following code: > > import sys > import socket > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > loginPacket = ' to="jabber.org" xmlns="jabber:client" > xmlns:stream="http://etherx.jabber.org/streams">' > > s.send(loginPacket) > > data = s.recv(1024) > s.close() > print "Recieved", data > ---- > > i get the error message: s.send(loginPacket) socket.error: (32, 'Broken > pipe'). any clue what i'm doing wrong? I'd suggest taking a look at http://www.python.org/doc/current/lib/socket-example.html. The problem is, you create the socket, but then you aren't connecting it to a particular address. Where exactly are you aiming to send the packet to? Since you aren't telling it, it's not getting sent anywhere... At a guess, you want to send it back to the same machine. The URL I provided gives an example of how to do this.... Allan. From bren@europe.nl.com Mon Jul 2 21:25:12 2001 From: bren@europe.nl.com (Brendon) Date: Mon, 2 Jul 2001 22:25:12 +0200 Subject: [Tutor] sockets In-Reply-To: References: Message-ID: <01070222251204.18714@yatsu> On Monday 02 July 2001 22:05, you wrote: > > with the following code: > > > > import sys > > import socket > > > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > loginPacket = ' > to="jabber.org" xmlns="jabber:client" > > xmlns:stream="http://etherx.jabber.org/streams">' > > > > s.send(loginPacket) > > > > data = s.recv(1024) > > s.close() > > print "Recieved", data > > ---- > > > > i get the error message: s.send(loginPacket) socket.error: (32, 'Broken > > pipe'). any clue what i'm doing wrong? > > I'd suggest taking a look at > http://www.python.org/doc/current/lib/socket-example.html. > > The problem is, you create the socket, but then you aren't connecting it to > a particular address. Where exactly are you aiming to send the packet to? > Since you aren't telling it, it's not getting sent anywhere... hum, true... somehow i must have, er.. overlooked it. i need to have a little patience and stay off this list for awhile :) > At a guess, you want to send it back to the same machine. The URL I > provided gives an example of how to do this.... which i was using, poorly :) back to the tutorials...... Brendon -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From bsass@freenet.edmonton.ab.ca Mon Jul 2 21:38:01 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Mon, 2 Jul 2001 14:38:01 -0600 (MDT) Subject: [Tutor] 1.52 vs 2.1. Problems? In-Reply-To: Message-ID: On Sun, 1 Jul 2001, Deirdre Saoirse Moen wrote: > Download the source tarball, the patch tarball and the .dsc file (the > manifest) from the Debian site (see URL below) > > Then, do the following: > > dpkg-source -x _.dsc > cd -/ > debian/rules build or "debian/rules binary" then install the resulting .deb with "dpkg -i ..." or "debuild", if you want lintian to be run on the package (it may also consider uploading the results to Debian, but fail). > make install - Bruce From deirdre@deirdre.net Mon Jul 2 21:47:37 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Mon, 2 Jul 2001 13:47:37 -0700 Subject: [Tutor] 1.52 vs 2.1. Problems? In-Reply-To: References: Message-ID: At 2:38 PM -0600 7/2/01, Bruce Sass wrote: >On Sun, 1 Jul 2001, Deirdre Saoirse Moen wrote: > >> Download the source tarball, the patch tarball and the .dsc file (the >> manifest) from the Debian site (see URL below) >> >> Then, do the following: >> >> dpkg-source -x _.dsc >> cd -/ >> debian/rules build > >or "debian/rules binary" I got errors when I tried that, which is why I didn't recommend it. Evidently I'm missing some piece of building .deb packages. Since it's not something I normally do, I figured make install wasn't too odious. -- _Deirdre Stash-o-Matic: http://weirdre.com http://deirdre.net "Cannot run out of time.... Is infinite time. You... are finite.... Zathrus... is finite. This... is wrong tool!" -- Zathrus From bren@europe.nl.com Mon Jul 2 23:06:15 2001 From: bren@europe.nl.com (Brendon) Date: Tue, 3 Jul 2001 00:06:15 +0200 Subject: [Tutor] sockets In-Reply-To: References: Message-ID: <01070300061605.18714@yatsu> On Monday 02 July 2001 22:05, you wrote: > > i get the error message: s.send(loginPacket) socket.error: (32, 'Broken > > pipe'). any clue what i'm doing wrong? > > I'd suggest taking a look at > http://www.python.org/doc/current/lib/socket-example.html. > well, just one last question before i dive into the docs. i was wondering how i could write all the data recieved from socket to a file. i.e. #------------------------ # Echo client program import socket HOST = 'jabber.org' # The remote host PORT = 5222 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) loginData = '' s.send(loginData) data = s.recv(1024) s.close() print 'Received', data #------------------------- the statement "data = s.recv(1024)" apparently causes the first 1024 characters to be assigned to 'data', but because eventually it'll go over the limit i want it to write every packet to a file which can be queried later. how do i go about this? -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From wilson@visi.com Mon Jul 2 23:07:56 2001 From: wilson@visi.com (Timothy Wilson) Date: Mon, 2 Jul 2001 17:07:56 -0500 (CDT) Subject: [Tutor] Twin Cities Zope/Python Users Group now open for business Message-ID: Hi everyone, I'm happy to announce that a new Zope/Python Users Group has formed in the Minneapolis/St. Paul area. Our first meeting will be held July 14th at the University of Minnesota in conjunction with the Twin Cities Linux Users Group. More details and instructions for subscribing to the mailing list are available at the group's Web page at http://www.zope.org/Members/tczpug/. -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.org | http://www.zope.org W. St. Paul, MN | | http://slashdot.org wilson@visi.com | | http://linux.com From bsass@freenet.edmonton.ab.ca Mon Jul 2 23:26:43 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Mon, 2 Jul 2001 16:26:43 -0600 (MDT) Subject: [Tutor] 1.52 vs 2.1. Problems? In-Reply-To: Message-ID: On Mon, 2 Jul 2001, Deirdre Saoirse Moen wrote: > At 2:38 PM -0600 7/2/01, Bruce Sass wrote: > >On Sun, 1 Jul 2001, Deirdre Saoirse Moen wrote: > > > >> Download the source tarball, the patch tarball and the .dsc file (the > >> manifest) from the Debian site (see URL below) > >> > >> Then, do the following: > >> > >> dpkg-source -x _.dsc > >> cd -/ > >> debian/rules build > > > >or "debian/rules binary" > > I got errors when I tried that, which is why I didn't recommend it. > Evidently I'm missing some piece of building .deb packages. Since > it's not something I normally do, I figured make install wasn't too > odious. You are building to Debian's specs, but bypassing the package manager by using the source's install (which will not know about stuff generated by the "rules" script). The results will depend on the package; ranging from missing menus and docs, to a broken app. "apt-get install task-debian-devel" should get you everything you need to build .deb-s - Bruce From DavidCraig@PIA.CA.GOV Mon Jul 2 23:54:33 2001 From: DavidCraig@PIA.CA.GOV (DavidCraig@PIA.CA.GOV) Date: Mon, 2 Jul 2001 15:54:33 -0700 Subject: [Tutor] Missing the Obvious Again?? Message-ID: In doing the exercises in "How To Think Like A Computer Scientist (Python)" I am trying the following: def addTime(t1, t2): sum = Time() sum.hour = t1.hour + t2.hour sum.minute = t1.minute + t2.minute sum.second = t1.second + t2.second return sum currentTime = Time() currentTime.hour = 9 currentTime.minute = 14 currentTime.second = 30 breadTime = Time() breadTime.hour = 3 breadTime.minute = 35 breadTime.second = 0 doneTime = addTime(currentTime, breadTime) printTime(doneTime) Here is the output I get: Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> Traceback (most recent call last): File "C:/Python21/Practice/addTime.py", line 24, in ? printTime(doneTime) NameError: name 'printTime' is not defined Must this be defined outside this file? I expect to print the result but continue to get this message. Thanks in advance for any help. Dave D. H. Craig, CSM From allan.crooks@btinternet.com Tue Jul 3 00:01:56 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Tue, 03 Jul 2001 00:01:56 +0100 Subject: [Tutor] Missing the Obvious Again?? Message-ID: > In doing the exercises in "How To Think Like A Computer Scientist (Python)" > I am trying the following: > > def addTime(t1, t2): > sum = Time() > sum.hour = t1.hour + t2.hour > sum.minute = t1.minute + t2.minute > sum.second = t1.second + t2.second > return sum > > currentTime = Time() > currentTime.hour = 9 > currentTime.minute = 14 > currentTime.second = 30 > > breadTime = Time() > breadTime.hour = 3 > breadTime.minute = 35 > breadTime.second = 0 > > doneTime = addTime(currentTime, breadTime) > printTime(doneTime) > > > Here is the output I get: > > Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > >>> > Traceback (most recent call last): > File "C:/Python21/Practice/addTime.py", line 24, in ? > printTime(doneTime) > NameError: name 'printTime' is not defined > > Must this be defined outside this file? I expect to print the result but > continue to get this message. Thanks in advance for any help. In this example, you haven't defined printTime anywhere else. The "printTime(doneTime)" line is the first time you've mentioned printTime, so maybe you've forgotten to define it in the code above. You could replace it with: print doneTime if you wanted to.... Allan. From dyoo@hkn.eecs.berkeley.edu Tue Jul 3 00:34:59 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 2 Jul 2001 16:34:59 -0700 (PDT) Subject: [Tutor] sockets In-Reply-To: <01070300061605.18714@yatsu> Message-ID: On Tue, 3 Jul 2001, Brendon wrote: > > s.send(loginData) > data = s.recv(1024) > > s.close() > print 'Received', data > #------------------------- > the statement "data = s.recv(1024)" apparently causes the first 1024 > characters to be assigned to 'data', but because eventually it'll go > over the limit i want it to write every packet to a file which can be > queried later. You can do the s.recv() in a loop that keeps on pulling data from the socket, until the socket runs dry. ### whole_data = '' while 1: data = s.recv(1024) if not data: break whole_data += data ### Hope this helps! From allan.crooks@btinternet.com Tue Jul 3 00:37:08 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Tue, 03 Jul 2001 00:37:08 +0100 Subject: [Tutor] Missing the Obvious Again?? Message-ID: > Thanks, I made the change you suggested but now I get this: > > <__main__.Time instance at 00B17D5C> Well, that's normal. This depends on whether you have the ability to alter the definition of the Time object or not. If you do, try putting this method inside it: def __str__(self): return "%d hours, %d mins, %d secs" % (self.hour, self.mins, self.secs) That should return a nice formatted string when you print it. If not, then you could always change the print statement to: print doneTime.hours, "hours,", doneTime.mins, "mins,", doneTime.secs, "secs" Hopefully you should understand what is going on here..... Let us know if that isn't the case. Allan. > > > ?? > > > D. H. Craig, CSM > > > > "Allan Crooks" > ernet.com> cc: tutor@python.org > Subject: RE: [Tutor] Missing the Obvious > 07/02/01 04:01 PM Again?? > Please respond to > allan.crooks > > > > > > > > In doing the exercises in "How To Think Like A Computer Scientist > (Python)" > > I am trying the following: > > > > def addTime(t1, t2): > > sum = Time() > > sum.hour = t1.hour + t2.hour > > sum.minute = t1.minute + t2.minute > > sum.second = t1.second + t2.second > > return sum > > > > currentTime = Time() > > currentTime.hour = 9 > > currentTime.minute = 14 > > currentTime.second = 30 > > > > breadTime = Time() > > breadTime.hour = 3 > > breadTime.minute = 35 > > breadTime.second = 0 > > > > doneTime = addTime(currentTime, breadTime) > > printTime(doneTime) > > > > > > Here is the output I get: > > > > Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 > > Type "copyright", "credits" or "license" for more information. > > IDLE 0.8 -- press F1 for help > > >>> > > Traceback (most recent call last): > > File "C:/Python21/Practice/addTime.py", line 24, in ? > > printTime(doneTime) > > NameError: name 'printTime' is not defined > > > > Must this be defined outside this file? I expect to print the result but > > continue to get this message. Thanks in advance for any help. > > In this example, you haven't defined printTime anywhere else. The > "printTime(doneTime)" line is the first time you've mentioned printTime, so > maybe you've forgotten to define it in the code above. > > You could replace it with: > > print doneTime > > if you wanted to.... > > Allan. > > > > > > > From scarblac@pino.selwerd.nl Tue Jul 3 00:46:42 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 3 Jul 2001 01:46:42 +0200 Subject: [Tutor] Language truce In-Reply-To: <20010702145637.A22795@harmony.cs.rit.edu>; from dsh8290@rit.edu on Mon, Jul 02, 2001 at 02:56:37PM -0400 References: <200106281940.f5SJeV801515@cecilia.trollope.org> <20010702145637.A22795@harmony.cs.rit.edu> Message-ID: <20010703014642.A4043@pino.selwerd.nl> On 0, D-Man wrote: > On Thu, Jun 28, 2001 at 02:20:58PM -0700, Danny Yoo wrote: > | One reason that 'for/in' might be preferred is because we are guaranteed > | that the loop will always terminate: there can only be a finite number of > | elements in a list. That's one big advantage of a loop construct that > | goes along elements --- theoretically, we'll never get into infinite > | loops. > > Almost. > > l = range( 1 ) > for i in l : > print l > l.append( i+1 ) > > Don't do this! It's just as bad in C or any other language -- > mutating a collection while iterating over it is just a bad idea. Or even: class InfiniteList: def __getitem__(self, i): return i for i in InfiniteList(): print i (well, it'll end when i doesn't fit into an integer anymore) -- Remco Gerlich From ppathiyi@cisco.com Tue Jul 3 06:19:58 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Tue, 3 Jul 2001 10:49:58 +0530 Subject: [Tutor] sockets References: <01070300061605.18714@yatsu> Message-ID: <0baf01c1037f$cdb585c0$37ef87c0@ppathiyipc> Hi, I think that the connection may have got closed due to some reason. This could be a case where there is a chance of the error message -- socket.error: (32, 'Broken pipe'). Another source of information for socket programming in python would be http://py-howto.sourceforge.net/sockets/sockets.html And if you are interested in the underlying stuff, i would recommend looking at UNIX Network Programming by Richard Stevens. Regards, Praveen. ----- Original Message ----- From: "Brendon" To: Sent: Tuesday, July 03, 2001 3:36 AM Subject: Re: [Tutor] sockets > On Monday 02 July 2001 22:05, you wrote: > > > i get the error message: s.send(loginPacket) socket.error: (32, 'Broken > > > pipe'). any clue what i'm doing wrong? > > > > I'd suggest taking a look at > > http://www.python.org/doc/current/lib/socket-example.html. > > > > well, just one last question before i dive into the docs. i was wondering how > i could write all the data recieved from socket to a file. i.e. > > #------------------------ > # Echo client program > import socket > > HOST = 'jabber.org' # The remote host > PORT = 5222 # The same port as used by the server > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((HOST, PORT)) > > loginData = ' to="jabber.org" xmlns="jabber:client" > xmlns:stream="http://etherx.jabber.org/streams">' > > s.send(loginData) > data = s.recv(1024) > > s.close() > print 'Received', data > #------------------------- > the statement "data = s.recv(1024)" apparently causes the first 1024 > characters to be assigned to 'data', but because eventually it'll go over the > limit i want it to write every packet to a file which can be queried later. > > how do i go about this? > -- > > "if we live by an "eye for an eye and a tooth for a tooth"...before long, > the whole world will be blind and toothless." > --Tevye, Fiddler on the Roof > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ppathiyi@cisco.com Tue Jul 3 08:00:28 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Tue, 3 Jul 2001 12:30:28 +0530 Subject: [Tutor] reversing a string Message-ID: <0c2401c1038d$d9c78c10$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_0C21_01C103BB.F20F9640 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, Is there any methods in string module or any builtin functions = to reverse a string ? I am using Python 1.5.2 Thanks, Praveen. ------=_NextPart_000_0C21_01C103BB.F20F9640 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hi,
 
        Is there any methods in = string=20 module or any builtin functions to reverse a string ? I am using = Python=20 1.5.2
 
Thanks,
Praveen.
------=_NextPart_000_0C21_01C103BB.F20F9640-- From NHYTRO@compuserve.com Tue Jul 3 08:28:16 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Tue, 3 Jul 2001 03:28:16 -0400 Subject: [Tutor] Plug-in system Message-ID: <200107030328_MC3-D7DA-CF58@compuserve.com> Can anyone point me to a place where I can read how to implement a "Pythonic plug-in system"? I have an application that supports Python scripting and I would like to code a comfortable plug-in system for it. I= would not mind if its in C as long as its very basic :-)) Thanks Sharriff = From scarblac@pino.selwerd.nl Tue Jul 3 08:38:02 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 3 Jul 2001 09:38:02 +0200 Subject: [Tutor] reversing a string In-Reply-To: <0c2401c1038d$d9c78c10$37ef87c0@ppathiyipc>; from ppathiyi@cisco.com on Tue, Jul 03, 2001 at 12:30:28PM +0530 References: <0c2401c1038d$d9c78c10$37ef87c0@ppathiyipc> Message-ID: <20010703093802.A4425@pino.selwerd.nl> On 0, Praveen Pathiyil wrote: > Is there any methods in string module or any builtin functions to reverse > a string ? I am using Python 1.5.2 No, there aren't. The easiest is probably to change it into a list, reverse that, then join that back together: import string x = "whee" temp = list(x) temp.reverse() x = string.join(temp, '') print x # prints eehw -- Remco Gerlich From SBrunning@trisystems.co.uk Tue Jul 3 08:43:13 2001 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Tue, 3 Jul 2001 08:43:13 +0100 Subject: [Tutor] reversing a string Message-ID: <31575A892FF6D1118F5800600846864D78BDFD@intrepid> > From: Praveen Pathiyil [SMTP:ppathiyi@cisco.com] > Is there any methods in string module or any builtin functions to > reverse a string ? I am using Python 1.5.2 > Nothing built in that I know of, but it's pretty simple. Try the following (untested): import string def reversestring(inString): letters = list(inString) letters.reverse() return string.join(letters, '') Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From wesc@deirdre.org Tue Jul 3 20:12:09 2001 From: wesc@deirdre.org (Wesley Chun) Date: Tue, 3 Jul 2001 12:12:09 -0700 (PDT) Subject: [Tutor] reversing a string In-Reply-To: <0c2401c1038d$d9c78c10$37ef87c0@ppathiyipc> Message-ID: On Tue, 3 Jul 2001, Praveen Pathiyil wrote: > Is there any methods in string module or any builtin functions to reverse a string ? > I am using Python 1.5.2 as others have pointed out, the answer is no, but the easiest way to do it in Python is to reverse a list. however, if your application requires reverse a massive number of strings continuously, it would probably benefit you to write such functionality as an extension. that way, you won't have a "translation" bottleneck. and as it turns out, this is the extension example in Chapter 20 (Extending Python) in the Core Python Programming text. (shamelss but relative plug i hope!) ;-) if you're not interested in the book, you can still get the code from the book's website (see below). hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From Mark.Tobin@attcanada.com Tue Jul 3 21:49:25 2001 From: Mark.Tobin@attcanada.com (Tobin, Mark) Date: Tue, 3 Jul 2001 14:49:25 -0600 Subject: [Tutor] HTML Generating Message-ID: <3D7C088D6CCFD31190A5009027D30E9103391049@torex004.attcanada.ca> OK... how come when I make a python script such as the one Sheila King posted (below) and execute it through my local IE5.5, it executes in a python window (DOS window) as opposed to in the browser? I'm using PY2.1 on a WIN95 machine with IE5.5. I don't really know how to express this any better (I'm just beginning to pick up some of this new language called "programerese"), but if this isn't clear I'll try again... Thanks in advance, Mark #!/usr/bin/env python import os print "Content-type: text/html\n\n" print "\n" print "" print "Obligatory Python Test Script" print "\n" print "\n" print "

Hello

" print "This is the obligatory
Python 'Hello\' testscript
" print "Ta-da

" print "NEW STUFF: testing environment variables
" print os.environ["REMOTE_ADDR"],"

" print "

And now, all the environment variables:
" print "", for el in os.environ.keys(): print el, " = ", os.environ[el], "
" print "
" print "THE END" print "\n" From sheila@thinkspot.net Tue Jul 3 22:15:36 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 03 Jul 2001 14:15:36 -0700 Subject: [Tutor] HTML Generating In-Reply-To: <3D7C088D6CCFD31190A5009027D30E9103391049@torex004.attcanada.ca> References: <3D7C088D6CCFD31190A5009027D30E9103391049@torex004.attcanada.ca> Message-ID: <822D78045E0@kserver.org> In order to have it "execute in a browser", you would need to have a web server, and have your script in the cgi-bin of the website and call the script by putting a URL that points to the script into the Location in your web browser. Are you trying to learn CGI programming? (This is how you get programs to run on a web page.) Or are you just trying to get your feet wet with programming. CGI programming isn't hard, but it is something additional to learning just the "programming" part. If you want to get it to run on your WIN95 machine, you would need to install a web server on your home machine, get it running, and then have a link to the script on your machine. This is probably not very clear, but I'm sure we can provide more information if you are interested. Let us know. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Tue, 3 Jul 2001 14:49:25 -0600, "Tobin, Mark" wrote about [Tutor] HTML Generating: :OK... how come when I make a python script such as the one Sheila King :posted (below) and execute it through my local IE5.5, it executes in a :python window (DOS window) as opposed to in the browser? I'm using PY2.1 on :a WIN95 machine with IE5.5. I don't really know how to express this any :better (I'm just beginning to pick up some of this new language called :"programerese"), but if this isn't clear I'll try again... : :Thanks in advance, : :Mark : :#!/usr/bin/env python : :import os : :print "Content-type: text/html\n\n" : :print "\n" : :print "" :print "Obligatory Python Test Script" :print "\n" : :print "\n" :print "

Hello

" :print "This is the obligatory
Python 'Hello\' testscript
" :print "Ta-da

" : :print "NEW STUFF: testing environment variables
" :print os.environ["REMOTE_ADDR"],"

" :print "

And now, all the environment variables:
" :print "", :for el in os.environ.keys(): : print el, " = ", os.environ[el], "
" :print "
" :print "THE END" : :print "\n" : :_______________________________________________ :Tutor maillist - Tutor@python.org :http://mail.python.org/mailman/listinfo/tutor From mtobin@bigfoot.com Wed Jul 4 00:02:25 2001 From: mtobin@bigfoot.com (Mark Tobin) Date: Tue, 3 Jul 2001 19:02:25 -0400 Subject: [Tutor] HTML Generating In-Reply-To: <822D78045E0@kserver.org> References: <3D7C088D6CCFD31190A5009027D30E9103391049@torex004.attcanada.ca> Message-ID: <3B4216C1.22821.2D3880@localhost> OK, now I feel just a little bit silly... thanks a lot for the conk on the head... ;-) Mark On 3 Jul 2001, at 14:15, Sheila King wrote: > In order to have it "execute in a browser", you would need to have a web > server, and have your script in the cgi-bin of the website and call the > script by putting a URL that points to the script into the Location in > your web browser. > > Are you trying to learn CGI programming? (This is how you get programs > to run on a web page.) Or are you just trying to get your feet wet with > programming. CGI programming isn't hard, but it is something additional > to learning just the "programming" part. > > If you want to get it to run on your WIN95 machine, you would need to > install a web server on your home machine, get it running, and then have > a link to the script on your machine. > > This is probably not very clear, but I'm sure we can provide more > information if you are interested. Let us know. > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > > > On Tue, 3 Jul 2001 14:49:25 -0600, "Tobin, Mark" > wrote about [Tutor] HTML Generating: > > :OK... how come when I make a python script such as the one Sheila King > :posted (below) and execute it through my local IE5.5, it executes in a > :python window (DOS window) as opposed to in the browser? I'm using PY2.1 on > :a WIN95 machine with IE5.5. I don't really know how to express this any > :better (I'm just beginning to pick up some of this new language called > :"programerese"), but if this isn't clear I'll try again... > : > :Thanks in advance, > : > :Mark > : > :#!/usr/bin/env python > : > :import os > : > :print "Content-type: text/html\n\n" > : > :print "\n" > : > :print "" > :print "Obligatory Python Test Script" > :print "\n" > : > :print "\n" > :print "

Hello

" > :print "This is the obligatory
Python 'Hello\' testscript
" > :print "Ta-da

" > : > :print "NEW STUFF: testing environment variables
" > :print os.environ["REMOTE_ADDR"],"

" > :print "

And now, all the environment variables:
" > :print "", > :for el in os.environ.keys(): > : print el, " = ", os.environ[el], "
" > :print "
" > :print "THE END" > : > :print "\n" > : > :_______________________________________________ > :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 van@lindbergs.org Wed Jul 4 04:36:20 2001 From: van@lindbergs.org (VanL) Date: Tue, 03 Jul 2001 21:36:20 -0600 Subject: [Tutor] lambda vs def Message-ID: <3B428F34.7090906@lindbergs.org> Hello, I have been experimenting with functional programming styles using python, and I was wondering about speed differences. How different is add = lambda x, y: x+y from def add(x, y): return x + y ? Admittedly, this is a trivial example, but for functions called repeatedly, it would add up. Also, how about eval()? Is the cost for parsing prohibitive? Thanks, Van From r.b.rigilink@chello.nl Wed Jul 4 05:42:31 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Wed, 04 Jul 2001 06:42:31 +0200 Subject: [Tutor] lambda vs def References: <3B428F34.7090906@lindbergs.org> Message-ID: <3B429EB7.72B2BAC8@chello.nl> Hi Van, An ounce of measurement beats a pound of argument. VanL wrote: > > Hello, > > I have been experimenting with functional programming styles using > python, and I was wondering about speed differences. How different is > > add = lambda x, y: x+y > > from > > def add(x, y): return x + y ? > No difference, they're exactly the same thing (see below) > Admittedly, this is a trivial example, but for functions called > repeatedly, it would add up. > > Also, how about eval()? Is the cost for parsing prohibitive? > The cost is prohibitive Here's the output of the little Python program I've attached at the end. function : 0.0673129558563 lambda : 0.0682300329208 eval : 3.12110495567 Lamdas are function objects at 0x810d1e4> Bytecode function 0 SET_LINENO 3 3 SET_LINENO 4 6 LOAD_FAST 0 (x) 9 LOAD_FAST 1 (y) 12 BINARY_ADD 13 RETURN_VALUE 14 LOAD_CONST 0 (None) 17 RETURN_VALUE Bytecode lambda 0 SET_LINENO 6 3 LOAD_FAST 0 (x) 6 LOAD_FAST 1 (y) 9 BINARY_ADD 10 RETURN_VALUE -- import time def add1(x, y): return x+y add2 = lambda x, y: x+y t = time.time() for i in xrange(10000): r = add1(1, 2) print 'function :', time.time()-t t = time.time() for i in xrange(10000): r = add2(1, 2) print 'lambda :', time.time()-t t = time.time() for i in xrange(10000): r = eval('1+2') print 'eval :', time.time()-t print 'Lamdas are function objects' print add1, add2 import dis print 'Bytecode function' dis.dis(add1) print 'Bytecode lambda' dis.dis(add2) -- Hope this helps, Roeland -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From scarblac@pino.selwerd.nl Wed Jul 4 06:39:37 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 4 Jul 2001 07:39:37 +0200 Subject: [Tutor] lambda vs def In-Reply-To: <3B428F34.7090906@lindbergs.org>; from van@lindbergs.org on Tue, Jul 03, 2001 at 09:36:20PM -0600 References: <3B428F34.7090906@lindbergs.org> Message-ID: <20010704073937.A6300@pino.selwerd.nl> On 0, VanL wrote: > I have been experimenting with functional programming styles using > python, and I was wondering about speed differences. How different is > > add = lambda x, y: x+y > > from > > def add(x, y): return x + y ? > > Admittedly, this is a trivial example, but for functions called > repeatedly, it would add up. They're exactly the same, as Roeland said (the difference is that add.func_name is different). I just wanted to add that operator.add is an existing function that does the same, and it is written in C. And if you want it very fast, you first make that add into a local variable (since local variable lookup is very fast); so usually you'd do 'from operator import add' instead of the lambda or the def. > Also, how about eval()? Is the cost for parsing prohibitive? About 42, I'd say. It all depends on your needs. Use the profile.run() function to test how much time something takes, and compare. Or better yet, don't. Don't worry about speed until your program works and you find it is too slow. *Then* use the profiler to find out where the problem is. It's likely that most of the time is spent in quite a small region, and there you probably get the most gain from improving the algorithm instead of trying to locally optimize the Python code. -- Remco Gerlich From ppathiyi@cisco.com Wed Jul 4 07:06:11 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 4 Jul 2001 11:36:11 +0530 Subject: [Tutor] Bit Manipulations Message-ID: <009001c1044f$6da7b740$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_008D_01C1047D.8652F010 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi All, Where will i get some info about bitwise operations in python ? = I am trying to determine whether the MSB of a byte is 0 or 1. Thanks, Praveen. ------=_NextPart_000_008D_01C1047D.8652F010 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hi All,
 
        Where will i get some info = about=20 bitwise operations in python ? I am trying to determine whether the MSB = of a=20 byte is 0 or 1.
 
Thanks,
Praveen.
------=_NextPart_000_008D_01C1047D.8652F010-- From ppathiyi@cisco.com Wed Jul 4 07:25:19 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 4 Jul 2001 11:55:19 +0530 Subject: [Tutor] Bit Manipulations References: <009001c1044f$6da7b740$37ef87c0@ppathiyipc> Message-ID: <00a401c10452$19135010$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_00A1_01C10480.32A6C600 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Actually i was a bit lazy. I checked out the bitwise operators. But the = problem for me is that the input is a hex value. So do i have to convert = that into an integer before i apply the bitwise operators ? Thx, Praveen. ----- Original Message -----=20 From: Praveen Pathiyil=20 To: tutor@python.org=20 Sent: Wednesday, July 04, 2001 11:36 AM Subject: [Tutor] Bit Manipulations Hi All, Where will i get some info about bitwise operations in python = ? I am trying to determine whether the MSB of a byte is 0 or 1. Thanks, Praveen. ------=_NextPart_000_00A1_01C10480.32A6C600 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Actually i was a bit lazy. I checked out the bitwise operators. But = the=20 problem for me is that the input is a hex value. So do i have to convert = that=20 into an integer before i apply the bitwise operators ?
 
Thx,
Praveen.
----- Original Message -----
From:=20 Praveen=20 Pathiyil
Sent: Wednesday, July 04, 2001 = 11:36=20 AM
Subject: [Tutor] Bit = Manipulations

 
Hi All,
 
        Where will i get some info = about=20 bitwise operations in python ? I am trying to determine whether the = MSB of a=20 byte is 0 or 1.
 
Thanks,
Praveen.
------=_NextPart_000_00A1_01C10480.32A6C600-- From dyoo@hkn.eecs.berkeley.edu Wed Jul 4 08:01:35 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jul 2001 00:01:35 -0700 (PDT) Subject: [Tutor] lambda vs def In-Reply-To: <3B429EB7.72B2BAC8@chello.nl> Message-ID: On Wed, 4 Jul 2001, Roeland Rengelink wrote: > > > > Hello, > > > > I have been experimenting with functional programming styles using > > python, and I was wondering about speed differences. How different is > > > > add = lambda x, y: x+y > > > > from > > > > def add(x, y): return x + y ? > > > > No difference, they're exactly the same thing (see below) In this particular example, it might be better to use operator.add(), because it should have a speed advantage from what I remember. I have a feeling, though, that I'd better back that up with something plausable. ### import time from random import randint ONE_MILLION = 10**6 def add1(x, y): return x+y add2 = lambda x, y: x+y from operator import add as add3 def doTimeTrials(adding_function, arguments): start = time.time() for argument_list in arguments: apply(adding_function, argument_list) stop = time.time() return stop - start if __name__ == '__main__': random_number_pairs = [ (randint(101, ONE_MILLION), randint(101, ONE_MILLION)) for i in range(2000) ] print 'function :', doTimeTrials(add1, random_number_pairs) print 'lambda :', doTimeTrials(add2, random_number_pairs) print 'operator :', doTimeTrials(add3, random_number_pairs) ### Some of those mysterious constants are there to try to avoid the caching behavior that Python does on numbers smaller than 101. I don't know if it will be effective, but at least the random numbers will keep the addition functions on their toes... *grin* Let's see what happens. ### # Let's call this program a few times. dyoo@coffeetable:~$ python timer.py function : 0.0131589174271 lambda : 0.0132449865341 operator : 0.0109980106354 dyoo@coffeetable:~$ python timer.py function : 0.0132310390472 lambda : 0.0132108926773 operator : 0.0110750198364 dyoo@coffeetable:~$ python timer.py function : 0.0133099555969 lambda : 0.0131999254227 operator : 0.0110510587692 dyoo@coffeetable:~$ python timer.py function : 0.0131978988647 lambda : 0.013288974762 operator : 0.0109850168228 dyoo@coffeetable:~$ python timer.py function : 0.0132899284363 lambda : 0.0141140222549 operator : 0.0118650197983 ### To tell the truth, all of them look very evenly matched, so you probably shouldn't worry about the efficiency difference between these three definitions. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Jul 4 08:05:22 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jul 2001 00:05:22 -0700 (PDT) Subject: [Tutor] Bit Manipulations In-Reply-To: <00a401c10452$19135010$37ef87c0@ppathiyipc> Message-ID: On Wed, 4 Jul 2001, Praveen Pathiyil wrote: > Actually i was a bit lazy. I checked out the bitwise operators. But > the problem for me is that the input is a hex value. So do i have to > convert that into an integer before i apply the bitwise operators ? How is the program inputting the numbers in? Python will automatically represent the numbers appropriately as 32-bit integers if we enter hexidecimal like this: ### >>> 0x8 8 >>> 0x9 9 >>> 0xa 10 >>> 0xb 11 >>> 0xc 12 >>> 0xd 13 >>> 0xe 14 >>> 0xf 15 >>> 0x10 16 ### However, if we're getting the input as strings, then yes, we'll need to convert them with the int() function. From dyoo@hkn.eecs.berkeley.edu Wed Jul 4 08:17:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jul 2001 00:17:24 -0700 (PDT) Subject: [Tutor] URLs for urllib.urlopen In-Reply-To: <31575A892FF6D1118F5800600846864D78BDF3@intrepid> Message-ID: On Mon, 2 Jul 2001, Simon Brunning wrote: > > From: Danny Yoo [SMTP:dyoo@hkn.eecs.berkeley.edu] > > Very strange! This seems to work for me, trailing slash or not. Can you > > check to see if that error happens again? Does anyone else know what > > would cause the above? > > Danny, > Hmmm. It's definitely happening - but only at work. It works fine at home. > > It also happens to other people at my office too - I reckon that the proxy > is up to something. > > Sorry to confuse everyone. Don't worry about it; if you ever do figure out why it's doing that, tell us so we can be better informed... *grin* From dyoo@hkn.eecs.berkeley.edu Wed Jul 4 08:22:35 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jul 2001 00:22:35 -0700 (PDT) Subject: [Tutor] wxPython - how to 'focus'? In-Reply-To: <000901c1031b$4437ea40$0100007f@localdomain> Message-ID: On Mon, 2 Jul 2001, Hanna Joo wrote: > Hello all > > I am trying to build in 'LostFocus' and 'GotFocus' (Visual Basic terms, I > think) into my simple wxPython program. So far, I managed to find two > entries on events re 'Focus': > -- EVT_SET_FOCUS and EVT_KILL_FOCUS > there are a few other methods from wxWindow class: onSetFocus and > OnKillFocus. What I want to do is quite simple. I want the second textbox to > set its value when the first textbox loses focus. Dear Hanna, I haven't touched wxPython before, and I've noticed that your message hasn't been answered yet; I don't think we have enough wxPython users here to adequately answer your question. You might want to ask your question on the wxPython-users mailing list --- it should have people who are more experienced with your graphics library: http://www.wxpython.org/maillist.php I hope that someone there can help. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Wed Jul 4 08:44:49 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jul 2001 00:44:49 -0700 (PDT) Subject: [Tutor] sockets In-Reply-To: Message-ID: On Mon, 2 Jul 2001, Danny Yoo wrote: > > s.close() > > print 'Received', data > > #------------------------- > > > the statement "data = s.recv(1024)" apparently causes the first 1024 > > characters to be assigned to 'data', but because eventually it'll go > > over the limit i want it to write every packet to a file which can be > > queried later. > > You can do the s.recv() in a loop that keeps on pulling data from the > socket, until the socket runs dry. > > ### > whole_data = '' > while 1: > data = s.recv(1024) > if not data: break > whole_data += data > ### > Err... that is, until the socket blocks. *sigh* I just tried the example, and the program stalls after one iteration of the loop. The problem lies on this line: data = s.recv(1024) If the server doesn't have anything to send, but if we don't want to terminate the connection, we'll twiddle our fingers and wait. In a sense, we'll "block" until the server starts sending us something interesting. (The same sort of behavior is responsible for what allows raw_input() to "pause" the system: the system is waiting for input from us, and is essentially "blocked".) What you'll probably want to look at is a way of asking the socket: "if there's anything interesting coming at us from the server, tell us about it. But if not, let me do my own thing." I think this is asynchronous io, but I've never actually played with async stuff before. You might want to look at: http://python.org/doc/lib/module-asyncore.html which seems to have some good documentation on doing asyncronous IO. I'll need to take a look at the Stevens book myself, one of these days, to understand what's happening. From bren@europe.nl.com Wed Jul 4 08:53:26 2001 From: bren@europe.nl.com (Brendon) Date: Wed, 4 Jul 2001 09:53:26 +0200 Subject: [Tutor] sockets In-Reply-To: References: Message-ID: <01070409532600.06568@yatsu> On Wednesday 04 July 2001 09:44, you wrote: > On Mon, 2 Jul 2001, Danny Yoo wrote: > What you'll probably want to look at is a way of asking the socket: "if > there's anything interesting coming at us from the server, > tell us about > it. But if not, let me do my own thing." yup.. > I think this is asynchronous > io, but I've never actually played with async stuff before. You might > want to look at: > > http://python.org/doc/lib/module-asyncore.html > > which seems to have some good documentation on doing asyncronous IO. > I'll need to take a look at the Stevens book myself, one of these days, to > understand what's happening. more documents to read, there goes my summer holiday :) -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From ppathiyi@cisco.com Wed Jul 4 08:58:17 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 4 Jul 2001 13:28:17 +0530 Subject: [Tutor] Bit Manipulations References: Message-ID: <00db01c1045f$15ee2f60$37ef87c0@ppathiyipc> HI, The operation is to be done on an input obtained from the recv() call. The other side is sending the data in binary format. For parsing, what we do is to represent each byte by the corresponding 2-digit hex value. i.e., 1010 0101 will be converted as a5. It is from such a hex value that i have to find the value of the MSB. I guess i can just check whether the first digit in the hex representation is less than 8, right ? Can we do direct operations on the binary input got from the recv() call ? How will python treat such input ? I mean as which type should we take them ? Thx, Praveen. ----- Original Message ----- From: "Danny Yoo" To: "Praveen Pathiyil" Cc: Sent: Wednesday, July 04, 2001 12:35 PM Subject: Re: [Tutor] Bit Manipulations > On Wed, 4 Jul 2001, Praveen Pathiyil wrote: > > > Actually i was a bit lazy. I checked out the bitwise operators. But > > the problem for me is that the input is a hex value. So do i have to > > convert that into an integer before i apply the bitwise operators ? > > How is the program inputting the numbers in? Python will automatically > represent the numbers appropriately as 32-bit integers if we enter > hexidecimal like this: > > ### > >>> 0x8 > 8 > >>> 0x9 > 9 > >>> 0xa > 10 > >>> 0xb > 11 > >>> 0xc > 12 > >>> 0xd > 13 > >>> 0xe > 14 > >>> 0xf > 15 > >>> 0x10 > 16 > ### > > However, if we're getting the input as strings, then yes, we'll need to > convert them with the int() function. > > From ppathiyi@cisco.com Wed Jul 4 09:11:21 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 4 Jul 2001 13:41:21 +0530 Subject: [Tutor] sockets References: <01070409532600.06568@yatsu> Message-ID: <00eb01c10460$e9871480$37ef87c0@ppathiyipc> Hi, There is a select module which gives you the asynchronous behaviour. The select call returns the socket descriptor on which there is any data to be read. Calling this in a separate thread could do the job. Hence if you want to do some processing while you wait for the data to arrive, you can use the select call. http://www.python.org/doc/current/lib/module-select.html If you would like to take a look at more code which does similar things, there is a page about the Medusa project. This was referred to me by Danny when i was doing some stuff on telnet server. It really bailed me out on a couple of occasions. http://www.nightmare.com/medusa/ Regards, Praveen. ----- Original Message ----- From: "Brendon" To: Sent: Wednesday, July 04, 2001 1:23 PM Subject: Re: [Tutor] sockets > On Wednesday 04 July 2001 09:44, you wrote: > > On Mon, 2 Jul 2001, Danny Yoo wrote: > > What you'll probably want to look at is a way of asking the socket: "if > > there's anything interesting coming at us from the server, > > tell us about > > it. But if not, let me do my own thing." > > yup.. > > > I think this is asynchronous > > io, but I've never actually played with async stuff before. You might > > want to look at: > > > > http://python.org/doc/lib/module-asyncore.html > > > > which seems to have some good documentation on doing asyncronous IO. > > I'll need to take a look at the Stevens book myself, one of these days, to > > understand what's happening. > > more documents to read, there goes my summer holiday :) > > -- > > "if we live by an "eye for an eye and a tooth for a tooth"...before long, > the whole world will be blind and toothless." > --Tevye, Fiddler on the Roof > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From van@lindbergs.org Wed Jul 4 10:14:21 2001 From: van@lindbergs.org (VanL) Date: Wed, 04 Jul 2001 03:14:21 -0600 Subject: [Tutor] Infinite recursion or too big a problem? Message-ID: <3B42DE6D.5000303@lindbergs.org> Hello, Thanks to everyone who contributed insight about lambda functions. I have a different, though related problem: I am (re)writing a logfile analyzer for my work, and just for fun I am doing it in a functional style. Here is what I want to do: Starting at a certain directory, find all files named 'log' and put them in a list. I will analyze them later in the program. (Yes, I know about os.path.walk, that is how I did it the first time. I was trying something different). To give an idea of the scope of the problem, there is not more than one logfile in each directory, and the completed list would have between six and eight thousand items in it. Now, just for fun, I am doing this in a functional style. (Probably bad functional style; the result is the closest thing to obfuscated python that I have ever seen!) When I run the code I wrote, it appears to work, but after a minute or two I get a runtime error, "Maximum recursion depth exceeded". I think I wrote this correctly, but do I have infinite recursion that I haven't caught somewhere? Also, comments on style are appreciated. Thanks, Van Begin code::::::::: #!/usr/bin/env python """ Pylog, version 2. Written in functional style, just for fun. """ # Imports import os, string # Globals # Force local evaluation of selected module functions list_directory = os.listdir is_directory = os.path.isdir is_file = os.path.isfile abs_path = os.path.abspath string_find = string.find # Functions ## my apply functions do = lambda func: func() doSequence = lambda functionlist: map(do, functionlist) ## identity functions isDir = lambda fileobj: is_directory(fileobj) isFile = lambda fileobj: is_file(fileobj) isLogfile = lambda filename: (is_file(filename)) and (filename == 'log') ## list generating functions concatenate = lambda seq1, seq2: seq1 + seq2 getFileList = lambda dir: list_directory(dir) getDirectories = lambda fileobjs: filter(isDir, fileobjs) getLogfiles = lambda fileobjs: filter(isLogfile, fileobjs) getAllLogfiles = lambda dirname: reduce(concatenate, [], getLogfiles(getFileList(abs_path(dirname))) + map(getAllLogfiles, map(abs_path, getDirectories(getFileList(dirname))))) From scarblac@pino.selwerd.nl Wed Jul 4 10:10:28 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 4 Jul 2001 11:10:28 +0200 Subject: [Tutor] Bit Manipulations In-Reply-To: <00db01c1045f$15ee2f60$37ef87c0@ppathiyipc>; from ppathiyi@cisco.com on Wed, Jul 04, 2001 at 01:28:17PM +0530 References: <00db01c1045f$15ee2f60$37ef87c0@ppathiyipc> Message-ID: <20010704111028.A6389@pino.selwerd.nl> On 0, Praveen Pathiyil wrote: > Can we do direct operations on the binary input got from the recv() call ? > How will python treat such input ? I mean as which type should we take them > ? You can have arbitrary binary data in a Python string. Check out the struct module to see how you can convert from and to binary data in general. -- Remco Gerlich From lonetwin@yahoo.com Wed Jul 4 10:46:01 2001 From: lonetwin@yahoo.com (steve) Date: Wed, 4 Jul 2001 15:16:01 +0530 Subject: [Tutor] About UserDict class Message-ID: <01070415160106.15338@mercury.in.cqsl.com> Greetings everyone, I'd like someone to explain this thing to me .... I have a class mp3file (given below in entierty), which inherits from the= =20 UserDict class, when I create a class instance from the intepreter window= , it=20 initialises the tagdata (ie: reads the ID3 TAG and fills the dict with=20 key/value pairs)...funny thing is when I do the same from the command lin= e=20 (create an object, associated with a file name passed as the argument) it= =20 does not initialise the tagdata.... I have no idea what's going wrong !! Thanx & Peace Steve the code : (I've given the sample op after the code) ############################################################### #!/usr/bin/python2.0 from UserDict import UserDict import re=20 import curses=20 import os=20 def stripnulls(data): "strip whitespace and nulls" return data.replace("\0", " ").strip() class mp3file(UserDict): =09tagDataMap =3D { "title" : ( 3, 33, stripnulls) =09=09=09"artist" : ( 33, 63, stripnulls), =09=09=09"album" : ( 63, 93, stripnulls), =09=09=09"year" : ( 93, 97, stripnulls), =09=09=09"comment" : ( 96, 126, stripnulls), =09=09=09"genre" : (127, 128, ord) } =09rulez =3D { ('One or more underscores', '_+' ) : [ 1= , ' '], =09=09 ('Two or more hypens', '-{2,}' ) : [ 1, '-'], =09=09 ('An ampersand', '&' ) : [ 1, 'And'= ], =09=09 ('Words that have a hypen between them', '(-)(\w*)') : [ 1, r' \1= \2'] } =09def __init__(self, flname =3D None): =09=09UserDict.__init__(self) =09=09self["old_name"] =3D flname =09=09self["name"] =3D flname =09 =09def __parse(self, flname): =09=09try: =09=09=09fl =3D open(flname, "rb", 0) =09=09=09try: =09=09=09=09fl.seek(-128, 2) =09=09=09=09tagdata =3D fl.read() =09=09=09finally: =09=09=09=09fl.close() =09=09=09if tagdata[:3] =3D=3D 'TAG': =09=09=09=09for tag, (start, end, parseFunc) in self.tagDataMap.items(): =09=09=09=09=09self[tag] =3D parseFunc(tagdata[start:end]) =09=09except IOError: =09=09=09pass =09=09=09 =09=09 =09def __setitem__(self, key, item): =09=09if key =3D=3D "name" and item: =09=09=09self.__parse(item) =09=09elif key in [ "title", "artist", "album", "comment" ]: =09=09=09item =3D item[:30]=09=09# Truncate upto 30 chars =09=09elif key =3D=3D "year": =09=09=09item =3D item[:4]=09=09=09# Trancate upto 4 chars =09=09UserDict.__setitem__(self, key, item) =09def changeName(self): =09=09for k in self.rulez.keys(): =09=09=09if self.rulez[k][0]: =09=09=09=09self["name"] =3D re.sub(k[1], self.rulez[k][1], self["name"]) =09=09self["name"] =3D ' '.join([ x.capitalize() for x in self["name"].sp= lit()]) =09def changeTag(self, tagdata): =09=09for tag in tagdata.keys(): =09=09=09self[tag] =3D tagdata[tag] =09 =09def writeTag(self): =09=09try: =09=09=09tag =3D 'TAG%-30s%-30s%-30s%-4s%-30s%s' % \ =09=09=09=09=09( self["title"], self["artist"], self["album"], =09=09=09=09=09 self["year"], self["comment"], chr(self["genre"])) =09=09=09try: =09=09=09=09fl =3D open(self["name"], "rb") =09=09=09=09p =3D fl.read() =09=09=09=09fl.close() =09=09=09=09p =3D p[:-128]+tag =09=09=09=09fl =3D open(self["name"], "wb") =09=09=09=09fl.write(p) =09=09=09finally: =09=09=09=09fl.close() =09=09except IOError: =09=09=09return 1 =09 if __name__ =3D=3D '__main__': #=09print "Not yet ready ..." =09initial_flist =3D os.sys.argv[1:] or os.listdir('./*.mp3') =09names =3D [] =09for file in initial_flist: =09=09dirnm =3D os.path.dirname(file) =09=09fl =3D mp3file(os.path.basename(file)) =09=09print fl =09=09raw_input() ################################################## output : ################################################## =09in the intepreter: Python 2.1 (#3, Jun 25 2001, 13:39:27)=20 [GCC 2.95.3 19991030 (prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import foo >>> fl =3D foo.mp3file('/home/steve/Mp3s/Eagles/Eagles - Full Album - Gre= atest=20 Hits.mp3') >>> print fl {'artist': 'Eagles', 'genre': 0, 'old_name': '/home/steve/Mp3s/Eagles/Eag= les=20 - Full Album - Greatest Hits.mp3', 'name': '/home/steve/Mp3s/Eagles/Eagle= s -=20 Full Album - Greatest Hits.mp3', 'title': 'Greatest Hits', 'year': '',=20 'comment': '', 'album': 'Greatest Hits'} >>>=20 =09on the prompt: $ foo.py /home/steve/Mp3s/Eagles/Eagles - Full Album - Greatest Hits.mp3 {'old_name': 'Eagles', 'name': 'Eagles'} =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=09 It is so very hard to be an on-your-own-take-care-of-yourself-because- there-is-no-one-else-to-do-it-for-you grown-up. =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 From van@lindbergs.org Wed Jul 4 10:55:24 2001 From: van@lindbergs.org (VanL) Date: Wed, 04 Jul 2001 03:55:24 -0600 Subject: [Tutor] Infinite recursion or too big a problem? References: <3B42DE6D.5000303@lindbergs.org> Message-ID: <3B42E80C.2000803@lindbergs.org> Upn rereading my post, it is not clear what I am calling. It is this function (the last writtent): > > getAllLogfiles = lambda dirname: reduce(concatenate, [], > getLogfiles(getFileList(abs_path(dirname))) + > map(getAllLogfiles, map(abs_path, getDirectories(getFileList(dirname))))) > Sample editor session: >>> import Pylog2 >>> lst = Pylog2.getAllLogfiles('.') [time goes by ...] [snip a bunch of errors identical to the top one listed below ...] File "Pylog2.py", line 34, in getAllLogfiles = lambda dirname: reduce(concatenate, [], getLogfiles(getFileList(abs_path(dirname))) + map(getAllLogfiles, map(abs_path, getDirectories(getFileList(dirname))))) File "Pylog2.py", line 34, in getAllLogfiles = lambda dirname: reduce(concatenate, [], getLogfiles(getFileList(abs_path(dirname))) + map(getAllLogfiles, map(abs_path, getDirectories(getFileList(dirname))))) File "Pylog2.py", line 33, in getLogfiles = lambda fileobjs: filter(isLogfile, fileobjs) File "Pylog2.py", line 27, in isLogfile = lambda filename: (is_file(filename)) and (filename == 'log') File "/usr/local/lib/python2.0/posixpath.py", line 195, in isfile return stat.S_ISREG(st[stat.ST_MODE]) File "/usr/local/lib/python2.0/stat.py", line 55, in S_ISREG return S_IFMT(mode) == S_IFREG RuntimeError: Maximum recursion depth exceeded >>> From lonetwin@yahoo.com Wed Jul 4 11:12:39 2001 From: lonetwin@yahoo.com (steve) Date: Wed, 4 Jul 2001 15:42:39 +0530 Subject: [Tutor] About UserDict class !!! In-Reply-To: <01070415160106.15338@mercury.in.cqsl.com> References: <01070415160106.15338@mercury.in.cqsl.com> Message-ID: <01070415400507.15338@mercury.in.cqsl.com> M SORRY SORRY SORRY !!!! t'was a kludge, I failed to see, An' now I've made, An Ass of me !!! < with his head down in shame >=20 Peace Steve > Greetings everyone, > I'd like someone to explain this thing to me .... > I have a class mp3file (given below in entierty), which inherits from t= he > UserDict class, when I create a class instance from the intepreter wind= ow, > it initialises the tagdata (ie: reads the ID3 TAG and fills the dict wi= th > key/value pairs)...funny thing is when I do the same from the command l= ine > (create an object, associated with a file name passed as the argument) = it > does not initialise the tagdata.... > I have no idea what's going wrong !! > > Thanx & Peace > Steve > > the code : (I've given the sample op after the code) =2E..... =2E..... =2E..... --=20 |||||||||||||||||||||| |||||||||#####|||||||| ||||||||#######||||||| ||||||||# O O #||||||| ||||||||#\ ~ /#||||||| ||||||##||\_/||##||||| |||||#||||||||||##|||| ||||#||||||||||||##||| ||||#|||||||||||||##||=09 |||/\##|||||||||##/\||=09 |/ \#########/ \=09 |\ \#######/ /=09 ||\____/#######\____/|=09 =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=09 It is so very hard to be an on-your-own-take-care-of-yourself-because- there-is-no-one-else-to-do-it-for-you grown-up. =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 From wheelege@tsn.cc Wed Jul 4 11:06:22 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Wed, 4 Jul 2001 20:06:22 +1000 Subject: [Tutor] import question Message-ID: <012101c10470$fa85b740$0200a8c0@ACE> This is a multi-part message in MIME format. ------=_NextPart_000_011E_01C104C4.CBB32160 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hey Tutorians, I've got a little query regarding importing. Say I've got several = modules, one main module and the others are specific functional modules. My problem is that I have a few classes defined in the main module, = and these are useful to all the auxilary modules. The badness? Python = spews when I try to do it. In fact, I get very weird results. ###mainmodule### import aux1,aux2,aux3 #--code--# ###aux1### from mainmodule import uniclass #--code--# and when I try to run mainmodule pythonwin spits with an error in aux1 - = saying mainmodule has no attribute uniclass, which is just wrong. If I = run it again then it dies when I try to use a class from aux1 (or any of = the other modules), which makes sense if the original import died. I figured I could try something along the lines of... ###aux1### uniclass =3D mainmodule.uniclass #--code--# But of course this does not work. Is there a way to refer to the = module which imported the current module? Like with bases in classes? Any help would be greatly appreciated, Glen. ------=_NextPart_000_011E_01C104C4.CBB32160 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
  Hey Tutorians,
 
  I've got a little query regarding importing.  Say I've = got=20 several modules, one main module and the others are specific functional=20 modules.
  My problem is that I have a few classes defined in the main = module,=20 and these are useful to all the auxilary modules.  The = badness? =20 Python spews when I try to do it.  In fact, I get very weird = results.
 
###mainmodule###
import aux1,aux2,aux3
 
#--code--#
 
###aux1###
from mainmodule import uniclass
 
#--code--#
 
and when I try to run mainmodule pythonwin spits with an error in = aux1 -=20 saying mainmodule has no attribute uniclass, which is just wrong.  = If I run=20 it again then it dies when I try to use a class from aux1 (or any of the = other=20 modules), which makes sense if the original import died.
  I figured I could try something along the lines of...
 
###aux1###
uniclass =3D mainmodule.uniclass
 
#--code--#
 
  But of course this does not work.  Is there a way to = refer to=20 the module which imported the current module?  Like with bases in=20 classes?
 
  Any help would be greatly appreciated,
  Glen.
------=_NextPart_000_011E_01C104C4.CBB32160-- From scarblac@pino.selwerd.nl Wed Jul 4 11:26:19 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 4 Jul 2001 12:26:19 +0200 Subject: [Tutor] import question In-Reply-To: <012101c10470$fa85b740$0200a8c0@ACE>; from wheelege@tsn.cc on Wed, Jul 04, 2001 at 08:06:22PM +1000 References: <012101c10470$fa85b740$0200a8c0@ACE> Message-ID: <20010704122619.A6783@pino.selwerd.nl> On 0, Glen Wheeler wrote: > Hey Tutorians, > > I've got a little query regarding importing. Say I've got several modules, one main module and the others are specific functional modules. > My problem is that I have a few classes defined in the main module, and these are useful to all the auxilary modules. The badness? Python spews when I try to do it. In fact, I get very weird results. > > ###mainmodule### > import aux1,aux2,aux3 > > #--code--# > > ###aux1### > from mainmodule import uniclass > > #--code--# > > and when I try to run mainmodule pythonwin spits with an error in aux1 - > saying mainmodule has no attribute uniclass, which is just wrong. If I run > it again then it dies when I try to use a class from aux1 (or any of the > other modules), which makes sense if the original import died. Look closely what happens: in the main module, you do the import *before* your class definitions. So *at the time the aux1 module is run*, uniclass doesn't exist yet! Usually, you can solve this though by doing the imports in the main module at the bottom of the file, when the classes have already been defined. Also, in many cases not using "from...import" works, because the class is only used inside of functions, so it's only looked up when the function is run. Lots of problems can be avoided by never using "from...import" :-) Generally "circular imports" are a bit dodgy and sometimes a sign of bad design, at least, I often have the feeling that there's a cleaner design lurking just outside my range of thought somewhere. "Learning Python" has a nice explanation of this phenomenon under "Module Gotchas", and their advice is basically: "Don't do that...really!" :-). Redesigning helps. -- Remco Gerlich From bren@europe.nl.com Wed Jul 4 11:56:11 2001 From: bren@europe.nl.com (Brendon) Date: Wed, 4 Jul 2001 12:56:11 +0200 Subject: [Tutor] sockets In-Reply-To: References: Message-ID: <01070412561100.07515@yatsu> On Thursday 01 January 1970 00:59, you wrote: > On Mon, 2 Jul 2001, Danny Yoo wrote: > > > s.close() > > > print 'Received', data > > > #------------------------- > > > > > > the statement "data = s.recv(1024)" apparently causes the first 1024 > > > characters to be assigned to 'data', but because eventually it'll go > > > over the limit i want it to write every packet to a file which can be > > > queried later. > > > > You can do the s.recv() in a loop that keeps on pulling data from the > > socket, until the socket runs dry. > > > > ### > > whole_data = '' > > while 1: > > data = s.recv(1024) > > if not data: break > > whole_data += data > > ### > > Err... that is, until the socket blocks. *sigh* I just tried the > example, and the program stalls after one iteration of the loop. The > problem lies on this line: > > data = s.recv(1024) > > If the server doesn't have anything to send, but if we don't want to > terminate the connection, we'll twiddle our fingers and wait. In a sense, > we'l > l "block" until the server starts sending us something interesting. > (The same sort of behavior is responsible for what allows raw_input() to > "pause" the system: the system is waiting for input from us, and is > essentially "blocked".) > > What you'll probably want to look at is a way of asking the socket: "if > there's anything interesting coming at us from the server, tell us about > it. But if not, let me do my own thing." I think this is asynchronous > io, but I've never actually played with async stuff before. You might > want to look at: > > http://python.org/doc/lib/module-asyncore.html > > which seems to have some good documentation on doing asyncronous IO. > I'll need to take a look at the Stevens book myself, one of these days, to > understand what's happening. hmm, but.. what i want to happen is when data arrives, it gets thrown into a file where it is validated and parsed after which the socket waits for data again. so how do IM clients (and, actually.. just about everything that operates with a network connection) do this then? threading i'm guessing but i once heard mentioned that it wasn't ideal. basically, what needs to be done is have a socket that keepson receiving data while the rest of the program does it's thing. i.e. parse that data and handle UI events. from http://www.nightmare.com/pythonwin/async_sockets.html: "What is 'asynchronous socket programming'? a.k.a. event-driven programming or select()-based multiplexing, it's a solution to a network programming problem: How do I talk to bunch of different network connections at once, all within one process/thread?" which isn't what i'm looking for, i think (?). -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From wheelege@tsn.cc Wed Jul 4 12:10:59 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Wed, 4 Jul 2001 21:10:59 +1000 Subject: [Tutor] import question References: <012101c10470$fa85b740$0200a8c0@ACE> <20010704122619.A6783@pino.selwerd.nl> Message-ID: <01b201c1047a$b189bdc0$0200a8c0@ACE> > On 0, Glen Wheeler wrote: > > Hey Tutorians, > > > > <...snip!...> > > > > and when I try to run mainmodule pythonwin spits with an error in aux1 - > > saying mainmodule has no attribute uniclass, which is just wrong. If I run > > it again then it dies when I try to use a class from aux1 (or any of the > > other modules), which makes sense if the original import died. > > Look closely what happens: in the main module, you do the import *before* > your class definitions. So *at the time the aux1 module is run*, uniclass > doesn't exist yet! > *clonk!* Silly me :) > Usually, you can solve this though by doing the imports in the main module > at the bottom of the file, when the classes have already been defined. > Yes...but...urgh so not-nice...hmmm I'm sure you know what I'm trying to express here :). > Also, in many cases not using "from...import" works, because the class is > only used inside of functions, so it's only looked up when the function is > run. Lots of problems can be avoided by never using "from...import" :-) > Indeed, yet more reasons to not use it :) > Generally "circular imports" are a bit dodgy and sometimes a sign of bad > design, at least, I often have the feeling that there's a cleaner design > lurking just outside my range of thought somewhere. > Bad design eh? Hmmm sure sounds like it. But, if I have several modules all doing some particular thing, but all needing this one (or two or three) class, wouldn't it make sense to put it in the main module? Hmmm perhaps not. Perhaps this universal class and others like it should be in a module all by themselves. Either way, looks like your last advice is the route I will take. > "Learning Python" has a nice explanation of this phenomenon under "Module > Gotchas", and their advice is basically: "Don't do that...really!" :-). > Redesigning helps. > Haven't done Learning Python, but it can't hurt this early in development to at least consider a redesign. Thanks for the advice! Glen. > -- > Remco Gerlich > From hermit@erie.net Wed Jul 4 13:38:55 2001 From: hermit@erie.net (Hermit) Date: Wed, 4 Jul 2001 08:38:55 -0400 (EDT) Subject: [Tutor] decisions, decisions Message-ID: I am an advocate for buying and using manuals for learning new things. I am a complete newbie to Python, but I have been lurking on this mailing list for a couple of months now, and I am excited about learning how to program with Python. I have been to local bookstores more than I can count and have settled on one of two books for Python beginners. One by O'Reilly, of course, the other by the grandmaster, Mr. Alan Gauld (head bowed in reverence). I would like to buy both, but at this time I have to settle for one. Could someone more knowledgeable advise me on my purchase? Regards, Dick Williams -- Linux - Not just an OS, but a lifestyle. Powered by RedHat Mentored by Razvan From rwilkins@bigpond.net.au Wed Jul 4 13:48:24 2001 From: rwilkins@bigpond.net.au (Richard Wilkins) Date: Wed, 4 Jul 2001 20:48:24 +0800 Subject: [Tutor] sockets In-Reply-To: <01070412561100.07515@yatsu> Message-ID: Howdy Brendon, *schnip* > basically, what needs to be done is have a socket that keepson > receiving data > while the rest of the program does it's thing. i.e. parse that data and > handle UI events. I _think_ what you want are non-blocking sockets. ie. the sockets do not wait for the next lot of data to come through, they will merely raise an exception. Take a look at Gordon McMillan's socket HOWTO - http://www.mcmillan-inc.com/sock1.html, if this sounds like what you're looking for. As for how IM programs work, I wouldn't have a clue ^_^ Hope this helps, Andrew Wilkins From scarblac@pino.selwerd.nl Wed Jul 4 13:42:49 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 4 Jul 2001 14:42:49 +0200 Subject: [Tutor] decisions, decisions In-Reply-To: ; from hermit@erie.net on Wed, Jul 04, 2001 at 08:38:55AM -0400 References: Message-ID: <20010704144249.A7047@pino.selwerd.nl> On 0, Hermit wrote: > I am an advocate for buying and using manuals for learning new things. I > am a complete newbie to Python, but I have been lurking on this mailing > list for a couple of months now, and I am excited about learning how to > program with Python. > > I have been to local bookstores more than I can count and have settled on > one of two books for Python beginners. One by O'Reilly, of course, the > other by the grandmaster, Mr. Alan Gauld (head bowed in reverence). I > would like to buy both, but at this time I have to settle for one. > > Could someone more knowledgeable advise me on my purchase? Do you have any experience with programming? Alan's book teaches programming in general, with Python examples. You can check the website (on which the book is based) to see whether you like it, http://www.crosswinds.net/~agauld/ There are several other good books; O'Reilly's "Learning Python" is nice, but seems to assume some experience with programming. So first tell us, what do you know already, also what do you want to do with Python? :) -- Remco Gerlich From pdeluca@sia.net.au Thu Jul 5 05:59:44 2001 From: pdeluca@sia.net.au (Paul De Luca) Date: Thu, 5 Jul 2001 00:59:44 -0400 (EDT) Subject: [Tutor] decisions, decisions In-Reply-To: Message-ID: Dick, I too am a newbie, and have bought both the books you mentioned. Being new to programming (besides a little basic/pascal/VBA/logo over the years) I found Alans book just what I needed. If you are new to programming this is a *must*. It teaches you how to program using python as opposed to learning the python language itslef. Needless to say, with Alans book, this mailing list, the python docs, useless python, I am doing ok. Learning Python -read the first couple of chapters, personally I found it a bit of a dissapointment for an Oreilly book. It made constant comparisons to C, despite stating in the foreword (maybe back cover) that it could be a first programming book. Keep in mind that I didnt get past chapter 2... Hope this info is useful. On Wed, 4 Jul 2001, Hermit wrote: > I am an advocate for buying and using manuals for learning new things. I > am a complete newbie to Python, but I have been lurking on this mailing > list for a couple of months now, and I am excited about learning how to > program with Python. > > I have been to local bookstores more than I can count and have settled on > one of two books for Python beginners. One by O'Reilly, of course, the > other by the grandmaster, Mr. Alan Gauld (head bowed in reverence). I > would like to buy both, but at this time I have to settle for one. > > Could someone more knowledgeable advise me on my purchase? > > Regards, > > Dick Williams > > -- > Linux - Not just an OS, but a lifestyle. > > Powered by RedHat > Mentored by Razvan > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From carole@autosim.no Wed Jul 4 16:28:06 2001 From: carole@autosim.no (Carole Valentin) Date: Wed, 04 Jul 2001 17:28:06 +0200 Subject: [Tutor] Read a data file Message-ID: <3B433606.35969A94@autosim.no> Hi, I would like to read a data file like this one: x1 y1 x2 y2 x3 y3 ... (each line contains 2 float values) I want to read each value separately. How can I do this? Thanks in advance, Carole Valentin. From Lindsay@moonshine.co.uk Wed Jul 4 16:33:11 2001 From: Lindsay@moonshine.co.uk (Lindsay Davies) Date: Wed, 4 Jul 2001 16:33:11 +0100 Subject: [Tutor] decisions, decisions Message-ID: I can't comment on either of the two books you mention, but I would wholeheartedly recommend the 'Python Essential Reference', second edition, by David Beazley as a useful resource to complement any 'Learning Python'-type book. Best wishes, Lindsay On 4/7/01, Hermit wrote about '[Tutor] decisions, decisions': >I am an advocate for buying and using manuals for learning new things. I >am a complete newbie to Python, but I have been lurking on this mailing >list for a couple of months now, and I am excited about learning how to >program with Python. > >I have been to local bookstores more than I can count and have settled on >one of two books for Python beginners. One by O'Reilly, of course, the >other by the grandmaster, Mr. Alan Gauld (head bowed in reverence). I >would like to buy both, but at this time I have to settle for one. > >Could someone more knowledgeable advise me on my purchase? > >Regards, > >Dick Williams > >-- >Linux - Not just an OS, but a lifestyle. > >Powered by RedHat >Mentored by Razvan > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From karimy@nipltd.com Wed Jul 4 16:53:03 2001 From: karimy@nipltd.com (Karim Yaici) Date: Wed, 4 Jul 2001 16:53:03 +0100 Subject: [Tutor] Read a data file References: <3B433606.35969A94@autosim.no> Message-ID: <013101c104a1$6ead9540$a5020a0a@private.nipltd.com> Hi Carole, > I would like to read a data file like this one: > > x1 y1 > x2 y2 > x3 y3 > ... > > (each line contains 2 float values) > I want to read each value separately. > How can I do this? That's an easy one ;-) Here is a quick solution. Warning untested code ;-) import string def line2floats(theLine): # useful to convert a string to a tuple of floats f1,f2 = string.split(string,strip(theLine),' ') return float(f1),float(f2) file = open('data.txt','rb') lines= file.readlines() # this should return a list of string, one string per line. floats = map(lambda eachLine: line2floats(eachLine), lines) # line2floats is defined below.. print floats so if you had: 1.02 2.03 3.04 4.05 floats will be equal to [(1.02,2.03),(3.04,4.05)] I hope this will help you Cheers, Karim From dsh8290@rit.edu Wed Jul 4 17:22:04 2001 From: dsh8290@rit.edu (D-Man) Date: Wed, 4 Jul 2001 12:22:04 -0400 Subject: [Tutor] Infinite recursion or too big a problem? In-Reply-To: <3B42DE6D.5000303@lindbergs.org>; from van@lindbergs.org on Wed, Jul 04, 2001 at 03:14:21AM -0600 References: <3B42DE6D.5000303@lindbergs.org> Message-ID: <20010704122204.D26446@harmony.cs.rit.edu> On Wed, Jul 04, 2001 at 03:14:21AM -0600, VanL wrote: | I think I wrote this correctly, but do I have infinite recursion that I | haven't caught somewhere? I haven't checked the code yet, but with 6-8 thousand logs to traverse you could very well be hitting the stack limit even if your code is correct. Try it again with only a couple log files (samples you stick somewhere to play with) and see if it works then. If it does, you know the code is correct and you need Stackless to get a big enough stack. (Stackless puts the python stack on the C heap so you are only limited by the heap space on your system. CPython intertwines the python stack with the C stack so when you run out of C stack (C has a relatively small stack, compared to functional languages) you run out of Python stack and get the error you were seeing). HTH, -D From dsh8290@rit.edu Wed Jul 4 17:26:37 2001 From: dsh8290@rit.edu (D-Man) Date: Wed, 4 Jul 2001 12:26:37 -0400 Subject: [Tutor] decisions, decisions In-Reply-To: ; from hermit@erie.net on Wed, Jul 04, 2001 at 08:38:55AM -0400 References: Message-ID: <20010704122637.E26446@harmony.cs.rit.edu> On Wed, Jul 04, 2001 at 08:38:55AM -0400, Hermit wrote: | I am an advocate for buying and using manuals for learning new things. I | am a complete newbie to Python, but I have been lurking on this mailing | list for a couple of months now, and I am excited about learning how to | program with Python. | | I have been to local bookstores more than I can count and have settled on | one of two books for Python beginners. One by O'Reilly, of course, the | other by the grandmaster, Mr. Alan Gauld (head bowed in reverence). I | would like to buy both, but at this time I have to settle for one. | | Could someone more knowledgeable advise me on my purchase? Well, if you are trying to maximize your money, get the O'Reilly book because Alan's is free at http://www.crosswinds.net/~aguald. My personal preference is to search all over the web to find free references and tutorials and start there (and I recommend Alan's a lot to people :-)). I have bought some books before, and too often they become out-of-date or once I learn a little I never use them again. As a result I go for the free-on-the-web stuff first, then buy a book only if I think I will use the book a lot throughout my career. -D From britt_green@hotmail.com Wed Jul 4 17:32:03 2001 From: britt_green@hotmail.com (Britt Green) Date: Wed, 04 Jul 2001 09:32:03 -0700 Subject: [Tutor] Re; decisions, decisions Message-ID: Well, the book that I would go with is the one my Mr. Gauld, particularly if you're brand new to the languge. His book tends to teach you the 20% of the stuff you'll use 80% of the time, and not get bogged down in the rest. Once you've gotten through that, I'd really recommend picking up a copy of Core Python Programming by Wesley Chun. I use it almost exclusively now. Britt >I am an advocate for buying and using manuals for learning new things. I >am a complete newbie to Python, but I have been lurking on this mailing >list for a couple of months now, and I am excited about learning how to >program with Python. > >I have been to local bookstores more than I can count and have settled on >one of two books for Python beginners. One by O'Reilly, of course, the >other by the grandmaster, Mr. Alan Gauld (head bowed in reverence). I >would like to buy both, but at this time I have to settle for one. > >Could someone more knowledgeable advise me on my purchase? > >Regards, > >Dick Williams _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From britt_green@hotmail.com Wed Jul 4 17:42:34 2001 From: britt_green@hotmail.com (Britt Green) Date: Wed, 04 Jul 2001 09:42:34 -0700 Subject: [Tutor] SocketServer Documentation Anywhere? Message-ID: I was just wondering if there was any documentation on the SocketServer module. I didn't see any in the python.org documentation area. Maybe I was looking in the wrong place though. Britt -- It is pitch black. You are likely to be eaten by a grue. _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From Paul De Luca Thu Jul 5 07:48:50 2001 From: Paul De Luca (Paul De Luca) Date: Thu, 5 Jul 2001 02:48:50 -0400 (EDT) Subject: [Tutor] Windons Task tray In-Reply-To: <200001311713.MAA19985@smtp.rma.edu> Message-ID: Bob, This question has been asked on the list before a couple of moths ago, and got a few answers. Try searching through the archive for this mailing list at http://www.python.org. The whole archive can be downloaded too, though be warned, its 20MB. On Mon, 31 Jan 100 rhicks@rma.edu wrote: > Is it possible to minimize a python program to the task tray area of the > taskbar in Windows95/98? > > Bob > pop3.rma.edu > > > From ium@micromuse.com Wed Jul 4 18:42:43 2001 From: ium@micromuse.com (ibraheem umaru-mohammed) Date: Wed, 4 Jul 2001 18:42:43 +0100 Subject: [Tutor] Read a data file In-Reply-To: <013101c104a1$6ead9540$a5020a0a@private.nipltd.com>; from karimy@nipltd.com on Wed, Jul 04, 2001 at 04:53:03PM +0100 References: <3B433606.35969A94@autosim.no> <013101c104a1$6ead9540$a5020a0a@private.nipltd.com> Message-ID: <20010704184243.A9876@micromuse.com> [Karim Yaici wrote...] -| That's an easy one ;-) -| -| Here is a quick solution. Warning untested code ;-) -| -| import string -| -| def line2floats(theLine): -| # useful to convert a string to a tuple of floats -| f1,f2 = string.split(string,strip(theLine),' ') -| return float(f1),float(f2) -| -| file = open('data.txt','rb') -| lines= file.readlines() # this should return a list of string, one string -| per line. -| floats = map(lambda eachLine: line2floats(eachLine), lines) # line2floats is -| defined below.. -| -| print floats -| -| so if you had: -| 1.02 2.03 -| 3.04 4.05 -| -| floats will be equal to [(1.02,2.03),(3.04,4.05)] -| -| I hope this will help you -| -| Cheers, -| Karim Similar solution using list comprehensions: >>> import string >>> f=open('foo.txt') >>> floats=[ string.split(i.strip(),' ') for i in f.readlines() ] [['1.02','2.03'], ['3.04','4.05']] >>> Kindest regards, --ibs -- I know not how I came into this, shall I call it a dying life or a living death? -- St. Augustine From arcege@speakeasy.net Wed Jul 4 19:11:10 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 4 Jul 2001 14:11:10 -0400 (EDT) Subject: [Tutor] SocketServer Documentation Anywhere? In-Reply-To: from "Britt Green" at Jul 04, 2001 09:42:34 AM Message-ID: <200107041811.f64IBAj01056@dsl092-074-184.bos1.dsl.speakeasy.net> Britt Green wrote > > I was just wondering if there was any documentation on the SocketServer > module. I didn't see any in the python.org documentation area. Maybe I was > looking in the wrong place though. The doc is in Library Reference 11.14, SocketServer -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From dyoo@hkn.eecs.berkeley.edu Wed Jul 4 19:19:09 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 4 Jul 2001 11:19:09 -0700 (PDT) Subject: [Tutor] Windons Task tray In-Reply-To: Message-ID: On Thu, 5 Jul 2001, Paul De Luca wrote: > This question has been asked on the list before a couple of moths > ago, and got a few answers. Try searching through the archive for this > mailing list at http://www.python.org. The whole archive can be > downloaded too, though be warned, its 20MB. ActiveState, too, archives the tutor mailing list, and they also have a searching interface here: http://aspn.activestate.com/ASPN/Mail/Archives/python-Tutor/ The information below should help you minimize Python programs into the system tray. http://aspn.activestate.com/ASPN/Mail/Message/534394 Good luck! From gman_95@hotmail.com Wed Jul 4 23:37:10 2001 From: gman_95@hotmail.com (Daryl G) Date: Wed, 04 Jul 2001 22:37:10 -0000 Subject: [Tutor] A thread gui chat problem Message-ID: Hi, I seem to be having a problem with threading in my chat gui client program The thread run method only accepts two recieve mesages and thats it and I don't see why it does that. If I change the code in the run method to just add a number to itself it works fine. The chat server is a script I got from strout.net and sends messages it receives to all clients. What am I doing wrong? Thanks Daryl #code import threading, time from Tkinter import * import string import sys from socket import * #Gui Class class App: def __init__(self, master): #initialize socket variables for theclient self.HOST='localhost' self.BUFSIZ = 1024 self.PORT=4000 self.ADDR= (self.HOST, self.PORT) self.tcpCliSock= socket(AF_INET, SOCK_STREAM) self.tcpCliSock.connect(self.ADDR) #initalize Gui self.senddata=StringVar() self.recdata=StringVar() self.frame = Frame(master) self.frame.pack() self.send=Button(self.frame, text='Send', command=self.sendData) self.send.pack(side=LEFT) self.sendtext=Entry(self.frame, width=50, textvariable=self.senddata) self.sendtext.pack(side=LEFT) self.rectext=Entry(self.frame, width=50, textvariable=self.recdata) self.rectext.pack(side=RIGHT) #display text in gui self.senddata.set('send chat area') self.recdata.set('receive area') def sendData(self): str= self.senddata.get() self.tcpCliSock.send(str) #display received message in text entry rectext widget def recData(self, data): self.data=data self.recdata.set(data) #threading class module for receiving threads and calling recData method in App class msgThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): #add=1 while 1: #I get the same thing both with and without a while loop #print add data=app.tcpCliSock.recv(1024) app.recdata.set(data) #print data #add=add+1 #time.sleep(1) #print 'sleep' root = Tk() classtitle="chater" root.title(classtitle) app = App(root) #Screen resolution must be set to 1024X768 or Gui will be off the screen if #the resolution is smaller root.geometry('%dx%d+%d+%d' % (660,20,210,690)) thread= msgThread() thread.start() root.mainloop() app.tcpCliSock.close() #end _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From gman_95@hotmail.com Thu Jul 5 01:55:43 2001 From: gman_95@hotmail.com (Daryl G) Date: Thu, 05 Jul 2001 00:55:43 -0000 Subject: [Tutor] re:A thread gui chat problem Message-ID: I FIGURED IT OUT!!!!!!!! I'm a moron and a genius all in one?!?..... I hate it when I post a question, then figure it out. I suddenly (5 minutes ago) decided to see what would happen f I put the data socket receive line inside a try statement in the thread run method And it WORKED!! Yippie!!!! I just don't know why that worked. Could anyone explain if possible please? Any additional suggestions are helpful too. Thanks! Also, to get a window to pop back up on top of other windows, would I use deiconify? New code in run method class msgThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while 1: #put socket receive statement in try loop. Works now!! try: data=app.tcpCliSock.recv(1024) except: pass app.recdata.set(data) _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From sheila@thinkspot.net Thu Jul 5 01:55:25 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 04 Jul 2001 17:55:25 -0700 Subject: [Tutor] Config options on Tkinter Label Widget Message-ID: I'm trying my hand at a bit of Tkinter programming. I must say, the discussion in Mark Lutz' Programming Python, 2nd ed, is really excellent. Anyhow, I liked the suggestion in Chun's Core Python Programming for one of the exercises: "Label and Entry Widgets and Python I/O: Create a GUI application that provides and Entry field where the suer can provide the name of a text file. Open the file and read it, displaying its contents in a Label." So, I'm just starting out on the exercise, and I decided to mess around a bit with the look and feel of the application. (I've also snagged a local copy of Lundh's Tkinter reference and the Tkinter Life Preserver...so I think I have ample reference material.) So, here is my code so far: -------------------------------------------------------------- from Tkinter import * root = Tk() Directions = Label(root, text ='Enter name of File to Open:') Directions.config(anchor=W) inputBox = Entry(root, width=80) Directions.pack() inputBox.pack() mainloop() -------------------------------------------------------------- Now, notice the line where I am trying to configure on Directions the positioning of the text in the label: Directions.config(anchor=W) >From reading Lundh's reference, I thought that this would position the text all the way to the left of the label. However, it remains centered. Why isn't it moving to the left? What do I need to do to get that effect? Thanks, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From rick@niof.net Thu Jul 5 02:57:19 2001 From: rick@niof.net (Rick Pasotto) Date: Wed, 4 Jul 2001 21:57:19 -0400 Subject: [Tutor] Config options on Tkinter Label Widget In-Reply-To: Message-ID: <20010704215719.D406@tc.niof.net> On Wed, Jul 04, 2001 at 05:55:25PM -0700, Sheila King wrote: > I'm trying my hand at a bit of Tkinter programming. I must say, the > discussion in Mark Lutz' Programming Python, 2nd ed, is really > excellent. > > Anyhow, I liked the suggestion in Chun's Core Python Programming for one > of the exercises: "Label and Entry Widgets and Python I/O: Create a GUI > application that provides and Entry field where the suer can provide the > name of a text file. Open the file and read it, displaying its contents > in a Label." > > So, I'm just starting out on the exercise, and I decided to mess around > a bit with the look and feel of the application. (I've also snagged a > local copy of Lundh's Tkinter reference and the Tkinter Life > Preserver...so I think I have ample reference material.) > > So, here is my code so far: > -------------------------------------------------------------- > > from Tkinter import * > > root = Tk() > Directions = Label(root, text ='Enter name of File to Open:') > Directions.config(anchor=W) > inputBox = Entry(root, width=80) > > Directions.pack() > inputBox.pack() > mainloop() > -------------------------------------------------------------- > > Now, notice the line where I am trying to configure on Directions the > positioning of the text in the label: > Directions.config(anchor=W) > > >From reading Lundh's reference, I thought that this would position the > text all the way to the left of the label. > > However, it remains centered. > > Why isn't it moving to the left? What do I need to do to get that > effect? Actually it *is* positioned to the left of the label. The problem is that the label is only as wide as the text. You need to add two things to the pack command: 'expand=1' to say you want the label to fill the available space, and 'fill=X' to say you want the label to expand horizontally. Directions.pack(expand=1,fill=X) To get a better idea of what is happening first color the label: Directions.config(anchor=W,bg='yellow') and then try adding a width: Directions.config(anchor=W,bg='yellow',width=70) (Be sure you do the above with the original Directions.pack().) -- The ideological war now being waged against property is neither the most bitter nor the most dangerous that it has had to contend with. Since the beginning of the world there has also been a real war of violence and conspiracy waged against it that gives no sign of abating. War, slavery, imposture, inequitable taxation, monopoly, privilege, unethical practice, colonialism, the right to employment, the right to credit, the right to education, the right too public aid, progressive taxation in direct or inverse ratio to the ability to pay -- all are so many battering rams pounding against the tottering column. Could anyone assure me whether there are many men in France, even among those who consider themselves conservatives, who do not, in one form or another, lend a hand to this work of destruction. -- Frйdйric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From sheila@thinkspot.net Thu Jul 5 03:08:57 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 04 Jul 2001 19:08:57 -0700 Subject: [Tutor] Config options on Tkinter Label Widget In-Reply-To: <20010704215719.D406@tc.niof.net> References: <20010704215719.D406@tc.niof.net> Message-ID: Very cool. Thanks, much. It is all clear to me now! ;) Off I go, a tkintering... -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Wed, 4 Jul 2001 21:57:19 -0400, Rick Pasotto wrote about Re: [Tutor] Config options on Tkinter Label Widget: : :Actually it *is* positioned to the left of the label. The problem is :that the label is only as wide as the text. You need to add two things :to the pack command: 'expand=1' to say you want the label to fill the :available space, and 'fill=X' to say you want the label to expand :horizontally. : :Directions.pack(expand=1,fill=X) : :To get a better idea of what is happening first color the label: : :Directions.config(anchor=W,bg='yellow') From rufmetal@home.com Thu Jul 5 05:15:51 2001 From: rufmetal@home.com (Chris Keelan) Date: Wed, 4 Jul 2001 23:15:51 -0500 Subject: [Tutor] OT: HTDP zip available Message-ID: <01070423155100.02192@tygesen> I've had a few requests for HTDP in a .zip format so I've stuck it here: http://members.home.com/rufmetal/files/htdp.zip . I had to boot into Windoze to get this done so y'all owe me big. When you speak of me, speak well! - Chris From dtropp@psych.unimelb.edu.au Thu Jul 5 05:17:23 2001 From: dtropp@psych.unimelb.edu.au ([Secure] Dan Tropp) Date: Thu, 5 Jul 2001 14:17:23 +1000 Subject: [Tutor] How to produce compiled python using ActiveState? Message-ID: <001601c10509$652850b0$0601c10a@oz.intelligenesis.net> *This message was transferred with a trial version of CommuniGate(tm) Pro* I've been using the ActiveState ide on winnt. Sometimes when I run a script I get a compiled version (.pyc) being created and other times not. Is there an easy way to generate compiled files from source using the ide? Why does the file browser (for opening files, etc) only allow single selection!! dan Dan Tropp Dept Psychology, University of Melbourne, Australia From rnd@onego.ru Thu Jul 5 05:52:44 2001 From: rnd@onego.ru (Roman Suzi) Date: Thu, 5 Jul 2001 08:52:44 +0400 (MSD) Subject: [Tutor] re:A thread gui chat problem In-Reply-To: Message-ID: On Thu, 5 Jul 2001, Daryl G wrote: >I FIGURED IT OUT!!!!!!!! >I'm a moron and a genius all in one?!?..... I hate it when I post a >question, then figure it out. It's very comman to solve something right after the formulation. >I suddenly (5 minutes ago) decided to see what would happen f I put the data >socket receive line inside a try statement in the thread run method >And it WORKED!! > >Yippie!!!! >I just don't know why that worked. Could anyone explain if possible please? >Any additional suggestions are helpful too. Thanks! >Also, to get a window to pop back up on top of other windows, would I use >deiconify? > >New code in run method > >class msgThread(threading.Thread): > def __init__(self): > > > > threading.Thread.__init__(self) > > def run(self): > > while 1: > #put socket receive statement in try loop. Works now!! > try: > data=app.tcpCliSock.recv(1024) > except: > pass Have you tried to output some debug info from here like sys.exc_info() (and print it with one of the module traceback functions to some log-file?) (I still feel like maybe your program is not correct, but am not sure why, because have not dealt enough with threads.) > app.recdata.set(data) Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ _/ Thursday, July 05, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ ">From the Department of Redundancy Dept." _/ From kojo@hal-pc.org Thu Jul 5 06:16:02 2001 From: kojo@hal-pc.org (Kojo Idrissa) Date: Thu, 05 Jul 2001 00:16:02 -0500 Subject: [Tutor] OT: HTDP zip available In-Reply-To: <01070423155100.02192@tygesen> Message-ID: <5.1.0.14.0.20010705001408.00ad9278@Pop3.norton.antivirus> Big Thanks to Chris for his help here. Good News!! is functioning properly once again!! That said, it is helpful to have the zip, so I can read offline. Thanks again Chris!! At 11:15 PM 7/4/2001 -0500, you wrote: >I've had a few requests for HTDP in a .zip format so I've stuck it here: >http://members.home.com/rufmetal/files/htdp.zip . I had to boot into Windoze >to get this done so y'all owe me big. > >When you speak of me, speak well! > >- Chris > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** From kiranke@rediffmail.com Thu Jul 5 09:02:41 2001 From: kiranke@rediffmail.com (Kiran K. Enuganti) Date: 5 Jul 2001 08:02:41 -0000 Subject: [Tutor] python 2.1 Message-ID: <20010705080241.30108.qmail@mailweb22.rediffmail.com> hi, I am new to python and been using python 1.5.2 which includes tcl/tk. i uninstalled both python 1.5.2 and tcl and installed the latest version of python 2.1(to install vpython, which requires 2.1) but the latest python2.1 does not include tck/tk ? do i have to download tcl/tk separately and install it in the same folder? please help. ____________________________________________________ Buy Feng Shui Package for Rs. 151/- only, at http://shopping.rediff.com/shopping/fengshui_mailer.htm From ppathiyi@cisco.com Thu Jul 5 10:41:24 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Thu, 5 Jul 2001 15:11:24 +0530 Subject: [Tutor] python 2.1 References: <20010705080241.30108.qmail@mailweb22.rediffmail.com> Message-ID: <023501c10536$a7f10d10$37ef87c0@ppathiyipc> Hi, I am not sure about this, but i remember seeing somewhere that Tcl/Tk won't come with the Python2.1 distribution. You can download the same from http://dev.scriptics.com/ For installing, make the necessary changes (give the header file and library paths) in the Modules/Setup file. Since we can give the path in this file, it need not be in the same folder as the python files. Regards, Praveen. ----- Original Message ----- From: "Kiran K. Enuganti" To: Sent: Thursday, July 05, 2001 1:32 PM Subject: [Tutor] python 2.1 > hi, > I am new to python and been using python 1.5.2 which includes tcl/tk. i uninstalled both python 1.5.2 and tcl and installed the latest version of python 2.1(to install vpython, which requires 2.1) but the latest python2.1 does not include tck/tk ? > do i have to download tcl/tk separately and install it in the same folder? > please help. > > > ____________________________________________________ > Buy Feng Shui Package for Rs. 151/- only, at http://shopping.rediff.com/shopping/fengshui_mailer.htm > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld@bt.com Thu Jul 5 12:22:08 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 5 Jul 2001 12:22:08 +0100 Subject: [Tutor] when to use "self." Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D89D@mbtlipnt02.btlabs.bt.co.uk> > At 5:18 PM +0200 7/2/01, Brendon wrote: > >methods (hum, why not just call them functions?.. grr) History. A *method* is the *function* executed by an objects *selector* in response to a *message*. In most modern OOP languages including Python the algorithm for selecting functions in response to messages(the selector) is fixed and usually has a 1:1 operation so that a method is a function (actually a bound function). In early OOP languages (and its still the case in Lisp/CLOS) the programmer can change the selector algorithm and its perfectly possible for the function that gets executed in response to a message to change with time and/or state. Similarly its possible to bind the same *function* to several *messages*. Thus multiple *methods* map to a single *function*. In this scenario it is important to distinguish between the method (the function currently associated with a given message) and the functions which implement those methods. In less flexible envronments - C++, Java, Python etc - the distinction is not so relevant. Alan G (Who is officially on vacation but realised he'd forgotten to turn off the tutor list and wanted to clear his mailbox! Sorry if you've all been getting out of office messages, oops!) From arcege@speakeasy.net Thu Jul 5 12:31:34 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Thu, 5 Jul 2001 07:31:34 -0400 (EDT) Subject: [Tutor] Config options on Tkinter Label Widget In-Reply-To: <20010704215719.D406@tc.niof.net> from "Rick Pasotto" at Jul 04, 2001 09:57:19 PM Message-ID: <200107051131.f65BVZp01968@dsl092-074-184.bos1.dsl.speakeasy.net> Rick Pasotto wrote > Actually it *is* positioned to the left of the label. The problem is > that the label is only as wide as the text. You need to add two things > to the pack command: 'expand=1' to say you want the label to fill the > available space, and 'fill=X' to say you want the label to expand > horizontally. FYI: `expand' does not "turn on and off" the `fill' option (you seem to imply this). They are not fully independant, but each works well without the other. Fill adjusts the widget's appearance and expand allows for better resizing the widget. Try the following: >>> from Tkinter import * >>> r1 = Tk() >>> r1.title('expand=YES') >>> l1 = Label(r1, text='hi', bg='green') >>> l1.pack(expand=YES) >>> >>> r2 = Tk() >>> r2.title('fill=BOTH') >>> l2 = Label(r2, text='hi', bg='green') >>> l2.pack(fill=BOTH) >>> >>> r3 = Tk() >>> r3.title('fill=BOTH, expand=YES') >>> l3 = Label(r3, text='hi', bg='green') >>> l3.pack(fill=BOTH, expand=YES') >>> >>> r4 = Tk() >>> r4.title('fill=BOTH, side=LEFT') >>> l4 = Label(r4, text='hi', bg='green') >>> l4.pack(fill=BOTH, side=LEFT) >>> >>> mainloop() Now manually resize them all and see how the widget changes. (Without manually resizing them, it is hard to see how the geometry manager is important.) The 'expand=YES' widget stays centered in the window, but does not full the window. The 'fill=BOTH' widget fills the window, but does not expand (vertically) because of the packing geometry (available, unallocated space is below) and 'fill=BOTH, side=LEFT' widget does not expand horizontally (available space is to the right). And the 'fill=BOTH, expand=YES' widget is centered, and uses all the space. So, the expand option tells the geometry manager to use as much space as possible, allowing for resizing. The fill option tells the manager to size the widget to the _given_ space in the directions given. Hope this helps. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From bren@europe.nl.com Thu Jul 5 13:00:40 2001 From: bren@europe.nl.com (Brendon) Date: Thu, 5 Jul 2001 14:00:40 +0200 Subject: [Tutor] threads Message-ID: <200107051200.f65C0AW94093@garm.bart.nl> there seems to remarkably little documentation on this subject, so i'll ask here. how do you thread a program? i.e., to keep it very basic a program. def thread_one(): r1 = 4+5 #pass r1 to thread two def thread_two(): r2 = 3+4 r3 = r1 + r2 #call both threads simultaneously granted, this is completely useless, but i just need to get the idea :) -- "if we live by an "eye for an eye and a tooth for a tooth"...before long, the whole world will be blind and toothless." --Tevye, Fiddler on the Roof From r.b.rigilink@chello.nl Thu Jul 5 14:08:32 2001 From: r.b.rigilink@chello.nl (Roeland Rengelink) Date: Thu, 05 Jul 2001 15:08:32 +0200 Subject: [Tutor] threads References: <200107051200.f65C0AW94093@garm.bart.nl> Message-ID: <3B4466D0.CECEB6C7@chello.nl> Hi Brendon, I'd been working on a short introduction to threads, but I never finished it. Let me use this post to at least release this much to the public, it will probably never be finished, and half an answer may be better than none. Brendon wrote: > > there seems to remarkably little documentation on this subject, so i'll ask > here. how do you thread a program? i.e., to keep it very basic a program. > > def thread_one(): > r1 = 4+5 > #pass r1 to thread two > > def thread_two(): > r2 = 3+4 > r3 = r1 + r2 > > #call both threads simultaneously > Threads are pieces of a program that run asynchronously. There are several reasons you might want to use threads in your program, sometimes you have to deal with asynchronous events, sometimes you just wish to simulate them. Simulating asynchonous execution doesn't need threads, just do something like this: while 1: if random.randrange(2) == 0: do_something(data) else: do_another_thing(data) This is almost equivalent to: from threading import Thread class T1(Thread): def __init__(self): Thread.__init__(self) def run(self): while 1: do_something(data) class T2(Thread): def __init__(self): Thread.__init__(self) def run(self): while 1: do_another_thing(data) t1 = T1() t2 = T2() t1.start() t2.start() t1.join() t2.join() Notice two things: 1 - The example without threads is much shorter 2 - I said 'almost equivalent' They are not really equivalent because in the non-threaded example do_something(data) and do_another_thing(data) are never executed at the same time. While in the threaded example they appear to be. Depending on the circumstances this makes the threaded solution a better one, or an absolute nightmare. I say appear because in reality at each moment only one of the functions is being executed. Executing a function means executing a series of (bytecode) operations. The OS and Python together may decide to switch from one to the other series between each operation. This is OK if you don't mind them switching at random, unfortunately, usually, you do. Problems start when you want to share resources between threads (in this case 'data' is a shared resource), and/or when you want to communicate between threads, i.e. when do_something and do_another_thing are going to depend on the state of T2 and T1 respectively Sharing resources is a problem because you want to make sure that T1's operation on the resource doesn't interfere with T2's operation on the resource. This is what people refer to when they ask worried questions about the thread-safety of an operation. You can solve this problem with locks. A lock is the moral equivalent of: class Lock: def __init__(self): self.__locked = 0 def acquire(self): while self.__locked: pass # wait till self.__locked = 0 self.__locked = 1 # then lock def release(self): self.__locked = 0 You would use this in your do_* functions like this: l = Lock() def do_something(data): l.acquire() operate(data) # do some stuff that shouldn't be interfered with l.release() def do_another_thing(data): l.acquire() l.release() do_something can now only execute operate(data) if it has first acquired the lock. This lock will remain into effect untill that operation is finished. Only when do_something has released the lock, do_another_thing can acquire it to do stuff that might otherwise have interfered with operate(data) Sometimes we want one thread to notify the other thread that an event has occured. (for example when a variable has been set). The simplest mechanism for that is the Event object. An event object is something like: class Event: __init__(self): self.__flag = 0 def set(self): self.__flag = 1 def isSet(self): return self.__flag def clear(self): self.__flag = 0 def wait(self, timeout=None): if timeout is None: # wait indefinetely while not self.__flag: time.sleep(0.01) return else: # wait at most timeout seconds start = time.time() while not self.__flag and (time.time()-start) do_it.set() # We're notifying T2 class T2(Thread): def run(self): do_it.wait() # We're waiting for notification from T1 do_it.clear() The threading library module provides Lock and Event objects, as well as some other usefull stuff. I hope this this intro will have made the library documentation somwehat more usefull. Roeland PS On re-reading I'm left with a nagging doubt that I may use the term asynchronous incorrectly. I mean it here in the sense that a thread normally doesn't influence the moment at which an operation in another thread is executed. Can somebody confirm this is correct usage. -- r.b.rigilink@chello.nl "Half of what I say is nonsense. Unfortunately I don't know which half" From qhe@ydyn.com Thu Jul 5 14:08:56 2001 From: qhe@ydyn.com (Peter He) Date: Thu, 05 Jul 2001 08:08:56 -0500 Subject: [Tutor] How to start an application with maximized window? In-Reply-To: Message-ID: <5.1.0.14.0.20010705080511.00a6e3c8@mail.ydyn.com.criticalpath.net> Hi all, As title. I want my application start with the main window maximized. Where can I config this? Thank you! Peter From ppathiyi@cisco.com Thu Jul 5 14:20:42 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Thu, 5 Jul 2001 18:50:42 +0530 Subject: [Tutor] threads References: <200107051200.f65C0AW94093@garm.bart.nl> Message-ID: <02cc01c10555$4b0803a0$37ef87c0@ppathiyipc> Hi Brendon, I guess your question can't be more betterly and simply answered than what Roeland has done. I would just add a link and nothing more :-)) http://www.serpentine.com/~bos/threads-faq/ Gives some basic idea about the terminologies involved. Regards, Praveen. ----- Original Message ----- From: "Brendon" To: Sent: Thursday, July 05, 2001 5:30 PM Subject: [Tutor] threads > there seems to remarkably little documentation on this subject, so i'll ask > here. how do you thread a program? i.e., to keep it very basic a program. > > def thread_one(): > r1 = 4+5 > #pass r1 to thread two > > def thread_two(): > r2 = 3+4 > r3 = r1 + r2 > > #call both threads simultaneously > > granted, this is completely useless, but i just need to get the idea :) > -- > > "if we live by an "eye for an eye and a tooth for a tooth"...before long, > the whole world will be blind and toothless." > --Tevye, Fiddler on the Roof > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rick@niof.net Thu Jul 5 15:55:12 2001 From: rick@niof.net (Rick Pasotto) Date: Thu, 5 Jul 2001 10:55:12 -0400 Subject: [Tutor] Config options on Tkinter Label Widget In-Reply-To: <200107051131.f65BVZp01968@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: <20010705105512.E406@tc.niof.net> On Thu, Jul 05, 2001 at 07:31:34AM -0400, Michael P. Reilly wrote: > Rick Pasotto wrote > > Actually it *is* positioned to the left of the label. The problem is > > that the label is only as wide as the text. You need to add two things > > to the pack command: 'expand=1' to say you want the label to fill the > > available space, and 'fill=X' to say you want the label to expand > > horizontally. > > FYI: `expand' does not "turn on and off" the `fill' option (you seem to > imply this). They are not fully independant, but each works well without > the other. Fill adjusts the widget's appearance and expand allows for > better resizing the widget. First let me say that I frequently have the bad habit of just fiddling until something works instead of really understanding it, so writing it out here will be good for me. (And please correct any errors.) Second, while there is no book specifically on Python/Tk there *is* one on Perl/Tk and I've found it very useful in understanding the Tk part. (I don't have the book, but my understanding is that Greyson's book is about programming Python and it also covers Tkinter. The Perk/Tk book assumes you already know Perl.) So.... The packer puts each widget into an invisible allocation rectangle. By default this allocation rectangle is the same size as the widget. Setting 'expand=TRUE' tells the packer to fill all available space (which can be changed by manually resizing the window) with the allocation rectangle. This does not affect the widget at all. By default the widget is centered within the allocation rectangle. This can be changed by setting 'anchor=??' where the ?? is a compass direction, ie, N,S,E,W,NE,NW,SE,SW. The size of the widget is determined by its contents (or by its 'width' and/or 'height' parameters). Setting 'fill=?' (where ? is X, Y, or BOTH) tells the widget to be the size of the allocation rectangle in the appropriate direction(s). By default, the text in a label widget is centered. This can be changed by setting 'justify=?' where ? is 'left', 'center', or 'right'. Thus you can have right justified text in a left anchored widget. This all is further complicated by the 'padx=' and 'pady=' parameters. When given to the pack() command they make the allocation rectangle that much bigger than the widget. When given to the widget they make the widget that much bigger than its contents. One tricky aspect is that allocation rectangles are allocated in the order they are encountered. lab1.pack(side=TOP) lab2.pack(side=BOTTOM) lab3.pack(side=LEFT) lab4.pack(side=RIGHT) gives: +------------------+ | lab1 | +------+----+------+ | lab3 | | lab4 | +------+----+------+ | lab2 | +------------------+ which is different than lab3.pack(side=LEFT) lab4.pack(side=RIGHT) lab1.pack(side=TOP) lab2.pack(side=BOTTOM) which gives: +------+------+------+ | | lab1 | | | +------+ | | lab3 | | lab4 | | +------+ | | | lab2 | | +------+------+------+ I've probably still got some detail mis-worded but I think what I've written should help you (and me) understand what's happening. -- Each of us certainly gets from Nature, from God, the right to defend his person, his liberty, and his property, since they are the three elements constituting or sustaining life, elements which are mutually complementary and which cannot be understood without one another. For what are our faculties, if not an extension of our personality, and what is property, if not an extension of our faculties? -- Frйdйric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From aschmidt@nv.cc.va.us Thu Jul 5 16:28:02 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Thu, 5 Jul 2001 11:28:02 -0400 Subject: [Tutor] HTML Generating Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090688C114@novamail1.nv.cc.va.us> ...Or just use Zope! <8^) Allen -----Original Message----- From: Mark Tobin [mailto:mtobin@attcanada.net] Sent: Tuesday, July 03, 2001 7:02 PM To: Sheila King Cc: 'tutor@python.org' Subject: Re: [Tutor] HTML Generating OK, now I feel just a little bit silly... thanks a lot for the conk on the head... ;-) Mark On 3 Jul 2001, at 14:15, Sheila King wrote: > In order to have it "execute in a browser", you would need to have a web > server, and have your script in the cgi-bin of the website and call the > script by putting a URL that points to the script into the Location in > your web browser. > > Are you trying to learn CGI programming? (This is how you get programs > to run on a web page.) Or are you just trying to get your feet wet with > programming. CGI programming isn't hard, but it is something additional > to learning just the "programming" part. > > If you want to get it to run on your WIN95 machine, you would need to > install a web server on your home machine, get it running, and then have > a link to the script on your machine. > > This is probably not very clear, but I'm sure we can provide more > information if you are interested. Let us know. > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > > > On Tue, 3 Jul 2001 14:49:25 -0600, "Tobin, Mark" > wrote about [Tutor] HTML Generating: > > :OK... how come when I make a python script such as the one Sheila King > :posted (below) and execute it through my local IE5.5, it executes in a > :python window (DOS window) as opposed to in the browser? I'm using PY2.1 on > :a WIN95 machine with IE5.5. I don't really know how to express this any > :better (I'm just beginning to pick up some of this new language called > :"programerese"), but if this isn't clear I'll try again... > : > :Thanks in advance, > : > :Mark > : > :#!/usr/bin/env python > : > :import os > : > :print "Content-type: text/html\n\n" > : > :print "\n" > : > :print "" > :print "Obligatory Python Test Script" > :print "\n" > : > :print "\n" > :print "

Hello

" > :print "This is the obligatory
Python 'Hello\' testscript
" > :print "Ta-da

" > : > :print "NEW STUFF: testing environment variables
" > :print os.environ["REMOTE_ADDR"],"

" > :print "

And now, all the environment variables:
" > :print "", > :for el in os.environ.keys(): > : print el, " = ", os.environ[el], "
" > :print "
" > :print "THE END" > : > :print "\n" > : > :_______________________________________________ > :Tutor maillist - Tutor@python.org > :http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From arcege@speakeasy.net Thu Jul 5 16:36:12 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Thu, 5 Jul 2001 11:36:12 -0400 (EDT) Subject: [Tutor] Config options on Tkinter Label Widget In-Reply-To: <20010705105512.E406@tc.niof.net> from "Rick Pasotto" at Jul 05, 2001 10:55:12 AM Message-ID: <200107051536.f65FaDI02424@dsl092-074-184.bos1.dsl.speakeasy.net> Rick Pasotto wrote > First let me say that I frequently have the bad habit of just fiddling > until something works instead of really understanding it, so writing it > out here will be good for me. (And please correct any errors.) Wasn't trying to say that you weren't giving wrong info; sorry if I mistakenly implied that. Since the online docs don't go into great detail about about the difference between fill and expand for the packer, I figured that I would throw that in. > Second, while there is no book specifically on Python/Tk there *is* one > on Perl/Tk and I've found it very useful in understanding the Tk part. > (I don't have the book, but my understanding is that Greyson's book is > about programming Python and it also covers Tkinter. The Perk/Tk book > assumes you already know Perl.) Actually, Grayson's _Python and Tkinter Programming_ has only one chapter on Python, which is only nine pages - the rest of the book is on Tkinter (and PMW). As a Python book, it would be pitiful. ;) But yes, it really only covers Tkinter (in pretty good detail) and not Tk. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From bill-bell@bill-bell.hamilton.on.ca Thu Jul 5 17:02:55 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Thu, 5 Jul 2001 12:02:55 -0400 Subject: [Tutor] Re: threads In-Reply-To: Message-ID: <3B44576F.14786.3CBBBC@localhost> Brendon wrote, in part: > there seems to remarkably little documentation on this subject, so > i'll ask here. how do you thread a program? ... What little I know about Python threads I read on an Acrobat document called "threads.pdg" which was written by someone calling himself "Aahz" and that might still be available at http://starship.python.net/crew/aahz/. I applied the author's advice and my stuff works. :o) From allan.crooks@btinternet.com Thu Jul 5 17:43:03 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Thu, 05 Jul 2001 17:43:03 +0100 Subject: [Tutor] Infinite recursion or too big a problem? Message-ID: This question was a bit problematic to solve. But I like a challenge. :) Answer to your question, infinite recursion or too big a problem? Neither. :) It's not infinite recursion, because under most test cases it does quit. It's not too big a problem, because the stack-limit is about 1000 method calls by default, so unless you have a directory structure has really really really deep nested directories, it won't fail. So what's the problem with your program? Easy. Buggy code which if run under certain conditions will lead to infinite recursion. Let's have a glimpse at your code. > #!/usr/bin/env python > """ > Pylog, version 2. Written in functional style, just for fun. > """ > > # Imports > import os, string > > # Globals > > > # Force local evaluation of selected module functions > list_directory = os.listdir > is_directory = os.path.isdir > is_file = os.path.isfile > abs_path = os.path.abspath > string_find = string.find > > # Functions > ## my apply functions > do = lambda func: func() > doSequence = lambda functionlist: map(do, functionlist) > > ## identity functions > isDir = lambda fileobj: is_directory(fileobj) > isFile = lambda fileobj: is_file(fileobj) > isLogfile = lambda filename: (is_file(filename)) and (filename == 'log') > > ## list generating functions > concatenate = lambda seq1, seq2: seq1 + seq2 > getFileList = lambda dir: list_directory(dir) > getDirectories = lambda fileobjs: filter(isDir, fileobjs) > getLogfiles = lambda fileobjs: filter(isLogfile, fileobjs) > getAllLogfiles = lambda dirname: reduce(concatenate, [], > getLogfiles(getFileList(abs_path(dirname))) + > map(getAllLogfiles, map(abs_path, getDirectories(getFileList(dirname))))) So the first thing I did was to run the program. The stack trace however, unhelpfully kept on saying "lambda", so I didn't know where the loop was happening. So I then rewrote all the functions from "lambda" to "def". The loop seemed to indicate that the problem was just happening in "getAllLogfiles". So I then rewrote the algorithm and shortened it down to this: def getAllLogfiles (dirname): res = map(abs_path, getDirectories(getFileList(dirname))) print dirname, res return map(getAllLogfiles, map(abs_path, res)) This is the output I got. >>> getAllLogfiles(".") ['F:\\PROGRA~1\\Python\\DLLs', 'F:\\PROGRA~1\\Python\\Doc', 'F:\\PROGRA~1\\Pyt hon\\include', 'F:\\PROGRA~1\\Python\\Lib', 'F:\\PROGRA~1\\Python\\libs', 'F:\\P ROGRA~1\\Python\\tcl', 'F:\\PROGRA~1\\Python\\Tools'] F:\PROGRA~1\Python\DLLs [] F:\PROGRA~1\Python\Doc ['F:\\PROGRA~1\\Python\\doc', 'F:\\PROGRA~1\\Python\\lib' ] F:\PROGRA~1\Python\doc ['F:\\PROGRA~1\\Python\\doc', 'F:\\PROGRA~1\\Python\\lib' ] F:\PROGRA~1\Python\doc ['F:\\PROGRA~1\\Python\\doc', 'F:\\PROGRA~1\\Python\\lib' ] F:\PROGRA~1\Python\doc ['F:\\PROGRA~1\\Python\\doc', 'F:\\PROGRA~1\\Python\\lib' ] F:\PROGRA~1\Python\doc ['F:\\PROGRA~1\\Python\\doc', 'F:\\PROGRA~1\\Python\\lib' ] And then I ran it with getAllLogfiles("c:/"), but that didn't crash. And then I saw the problem. It's partly your code's fault (well, realistically, it's entirely your code's fault.. :), and the directory you're executing it in. Your code isn't working properly, because look at the sample execution. It processes the current directory, which is F:\PROGRA~1\Python. Then it goes into F:\PROGRA~1\Python\DLLs. Then it goes into the F:\PROGRA~1\Python\Doc directory (which has more directories in it than what is listed there, but that's a side effect of the bug I'm about to describe :) Then look at the third line execution (F:\PROGRA~1\Python\doc). It looks like it's doing the same as the second line, but it isn't. Note the difference in the capitalisation of "doc". Now, in my F:\PROGRA~1\Python\Doc directory, it has several sub-directories, including another one called "doc" (which expands to F:\PROGRA~1\Python\Doc\doc"). The problem is, you're not recreating the path fully. The absolute path function is documented to do this: Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to normpath(join(os.getcwd(), path)). Now, os.getcwd() returns the current directory. os.getcwd() is the same as "." "." is, at this moment in time, F:\PROGRA~1\Python So when it moves into the F:\PROGRA~1\Python\Doc directory, and listdir provides all these entries. about.html * acks.html * api dist doc ext icons index.html * inst lib mac modindex.html * ref tut Now, this line only lists two directories: F:\PROGRA~1\Python\doc ['F:\\PROGRA~1\\Python\\doc', 'F:\\PROGRA~1\\Python\\lib'] But all the directories (the ones with no * next to them) should be listed, but only these two are. That's because "isdir" will only return true if there is a file of that name, which is a directory. But you aren't testing to see if F:\PROGRA~1\Python\doc\api exists, you are actually checking to see if F:\PROGRA~1\Python\api exists (since you are using abspath, which joins "F:\PROGRA~1\Python\" with "api", which doesn't exist. It just so happens that F:\PROGRA~1\Python\doc and F:\PROGRA~1\Python\lib exist, as well as F:\PROGRA~1\Python\doc\doc and F:\PROGRA~1\Python\doc\lib. That's why those two entries are being returned, because "doc" and "lib" are elements of the F:\PROGRA~1\Python\doc directory (and they show up in listdir), and when you use abspath, they also exist as an element of the current directory. Hopefully that makes sense. I would try to explain it better, but let's just say I'm enough trouble with my wife as it is. ;) So what are you to do? Well, I'll leave that to you, but I suggest you look into os.path.join function, and pass the current directory you are in to a function, so that you can properly join the path to the element. HTH, Allan. From gman_95@hotmail.com Thu Jul 5 17:59:12 2001 From: gman_95@hotmail.com (Daryl G) Date: Thu, 05 Jul 2001 16:59:12 -0000 Subject: [Tutor] re:A thread problem Message-ID: Hey , thanks Roman! ... ... Hmmmm, looks like I can't. That stinks. Then whats the point of threading if I can't destroy it. I either need to figure out how to rewrite it so the thread will end when the main program ends or use some other means, like poll or select I guess -which I need to figure out. grrrr As the program is for windows I can't use fork. DAryl >From: Roman Suzi >To: Daryl G >Subject: Re: [Tutor] re:A thread problem >Date: Thu, 5 Jul 2001 20:14:24 +0400 (MSD) > >On Thu, 5 Jul 2001, Daryl G wrote: > > >HAven't done the traceback yet that area seems ok -but I'll check it. I >am, > >however, having a problem with the thread > >The seperate thread doesn't end when the program quits > >thread.exit() doesn't work and I thought the threading module used the >same > >low level thread modules. > >Now I recalled where I saw good answer for threading questions: > >Knowledge base at > >http://www.faqts.com >-> Python > >Sincerely yours, Roman Suzi >-- >_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ >_/ Thursday, July 05, 2001 _/ Powered by Linux RedHat 6.2 _/ >_/ ">From the Department of Redundancy Dept." _/ > _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From tutor@python.org Thu Jul 5 21:56:12 2001 From: tutor@python.org (Tim Peters) Date: Thu, 5 Jul 2001 16:56:12 -0400 Subject: [Tutor] python 2.1 In-Reply-To: <20010705080241.30108.qmail@mailweb22.rediffmail.com> Message-ID: [Kiran K. Enuganti] > I am new to python and been using python 1.5.2 which includes > tcl/tk. i uninstalled both python 1.5.2 and tcl and installed the > latest version of python 2.1(to install vpython, which requires > 2.1) but the latest python2.1 does not include tck/tk ? If you ran the PythonLabs 2.1 Windows installer, it installed Tcl/Tk, but under Python21/tcl/. Since IDLE is a Tk app, IDLE couldn't possibly work otherwise! From wesc@deirdre.org Thu Jul 5 21:52:12 2001 From: wesc@deirdre.org (Wesley Chun) Date: Thu, 5 Jul 2001 13:52:12 -0700 (PDT) Subject: [Tutor] threads In-Reply-To: <200107051200.f65C0AW94093@garm.bart.nl> Message-ID: On Thu, 5 Jul 2001, Brendon wrote: > there seems to remarkably little documentation on this subject, so i'll ask > here. how do you thread a program? i.e., to keep it very basic a program. some really good replies from others on this list, so i won't dwell on it. what i *did* want to say was that it was this lack of documentation that was the motivation for me to put an entire chapter on Threads in Core Py- thon Programming. We focus on one specific example and use it throughout to introduce the concept of threads and how threading works in Python. Aahz also happens to have been one of the reviewers of that chapter. if you are not interested in the book, you can still get this code at the book's website (see the URL below). basically, the example evolves like this: we start off with motivation on why one may want to use threads, then we look at Python's primitive thread support. then we progress to the 3 different ways to add threading to your application. finally, we conclude with one more example and a set of exercises. -wesley From DarkNemesis@nyc.rr.com Fri Jul 6 03:54:00 2001 From: DarkNemesis@nyc.rr.com (Leonid Ayzenshtat) Date: Thu, 5 Jul 2001 22:54:00 -0400 Subject: [Tutor] (no subject) Message-ID: <000001c105c6$e8f490d0$6401a8c0@viperlenny> This is a multi-part message in MIME format. ------=_NextPart_000_0001_01C105A5.61E47770 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit I would Like to join this mail list. ------=_NextPart_000_0001_01C105A5.61E47770 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable

I would Like to join this mail = list.

------=_NextPart_000_0001_01C105A5.61E47770-- From rob@jam.rr.com Fri Jul 6 03:58:31 2001 From: rob@jam.rr.com (Rob Andrews) Date: Thu, 5 Jul 2001 21:58:31 -0500 Subject: [Tutor] (no subject) In-Reply-To: <000001c105c6$e8f490d0$6401a8c0@viperlenny> Message-ID: It would seem that you have done so. Bienvenido, Rob Useless Python: Aw, heck, we love you! http://www.lowerstandard.com/python/ -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Leonid Ayzenshtat Sent: Thursday, July 05, 2001 9:54 PM To: tutor@python.org Subject: [Tutor] (no subject) I would Like to join this mail list. From kojo@hal-pc.org Fri Jul 6 04:43:51 2001 From: kojo@hal-pc.org (Kojo Idrissa) Date: Thu, 05 Jul 2001 22:43:51 -0500 Subject: [Tutor] (no subject) In-Reply-To: <000001c105c6$e8f490d0$6401a8c0@viperlenny> Message-ID: <5.1.0.14.0.20010705224128.00ad9950@Pop3.norton.antivirus> --=====================_115454925==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed In case you haven't gotten any mail from the list, or are having trouble, you can follow the link below and subscribe yourself to the list. I'm not sure if you're subscribed, as I didn't see the standard list footer in your email. At 10:54 PM 7/5/2001 -0400, you wrote: >I would Like to join this mail list. **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** --=====================_115454925==_.ALT Content-Type: text/html; charset="us-ascii" In case you haven't gotten any mail from the list, or are having trouble, you can follow the link below and subscribe yourself to the list.  I'm not sure if you're subscribed, as I didn't see the standard list footer in your email.


<http://mail.python.org/mailman/listinfo/tutor>

At 10:54 PM 7/5/2001 -0400, you wrote:

I would Like to join this mail list.

****************************
Kojo Idrissa
 
kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
****************************
--=====================_115454925==_.ALT-- From aschmidt@nv.cc.va.us Fri Jul 6 12:11:06 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Fri, 6 Jul 2001 07:11:06 -0400 Subject: [Tutor] Hopefully a quick Python/odbc/Zope question Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090688C117@novamail1.nv.cc.va.us> I have a Python program that reads a URL, rips it apart and dumps the pieces into an ODBC connected database. Works fine from the command line. If I try to add this into Zope as an External Method, it states it cannot find the dbi component. import dbi uses a dbi.dll in Windows. This was developed on 2.1 Python but the dbi module exists in Zopes 1.52 Python so I am not sure where the problem is. I know some Zopers read this list and I thought this too elementary for the Zope list. I will take it there unless someone has the quick one line answer I am sure this probably needs. Thanks Allen From bill-bell@bill-bell.hamilton.on.ca Fri Jul 6 17:10:37 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Fri, 6 Jul 2001 12:10:37 -0400 Subject: [Tutor] Re: threads In-Reply-To: Message-ID: <3B45AABD.8184.6B0386@localhost> > Brendon wrote, in part: > > there seems to remarkably little documentation on this subject, so > > i'll ask here. how do you thread a program? ... I haven't followed this thread carefully enough to know whether anyone has mentioned the availability of thread facilities in wxPython. Haven't tried 'em so cannot comment. From dyoo@hkn.eecs.berkeley.edu Fri Jul 6 18:07:04 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 6 Jul 2001 10:07:04 -0700 (PDT) Subject: [Tutor] Python/QT book online Message-ID: Hiya everyone, I just noticed that there's a book called "Graphical Programming with Python: QT Edition" available here: http://www.opendocspublishing.com/entry.lxp?lxpe=93 It doesn't appear complete yet, but it may help people who are learning Py/QT. Hope this helps! From bill-bell@bill-bell.hamilton.on.ca Fri Jul 6 19:10:13 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Fri, 6 Jul 2001 14:10:13 -0400 Subject: [Tutor] Re: threads In-Reply-To: Message-ID: <3B45C6C5.27198.49D16B@localhost> Wesley Chun wrote, in part: > ... an entire chapter on Threads in Core Python Programming. ... > you can still get this code at the book's website (see the URL > below) Wesley, unfortunately for some reason your URL did not come through on the version of this list that I read. Incidentally, this is very generous of you. - Bill From gman_95@hotmail.com Fri Jul 6 22:26:12 2001 From: gman_95@hotmail.com (Daryl G) Date: Fri, 06 Jul 2001 21:26:12 -0000 Subject: [Tutor] using lift() Message-ID: Hi, I'm trying to get my chatgui window to appear on top of other non-python windows when it receives a message, For example, user has some other applicatin displayed and is covering the python chatgui, I need it to appear on top of whatever application the user is using when a message is received. When I use self.rootobj.lift(), this doesn't happen. My mouse just turns into an hour glass when I move it over the chatgui. I can't even click on anything in it or type anything in there. I have to close the dos shell to exit it. #Threading class class msgThread(threading.Thread): def __init__(self, rb): self.rootobj=rb #app.recdata.set() threading.Thread.__init__(self) def run(self): #st=self.rootobj.state() while 1: try: data=app.tcpCliSock.recv(1024) except: pass self.rootobj.lift() #should bring chat gui to top app.recdata.set(data) #Main code root = Tk() classtitle="chater" root.title(classtitle) app = App(root) #Screen resolution must be set to 1024X768 or Gui will be off the screen if #the resolution is smaller root.geometry('%dx%d+%d+%d' % (660,20,210,690)) #pass root object to thread thread= msgThread(root) thread.start() root.mainloop() app.tcpCliSock.close() I have read all I could find on this, python.org and Tkinter and Python Programming. Is my logic wrong or is it not possible to do this? Thanks Daryl _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From pobrien@orbtech.com Fri Jul 6 22:43:40 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Fri, 6 Jul 2001 16:43:40 -0500 Subject: [Tutor] Need help with SWIG Message-ID: If there is anyone here that has experience with SWIG, I could use some help. I'm trying to build an interface to a commercial Windows application that provides an api in the form of a dll file. I have the C header file and tried to run it through SWIG to create the Python interface but SWIG fails with a whole bunch of "Syntax error in input" errors. I really don't know where to begin and I hate to spend any more time on this than necessary. All I want is the darn Python interface so I can start using the dll from Python. If anyone could help I would greatly appreciate it. I can send you the .h file as well. Thanks. --- Patrick K. O'Brien Orbtech "I am, therefore I think." From mattvogel@hotmail.com Sat Jul 7 01:48:36 2001 From: mattvogel@hotmail.com (Matthew Vogel) Date: Sat, 07 Jul 2001 00:48:36 Subject: [Tutor] C and python together Message-ID:

Hi
I have written a C library of functions and now i want to use python to call those functions directly from python. I have been informed that i will need some special header files and such in order for this to work. I was just wondering if anyone could give me some information on what header files i might need and how to actually call a C function from my library, in python.
Note: I DONT want to create a main C program that prints to standard out the results from each of the library functions when given certain command line args, through python.
I actually need to call the C functions from inside python.
 
Thanks a lot for any info
Matt


Get Your Private, Free E-mail from MSN Hotmail at http://www.hotmail.com.

From dyoo@hkn.eecs.berkeley.edu Sat Jul 7 02:02:03 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 6 Jul 2001 18:02:03 -0700 (PDT) Subject: [Tutor] C and python together In-Reply-To: Message-ID: On Sat, 7 Jul 2001, Matthew Vogel wrote: > I have written a C library of functions and now i want to use python to > call those functions directly from python. I have been informed that i > will need some special header files and such in order for this to work. > I was just wondering if anyone could give me some information on what > header files i might need and how to actually call a C function from my > library, in python. > Note: I DONT want to create a main C program that prints to standard out > the results from each of the library functions when given certain > command line args, through python. > I actually need to call the C functions from inside python. It sounds like you'll want the extension module capabilites in Python. Are you running on Windows or a Unix? In either case, you'll need to download the source to Python, because it comes with tools to help build extensions. Python's source code can be found here: http://python.org/ftp/python/2.1/ as Python-2.1.tgz. Making an extension module is an advanced topic, so it's not as fully documented as the rest of the Python system. You can take a look at: http://python.org/doc/current/ext/ext.html which gives a tutorial on the art of making extensions. The example on their tutorial shows how to run C's system() function from Python. The dry details about the Python/C API lies here: http://python.org/doc/current/api/api.html Core Python Programming, by Wesley Chun, also gives examples on writing Python extensions, so you may want to look into that book as well. By the way, you can ask questions about making extension modules here, but you might also want to ask on a forum like comp.lang.python just in case we can't answer your question well. Good luck to you! From rnd@onego.ru Sat Jul 7 08:13:35 2001 From: rnd@onego.ru (Roman Suzi) Date: Sat, 7 Jul 2001 11:13:35 +0400 (MSD) Subject: [Tutor] Need help with SWIG Message-ID: (oops. mailed to wrong list first time) On Fri, 6 Jul 2001, Patrick K. O'Brien wrote: >If there is anyone here that has experience with SWIG, I could use some >help. I'm trying to build an interface to a commercial Windows application I've heard, that on Windows you can use COM to access application as an object? (And Python works with COM) >that provides an api in the form of a dll file. I have the C header file and >tried to run it through SWIG to create the Python interface but SWIG fails >with a whole bunch of "Syntax error in input" errors. I really don't know >where to begin and I hate to spend any more time on this than necessary. All >I want is the darn Python interface so I can start using the dll from >Python. > >If anyone could help I would greatly appreciate it. I can send you the .h >file as well. Thanks. Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ _/ Saturday, July 07, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "OK, I'm weird! But I'm saving up to become eccentric." _/ From yendord@yahoo.com Sat Jul 7 10:12:49 2001 From: yendord@yahoo.com (Rodney Dieguez) Date: Sat, 7 Jul 2001 02:12:49 -0700 (PDT) Subject: [Tutor] How can I learn MORE!!!!!! Message-ID: <20010707091249.39866.qmail@web13406.mail.yahoo.com> Hi people, im a fesh-programmer from Brazil and LOVED Python... its so easy and friendly to us(poor mortals which dont know another languages ... )but its so hard to find a good book in portuguese. I wish became a effort guy to programming some applications on Python... Im need practice and expertise, I really need simple exercises to practice more and more... Would like to keep contact with begineers (like me)and experts too... to orientate me, to improve my knowledge in this area... maybe be a part of mailing list in portuguese(theres already exists ????) Thanks and best regards for all Rodney Dieguez __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From pobrien@orbtech.com Sat Jul 7 15:50:15 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Sat, 7 Jul 2001 09:50:15 -0500 Subject: [Tutor] Need help with SWIG In-Reply-To: Message-ID: Yes, I could use COM. But for a variety of reasons I still want to use the DLL API in addition to the COM and DDE interfaces. It seemed like SWIG would be the fastest way to get something up and running. --- Patrick K. O'Brien Orbtech "I am, therefore I think." -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Roman Suzi Sent: Saturday, July 07, 2001 2:14 AM To: tutor@python.org Subject: Re: [Tutor] Need help with SWIG (oops. mailed to wrong list first time) On Fri, 6 Jul 2001, Patrick K. O'Brien wrote: >If there is anyone here that has experience with SWIG, I could use some >help. I'm trying to build an interface to a commercial Windows application I've heard, that on Windows you can use COM to access application as an object? (And Python works with COM) From dyoo@hkn.eecs.berkeley.edu Sat Jul 7 20:38:37 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 7 Jul 2001 12:38:37 -0700 (PDT) Subject: [Tutor] Need help with SWIG In-Reply-To: Message-ID: On Fri, 6 Jul 2001, Patrick K. O'Brien wrote: > If there is anyone here that has experience with SWIG, I could use some > help. I'm trying to build an interface to a commercial Windows application > that provides an api in the form of a dll file. I have the C header file and > tried to run it through SWIG to create the Python interface but SWIG fails > with a whole bunch of "Syntax error in input" errors. I really don't know > where to begin and I hate to spend any more time on this than necessary. All > I want is the darn Python interface so I can start using the dll from > Python. SWIG does have a parser to figure out the functions it will wrap, but it is not perfect. You may need to nudge it to get it to work. > If anyone could help I would greatly appreciate it. I can send you the > .h file as well. Thanks. I don't know too much about SWIG, but I'm curious about it. Send the header over, and I'll play around with it today. From dyoo@hkn.eecs.berkeley.edu Sat Jul 7 20:44:54 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 7 Jul 2001 12:44:54 -0700 (PDT) Subject: [Tutor] How can I learn MORE!!!!!! In-Reply-To: <20010707091249.39866.qmail@web13406.mail.yahoo.com> Message-ID: On Sat, 7 Jul 2001, Rodney Dieguez wrote: > Hi people, > > im a fesh-programmer from Brazil and LOVED Python... > its so easy and friendly to us(poor mortals which dont > know another languages ... )but its so hard to find a > good book in portuguese. There are some resources in Portuguese for Python: http://bazar.conectiva.com.br/~cavassin/python/diferente.html http://www.python.org/doc/NonEnglish.html#portuguese Alan Gauld's web page on "Learning to Program" does have a Portuguese translation: http://www.crosswinds.net/~agauld/port/index.htm and this looks like it would be very close to what you're looking for. > Would like to keep contact with begineers (like me)and > experts too... to orientate me, to improve my > knowledge in this area... > maybe be a part of mailing list in portuguese(theres > already exists ????) You may want to ask on comp.lang.python to see if there are any Portuguese Python user groups. We're not too picky about human languages, so, feel free to ask your questions here as well. From wmperry@swbell.net Sat Jul 7 21:30:41 2001 From: wmperry@swbell.net (William Perry) Date: Sat, 07 Jul 2001 15:30:41 -0500 Subject: [Tutor] decisions, decisions In-Reply-To: References: Message-ID: <200107071530410320.1B6C9296@mail.swbell.net> A personal FWIW, I am also a newby, and I bought 'Learning Python' first, I= got stalled fairly quickly and then found Alan's web Tutorial. (Book= wasn't published yet) The tutorial got me 'unstuck' and off and= relearning. Teach yourself Python was the book I was in when it began to= gel but you may not need multiple explanations like I did. ;-\ Bill Perry *********** REPLY SEPARATOR *********** On 7/5/01 at 12:59 AM Paul De Luca wrote: > (stuff) > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From arcege@speakeasy.net Sat Jul 7 22:55:27 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 7 Jul 2001 17:55:27 -0400 (EDT) Subject: [Tutor] Need help with SWIG In-Reply-To: from "Patrick K. O'Brien" at Jul 06, 2001 04:43:40 PM Message-ID: <200107072155.f67LtRa01104@dsl092-074-184.bos1.dsl.speakeasy.net> Patrick K. O'Brien wrote > If there is anyone here that has experience with SWIG, I could use some > help. I'm trying to build an interface to a commercial Windows application > that provides an api in the form of a dll file. I have the C header file and > tried to run it through SWIG to create the Python interface but SWIG fails > with a whole bunch of "Syntax error in input" errors. I really don't know > where to begin and I hate to spend any more time on this than necessary. All > I want is the darn Python interface so I can start using the dll from > Python. It is likely that you have C++ headers, not C (windoze seems to C++), and SWIG has a lot of limitations when handling C++. It might be easier to write your own extension to wrap around the API. SWIG is very nice... when it has proper header files to work with. Also, you may need to make some typemaps to help the translations. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From sheila@thinkspot.net Sat Jul 7 23:36:43 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 07 Jul 2001 15:36:43 -0700 Subject: [Tutor] Tkinter class defn questions Message-ID: <89BF41D2CF9@kserver.org> OK, I'm going through Mark Lutz' Programming Python, 2nd ed. and Chaps. 6-9 are very thorough explanations of Tkinter programming. So, I feel like I'm doing fairly well with it (I'm on Chap. 7, right now). I even downloaded the Python Mega-Widgets and played with those a bit. But some of the finer details and nuances...well let's just say I don't fully grok them, yet. Here is an example from the book: ---------------page 305 quitter.py------------------------------ ############################################# # a quit button that verifies exit requests; # to reuse, attach an instance to other guis ############################################# from Tkinter import * # get widget classes from tkMessageBox import askokcancel # get canned std dialog class Quitter(Frame): # subclass our GUI def __init__(self, parent=None): # constructor method Frame.__init__(self, parent) self.pack() widget = Button(self, text='Quit', command=self.quit) widget.pack(expand=YES, fill=BOTH, side=LEFT) def quit(self): ans = askokcancel('Verify exit', "Really quit?") if ans: Frame.quit(self) if __name__ == '__main__': Quitter().mainloop() ----------------------------------------------------------------- OK, I'm going to say what I think the code does, and then someone please correct me, if I am wrong. First, the __init__ function: Takes "self" and a "parent" as parameters. Calls Frame.__init__(self, parent). I looked up the Frame.__init__ function in Tkinter.py and found (in part) this: ----------------------------------------------------------------- class Frame(Widget): """Frame widget which may contain other widgets and can have a 3D border.""" def __init__(self, master=None, cnf={}, **kw): """Construct a frame widget with the parent MASTER. #[much snipped] ----------------------------------------------------------------- So, we are passing to the Frame.__init__ function, the newly instantiated Quitter class object as "self", and so we are telling the Frame, in effect, that "you are a new Quitter object". Is that a good understanding of what's going on here? If the parent is "none", then it packs on the Tk root object. Otherwise, it packs on whatever object is passed as the parent parameter. In the case that the program is run as the main function, this statement: Quitter().mainloop() Takes no parameter for the Quitter object instantiation, so if parent is "none", then parent is the root Tk object. And since "self" is passed to the Frame object in Frame.__init__, then we are telling the Frame "you, the new Quitter object, have root object as your parent", and the button gets packed onto that. Is this a mostly correct understanding of this code? Can we put the .mainloop() command on any Tkinter object, not just the root Tk object? Because as I've explained it above, the Quitter object is not the root object. Rather, in the case the code is executed as "main", the Quitter object is a frame on the root Tk object, with a button on it. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From arcege@speakeasy.net Sun Jul 8 00:09:07 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sat, 7 Jul 2001 19:09:07 -0400 (EDT) Subject: [Tutor] Tkinter class defn questions In-Reply-To: <89BF41D2CF9@kserver.org> from "Sheila King" at Jul 07, 2001 03:36:43 PM Message-ID: <200107072309.f67N97K01247@dsl092-074-184.bos1.dsl.speakeasy.net> Sheila King wrote > So, we are passing to the Frame.__init__ function, the newly > instantiated Quitter class object as "self", and so we are telling the > Frame, in effect, that "you are a new Quitter object". Is that a good > understanding of what's going on here? If the parent is "none", then it > packs on the Tk root object. Otherwise, it packs on whatever object is > passed as the parent parameter. Frame.__init__ is an unbound method, so it needs to be passed the instance explicitly, self. By calling it, you are just telling the self object to pre-initialize itself as a Frame, to then setup the Quitter values. > In the case that the program is run as the main function, this > statement: > Quitter().mainloop() > > Takes no parameter for the Quitter object instantiation, so if parent is > "none", then parent is the root Tk object. And since "self" is passed to > the Frame object in Frame.__init__, then we are telling the Frame "you, > the new Quitter object, have root object as your parent", and the button > gets packed onto that. > > Is this a mostly correct understanding of this code? Yes, that's basically correct. The root object in this case would be the Tkinter._default_root global object. > Can we put the .mainloop() command on any Tkinter object, not just the > root Tk object? Because as I've explained it above, the Quitter object > is not the root object. Rather, in the case the code is executed as > "main", the Quitter object is a frame on the root Tk object, with a > button on it. Each widget has a number of standard methods, one is mainloop, which gets passed to the root widget. Also, there is a module function called "mainloop" which calls '_default_root.mainloop()'. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From s.lastinger@computernetdesign.com Sun Jul 8 00:39:58 2001 From: s.lastinger@computernetdesign.com (Stephen Lastinger) Date: Sat, 7 Jul 2001 19:39:58 -0400 (EDT) Subject: [Tutor] a question based on Sheila's Tkinter class defn questions In-Reply-To: <89BF41D2CF9@kserver.org> Message-ID: Just to see if I got this straight....Based on this formula: instance.method(args...) => becomes => class.method(instance, args...) Frame.__init__(self, parent=None) calls the Frame superclass __init__ method by a (and i'm not sure i'm using the right term here) instance caller like: im_feeling_dufus_like=Frame(blah) and blah would be the argument passed to parent? I've got inheretance[sp.] and specialization down cold, but this ....ugh and passing blah to parent...would that in turn be passed to the Frame __init__ method, and if so is it master, cnf, **kw, or none of the above... this just seems like a damn ugly way to do things..... on an opposite note...I ment to say something earlier but I've been trying to grapple with the above stuff....Danny your Ballon class e-mail on june 28th was beautiful. This is simple and elegant (and fun!). Loved it. ### class Balloon: def __init__(self, shape, color): self.shape, self.color = shape, color def __add__(self, other): return Balloon('%s tied with %s' % (self.shape, other.shape), '%s-%s' % (self.color, other.color)) myballoon = Balloon('airplane', 'blue') print myballoon.color, 'is the color of my balloon.' balloon_bag = [ Balloon('heart', 'red'), Balloon('robot', 'silver'), Balloon('blimp', 'black') ] ### Let's see what happens: ### >>> b1 = Balloon('tree', 'red') >>> b2 = Balloon('bear', 'gold') >>> b1 + b2 <__main__.Balloon instance at 80ccd30> >>> b3 = b1 + b2 >>> print b3.shape tree tied with bear >>> print b3.color red-gold On Sat, 7 Jul 2001, Sheila King wrote: [snip..] > > Here is an example from the book: > > ---------------page 305 quitter.py------------------------------ > ############################################# > # a quit button that verifies exit requests; > # to reuse, attach an instance to other guis > ############################################# > > from Tkinter import * # get widget classes > from tkMessageBox import askokcancel # get canned std dialog > > class Quitter(Frame): # subclass our GUI > def __init__(self, parent=None): # constructor method > Frame.__init__(self, parent) > self.pack() > widget = Button(self, text='Quit', command=self.quit) > widget.pack(expand=YES, fill=BOTH, side=LEFT) > def quit(self): > ans = askokcancel('Verify exit', "Really quit?") > if ans: Frame.quit(self) > > if __name__ == '__main__': Quitter().mainloop() > ----------------------------------------------------------------- > class Frame(Widget): > """Frame widget which may contain other widgets and can have a 3D > border.""" > def __init__(self, master=None, cnf={}, **kw): > """Construct a frame widget with the parent MASTER. > > #[much snipped] > ----------------------------------------------------------------- -- Stephen Lastinger - s.lastinger@computernetdesign.com Computer Network Design,Inc. - http://www.computernetdesign.com From sheila@thinkspot.net Sun Jul 8 00:34:51 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 07 Jul 2001 16:34:51 -0700 Subject: [Tutor] a question based on Sheila's Tkinter class defn questions In-Reply-To: References: <89BF41D2CF9@kserver.org> Message-ID: <8D12474124B@kserver.org> On Sat, 7 Jul 2001 19:39:58 -0400 (EDT), Stephen Lastinger wrote about [Tutor] a question based on Sheila's Tkinter class defn questions: :Just to see if I got this straight....Based on this formula: : :instance.method(args...) => becomes => class.method(instance, args...) I can't comment on the above stuff, but... :Frame.__init__(self, parent=None) : :calls the Frame superclass __init__ method by a (and i'm not sure i'm :using the right term here) instance caller like: : :im_feeling_dufus_like=Frame(blah) : :and blah would be the argument passed to parent? Yes, this is correct. :I've got inheretance[sp.] and specialization down cold, but this :....ugh : :and passing blah to parent...would that in turn be passed to the Frame :__init__ method, and if so is it master, cnf, **kw, or none of the :above... It would pass blah to parent, and then in the Frame.__init__ method, it is passed to master. self is the Frame instance, itself. master is the parent. I'm not sure what cnf is, but **kw is (I believe) a dictionary of all additional parameters not already specified by a particular argument in the parameter list. In this way, you can pass an unlimited number of parameters. In Tkinter, you may want to optionally specify a number of configuration options. I suppose, they must get passed to **kw ?? (My newbie-ish sort of guess...) -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Sat, 7 Jul 2001, Sheila King wrote: [snip..] > > Here is an example from the book: > > ---------------page 305 quitter.py------------------------------ > ############################################# > # a quit button that verifies exit requests; > # to reuse, attach an instance to other guis > ############################################# > > from Tkinter import * # get widget classes > from tkMessageBox import askokcancel # get canned std dialog > > class Quitter(Frame): # subclass our GUI > def __init__(self, parent=None): # constructor method > Frame.__init__(self, parent) > self.pack() > widget = Button(self, text='Quit', command=self.quit) > widget.pack(expand=YES, fill=BOTH, side=LEFT) > def quit(self): > ans = askokcancel('Verify exit', "Really quit?") > if ans: Frame.quit(self) > > if __name__ == '__main__': Quitter().mainloop() > ----------------------------------------------------------------- > class Frame(Widget): > """Frame widget which may contain other widgets and can have a 3D > border.""" > def __init__(self, master=None, cnf={}, **kw): > """Construct a frame widget with the parent MASTER. > > #[much snipped] > ----------------------------------------------------------------- From britt_green@hotmail.com Sun Jul 8 04:27:37 2001 From: britt_green@hotmail.com (Britt Green) Date: Sat, 07 Jul 2001 20:27:37 -0700 Subject: [Tutor] Problem Importing Classes I Create in WinNT Message-ID: I've created a very minimal class in Python. I save it and then try to import it into another program like so: import GameTime myTime = GameTime(100) Unfortunately the Python shells spits this back at me: Traceback (innermost last): File "C:/Python20/Code/stub.py", line 1, in ? import GameTime ImportError: No module named GameTime I've checked and the folder that both of these files are in is in my system PATH variable. Any thoughts? Britt -- It is pitch black. You are likely to be eaten by a grue. _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From dyoo@hkn.eecs.berkeley.edu Sun Jul 8 04:48:13 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 7 Jul 2001 20:48:13 -0700 (PDT) Subject: [Tutor] Problem Importing Classes I Create in WinNT In-Reply-To: Message-ID: On Sat, 7 Jul 2001, Britt Green wrote: > I've created a very minimal class in Python. I save it and then try to > import it into another program like so: > > import GameTime > > myTime = GameTime(100) > > Unfortunately the Python shells spits this back at me: > > Traceback (innermost last): > File "C:/Python20/Code/stub.py", line 1, in ? > import GameTime > ImportError: No module named GameTime > > I've checked and the folder that both of these files are in is in my system > PATH variable. Any thoughts? Do you mean the system PATH, or the system PYTHONPATH? The difference between them is that PATH is used for running executables (throughout the system, not just Python), and PYTHONPATH is used for looking up Python modules. You might need to add an entry in your PYTHONPATH to include those directories. Good luck! From wesc@deirdre.org Sun Jul 8 07:19:31 2001 From: wesc@deirdre.org (Wesley Chun) Date: Sat, 7 Jul 2001 23:19:31 -0700 (PDT) Subject: [Tutor] Problem Importing Classes I Create in WinNT In-Reply-To: Message-ID: On Sat, 7 Jul 2001, Danny Yoo wrote: > On Sat, 7 Jul 2001, Britt Green wrote: > > > I've created a very minimal class in Python. I save it and then try to > > import it into another program like so: > > > > import GameTime > > myTime = GameTime(100) > > Unfortunately the Python shells spits this back at me: > > > > Traceback (innermost last): > > File "C:/Python20/Code/stub.py", line 1, in ? > > import GameTime > > ImportError: No module named GameTime > > > > I've checked and the folder that both of these files are in is in my system > > PATH variable. Any thoughts? > > Do you mean the system PATH, or the system PYTHONPATH? The difference > between them is that PATH is used for running executables (throughout the > system, not just Python), and PYTHONPATH is used for looking up Python > modules. > > You might need to add an entry in your PYTHONPATH to include those > directories. Good luck! the other, less-preferred, yet more dynamic way is to fool around with your PYTHONPATH variable internally while your program is running. what i means is that the contents of PYTHONPATH are read into the sys.path variable, so upon starting your program, you could: import sys sys.path.append('/your/path/to/GameTime/') remember, this string can also be a variable, and the cool thing about doing things this way is that it allows you to dynamically decide which directory you want to grab your file from -- perhaps you have a directory for staging and one for a final or customer release, etc., or if the damn thing just keeps on changing locations all the time! better yet, this variable that is read from a "config" file for your application. this means that you can alter the behavior of your app simply by changing a config file rather than modifying your application. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From pd@localhost.localdomain Sun Jul 8 11:52:36 2001 From: pd@localhost.localdomain (pd) Date: Sun, 8 Jul 2001 20:52:36 +1000 (EST) Subject: [Tutor] Returning a variable from a module Message-ID: Hi, I have a problem with functions/modules. My code is as follows: def get(filename): """Gets values from a config file. This function scans a single config file in the format: [Config Filename] key1=value1 key2=value2 ... keyN=valueN Note: each configuration option is on a new line, and there is no space on either side of the equal sign. It dumps the value into a dictionary called config which is a global variable. It is assumed that the config file is an ascii text file.""" import string file = filename configFile= open(file, 'r') configList = configFile.readlines() configFile.close() for n in range(0, len(configList)): configList[n] = string.rstrip(configList[n]) configList[n] = string.lstrip(configList[n]) configList[n] = string.replace(configList[n], '\012', '') global config config = {} for n in range(1, len(configList)): splitString = string.split(configList[n], '=') config[splitString[0]] = splitString[1] When I cut and paste the code listed below, and call the function with: get('.gamerc') It seems to work, but when I save this code into a file called configlib.py and try to get values from the variable config. It doesnt seem to work. import configlib configlib.import('.gamerc') This leads to my question: How do I access a variable that I have created within a module which I have imported? From wheelege@tsn.cc Sun Jul 8 15:26:12 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Mon, 9 Jul 2001 00:26:12 +1000 Subject: [Tutor] Returning a variable from a module References: Message-ID: <002801c107b9$f151d220$0200a8c0@ACE> > <..snip!..> > > It seems to work, but when I save this code into a file called > configlib.py and try to get values from the variable config. It doesnt > seem to work. > > import configlib > configlib.import('.gamerc') > > This leads to my question: How do I access a variable that I have created > within a module which I have imported? > Hmmm, well it's as simple as this... def dosomething(args): ..code.. return result ## important! So, in your code, just return that config dictionary. Try to avoid global variables, as they aren't too crash hot. ## global config config = {} for n in range(1, len(configList)): splitString = string.split(configList[n], '=') config[splitString[0]] = splitString[1] ## Would become... ## config = {} for n in range(1, len(configList)): splitString = string.split(configList[n], '=') config[splitString[0]] = splitString[1] return config ## And would be called like this... import configlib config = configlib.import('.gamerc') Like magic, the variable config now has that dictionary you made in the other module. Quick question about your code - shouldn't this... for n in range(0, len(configList)): configList[n] = string.rstrip(configList[n]) configList[n] = string.lstrip(configList[n]) configList[n] = string.replace(configList[n], '\012', '') Be... for n in range(0, (len(configList)-1)): configList[n] = string.rstrip(configList[n]) configList[n] = string.lstrip(configList[n]) configList[n] = string.replace(configList[n], '\012', '') ?? Either that or I really am poor tonight :) HTH, Glen. From pdeluca@sia.net.au Sun Jul 8 16:13:16 2001 From: pdeluca@sia.net.au (Paul De Luca) Date: Mon, 9 Jul 2001 01:13:16 +1000 (EST) Subject: [Tutor] Returning a variable from a module In-Reply-To: <002801c107b9$f151d220$0200a8c0@ACE> Message-ID: Thanks, I have used return before but until now have never really understood what was going on. I tried it first, but I was returning the config dictionary in the module, then referencing it directly just like any other variable I had created in the main code. > for n in range(0, len(configList)): > configList[n] = string.rstrip(configList[n]) > configList[n] = string.lstrip(configList[n]) > configList[n] = string.replace(configList[n], '\012', '') > > Be... > > for n in range(0, (len(configList)-1)): > configList[n] = string.rstrip(configList[n]) > configList[n] = string.lstrip(configList[n]) > configList[n] = string.replace(configList[n], '\012', '') > > ?? Either that or I really am poor tonight :) > > HTH, > Glen. No, range is up to, but not including the last argument. To quote the docs: "To iterate over the indices of a sequence, combine range() and len() as follows: >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb" I think we are both really poor tonight ;) From pobrien@orbtech.com Sun Jul 8 15:24:30 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Sun, 8 Jul 2001 09:24:30 -0500 Subject: [Tutor] Returning a variable from a module In-Reply-To: Message-ID: Is that just a typo, or the cause of the problem? Your code should probably be: import configlib configlib.get('.gamerc') # not configlib.import('.gamerc') Does the get() function return a value? It probably should return config. Then the code would actually be something like: import configlib gamercConfig = configlib.get('.gamerc') --- Patrick K. O'Brien Orbtech "I am, therefore I think." -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of pd Sent: Sunday, July 08, 2001 5:53 AM To: tutor@python.org Subject: [Tutor] Returning a variable from a module It seems to work, but when I save this code into a file called configlib.py and try to get values from the variable config. It doesnt seem to work. import configlib configlib.import('.gamerc') This leads to my question: How do I access a variable that I have created within a module which I have imported? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From britt_green@hotmail.com Sun Jul 8 22:24:52 2001 From: britt_green@hotmail.com (Britt Green) Date: Sun, 08 Jul 2001 14:24:52 -0700 Subject: [Tutor] Time Variable Message-ID: What I'm trying to do is to get a variable that gets updated once every second to hold the current time. However, when I write my code, the variable gets initialized once, and never again. Can someone point out the error in my code? import time class GameTime: def __init__(self): print "Class GameTime initiated." def updateTime(self, theTime): while 1: self.theTime = time.ctime(time.time()) print theTime time.sleep( 1 ) myTime = GameTime() myTime.updateTime( time.ctime(time.time()) ) _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From scarblac@pino.selwerd.nl Sun Jul 8 22:51:08 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Sun, 8 Jul 2001 23:51:08 +0200 Subject: [Tutor] Time Variable In-Reply-To: ; from britt_green@hotmail.com on Sun, Jul 08, 2001 at 02:24:52PM -0700 References: Message-ID: <20010708235108.A14041@pino.selwerd.nl> On 0, Britt Green wrote: > What I'm trying to do is to get a variable that gets updated once every > second to hold the current time. However, when I write my code, the variable > gets initialized once, and never again. Can someone point out the error in > my code? > > import time > > class GameTime: > def __init__(self): > print "Class GameTime initiated." > > def updateTime(self, theTime): > while 1: > self.theTime = time.ctime(time.time()) > print theTime This line should be "print self.theTime" > time.sleep( 1 ) > > myTime = GameTime() > myTime.updateTime( time.ctime(time.time()) ) Just remember that theTime and self.theTime are two different variables. -- Remco Gerlich From lumbricus@gmx.net Sun Jul 8 23:17:26 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon, 9 Jul 2001 00:17:26 +0200 Subject: [Tutor] Time Variable In-Reply-To: ; from britt_green@hotmail.com on Sun, Jul 08, 2001 at 02:24:52PM -0700 References: Message-ID: <20010709001726.A1811@Laplace.localdomain> On Sun, Jul 08, 2001 at 02:24:52PM -0700, Britt Green wrote: > What I'm trying to do is to get a variable that gets updated once every > second to hold the current time. However, when I write my code, the variable > gets initialized once, and never again. Can someone point out the error in > my code? > > import time > > class GameTime: > def __init__(self): > print "Class GameTime initiated." > > def updateTime(self, theTime): ^^^^^^^ what for? > while 1: > self.theTime = time.ctime(time.time()) ^^^^^^^^^^^^^^^^^^^^^ > print theTime print self.theTime > time.sleep( 1 ) > > myTime = GameTime() > myTime.updateTime( time.ctime(time.time()) ) ^^^^^^^^^^^^^^^^^^^^^^^ why? Greetings J"o! -- "Give me enough medals, and I'll win any war." -- Napoleon From jessw@loop.com Mon Jul 9 01:53:05 2001 From: jessw@loop.com (Jesse W) Date: Sun, 8 Jul 2001 17:53:05 -0700 Subject: [Tutor] =?ISO-8859-1?Q?Who_is_Fr=E9d=E9ric_Bastiat=3F?= Message-ID: <3B489E01.26006.3F45181@localhost> Dear Rick Pasotto(and all you tutor-ites), After reading some of the long, ambiguous, and quite fascinating quotations Rick includes as his signatures, I really need to know: Who is Fr=E9d=E9ric Bastiat? Rick(or anyone else), please raise to the state of enlightenment. Thank you all, Jesse W From pdeluca@sia.net.au Mon Jul 9 03:23:02 2001 From: pdeluca@sia.net.au (Paul De Luca) Date: Mon, 9 Jul 2001 12:23:02 +1000 (EST) Subject: [Tutor] Returning a variable from a module In-Reply-To: Message-ID: Yeah, it was just a typo I made when writing the email. I realized it after I send the email. I Was hoping nobody would notice, but I guess thats hard considering every single person subscribed to this list is a programmer. Poor spelling/grammar never seems to go down well with the open source community. ;) On Sun, 8 Jul 2001, Patrick K. O'Brien wrote: > Is that just a typo, or the cause of the problem? Your code should probably > be: > > import configlib > configlib.get('.gamerc') # not configlib.import('.gamerc') > > Does the get() function return a value? It probably should return config. > Then the code would actually be something like: > > import configlib > gamercConfig = configlib.get('.gamerc') > > --- > Patrick K. O'Brien > Orbtech > "I am, therefore I think." > > -----Original Message----- > From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of pd > Sent: Sunday, July 08, 2001 5:53 AM > To: tutor@python.org > Subject: [Tutor] Returning a variable from a module > > > > It seems to work, but when I save this code into a file called > configlib.py and try to get values from the variable config. It doesnt > seem to work. > > import configlib > configlib.import('.gamerc') > > This leads to my question: How do I access a variable that I have created > within a module which I have imported? > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------- Paul De Luca Email: pdeluca@sia.net.au Ph: 0414 225 561 ------------------------- From rick@niof.net Mon Jul 9 04:02:56 2001 From: rick@niof.net (Rick Pasotto) Date: Sun, 8 Jul 2001 23:02:56 -0400 Subject: [Tutor] Who is Fr?d?ric Bastiat? In-Reply-To: <3B489E01.26006.3F45181@localhost> Message-ID: <20010708230256.B13626@tc.niof.net> On Sun, Jul 08, 2001 at 05:53:05PM -0700, Jesse W wrote: > Dear Rick Pasotto(and all you tutor-ites), > After reading some of the long, ambiguous, and quite > fascinating quotations Rick includes as his signatures, I really need > to know: Who is Fr?d?ric Bastiat? Rick(or anyone else), please > raise to the state of enlightenment. A french free market economist. His essay 'That which is seen and that which is not seen' was the basis for Henry Hazlitt's book 'Economics In One Lesson.' Visit http://www.bastiat.org -- Our doctrine is based on private property. Communism is based on systematic plunder, since it consists in handing over to one man, without compensation, the labor of another. If it distributed to each one according to his labor, it would, in fact, recognize private property and would no longer be communism. -- Frйdйric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From dyoo@hkn.eecs.berkeley.edu Mon Jul 9 09:23:38 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 9 Jul 2001 01:23:38 -0700 (PDT) Subject: [Tutor] Typos and attitudes on language In-Reply-To: Message-ID: On Mon, 9 Jul 2001, Paul De Luca wrote: > Yeah, it was just a typo I made when writing the email. I realized it > after I send the email. I Was hoping nobody would notice, but I guess > thats hard considering every single person subscribed to this list is a > programmer. Poor spelling/grammar never seems to go down well with the > open source community. ;) Not just open source communities: I've noticed that there's an overall trend of those who have experience with computer languages becoming a little more careful with their spelling and grammar. Perhaps part of it is because programmers might be developing a stronger sensitivity for syntax, even in the "artificial" form of a computer language. Personally, I've felt that programming isn't always "mathy", but on the other hand, is consistently "verbal" because of the effort of organizing and expressing ideas. It might be something that a sociologist could write an essay about... *grin* From senthil_kovai@yahoo.com Mon Jul 9 14:30:10 2001 From: senthil_kovai@yahoo.com (senthilvellan) Date: Mon, 9 Jul 2001 19:00:10 +0530 Subject: [Tutor] subscribe me Message-ID: <004701c1087b$de24fc50$300110ac@kovaiteam> This is a multi-part message in MIME format. ------=_NextPart_000_0043_01C108A9.6087EAE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ------=_NextPart_000_0043_01C108A9.6087EAE0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 
------=_NextPart_000_0043_01C108A9.6087EAE0-- _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From mosrassil@yahoo.com Mon Jul 9 10:21:02 2001 From: mosrassil@yahoo.com (mosrassil@yahoo.com) Date: Пн, 9 июл 2001 14:43:02 Subject: [Tutor] Рассылка по 100.000 Московских е-майлов Message-ID: Рассылка Вашей рекламы по 100.000 Московских е-майлов. Эффективно. Профессиональный подход. Цена: 100 долл. From aschmidt@nv.cc.va.us Mon Jul 9 15:22:51 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Mon, 9 Jul 2001 10:22:51 -0400 Subject: [Tutor] Date and Time questions Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090688C121@novamail1.nv.cc.va.us> I have looked around for things that deal with Date and Time. All I want to do is be able to assign a date/time value to a variable. Like 20010709_18:05. Does not need to be a date object just a text string that I can use to drop into a database table or use in other ways. The date time stuff seems a bit overly complicated. Any tips or pointers to online resources I may have missed. Thanks Allen From wheelege@tsn.cc Mon Jul 9 15:32:14 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Tue, 10 Jul 2001 00:32:14 +1000 Subject: [Tutor] Typos and attitudes on language References: Message-ID: <003201c10883$f347ee00$0200a8c0@ACE> > On Mon, 9 Jul 2001, Paul De Luca wrote: > > > Yeah, it was just a typo I made when writing the email. I realized it > > after I send the email. I Was hoping nobody would notice, but I guess > > thats hard considering every single person subscribed to this list is a > > programmer. Poor spelling/grammar never seems to go down well with the > > open source community. ;) > > Not just open source communities: I've noticed that there's an overall > trend of those who have experience with computer languages becoming a > little more careful with their spelling and grammar. > > Perhaps part of it is because programmers might be developing a stronger > sensitivity for syntax, even in the "artificial" form of a computer > language. Personally, I've felt that programming isn't always "mathy", > but on the other hand, is consistently "verbal" because of the effort of > organizing and expressing ideas. > > It might be something that a sociologist could write an essay about... > *grin* > And to think, I always put it down to the people of over-average intelligence being computer programmers. I guess what Mr D is saying makes alot of sense :) From wheelege@tsn.cc Mon Jul 9 15:51:46 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Tue, 10 Jul 2001 00:51:46 +1000 Subject: [Tutor] Date and Time questions References: <5CDFEBB60E7FD311B9E30000F6D6090688C121@novamail1.nv.cc.va.us> Message-ID: <002701c10886$ad75c160$0200a8c0@ACE> > I have looked around for things that deal with Date and Time. > All I want to do is be able to assign a date/time value to a variable. Like > 20010709_18:05. > Does not need to be a date object just a text string that I can use to drop > into a database table or use in other ways. > > The date time stuff seems a bit overly complicated. Any tips or pointers to > online resources I may have missed. > You sure this isn't what you want? >>> import time >>> time.ctime() 'Tue Jul 10 00:50:35 2001' >>> Isn't that a good enough string? From rob@jam.rr.com Mon Jul 9 16:00:53 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 9 Jul 2001 10:00:53 -0500 Subject: [Tutor] Date and Time questions In-Reply-To: <5CDFEBB60E7FD311B9E30000F6D6090688C121@novamail1.nv.cc.va.us> Message-ID: # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # Schmidt, Allen J. # Sent: Monday, July 09, 2001 9:23 AM # To: tutor@python.org # Subject: [Tutor] Date and Time questions # # # I have looked around for things that deal with Date and Time. # All I want to do is be able to assign a date/time value to a # variable. Like # 20010709_18:05. # Does not need to be a date object just a text string that I can # use to drop # into a database table or use in other ways. # # The date time stuff seems a bit overly complicated. Any tips or # pointers to # online resources I may have missed. # Here are a few things you can do with the time module: # first import the time module >>> import time # the time module allows a few different ways to express time >>> time.time() 994689648.35000002 >>> time.clock() 6.7047721215575185e-006 # assigning the value to a variable is pretty painless >>> currenttime=time.time() >>> currenttime 994689713.05999994 # Personally, I like to be able to make some sense of it when I look at it. >>> time.ctime(currenttime) 'Mon Jul 09 09:41:53 2001' >>> time.ctime(time.time()) 'Mon Jul 09 09:45:23 2001' Hope this helps, Rob "Perl is worse than Python because people wanted it worse." Larry Wall (Creator of Perl), 14 Oct 1998 Useless Python: http://www.lowerstandard.com/python/ From arcege@speakeasy.net Mon Jul 9 16:41:57 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Mon, 9 Jul 2001 11:41:57 -0400 (EDT) Subject: [Tutor] Date and Time questions In-Reply-To: <5CDFEBB60E7FD311B9E30000F6D6090688C121@novamail1.nv.cc.va.us> from "Schmidt, Allen J." at Jul 09, 2001 10:22:51 AM Message-ID: <200107091541.f69Ffv402872@dsl092-074-184.bos1.dsl.speakeasy.net> Schmidt, Allen J. wrote > > I have looked around for things that deal with Date and Time. > All I want to do is be able to assign a date/time value to a variable. Like > 20010709_18:05. > Does not need to be a date object just a text string that I can use to drop > into a database table or use in other ways. Date formatting is complicated because different software systems use different formats for the dates. Remember that the infamous Y2K "bugs" were because of date formatting. Most computers keep track of time as the number of seconds since what is called the Epoch, approxiately 1970. Everything else is just a re-formatting of that count. To add to the complexity, there are timezones (which are not all equal) and daylight savings time, which doesn't exist everywhere. First, get the current time, then convert it to the local timezone, adjusting for daylight savings, then to a string. If you are looking for a filename, then it is a bad idea to use the ctime output, it doesn't sort well and contains spaces. >>> import time >>> curtime = time.time() >>> curtime = time.time() >>> curlcltime = time.localtime(curtime) >>> print curtime, curlcltime 994692772.858 (2001, 7, 9, 11, 32, 52, 0, 190, 1) >>> print time.asctime(curlcltime) Mon Jul 9 11:32:52 2001 >>> print time.ctime(curtime) Mon Jul 9 11:32:52 2001 >>> fmt = '%Y%m%d_%H:%M' # set the output format: YYYYMMDD_HH:MM >>> print time.strftime(fmt, curlcltime) 20010709_11:32 >>> (year, month, day, hour, min, sec, wday, yday, dst) = curlcltime >>> print '%4d%02d%02d_%02d:%02d' % (year, month, day, hour, min) With strftime, you can create just about any string you like, but you also can do the same with accessing the items in the tuple returned by time.localtime(). You might also want to look at the wxDateTime package. Good luck, -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From aschmidt@nv.cc.va.us Mon Jul 9 16:50:08 2001 From: aschmidt@nv.cc.va.us (Schmidt, Allen J.) Date: Mon, 9 Jul 2001 11:50:08 -0400 Subject: [Tutor] Date and Time questions Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090688C123@novamail1.nv.cc.va.us> This is it! Perfect! Been using Zope for so long and could do this easily using the fmt attribute of dtml-var. Your solution offered something that matches what I have been used to. Just did not know how to get it into a usable format to use the fmt attribute. This is an email that will be added to my KnowledgeArsenal! Thanks very much to you and all the suggestions offered! -Allen -----Original Message----- From: Michael P. Reilly [mailto:arcege@dsl092-074-184.bos1.dsl.speakeasy.net] Sent: Monday, July 09, 2001 11:42 AM To: aschmidt@nv.cc.va.us Cc: tutor@python.org Subject: Re: [Tutor] Date and Time questions Schmidt, Allen J. wrote > > I have looked around for things that deal with Date and Time. > All I want to do is be able to assign a date/time value to a variable. Like > 20010709_18:05. > Does not need to be a date object just a text string that I can use to drop > into a database table or use in other ways. Date formatting is complicated because different software systems use different formats for the dates. Remember that the infamous Y2K "bugs" were because of date formatting. Most computers keep track of time as the number of seconds since what is called the Epoch, approxiately 1970. Everything else is just a re-formatting of that count. To add to the complexity, there are timezones (which are not all equal) and daylight savings time, which doesn't exist everywhere. First, get the current time, then convert it to the local timezone, adjusting for daylight savings, then to a string. If you are looking for a filename, then it is a bad idea to use the ctime output, it doesn't sort well and contains spaces. >>> import time >>> curtime = time.time() >>> curtime = time.time() >>> curlcltime = time.localtime(curtime) >>> print curtime, curlcltime 994692772.858 (2001, 7, 9, 11, 32, 52, 0, 190, 1) >>> print time.asctime(curlcltime) Mon Jul 9 11:32:52 2001 >>> print time.ctime(curtime) Mon Jul 9 11:32:52 2001 >>> fmt = '%Y%m%d_%H:%M' # set the output format: YYYYMMDD_HH:MM >>> print time.strftime(fmt, curlcltime) 20010709_11:32 >>> (year, month, day, hour, min, sec, wday, yday, dst) = curlcltime >>> print '%4d%02d%02d_%02d:%02d' % (year, month, day, hour, min) With strftime, you can create just about any string you like, but you also can do the same with accessing the items in the tuple returned by time.localtime(). You might also want to look at the wxDateTime package. Good luck, -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From bill-bell@bill-bell.hamilton.on.ca Mon Jul 9 17:15:12 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Mon, 9 Jul 2001 12:15:12 -0400 Subject: [Tutor] Re: Typos and attitudes on language In-Reply-To: Message-ID: <3B49A050.12804.3D582A2@localhost> Danny Yoo wrote, in part: > ... Personally, I've felt that programming isn't > always "mathy", but on the other hand, is consistently "verbal" > because of the effort of organizing and expressing ideas. I'm fairly sure that Knuth says something like this in one of his books, possibly the one that is a compendium of samples of his writings. If not him then it was someone else of approximately his stature. And, FWIW, I've been at this for a very long time and it's the way it seems to me too. If the ability to make syllogisms and other logical constructions were paramount then I would be dead. From pdeluca@sia.net.au Mon Jul 9 17:45:00 2001 From: pdeluca@sia.net.au (Paul De Luca) Date: Tue, 10 Jul 2001 02:45:00 +1000 (EST) Subject: [Tutor] Date and Time questions In-Reply-To: <5CDFEBB60E7FD311B9E30000F6D6090688C121@novamail1.nv.cc.va.us> Message-ID: >From the docs I managed to work out your problem. It was a bit complicated, I just looked for the function that provided output, then find out what data it needed, then looked for a function that provided that etc. Running Linux and using the date command with its string formatting options made this seem a bit familiar too. [pd@localhost pd]$ python Python 2.0 (#1, Apr 11 2001, 19:18:08) [GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386 Type "copyright", "credits" or "license" for more information. >>> import time >>> epoch = time.time() >>> localtime = time.localtime(epoch) >>> timeString = time.strftime('%Y%m%d_%H:%M', localtime) >>> print timeString 20010710_02:25 >>> Here I returned the string as year|month|day_HourIn24hrFormat|Minute| If it looks a bit foreign read through the time module a few times, and you should get it. Epoch - the time in seconds past a set date. On UNIX machines this is Jan 1 1970 at 00:00 There is also a bit of info on the different ways time is measured at the beginning of the module docs. On Mon, 9 Jul 2001, Schmidt, Allen J. wrote: > I have looked around for things that deal with Date and Time. > All I want to do is be able to assign a date/time value to a variable. Like > 20010709_18:05. > Does not need to be a date object just a text string that I can use to drop > into a database table or use in other ways. > > The date time stuff seems a bit overly complicated. Any tips or pointers to > online resources I may have missed. > > Thanks > > Allen > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------- Paul De Luca Email: pdeluca@sia.net.au Ph: 0414 225 561 ------------------------- From britt_green@hotmail.com Mon Jul 9 17:57:44 2001 From: britt_green@hotmail.com (Britt Green) Date: Mon, 09 Jul 2001 09:57:44 -0700 Subject: [Tutor] Threading a Class? Message-ID: Alright, I think I have the basics of my Time class going the way I want it to. Now I need to make it threaded. This is what I have so far: import time class GameTime: def __init__(self): print "Class GameTime initiated." def updateTime(self): while 1: self.theTime = time.ctime(time.time()) print self.theTime time.sleep( 20 ) myTime = GameTime() myTime.updateTime() The time.sleep() function causes my program to, well, sleep for twenty seconds and during that time my program can do nothing else. I'd like to put this in a thread so that other things can be executed while the timer is sleeping. Unfortunately, I'm kind of stuck on how to do this. I've gotten pointed in the right direction by a couple of books, but because this is the first time I've written anything involving threads, I could really use some step-by-step instruction on this. Many thanks! _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From scarblac@pino.selwerd.nl Mon Jul 9 18:26:47 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Mon, 9 Jul 2001 19:26:47 +0200 Subject: [Tutor] Threading a Class? In-Reply-To: ; from britt_green@hotmail.com on Mon, Jul 09, 2001 at 09:57:44AM -0700 References: Message-ID: <20010709192647.A15580@pino.selwerd.nl> On 0, Britt Green wrote: > Alright, I think I have the basics of my Time class going the way I want it > to. Now I need to make it threaded. This is what I have so far: > > import time > > class GameTime: > def __init__(self): > print "Class GameTime initiated." > > def updateTime(self): > while 1: > self.theTime = time.ctime(time.time()) > print self.theTime > time.sleep( 20 ) > > myTime = GameTime() > myTime.updateTime() > > The time.sleep() function causes my program to, well, sleep for twenty > seconds and during that time my program can do nothing else. I'd like to put > this in a thread so that other things can be executed while the timer is > sleeping. import threading mythread = threading.Thread(target=myTime.updateTime) mythread.start() Now mythread is running the updateTime function, and your program continues in the main thread. The thread won't stop by itself - it's in a while 1:. Change that into a while someguard: so that you can set someguard to 0 from the main thread, if you want to stop the thread. > Unfortunately, I'm kind of stuck on how to do this. I've gotten pointed in > the right direction by a couple of books, but because this is the first time > I've written anything involving threads, I could really use some > step-by-step instruction on this. This is the simple part; getting a thread to run. Concurrent programming holds many gotchas though, it's not a trivial subject. Just to name a few things: if you have a GUI, make sure only one thread works with GUI elements. Also, if several threads want to change the same variable, you may have race conditions. I.e, if x == 0, and two threads execute "x = x+1", it may go like this: thread 1 thread 2 get x compute x+1 (=1) get x compute x+1 (=1) store 1 in x store 1 in x Now x is 1 after both threads finish. But this is also possible: thread 1 thread 2 get x compute x+1 (=1) store 1 in x get x compute x+1 (=2) store 1 in x Now x is 2. You need to put a *semaphore* around x when you do something with it; it's a sort of lock around the variable, saying "i'm busy with this now, wait until I'm done before you start". This space is too small to explain everything; just expect the unexpected... -- Remco Gerlich From tim@digicool.com Mon Jul 9 20:18:48 2001 From: tim@digicool.com (Tim Peters) Date: Mon, 9 Jul 2001 15:18:48 -0400 Subject: [Tutor] Re: Typos and attitudes on language In-Reply-To: <3B49A050.12804.3D582A2@localhost> Message-ID: [Danny Yoo] > ... Personally, I've felt that programming isn't always "mathy", > but on the other hand, is consistently "verbal" because of the > effort of organizing and expressing ideas. [Bill Bell] > I'm fairly sure that Knuth says something like this in one of his > books, possibly the one that is a compendium of samples of his > writings. If not him then it was someone else of approximately his > stature. I expect you're thinking of this line from Dijkstra's famous 1975 "How do we tell truths that might hurt?" (widely paraphrased by others since): Besides a mathematical inclination, an exceptionally good mastery of one's native tongue is the most vital asset of a competent programmer. The full text of this brief but influential essay can be found here: http://www.imm.dtu.dk/~uniaaa/hurtingtruths.html > And, FWIW, I've been at this for a very long time and it's the way it > seems to me too. If the ability to make syllogisms and other logical > constructions were paramount then I would be dead. That differs from "mathematical inclination": if you can't *think* logically, programming will forever frustrate. Whether you know the formal mechanics of predicate logic isn't of much relevance. From robin@centralsoftwareservices.com Mon Jul 9 21:25:18 2001 From: robin@centralsoftwareservices.com (Robin Kuruvila) Date: Mon, 9 Jul 2001 13:25:18 -0700 Subject: [Tutor] environment settings Message-ID: hi all, I am writing a small C Extension Module. I've included in the program. When i run the program it says ' Python.h: No such file or directory' , am not sure how to set the environment. robin From dsh8290@rit.edu Mon Jul 9 22:06:49 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 9 Jul 2001 17:06:49 -0400 Subject: [Tutor] environment settings In-Reply-To: ; from robin@centralsoftwareservices.com on Mon, Jul 09, 2001 at 01:25:18PM -0700 References: Message-ID: <20010709170649.A3366@harmony.cs.rit.edu> On Mon, Jul 09, 2001 at 01:25:18PM -0700, Robin Kuruvila wrote: | hi all, | I am writing a small C Extension Module. I've included in the | program. When i run the program it says ' Python.h: No such file or | directory' , am not sure how to set the environment. Do you have the python headers installed on your system? If so they either need to be in the system include path or you need to include it when you invoke the compiler. You haven't mentioned what OS or what compiler you're using. If you are using gcc (Unix or cygwin) use the -I option to add directories to the include path. For example, if the headers are in ~/Python_headers use 'gcc -I ~/Python_headers my_app.c'. -D From rear@sirius.com Tue Jul 10 02:00:49 2001 From: rear@sirius.com (Bob Rea) Date: Mon, 9 Jul 2001 18:00:49 -0700 Subject: [Tutor] Help with Homework ;) Message-ID: <01070918004904.14790@gandalf> I am trying to teach myself Python from Wes Chun's book and I am stuck on one of the exercises, 3-11. I could use a hint. Here is what I have tried (the exercise is stated in the comments): #!/usr/bin/env python ''' $Id: fgrepwc.py,v 1.3 1999/09/08 02:23:51 wesc Exp wesc $ fgrepwc.py - searches for string in text file This module will output all lines of given file containing given string, including total number of matching lines. This module can be imported, or executed standalone with the following usage syntax: Usage: fgrepwc.py word filename Exercises: 3-10) add case-insensitive search 3-11) change "line count" to "word count...," i.e., check if word appears more than once in line and truly count how many times a word shows up in a text file ''' import sys # system module import string # string utility module # # usage() -- prints usage and exits # def usage(): print "usage: fgrepwc [ -i ] string file" sys.exit(1) # # filefind() -- searches for 'word' within file 'filename' # def filefind(word, filename): # reset word count count = 0 # see if we can open the file try: file_handle = open(filename, 'r') except: print filename, ":", sys.exc_value[1] sys.exit(1) # read in all lines and close file lines = file_handle.readlines() file_handle.close() # for each line, check for the word for i in lines: if sys.argv[1] == '-i': if string.count(string.split(string.lower(i)), word) > -1: count = count + 1 print i, else: if string.count(string.split(i), word) > -1: count = count + 1 print i # output line count print count # # main() -- used only when module is executed # def main(): # check command-line arguments print "Hello" print sys.argv argc = len(sys.argv) if argc != 3 and argc != 4: usage() if sys.argv[1] == '-i': filefind(sys.argv[2], sys.argv[3]) else: filefind(sys.argv[1], sys.argv[2]) # executes only if not imported if __name__ == '__main__': main() comments? -- Bob Rea Fear of Hell is pernicious; So is fear of Heaven. rear@sirius.com http://www.sirius.com/~rear From ak@silmarill.org Tue Jul 10 02:12:36 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Mon, 09 Jul 2001 21:12:36 -0400 Subject: [Tutor] Help with Homework ;) In-Reply-To: <"from rear"@sirius.com> References: <01070918004904.14790@gandalf> Message-ID: <20010709211236.A27320@sill.silmarill.org> On Mon, Jul 09, 2001 at 06:00:49PM -0700, Bob Rea wrote: > I am trying to teach myself Python from Wes Chun's book and I am > stuck on one of the exercises, 3-11. I could use a hint. > > Here is what I have tried (the exercise is stated in the comments): > > #!/usr/bin/env python > ''' > $Id: fgrepwc.py,v 1.3 1999/09/08 02:23:51 wesc Exp wesc $ > > fgrepwc.py - searches for string in text file > > This module will output all lines of given file containing given > string, > including total number of matching lines. This module can be > imported, > or executed standalone with the following usage syntax: > > Usage: fgrepwc.py word filename > > Exercises: > > 3-10) add case-insensitive search > > 3-11) change "line count" to "word count...," i.e., check if word > appears more than once in line and truly count how many times > a word shows up in a text file > ''' > > import sys # system module > import string # string utility module > > # > # usage() -- prints usage and exits > # > def usage(): > print "usage: fgrepwc [ -i ] string file" > sys.exit(1) > > > # > # filefind() -- searches for 'word' within file 'filename' > # > > > def filefind(word, filename): > > # reset word count > count = 0 > > # see if we can open the file > try: > file_handle = open(filename, 'r') > except: > print filename, ":", sys.exc_value[1] > sys.exit(1) > > # read in all lines and close file > lines = file_handle.readlines() > file_handle.close() > > # for each line, check for the word > for i in lines: > if sys.argv[1] == '-i': > if string.count(string.split(string.lower(i)), word) > > -1: why are you splitting i? string.count takes two strings, in this case it should be something like string.count(i.lower(), word). When you split i you get a list of words there, instead of one string. Also, if you use 2.1 (and maybe 2.0), it's shorter to use string methods like i.lower() instead of string.lower(i). > count = count + 1 > print i, > else: > if string.count(string.split(i), word) > -1: > count = count + 1 > print i > > # output line count > print count > > > # > # main() -- used only when module is executed > # > def main(): > > # check command-line arguments > print "Hello" > print sys.argv > argc = len(sys.argv) > if argc != 3 and argc != 4: > usage() > if sys.argv[1] == '-i': > filefind(sys.argv[2], sys.argv[3]) > else: > filefind(sys.argv[1], sys.argv[2]) > > > > > # executes only if not imported > if __name__ == '__main__': > main() > > comments? > > -- > Bob Rea > > Fear of Hell is pernicious; > So is fear of Heaven. > > rear@sirius.com http://www.sirius.com/~rear > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From dsh8290@rit.edu Tue Jul 10 02:23:50 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 9 Jul 2001 21:23:50 -0400 Subject: [Tutor] environment settings In-Reply-To: ; from robin@centralsoftwareservices.com on Mon, Jul 09, 2001 at 02:41:54PM -0700 References: <20010709170649.A3366@harmony.cs.rit.edu> Message-ID: <20010709212350.C3490@harmony.cs.rit.edu> On Mon, Jul 09, 2001 at 02:41:54PM -0700, Robin Kuruvila wrote: | hello, | I am using Red Hat Linux 7.0 and use Python2.1 and use gcc 2.95 for | compilation. I 've included the test programs and the associated make file. | When run 'gcc hello.c' i get an error saying 'Python.h: No such file or | directory' | tried 'gcc -I /usr/include/python2.1/Python.h hello.c' get an error saying | 'Python.h: No such file or directory' | | I could eliminate the error by hardcoding the header file path within the | program as shown in the example. When i do this i get This will work because /usr/include is part of the default search path. | bunch of linker issues, when compiling. You need to tell the linker what libraries you want to link to. You might have to tell it where the .so is, if it isn't in the default search path. I think it should be in /usr/lib which is in the default search path. If I assume that the library is "libpython.so" then you want the following gcc command line : gcc -I /usr/include/python2.1 -lpython hello.c HTH, -D From Sheila King , tutor@python.org Tue Jul 10 02:46:38 2001 From: Sheila King , tutor@python.org (Sheila King , tutor@python.org) Date: Mon, 09 Jul 2001 18:46:38 -0700 Subject: [Tutor] Tkinter class defn questions In-Reply-To: <89BF41D2CF9@kserver.org> References: <89BF41D2CF9@kserver.org> Message-ID: <200107100146.UAA34326250@smtppop3pub.verizon.net> On Sat, 07 Jul 2001 15:36:43 -0700, Sheila King wrote about [Tutor] Tkinter class defn questions: : :Here is an example from the book: : :---------------page 305 quitter.py------------------------------ :############################################# :# a quit button that verifies exit requests; :# to reuse, attach an instance to other guis :############################################# : :from Tkinter import * # get widget classes :from tkMessageBox import askokcancel # get canned std dialog : :class Quitter(Frame): # subclass our GUI : def __init__(self, parent=None): # constructor method : Frame.__init__(self, parent) : self.pack() : widget = Button(self, text='Quit', command=self.quit) : widget.pack(expand=YES, fill=BOTH, side=LEFT) : def quit(self): : ans = askokcancel('Verify exit', "Really quit?") : if ans: Frame.quit(self) : :if __name__ == '__main__': Quitter().mainloop() :----------------------------------------------------------------- : :OK, I'm going to say what I think the code does, and then someone please :correct me, if I am wrong. OK, here is something I didn't realize at the time I sent my previous message on this topic. However, I did some additional reading on Classes in Core Python Programming and NOW I SEE that... class NewClass(OtherClass): class-suite Is how you derive a New Class from some Other Class. If you want to take advantage of the __init__ procedure of the parent class from which you are deriving the new class, then you must call the parent class' __init__ procedure specifically, thus the Frame.__init__(self, parent) statement in the example above. If I would have realized before, that this was an example of Subclassing, I would have understood the code better in the first place! -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From Sheila King , tutor@python.org Tue Jul 10 03:28:04 2001 From: Sheila King , tutor@python.org (Sheila King , tutor@python.org) Date: Mon, 09 Jul 2001 19:28:04 -0700 Subject: [Tutor] Please Critque Tkinter Class for Newbie Message-ID: <200107100228.VAA138360666@smtppop1pub.verizon.net> OK, I'm learning Tkinter, and have written a small Tkinter class, and would appreciate the useful criticism of those more learned than myself. Anything about style, efficiency, idioms, etc... that you think would improve the code would be most welcome. Thanks. Code follows signature. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ from Tkinter import * colorVals = [ '00', '33', '66', '99', 'CC', 'FF' ] class Palette(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) for item in colorVals: for tuple in [('00', '33', '66'), ('99', 'CC', 'FF')]: PlaqueRow(self, item, tuple).pack() self.pack() self.colortext=StringVar() self.info = colorInfo(self, self.colortext) self.info.pack(side=LEFT) self.colortext.set("") self.bind_all('', self.displayColor) def displayColor(self, event): self.colortext.set(event.widget.color) self.info.colorDisplay.config(bg=event.widget.color) class colorInfo(Frame): def __init__(self, parent=None, text=""): Frame.__init__(self, parent, height=25, width=200) Label(self, text="click on a color", font=("bold", 12)).pack() self.colorDisplay = Label(self, width=6, height = 1, bg='#FFFFFF') self.colorDisplay.pack(side=LEFT) colorValue = Entry(self, width=10, textvariable = text) colorValue.pack(side=LEFT) class PlaqueRow(Frame): def __init__(self, parent=None, leadcolor='00', colortuple = ('00', '33', '66')): Frame.__init__(self, parent) for val in colortuple: for choice in colorVals: # global variable-list of all colors block = Plaque(self, '#'+leadcolor+val+choice) block.config(bd='1') # set border of button to one block.pack(side=LEFT) class Plaque(Button): def __init__(self, parent, color="#000000"): Button.__init__(self, parent, bg=color, activebackground=color, height=1, width=2) self.color=color if __name__ == '__main__': root = Tk() root.protocol("WM_DELETE_WINDOW", root.quit) palette = Palette(root) palette.pack() root.mainloop() From clanoftheinsane@hotmail.com Tue Jul 10 03:48:28 2001 From: clanoftheinsane@hotmail.com (Paul Brown) Date: Mon, 09 Jul 2001 22:48:28 -0400 Subject: [Tutor] executing Python programs in windows Message-ID:

hello,

i know that in Linux, you can do the chmod function to allow the user to be able to execute a python program from any directory in the system.  for example, if python was installed in the /home/python directory, you could still execute a python script even if you are in /home/myfiles directory (just an example) in the terminal.  is there any way to do this in Windows?  thanks

paul brown



Get your FREE download of MSN Explorer at http://explorer.msn.com

From ppathiyi@cisco.com Tue Jul 10 06:22:19 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Tue, 10 Jul 2001 10:52:19 +0530 Subject: [Tutor] Number Conversion routines Message-ID: <014501c10900$4e6caec0$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_0142_01C1092E.64006E60 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi All, Is there any module or built-in routines which does conversion = between different represenations of numbers ? I mean binary-to-hex, hex-to-binary, binary-to decimal etc. Thanks, Praveen. ------=_NextPart_000_0142_01C1092E.64006E60 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi All,
 
        Is there any module or = built-in=20 routines which does conversion between different represenations of = numbers=20 ?
I mean binary-to-hex, hex-to-binary, binary-to decimal etc.
 
Thanks,
Praveen.
------=_NextPart_000_0142_01C1092E.64006E60-- From ak@silmarill.org Tue Jul 10 06:42:08 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Tue, 10 Jul 2001 01:42:08 -0400 Subject: [Tutor] Number Conversion routines In-Reply-To: <"from ppathiyi"@cisco.com> References: <014501c10900$4e6caec0$37ef87c0@ppathiyipc> Message-ID: <20010710014208.A29260@sill.silmarill.org> On Tue, Jul 10, 2001 at 10:52:19AM +0530, Praveen Pathiyil wrote: > Hi All, > > Is there any module or built-in routines which does conversion between different represenations of numbers ? > I mean binary-to-hex, hex-to-binary, binary-to decimal etc. > > Thanks, > Praveen. There's built in hex() function that turns a decimal into hex. Also, I saw a function posted to comp.lang.python that turns decimal into binary, search groups.google.com for it. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From lumbricus@gmx.net Tue Jul 10 03:56:39 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue, 10 Jul 2001 04:56:39 +0200 Subject: [Tutor] Help with Homework ;) In-Reply-To: <01070918004904.14790@gandalf>; from rear@sirius.com on Mon, Jul 09, 2001 at 06:00:49PM -0700 References: <01070918004904.14790@gandalf> Message-ID: <20010710045639.A10471@Laplace.localdomain> On Mon, Jul 09, 2001 at 06:00:49PM -0700, Bob Rea wrote: > I am trying to teach myself Python from Wes Chun's book and I am > stuck on one of the exercises, 3-11. I could use a hint. > > Here is what I have tried (the exercise is stated in the comments): > > #!/usr/bin/env python > ''' > $Id: fgrepwc.py,v 1.3 1999/09/08 02:23:51 wesc Exp wesc $ > > fgrepwc.py - searches for string in text file > > > # for each line, check for the word > for i in lines: > if sys.argv[1] == '-i': you get sys.argv[1] once but you test it in every iteration of the for-loop. > # check command-line arguments getopt is your friend ;-) HTH J"o! -- Delta: We never make the same mistake three times. -- David Letterman From doc_pepin@yahoo.com Tue Jul 10 12:13:29 2001 From: doc_pepin@yahoo.com (doc pepin) Date: Tue, 10 Jul 2001 04:13:29 -0700 (PDT) Subject: [Tutor] please help me on this small project of mine Message-ID: <20010710111329.87626.qmail@web13908.mail.yahoo.com> i am a newbie programmer and an owner of a small internet cafe. i was thinking that to learn to program i have to strart with a small project. i was thinking that a program to manage my internet cafe would be great. i have already started with the script on how to compute for time spent by the client and how much was the charge for that time. what i want is have a GUI for that and can disable a certain workstation (like its keyboard) from the server. i'm at a lost on how to start it. any help would be greatly appreciated. or is this project too complicated for a newbie like me? __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From arcege@speakeasy.net Tue Jul 10 13:09:46 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 10 Jul 2001 08:09:46 -0400 (EDT) Subject: [Tutor] Please Critque Tkinter Class for Newbie In-Reply-To: <200107100228.VAA138360666@smtppop1pub.verizon.net> from "notme@gte.net" at Jul 09, 2001 07:28:04 PM Message-ID: <200107101209.f6AC9k602068@dsl092-074-184.bos1.dsl.speakeasy.net> notme@gte.net wrote > OK, I'm learning Tkinter, and have written a small Tkinter class, and would > appreciate the useful criticism of those more learned than myself. Anything > about style, efficiency, idioms, etc... that you think would improve the > code would be most welcome. Just two comments. A widget should not pack itself as your Palette does. That should be the application's choice. If there are some "adjustments" you want, then override the method to modify the parameters. The colorInfo widget gets passed a StringVar instance, but the default is a (empty) string. The system might get a little confused: Tk (under Tkinter) uses the name of the variable, the default string could be taken without an error, but lead to some odd problems. You probably want to test before using the value and if not value, then possibly raise an exception or create a new variable. Other than that, it looks pretty good. -Arcege > from Tkinter import * > > colorVals = [ '00', '33', '66', '99', 'CC', 'FF' ] > > class Palette(Frame): > def __init__(self, parent=None): > Frame.__init__(self, parent) > for item in colorVals: > for tuple in [('00', '33', '66'), ('99', 'CC', 'FF')]: > PlaqueRow(self, item, tuple).pack() > self.pack() XXXXXXXXXXX # allow application to pack > self.colortext=StringVar() > self.info = colorInfo(self, self.colortext) > self.info.pack(side=LEFT) > self.colortext.set("") > self.bind_all('', self.displayColor) > class colorInfo(Frame): > def __init__(self, parent=None, text=""): > Frame.__init__(self, parent, height=25, width=200) > Label(self, text="click on a color", font=("bold", 12)).pack() > self.colorDisplay = Label(self, width=6, height = 1, bg='#FFFFFF') > self.colorDisplay.pack(side=LEFT) if text == "": raise ValueError("text must be StringVar instance") > colorValue = Entry(self, width=10, textvariable = text) > colorValue.pack(side=LEFT) -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From ppathiyi@cisco.com Tue Jul 10 14:30:39 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Tue, 10 Jul 2001 19:00:39 +0530 Subject: [Tutor] Order of functions Message-ID: <025301c10944$8ce860b0$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_0250_01C10972.9C888940 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, Is the order of functions important in python ? Suppose that i have a class X. If i have functions a, b,c and if = 'a' calls 'b', is it necessaruy to define 'b' before 'a' or before 'b' = is being called. =20 Praveen. ------=_NextPart_000_0250_01C10972.9C888940 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
 
        Is the order of functions = important=20 in python ?
        Suppose that i have a class = X. If i=20 have functions a, b,c and if 'a' calls 'b', is it necessaruy to define = 'b'=20 before 'a' or before 'b' is being called.
       
Praveen.
------=_NextPart_000_0250_01C10972.9C888940-- From rob@jam.rr.com Tue Jul 10 14:53:50 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 10 Jul 2001 08:53:50 -0500 Subject: [Tutor] Order of functions In-Reply-To: <025301c10944$8ce860b0$37ef87c0@ppathiyipc> Message-ID: # This is addsem.py addsem() def addsem(): total=2+2 print total # When run from the command line (DOS prompt for some), the following is returned: D:\Python21>python addsem.py Traceback (most recent call last): File "addsem.py", line 1, in ? addsem() NameError: name 'addsem' is not defined # This is addem.py def addem(): total=2+2 print total addem() #This is the more desirable output generated: D:\Python21>python addem.py 4 You asked specifically about classes, so this might not answer your question. But in these non-class-oriented scripts, the function must be defined before calling it. Rob Useless Python: Aw, heck, we love you! http://www.lowerstandard.com/python/ -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Praveen Pathiyil Sent: Tuesday, July 10, 2001 8:31 AM To: tutor@python.org Subject: [Tutor] Order of functions Hi, Is the order of functions important in python ? Suppose that i have a class X. If i have functions a, b,c and if 'a' calls 'b', is it necessaruy to define 'b' before 'a' or before 'b' is being called. Praveen. From arcege@speakeasy.net Tue Jul 10 15:06:26 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 10 Jul 2001 10:06:26 -0400 (EDT) Subject: [Tutor] Order of functions In-Reply-To: <025301c10944$8ce860b0$37ef87c0@ppathiyipc> from "Praveen Pathiyil" at Jul 10, 2001 07:00:39 PM Message-ID: <200107101406.f6AE6Qe02276@dsl092-074-184.bos1.dsl.speakeasy.net> Praveen Pathiyil wrote > Is the order of functions important in python ? > Suppose that i have a class X. If i have functions a, b,c and if = > 'a' calls 'b', is it necessaruy to define 'b' before 'a' or before 'b' = > is being called. The only requirement is that the function (or class) needs to be defined before it is called. So: class Eggs: f = Toast() # Toast is not defined yet but is trying to be called def __init__(self): pass def Toast(): pass would fail when defining the class since func1 is not defined before it is called. But: def Spam(): f = Ham() # does not get executed until Spam is called def Ham(): pass Spam() # Ham is now defined Would have no problem since Spam would still be defined but the code is not called. There is a similar problem with modules: ----- mod1.py ----- import mod2 # import mod2 before funct1 has been defined def funct1(): pass ------------------- ----- mod2.py ----- import mod1 # import mod1 and trying to call funct1, but it isn't defined print dir(mod1) # won't show funct1 mod1.funct1() ------------------- Here, the problem is that import happens before the function definition. It is not a requirement to put functions into a proper order, but it is a VERY good idea to. The order I would suggest is: more complicated functions go last, functions and classes that use fewer other callables earlier. There can always be fun exceptions tho. ;) Hope I'm coherent enough today. :/ -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From britt_green@hotmail.com Tue Jul 10 15:37:07 2001 From: britt_green@hotmail.com (Britt Green) Date: Tue, 10 Jul 2001 07:37:07 -0700 Subject: [Tutor] Re: Threading a Class? Message-ID: >import threading > >mythread = threading.Thread(target=myTime.updateTime) >mythread.start() > >Now mythread is running the updateTime function, and your program continues >in the main thread. Is there a way to make the GameTimer class itself threaded? I've seen some examples that look a bit like this: class GameTimer(threading.Thread): def__init__(self): threading.Thread.__init__(self) def run (self): #stuff here But I'm a little unsure of exactly how to do this. Is there an advantage to one over the other? Britt -- It is pitch black. You are likely to be eaten by a grue. _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From Sheila King Tue Jul 10 16:04:30 2001 From: Sheila King (Sheila King ) Date: Tue, 10 Jul 2001 08:04:30 -0700 Subject: [Tutor] Tkinter class defn questions In-Reply-To: <200107100146.UAA34326250@smtppop3pub.verizon.net> References: <89BF41D2CF9@kserver.org> <200107100146.UAA34326250@smtppop3pub.verizon.net> Message-ID: <200107101504.KAA138740951@smtppop1pub.verizon.net> OK, one more thing that I thought of last night, I want to add here, to make this topic "more complete", in case someone searches on it later. See below... On Mon, 09 Jul 2001 18:46:38 -0700, notme@gte.net wrote about Re: [Tutor] Tkinter class defn questions: :On Sat, 07 Jul 2001 15:36:43 -0700, Sheila King :wrote about [Tutor] Tkinter class defn questions: : :: ::Here is an example from the book: [snipped] ::class Quitter(Frame): # subclass our GUI :: def __init__(self, parent=None): # constructor method :: Frame.__init__(self, parent) :: self.pack() :: widget = Button(self, text='Quit', command=self.quit) :: widget.pack(expand=YES, fill=BOTH, side=LEFT) :: def quit(self): :: ans = askokcancel('Verify exit', "Really quit?") :: if ans: Frame.quit(self) ::OK, I'm going to say what I think the code does, and then someone please ::correct me, if I am wrong. : :OK, here is something I didn't realize at the time I sent my previous :message on this topic. However, I did some additional reading on Classes :in Core Python Programming and NOW I SEE that... : :class NewClass(OtherClass): : class-suite : :Is how you derive a New Class from some Other Class. Another remark about the subclassing and how it works... Since the Quitter class is a subclass of the Tkinter Frame class, if you do no write a __init__ function for the Quitter class, it will simply use the Frame class' __init__ function. However, and here's the big thing, if you DO write an __init__ function for the Quitter class, that __init__ function will override and replace the __init__ function of the Tkinter Frame class. So, what if you want to take advantage of the __init__ function from the Frame class, but embellish it a little and add to it??? In that case, you have to declare the new __init__ function for the Quitter class, but since this overrides the Frame's __init__, if you still want to use it, you must call it explicitly. That's why the statement Frame.__init__(self, parent) is in the Quitter class __init__ function. (I hope I explained this well enough...) -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dsh8290@rit.edu Tue Jul 10 16:34:18 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 10 Jul 2001 11:34:18 -0400 Subject: [Tutor] executing Python programs in windows In-Reply-To: ; from clanoftheinsane@hotmail.com on Mon, Jul 09, 2001 at 10:48:28PM -0400 References: Message-ID: <20010710113418.B5592@harmony.cs.rit.edu> On Mon, Jul 09, 2001 at 10:48:28PM -0400, Paul Brown wrote: | | hello, | | i know that in Linux, you can do the chmod function to allow the user | to be able to execute a python program from any directory in the | system. for example, if python was installed in the /home/python | directory, you could still execute a python script even if you are in | /home/myfiles directory (just an example) in the terminal. is there | any way to do this in Windows? thanks Windows doesn't have any permissions on files. It will let you execute any darn file you want (more or less -- sometimes the default action is to open it in a viewer of some sort). As long as .py files are associated with python.exe, you can simply double-click it to run it. -D From dsh8290@rit.edu Tue Jul 10 16:54:27 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 10 Jul 2001 11:54:27 -0400 Subject: [Tutor] Order of functions In-Reply-To: <025301c10944$8ce860b0$37ef87c0@ppathiyipc>; from ppathiyi@cisco.com on Tue, Jul 10, 2001 at 07:00:39PM +0530 References: <025301c10944$8ce860b0$37ef87c0@ppathiyipc> Message-ID: <20010710115427.A5644@harmony.cs.rit.edu> On Tue, Jul 10, 2001 at 07:00:39PM +0530, Praveen Pathiyil wrote: | Hi, | | Is the order of functions important in python ? | Suppose that i have a class X. If i have functions a, b,c | and if 'a' calls 'b', is it necessaruy to define 'b' before | 'a' or before 'b' is being called. Regardless of your programming environment, any function/class/module/whatever must be defined before it can be used. In some environments, such as C C++ and Java, the compiler looks at all the source and generates all the machine code so the order of the text in a source file is irrelevant -- the compiler defines all functions before the program is run. In Python, because it executes the code while it is "compiling" it (creating the function objects -- I'm trying to use the same terminology as with the other environments) so it must have the definition of some function before it is called. The result : if you have a class that defines several methods, and those methods call each other, it doesn't matter what order the methods are in the source code because they won't be executed until after an instance had been created, which can't happen until the class object is created which includes creating all the method objects. I know this sounds a bit confusing, but if you trace through what the interpreter does as it executes your code you will see what needs to be done first and what needs to be done later. HTH, -D From Daniel.Kinnaer@Advalvas.be Tue Jul 10 17:08:26 2001 From: Daniel.Kinnaer@Advalvas.be (Daniel Kinnaer) Date: Tue, 10 Jul 2001 18:08:26 +0200 Subject: [Tutor] string format preceeded with letter 'r' In-Reply-To: Message-ID: Hello All. I've been working on a module (Python 2.1) to read from and write to the Windows Registry. In the _winreg module there is a procedure called OpenKey. >> OpenKey(key, sub_key[, res = 0][, sam = KEY_READ]) This procedure in fact opens the specified key and returns a handle object. Sub_key is a string that identifies the sub_key to open. Now here's the question: aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") ---------------------^ Why do we need to write an 'r' in front of sub_key? I've been doing some tests and it also works without this 'r' in front of the sub_key.. Now why is that? What is the purpose of this 'r' anyway? Can it be something else as well? Hope to read you soon. Best regards, Daniel From dsh8290@rit.edu Tue Jul 10 17:14:40 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 10 Jul 2001 12:14:40 -0400 Subject: [Tutor] string format preceeded with letter 'r' In-Reply-To: ; from Daniel.Kinnaer@Advalvas.be on Tue, Jul 10, 2001 at 06:08:26PM +0200 References: Message-ID: <20010710121440.A5704@harmony.cs.rit.edu> On Tue, Jul 10, 2001 at 06:08:26PM +0200, Daniel Kinnaer wrote: | Now here's the question: | | aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") | ---------------------^ | | Why do we need to write an 'r' in front of sub_key? I've been doing some | tests and it also works without this 'r' in front of the sub_key.. Now why | is that? What is the purpose of this 'r' anyway? Can it be something else as | well? The r means that you have a "raw" string. If it worked without the r in your tests, then you were lucky, or not, because you didn't test the certain cases where it will fail. Try something like the following : >>> print r"T\tE\nS\rT" T\tE\nS\rT >>> print "T\tE\nS\rT" T E T >>> The backslash '\' is used as an escape character. Some escape sequences have an actual meaning, and they are substituted. If the escape sequence is meaningless the backslash stays in the string. In my example, \t means tab, \n means newline and \r means carriage return (what happened above was the S was printed, then the "carriage" was returned to the beginning of the line and the T was printed causing the S to no longer be seen -- think of a typewriter). To include a '\' in a string you either need to use raw strings, as you have above, or escape each backslash. ie "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" HTH, -D From bill-bell@bill-bell.hamilton.on.ca Tue Jul 10 18:51:27 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Tue, 10 Jul 2001 13:51:27 -0400 Subject: [Tutor] Re: Number Conversion routines In-Reply-To: Message-ID: <3B4B085F.28957.35E9187@localhost> "Praveen Pathiyil" wrote, in part: > Is there any module or built-in routines which does conversion > between different represenations of numbers ? I mean binary-to-hex, > hex-to-binary, binary-to decimal etc. See "2.1.5.2 String Formatting Operations" in the Python library reference. I don't know of built-in ways of processing binary. Easiest way I can think of would be to convert to or from octal. From kp87@lycos.com Tue Jul 10 22:21:23 2001 From: kp87@lycos.com (kevin parks) Date: Wed, 11 Jul 2001 06:21:23 +0900 Subject: [Tutor] Mac to UNIX and back again (what to do about path) Message-ID: I have some scripts that i want to be able to run on both Mac OS 9 and under UNIX (the UNIX distribution on Mac OS X). I've managed to get the line endings thing somewhat under control with a little drag an drop changer app, but i don't know what to do about the path separator. On Mac it is (as you know ':' and UNIX is '/'. I'd really like to have one script that works on both. cheers, kevin parks seoul, korea kp87@lycos.com Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From sheila@thinkspot.net Tue Jul 10 22:47:16 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 10 Jul 2001 14:47:16 -0700 Subject: [Tutor] Mac to UNIX and back again (what to do about path) In-Reply-To: References: Message-ID: <6BFA1C42DFB@kserver.org> On Wed, 11 Jul 2001 06:21:23 +0900, "kevin parks" wrote about [Tutor] Mac to UNIX and back again (what to do about path): :I have some scripts that i want to be able to run on both Mac OS 9 and under UNIX (the UNIX distribution on Mac OS X). I've managed to get the line endings thing somewhat under control with a little drag an drop changer app, but i don't know what to do about the path separator. On Mac it is (as you know ':' and UNIX is '/'. I'd really like to have one script that works on both. Try looking at the os module and its submodules (such as os.path). http://www.python.org/doc/current/lib/module-os.html Notice that os.sep is the path separator for the system on which the script is currently running. Also, there are commands for joining paths with file names correctly and so on in this module. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From wesc@deirdre.org Tue Jul 10 23:32:52 2001 From: wesc@deirdre.org (Wesley Chun) Date: Tue, 10 Jul 2001 15:32:52 -0700 (PDT) Subject: [Tutor] Order of functions In-Reply-To: <025301c10944$8ce860b0$37ef87c0@ppathiyipc> Message-ID: On Tue, 10 Jul 2001, Praveen Pathiyil wrote: > Is the order of functions important in python ? > Suppose that i have a class X. If i have functions a, b,c and if 'a' calls 'b', is it necessaruy to define 'b' before 'a' or before 'b' is being called. yes, the order of function invocations vs. declarations/definitions is important. functions which have not been declared/defined cannot be invoked. - - - - - - - foo() def foo(): pass FAILS because foo() was called b4 it was def'd. - - - - - - - def bar(): foo() bar() def foo(): pass FAILS: reason is the same as above; bar() is okay because it was def'd b4 it was called - - - - - - - def bar(): foo() def foo(): pass bar() WORKS: because both functions are def'd b4 invocation - - - - - - - def foo(): pass def bar(): foo() bar() WORKS: same as above, but look even more convincing because foo() is def'd b4 it shows up anywhere else! - - - - - - if you have Core Python Programming, this topic can be found in section 11.3.3 (Forward References) on pp. 340-41. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From wesc@deirdre.org Wed Jul 11 00:03:07 2001 From: wesc@deirdre.org (Wesley Chun) Date: Tue, 10 Jul 2001 16:03:07 -0700 (PDT) Subject: [Tutor] Mac to UNIX and back again (what to do about path) In-Reply-To: Message-ID: On Wed, 11 Jul 2001, kevin parks wrote: > I have some scripts that i want to be able to run on both Mac OS 9 and > under UNIX (the UNIX distribution on Mac OS X). I've managed to get > the line endings thing somewhat under control with a little drag an > drop changer app, but i don't know what to do about the path > separator. On Mac it is (as you know ':' and UNIX is '/'. I'd really > like to have one script that works on both. Kevin, You have such a well-known and commonly-occurring problem that all of it has been taken care of by Python's OS module... you don't even need ':' or '/' in any of your code anymore(!) nor do you need os.platform for it as ugly and messy as John indicated in his reply. The os module has the following 5 file system (string) attributes for you and anyone else with porting issues to contend with: Attribute Description --------- ----------- linesep string used to separate lines in a file sep string used to separate file pathname components pathsep string used to delimit a set of file pathnames curdir string name for current working directory pardir string name for parent (of current working dir) If you just "import os" in your script, no matter what platform that script is running on, the corect string values will be available in these attributes, i.e., on UNIX, os.sep == '/' and on the Mac, os.sep == ':', and on Windoze, os.sep == '\\'. In John's reply, he indicated an intelligent way to join pathnames into a singleproperly-delimited string like this: >>path=os.path.join("myfolder", "mysubfolder", "myfile") I think that he meant using os.sep and a sequence instead: path=os.sep.join(["myfolder", "mysubfolder", "myfile"]) So no matter who is running this line of code, the "right" thing will be done... on the Mac, it'll turn into: path = ':'.join(["myfolder", "mysubfolder", "myfile"]) (and '/'.join() for UNIX and '\\'.join() for Win) Here's an example for Windoze: >>> os.sep.join(['C:', 'a', 'b', 'c']) 'C:\\a\\b\\c' If you happen to have Core Python Programming, this topic is discussed in detail in the Core Note on p. 263 in section 9.3.5. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From wesc@deirdre.org Wed Jul 11 00:10:46 2001 From: wesc@deirdre.org (Wesley Chun) Date: Tue, 10 Jul 2001 16:10:46 -0700 (PDT) Subject: [Tutor] Typos and attitudes on language In-Reply-To: Message-ID: what an interesting thought!!! i am paranoid about misspellings and cannot stand looking at a misspelled word. my spouse frowns upon my correcting her spelling, and i always thought it was just me, but you may have a Psych disseration here! :-) -wesley On Mon, 9 Jul 2001, Danny Yoo wrote: > On Mon, 9 Jul 2001, Paul De Luca wrote: > > > Yeah, it was just a typo I made when writing the email. I realized it > > after I send the email. I Was hoping nobody would notice, but I guess > > thats hard considering every single person subscribed to this list is a > > programmer. Poor spelling/grammar never seems to go down well with the > > open source community. ;) > > Not just open source communities: I've noticed that there's an overall > trend of those who have experience with computer languages becoming a > little more careful with their spelling and grammar. From deirdre@deirdre.net Wed Jul 11 03:44:34 2001 From: deirdre@deirdre.net (Deirdre Saoirse Moen) Date: Tue, 10 Jul 2001 19:44:34 -0700 Subject: [Tutor] Mac to UNIX and back again (what to do about path) In-Reply-To: References: Message-ID: At 4:03 PM -0700 7/10/01, Wesley Chun wrote: >path = ':'.join(["myfolder", "mysubfolder", "myfile"]) > >(and '/'.join() for UNIX and '\\'.join() for Win) > >Here's an example for Windoze: > >>>> os.sep.join(['C:', 'a', 'b', 'c']) >'C:\\a\\b\\c' Note that on MacOS X you'll get the Unix separator and not the "Mac" one. -- _Deirdre Stash-o-Matic: http://weirdre.com http://deirdre.net "Cannot run out of time.... Is infinite time. You... are finite.... Zathrus... is finite. This... is wrong tool!" -- Zathrus From joejava@dragoncat.net Wed Jul 11 04:27:42 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Tue, 10 Jul 2001 23:27:42 -0400 Subject: [Tutor] please help me on this small project of mine References: <20010710111329.87626.qmail@web13908.mail.yahoo.com> Message-ID: <008201c109b9$73475920$2ca2d6d1@joeltklrijxxms> > i have already started with the script on how > to compute for time spent by the client and how much > was the charge for that time. what i want is have a > GUI for that and can disable a certain workstation > (like its keyboard) from the server. I might have a few ideas of where to start first of all we all would need to know what sort of hardware and software are using to network your workstations? Linux, Windows NT or 2000, or something else? Joel From joejava@dragoncat.net Wed Jul 11 05:21:55 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Wed, 11 Jul 2001 00:21:55 -0400 Subject: [Tutor] Typos and attitudes on language References: Message-ID: <00d501c109c1$05a93d40$2ca2d6d1@joeltklrijxxms> > Perhaps part of it is because programmers might be developing a stronger > sensitivity for syntax, even in the "artificial" form of a computer > language. Personally, I've felt that programming isn't always "mathy", > but on the other hand, is consistently "verbal" because of the effort of > organizing and expressing ideas. > > It might be something that a sociologist could write an essay about... > *grin* Of course there are those like me who in their haste to whip out thoughts and ideas, make some pretty bad mistakes in spelling and grammar. I've looked at some of my posts sometimes and cringe in horror at what I previously wrote. I've tried to be a bit more concious of what I write now so that people don't misunderstand me or think that my thoughts are a little less important than others. Which brings to mind another reason: Showing mastery of rhetoric and being and to communicate clearly helps to add credibility to what we do write. I would hate to be thought of as "that guy" who couldn't put a sentence together to save his live, making my thoughts on Python code and issues less than others. Guess its time to brush the dust of my "Elements of Style" guide and read it again :) Joel From pdeluca@sia.net.au Wed Jul 11 06:34:58 2001 From: pdeluca@sia.net.au (Paul De Luca) Date: Wed, 11 Jul 2001 15:34:58 +1000 (EST) Subject: [Tutor] Typos and attitudes on language In-Reply-To: Message-ID: Yeah, You should read the posts on slashdot. If you argue a point be sure that the spelling/grammar is perfect otherwise your argument will have its "legs cut off". ESR's hacker howto makes the following remarks: http://www.tuxedo.org/~esr/faqs/hacker-howto.html "Learn to write your native language well. Though it's a common stereotype that programmers can't write, a surprising number of hackers (including all the best ones I know of) are able writers." "Finally, a few things not to do. Don't use a silly, grandiose user ID or screen name. Don't get in flame wars on Usenet (or anywhere else). Don't call yourself a `cyberpunk', and don't waste your time on anybody who does. Don't post or email writing that's full of spelling errors and bad grammar. The only reputation you'll make doing any of these things is as a twit. Hackers have long memories -- it could take you years to live your early blunders down enough to be accepted." > what an interesting thought!!! > > i am paranoid about misspellings and cannot stand looking at > a misspelled word. my spouse frowns upon my correcting her > spelling, and i always thought it was just me, but you may > have a Psych disseration here! :-) > > -wesley > ------------------------- Paul De Luca Email: pdeluca@sia.net.au Ph: 0414 225 561 ------------------------- From ppathiyi@cisco.com Wed Jul 11 10:52:49 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 11 Jul 2001 15:22:49 +0530 Subject: [Tutor] Killing a thread .. Message-ID: <039501c109ef$3f088040$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_0392_01C10A1D.586CA8D0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi All, I wanted some help on killing a thread. The scenario is something like = this -- I have a main function which is executed in the main thread. (This is = actually a GUI). The actual back-end, is started in a thread spawned = from the main thread. Now i want to kill the spawned thread from the = main thread. How can i acheive that ? (The back-end is a protocol simulator. When the user presses "stop" of = the GUI, i wanted to kill the thread which is used for running the = simulator). Thanks in advance, Praveen. ------=_NextPart_000_0392_01C10A1D.586CA8D0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi All,
 
I wanted some help on killing a thread. The scenario is something = like this=20 --
 
I have a main function which is executed in the main thread. (This = is=20 actually a GUI). The actual back-end, is started in a thread spawned = from the=20 main thread. Now i want to kill the spawned thread from the main thread. = How can=20 i acheive that ?
 
(The back-end is a protocol simulator. When the user presses "stop" = of the=20 GUI, i wanted to kill the thread which is used for running the = simulator).
 
Thanks in advance,
Praveen.
------=_NextPart_000_0392_01C10A1D.586CA8D0-- From Mark.Tobin@attcanada.com Wed Jul 11 14:34:40 2001 From: Mark.Tobin@attcanada.com (Tobin, Mark) Date: Wed, 11 Jul 2001 07:34:40 -0600 Subject: [Tutor] Killing a thread .. Message-ID: <3D7C088D6CCFD31190A5009027D30E910339104B@torex004.attcanada.ca> I think Allan Crooks posted a great answer to this in reply to my question of a really similar nature (at least from my point of view they look similar) on Wednesday June 20 around 6:21pm (Eastern I think) under the subject RE: [TUTOR] Killing threads... I don't know how to post a link but I'm sure you can find it in the archives... Mark p.s.. it also has a few corrections of my code so bear with my problems while reading his answers... ;-) -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Praveen Pathiyil Sent: Wednesday, July 11, 2001 5:53 AM To: tutor@python.org Subject: [Tutor] Killing a thread .. Hi All, I wanted some help on killing a thread. The scenario is something like this -- I have a main function which is executed in the main thread. (This is actually a GUI). The actual back-end, is started in a thread spawned from the main thread. Now i want to kill the spawned thread from the main thread. How can i acheive that ? (The back-end is a protocol simulator. When the user presses "stop" of the GUI, i wanted to kill the thread which is used for running the simulator). Thanks in advance, Praveen. From ppathiyi@cisco.com Wed Jul 11 15:06:16 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 11 Jul 2001 19:36:16 +0530 Subject: [Tutor] Killing a thread .. References: <3D7C088D6CCFD31190A5009027D30E910339104B@torex004.attcanada.ca> Message-ID: <044f01c10a12$ac1faa50$37ef87c0@ppathiyipc> Hi Mark, Thanks for that pointer. I went through that mail you suggested. But there seemed to be a slight difference. In my case, the main thread waits for the user input( To press any of the buttons). The spawned thread is trying to simulate some real-time message processing. So it doesn't seem to be a good idea to ask that thread to check a condition variable periodically, because figuratively speaking it just want to continue processing and doesn't want to stop. It is the main thread, upon "user intervention", that will terminate this "eager-to-continue" thread. Also i can't make the spawned thread to sleep in-between for checking the variable. I hope that i have somewhat cleared the intent of my usage. Just on the same topic, if i am running the function using a thread object (rather just doing a "thread.start_new(func, (..))", will deleting that object achieve the effect of killing that thread ? I feel that there is something seriously wrong in this, but can someone tell me exactly what :-)) ? Thanks, Praveen. ----- Original Message ----- From: "Tobin, Mark" To: "'Praveen Pathiyil'" Cc: Sent: Wednesday, July 11, 2001 7:04 PM Subject: RE: [Tutor] Killing a thread .. > I think Allan Crooks posted a great answer to this in reply to my question > of a really similar nature (at least from my point of view they look > similar) on Wednesday June 20 around 6:21pm (Eastern I think) under the > subject RE: [TUTOR] Killing threads... I don't know how to post a link but > I'm sure you can find it in the archives... > > Mark > p.s.. it also has a few corrections of my code so bear with my problems > while reading his answers... ;-) > > -----Original Message----- > From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of > Praveen Pathiyil > Sent: Wednesday, July 11, 2001 5:53 AM > To: tutor@python.org > Subject: [Tutor] Killing a thread .. > > > Hi All, > > I wanted some help on killing a thread. The scenario is something like this > -- > > I have a main function which is executed in the main thread. (This is > actually a GUI). The actual back-end, is started in a thread spawned from > the main thread. Now i want to kill the spawned thread from the main thread. > How can i acheive that ? > > (The back-end is a protocol simulator. When the user presses "stop" of the > GUI, i wanted to kill the thread which is used for running the simulator). > > Thanks in advance, > Praveen. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ppathiyi@cisco.com Wed Jul 11 15:14:24 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Wed, 11 Jul 2001 19:44:24 +0530 Subject: [Tutor] Pass by reference Message-ID: <045801c10a13$c9b80020$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_0455_01C10A41.E3191B70 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, Can we do a "pass by reference" in python ? Ex: ( I would like to know whether there is a way to have the modified = ex_dict to be visible in modified form in func1 with out explicitly = returning that ) def func2(x, ex_dict): ex_dict[x] =3D x*x def func1(a): ex_dict =3D {} func2(a, ex_dict) func1(2) TIA, Praveen. ------=_NextPart_000_0455_01C10A41.E3191B70 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
 
Can we do a "pass by reference" in python ?
 
Ex:
 
( I would like to know whether there is a way to have the modified = ex_dict=20 to be visible in modified form in func1 with out explicitly returning = that=20 )
 
def func2(x, ex_dict):
    ex_dict[x] =3D x*x
 
def func1(a):
    ex_dict =3D {}
    func2(a, ex_dict)
 
func1(2)
 
TIA,
Praveen.
------=_NextPart_000_0455_01C10A41.E3191B70-- From wildchild07770@hotmail.com Wed Jul 11 16:33:05 2001 From: wildchild07770@hotmail.com (AVD) Date: Wed, 11 Jul 2001 10:33:05 -0500 Subject: [Tutor] Linux and IDLE Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C109F4.DEC97760 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I recentley got my laptop up and running with red hat 7.0, i've been = using windows with IDLE to write in Python which I find is ALOT easier = than a simple text editor, I have Core Python Programming that has a = supplement CD with IDLE on it and I can't seem to get it to run, I = pulled it out of the tarball and onto the hard drive but when I go to = run it I get syntax errors from trying to run it, i've updated Tcl/Tk = and Python to version 2.0, any help is appreciated. Thanks, Aaron ------=_NextPart_000_0007_01C109F4.DEC97760 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I recentley got my laptop up and = running with red=20 hat 7.0, i've been using windows with IDLE to write in Python which = I find=20 is ALOT easier than a simple text editor, I have Core Python Programming = that=20 has a supplement CD with IDLE on it and I can't seem to get it to run, I = pulled=20 it out of the tarball and onto the hard drive but when I go to run it I = get=20 syntax errors from trying to run it, i've updated Tcl/Tk and Python to = version=20 2.0, any help is appreciated.
 
Thanks,
Aaron
------=_NextPart_000_0007_01C109F4.DEC97760-- From ium@micromuse.com Wed Jul 11 17:33:18 2001 From: ium@micromuse.com (ibraheem umaru-mohammed) Date: Wed, 11 Jul 2001 17:33:18 +0100 Subject: [Tutor] Pass by reference In-Reply-To: <045801c10a13$c9b80020$37ef87c0@ppathiyipc>; from ppathiyi@cisco.com on Wed, Jul 11, 2001 at 07:44:24PM +0530 References: <045801c10a13$c9b80020$37ef87c0@ppathiyipc> Message-ID: <20010711173318.G9876@micromuse.com> [Praveen Pathiyil wrote...] -| Can we do a "pass by reference" in python ? no. not directly. -| Ex: -| -| ( I would like to know whether there is a way to have the modified ex_dict to be visible in modified form in func1 with out explicitly returning that ) -| -| def func2(x, ex_dict): -| ex_dict[x] = x*x -| -| def func1(a): -| ex_dict = {} -| func2(a, ex_dict) -| -| func1(2) -| You can do this in at least two ways: o using a class o using global dictionary variable Here is one way of achieving similar functionality using classes: ibraheem@ignoramus:$ python Python 2.1 (#1, Apr 20 2001, 17:50:32) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> class A: ... def __init__(self): ... self.ex_dict={} ... def func2(self,x): ... self.ex_dict[x]=x*x ... def func1(self,a): ... self.func2(a) ... def print_items(self): ... for i in self.ex_dict.items(): ... print i ... >>> test = A() >>> test.func1(2) >>> test.print_items() (2, 4) >>> test.func1(3) >>> test.print_items() (3, 9) (2, 4) >>> Hope that helps a little. Kindest regards, --ibs -- A sad spectacle. If they be inhabited, what a scope for misery and folly. If they be not inhabited, what a waste of space. -- Thomas Carlyle, looking at the stars From scarblac@pino.selwerd.nl Wed Jul 11 16:44:33 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 11 Jul 2001 17:44:33 +0200 Subject: [Tutor] Killing a thread .. In-Reply-To: <044f01c10a12$ac1faa50$37ef87c0@ppathiyipc>; from ppathiyi@cisco.com on Wed, Jul 11, 2001 at 07:36:16PM +0530 References: <3D7C088D6CCFD31190A5009027D30E910339104B@torex004.attcanada.ca> <044f01c10a12$ac1faa50$37ef87c0@ppathiyipc> Message-ID: <20010711174432.A19149@pino.selwerd.nl> On 0, Praveen Pathiyil wrote: > Thanks for that pointer. I went through that mail you suggested. But there > seemed to be a slight difference. > > In my case, the main thread waits for the user input( To press any of the > buttons). The spawned thread is trying to simulate some real-time message > processing. So it doesn't seem to be a good idea to ask that thread to check > a condition variable periodically, because figuratively speaking it just > want to continue processing and doesn't want to stop. It is the main thread, > upon "user intervention", that will terminate this "eager-to-continue" > thread. As far as I know, that is simply not the way it works. You can't stop a thread, but the thread can end. It's not that expensive to check a variable now and then. (I might be wrong on this, but I think I've heard this quite often). > Also i can't make the spawned thread to sleep in-between for checking the > variable. > > I hope that i have somewhat cleared the intent of my usage. > > Just on the same topic, if i am running the function using a thread object > (rather just doing a "thread.start_new(func, (..))", will deleting that > object achieve the effect of killing that thread ? I feel that there is > something seriously wrong in this, but can someone tell me exactly what :-)) > ? How would you delete an object? "del ob" will delete the local name 'ob' that refers to that object, but as long as something else refers to it, the object will be there (and as long as it's a running thread, there will be things referring to it). -- Remco Gerlich From ium@micromuse.com Wed Jul 11 18:42:08 2001 From: ium@micromuse.com (ibraheem umaru-mohammed) Date: Wed, 11 Jul 2001 18:42:08 +0100 Subject: [Tutor] Pass by reference In-Reply-To: <20010711173318.G9876@micromuse.com>; from ium@micromuse.com on Wed, Jul 11, 2001 at 05:33:18PM +0100 References: <045801c10a13$c9b80020$37ef87c0@ppathiyipc> <20010711173318.G9876@micromuse.com> Message-ID: <20010711184208.H9876@micromuse.com> [ibraheem umaru-mohammed wrote...] -| [Praveen Pathiyil wrote...] -| -| Can we do a "pass by reference" in python ? -| -| no. not directly. -| -| -| Ex: -| -| -| -| ( I would like to know whether there is a way to have the modified ex_dict to be visible in modified form in func1 with out explicitly returning that ) -| -| -| -| def func2(x, ex_dict): -| -| ex_dict[x] = x*x -| -| -| -| def func1(a): -| -| ex_dict = {} -| -| func2(a, ex_dict) -| -| -| -| func1(2) -| -| -| -| You can do this in at least two ways: -| o using a class -| o using global dictionary variable -| This is actually in the FAQ - so here is the answer in full ;) 4.35. How do I write a function with output parameters (call by reference)? [Mark Lutz] The thing to remember is that arguments are passed by assignment in Python. Since assignment just creates references to objects, there's no alias between an argument name in the caller and callee, and so no call-by-reference per se. But you can simulate it in a number of ways: 1) By using global variables; but you probably shouldn't :-) 2) By passing a mutable (changeable in-place) object: def func1(a): a[0] = 'new-value' # 'a' references a mutable list a[1] = a[1] + 1 # changes a shared object args = ['old-value', 99] func1(args) print args[0], args[1] # output: new-value 100 3) By returning a tuple, holding the final values of arguments: def func2(a, b): a = 'new-value' # a and b are local names b = b + 1 # assigned to new objects return a, b # return new values x, y = 'old-value', 99 x, y = func2(x, y) print x, y # output: new-value 100 4) And other ideas that fall-out from Python's object model. For instance, it might be clearer to pass in a mutable dictionary: def func3(args): args['a'] = 'new-value' # args is a mutable dictionary args['b'] = args['b'] + 1 # change it in-place args = {'a':' old-value', 'b': 99} func3(args) print args['a'], args['b'] 5) Or bundle-up values in a class instance: class callByRef: def __init__(self, **args): for (key, value) in args.items(): setattr(self, key, value) def func4(args): args.a = 'new-value' # args is a mutable callByRef args.b = args.b + 1 # change object in-place args = callByRef(a='old-value', b=99) func4(args) print args.a, args.b But there's probably no good reason to get this complicated :-). [Python's author favors solution 3 in most cases.] Kindest regards, --ibs. -- Do not take life too seriously; you will never get out of it alive. From dsh8290@rit.edu Wed Jul 11 17:57:56 2001 From: dsh8290@rit.edu (D-Man) Date: Wed, 11 Jul 2001 12:57:56 -0400 Subject: [Tutor] Pass by reference In-Reply-To: <045801c10a13$c9b80020$37ef87c0@ppathiyipc>; from ppathiyi@cisco.com on Wed, Jul 11, 2001 at 07:44:24PM +0530 References: <045801c10a13$c9b80020$37ef87c0@ppathiyipc> Message-ID: <20010711125756.A6599@harmony.cs.rit.edu> On Wed, Jul 11, 2001 at 07:44:24PM +0530, Praveen Pathiyil wrote: | Hi, | | Can we do a "pass by reference" in python ? Sort of -- Python always does call-by-value, but the value is always a reference to an object on the heap. If you assign to the argument, then, no that won't be seen by the caller (just like C, C++ and Java). If, instead, the reference refers to a mutable object and you modify that object then you have the same effect (this is like using pointers in C/C++ or a reference to a mutable object in Java). Don't get bogged down in the implementation details and terminology though (there can be huge flamewars as to what "pass-by-value" and "pass-by-reference" really mean). | Ex: | | ( I would like to know whether there is a way to have the modified | ex_dict to be visible in modified form in func1 with out explicitly | returning that ) | | def func2(x, ex_dict): | ex_dict[x] = x*x | | def func1(a): | ex_dict = {} | func2(a, ex_dict) | | func1(2) Lets try it : >>> def func( x , ex_dict ) : ex_dict[x] = x*x ... >>> ex_dict = {} >>> func( 2 , ex_dict ) >>> print ex_dict {2: 4} >>> It works for dictionaries because you didn't modify the reference but instead modified the referred-to object on the heap. If you try and do it with, say, integers it won't work because you can't modify the integer object on the heap : >>> def badfunc( i ) : ... i = i * i ... print "in badfunc, i = %d" % i ... >>> a = 5 >>> badfunc( a ) in badfunc, i = 25 >>> print a 5 >>> -D From wesc@deirdre.org Wed Jul 11 17:57:15 2001 From: wesc@deirdre.org (Wesley Chun) Date: Wed, 11 Jul 2001 09:57:15 -0700 (PDT) Subject: [Tutor] Pass by reference In-Reply-To: <045801c10a13$c9b80020$37ef87c0@ppathiyipc> Message-ID: On Wed, 11 Jul 2001, Praveen Pathiyil wrote: > > Can we do a "pass by reference" in python ? > > ( I would like to know whether there is a way to have the modified > ex_dict to be visible in modified form in func1 with out explicitly > returning that ) > > def func2(x, ex_dict): > ex_dict[x] = x*x > > def func1(a): > ex_dict = {} > func2(a, ex_dict) > > func1(2) In addition to ibraheem's 2nd message from the FAQ and a slight correction to his 1st, you should just be aware that *all* Python's calls are by reference. In other words, the objects you pass in to any function are the real deal (i.e., an additional reference is created "pointing" to that object), and any modification to that object in the function call will result in the "original" being changed, as it does in your example *without* returning it: >>> def func2(x, ex_dict): ex_dict[x] = x*x >>> def func1(a): dummyd = {} func2(a, dummyd) print `dummyd` >>> func1(2) {2: 4} >>> Note that the dictionary would've been empty if this wasn't the case. I even changed the name of the dictionary to "dummyd" in func1() to make sure that people do not get confused between the ex_dict in func2() which is a totally different variable and to show that it isn't a global variable, which should always be avoided whenever possible. Hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From kp87@lycos.com Wed Jul 11 20:56:49 2001 From: kp87@lycos.com (kevin parks) Date: Thu, 12 Jul 2001 04:56:49 +0900 Subject: [Tutor] file I/O Message-ID: Hi. I am a little confused as to why this hangs when i run it. I am trying to make a script that opens a file for input opens a file for writing and reads in a line from the input and copies it to the created output file. In this case except for the start here and EOF lines the file should be an exact copy. (the point is that later i an going to do something to each line of text), but i have to get this much working, plus the other business i mentioned on UNIX and Mac paths, but first this, Why does it just hang the interpreter? This is in Mac OS 9.bloat Python 2.1 IDE def finout(): infilename = raw_input('Enter in file name: ') infile = open(infilename, 'r') f = open('sys:scripts:foo.txt', 'w') f.write("start here\n\n") done = 0 while not done: aLine = infile.readline() if aLine != " ": f.write(aLine + '\n') else: done = 1 infile.close() f.write("\n\nEOF\n") f.close() if __name__ == '__main__': finout() Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From arcege@speakeasy.net Wed Jul 11 21:31:16 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 11 Jul 2001 16:31:16 -0400 (EDT) Subject: [Tutor] file I/O In-Reply-To: from "kevin parks" at Jul 12, 2001 04:56:49 AM Message-ID: <200107112031.f6BKVGV05826@dsl092-074-184.bos1.dsl.speakeasy.net> kevin parks wrote > > Hi. I am a little confused as to why this hangs when i run it. I am trying to Off hand, I would say it is the end condition. The readline method returns an empty string (false) when the end of file is reached, not a string with a space. > done = 0 > while not done: > aLine = infile.readline() > if aLine != " ": if aLine != "": # not at EOF, so write out > f.write(aLine + '\n') > else: > done = 1 Also, readline returns a whole line of text, including the newline. You probably do not need to append an additional newline. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From Craig.Massey@oxygenforbusiness.com Wed Jul 11 21:35:39 2001 From: Craig.Massey@oxygenforbusiness.com (Massey, Craig) Date: Thu, 12 Jul 2001 08:35:39 +1200 Subject: [Tutor] file I/O Message-ID: <2408B6871730D511881100B0D0AB59AA013BCA@MFORTOK1> Is there a "standard" way of removing the newline, like chomp in Perl? -----Original Message----- From: Michael P. Reilly [mailto:arcege@dsl092-074-184.bos1.dsl.speakeasy.net] Sent: Thursday, July 12, 2001 8:31 AM To: kp87@lycos.com Cc: tutor@python.org Subject: Re: [Tutor] file I/O kevin parks wrote > > Hi. I am a little confused as to why this hangs when i run it. I am trying to Off hand, I would say it is the end condition. The readline method returns an empty string (false) when the end of file is reached, not a string with a space. > done = 0 > while not done: > aLine = infile.readline() > if aLine != " ": if aLine != "": # not at EOF, so write out > f.write(aLine + '\n') > else: > done = 1 Also, readline returns a whole line of text, including the newline. You probably do not need to append an additional newline. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor DISCLAIMER: This electronic message together with any attachments is confidential. If you are not the intended recipient, do not copy, disclose or use the contents in any way. Please also advise us by return e-mail that you have received the message and then please destroy. Carter Holt Harvey is not responsible for any changes made to this message and / or any attachments after sending by Carter Holt Harvey. We use virus scanning software but exclude all liability for viruses or anything similar in this email or any attachment. From webmindforever@organicmeat.net Wed Jul 11 21:49:41 2001 From: webmindforever@organicmeat.net (charlie derr) Date: Wed, 11 Jul 2001 16:49:41 -0400 Subject: [Tutor] file I/O In-Reply-To: Message-ID: Not sure. It seems to work fine in idle (2.1 on NT) if i remove the blank line you have on line 2. ~c +-----Original Message----- +From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of +kevin parks +Sent: Wednesday, July 11, 2001 3:57 PM +To: tutor@python.org +Subject: [Tutor] file I/O + + +Hi. I am a little confused as to why this hangs when i run it. I +am trying to make a script that opens a file for input opens a +file for writing and reads in a line from the input and copies it +to the created output file. In this case except for the start +here and EOF lines the file should be an exact copy. (the point is +that later i an going to do something to each line of text), but i +have to get this much working, plus the other business i mentioned +on UNIX and Mac paths, but first this, Why does it just hang the +interpreter? + +This is in Mac OS 9.bloat Python 2.1 IDE + + +def finout(): + + infilename = raw_input('Enter in file name: ') + infile = open(infilename, 'r') + f = open('sys:scripts:foo.txt', 'w') + f.write("start here\n\n") + done = 0 + while not done: + aLine = infile.readline() + if aLine != " ": + f.write(aLine + '\n') + else: + done = 1 + infile.close() + f.write("\n\nEOF\n") + f.close() + +if __name__ == '__main__': + finout() + + + + +Get 250 color business cards for FREE! +http://businesscards.lycos.com/vp/fastpath/ + +_______________________________________________ +Tutor maillist - Tutor@python.org +http://mail.python.org/mailman/listinfo/tutor + From ak@silmarill.org Wed Jul 11 21:45:32 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Wed, 11 Jul 2001 16:45:32 -0400 Subject: [Tutor] file I/O In-Reply-To: <"from kp87"@lycos.com> References: Message-ID: <20010711164532.A4631@sill.silmarill.org> On Thu, Jul 12, 2001 at 04:56:49AM +0900, kevin parks wrote: > Hi. I am a little confused as to why this hangs when i run it. I am trying to make a script that opens a file for input opens a file for writing and reads in a line from the input and copies it to the created output file. In this case except for the start here and EOF lines the file should be an exact copy. (the point is that later i an going to do something to each line of text), but i have to get this much working, plus the other business i mentioned on UNIX and Mac paths, but first this, Why does it just hang the interpreter? > > This is in Mac OS 9.bloat Python 2.1 IDE > > > def finout(): > > infilename = raw_input('Enter in file name: ') > infile = open(infilename, 'r') > f = open('sys:scripts:foo.txt', 'w') > f.write("start here\n\n") > done = 0 > while not done: > aLine = infile.readline() > if aLine != " ": if aLine: # clearer, and works :-) > f.write(aLine + '\n') > else: > done = 1 I usually do something like: while 1: l = infile.readline() if not l: break f.write(l) I think it's more straightforward and clear.. The reason people feel the need for 'done' variables and such is that in this idiom you have to create an infinite loop and then break out of it - that's two things that just don't feel right. break feels like something you'd do in case of an error.. afaik, this will be fixed in 2.2 that will provide a clean and clear idiom, and until then, the above idiom is the right choice, because everybody who feels uneasy about it first always gets over it and uses it, like I did. Everybody comes to realize it's lesser of two evils :-P. > infile.close() > f.write("\n\nEOF\n") I'm not sure this is needed, but I never used Mac. > f.close() Files will be closed anyway when program ends, by the way. > > if __name__ == '__main__': > finout() > > > > > Get 250 color business cards for FREE! > http://businesscards.lycos.com/vp/fastpath/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From ak@silmarill.org Wed Jul 11 21:47:33 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Wed, 11 Jul 2001 16:47:33 -0400 Subject: [Tutor] file I/O In-Reply-To: <"from Craig.Massey"@oxygenforbusiness.com> References: <2408B6871730D511881100B0D0AB59AA013BCA@MFORTOK1> Message-ID: <20010711164733.B4631@sill.silmarill.org> On Thu, Jul 12, 2001 at 08:35:39AM +1200, Massey, Craig wrote: > Is there a "standard" way of removing the newline, like chomp in Perl? there's strip() method: >>> s = 'aljsk\n' >>> s 'aljsk\n' >>> print s aljsk >>> s.strip() 'aljsk' >>> help(s.strip) Help on built-in function strip: strip(...) S.strip() -> string Return a copy of the string S with leading and trailing whitespace removed. > > -----Original Message----- > From: Michael P. Reilly > [mailto:arcege@dsl092-074-184.bos1.dsl.speakeasy.net] > Sent: Thursday, July 12, 2001 8:31 AM > To: kp87@lycos.com > Cc: tutor@python.org > Subject: Re: [Tutor] file I/O > > > kevin parks wrote > > > > Hi. I am a little confused as to why this hangs when i run it. I am trying > to > > Off hand, I would say it is the end condition. The readline method > returns an empty string (false) when the end of file is reached, not a > string with a space. > > > done = 0 > > while not done: > > aLine = infile.readline() > > if aLine != " ": > if aLine != "": # not at EOF, so write out > > > f.write(aLine + '\n') > > else: > > done = 1 > > Also, readline returns a whole line of text, including the newline. > You probably do not need to append an additional newline. > > -Arcege > > -- > +----------------------------------+-----------------------------------+ > | Michael P. Reilly | arcege@speakeasy.net | > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > DISCLAIMER: This electronic message together with any attachments is > confidential. If you are not the intended recipient, do not copy, disclose or > use the contents in any way. Please also advise us by return e-mail that you > have received the message and then please destroy. Carter Holt Harvey is not > responsible for any changes made to this message and / or any attachments after > sending by Carter Holt Harvey. We use virus scanning software but exclude all > liability for viruses or anything similar in this email or any attachment. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From dsh8290@rit.edu Wed Jul 11 21:50:04 2001 From: dsh8290@rit.edu (D-Man) Date: Wed, 11 Jul 2001 16:50:04 -0400 Subject: [Tutor] file I/O In-Reply-To: ; from kp87@lycos.com on Thu, Jul 12, 2001 at 04:56:49AM +0900 References: Message-ID: <20010711165004.A6824@harmony.cs.rit.edu> On Thu, Jul 12, 2001 at 04:56:49AM +0900, kevin parks wrote: | Hi. I am a little confused as to why this hangs when i run it. I am | trying to make a script that opens a file for input opens a file for | writing and reads in a line from the input and copies it to the | created output file. In this case except for the start here and EOF | lines the file should be an exact copy. (the point is that later i an | going to do something to each line of text), but i have to get this | much working, plus the other business i mentioned on UNIX and Mac | paths, but first this, Why does it just hang the interpreter? | | This is in Mac OS 9.bloat Python 2.1 IDE | | | def finout(): | | infilename = raw_input('Enter in file name: ') | infile = open(infilename, 'r') | f = open('sys:scripts:foo.txt', 'w') | f.write("start here\n\n") As Arcege said, the loop's terminating condition is incorrect. | done = 0 | while not done: | aLine = infile.readline() | if aLine != " ": | f.write(aLine + '\n') | else: | done = 1 I would recommend the following instead : while 1 : aLine = infile.readline() if not aLine : break f.write(aLine) It is more compact, and it is the standard idiom for reading a file line-by-line. However, if you are using a new enough version of Python (2.1 I think, maybe 2.0) you can use the following instead : for aLine in infile.xreadlines() : f.write( aLine ) | infile.close() | f.write("\n\nEOF\n") | f.close() | | if __name__ == '__main__': | finout() HTH, -D From arcege@speakeasy.net Wed Jul 11 21:56:12 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 11 Jul 2001 16:56:12 -0400 (EDT) Subject: [Tutor] file I/O In-Reply-To: <2408B6871730D511881100B0D0AB59AA013BCA@MFORTOK1> from "Massey, Craig" at Jul 12, 2001 08:35:39 AM Message-ID: <200107112056.f6BKuC405934@dsl092-074-184.bos1.dsl.speakeasy.net> Massey, Craig wrote > > Is there a "standard" way of removing the newline, like chomp in Perl? Mostly, I use string.strip or string.rstrip. But that removes all whitespace, not just line terminators (carriage returns and newlines). When reading in text format (not 'rb'), then the terminator gets converted to '\n'. So you can safely remove that from the end. In binary, since each system is different and since you could get a UNIX file on a Mac, the line terminator could be different. What is the terminator, the carriage return (Mac standard) or the newline (UNIX standard of the file)? That is the problem with making one function (chomp) do to that. But readline simplifies this as I said above. Just using f.readline()[:-1] is good enough. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From Craig.Massey@oxygenforbusiness.com Wed Jul 11 22:00:29 2001 From: Craig.Massey@oxygenforbusiness.com (Massey, Craig) Date: Thu, 12 Jul 2001 09:00:29 +1200 Subject: [Tutor] file I/O Message-ID: <2408B6871730D511881100B0D0AB59AA013BCF@MFORTOK1> Well there you go, thanks. I did a workaround which got there, but I was looking for something neater like this. I'd love to know how people find out about these things as I spent a lot of time looking for it. The help with Activestate is either babyish(Tutorial) or very specific (Language Reference) and I have trouble finding out how to do things. Ignore me, I'm a newbie struggling up the learning curve on another language and not liking it any better this time either. Once I stop feeling stupid because I don't know how to do stuff like this I'll be happier. -----Original Message----- From: sill@optonline.net [mailto:sill@optonline.net] Sent: Thursday, July 12, 2001 8:48 AM To: tutor@python.org Subject: Re: [Tutor] file I/O On Thu, Jul 12, 2001 at 08:35:39AM +1200, Massey, Craig wrote: > Is there a "standard" way of removing the newline, like chomp in Perl? there's strip() method: >>> s = 'aljsk\n' >>> s 'aljsk\n' >>> print s aljsk >>> s.strip() 'aljsk' >>> help(s.strip) Help on built-in function strip: strip(...) S.strip() -> string Return a copy of the string S with leading and trailing whitespace removed. > > -----Original Message----- > From: Michael P. Reilly > [mailto:arcege@dsl092-074-184.bos1.dsl.speakeasy.net] > Sent: Thursday, July 12, 2001 8:31 AM > To: kp87@lycos.com > Cc: tutor@python.org > Subject: Re: [Tutor] file I/O > > > kevin parks wrote > > > > Hi. I am a little confused as to why this hangs when i run it. I am trying > to > > Off hand, I would say it is the end condition. The readline method > returns an empty string (false) when the end of file is reached, not a > string with a space. > > > done = 0 > > while not done: > > aLine = infile.readline() > > if aLine != " ": > if aLine != "": # not at EOF, so write out > > > f.write(aLine + '\n') > > else: > > done = 1 > > Also, readline returns a whole line of text, including the newline. > You probably do not need to append an additional newline. > > -Arcege > > -- > +----------------------------------+-----------------------------------+ > | Michael P. Reilly | arcege@speakeasy.net | > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > DISCLAIMER: This electronic message together with any attachments is > confidential. If you are not the intended recipient, do not copy, disclose or > use the contents in any way. Please also advise us by return e-mail that you > have received the message and then please destroy. Carter Holt Harvey is not > responsible for any changes made to this message and / or any attachments after > sending by Carter Holt Harvey. We use virus scanning software but exclude all > liability for viruses or anything similar in this email or any attachment. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor DISCLAIMER: This electronic message together with any attachments is confidential. If you are not the intended recipient, do not copy, disclose or use the contents in any way. Please also advise us by return e-mail that you have received the message and then please destroy. Carter Holt Harvey is not responsible for any changes made to this message and / or any attachments after sending by Carter Holt Harvey. We use virus scanning software but exclude all liability for viruses or anything similar in this email or any attachment. From clanoftheinsane@hotmail.com Wed Jul 11 22:50:33 2001 From: clanoftheinsane@hotmail.com (Paul Brown) Date: Wed, 11 Jul 2001 17:50:33 -0400 Subject: [Tutor] string comparison Message-ID:
hey all,
i am a very newbie to Python, and i am making my way through the Core Python Programming book, and Exercise 6-5(b) says i have to determine if two strings match (without using the comparison operators or the cmp() built-in function) by scanning each string.  Also, for extra credit, it asks me to add case-insensitivity to the solution.  does anyone have any suggestions?  i can only think to use the "==" operator.  thanks
paul


Get your FREE download of MSN Explorer at http://explorer.msn.com

From dyoo@hkn.eecs.berkeley.edu Wed Jul 11 22:58:05 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 Jul 2001 14:58:05 -0700 (PDT) Subject: [Tutor] file I/O In-Reply-To: <2408B6871730D511881100B0D0AB59AA013BCF@MFORTOK1> Message-ID: On Thu, 12 Jul 2001, Massey, Craig wrote: > Well there you go, thanks. I did a workaround which got there, but I > was looking for something neater like this. I'd love to know how > people find out about these things as I spent a lot of time looking > for it. The help with Activestate is either babyish(Tutorial) or very > specific (Language Reference) and I have trouble finding out how to do > things. Well, if you have any questions on certain topics, feel free to ask them here. If there's some part of Python that doesn't seem well documented, we can help patch it up... *grin* By the way, it sounds like you may be doing some string manipulation stuff. If so, take a look here: http://python.org/doc/lib/strings.html It gives more specific information on string manipulation. For example, you can find information on strip() and its variants here: http://python.org/doc/lib/module-string.html#l2h-645 From kp87@lycos.com Wed Jul 11 22:58:27 2001 From: kp87@lycos.com (kevin parks) Date: Thu, 12 Jul 2001 06:58:27 +0900 Subject: [Tutor] Re: Tutor digest, Vol 1 #950 - 12 msgs Message-ID: The new way: for aLine in infile.xreadlines() : f.write( aLine ) does indeed work on Mac Python 2.1. This little script copies a file exactly boksa('infile', 'outfile') def boksa(infilename, outfilename): infile = open(infilename, 'r') f = open(outfilename, 'w') for aLine in infile.xreadlines() : f.write( aLine ) infile.close() f.close() if __name__ == '__main__': boksa() Now i can use f.readline()[:-1] also to change line endings, no? But doesn't DOS use both carriage return and newline? so wouldn't you have to use: f.readline()[:-2] in case of DOS? Anyway it works (unless there is yet another bug i don't see) and it is so small! cheers, kevin parks seoul, korea kp87@lycos.com Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From dyoo@hkn.eecs.berkeley.edu Wed Jul 11 23:11:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 Jul 2001 15:11:15 -0700 (PDT) Subject: [Tutor] string comparison In-Reply-To: Message-ID: On Wed, 11 Jul 2001, Paul Brown wrote: > i am a very newbie to Python, and i am making my way through the Core Hello! > Python Programming book, and Exercise 6-5(b) says i have to determine if > two strings match (without using the comparison operators or the cmp() > built-in function) by scanning each string. Also, for extra credit, it Do you mean checking each character in the string, letter by letter? > asks me to add case-insensitivity to the solution. does anyone have any > suggestions? i can only think to use the "==" operator. thanks Whoa! That seems really restrictive to not allow '=='! Does the exercise kebep us from doing '==' altogether, or just against two long strings? (Wesley, I will buy your book today... *grin*) I can think a convoluted way of getting around the restriction of not using '=='. For example, if we're dealing with numbers, we can define another notion of equality if we're devious and underhanded: ### def numericEquals(x, y): return not (x < y) and not (x > y) ### That is, two numbers are equal only if one isn't larger than the other. It's a mathematical statement, and extremely silly, but it does work: ### >>> numericEquals(1, 1) 1 >>> numericEquals(1, 2) 0 >>> numericEquals(42, 42) 1 >>> numericEquals(42, 43) 0 ### Also, it turns out that we can treat single characters as numbers by using the ord() "ordinal" function: ### >>> ord('a') 97 >>> ord('z') 122 >>> ord('z') - ord('a') 25 ### By combining these two trains of thought, we can write a small function that checks for string equality, without using the '==' equality operation. I really really doubt, however, that this is what the book had in mind... *grin* Good luck to you. From dyoo@hkn.eecs.berkeley.edu Wed Jul 11 23:18:57 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 Jul 2001 15:18:57 -0700 (PDT) Subject: [Tutor] Taking off carriage returns/newlines In-Reply-To: Message-ID: On Thu, 12 Jul 2001, kevin parks wrote: > Now i can use f.readline()[:-1] also to change line endings, no? But > doesn't DOS use both carriage return and newline? so wouldn't you have > to use: f.readline()[:-2] in case of DOS? Yes. However, you can avoid the problem of choosing between -1 and -2 by using a string's rstrip() method. rstrip() removes all whitespace from the right side of the string, and can be used like this: f.readline().rstrip() From dyoo@hkn.eecs.berkeley.edu Wed Jul 11 23:26:49 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 Jul 2001 15:26:49 -0700 (PDT) Subject: [Tutor] string comparison In-Reply-To: Message-ID: On Wed, 11 Jul 2001, Danny Yoo wrote: > Whoa! That seems really restrictive to not allow '=='! Does the exercise > kebep us from doing '==' altogether, or just against two long strings? ^^^^^ Hmmm. What does "kebep" mean? "Keb": God of the earth; father of Osiris and Isis. (http://www.cogsci.princeton.edu/cgi-bin/testcgi/?stage=1&word=keb) I guess we could make the argument that to "kebep" is to deify something into the Earth god. *grin* Sorry about that; I meant to write "keep" instead. From Craig.Massey@oxygenforbusiness.com Thu Jul 12 00:15:00 2001 From: Craig.Massey@oxygenforbusiness.com (Massey, Craig) Date: Thu, 12 Jul 2001 11:15:00 +1200 Subject: [Tutor] file I/O Message-ID: <2408B6871730D511881100B0D0AB59AA013BD9@MFORTOK1> Where was that hiding when I was looking for it? Suddenly the language reference contains all kinds of useful stuff. Either my local version doesn't have it or I was blind. Probably the latter. -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Thursday, July 12, 2001 9:58 AM To: Massey, Craig Cc: 'ak@silmarill.org'; tutor@python.org Subject: RE: [Tutor] file I/O On Thu, 12 Jul 2001, Massey, Craig wrote: > Well there you go, thanks. I did a workaround which got there, but I > was looking for something neater like this. I'd love to know how > people find out about these things as I spent a lot of time looking > for it. The help with Activestate is either babyish(Tutorial) or very > specific (Language Reference) and I have trouble finding out how to do > things. Well, if you have any questions on certain topics, feel free to ask them here. If there's some part of Python that doesn't seem well documented, we can help patch it up... *grin* By the way, it sounds like you may be doing some string manipulation stuff. If so, take a look here: http://python.org/doc/lib/strings.html It gives more specific information on string manipulation. For example, you can find information on strip() and its variants here: http://python.org/doc/lib/module-string.html#l2h-645 DISCLAIMER: This electronic message together with any attachments is confidential. If you are not the intended recipient, do not copy, disclose or use the contents in any way. Please also advise us by return e-mail that you have received the message and then please destroy. Carter Holt Harvey is not responsible for any changes made to this message and / or any attachments after sending by Carter Holt Harvey. We use virus scanning software but exclude all liability for viruses or anything similar in this email or any attachment. From israel@lith.com Thu Jul 12 01:42:16 2001 From: israel@lith.com (Israel Evans) Date: Wed, 11 Jul 2001 17:42:16 -0700 Subject: [Tutor] in as a stream, change stuff, out as a stream? Message-ID: Hello, I'm in the middle of reading a bunch of rather large files in order to change one string to another. I'm probably missing something extremely obvious, but that's what this glorious Tutor Mailing list is all about isn't it? I've been reading the documentation, and due to my newbie status, I can't find the right "aha!" yet, so any help would be most appreciated I know I should be able to open up a file, read all of it's contents into a list with readlines() or read one line at a time with readline(), and then write all of that out to another file. I think that since the files are rather large, it might be best to avoid the speed of readlines() and go with readline() repeatedly. At any rate, I was wondering if it would be possible to read a line, change it in the same file I'm reading and move on to the next line, when I'm done. Is this possible? Or should I read everything at once, change the name of the old file and write everything out to a file with the same name as the old one. Is it possible to open a file as a stream and output it back into itself? or is that just plain goofy. I'm trying to do this bit with a number of fairly large files in multiple directories, and so it would be ideal If I didn't have to fill up my hard drive with old copies. ~Israel~ From ak@silmarill.org Thu Jul 12 02:13:36 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Wed, 11 Jul 2001 21:13:36 -0400 Subject: [Tutor] in as a stream, change stuff, out as a stream? In-Reply-To: <"from israel"@lith.com> References: Message-ID: <20010711211336.A5522@sill.silmarill.org> On Wed, Jul 11, 2001 at 05:42:16PM -0700, Israel Evans wrote: > Hello, > > I'm in the middle of reading a bunch of rather large files in order to > change one string to another. I'm probably missing something extremely > obvious, but that's what this glorious Tutor Mailing list is all about isn't > it? I've been reading the documentation, and due to my newbie status, I > can't find the right "aha!" yet, so any help would be most appreciated > > I know I should be able to open up a file, read all of it's contents into a > list with readlines() or read one line at a time with readline(), and then > write all of that out to another file. I think that since the files are > rather large, it might be best to avoid the speed of readlines() and go with > readline() repeatedly. there's also xreadlines() > > At any rate, I was wondering if it would be possible to read a line, change > it in the same file I'm reading and move on to the next line, when I'm done. > Is this possible? Or should I read everything at once, change the name of > the old file and write everything out to a file with the same name as the > old one. I'd read a line, change it, write it to a temp file, when done overwrite old file with new. > > Is it possible to open a file as a stream and output it back into itself? > or is that just plain goofy. > > I'm trying to do this bit with a number of fairly large files in multiple > directories, and so it would be ideal If I didn't have to fill up my hard > drive with old copies. > > ~Israel~ > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From dsh8290@rit.edu Thu Jul 12 04:33:28 2001 From: dsh8290@rit.edu (D-Man) Date: Wed, 11 Jul 2001 23:33:28 -0400 Subject: [Tutor] in as a stream, change stuff, out as a stream? In-Reply-To: ; from israel@lith.com on Wed, Jul 11, 2001 at 05:42:16PM -0700 References: Message-ID: <20010711233328.F6900@harmony.cs.rit.edu> On Wed, Jul 11, 2001 at 05:42:16PM -0700, Israel Evans wrote: | I know I should be able to open up a file, read all of it's contents into a | list with readlines() or read one line at a time with readline(), and then | write all of that out to another file. I think that since the files are | rather large, it might be best to avoid the speed of readlines() and go with | readline() repeatedly. Use xreadlines -- it gives the convenience of readlines without the memory overhead. | At any rate, I was wondering if it would be possible to read a line, change | it in the same file I'm reading and move on to the next line, when I'm done. | Is this possible? Or should I read everything at once, change the name of | the old file and write everything out to a file with the same name as the | old one. It is possible to open a file in "rw" mode (read and write) (or maybe "ra" so that it doesn't get truncated -- read the docs and test first) and use random access to move the file pointer to where you want to write text and write it. The problem here is if the data you want to write is not the _exact_ same size as the existing data you will have problems -- either some of the old data will trail the new data (because it was never removed) or the new data will overwrite some of the existing data that wasn't supposed to be changed. | Is it possible to open a file as a stream and output it back into itself? | or is that just plain goofy. You can try it out with a test file. Create some text in a file, then open it in write mode, then try to read it. When you open the file in write mode it immediately truncates the file to have a length of zero. This is why temporary files are commonly used. Read the existing data in line-by-line (with xreadlines), make the change to the line you want to change, and output it (line-by-line) to a temporary file. Then overwrite the original with the old file (use os.rename) and you won't have extra copies lying around on your disk. -D From wesc@deirdre.org Thu Jul 12 04:33:13 2001 From: wesc@deirdre.org (Wesley Chun) Date: Wed, 11 Jul 2001 20:33:13 -0700 (PDT) Subject: [Tutor] in as a stream, change stuff, out as a stream? In-Reply-To: <20010711211336.A5522@sill.silmarill.org> Message-ID: On Wed, 11 Jul 2001 sill@optonline.net wrote: > On Wed, Jul 11, 2001 at 05:42:16PM -0700, Israel Evans wrote: > > > > I'm in the middle of reading a bunch of rather large files in order to > > change one string to another. > > > > I know I should be able to open up a file, read all of it's contents into a > > list with readlines() or read one line at a time with readline(), and then > > write all of that out to another file. I think that since the files are > > rather large, it might be best to avoid the speed of readlines() and go with > > readline() repeatedly. > there's also xreadlines() xreadlines() will work here. it was invented in a similar vein to xrange(). in other words it implements a "lazy" reading scheme where by you *do* get the entire list read in, but it will do just enough I/O to get you going rather than reading everything in all at once, filling up memory. > > At any rate, I was wondering if it would be possible to read a line, change > > it in the same file I'm reading and move on to the next line, when I'm done. > > Is this possible? Or should I read everything at once, change the name of > > the old file and write everything out to a file with the same name as the > > old one. > > I'd read a line, change it, write it to a temp file, when done overwrite old > file with new. this is definitely the way most people do it. you only hold both files on the disk while the data is being converted but once that's done, the old file goes away b4 your app ends. > > Is it possible to open a file as a stream and output it back into itself? > > or is that just plain goofy. in C, you can mmap() a large file into memory, manipulate it that way. more higher-level, you can open your file for both read *and* write, but unless your records are fixed-length, you may end up corrupting things... this can also happen with mmap(). in short, it's safer to have a temp file, so in case the new file is bad for some reason, you can fall back on the old, unmanipulated data file. > > I'm trying to do this bit with a number of fairly large files in multiple > > directories, and so it would be ideal If I didn't have to fill up my hard > > drive with old copies. (see comment up above) hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From wesc@deirdre.org Thu Jul 12 04:49:32 2001 From: wesc@deirdre.org (Wesley Chun) Date: Wed, 11 Jul 2001 20:49:32 -0700 (PDT) Subject: [Tutor] string comparison In-Reply-To: Message-ID: On Wed, 11 Jul 2001, Danny Yoo wrote: > On Wed, 11 Jul 2001, Paul Brown wrote: > > > Core Python Programming, and Exercise 6-5(b) says i have to determine if > > two strings match (without using the comparison operators or the cmp() > > built-in function) by scanning each string. Also, for extra credit, it > > Do you mean checking each character in the string, letter by letter? well, character-by-character is more like it!! > > asks me to add case-insensitivity to the solution. does anyone have any > > suggestions? i can only think to use the "==" operator. thanks > > Whoa! That seems really restrictive to not allow '=='! Does the exercise > kebep us from doing '==' altogether, or just against two long strings? well heck! if you use '==', the exercise is over!! of *course* it's restrictive!! you gotta *make* strcmp() before you can really appreciate it! one char-at-a-time. > (Wesley, I will buy your book today... *grin*) i told you that i'd hand one to you if you help me out!! i'll even sign it!! *W* > I can think a convoluted way of getting around the restriction of not > using '=='. the exercise is simple. given 2 strings, determine if they are "the same." (no, i'm not talking about whether the objects are the same, just the string contents.) if str1 == 'foo' and str2 == 'foo', even if they are different objects, the strings themselves are made up of the same characters. if str1 == 'foo' and str2 == 'bar', they are *not* the same. after this exercise is complete, upgrade it with case-insensitivity so that if str1 == 'FoO' and str2 = 'fOo', then they match. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From scarblac@pino.selwerd.nl Thu Jul 12 05:13:40 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 12 Jul 2001 06:13:40 +0200 Subject: [Tutor] in as a stream, change stuff, out as a stream? In-Reply-To: ; from israel@lith.com on Wed, Jul 11, 2001 at 05:42:16PM -0700 References: Message-ID: <20010712061340.A701@pino.selwerd.nl> On 0, Israel Evans wrote: > At any rate, I was wondering if it would be possible to read a line, change > it in the same file I'm reading and move on to the next line, when I'm done. > Is this possible? Or should I read everything at once, change the name of > the old file and write everything out to a file with the same name as the > old one. The fileinput module is a high level layer over things like this. You can use it to read files line by line (it won't read it all into memory at once) and your output goes back to the file (that is, it renames the old file to a .bak file, and sends the output to a new file - then deletes the backup, by default). Something like: import fileinput files = [...list of filenames...] def process_line(line): # Do something with a line, print the result for line in fileinput.FileInput(files, inplace=1): process_line(line) -- Remco Gerlich From rnd@onego.ru Thu Jul 12 05:32:13 2001 From: rnd@onego.ru (Roman Suzi) Date: Thu, 12 Jul 2001 08:32:13 +0400 (MSD) Subject: [Tutor] file I/O In-Reply-To: <200107112056.f6BKuC405934@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: On Wed, 11 Jul 2001, Michael P. Reilly wrote: >Massey, Craig wrote >> > >But readline simplifies this as I said above. Just using >f.readline()[:-1] is good enough. No, it is not. Last line of a file could contain no "\n". Why not to write chomp? def chomp(s): if s[-1:] == "\n": return s[:-1] else: return s Or, another way: >>> def chomp1(s): ... return s[-1:] != "\n" and s or s[:-1] ... >>> chomp1("") '' >>> chomp1("1") '1' >>> chomp1("12") '12' >>> chomp1("12\n") '12' >>> chomp1("12\n\n") '12\012' > Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/ _/ Thursday, July 12, 2001 _/ Powered by Linux RedHat 6.2 _/ _/ "Misfortune: The kind of fortune that never misses." _/ From lonetwin@yahoo.com Thu Jul 12 07:15:06 2001 From: lonetwin@yahoo.com (steve) Date: Thu, 12 Jul 2001 11:45:06 +0530 Subject: [Tutor] file I/O In-Reply-To: References: Message-ID: <01071211450601.03093@mercury.in.cqsl.com> Hi all, =09I've been meaning to ask this question for a long time now, I've always seen ppl do file i/o, especially file read using an open()=20 followed by a loop of readline(), stripping the '\n' at the end.... I discovered fileinput (the module) quite early on when I started learn= ing=20 python....so I always do things like Python 2.1 (#3, Jun 25 2001, 13:39:27)=20 [GCC 2.95.3 19991030 (prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import fileinput >>> p =3D [ line.strip() for line in fileinput.input("myfile.txt") ] =09What bothers me is that I don't see enough ppl do that, an' I wonder i= s it=20 b'cos it is some kinda *Bad thing* ....could n e one comment on this ??? --=20 |||||||||||||||||||||| |||||||||#####|||||||| ||||||||#######||||||| ||||||||# O O #||||||| ||||||||#\ ~ /#||||||| ||||||##||\_/||##||||| |||||#||||||||||##|||| ||||#||||||||||||##||| ||||#|||||||||||||##||=09 |||/\##|||||||||##/\||=09 |/ \#########/ \=09 |\ \#######/ /=09 ||\____/#######\____/|=09 =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=09 Debug is human, de-fix divine. =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 From sheila@thinkspot.net Thu Jul 12 07:16:30 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 11 Jul 2001 23:16:30 -0700 Subject: [Tutor] Please Critque Tkinter Class for Newbie In-Reply-To: <200107101209.f6AC9k602068@dsl092-074-184.bos1.dsl.speakeasy.net> References: <200107100228.VAA138360666@smtppop1pub.verizon.net> <200107101209.f6AC9k602068@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: Thanks for the comments, Michael. You make two points. I will respond to one in this e-mail, and the other in a separate e-mail. On Tue, 10 Jul 2001 08:09:46 -0400 (EDT), "Michael P. Reilly" wrote about Re: [Tutor] Please Critque Tkinter Class for Newbie: :Just two comments. A widget should not pack itself as your Palette does. :That should be the application's choice. If there are some "adjustments" :you want, then override the method to modify the parameters. Oops. That was just plain dumb. I probably had that statement in there from very early in my writing/testing phase and forgot to take it out. It is now gone, and the class works just as I want it to. As a matter of fact, I'm surprised, that since the class (as I originally posted it) packed itself, and then my __main__ function packed it again, that this didn't create some kind of error. [added later] You know, I later was reading in PP2, and saw examples that did just like I had in my class...well, not exactly. They had a self.pack() statement in the class, and the if __name__=='__main__' block didn't not have the object being packed again. However, the module was reused later in the book, and they did repack the object in the main program file. Why would the author do it that way? [/end added part] -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ : :> from Tkinter import * :> :> colorVals = [ '00', '33', '66', '99', 'CC', 'FF' ] :> :> class Palette(Frame): :> def __init__(self, parent=None): :> Frame.__init__(self, parent) :> for item in colorVals: :> for tuple in [('00', '33', '66'), ('99', 'CC', 'FF')]: :> PlaqueRow(self, item, tuple).pack() :> self.pack() : XXXXXXXXXXX # allow application to pack : :> self.colortext=StringVar() :> self.info = colorInfo(self, self.colortext) :> self.info.pack(side=LEFT) :> self.colortext.set("") :> self.bind_all('', self.displayColor) : : :> class colorInfo(Frame): :> def __init__(self, parent=None, text=""): :> Frame.__init__(self, parent, height=25, width=200) :> Label(self, text="click on a color", font=("bold", 12)).pack() :> self.colorDisplay = Label(self, width=6, height = 1, bg='#FFFFFF') :> self.colorDisplay.pack(side=LEFT) : if text == "": : raise ValueError("text must be StringVar instance") : :> colorValue = Entry(self, width=10, textvariable = text) :> colorValue.pack(side=LEFT) : From sheila@thinkspot.net Thu Jul 12 07:33:13 2001 From: sheila@thinkspot.net (Sheila King) Date: Wed, 11 Jul 2001 23:33:13 -0700 Subject: [Tutor] Please Critque Tkinter Class for Newbie In-Reply-To: <200107101209.f6AC9k602068@dsl092-074-184.bos1.dsl.speakeasy.net> References: <200107100228.VAA138360666@smtppop1pub.verizon.net> <200107101209.f6AC9k602068@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: On Tue, 10 Jul 2001 08:09:46 -0400 (EDT), "Michael P. Reilly" wrote about Re: [Tutor] Please Critque Tkinter Class for Newbie: :The colorInfo widget gets passed a StringVar instance, but the :default is a (empty) string. The system might get a little :confused: Tk (under Tkinter) uses the name of the variable, :the default string could be taken without an error, but lead to :some odd problems. You probably want to test before using the :value and if not value, then possibly raise an exception or create :a new variable. OK, I'm working on understanding the issue, here. I guess I didn't really understand the distinction between the text and textvariable being string vs. StringVar types, and it must've completely passed over my head, that the option on the Entry widget is a textvariable (requires a Tkinter variable class). So, I'm experimenting with some other stuff, to see if I understand this whole thing, and I write the following code: ----------------------------------------------------------- from Tkinter import * root = Tk() ent = Entry(root, text = "Enter your name") ent.pack() root.mainloop() ----------------------------------------------------------- And the weird thing, is that although the Entry widget doesn't have a text option, this causes no error message. (It doesn't display the text "Enter your name", either, but then I didn't expect that it would.) Most of these widgets give me an error like "Such-and-such-widget doesn't have a method/attribute". But the Entry widget isn't doing that here. Now if I change the line ent = Entry(root, text = "Enter your name") to ent = Entry(root, textvariable = "Enter your name") I get the same behavior as before...no error message, but it doesn't display my string, either. Now, when I replaced it with this line: ent = Entry(root, textvariable = StringVar("Enter your name")) it raised an exception (which I expected). I do see what needs to be done. An instance of a textvariable must be created before an instance of the class colorInfo is created, and it must be passed to the instance at invocation (which is what I was doing). But the default empty string is the wrong type and doesn't work. You suggested raising an exception and dealing with that. I suppose that is one possibility. For now, I think I will just remove that default parameter from my class. If the user doesn't pass a StringVar type, though, the Hex codes for the colors will never appear in the Entry Widget. Then, again, I don't expect the colorInfo class will ever be used outside of my Palette class, so that situation isn't likely to occur. I guess there is no recommended way to pass default parameters to Tkinter variables such as the StringVar type (and IntVar and DoubleVar)? :Other than that, it looks pretty good. : -Arcege Thanks! -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ :> from Tkinter import * :> :> colorVals = [ '00', '33', '66', '99', 'CC', 'FF' ] :> :> class Palette(Frame): :> def __init__(self, parent=None): :> Frame.__init__(self, parent) :> for item in colorVals: :> for tuple in [('00', '33', '66'), ('99', 'CC', 'FF')]: :> PlaqueRow(self, item, tuple).pack() :> self.pack() : XXXXXXXXXXX # allow application to pack : :> self.colortext=StringVar() :> self.info = colorInfo(self, self.colortext) :> self.info.pack(side=LEFT) :> self.colortext.set("") :> self.bind_all('', self.displayColor) : : :> class colorInfo(Frame): :> def __init__(self, parent=None, text=""): :> Frame.__init__(self, parent, height=25, width=200) :> Label(self, text="click on a color", font=("bold", 12)).pack() :> self.colorDisplay = Label(self, width=6, height = 1, bg='#FFFFFF') :> self.colorDisplay.pack(side=LEFT) : if text == "": : raise ValueError("text must be StringVar instance") : :> colorValue = Entry(self, width=10, textvariable = text) :> colorValue.pack(side=LEFT) : From scarblac@pino.selwerd.nl Thu Jul 12 07:48:04 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 12 Jul 2001 08:48:04 +0200 Subject: [Tutor] file I/O In-Reply-To: <01071211450601.03093@mercury.in.cqsl.com>; from lonetwin@yahoo.com on Thu, Jul 12, 2001 at 11:45:06AM +0530 References: <01071211450601.03093@mercury.in.cqsl.com> Message-ID: <20010712084804.A1074@pino.selwerd.nl> On 0, steve wrote: > I've been meaning to ask this question for a long time now, > I've always seen ppl do file i/o, especially file read using an open() > followed by a loop of readline(), stripping the '\n' at the end.... > I discovered fileinput (the module) quite early on when I started learning > python....so I always do things like > > Python 2.1 (#3, Jun 25 2001, 13:39:27) > [GCC 2.95.3 19991030 (prerelease)] on linux2 > Type "copyright", "credits" or "license" for more information. > >>> import fileinput > >>> p = [ line.strip() for line in fileinput.input("myfile.txt") ] > > What bothers me is that I don't see enough ppl do that, an' I wonder is it > b'cos it is some kinda *Bad thing* ....could n e one comment on this ??? Well, not a bad thing, but I think you lose most of the advantages of fileinput (not reading in the whole file at once, for one). On the other hand, fileinput will probably give a small performance hit because it has to supply these things, and the strip() in the list comprehension are minor slowdowns as well. If you need the whole file in lines, but without \n, the easiest way is to read it all in and to split on \n: p = open("myfile.txt","r").read().split("\n") That's the most direct way. -- Remco Gerlich From scarblac@pino.selwerd.nl Thu Jul 12 07:55:07 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 12 Jul 2001 08:55:07 +0200 Subject: [Tutor] Mac to UNIX and back again (what to do about path) In-Reply-To: ; from wesc@deirdre.org on Tue, Jul 10, 2001 at 04:03:07PM -0700 References: Message-ID: <20010712085507.B1074@pino.selwerd.nl> On 0, Wesley Chun wrote: > In John's reply, he indicated an intelligent way to join pathnames > into a singleproperly-delimited string like this: > > >>path=os.path.join("myfolder", "mysubfolder", "myfile") > > I think that he meant using os.sep and a sequence instead: > > path=os.sep.join(["myfolder", "mysubfolder", "myfile"]) No, he meant the very useful function os.path.join(), which is more intelligent than a simple string join. For instance, it ignores empty arguments, and if one of the arguments starts at the root dir again ("/home", "scarblac", "/home") it throws away the arguments before that. If one of the arguments ends with a path seperator, a new one isn't inserted. The documentation talks about inserting a /, but it actually means inserting whatever seperator is relevant on the current platform. -- Remco Gerlich From scarblac@pino.selwerd.nl Thu Jul 12 08:02:42 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 12 Jul 2001 09:02:42 +0200 Subject: [Tutor] Re: Tutor digest, Vol 1 #950 - 12 msgs In-Reply-To: ; from kp87@lycos.com on Thu, Jul 12, 2001 at 06:58:27AM +0900 References: Message-ID: <20010712090242.A1129@pino.selwerd.nl> On 0, kevin parks wrote: > The new way: > > for aLine in infile.xreadlines() : > f.write( aLine ) > > does indeed work on Mac Python 2.1. This little script copies a file exactly In 2.2, 'for line in infile:' should work :-) (snip) > Now i can use f.readline()[:-1] also to change line endings, no? But > doesn't DOS use both carriage return and newline? so wouldn't you have to > use: f.readline()[:-2] in case of DOS? No. The conversion is handled by the read() calls of the file; as long as you opened it in ascii mode, on DOS, the DOS end of line is translated to \n in Python; ditto for writing a file. In Python it all looks like a single \n. -- Remco Gerlich From wwwjessie@21cn.com Thu Jul 12 10:59:34 2001 From: wwwjessie@21cn.com (wwwjessie@21cn.com) Date: Thu, 12 Jul 2001 17:59:34 +0800 Subject: [Tutor] =?gb2312?B?xvPStcnPzfijrNK7sr21vc67KFlvdXIgb25saW5lIGNvbXBhbnkp?= Message-ID: <3250e01c10ab9$5a4abec0$9300a8c0@ifood1gongxing> This is a multi-part message in MIME format. ------=_NextPart_000_3250F_01C10AFC.686DFEC0 Content-Type: text/plain; charset="gb2312" Content-Transfer-Encoding: base64 1/C+tLXEu+HUsaOsxPq6w6Oh0rzKs8a31tC5+s34t/7O8dDFz6K5qcT6ss6/vKO6ICANCg0K07XT 0NfUvLq1xM34yc+5q8u+o6zVucq+uavLvrL6xre6zbf+zvGjrMzhuN/G89K1vrrV+cGmLMT609DB vdbW0aHU8aO6DQoNCjEvIM341b62qNbGIDxodHRwOi8vd3d3Lmlmb29kMS5jb20vYWJvdXR1cy9v dXJzZXJ2aWNlcy93ZWIuYXNwPiAgOg0K19S8us6su6S4/NDCo6y53MDtx7DMqLrzzKijrLj5vt3G 89K10OjSqqOsvajBotfUvLq1xM34yc+5q8u+o6zK/b7dv+LEo7/pyM7E+tGh1PGjusnMx+nQxc+i t6KyvCzN+MnPsvrGt9W5yr6jrL/Nu6e3/s7x1tDQxCzN+MnPubrO78+1zbMsv827p7nYDQrPtbnc wO0szfjJz8LbzLMszfjJz7vh0unW0NDELM34yc/V0Ma4LM22xrHPtc2zLNfKwc/PwtTY1tDQxCzO yr7ttfey6Swg1dCx6rLJubrPtc2zLLfDzsrV382zvMa31s72LCDBxMzsytIovbvB96GizLjF0Cmh raGtDQoNCs/rwcu94sr9vt2/4sSjv+nR3cq+1tDQxKO/x+vBqs+1o7ogc2FsZXNAaWZvb2QxLmNv bSA8bWFpbHRvOnNhbGVzQGlmb29kMS5jb20+DQqhobXnu7CjujA3NTUtMzc4NjMwOaGhz/rK27K/ yfLQob3jDQoNCjIvINK8zfjNqCA8aHR0cDovL29uZXQuaWZvb2QxLmNvbS8+DQot19TW+sq9vajN +KOsstnX97zytaWjrLy0vai8tNPDo7q/ydW5yr4zMNXFu/K4/Lbg1dXGrKOs19TW+sq9zqy7pKOs v8nL5sqxuPzQws28xqy6zc7E19bE2sjdo6zU2s/ft6KyvLL6xrfQxc+ioaK5q8u+tq/MrLXIo6zU +cvNtv68trn6vMrT8sP7KA0KyOdodHRwOi8veW91cm5hbWUuaWZvb2QxLmNvbSmjrNPr0rzKs8a3 1tC5+s34KNKzw+bkr8DAwb/UwtPiMjAwzfK0zim99MPcway906OszOG438LyvNK6zbnLv823w87K wb+jrLaoxtrK1bW90rzKsw0KxrfW0Ln6zfjM4bmptcS/zbun0OjH87rNssm5utDFz6Khow0KDQoN Cg0KN9TCMzDI1cewyerH67KiuLa/7sq508PSvM34zaijrMzYsfDTxbvdvNszODAw1KovxOqjrNT5 y83M9cLrueO45rKiw+K30dTayrPGt9eo0rXU09a+v6+1x7mpo6zH86OstPrA7aOsus/X99DFz6IN Cs/rwcu94rj8tuA/IKGhx+vBqs+1o7ogc2FsZXNAaWZvb2QxLmNvbSA8bWFpbHRvOnNhbGVzQGlm b29kMS5jb20+DQqhobXnu7CjujA3NTUtMzc4NjMwOaGhoaHP+srbsr/J8tChveMNCrvyILfDzsrO 0sPHtcTN+NKzIDxodHRwOi8vd3d3Lmlmb29kMS5jb20vYWJvdXR1cy9vdXJzZXJ2aWNlcy9jcHNl cnZpY2UuYXNwPg0KOnd3dy5pZm9vZDEuY29tDQoNCrvY1rSjqMfrtKvV5qO6MDc1NS0zMjM5MDQ3 u/K3orXn19PTyrz+o7ogc2FsZXNAaWZvb2QxLmNvbSA8bWFpbHRvOnNhbGVzQGlmb29kMS5jb20+ IKOpDQoNCqH1ILG+uavLvrbUzfjVvrao1sa40NDLyKShoaGhICAgICAgICAgICAgICAgICAgICAg ofUgsb65q8u+ttTSvM34zai3/s7xuNDQy8ikDQoNCrmry77D+7PGo7pfX19fX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fX19fX19fX19fX1/Bqs+1yMujul9fX19fX19fX19fX19fX19fXw0K X19fX18gDQoNCrXnu7Cjul9fX19fX19fX19fX19fX19fX19fX7Sr1eajul9fX19fX19fX19fX19f X19fX19fX19FLW1haWyjul9fX19fX19fX19fX19fX18NCl9fX19fXyANCg0K ------=_NextPart_000_3250F_01C10AFC.686DFEC0 Content-Type: text/html; charset="gb2312" Content-Transfer-Encoding: base64 PEhUTUw+DQo8SEVBRD4NCjxUSVRMRT5VbnRpdGxlZCBEb2N1bWVudDwvVElUTEU+IDxNRVRBIEhU VFAtRVFVSVY9IkNvbnRlbnQtVHlwZSIgQ09OVEVOVD0idGV4dC9odG1sOyBjaGFyc2V0PWdiMjMx MiI+IA0KPC9IRUFEPg0KDQo8Qk9EWSBCR0NPTE9SPSIjRkZGRkZGIiBURVhUPSIjMDAwMDAwIj4N CjxUQUJMRSBXSURUSD0iOTglIiBCT1JERVI9IjAiIENFTExTUEFDSU5HPSIwIiBDRUxMUEFERElO Rz0iMCI+PFRSPjxURD48UCBDTEFTUz1Nc29Ob3JtYWwgU1RZTEU9J21hcmdpbi1yaWdodDotMTcu ODVwdDtsaW5lLWhlaWdodDoxNTAlJz48Rk9OVCBTSVpFPSIyIj7X8L60tcS74dSxo6zE+rrDo6HS vMqzxrfW0Ln6zfi3/s7x0MXPormpxPqyzr+8o7ombmJzcDs8L0ZPTlQ+IA0KPC9QPjxQIENMQVNT PU1zb05vcm1hbCBTVFlMRT0nbWFyZ2luLXJpZ2h0Oi0xNy44NXB0O2xpbmUtaGVpZ2h0OjE1MCUn PjxGT05UIFNJWkU9IjIiPtO109DX1Ly6tcTN+MnPuavLvqOs1bnKvrmry76y+sa3us23/s7xo6zM 4bjfxvPStb661fnBpizE+tPQwb3W1tGh1PGjujxCUj48QlI+MS8gDQo8QQ0KSFJFRj0iaHR0cDov L3d3dy5pZm9vZDEuY29tL2Fib3V0dXMvb3Vyc2VydmljZXMvd2ViLmFzcCI+zfjVvrao1sY8L0E+ IDog19S8us6su6S4/NDCo6y53MDtx7DMqLrzzKijrLj5vt3G89K10OjSqqOsvajBotfUvLq1xM34 yc+5q8u+o6zK/b7dv+LEo7/pyM7E+tGh1PGjusnMx+nQxc+it6KyvCzN+MnPsvrGt9W5yr6jrL/N u6e3/s7x1tDQxCzN+MnPubrO78+1zbMsv827p7nYz7W53MDtLM34yc/C28yzLM34yc+74dLp1tDQ xCzN+MnP1dDGuCzNtsaxz7XNsyzXysHPz8LU2NbQ0MQszsq+7bX3suksIA0K1dCx6rLJubrPtc2z LLfDzsrV382zvMa31s72LCDBxMzsytIovbvB96GizLjF0CmhraGtPC9GT05UPjwvUD48UCBDTEFT Uz1Nc29Ob3JtYWwgU1RZTEU9J2xpbmUtaGVpZ2h0OjIwLjBwdCc+PEI+PEZPTlQgQ09MT1I9IiNG RjAwMDAiPs/rwcu94sr9vt2/4sSjv+nR3cq+1tDQxKO/PC9GT05UPjwvQj48Rk9OVCBTSVpFPSIy Ij7H68Gqz7WjujxBIEhSRUY9Im1haWx0bzpzYWxlc0BpZm9vZDEuY29tIj5zYWxlc0BpZm9vZDEu Y29tPC9BPiANCqGhtee7sKO6MDc1NS0zNzg2MzA5oaHP+srbsr/J8tChveM8L0ZPTlQ+PC9QPjxQ IENMQVNTPU1zb05vcm1hbCBTVFlMRT0nbGluZS1oZWlnaHQ6MjAuMHB0Jz48L1A+PFAgQ0xBU1M9 TXNvTm9ybWFsIFNUWUxFPSdsaW5lLWhlaWdodDoyMC4wcHQnPjxGT05UIFNJWkU9IjIiPjIvIA0K PEEgSFJFRj0iaHR0cDovL29uZXQuaWZvb2QxLmNvbS8iPtK8zfjNqDwvQT4t19TW+sq9vajN+KOs stnX97zytaWjrLy0vai8tNPDo7q/ydW5yr4zMNXFu/K4/Lbg1dXGrKOs19TW+sq9zqy7pKOsv8nL 5sqxuPzQws28xqy6zc7E19bE2sjdo6zU2s/ft6KyvLL6xrfQxc+ioaK5q8u+tq/MrLXIo6zU+cvN tv68trn6vMrT8sP7KMjnaHR0cDovL3lvdXJuYW1lLmlmb29kMS5jb20po6zT69K8yrPGt9bQufrN +CjSs8Pm5K/AwMG/1MLT4jIwMM3ytM4pvfTD3MGsvdOjrMzhuN/C8rzSus25y7/Nt8POysG/o6y2 qMbaytW1vdK8yrPGt9bQufrN+Mzhuam1xL/Nu6fQ6Mfzus2yybm60MXPoqGjPEJSPjwvRk9OVD48 L1A+PFAgQ0xBU1M9TXNvTm9ybWFsIFNUWUxFPSdtYXJnaW4tcmlnaHQ6LTE3Ljg1cHQ7bGluZS1o ZWlnaHQ6MTUwJSc+PEZPTlQgU0laRT0iMiI+PEJSPjwvRk9OVD4gDQo8Qj48Rk9OVCBDT0xPUj0i I0ZGMDAwMCI+NzwvRk9OVD48L0I+PEZPTlQgQ09MT1I9IiNGRjAwMDAiPjxCPtTCMzDI1cewyerH 67KiuLa/7sq508PSvM34zaijrMzYsfDTxbvdvNszODAw1KovxOqjrNT5y83M9cLrueO45rKiw+K3 0dTayrPGt9eo0rXU09a+v6+1x7mpo6zH86OstPrA7aOsus/X99DFz6I8L0I+PEJSPjwvRk9OVD4g DQo8Rk9OVCBTSVpFPSIyIj7P68HLveK4/LbgPyChocfrwarPtaO6PEEgSFJFRj0ibWFpbHRvOnNh bGVzQGlmb29kMS5jb20iPnNhbGVzQGlmb29kMS5jb208L0E+IA0KoaG157uwo7owNzU1LTM3ODYz MDmhoaGhz/rK27K/yfLQob3jPEJSPjwvRk9OVD48Rk9OVCBTSVpFPSIyIj678jxBDQpIUkVGPSJo dHRwOi8vd3d3Lmlmb29kMS5jb20vYWJvdXR1cy9vdXJzZXJ2aWNlcy9jcHNlcnZpY2UuYXNwIj63 w87KztLDx7XEzfjSszwvQT46d3d3Lmlmb29kMS5jb208L0ZPTlQ+PC9QPjxQIENMQVNTPU1zb05v cm1hbCBTVFlMRT0nbGluZS1oZWlnaHQ6MjAuMHB0JyBBTElHTj0iTEVGVCI+PC9QPjxQIENMQVNT PU1zb05vcm1hbCBBTElHTj1MRUZUIFNUWUxFPSdsaW5lLWhlaWdodDoyMC4wcHQnPjxGT05UIFNJ WkU9IjIiPjxCPrvY1rSjqMfrtKvV5qO6MDc1NS0zMjM5MDQ3u/K3orXn19PTyrz+o7o8L0I+PEEN CkhSRUY9Im1haWx0bzpzYWxlc0BpZm9vZDEuY29tIj5zYWxlc0BpZm9vZDEuY29tIDwvQT48Qj6j qTwvQj48L0ZPTlQ+PC9QPjxQPjxGT05UIFNJWkU9IjIiPqH1IA0Ksb65q8u+ttTN+NW+tqjWxrjQ 0MvIpKGhoaEmbmJzcDsmbmJzcDsgJm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7 Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7IA0KJm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7Jm5ic3A7 Jm5ic3A7IKH1ILG+uavLvrbU0rzN+M2ot/7O8bjQ0MvIpDwvRk9OVD48L1A+PFAgQ0xBU1M9TXNv Tm9ybWFsIFNUWUxFPSdsaW5lLWhlaWdodDoyMC4wcHQnPjxGT05UIFNJWkU9IjIiPrmry77D+7PG o7pfX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX1/Bqs+1yMujul9f X19fX19fX19fX19fX19fX19fX19fIA0KPEJSPiA8QlI+ILXnu7Cjul9fX19fX19fX19fX19fX19f X19fX7Sr1eajul9fX19fX19fX19fX19fX19fX19fX19FLW1haWyjul9fX19fX19fX19fX19fX19f X19fX18gDQo8L0ZPTlQ+PC9QPjxQIENMQVNTPU1zb05vcm1hbCBTVFlMRT0nbGluZS1oZWlnaHQ6 MjAuMHB0Jz48L1A+PC9URD48L1RSPjwvVEFCTEU+IA0KPC9CT0RZPg0KPC9IVE1MPg0K ------=_NextPart_000_3250F_01C10AFC.686DFEC0-- From arcege@speakeasy.net Thu Jul 12 13:20:18 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Thu, 12 Jul 2001 08:20:18 -0400 (EDT) Subject: [Tutor] Please Critque Tkinter Class for Newbie In-Reply-To: from "Sheila King" at Jul 11, 2001 11:16:30 PM Message-ID: <200107121220.f6CCKIk07210@dsl092-074-184.bos1.dsl.speakeasy.net> Sheila King wrote > :Just two comments. A widget should not pack itself as your Palette does. > :That should be the application's choice. If there are some "adjustments" > :you want, then override the method to modify the parameters. > > Oops. That was just plain dumb. I probably had that statement in there > from very early in my writing/testing phase and forgot to take it out. > It is now gone, and the class works just as I want it to. As a matter of > fact, I'm surprised, that since the class (as I originally posted it) > packed itself, and then my __main__ function packed it again, that this > didn't create some kind of error. Tkinter will allow a widget to be repacked. The issue is that you cannot mix geometry managers. So if you want to use the Place or Grid managers, then this will be a problem (need to call pack_forget first). Wouldn't be an error, but you get interesting results if you try: >>> from Tkinter import * >>> root = Tk() >>> b = Button(root, text='bye', command=root.quit) >>> e = Entry(root) >>> b.pack() >>> e.grid() On my Linux system, I get a window that continually changes between the two widgets which are in the same space - so fast that I can't even click on the quit button, which wouldn't work since I'm not in mainloop. (It's kind of neat to watch, but I just had a MRI this morning, so it giving me a worse headache. I'll have to address your other question later today.) > You know, I later was reading in PP2, and saw examples that did just > like I had in my class...well, not exactly. They had a self.pack() > statement in the class, and the if __name__=='__main__' block didn't not > have the object being packed again. However, the module was reused later > in the book, and they did repack the object in the main program file. > Why would the author do it that way? Mostly because he's just writting little demos and that most things use pack instead of grid or place. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From kp87@lycos.com Thu Jul 12 13:58:19 2001 From: kp87@lycos.com (kevin parks) Date: Thu, 12 Jul 2001 21:58:19 +0900 Subject: [Tutor] ratios with regular expressions, split? Message-ID: One of the things that i am trying to do is calcualte, manuipulate, and plain old fondle ratios. I need to be able to input a series of ratios such as: 6/5, 10/9, 9/8, 6/5, 10/9 and then split them up in to numerator/denominator pairs for each one, so that 6/5 would be dumped in to 2 variables, say num1, denom1 and 10/9 would be assigned to say num2, denom2 etc... Additionally the ratios might also be input as 7:6 or 7/6 and some have a different number of digits, like 3/2, 81/80 and 127/128, etc. Also there is no way to tell in advance if there will be a series of 3 ratios, 4 ratios, or 53 ratios. What is the best way to do this? with regex or split? I bought the Chun book and it has a regular expressions chapter that i am looking at now, but i am not sure exactly the best way to get started on this. I have a Ratio class and some methods and funcs to muck with them but i am super tired of typing in scales like this: scale41 = [Ratio(15,14), Ratio(7,6), Ratio(6,5), Ratio(5,4), Ratio(16,15)] scale42 = [Ratio(6,5), Ratio(7,6), Ratio(15,14), Ratio(16,15), Ratio(5,4)] scale43 = [Ratio(15,14), Ratio(7,6), Ratio(6,5), Ratio(8,7), Ratio(7,6)] scale44 = [Ratio(12,11), Ratio(11,10), Ratio(5,4), Ratio(13,12), Ratio(16,13)] scale45 = [Ratio(9,8), Ratio(10,9), Ratio(6,5), Ratio(13,12), Ratio(16,13)] scale46 = [Ratio(6,5), Ratio(25,24), Ratio(6,5), Ratio(7,6), Ratio(8,7)] scale47 = [Ratio(1,1), Ratio(9,8), Ratio(6,5), Ratio(4,3), Ratio(3,2), Ratio(5,3), Ratio(7,4), Ratio(2,1)] scale48 = [Ratio(9,8), Ratio(16,15), Ratio(10,9), Ratio(9,8), Ratio(8,7), Ratio(21,20), Ratio(10,9)] scale49 = [Ratio(21,20), Ratio(8,7), Ratio(10,9), Ratio(9,8), Ratio(21,20), Ratio(8,7), Ratio(10,9)] I'd rather enter: 15/14, 7/6, 6/5, 5/4, 16/15 -or- 15:14, 7:6, 6:5, 5:4, 16:15 and have Pyhton pick it apart, like: scale41 = [Ratio(15,14), Ratio(7,6), Ratio(6,5), Ratio(5,4), Ratio(16,15)] num1 = 15 denom1 = 14 nem2 = 7 denom2 = 6 . . . back to work. ps. be nice to me it is my birthday (34! Ughh!) and i am all alone (except for my python book and the interpreter and maybe some kimchee soup a bit later) kevin parks seoul, korea Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From scarblac@pino.selwerd.nl Thu Jul 12 15:11:00 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 12 Jul 2001 16:11:00 +0200 Subject: [Tutor] ratios with regular expressions, split? In-Reply-To: ; from kp87@lycos.com on Thu, Jul 12, 2001 at 09:58:19PM +0900 References: Message-ID: <20010712161100.A1899@pino.selwerd.nl> On 0, kevin parks wrote: > Additionally the ratios might also be input as 7:6 or 7/6 and some have a > different number of digits, like 3/2, 81/80 and 127/128, etc. Also there is > no way to tell in advance if there will be a series of 3 ratios, 4 ratios, > or 53 ratios. What is the best way to do this? with regex or split? I bought > the Chun book and it has a regular expressions chapter that i am looking at > now, but i am not sure exactly the best way to get started on this. Could you hit enter now and then? I saw this whole paragraph on one line, and that's not that easy to read. (reads below). Oops. Happy Birthday! :-) Anyway, I think that split would work fine. As long as you're certain the ratios always have a simple n/m format and are seperated by commas, something like l = "3/4, 4/5, 6/7" ratios = [] for ratio in l.split(","): n, m = ratio.split("/") ratios.append(Ratio(n, m)) should work fine. -- Remco Gerlich From dsh8290@rit.edu Thu Jul 12 15:38:30 2001 From: dsh8290@rit.edu (D-Man) Date: Thu, 12 Jul 2001 10:38:30 -0400 Subject: [Tutor] ratios with regular expressions, split? In-Reply-To: <20010712161100.A1899@pino.selwerd.nl>; from scarblac@pino.selwerd.nl on Thu, Jul 12, 2001 at 04:11:00PM +0200 References: <"from kp87"@lycos.com> <20010712161100.A1899@pino.selwerd.nl> Message-ID: <20010712103830.B9075@harmony.cs.rit.edu> On Thu, Jul 12, 2001 at 04:11:00PM +0200, Remco Gerlich wrote: | On 0, kevin parks wrote: | > Additionally the ratios might also be input as 7:6 or 7/6 and some have a | > different number of digits, like 3/2, 81/80 and 127/128, etc. Also there is | > no way to tell in advance if there will be a series of 3 ratios, 4 ratios, | > or 53 ratios. What is the best way to do this? with regex or split? I bought | > the Chun book and it has a regular expressions chapter that i am looking at | > now, but i am not sure exactly the best way to get started on this. | Anyway, I think that split would work fine. As long as you're certain the | ratios always have a simple n/m format and are seperated by commas, | something like | | | l = "3/4, 4/5, 6/7" | ratios = [] | for ratio in l.split(","): | n, m = ratio.split("/") | ratios.append(Ratio(n, m)) I think you want ratios.append(Ratio( int(n) , int(m) )) instead, for the last line. To be more robust you would also need a try-except block around it to catch any ValueError exceptions, unless you know for certain that the input is good (or you want the ValueError to propagate up and terminate the interpreter). -D From dyoo@hkn.eecs.berkeley.edu Thu Jul 12 18:29:09 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 Jul 2001 10:29:09 -0700 (PDT) Subject: [Tutor] file I/O In-Reply-To: <01071211450601.03093@mercury.in.cqsl.com> Message-ID: On Thu, 12 Jul 2001, steve wrote: > I discovered fileinput (the module) quite early on when I started learning > python....so I always do things like > > Python 2.1 (#3, Jun 25 2001, 13:39:27) > [GCC 2.95.3 19991030 (prerelease)] on linux2 > Type "copyright", "credits" or "license" for more information. > >>> import fileinput > >>> p = [ line.strip() for line in fileinput.input("myfile.txt") ] > > What bothers me is that I don't see enough ppl do that, an' I > wonder is it b'cos it is some kinda *Bad thing* ....could n e one > comment on this ??? [warning: advanced apologies for the coding style.] The fileinput module itself isn't bad: if you have familiarity with the Perl programming language, you might recognize fileinput as an analog to the magic '<>' operator. When using fileinput.input(), we can actually leave it's input argument blank. To show this, let's make a fast 'one-liner' program. ### import fileinput; print ''.join([l.strip() for l in fileinput.input()]) ### This one-liner program takes any text file, and turns it into one long line. As we can see, there's no filename involved: fileinput()'s usefulness comes from the fact that it will automagically look for its input from filenames given at the prompt or standard input. Here are a few sample runs: ### [dyoo@tesuque dyoo]$ python makeOneLiner.py hello world this is a test of the emergency broadcast system. [At this point, I press Ctrl-d a few times to indicate the end of input.] hello worldthis is a testof the emergency broadcastsystem. [dyoo@tesuque dyoo]$ cat foo.txt hello again This is a another test of the emergency broadcast system. [dyoo@tesuque dyoo]$ python makeOneLiner.py foo.txt hello againThis is a another test of the emergencybroadcast system. ### This obscure program makes everything hard to read. From sheila@thinkspot.net Thu Jul 12 20:41:58 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 12 Jul 2001 12:41:58 -0700 Subject: [Tutor] Please Critque Tkinter Class for Newbie In-Reply-To: <200107121220.f6CCKIk07210@dsl092-074-184.bos1.dsl.speakeasy.net> References: <200107121220.f6CCKIk07210@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: <1098889D5B13@kserver.org> On Thu, 12 Jul 2001 08:20:18 -0400 (EDT), "Michael P. Reilly" wrote about Re: [Tutor] Please Critque Tkinter Class for Newbie: :Sheila King wrote :> :Just two comments. A widget should not pack itself as your Palette does. :> :That should be the application's choice. If there are some "adjustments" :> :you want, then override the method to modify the parameters. :> :> Oops. That was just plain dumb. I probably had that statement in there :> from very early in my writing/testing phase and forgot to take it out. :> It is now gone, and the class works just as I want it to. As a matter of :> fact, I'm surprised, that since the class (as I originally posted it) :> packed itself, and then my __main__ function packed it again, that this :> didn't create some kind of error. : :Tkinter will allow a widget to be repacked. The issue is that you :cannot mix geometry managers. So if you want to use the Place or Grid :managers, then this will be a problem (need to call pack_forget first). :Wouldn't be an error, but you get interesting results if you try: OK, but if one has a class derived from the Tkinter Frame Widget that has several other types of widgets on it (such as a button and a label and so forth), and those items are placed on the Frame subclass with the pack manager, then won't this incompatibility still exist? (i.e. someone will not then be able to place the Frame subclass on another widget unless they use the place geometry manager???). Or maybe not. OK, I will experiment with this. (I haven't tried using grid(), yet...) :but I just had a MRI this morning, so it :giving me a worse headache. I'll have to address your other question :later today.) Oh, sorry to hear that. Please, take care of yourself and rest. No hurry on this stuff, although I really DO appreciate your assistance so far. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From israel@lith.com Thu Jul 12 20:47:06 2001 From: israel@lith.com (Israel Evans) Date: Thu, 12 Jul 2001 12:47:06 -0700 Subject: [Tutor] raw string notation. Message-ID: Hi there good people! I'm performing a regular expression search and I'm running into some problems with the Raw String Notation. when I type a string and I don't want any meta characters read as metacharacters, I thought that typing r in front of the quotes. However in this particular circumstance, this doesn't seem to work dir = r'c:\temp\test\' #<--- this last single quote seems # to be getting escaped by the preceding slash SyntaxError: invalid token #<--- hence this error. Any ideas? What I'm trying to do overall is to search through a directory for files, with any one of a defined set of extensions and do something with each in turn. So first I made this little wordswapper module that goes like this.... #! % python wordswap import fileinput, re filename = raw_input('What is the name of the file? >> ') oldword = raw_input('What is the old word? >> ') newword = raw_input('What is the new word? >> ') pat = re.compile(oldword) def doswap(line): newline = pat.sub(newword, line) print newline, def wordswap(): for line in fileinput.input(filename, 1): doswap(line) if __name__ == '__main__': wordswap() raw_input('press any key to end') Then I plan to modify this so that I ask for a directory, the old word and the new word. Then look through that Directory for any files with extensions .txt .blah and so on. I was trying to use glob.glob(directory + searchpattern) to do this, but I think this is the wrong approach.. Any Ideas? Thanks a bundle! ~Israel~ From dsh8290@rit.edu Thu Jul 12 21:05:54 2001 From: dsh8290@rit.edu (D-Man) Date: Thu, 12 Jul 2001 16:05:54 -0400 Subject: [Tutor] raw string notation. In-Reply-To: ; from israel@lith.com on Thu, Jul 12, 2001 at 12:47:06PM -0700 References: Message-ID: <20010712160554.G9536@harmony.cs.rit.edu> On Thu, Jul 12, 2001 at 12:47:06PM -0700, Israel Evans wrote: | | Hi there good people! | | I'm performing a regular expression search and I'm running into some | problems with the Raw String Notation. | | when I type a string and I don't want any meta characters read as | metacharacters, I thought that typing r in front of the quotes. However in | this particular circumstance, this doesn't seem to work | | dir = r'c:\temp\test\' #<--- this last single quote seems | # to be getting escaped by the | preceding slash | SyntaxError: invalid token #<--- hence this error. | | Any ideas? Yes -- in order to allow quotes to appear in raw strings, they are the only escape sequence that is evaluated. As a result, a raw string can't end with a backslash. There are a few solutions to this, in your situation : dir = r'c:\temp\test' you don't really need the trailing backslash anyways. dir = r'c:/temp/test' Tim Peters pointed out that the windows API secretly allows forward slashes instead of backslashes in a path. This won't work with command.com or cmd.exe, but will work for most other stuff (explorer may not like it, though). | Any Ideas? Globing is good (from a Unix user's perspective, anyways ). Also take a look at the os.path module. It may help you. -D From arcege@speakeasy.net Thu Jul 12 21:21:29 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Thu, 12 Jul 2001 16:21:29 -0400 (EDT) Subject: [Tutor] Please Critque Tkinter Class for Newbie In-Reply-To: from "Sheila King" at Jul 11, 2001 11:24:14 PM Message-ID: <200107122021.f6CKLTF01086@dsl092-074-184.bos1.dsl.speakeasy.net> Sheila King wrote > wrote about Re: [Tutor] > :The colorInfo widget gets passed a StringVar instance, but the > :default is a (empty) string. The system might get a little > :confused: Tk (under Tkinter) uses the name of the variable, > :the default string could be taken without an error, but lead to > :some odd problems. You probably want to test before using the > :value and if not value, then possibly raise an exception or create > :a new variable. > > OK, I'm working on understanding the issue, here. I guess I didn't > really understand the distinction between the text and textvariable > being string vs. StringVar types, and it must've completely passed over > my head, that the option on the Entry widget is a textvariable (requires > a Tkinter variable class). It's a little complicated - it deals with the interactions between Python, Tcl (the language Tk works with) and Tk (which is under Tkinter). Try this experiment: >>> from Tkinter import * >>> root = Tk() >>> sv = StringVar(root) >>> str(sv) 'PY_VAR0' >>> sv.get() '' >>> root.setvar('PY_VAR0', 'hi there') >>> sv.get() 'hi there' >>> e = Entry(root, textvariable='PY_VAR0') >>> e.pack() >>> mainloop() Now look at the contents of the entry widget in the window. It will say "hi there". That's because the StringVar instance is setting the Tcl variable PY_VAR0 which the Tk entry widget is using. The Tkinter textvariable option takes the str() of the Variable instance (StringVar, IntVar, etc.) which is the name. > I guess there is no recommended way to pass default parameters to > Tkinter variables such as the StringVar type (and IntVar and DoubleVar)? Nope, the Variable subclasses do not take default arguments to the constructor... unless you would like to further subclass them. class StringVarDef(StringVar): _default = 'this is an empty string' class IntVarDef(IntVar): _default = 42 This will set up the new default value for that class (not the instances). -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From israel@lith.com Fri Jul 13 02:25:58 2001 From: israel@lith.com (Israel Evans) Date: Thu, 12 Jul 2001 18:25:58 -0700 Subject: [Tutor] raw string notation. Message-ID: Excellent! Thank you! I still have troubles with backslashes however... In the files, that I'm searching, I'd like to sometimes be able to have oldword and newword contain a \ character. def wordswap(filename, oldword, newword): import fileinput from string import * for line in fileinput.input(filename, 1): newline = replace(line, oldword, newword) print newline, It seems that if oldword and newword contain a \ then they never find anything. The files I'm searching contain paths to resources. Sometimes instead of changing oneword of the name of the resource, I want to change both one of the Directories and the name of the resource. It seems that this will work in the IDLE interpreter when I'm working with a list, but not when I'm working with a file. i.e. when in the for loop I use for line in list: newline = replace(line, oldword, newword) print newline, Does anybody know why and what I should do about it that I'm missing? Thanks again! ~Israel~ -----Original Message----- From: D-Man [mailto:dsh8290@rit.edu] Sent: Thursday, July 12, 2001 1:06 PM To: [tutor] Subject: Re: [Tutor] raw string notation. On Thu, Jul 12, 2001 at 12:47:06PM -0700, Israel Evans wrote: | | Hi there good people! | | I'm performing a regular expression search and I'm running into some | problems with the Raw String Notation. | | when I type a string and I don't want any meta characters read as | metacharacters, I thought that typing r in front of the quotes. However in | this particular circumstance, this doesn't seem to work | | dir = r'c:\temp\test\' #<--- this last single quote seems | # to be getting escaped by the | preceding slash | SyntaxError: invalid token #<--- hence this error. | | Any ideas? Yes -- in order to allow quotes to appear in raw strings, they are the only escape sequence that is evaluated. As a result, a raw string can't end with a backslash. There are a few solutions to this, in your situation : dir = r'c:\temp\test' you don't really need the trailing backslash anyways. dir = r'c:/temp/test' Tim Peters pointed out that the windows API secretly allows forward slashes instead of backslashes in a path. This won't work with command.com or cmd.exe, but will work for most other stuff (explorer may not like it, though). | Any Ideas? Globing is good (from a Unix user's perspective, anyways ). Also take a look at the os.path module. It may help you. -D _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dsh8290@rit.edu Fri Jul 13 04:04:25 2001 From: dsh8290@rit.edu (D-Man) Date: Thu, 12 Jul 2001 23:04:25 -0400 Subject: [Tutor] raw string notation. In-Reply-To: ; from israel@lith.com on Thu, Jul 12, 2001 at 06:25:58PM -0700 References: Message-ID: <20010712230425.B9794@harmony.cs.rit.edu> On Thu, Jul 12, 2001 at 06:25:58PM -0700, Israel Evans wrote: | Excellent! Thank you! | | I still have troubles with backslashes however... | | In the files, that I'm searching, I'd like to sometimes be able to | have oldword and newword contain a \ character. This shouldn't be a problem. | def wordswap(filename, oldword, newword): | import fileinput | from string import * Bad, bad, bad. Not only is from-import-* considererd poor style when used at the module level, inside a function it has undefined sematnics. I think it is also a bit slower, since it has to iterate over all the names in the string module and then create a local name to match it. BTW, that would happen for each invocation of the function. You don't want that overhead. Instead use "import string", then use "string.replace" instead of "replace". | for line in fileinput.input(filename, 1): print "'%s'" % oldword print "'%s'" % newword print "'%s'" % line print is an excellent debugging tool, and it totaly cross-platform | newline = replace(line, oldword, newword) | print newline, | | It seems that if oldword and newword contain a \ then they never | find anything. The files I'm searching contain paths to resources. | Sometimes instead of changing oneword of the name of the resource, | I want to change both one of the Directories and the name of the resource. | | It seems that this will work in the IDLE interpreter when I'm working | with a list, but not when I'm working with a file. i.e. when in the | for loop I use | for line in list: | newline = replace(line, oldword, newword) | print newline, | | Does anybody know why and what I should do about it that I'm missing? It works in IDLE because it is supposed to work. I haven't used the fileinput module, but my first inclination is to make sure that fileinput.input doesn't do any eval-ing on the text. I'm thinking of the difference between the builtin funcitons input() and raw_input(). Other than that, I would check the dta you have and make sure it really is supposed to match in that context. It may be a bug somewhere else that causes your function to have the wrong data. Use print liberally, and ask "stupid" questions -- the bug is often times a "stupid" oversight somewhere. -D From tutor@python.org Fri Jul 13 04:51:46 2001 From: tutor@python.org (Tim Peters) Date: Thu, 12 Jul 2001 23:51:46 -0400 Subject: [Tutor] ratios with regular expressions, split? In-Reply-To: Message-ID: [kevin parks] > One of the things that i am trying to do is calcualte, > manuipulate, and plain old fondle ratios. I need to be able to > input a series of ratios such as: > > 6/5, 10/9, 9/8, 6/5, 10/9 > > and then split them up in to numerator/denominator pairs for each > one, so that > > 6/5 would be dumped in to 2 variables, say num1, denom1 and > 10/9 would be assigned to say num2, denom2 > > etc... > > > Additionally the ratios might also be input as 7:6 or 7/6 and > some have a different number of digits, like 3/2, 81/80 and > 127/128, etc. Also there is no way to tell in advance if there > will be a series of 3 ratios, 4 ratios, or 53 ratios. What is the > best way to do this? with regex or split? Don't try to do too much at once. Start simple! For example, let's build a regexp to match a single ratio in isolation, possibly surrounded by whitespace: import re _ratio_re = re.compile(""" \s* # skip leading whitespace (\d+) # group 1 has one or more digits [:/] # separated by colon or slash (\d+) # group 2 has one or more digits \s* # skip trailing whitespace $ # and insist we're at the end of the string """, re.VERBOSE).match # Now we can build a parsing function. def parse_ratio(s): """Parse string s as a ratio. Return (numerator, denominator).""" m = _ratio_re(s) if m: n, d = m.groups() return int(n), int(d) else: raise SyntaxError("%r doesn't look like a ratio!" % s) Then get into an interactive shell and *try* it: >>> parse_ratio("1/2") (1, 2) >>> parse_ratio(" 23423:234 ") (23423, 234) >>> parse_ratio("-1/2") Traceback (most recent call last): File "", line 1, in ? parse_ratio("-1/2") File "C:/Python21/ratparse.py", line 21, in parse_ratio raise SyntaxError("%r doesn't look like a ratio!" % s) SyntaxError: '-1/2' doesn't look like a ratio! >>> Play around; see whether or not you're happy with it. If you're not, change the regexp until you are. Soon you'll have a solid building block for doing fancier things. For example, >>> for chunk in "6/5, 10/9, 9/8, 6/5, 10/9".split(','): print parse_ratio(chunk) (6, 5) (10, 9) (9, 8) (6, 5) (10, 9) >>> Regular expressions are very good for parsing simple and, umm, "regular" expressions. They'll drive you nuts if you try to do too much with them, though. I'd leave splitting on whitespace, or by commas (etc), to the string.split() function, which is simpler, quicker and easier to understand for that purpose. > ... > ps. be nice to me it is my birthday (34! Ughh!) and i am all > alone (except for my python book and the interpreter and maybe > some kimchee soup a bit later) You mean it's possible to spend a birthday *not* playing with Python?! Hmm. I doubt I have many birthdays remaining, but I'll give that a try just once . Happy birthday, Kevin! and-wishing-you-34-more-for-starters-ly y'rs - tim From ppathiyi@cisco.com Fri Jul 13 04:56:56 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Fri, 13 Jul 2001 09:26:56 +0530 Subject: [Tutor] Pass by reference References: <045801c10a13$c9b80020$37ef87c0@ppathiyipc> <20010711125756.A6599@harmony.cs.rit.edu> Message-ID: <05e201c10b4f$dcb4e890$37ef87c0@ppathiyipc> I would like to thank Michael, Rob, D-Man, Wesley, Ibraheem, Remco and everybody else who helped me clarify my doubts ... I am continuing with my doubts :-)) Can some one explain the differece between the allocation of variables or objects on the heap and that on the stack ? (May be from the python perspective itself). Also the differece this makes on the scope or life of that variable. One un-related question --> Why was strings made as immutable in python ? Once again thanks to all, Praveen. ----- Original Message ----- From: "D-Man" To: Sent: Wednesday, July 11, 2001 10:27 PM Subject: Re: [Tutor] Pass by reference > On Wed, Jul 11, 2001 at 07:44:24PM +0530, Praveen Pathiyil wrote: > | Hi, > | > | Can we do a "pass by reference" in python ? > > Sort of -- Python always does call-by-value, but the value is always a > reference to an object on the heap. If you assign to the argument, > then, no that won't be seen by the caller (just like C, C++ and Java). > If, instead, the reference refers to a mutable object and you modify > that object then you have the same effect (this is like using pointers > in C/C++ or a reference to a mutable object in Java). > > Don't get bogged down in the implementation details and terminology > though (there can be huge flamewars as to what "pass-by-value" and > "pass-by-reference" really mean). > > | Ex: > | > | ( I would like to know whether there is a way to have the modified > | ex_dict to be visible in modified form in func1 with out explicitly > | returning that ) > | > | def func2(x, ex_dict): > | ex_dict[x] = x*x > | > | def func1(a): > | ex_dict = {} > | func2(a, ex_dict) > | > | func1(2) > > Lets try it : > > >>> def func( x , ex_dict ) : ex_dict[x] = x*x > ... > >>> ex_dict = {} > >>> func( 2 , ex_dict ) > >>> print ex_dict > {2: 4} > >>> > > It works for dictionaries because you didn't modify the reference but > instead modified the referred-to object on the heap. > > If you try and do it with, say, integers it won't work because you > can't modify the integer object on the heap : > > >>> def badfunc( i ) : > ... i = i * i > ... print "in badfunc, i = %d" % i > ... > >>> a = 5 > >>> badfunc( a ) > in badfunc, i = 25 > >>> print a > 5 > >>> > > -D > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ak@silmarill.org Fri Jul 13 05:02:00 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Fri, 13 Jul 2001 00:02:00 -0400 Subject: [Tutor] Pass by reference In-Reply-To: <"from ppathiyi"@cisco.com> References: <045801c10a13$c9b80020$37ef87c0@ppathiyipc> <20010711125756.A6599@harmony.cs.rit.edu> <05e201c10b4f$dcb4e890$37ef87c0@ppathiyipc> Message-ID: <20010713000200.A661@sill.silmarill.org> On Fri, Jul 13, 2001 at 09:26:56AM +0530, Praveen Pathiyil wrote: > I would like to thank Michael, Rob, D-Man, Wesley, Ibraheem, Remco and > everybody else who helped me clarify my doubts ... > > I am continuing with my doubts :-)) > Can some one explain the differece between the allocation of variables or > objects on the heap and that on the stack ? (May be from the python > perspective itself). > Also the differece this makes on the scope or life of that variable. > > One un-related question --> Why was strings made as immutable in python ? For performance reasons. > > Once again thanks to all, > Praveen. > > ----- Original Message ----- > From: "D-Man" > To: > Sent: Wednesday, July 11, 2001 10:27 PM > Subject: Re: [Tutor] Pass by reference > > > > On Wed, Jul 11, 2001 at 07:44:24PM +0530, Praveen Pathiyil wrote: > > | Hi, > > | > > | Can we do a "pass by reference" in python ? > > > > Sort of -- Python always does call-by-value, but the value is always a > > reference to an object on the heap. If you assign to the argument, > > then, no that won't be seen by the caller (just like C, C++ and Java). > > If, instead, the reference refers to a mutable object and you modify > > that object then you have the same effect (this is like using pointers > > in C/C++ or a reference to a mutable object in Java). > > > > Don't get bogged down in the implementation details and terminology > > though (there can be huge flamewars as to what "pass-by-value" and > > "pass-by-reference" really mean). > > > > | Ex: > > | > > | ( I would like to know whether there is a way to have the modified > > | ex_dict to be visible in modified form in func1 with out explicitly > > | returning that ) > > | > > | def func2(x, ex_dict): > > | ex_dict[x] = x*x > > | > > | def func1(a): > > | ex_dict = {} > > | func2(a, ex_dict) > > | > > | func1(2) > > > > Lets try it : > > > > >>> def func( x , ex_dict ) : ex_dict[x] = x*x > > ... > > >>> ex_dict = {} > > >>> func( 2 , ex_dict ) > > >>> print ex_dict > > {2: 4} > > >>> > > > > It works for dictionaries because you didn't modify the reference but > > instead modified the referred-to object on the heap. > > > > If you try and do it with, say, integers it won't work because you > > can't modify the integer object on the heap : > > > > >>> def badfunc( i ) : > > ... i = i * i > > ... print "in badfunc, i = %d" % i > > ... > > >>> a = 5 > > >>> badfunc( a ) > > in badfunc, i = 25 > > >>> print a > > 5 > > >>> > > > > -D > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From dsh8290@rit.edu Fri Jul 13 05:57:48 2001 From: dsh8290@rit.edu (D-Man) Date: Fri, 13 Jul 2001 00:57:48 -0400 Subject: [Tutor] Pass by reference In-Reply-To: <05e201c10b4f$dcb4e890$37ef87c0@ppathiyipc>; from ppathiyi@cisco.com on Fri, Jul 13, 2001 at 09:26:56AM +0530 References: <045801c10a13$c9b80020$37ef87c0@ppathiyipc> <20010711125756.A6599@harmony.cs.rit.edu> <05e201c10b4f$dcb4e890$37ef87c0@ppathiyipc> Message-ID: <20010713005748.A9950@harmony.cs.rit.edu> On Fri, Jul 13, 2001 at 09:26:56AM +0530, Praveen Pathiyil wrote: | I would like to thank Michael, Rob, D-Man, Wesley, Ibraheem, Remco and | everybody else who helped me clarify my doubts ... You're welcome. | Also the differece this makes on the scope or life of that variable. Scope and lifetime are often related, but are actually separate issues. Scope is determined entirely by the language definition. In Python new classes and new functions define new scope. In C/C++/Java curly braces define a new scope (basically every block of code starts a new scope, but has access to outer scopes). Variables on the stack live only as long as the function call. Once the function returns they are popped off the stack. Heap variables live as long as you want them to, up to program termination. In Python they are cleaned up for you by the ref counting or gc. In C/C++ you must explicitly free() or 'delete' them when you are done. | I am continuing with my doubts :-)) | Can some one explain the differece between the allocation of variables or | objects on the heap and that on the stack ? (May be from the python | perspective itself). All Python objects are on the heap. This makes it simple :-). In C, C++ or Java you have both a stack and a heap. Take the following C code, for example, void func() { int j ; /* this is a stack variable */ int* k ; /* this is a basically reference, the refernce is a stack * variable but it refers to data on the heap */ /* this inizializes the memory allocated to j to have the value 2 */ j = 2 ; /* this requests some memory (for a single integer) and lets k * refer to that chunk of memory */ k = malloc( 1 * sizeof( int ) ) ; /* pointer dereferencing is explicit in C (that's what the '*' * does), * this initializes the memory refered to by k's value to have the * value 5 */ *k = 5 ; } If I call this function, function() a new "stack frame" is added to the runtime stack. This stack frame holds all the state the runtime needs to deal with function calls -- the address of the next instruction following the function call, all local variables for the function, (other stuff?). The variable 'j' lives on the stack so it is "automatically" freed when the function returns. It can be used "normally" (in a python sense). The variable 'k' is also on the stack, but it is a pointer (reference). Its value isn't usually directly useful (it is a memory address) but it can point to memory on the heap (ie the call to 'malloc'). The 'malloc' library marks the heap memory as in-use. The pointer must be explicitly dereferenced in C (this is automatic in Python) in order to access the heap memory it refers to. When the function returns, 'j' and 'k' are both popped off the stack. However, the heap memory that k referred to is still flagged as in-use even though nothing refers to it because I didn't free() it. This is known as a memory leak. That heap memory will be allocated until the program terminates. I'm sure that I've completely confused you now, but don't worry about it -- you're using Python, not C. The reason I jumped to C here is because C (and C++) programmers must worry about stack allocated vs. heap allocated objects in their program design and implementation. In Python all objects live on the heap and are "garbage collected" for you. Python does have a stack (that is how it knows where to return to when a function returns) but the only thing in the stack are _references_ to heap objects (local variables in functions). There are no _objects_ on the Python stack. Basically you don't need to worry about it unless you want to go deeper into computer and programming language operation and want to learn a language like C or C++ where memory management is the programmer's responsibility, rather than taken care of by the interpreter. | One un-related question --> Why was strings made as immutable in python ? I don't know, but I bet Tim Peters does . My guesses are as follows : o simpler to implement o can be "interned" (cached?) because they can't be changed o umm, probably because C strings aren't the most pleasant structures to deal with and python was implemented in C (BTW Java's java.lang.String are also immutable and this is the basis for strings in Jython) HTH, -D From lonetwin@yahoo.com Fri Jul 13 08:43:26 2001 From: lonetwin@yahoo.com (steve) Date: Fri, 13 Jul 2001 13:13:26 +0530 Subject: [Tutor] file I/O In-Reply-To: <20010712084804.A1074@pino.selwerd.nl> References: <01071211450601.03093@mercury.in.cqsl.com> <20010712084804.A1074@pino.selwerd.nl> Message-ID: <01071313132601.02506@mercury.in.cqsl.com> Hi there, Thanx Danny an' Remco, well, I kinda see what U mean, though I now have=20 to figure out when using fileinput would be a *GOOD* thing...but :) I guess, (like it's said) when the problem comes, there shall be one obvi= ous way to solve it :) Thanx again Steve On Thursday 12 July 2001 12:18, you wrote: > On 0, steve wrote: > > =09I've been meaning to ask this question for a long time now, > > I've always seen ppl do file i/o, especially file read using an open(= ) > > followed by a loop of readline(), stripping the '\n' at the end.... > > I discovered fileinput (the module) quite early on when I started > > learning python....so I always do things like > > > > Python 2.1 (#3, Jun 25 2001, 13:39:27) > > [GCC 2.95.3 19991030 (prerelease)] on linux2 > > Type "copyright", "credits" or "license" for more information. > > > > >>> import fileinput > > >>> p =3D [ line.strip() for line in fileinput.input("myfile.txt") ] > > > > =09What bothers me is that I don't see enough ppl do that, an' I wond= er is > > it b'cos it is some kinda *Bad thing* ....could n e one comment on th= is > > ??? [ Remco ] : > > Well, not a bad thing, but I think you lose most of the advantages of > fileinput (not reading in the whole file at once, for one). On the othe= r > hand, fileinput will probably give a small performance hit because it h= as > to supply these things, and the strip() in the list comprehension are m= inor > slowdowns as well. > > If you need the whole file in lines, but without \n, the easiest way is= to > read it all in and to split on \n: > > p =3D open("myfile.txt","r").read().split("\n") > [ Danny ] : The fileinput module itself isn't bad: if you have familiarity with the Perl programming language, you might recognize fileinput as an analog to the magic '<>' operator. When using fileinput.input(), we can actually leave it's input argument blank. To show this, let's make a fast 'one-liner' program. ### import fileinput; print ''.join([l.strip() for l in fileinput.input()]) ### This one-liner program takes any text file, and turns it into one long line. As we can see, there's no filename involved: fileinput()'s usefulness comes from the fact that it will automagically look for its input from filenames given at the prompt or standard input. Here are a few sample runs: ### [dyoo@tesuque dyoo]$ python makeOneLiner.py=20 hello world this is a test of the emergency broadcast system. [At this point, I press Ctrl-d a few times to indicate the end of input.] hello worldthis is a testof the emergency broadcastsystem. [dyoo@tesuque dyoo]$ cat foo.txt hello again This is a another test of the emergency broadcast system. [dyoo@tesuque dyoo]$ python makeOneLiner.py foo.txt hello againThis is a another test of the emergencybroadcast system. ### This obscure program makes everything hard to read. --=20 |||||||||||||||||||||| |||||||||#####|||||||| ||||||||#######||||||| ||||||||# O O #||||||| ||||||||#\ ~ /#||||||| ||||||##||\_/||##||||| |||||#||||||||||##|||| ||||#||||||||||||##||| ||||#|||||||||||||##||=09 |||/\##|||||||||##/\||=09 |/ \#########/ \=09 |\ \#######/ /=09 ||\____/#######\____/|=09 =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=09 Debug is human, de-fix divine. =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 From dyoo@hkn.eecs.berkeley.edu Fri Jul 13 10:02:13 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 Jul 2001 02:02:13 -0700 (PDT) Subject: [Tutor] Pass by reference [memory management details] In-Reply-To: <05e201c10b4f$dcb4e890$37ef87c0@ppathiyipc> Message-ID: On Fri, 13 Jul 2001, Praveen Pathiyil wrote: > I am continuing with my doubts :-)) > Can some one explain the differece between the allocation of variables or > objects on the heap and that on the stack ? (May be from the python > perspective itself). > Also the differece this makes on the scope or life of that variable. [Warning: this is a long message, and may induce yawning.] Python objects are allocated on the heap. We can look at memory as a huge flat block, sorta like this: +--------------+----------------------------+--------------+ | stack ---> | UNALLOCATED SPACE | <--- heap | +--------------+----------------------------+--------------+ Computer memory is used to keep track of details. In a programming language, there are two main questions the computer needs to keep asking itself: where are we in the program, and what objects are we using? Let's tackle the object topic first. Every time we create a new object, Python asks the underlying memory system to chop off a little more unallocated memory to make the heap side grow more. Python will use this newly allocated memory to save the state of that object. Python also uses a small chunk of each object to save a "reference count", an integer that keeps track of how many different ways we can "refer" to an object. We can even ask Python what the reference count of a variable is in our own programs by using the sys.getrefcount() function. ### >>> x = 'I am a string' >>> sys.getrefcount(x) 2 >>> y = x >>> sys.getrefcount(x) 3 >>> del y >>> sys.getrefcount(x) 2 ### Visually, the situation might look like this: data refcount +--------------------+-------+ | 'I am a string' | 3 | +--------------------+-------+ ^ ^ ^ x ---------+ | | | | | | y --------------+ | | | whatever-sys.refcount() | -calls-its-first-argument ---+ And this is just one small block out of the vastness that is the memory heap. It's pretty amazing how much detail is there. (And this description itself is a simplification of what REALLY happens!) If you're wondering why we get a refcount of 3 instead of 2, it's because the very act of inspecting the object 'I am a string' means that we need to pass the object off as an argument to the sys.getrefcount() function, and this argument passing raises the reference count up by one! This is what accounts for the optimistic counting. As soon as the refcount of an object goes to zero, Python can give back the memory to the pool of unallocated space. This is the idea of reference counting: let's count how many 'variables' refer to an object, and wait. When that count goes to zero, we should recycle the memory, because there's no way we'll be using that object, ever. Recycling is good! Our computers still don't have infinite memory: that flat block of memory has boundaries that we can't cross, so we are good neighbors and make do as best we can. Hopefully, this gives some idea of what the heap's is: the heap is used to store allocated objects, the things that actually hold things like strings, integers, lists, and other things, large and small. But it's not enough just to know what objects we're dealing with: we also need to keep track of location, that is, where we are in a program. Let's take a toy program and clarify what we mean by "where we are". ### def hypotenuse(a, b): return sqrt(square(a) + square(b)) def square(x): return x * x def sqrt(x): return x**0.5 if __name__ == '__main__': print "The hypotenuse of a triangle with sides 3 and 4 is", print hypotenuse(3, 4) ### If we run this program, we have an intuitive notion that there's some sort of path that we take: we jump from the "__main__" part off to the hypotenuse() part, which jumps on and off the square() part twice, passes through sqrt, and finally goes back home. So there's a flow, a weaving back and forth between the functions. What's important to see is that just storing the line number isn't enough to figure out the flow. For example, let's say that we just finished computing the square() of something, as part of some larger calculation. The problem now is: who does square() give its result back to? If we just know that we finished the square() function, we get lost: we need the prior history of the way we got to square(). That history is what the stack stores: the stack saves the information of a parent function so that, after a "helper" function is done, the parent can continue on its way. ### Main if statement print 'The hypotenuse ...' ==> hypotenuse(3, 4) ==> square(3) return 9 ==> square(4) return 16 ==> add them with + return 25 ==> sqrt(25) return 5 return 5 print 5 ### The idea of a stack is intrinsically tied to function calling. Not only does Python keep track of what line number we're on, but it also "pushes" and "pops" this function information on the stack. In Python, this is the primary thing that the stack saves for us. (If anyone is still reading: this explains why Python complains of a "Stack Overflow" when a recursive procedure goes out of control: the stack just gets too large, and smashes right into the heap on the other side of memory. Not good.) I know I'm being very handwavy, but there are just so many details involved. Usually, it's better to let Python handle this stuff. And my fingers are getting tired. *grin* Good luck to you! From lonetwin@yahoo.com Fri Jul 13 10:43:12 2001 From: lonetwin@yahoo.com (steve) Date: Fri, 13 Jul 2001 15:13:12 +0530 Subject: [Tutor] Born from : [memory management details] In-Reply-To: References: Message-ID: <01071315114400.00797@mercury.in.cqsl.com> Hi there, D-man and Danny Yoo, that explanation 'bout the stack and the heap was ^^REAL^^ good !! The best part is I understood all of it :) (even though I've just begun programming). Now you've got me hooked !... =2E..eh...I'd like somebody to point me to some resource (online or a=20 book maybe) that explains such low level details....to push it even more =2E..I'd like n e resource that explains low level details of things like networks/OS operation ...stuff like that !! Hope I ain't bugging ne one,=20 It's just that I feel good I just learned my new-thing-for-the-day Peace Steve --=20 |||||||||||||||||||||| |||||||||#####|||||||| ||||||||#######||||||| ||||||||# O O #||||||| ||||||||#\ ~ /#||||||| ||||||##||\_/||##||||| |||||#||||||||||##|||| ||||#||||||||||||##||| ||||#|||||||||||||##||=09 |||/\##|||||||||##/\||=09 |/ \#########/ \=09 |\ \#######/ /=09 ||\____/#######\____/|=09 =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=09 Debug is human, de-fix divine. =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 From arcege@speakeasy.net Fri Jul 13 13:28:23 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Fri, 13 Jul 2001 08:28:23 -0400 (EDT) Subject: [Tutor] Please Critque Tkinter Class for Newbie In-Reply-To: <1098889D5B13@kserver.org> from "Sheila King" at Jul 12, 2001 12:41:58 PM Message-ID: <200107131228.f6DCSOW02781@dsl092-074-184.bos1.dsl.speakeasy.net> Sheila King wrote > OK, but if one has a class derived from the Tkinter Frame Widget that > has several other types of widgets on it (such as a button and a label > and so forth), and those items are placed on the Frame subclass with the > pack manager, then won't this incompatibility still exist? (i.e. someone > will not then be able to place the Frame subclass on another widget > unless they use the place geometry manager???). Or maybe not. OK, I will > experiment with this. (I haven't tried using grid(), yet...) Each widget inside a single container needs to use the same geometry manager. But outside of that, they can be different. >>> from Tkinter import * >>> root1 = Tk() >>> frame11 = Frame(root1, relief=GROOVE, bd=2) >>> frame12 = Frame(root1, relief=GROOVE, bd=2) >>> Button(frame11, text='0,0').grid(row=0, column=0) >>> Button(frame11, text='0,1').grid(row=0, column=1) >>> Button(frame11, text='1,0').grid(row=1, column=0) >>> Button(frame11, text='1,1').grid(row=1, column=1) >>> Label(frame12, text='top' ).pack(side=TOP) >>> Label(frame12, text='bottom').pack(side=BOTTOM) >>> Label(frame12, text='left' ).pack(side=LEFT) >>> Label(frame12, text='right' ).pack(side=RIGHT) >>> frame11.place(relx=0, rely=0, relwidth=0.5, relheight=0.5, anchor=NW) >>> frame12.place(relx=1, rely=1, relwidth=0.5, relheight=0.5, anchor=SE) >>> root1.mainloop() Each frame (including the root widget) is using a different geometry manager, but all the widgets in an enclosing widget (root1, frame11, or frame12) must use the same manager. I.e., both frames are place'd in root1, but all the buttons are grid'd in frame11 and all the labels are pack'd into frame12. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From kp87@lycos.com Fri Jul 13 15:32:58 2001 From: kp87@lycos.com (kevin parks) Date: Fri, 13 Jul 2001 23:32:58 +0900 Subject: [Tutor] arg exceptions for scrips Message-ID: Below is my little copy thing which does nothing but copy a file. It works, but i would like be able to use it as a script and a module. So here i have it wired up for the usual __name__, run as main thing. The problem is that the cp() func takes 2 args. So i tried to patch it up so that when i typed: % cp.py foo.txt bar.txt it executed the cp() function and passes the 2 command line arguments to the func itself. I don't know if this is the standard way to do this or my kludge but it works, except the if len(sys.argv) < 2: part. What i want it to is complain if it doesn't get exactly 2 arguments and i want to to say: "Usage: infile outfile" or something close to that and then exit. But it doesn't Python itself complains if the args aren't right and i get: [localhost:~/scripts] kevin% python cp.py scales.txt Traceback (most recent call last): File "cp.py", line 28, in ? cp(sys.argv[1],sys.argv[2]) IndexError: list index out of range for less than 2 args (and nothing yet for more than 2). Is there no way to tell python to chill and print the exception and usage i want? This way if someone other than me executes this script they can know what the expected arguements are rather than knowing: cp(sys.argv[1],sys.argv[2]) IndexError: list index out of range Which is useless for the end user. #!/usr/bin/env python import os import sys def cp(infilename, outfilename): """this will copy a file exactly, args are: 'infile' and 'outfile'""" infile = open(infilename, 'r') f = open(outfilename, 'w') for aLine in infile.xreadlines() : f.write( aLine ) infile.close() f.close() # if used as a script we have to pass the args from the # shell command-line to the function above. If there are # not exactly 2 args, complain and quit. if __name__ == '__main__': if len(sys.argv) < 2: print "Usage:", sys.argv[0], "infile outfile" sys.exit(1) else: cp(sys.argv[1],sys.argv[2]) Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From ggates@appliedtheory.com Fri Jul 13 16:01:26 2001 From: ggates@appliedtheory.com (George Gates) Date: Fri, 13 Jul 2001 11:01:26 -0400 Subject: [Tutor] arg exceptions for scrips In-Reply-To: Message-ID: <5.0.2.1.0.20010713105404.02c2ad30@franklin.appliedtheory.com> >if __name__ == '__main__': > if len(sys.argv) < 2: > print "Usage:", sys.argv[0], "infile outfile" > sys.exit(1) > else: > cp(sys.argv[1],sys.argv[2]) The problem is the test of the length should be less than 3, not less than 2. If you executed with only one argument the length of sys.argv would be 2, sys.argv[0] for the script name, sys.argv[1] for the argument: ggates@ggates ggates]$ more arg_count.py #!/usr/bin/env python import sys print "The number of arguments are %s: %s" % (len(sys.argv),sys.argv) [ggates@ggates ggates]$ ./arg_count.py file1 The number of arguments are 2: ['./arg_count.py', 'file1'] [ggates@ggates ggates]$ At 11:32 PM 7/13/2001 +0900, kevin parks wrote: >Below is my little copy thing which does nothing but copy a file. It works, >but i would like be able to use it as a script and a module. So here i have it >wired up for the usual __name__, run as main thing. The problem is that >the cp() >func takes 2 args. So i tried to patch it up so that when i typed: > >% cp.py foo.txt bar.txt > >it executed the cp() function and passes the 2 command line arguments to >the func itself. I don't know if this is the standard way to do this or my >kludge but it works, except the if len(sys.argv) < 2: part. What i want it to >is complain if it doesn't get exactly 2 arguments and i want to to say: >"Usage: infile outfile" or something close to that and then exit. But it >doesn't >Python itself complains if the args aren't right and i get: > >[localhost:~/scripts] kevin% python cp.py scales.txt >Traceback (most recent call last): > File "cp.py", line 28, in ? > cp(sys.argv[1],sys.argv[2]) >IndexError: list index out of range > > >for less than 2 args (and nothing yet for more than 2). Is there no >way to tell python to chill and print the exception and usage i want? >This way if someone other than me executes this script they can know what >the expected arguements are rather than knowing: >cp(sys.argv[1],sys.argv[2]) >IndexError: list index out of range > >Which is useless for the end user. > > > > >#!/usr/bin/env python > >import os >import sys > >def cp(infilename, outfilename): > """this will copy a file exactly, args are: 'infile' and 'outfile'""" > infile = open(infilename, 'r') > f = open(outfilename, 'w') > for aLine in infile.xreadlines() : > f.write( aLine ) > infile.close() > f.close() > ># if used as a script we have to pass the args from the ># shell command-line to the function above. If there are ># not exactly 2 args, complain and quit. > >if __name__ == '__main__': > if len(sys.argv) < 2: > print "Usage:", sys.argv[0], "infile outfile" > sys.exit(1) > else: > cp(sys.argv[1],sys.argv[2]) > > > >Get 250 color business cards for FREE! >http://businesscards.lycos.com/vp/fastpath/ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor George H. Gates System Administrator - OSOS Implementation Phone: (315) 453-2912 x5671 Email: ggates@appliedtheory.com Web: http://ggates.appliedtheory.com From kp87@lycos.com Fri Jul 13 16:26:11 2001 From: kp87@lycos.com (kevin parks) Date: Sat, 14 Jul 2001 00:26:11 +0900 Subject: [Tutor] arg exceptions for scrips Message-ID: Oh, dopey me! I looked right past that thinking anticipating what that problem was. So what i really want is: if len(sys.argv) != 3: and not: if len(sys.argv) != 2: Thank you! On Fri, 13 Jul 2001 11:01:26 George Gates wrote: > >>if __name__ == '__main__': >> if len(sys.argv) < 2: >> print "Usage:", sys.argv[0], "infile outfile" >> sys.exit(1) >> else: >> cp(sys.argv[1],sys.argv[2]) > >The problem is the test of the length should be less than 3, not less than >2. If you executed with only one argument the length of sys.argv would be >2, sys.argv[0] for the script name, sys.argv[1] for the argument: > >ggates@ggates ggates]$ more arg_count.py > >#!/usr/bin/env python >import sys >print "The number of arguments are %s: %s" % (len(sys.argv),sys.argv) > >[ggates@ggates ggates]$ ./arg_count.py file1 > >The number of arguments are 2: ['./arg_count.py', 'file1'] > >[ggates@ggates ggates]$ Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From Mark.Tobin@attcanada.com Fri Jul 13 18:21:59 2001 From: Mark.Tobin@attcanada.com (Tobin, Mark) Date: Fri, 13 Jul 2001 11:21:59 -0600 Subject: [Tutor] RE: Newbie list question Message-ID: <3D7C088D6CCFD31190A5009027D30E910339104F@torex004.attcanada.ca> Does: foo += 'c' act like an append then? I always assumed it was the same as: foo = foo + 'c' which obviously should raise a TypeError. Here however it works, in that it appends 'c' to the object to which foo refers and thus to the object to which bar refers... Mark -----Original Message----- From: python-list-admin@python.org [mailto:python-list-admin@python.org]On Behalf Of Joshua Marshall Sent: Friday, July 13, 2001 12:52 PM To: python-list@python.org Subject: Re: Newbie list question Matthew Alton wrote: ... >>>> foo = ['a', 'b', 'c'] # We have a list named 'foo.' Excellent. >>>> bar = foo # bar points to foo. Or does it? bar points to the same object that foo points to. It's not the case that bar is an alias for foo. >>>> baz = foo[:] # baz is a copy of foo. For clarity, it might be better to say baz points to a copy of the list which foo points to. >>>> foo > ['a', 'b', 'c'] >>>> bar > ['a', 'b', 'c'] >>>> baz > ['a', 'b', 'c'] # So far, so good. >>>> del foo[2] # Get rid of 'c' in foo and, therefore in > bar (?) >>>> foo > ['a', 'b'] # 'c' is gone from foo... >>>> bar > ['a', 'b'] # ... and also from bar, as expected. >>>> baz > ['a', 'b', 'c'] # baz, the copy, is unaffected. Also as > expected. >>>> foo = foo + ['c'] # Add 'c' back to foo. Here, the variable foo is rebound to a new list. The previous list (which bar still points to) is unaffected. If you had done "foo.append('c')" instead of "foo = foo + ['c']", than a 'c' would be appended to the list object that foo and bar both still refer to. -- http://mail.python.org/mailman/listinfo/python-list From Mark.Tobin@attcanada.com Fri Jul 13 18:27:41 2001 From: Mark.Tobin@attcanada.com (Tobin, Mark) Date: Fri, 13 Jul 2001 11:27:41 -0600 Subject: [Tutor] RE: Newbie list question Message-ID: <3D7C088D6CCFD31190A5009027D30E9103391051@torex004.attcanada.ca> Sorry this was meant for python-list... mea culpa Mark -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Tobin, Mark Sent: Friday, July 13, 2001 1:22 PM To: 'Joshua Marshall'; 'Matthew.alton@anheuser-busch.com'; 'tutor@python.org' Subject: [Tutor] RE: Newbie list question Does: foo += 'c' act like an append then? I always assumed it was the same as: foo = foo + 'c' which obviously should raise a TypeError. Here however it works, in that it appends 'c' to the object to which foo refers and thus to the object to which bar refers... Mark -----Original Message----- From: python-list-admin@python.org [mailto:python-list-admin@python.org]On Behalf Of Joshua Marshall Sent: Friday, July 13, 2001 12:52 PM To: python-list@python.org Subject: Re: Newbie list question Matthew Alton wrote: ... >>>> foo = ['a', 'b', 'c'] # We have a list named 'foo.' Excellent. >>>> bar = foo # bar points to foo. Or does it? bar points to the same object that foo points to. It's not the case that bar is an alias for foo. >>>> baz = foo[:] # baz is a copy of foo. For clarity, it might be better to say baz points to a copy of the list which foo points to. >>>> foo > ['a', 'b', 'c'] >>>> bar > ['a', 'b', 'c'] >>>> baz > ['a', 'b', 'c'] # So far, so good. >>>> del foo[2] # Get rid of 'c' in foo and, therefore in > bar (?) >>>> foo > ['a', 'b'] # 'c' is gone from foo... >>>> bar > ['a', 'b'] # ... and also from bar, as expected. >>>> baz > ['a', 'b', 'c'] # baz, the copy, is unaffected. Also as > expected. >>>> foo = foo + ['c'] # Add 'c' back to foo. Here, the variable foo is rebound to a new list. The previous list (which bar still points to) is unaffected. If you had done "foo.append('c')" instead of "foo = foo + ['c']", than a 'c' would be appended to the list object that foo and bar both still refer to. -- http://mail.python.org/mailman/listinfo/python-list _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From Matthew.Alton@anheuser-busch.com Fri Jul 13 18:27:51 2001 From: Matthew.Alton@anheuser-busch.com (Alton, Matthew) Date: Fri, 13 Jul 2001 12:27:51 -0500 Subject: [Tutor] RE: Newbie list question Message-ID: It is my understanding that the C-like "+=" was added at 2.0 as syntactic sugar. It is syntactically equivalent. -----Original Message----- From: Tobin, Mark [mailto:Mark.Tobin@attcanada.com] Sent: Friday, July 13, 2001 12:22 PM To: 'Joshua Marshall'; 'Matthew.alton@anheuser-busch.com'; 'tutor@python.org' Subject: RE: Newbie list question Does: foo += 'c' act like an append then? I always assumed it was the same as: foo = foo + 'c' which obviously should raise a TypeError. Here however it works, in that it appends 'c' to the object to which foo refers and thus to the object to which bar refers... Mark -----Original Message----- From: python-list-admin@python.org [mailto:python-list-admin@python.org]On Behalf Of Joshua Marshall Sent: Friday, July 13, 2001 12:52 PM To: python-list@python.org Subject: Re: Newbie list question Matthew Alton wrote: ... >>>> foo = ['a', 'b', 'c'] # We have a list named 'foo.' Excellent. >>>> bar = foo # bar points to foo. Or does it? bar points to the same object that foo points to. It's not the case that bar is an alias for foo. >>>> baz = foo[:] # baz is a copy of foo. For clarity, it might be better to say baz points to a copy of the list which foo points to. >>>> foo > ['a', 'b', 'c'] >>>> bar > ['a', 'b', 'c'] >>>> baz > ['a', 'b', 'c'] # So far, so good. >>>> del foo[2] # Get rid of 'c' in foo and, therefore in > bar (?) >>>> foo > ['a', 'b'] # 'c' is gone from foo... >>>> bar > ['a', 'b'] # ... and also from bar, as expected. >>>> baz > ['a', 'b', 'c'] # baz, the copy, is unaffected. Also as > expected. >>>> foo = foo + ['c'] # Add 'c' back to foo. Here, the variable foo is rebound to a new list. The previous list (which bar still points to) is unaffected. If you had done "foo.append('c')" instead of "foo = foo + ['c']", than a 'c' would be appended to the list object that foo and bar both still refer to. -- http://mail.python.org/mailman/listinfo/python-list From israel@lith.com Fri Jul 13 18:31:52 2001 From: israel@lith.com (Israel Evans) Date: Fri, 13 Jul 2001 10:31:52 -0700 Subject: [Tutor] raw string notation. Message-ID: D-Man, You're Beautiful! And so are all of you other people on this list! Funny thing.. The problem I was having last night seemed to dissapear. I'm not sure exactly what I did, but everything works like you said it should. And about that from module import * thing... I think I've seen it said that that was a bad thing to do so many times, the image became fixed in my head and as a result floated to the top of my consciousness as the only right and proper thing to do! Curse this Deviant Brain of Mine! &>;] -----Original Message----- From: D-Man [mailto:dsh8290@rit.edu] Sent: Thursday, July 12, 2001 8:04 PM To: [tutor] Subject: Re: [Tutor] raw string notation. On Thu, Jul 12, 2001 at 06:25:58PM -0700, Israel Evans wrote: | Excellent! Thank you! | | I still have troubles with backslashes however... | | In the files, that I'm searching, I'd like to sometimes be able to | have oldword and newword contain a \ character. This shouldn't be a problem. | def wordswap(filename, oldword, newword): | import fileinput | from string import * Bad, bad, bad. Not only is from-import-* considererd poor style when used at the module level, inside a function it has undefined sematnics. I think it is also a bit slower, since it has to iterate over all the names in the string module and then create a local name to match it. BTW, that would happen for each invocation of the function. You don't want that overhead. Instead use "import string", then use "string.replace" instead of "replace". | for line in fileinput.input(filename, 1): print "'%s'" % oldword print "'%s'" % newword print "'%s'" % line print is an excellent debugging tool, and it totaly cross-platform | newline = replace(line, oldword, newword) | print newline, | | It seems that if oldword and newword contain a \ then they never | find anything. The files I'm searching contain paths to resources. | Sometimes instead of changing oneword of the name of the resource, | I want to change both one of the Directories and the name of the resource. | | It seems that this will work in the IDLE interpreter when I'm working | with a list, but not when I'm working with a file. i.e. when in the | for loop I use | for line in list: | newline = replace(line, oldword, newword) | print newline, | | Does anybody know why and what I should do about it that I'm missing? It works in IDLE because it is supposed to work. I haven't used the fileinput module, but my first inclination is to make sure that fileinput.input doesn't do any eval-ing on the text. I'm thinking of the difference between the builtin funcitons input() and raw_input(). Other than that, I would check the dta you have and make sure it really is supposed to match in that context. It may be a bug somewhere else that causes your function to have the wrong data. Use print liberally, and ask "stupid" questions -- the bug is often times a "stupid" oversight somewhere. -D _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Fri Jul 13 19:23:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 Jul 2001 11:23:11 -0700 (PDT) Subject: [Tutor] RE: Newbie list question In-Reply-To: <3D7C088D6CCFD31190A5009027D30E910339104F@torex004.attcanada.ca> Message-ID: On Fri, 13 Jul 2001, Tobin, Mark wrote: > Does: > > foo += 'c' > > act like an append then? I always assumed it was the same as: Not exactly like an append(), but very close: it's more like an extend(). ### >>> foo = ['austin', 'powers'] >>> foo += ['international', 'man', 'of', 'mystery'] >>> foo ['austin', 'powers', 'international', 'man', 'of', 'mystery'] ### If we forget the braces though, you're right: we'll hit a TypeError: ### >>> foo = ['Mononoke'] >>> foo += 'Hime' >>> foo ['Mononoke', 'H', 'i', 'm', 'e'] ### ... or not! Wow! I completely forgot that strings can be treated like lists of characters. That was a surprise. *grin* The TypeError SHOULD happen here: ### >>> foo = [1, 2, 3] >>> foo += 4 Traceback (most recent call last): File "", line 1, in ? TypeError: argument to += must be a sequence ### That's better. If we had: letters = ['a' ,'b', 'c'] then to add the letter 'd' to the end of 'letters', we can do these: letters += ['c'] letters = letters + ['c'] letters.append('c') All of these seem to have the same result in assigning 'letters', but they do go about it in different ways. For example, letters = letters + ['c'] creates a temporary list that contains the value of "letters + ['c']", and finally assigns 'letters' to this intermediate value. On the other hand, letters.append() directly influences the contents of the list. Here are three examples that shows that there's a real difference in the methods: ### test of foo = foo + bar >>> x = ['eta', 'kappa'] >>> y = x >>> x = x + ['nu'] >>> x ['eta', 'kappa', 'nu'] >>> y ['eta', 'kappa'] ### ### test of foo += bar >>> x = ['eta', 'kappa'] >>> y = x >>> x += ['nu'] >>> x ['eta', 'kappa', 'nu'] >>> y ['eta', 'kappa', 'nu'] ### [Note: this example shows that x += y is NOT the same as x = x + y when we deal with lists. Be careful!] ### test of foo.append(bar) >>> x = ['eta', 'kappa'] >>> y = x >>> x.append('nu') >>> x ['eta', 'kappa', 'nu'] >>> y ['eta', 'kappa', 'nu'] ### Good luck to you. From lha2@columbia.edu Fri Jul 13 19:54:07 2001 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Fri, 13 Jul 2001 13:54:07 -0500 Subject: [Tutor] why strings immutable Message-ID: <20010713185407.CJDC375207.mtapop3.verizon.net@[192.168.129.36]> Sorry to break out of a thread and not reference the message I'm referring to; I'm using pop for reading mail and a web client to write mail, so everything is awkward right now. Someone had asked, "Why are strings immutable?" Here's a guess: I recall having read that mutable objects are not allowed to be dictionary keys, and it would be a Good Thing to be able to use strings as dictionary keys (otherwise we'd probably want to call dictionaries something else, if they couldn't hold representations of words). From dsh8290@rit.edu Fri Jul 13 20:27:35 2001 From: dsh8290@rit.edu (D-Man) Date: Fri, 13 Jul 2001 15:27:35 -0400 Subject: [Tutor] why strings immutable In-Reply-To: <20010713185407.CJDC375207.mtapop3.verizon.net@[192.168.129.36]>; from vze2f978@verizon.net on Fri, Jul 13, 2001 at 01:54:07PM -0500 References: <20010713185407.CJDC375207.mtapop3.verizon.net@[192.168.129.36]> Message-ID: <20010713152735.G10123@harmony.cs.rit.edu> On Fri, Jul 13, 2001 at 01:54:07PM -0500, Lloyd Hugh Allen wrote: | Someone had asked, "Why are strings immutable?" | | Here's a guess: I recall having read that mutable objects are not | allowed to be dictionary keys More precisely, non-hashable objects aren't allowed to be dict keys. Mutable objects (such as lists) typically are not hashable. | , and it would be a Good Thing to be able to use strings as | dictionary keys (otherwise we'd probably want to call dictionaries | something else, if they couldn't hold representations of words). Sounds like a good idea to me :-). -D From israel@lith.com Fri Jul 13 23:21:39 2001 From: israel@lith.com (Israel Evans) Date: Fri, 13 Jul 2001 15:21:39 -0700 Subject: [Tutor] Scope Issues... Message-ID: Whoo! I sure seem to be on this list a lot lately! Thanks for bearing with me though. Ok.. My latest challenge is causing me headaches.... I've got three little function. The first walks through a directory and builds a list of files that have a specific extension. The second goes through a file and swaps one word with another. The third orchestrates the thing. It calls the first function and gets the list and performs the second function on every item in the list. Where I'm having trouble is in getting the list built by the first function. At first, I defined the empty list in the top function and had that function return the list after I've added stuff to it. It seems the list goes out of scope when I do it this way. Then I tried making the list a global variable and by having the top function returning, I would thereby change the list. It seems that when I do it this way I get "local variable 'result' referenced before assignment". And it seems that this error is called both for the top function and the one that recurses over the values of the list. I've been reading the documentation, but it seems I'm not understanding some of the basic scoping issues. Any suggestions? Most-repeatedly yours, ~Israel~ From dsh8290@rit.edu Sat Jul 14 00:16:32 2001 From: dsh8290@rit.edu (D-Man) Date: Fri, 13 Jul 2001 19:16:32 -0400 Subject: [Tutor] Scope Issues... In-Reply-To: ; from israel@lith.com on Fri, Jul 13, 2001 at 03:21:39PM -0700 References: Message-ID: <20010713191632.D10492@harmony.cs.rit.edu> On Fri, Jul 13, 2001 at 03:21:39PM -0700, Israel Evans wrote: | | Whoo! I sure seem to be on this list a lot lately! Thanks for bearing | with me though. | | | Ok.. My latest challenge is causing me headaches.... | | I've got three little function. | | The first walks through a directory and builds a list of files that have a | specific extension. | The second goes through a file and swaps one word with another. | The third orchestrates the thing. It calls the first function and gets the | list and performs the second function on every item in the list. | | Where I'm having trouble is in getting the list built by the first function. | | At first, I defined the empty list in the top function and had that function | return the list after I've added stuff to it. | It seems the list goes out of scope when I do it this way. Unless you do something really weird, the reference to the list doesn't go out of scope until the function returns. | Then I tried making the list a global variable and by having the top | function returning, I would thereby change the list. It seems that when I | do it this way I get "local variable 'result' referenced before assignment". | And it seems that this error is called both for the top function and the one | that recurses over the values of the list. If you have something like this : bar = [] def foo() : print bar bar = bar + [ baz ] you will get that error message. Basically the assignment in the function means that bar is a local variable. Then you try and print bar (the local variable) before you have created it. In old (pre 2.1's nested scopes) python it wouldn't have been an error but it would have been a subtle bug : sometimes you would refer to the global 'bar' and sometimes the 'local' bar which overshadows the global bar. Bad. | I've been reading the documentation, but it seems I'm not understanding some | of the basic scoping issues. Any suggestions? Show us the code, then we can show you the problem you really have. Otherwise we have to guess at what is confusing you :-). -D From csmith@blakeschool.org Sat Jul 14 04:47:49 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Fri, 13 Jul 2001 22:47:49 -0500 Subject: [Tutor] Sorting against another list Message-ID: Remco Gerlich wrote: > On 0, Sharriff Aina wrote: > > I have a list that is created dynamically, how do I sort this list so that > > it matches amother "mater template" list? > > > > example: > > [ 'aa', 'qq', 'ttt', 'hh'] # master list > > > > my dynamic list cotains all or only a few of the elements in the master > > list: > > > > ['ttt', 'hh', 'aa'] ### i would like to sort it to produce ['aa''ttt', > > 'hh'] accoriding to the sequense in the master list > > > > or [ 'hh', 'qq' 'ttt'] ### would like ['qq', 'ttt', 'hh'] > > > > I would like to sort these example list so that they at least follow the > > order of the master list. > > Hmm. Ok, we have two lists: 'master' and 'dynamic'. > > You can give an argument to .sort(), an alternative way to compare two > items. You want to compare them using the order of the master list. The > easiest way to spell that is this: > > def compare_using_master_list(a, b): > # Compare the indices of the two items in the master list > return cmp(master.index(a), master.index(b)) > > dynamic.sort(compare_using_master_list) > Or to be able to allow *any* list to be used as your master, def cmp_using(l): return lambda a,b: cmp(l.index(a), l.index(b)) dynamic.sort(cmp_using(master)) > > def compare_using_master_cache(a, b): > # Compare the cached index values of a and b > return cmp(cachedict[a], cachedict[b]) > > dynamic.sort(compare_using_master_cache) > You can do the same sort of trick here, too. > This should be faster with all but the most trivial lists (but I didn't test > it). > I tested it and it was significantly faster--about 3x for n=100, but then because the list lookup approach is O(n^2) it gets significantly slower as n increases. Here are the times for using the dictionary approach n seconds method # 10 0.00168800354 Sort(master(d)) # 100 0.010548114777 Sort(master(d)) # 1000 0.184627056122 Sort(master(d)) # 3000 0.680903911591 Sort(master(d)) ...and using the list approach # 10 0.0014672279358 Sort(master(l)) # 100 0.031841278076 Sort(master(l)) # 1000 3.28976583481 Sort(master(l)) # 3000 34.4554972649 Sort(master(l)) Slightly faster than the dictionary approach was the approach below which adds indices to the master list and then appends these indices onto the dynamic list, sorts it, and then removes the indices. It uses the zip(l1,l2) function which is equivalent to map(None,l1,l2). # 10 0.0011219978332 sortwrt # 100 0.0105338096619 sortwrt # 1000 0.136965751648 sortwrt # 3000 0.47709608078 sortwrt def sortwrt(l,master): #return l sorted wrt master '''Sort a list using a master list for the sort order.''' # # Indices are zipped into the master and then both # lists are sorted. Then the elements of the list get # the indices linked in, a sort is performed on the indices # and then the indices are removed. All modifications to # the list are done in place. If an item does not appear # in the master, a statement is printed and a normally sorted # list is returned. # # Christopher P. Smith, 7/13/2001 # ml=master+[] ml=zip(ml,range(len(ml))) ml.sort() l.sort() i=j=0 imax,jmax=len(l),len(ml) while iml[j][0]: j+=1 if j==jmax: #this is an error condition...perhaps raise an exception print l[i],"not found in master." imax=i #this is how many modifications will need to be undone else: l.sort() # # Now remove the sorting keys # # Note: must modify in place rather than doing something like # 'l=[i[1] for i in l]' # which would create a local l and not affect the original # for k in range(imax): l[k]=l[k][1] /c From csmith@blakeschool.org Sat Jul 14 05:01:36 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Fri, 13 Jul 2001 23:01:36 -0500 Subject: [Tutor] Unzip Message-ID: Here's a piece of useless code which extracts lists that have been zipped together (or mapped together with None: map(Nane,l1,l2) is the same as zip(l1,l2) Does anyone use something else to do this? ---code start--- def unzip(l,*jj): '''Return all (if none are specified) or some elements in the tuples of l that were zipped together. ''' # # Christopher P. Smith 7/13/2001 # if jj==(): jj=range(len(l[0])) rl = [[li[j] for li in l] for j in jj] # a list of lists if len(rl)==1: rl=rl[0] #convert list of 1 list to a list return rl a=[1,2,3] b=[4,5,6] c=[7,8,9] l=zip(a,b,c) x,y,z= unzip(l) # get them all: x=[1,2,3], y=[4,5,6], z=[7,8,9] y=unzip(l,1) # get the 1th one: y as above x,z=unzip(l,0,2)# get the 0th and 2th ones: x and z as above ---code end--- /c From ppathiyi@cisco.com Sat Jul 14 09:20:49 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Sat, 14 Jul 2001 13:50:49 +0530 Subject: [Tutor] Pass by reference [memory management details] References: Message-ID: <075801c10c3d$e4055e60$37ef87c0@ppathiyipc> Thanks Danny ... The explanation is too good. ----- Original Message ----- From: "Danny Yoo" To: "Praveen Pathiyil" Cc: "D-Man" ; Sent: Friday, July 13, 2001 2:32 PM Subject: Re: [Tutor] Pass by reference [memory management details] From dyoo@hkn.eecs.berkeley.edu Sat Jul 14 09:58:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 14 Jul 2001 01:58:11 -0700 (PDT) Subject: [Tutor] Another source of Python tutorials Message-ID: Hi everyone, http://www.devshed.com/Server_Side/Python/ is running a series of introductory tutorials on Python as well. The tutorials there look pretty good --- many of them concentrate on the CGI side of Python that may interest people here. From kp87@lycos.com Sat Jul 14 10:14:55 2001 From: kp87@lycos.com (kevin parks) Date: Sat, 14 Jul 2001 18:14:55 +0900 Subject: [Tutor] Unzip Message-ID: Wow, i had no idea that there was a built-in called zip. I rolled my own, but called it lace (like a shoe) and even have an "unlace", but i think, inferior to your Unzip, which also does x,z=unzip(l,0,2).: def lace(*lists): """lace: forms a list by interlacing elements from several lists. e.g.: a=[1,2,3,4]; b=[100,101,102,103]; c=['w','x','y','z'] d=lace(a,b,c); print d yields a single list of nested tuples: [(1, 100, 'w'), (2, 101, 'x'), (3, 102, 'y'), (4, 103, 'z')] **NOTE: Short lists are extended with values of None to match the longest list if necessary. """ # 99.999% of the work is done courtesy of Python's groovey built-in # map() function. # t = map(function, list1, list2, ...) # None as function means do nothing to list elements! return apply(map,(None,)+lists) So the built-in just does the exact same thing acording to the docs:" zip() is similar to map() with an initial argument of None." look at that! Only difference zip will truncate to the shortest list. Using map the above pads the short list with None, which i think is better. >>> a=[1,2,3] >>> b=[4,5,6] >>> c=[7,8,9] >>> d = [7,8,9,0] >>> l=zip(a,b,c) >>> l [(1, 4, 7), (2, 5, 8), (3, 6, 9)] >>> l2=zip(a,b,d) >>> l2 [(1, 4, 7), (2, 5, 8), (3, 6, 9)] >>> l3=lace(a,b,d) >>> l3 [(1, 4, 7), (2, 5, 8), (3, 6, 9), (None, None, 0)] As for Unzip, Christopher, thanks! your "useless" little piece of code is not so useless to me. in fact i love to mess with lists and often need to. I am building up quite a collection of them. Unzip is wonderful. Let me know if you have any others. Particularly ones that reorder or make patterns, or do stochastics. I collect and make them including silly ones (that i actually sometimes even use), like: def mirror(seq): # odd symmetry mirroring foo=seq[:-1] # copy list, excluding last element foo.reverse() # flip it seq.extend(foo) # stick it on the end of the other list return seq and: def scramble(foo): inList = foo[:] outList = [] #print inList, "\n", outList,"\n" # while there are still elements in the list do: while inList: # -- (will stop looping when seq is empty) -- element = random.choice(inList) # choose one element at random #print "--",element, "--" outList.append(element) # stick it on the end of the output list inList.remove(element) # remove pick from original seq return outList >Message: 11 >Date: Fri, 13 Jul 2001 23:01:36 -0500 >To: tutor@python.org >Cc: rob@jam.rr.com >From: "Christopher Smith" >Subject: [Tutor] Unzip > >Here's a piece of useless code which extracts lists that have been zipped >together (or mapped together with None: > map(Nane,l1,l2) is the same as zip(l1,l2) > >Does anyone use something else to do this? > >---code start--- >def unzip(l,*jj): > '''Return all (if none are specified) or some > elements in the tuples of l that were zipped together. > ''' > # > # Christopher P. Smith 7/13/2001 > # > if jj==(): > jj=range(len(l[0])) > rl = [[li[j] for li in l] for j in jj] # a list of lists > if len(rl)==1: > rl=rl[0] #convert list of 1 list to a list > return rl > >a=[1,2,3] >b=[4,5,6] >c=[7,8,9] >l=zip(a,b,c) > >x,y,z= unzip(l) # get them all: x=[1,2,3], y=[4,5,6], z=[7,8,9] >y=unzip(l,1) # get the 1th one: y as above >x,z=unzip(l,0,2)# get the 0th and 2th ones: x and z as above > >---code end--- > >/c > Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From rob@jam.rr.com Sat Jul 14 16:28:24 2001 From: rob@jam.rr.com (Rob Andrews) Date: Sat, 14 Jul 2001 10:28:24 -0500 Subject: [Tutor] Another source of Python tutorials In-Reply-To: Message-ID: # -----Original Message----- # Hi everyone, # # http://www.devshed.com/Server_Side/Python/ # # is running a series of introductory tutorials on Python as well. The # tutorials there look pretty good --- many of them concentrate on the CGI # side of Python that may interest people here. # # That's great! I've been checking DevShed periodically in hopes they'd add to their Python collection. OH, and thinking of which.... Apologies and thanks to everyone who has noticed the problems Useless Python has been plagued with lately. Our hosting service just got sold, and the transition left the server unavailable so much that I was unable to do any real updates for a few weeks. We're caught up (I think) on all the material that wasn't just plain lost, and I've started maintaining a pretty current mirror "just in case". Rob "Perl is worse than Python because people wanted it worse." Larry Wall (Creator of Perl), 14 Oct 1998 Useless Python: http://www.lowerstandard.com/python/ From dsh8290@rit.edu Sat Jul 14 16:42:35 2001 From: dsh8290@rit.edu (D-Man) Date: Sat, 14 Jul 2001 11:42:35 -0400 Subject: [Tutor] Born from : [memory management details] In-Reply-To: <01071315114400.00797@mercury.in.cqsl.com>; from lonetwin@yahoo.com on Fri, Jul 13, 2001 at 03:13:12PM +0530 References: <01071315114400.00797@mercury.in.cqsl.com> Message-ID: <20010714114235.F12594@harmony.cs.rit.edu> On Fri, Jul 13, 2001 at 03:13:12PM +0530, steve wrote: | Hi there, | D-man and Danny Yoo, that explanation 'bout the stack and the heap | was ^^REAL^^ good !! The best part is I understood all of it :) (even | though I've just begun programming). Now you've got me hooked !... Cool. Thanks. (Actually, I'm kinda surprised the C code didn't royally confuse people who haven't seen C before) | ...eh...I'd like somebody to point me to some resource (online or a | book maybe) that explains such low level details....to push it even more A lot of this is just normal C usage. I have a good C tutorial (HTML format) that I got of the web a few years back, but I don't think it is on the web anymore. I'll send it to you soon. | ...I'd like n e resource that explains low level details of things like | networks/OS operation ...stuff like that !! Hmm, not sure about that. It helps to follow lists like debian-user and python-list. I certainly learned a lot there. linuxdoc.org explains a bunch of stuff too. I just finished a course, OSI, that covered scheduling algorithms, syncronizationo (semaphores) and paging and segmentation algorithms. I don't know where to find that on the web (except for the author's slides, www.bell-labs.com/topic/books/aos-book/). I just started Data Comm & Networks 1 which is going to cover socket programming and stuff like that. If I find any good (free) stuff I'll let you know. | Hope I ain't bugging ne one, Just that 'ne' thing, but it's not that big of a deal ;-). (You're weren't talking about my ethernet adapter, were you ?) -D From clanoftheinsane@hotmail.com Sun Jul 15 02:11:29 2001 From: clanoftheinsane@hotmail.com (Paul Brown) Date: Sat, 14 Jul 2001 21:11:29 -0400 Subject: [Tutor] HTML project Message-ID:
hey all,
i am working on a project with Python.  some of my friends have a email-list going around, and somebody writes a daily (well, almost daily) devotional and sends it to everyone.  i'm wanting to put all of these on a website, and i'm gonna use python to write the html files.  i've got most of what i want complete, but i can't figure out the rest.  all of the devotionals i have saved into a big text document, separated by a common string: "Date:" and then it displays the date, in the form of Month ##th, 2000.  (or "st" and "2001" in their respective places).  i want to create an actual HTML file in the following format:  month##.html (all lowercase, double digits for the numbers to keep them in order).  what i've got so far is the python script that prints the whole file to the stdout, and it inserts the headings with the appropriate dates.  another thing i want to do is have the script write in the paragraph tag (<p>) whenever there is two linebreaks.  would that be possible?  here is my script so far:
 
import sys
file=open('c:\windows\desktop\goodtext', 'r')
br="Date:"
for line in file.readlines():
 if line[:5] != br:
     if line[:-1]=="\n":
  print "<p>", line,
     else:
  print line,
 else:
  sys.stdout.write(line[5:])
  print '''<html>
<head>
<title>%s</title>
</head>
<BODY>
<center><h1>%s</h1></center>
''' %(line[5:], line[5:])
 
 
any suggestions?  thanks
paul brown


Get your FREE download of MSN Explorer at http://explorer.msn.com

From csmith@blakeschool.org Sun Jul 15 02:13:30 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Sat, 14 Jul 2001 20:13:30 -0500 Subject: [Tutor] Copy and Deepcopy (List aliasing) Message-ID: Dear List, I've run into a perplexing issue and would like to understand the issues better: I create a list >>> l=[0,0] and make a copy with a new id (by using l+[] on the rhs instead of just l) >>> n=l+[] so that changes to one >>> n[0]=42 don't affect the other >>> n [42, 0] >>> l [0, 0] I try it with a *nested* list >>> l=[[0,0],[0,0]] >>> n=l+[] >>> n[0][0]=42 and find that even though the n and l are not the same >>> id(n) 59984352 >>> id(l) 60175248 n[0] and l[0] *are the same* >>> id(n[0]) 59985088 >>> id(l[0]) 59985088 so that changes to one *do affect* the other >>> l[0] [42, 0] >>> n[0] [42, 0] I know that using n=deepcopy(l) fixes the problem, but can anyone help me understand what is going on? Is there any other simple way to make a copy of l without using deepcopy? The "=" is a little more tricky than I have suspected. /c From ak@silmarill.org Sun Jul 15 02:31:20 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Sat, 14 Jul 2001 21:31:20 -0400 Subject: [Tutor] Copy and Deepcopy (List aliasing) In-Reply-To: <"from csmith"@blakeschool.org> References: Message-ID: <20010714213120.B516@sill.silmarill.org> On Sat, Jul 14, 2001 at 08:13:30PM -0500, Christopher Smith wrote: > Dear List, > > I've run into a perplexing issue and would like to understand the issues > better: > > I create a list > >>> l=[0,0] > and make a copy with a new id (by using l+[] on the rhs instead of just l) > >>> n=l+[] > so that changes to one > >>> n[0]=42 > don't affect the other > >>> n > [42, 0] > >>> l > [0, 0] > > I try it with a *nested* list > >>> l=[[0,0],[0,0]] > >>> n=l+[] > >>> n[0][0]=42 > and find that even though the n and l are not the same > >>> id(n) > 59984352 > >>> id(l) > 60175248 > n[0] and l[0] *are the same* > >>> id(n[0]) > 59985088 > >>> id(l[0]) > 59985088 > so that changes to one *do affect* the other > >>> l[0] > [42, 0] > >>> n[0] > [42, 0] > > I know that using n=deepcopy(l) fixes the problem, but can anyone > help me understand what is going on? Is there any other simple > way to make a copy of l without using deepcopy? The "=" is a > little more tricky than I have suspected. Umm.. there's newlst = lst[:] > > /c > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From dyoo@hkn.eecs.berkeley.edu Sun Jul 15 06:28:45 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 14 Jul 2001 22:28:45 -0700 (PDT) Subject: [Tutor] Copy and Deepcopy (List aliasing) In-Reply-To: Message-ID: On Sat, 14 Jul 2001, Christopher Smith wrote: > I create a list > > >>> l=[0,0] > > and make a copy with a new id (by using l+[] on the rhs instead of > just l) > > >>> n=l+[] > [... some text cut] > > I know that using n=deepcopy(l) fixes the problem, but can anyone help > me understand what is going on? Is there any other simple way to make > a copy of l without using deepcopy? The "=" is a little more tricky > than I have suspected. [warning: if you haven't played around with lists yet, this message might be confusing.] Using list addition is a good approach to create a new list. Another way that I've seen people do it is to take a slice of the whole list: n = l[:] Slices, too, create a new "shallow" copy of the list. I think that the subject of shallow vs. deep copying is at the heart of your question. To see what the difference between shallow and deep copying, we will need to draw some pictures. First, let's talk about what happens when we do something like this: ### >>> mylist_1 = [1, 2, 3, 4] >>> mylist_2 = mylist_1 >>> mylist_2[-1] = 'four' >>> mylist_1 [1, 2, 3, 'four'] >>> mylist_2 [1, 2, 3, 'four'] ### What we end up holding in our hands might look something like this: Variables List Instance ========= ============= mylist_1 -------------- +----+----+----+----+ \ | | | | | +-->| . | . | . | . | mylist_2 --------------/ +--+-+--+-+--+-+--+-+ | | | | | | | | v v v v 1 2 3 4 (*pant* There just HAS to be an easier way to do ASCII graphics...) Whenever we use '=', we are always direct a "name", the variable, off in the direction of some "thing". In this example, the incantation: mylist_1 = [1, 2, 3, 4] causes Python to create a list with four numbers. Except that, in truth, the list doesn't actually "contain" those numbers! Instead, we get four boxes that act like variables: they too can direct toward things, like numbers. That's why the numbers aren't drawn within the smaller boxes above. It seems like a needless distinction, but give it a moment. What happens when we do a shallow copy of a simple list? ### >>> mylist = [1, 2, 3, 4] >>> shallow_copy = mylist[:] >>> mylist[0] = 'one' >>> mylist ['one', 2, 3, 4] >>> shallow_copy [1, 2, 3, 4] ### Again, pictures will help a lot: mylist_1 -------------- +----+----+----+----+ \ | | | | | +-->| . | . | . | . | +--+-+--+-+--+-+--+-+ | | | | | | | | V V V V 1 'one' 2 3 4 ^ ^ ^ ^ +----+ | | | | | | | +--+-+--+-+--+-+--+-+ | | | | | | | | | +-->| . | . | . | . | shallow_copy ----------/ +----+----+----+----+ This is a "shallow" copy: Python will create a new list with the length that we request. However, each of the list elements will get directed toward the same thing that the original list pointed to. Although 'shallow_copy' is somewhat separate from 'mylist_1', there's still some potential interference possible between the two. And that's precisely the behavior we see with nested lists: ### >>> books = [['molecular biology of the cell'], ... ['the prydain chronicles']] >>> shallow_books = books[:] ### books ----------------- +----+----+ \ | | | +-->| . | . | +--+-+--+-+ | | | +-------+ V V +----+ +----+ "molecular bio..." <----+-. | | .-+---> "the pry..." | | | | +----+ +----+ ^ ^ | +-------+ | | +--+-+--+-+ | | | | | +-->| . | . | shallow_books ---------/ +----+----+ This model predicts that if we make a change to the large lists, we shouldn't see that change in its shallow "clone". However, if we make a change in one of the small inner lists, we'll see that change from both 'books' and 'shallow books'. Let's see: ### >>> books[0] = ['core python programming'] >>> books[1][0] = 'the return of the king' >>> books [['core python programming'], ['the return of the king']] >>> shallow_books [['molecular biology of the cell'], ['the return of the king']] ### If we draw out the picture, what we'll see will be complicated, but it should also make sense. Hopefully, this shows some of the motivations for deep copying: deep copying not only makes a top-level copy of the list, but it delves into the structure, making copies of every inner list too. But I'd better stop here, or else the next picture won't fit in 23 rows... Hope this helps! From wesc@deirdre.org Sun Jul 15 07:10:11 2001 From: wesc@deirdre.org (Wesley Chun) Date: Sat, 14 Jul 2001 23:10:11 -0700 (PDT) Subject: [Tutor] arg exceptions for scrips In-Reply-To: Message-ID: another thing you can do to make your program more robust is to determine whether the input/source file exists and to print out an error message like: 'file1' does not exist, try again or something like that, then perhaps give the usage string. without this code, your script will crap out again with an exception, also somewhat useless to the user. just another thought, -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ On Sat, 14 Jul 2001, kevin parks wrote: > > Oh, dopey me! I looked right past that thinking anticipating what that problem was. So what i really want is: > > if len(sys.argv) != 3: > > and not: > > if len(sys.argv) != 2: > > Thank you! > > On Fri, 13 Jul 2001 11:01:26 > George Gates wrote: > > > >>if __name__ == '__main__': > >> if len(sys.argv) < 2: > >> print "Usage:", sys.argv[0], "infile outfile" > >> sys.exit(1) > >> else: > >> cp(sys.argv[1],sys.argv[2]) > > > >The problem is the test of the length should be less than 3, not less than > >2. If you executed with only one argument the length of sys.argv would be > >2, sys.argv[0] for the script name, sys.argv[1] for the argument: > > > >ggates@ggates ggates]$ more arg_count.py > > > >#!/usr/bin/env python > >import sys > >print "The number of arguments are %s: %s" % (len(sys.argv),sys.argv) > > > >[ggates@ggates ggates]$ ./arg_count.py file1 > > > >The number of arguments are 2: ['./arg_count.py', 'file1'] From onav@yahoo.com Sun Jul 15 10:06:52 2001 From: onav@yahoo.com (Mike Serpa) Date: Sun, 15 Jul 2001 02:06:52 -0700 (PDT) Subject: [Tutor] Re: Unzip In-Reply-To: Message-ID: <20010715090652.54369.qmail@web9605.mail.yahoo.com> How serendipitous. This is just what I was looking for. I was trying to figure out how to print some lists of unequal length in columns and came up with: -------------- def printListColumns(*lists): paddedLists = padLists(lists) for row in range(len(paddedLists[0])): # number of rows for column in paddedLists: # number of columns print str(column[row]).ljust(20), print def padLists(lists): longestLength = findLongest(lists) for list in lists: while len(list) < longestLength: # pad shorter lists with '' list.append('') return lists def findLongest(lists): # find length of longest list longestLength = 0 for list in lists: if len(list) > longestLength: longestLength = len(list) return longestLength a = [1,2,3] b =[4,5,6] c = [7,8,9,10] printListColumns(a,b,c) ------------------------ Which I've now shortened to: ------------------- def printListColumns(*lists): import lace lacedList = apply(lace.lace,lists) # sort into columns lacedList = map(list,lacedList) # make mutable paddedList = map(padList,lacedList) # change all None's to '' for row in paddedList: for column in row: print str(column).ljust(20), print def padList(list): # padded = nullstrings for item in list: if item == None: list[list.index(None)] = '' return list a = [1,2,3] b = [4,5,6] c = [7,8,9,10] printListColumns(a,b,c) ------------------- Hmmmmm, not too much reduction, but I'm sure there is a better way to replace the None fields with nullstrings, but I'm a tired newbie who needs to go to bed. > Message: 3 > To: tutor@python.org > Date: Sat, 14 Jul 2001 18:14:55 +0900 > From: "kevin parks" > Reply-To: kp87@lycos.com > Subject: [Tutor] Unzip > Organization: Lycos Mail (http://mail.lycos.com:80) > > Wow, i had no idea that there was a built-in called zip. I rolled my > own, but called it lace (like a shoe) and even have an "unlace", but > i think, inferior to your Unzip, which also does x,z=unzip(l,0,2).: > > def lace(*lists): > """lace: forms a list by interlacing elements from several lists. > > e.g.: > a=[1,2,3,4]; b=[100,101,102,103]; c=['w','x','y','z'] > d=lace(a,b,c); print d > > yields a single list of nested tuples: > [(1, 100, 'w'), (2, 101, 'x'), (3, 102, 'y'), (4, 103, 'z')] > > **NOTE: Short lists are extended with values of None to match the > longest list if necessary. > """ > > # 99.999% of the work is done courtesy of Python's groovey built-in > # map() function. > # t = map(function, list1, list2, ...) > # None as function means do nothing to list elements! > > return apply(map,(None,)+lists) > > > So the built-in just does the exact same thing acording to the docs:" > zip() is similar to map() with an initial argument of None." > > look at that! Only difference zip will truncate to the shortest list. > Using map the above pads the short list with None, which i think is > better. __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From boegli@iinet.net.au Mon Jul 16 01:35:30 2001 From: boegli@iinet.net.au (Richard B) Date: Sun, 15 Jul 2001 17:35:30 -0700 Subject: [Tutor] parallel port?! Message-ID: <3B5236D2.A10528A7@iinet.net.au> How do I send commands to the parallel port under python? I got a module from some python web site but I don't have a clue how to use it. I got it from http://www.geocities.com/dinceraydin/python/indexeng.html I would like to be able to send commands to the parallell port under linux and windows. I need it to control a stepper motor control board. I am getting the board in the mail soon, so I'll be able to know exactly what commands I will need to send the board. All help would be appericiated. From lumbricus@gmx.net Sun Jul 15 10:28:11 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Sun, 15 Jul 2001 11:28:11 +0200 Subject: [Tutor] Copy and Deepcopy (List aliasing) In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Sat, Jul 14, 2001 at 10:28:45PM -0700 References: Message-ID: <20010715112811.A973@Laplace.localdomain> On Sat, Jul 14, 2001 at 10:28:45PM -0700, Danny Yoo wrote: > On Sat, 14 Jul 2001, Christopher Smith wrote: > > > Variables List Instance > ========= ============= > > mylist_1 -------------- +----+----+----+----+ > \ | | | | | > +-->| . | . | . | . | > mylist_2 --------------/ +--+-+--+-+--+-+--+-+ > | | | | > | | | | > v v v v > 1 2 3 4 > > > (*pant* There just HAS to be an easier way to do ASCII graphics...) > OT: Didn't use it myself but try "http://www.jave.de/" HTH J"o! -- He who knows that enough is enough will always have enough. -- Lao Tsu From israel@lith.com Sun Jul 15 16:23:22 2001 From: israel@lith.com (Israel Evans) Date: Sun, 15 Jul 2001 08:23:22 -0700 Subject: [Tutor] Scope Issues... Message-ID: The following kind of sums up what I was doing. It's a simplified version the merely demonstrates the issues I was having trouble with... Namely scope stuff... these three functions need to work together in this way: caller calls lister and will do reverser on the values returned by lister. def lister(): mylist = [] #initializes an empty list listcont = ['a','b','c']#your basic list for item in listcont: #adds each item in listcont to mylist mylist.append(item) return mylist #returns mylist def reverser(list): #takes a list list.reverse() #and reverses it return list #then returns it def caller(): #makes a local variable equal newlist = reverser(lister())#to the results returned by print newlist #both previous functions. The problem was that in caller() I was just running the lister and reverser by themselves without having any local variables there to catch their return values. like so... def badcaller(): lister() #run function without home for return value for item in mylist: #try to access out of scope local variable reverser(item) #even though mylist was "returned" # it needed to be caught by something, # otherwise it just disappears. Silly oversight that indicates, I need to pay more attention to basics before leaping ahead to more advanced stuff! Though I do have to say getting in over your head is the best way to learn! You have so many mistakes from which to be educated! Thanks folks! Israel... -----Original Message----- From: D-Man To: [tutor] Sent: 7/13/2001 4:16 PM Subject: Re: [Tutor] Scope Issues... On Fri, Jul 13, 2001 at 03:21:39PM -0700, Israel Evans wrote: | | Whoo! I sure seem to be on this list a lot lately! Thanks for bearing | with me though. | | | Ok.. My latest challenge is causing me headaches.... | | I've got three little function. | | The first walks through a directory and builds a list of files that have a | specific extension. | The second goes through a file and swaps one word with another. | The third orchestrates the thing. It calls the first function and gets the | list and performs the second function on every item in the list. | | Where I'm having trouble is in getting the list built by the first function. | | At first, I defined the empty list in the top function and had that function | return the list after I've added stuff to it. | It seems the list goes out of scope when I do it this way. Unless you do something really weird, the reference to the list doesn't go out of scope until the function returns. | Then I tried making the list a global variable and by having the top | function returning, I would thereby change the list. It seems that when I | do it this way I get "local variable 'result' referenced before assignment". | And it seems that this error is called both for the top function and the one | that recurses over the values of the list. If you have something like this : bar = [] def foo() : print bar bar = bar + [ baz ] you will get that error message. Basically the assignment in the function means that bar is a local variable. Then you try and print bar (the local variable) before you have created it. In old (pre 2.1's nested scopes) python it wouldn't have been an error but it would have been a subtle bug : sometimes you would refer to the global 'bar' and sometimes the 'local' bar which overshadows the global bar. Bad. | I've been reading the documentation, but it seems I'm not understanding some | of the basic scoping issues. Any suggestions? Show us the code, then we can show you the problem you really have. Otherwise we have to guess at what is confusing you :-). -D _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent@springfed.com Sun Jul 15 16:38:59 2001 From: kent@springfed.com (Kent Tenney) Date: Sun, 15 Jul 2001 10:38:59 -0500 Subject: [Tutor] Code to check for changed Web page Message-ID: <200107151539.KAA02176@svc1.netwk-innov.net> Howdy, I would like to be able to check if a web page has changed since the last time I checked it. Does this already exist? Thanks, Kent -- Kent Tenney, kent@springfed.com on 07/15/2001 From clanoftheinsane@hotmail.com Sun Jul 15 18:27:45 2001 From: clanoftheinsane@hotmail.com (Paul Brown) Date: Sun, 15 Jul 2001 13:27:45 -0400 Subject: [Tutor] re: HTML project Message-ID:
i just typed it in regular.  there are some html tags that i wanted to display, but i didn't write the message in html.  is there a special notation i need to use to prevent the html from taking over?
sorry,
paul


Get your FREE download of MSN Explorer at http://explorer.msn.com

From elnstaff@yahoo.com Sun Jul 15 19:53:26 2001 From: elnstaff@yahoo.com (ELN STAFF) Date: Sun, 15 Jul 2001 11:53:26 -0700 (PDT) Subject: [Tutor] Python Fonts? Message-ID: <20010715185326.83468.qmail@web13005.mail.yahoo.com> Hi! What is the easiest way to facilitate italic, bold and underline font styles (for the command line) in python? Any input will be appreciated. __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From csmith@blakeschool.org Sun Jul 15 21:15:12 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Sun, 15 Jul 2001 15:15:12 -0500 Subject: [Tutor] print as columns Message-ID: (Mike Serpa wrote about printListColumns.) I have a couple suggestions regarding your printListColumns: 1) you can find the longest in a list of lists by using the reduce function which keeps applying the function to successive pairs of elements from a list: n=len(reduce(lambda a,b:max(a,b),l)) --- ------------------- - ^ ^ ^->the list of lists (called Lists in your program) | | | |_ the function which returns the longer of two lists | |_ when the reduce is done we will know the longest list, len gives the length of it Example: a=[1,2,3,4] b=[5,6,7] c=[8,9,10,11,12] n=len( reduce( lambda a,b:max(a,b), [a,b,c] )) n is 5 2) Instead of padding, you might consider using the try/except construction to not print the list elements that don't exist. Here's how it looks for a list of 3 elements which is to be printed in 5 rows. for j in range(5): try: print str(l[j].ljust(20), #if l[j] exists, print it except: print ''.ljust(20) #otherwise format a null string Thanks for the thought provoking post. /c From csmith@blakeschool.org Sun Jul 15 21:25:19 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Sun, 15 Jul 2001 15:25:19 -0500 Subject: [Tutor] Copy and Deepcopy (List aliasing) In-Reply-To: References: Message-ID: >From: sill@optonline.net > >> I know that using n=deepcopy(l) fixes the problem, but can anyone >> help me understand what is going on? Is there any other simple >> way to make a copy of l without using deepcopy? The "=" is a >> little more tricky than I have suspected. > >Umm.. there's newlst = lst[:] This provides a shallow copy: >>> a=[1,2] >>> b=[2,3,4] >>> l=[a,b] >>> l [[1, 2], [2, 3, 4]] >>> n=l[:] >>> n [[1, 2], [2, 3, 4]] >>> n[0][0]=42 >>> n [[42, 2], [2, 3, 4]] >>> l [[42, 2], [2, 3, 4]] Note that l caught the change, too. /c From clanoftheinsane@hotmail.com Sun Jul 15 21:27:21 2001 From: clanoftheinsane@hotmail.com (Paul Brown) Date: Sun, 15 Jul 2001 16:27:21 -0400 Subject: [Tutor] HTML Project--in plain text format i hope Message-ID: ok, maybe everyone can read this without any trouble now. my original message was: hey all, i am working on a project with Python. some of my friends have a email-list going around, and somebody writes a daily (well, almost daily) devotional and sends it to everyone. i'm wanting to put all of these on a website, and i'm gonna use python to write the html files. i've got most of what i want complete, but i can't figure out the rest. all of the devotionals i have saved into a big text document, separated by a common string: "Date:" and then it displays the date, in the form of Month ##th, 2000. (or "st" and "2001" in their respective places). i want to create an actual HTML file in the following format: month##.html (all lowercase, double digits for the numbers to keep them in order). what i've got so far is the python script that prints the whole file to the stdout, and it inserts the headings with the appropriate dates. another thing i want to do is have the script write in the paragraph tag (

) whenever there is two linebreaks. would that be possible? here is my script so far: import sys file=open('c:\windows\desktop\goodtext', 'r') br="Date:" for line in file.readlines(): if line[:5] != br: if line[:-1]=="\n": print "

", line, else: print line, else: sys.stdout.write(line[5:]) print ''' %s

%s

''' %(line[5:], line[5:]) any suggestion? thanks, paul brown _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From bill-bell@bill-bell.hamilton.on.ca Sun Jul 15 23:25:34 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Sun, 15 Jul 2001 18:25:34 -0400 Subject: [Tutor] Re: parallel port?! In-Reply-To: Message-ID: <3B51E01E.16130.4A24578@localhost> Richard B wrote: > How do I send commands to the parallel port under python? I got a > module from some python web site but I don't have a clue how to > use it. I got it from > http://www.geocities.com/dinceraydin/python/indexeng.html I would > like to be able to send commands to the parallell port under linux > and windows. I need it to control a stepper motor control board. I > am getting the board in the mail soon, so I'll be able to know > exactly what commands I will need to send the board. All help > would be appericiated. Richard, I just glanced at the page you mentioned in your posting. This is an excerpt: "Using calldll it is possible to access functions in any DLL library. I imported the necessary functions from dlportio.dll and wrote some simple functions to aid using the printer port. The module and dlportio driver are available for download here ..." Can you be more specific about what you need to know? Bill From dsh8290@rit.edu Sun Jul 15 23:49:31 2001 From: dsh8290@rit.edu (D-Man) Date: Sun, 15 Jul 2001 18:49:31 -0400 Subject: [Tutor] Scope Issues... In-Reply-To: ; from israel@lith.com on Sun, Jul 15, 2001 at 08:23:22AM -0700 References: Message-ID: <20010715184931.C13028@harmony.cs.rit.edu> On Sun, Jul 15, 2001 at 08:23:22AM -0700, Israel Evans wrote: | The following kind of sums up what I was doing. It's a simplified version | the merely demonstrates the issues I was having trouble with... Namely scope | stuff... | these three functions need to work together in this way: | caller calls lister and will do reverser on the values returned by lister. | | def lister(): | mylist = [] #initializes an empty list | listcont = ['a','b','c']#your basic list | for item in listcont: #adds each item in listcont to mylist | mylist.append(item) | return mylist #returns mylist | | def reverser(list): #takes a list | list.reverse() #and reverses it | | return list #then returns it IMO this reverser function isn't very good. The reason is it modifies the argument _and_ returns something. It is easy for someone writing client code to get upset when the list they passed in gets changed. For example : l = [ 1 ,2 ] # the original rev = reverser( l ) # make a list that is the reverse of 'l' if rev == l : print "the list was a pallindrome" else : print "the list isn't a pallindrome" # a pallindrome is a word (maybe lists count too) that is the same # forwards and backwards This is buggy because rev and l both refer to the _same_ list. I would recommend either not having this function, since it is built-in functionality anyways, or doing something like the following : def reverser( l ) : shallow_copy = l[:] shallow_copy.reverse() return shallow_copy With this definition my above client code would work. | def caller(): #makes a local variable equal | newlist = reverser(lister())#to the results returned by | print newlist #both previous functions. | | | The problem was that in caller() I was just running the lister and | reverser by themselves without having any local variables there to | catch their return values. like so... | | def badcaller(): | lister() #run function without home for return value | for item in mylist: #try to access out of scope local variable | reverser(item) #even though mylist was "returned" | # it needed to be caught by something, | # otherwise it just disappears. | | Silly oversight Yep. 'mylist' was a local variable of a different function. | that indicates, I need to pay more attention to basics before | leaping ahead to more advanced stuff! Though I do have to say | getting in over your head is the best way to learn! You have so | many mistakes from which to be educated! Yeah, you don't learn by simply reading a book. You have to try it out for yourself too. -D From dsh8290@rit.edu Sun Jul 15 23:51:14 2001 From: dsh8290@rit.edu (D-Man) Date: Sun, 15 Jul 2001 18:51:14 -0400 Subject: [Tutor] Python Fonts? In-Reply-To: <20010715185326.83468.qmail@web13005.mail.yahoo.com>; from elnstaff@yahoo.com on Sun, Jul 15, 2001 at 11:53:26AM -0700 References: <20010715185326.83468.qmail@web13005.mail.yahoo.com> Message-ID: <20010715185114.D13028@harmony.cs.rit.edu> On Sun, Jul 15, 2001 at 11:53:26AM -0700, ELN STAFF wrote: | Hi! | | What is the easiest way to facilitate italic, bold and | underline font styles (for the command line) in | python? Umm, write your own using ncurses or something? The commandline doesn't have fancy formatting. That is usually found with programming editors such as gvim (www.vim.org). With gvim I get all sorts of nice syntax highlighting, but I edit a file which must be run by the interpreter, rather than an interactive session. HTH, -D From jstanley@start.com.au Mon Jul 16 00:06:12 2001 From: jstanley@start.com.au (Jordan Stanley) Date: Mon, 16 Jul 2001 0:06:12 +0100 Subject: [Tutor] Re: Tutor digest, Vol 1 #958 - 10 msgs Message-ID: Divx ;-) I believe that the perfect. most compact and effective implementation of te Divx ;-) algorithm can be implemented with Python. Jordan. __________________________________________________________________ Get your free Australian email account at http://www.start.com.au From ppathiyi@cisco.com Mon Jul 16 07:28:09 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Mon, 16 Jul 2001 11:58:09 +0530 Subject: [Tutor] Bus Error - Core Dumped Message-ID: <005201c10dc0$7bb29e70$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_004F_01C10DEE.95291680 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I am using python 1.5.2 and running a Tkinter GUI and some = python code for processing. I am getting a Bus Error (Core Dumped). The details are as follows -- when i use adb, it gives me the following : % adb core core file =3D core -- program ``python1.5'' on platform SUNW,Ultra-60 SIGBUS: Bus Error when i use dbx, it gives me the following : % dbx python core t@1340 (l@10) terminated by signal BUS (invalid address alignment) (dbx) where current thread: t@1340 =3D>[1] PyThreadState_Delete(0x4b2588, 0x0, 0x4b5bf8, 0x0, 0x0, 0x0), at = 0x2f21c [2] t_bootstrap(0x291f50, 0xef445d78, 0x0, 0xef5f0b54, 0x1, = 0xfe401000), at 0x579e0 Can somebody (may be someone who has worked on UNIX platforms) give me = an idea, what could be the reason for such a system critical error = condition ? Thanks in Advance, Praveen. ------=_NextPart_000_004F_01C10DEE.95291680 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
        I am using python 1.5.2 and = running a=20 Tkinter GUI and some python code for processing. I am getting a Bus = Error (Core=20 Dumped).
 
The details are as follows --
 
when i use adb, it gives me the following :
% adb core
 
core file =3D core -- program ``python1.5'' on platform=20 SUNW,Ultra-60
SIGBUS: Bus Error
when i use dbx, it gives me the following :
% dbx python core
 
t@1340 (l@10) terminated by signal BUS (invalid address = alignment)
 
(dbx) where
current thread: t@1340
=3D>[1]=20 PyThreadState_Delete(0x4b2588, 0x0, 0x4b5bf8, 0x0, 0x0, 0x0), at=20 0x2f21c
  [2] t_bootstrap(0x291f50, 0xef445d78, 0x0, 0xef5f0b54, = 0x1,=20 0xfe401000), at 0x579e0
 
Can somebody (may be someone who has worked on UNIX platforms) give = me an=20 idea, what could be the reason for such a system critical error = condition=20 ?
 
Thanks in Advance,
Praveen.
------=_NextPart_000_004F_01C10DEE.95291680-- From ppathiyi@cisco.com Mon Jul 16 08:09:52 2001 From: ppathiyi@cisco.com (Praveen Pathiyil) Date: Mon, 16 Jul 2001 12:39:52 +0530 Subject: [Tutor] Bus Error - Core Dumped References: <005201c10dc0$7bb29e70$37ef87c0@ppathiyipc> Message-ID: <008001c10dc6$4f2efe10$37ef87c0@ppathiyipc> This is a multi-part message in MIME format. ------=_NextPart_000_007D_01C10DF4.68B1AB20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I would like to add some more details regarding the operation scenario = -- The program is being run in a client-server mode using UNIX sockets. = When I am doing a at the client side, at the server I am = getting the Bus Error. Just after the start, when I do a , I am getting the error = which I sent in the previous mail. After the exchange of some messages, if I do the same i am getting the = core dump in a slightly different place: t@3211 (l@24) terminated by signal ABRT (Abort) (dbx) where current thread: t@3211 =3D>[1] __sigprocmask(0x0, 0x63a2eec0, 0x0, 0xffffffff, 0xffffffff, = 0x0), at 0xef5d4d34 [2] _resetsig(0xef5e78bc, 0xeba0bdd8, 0xef5e6c08, 0x0, 0x0, = 0xeba0be44), at 0xef5cba54 [3] _sigon(0xef5ec7e0, 0xef5eb680, 0xeba0be3c, 0xeba0bb94, 0x6, = 0xc8b), at 0xef5cb19c [4] _thrp_kill(0x0, 0x8b, 0x6, 0xef5e6c08, 0xeba0bdd8, 0xef5efd1c), at = 0xef5cdff0 [5] abort(0xef523180, 0x39, 0xef52aa64, 0xef526b60, 0x219400, 0x0), at = 0xef4ba600 [6] Py_FatalError(0x1d0110, 0xef529714, 0x0, 0x0, 0x0, 0x0), at = 0x30548 [7] PyThreadState_Delete(0x4ad9e8, 0x0, 0x49fa00, 0x0, 0x0, 0x0), at = 0x2f22c [8] t_bootstrap(0x2932f0, 0xeec65d78, 0x0, 0xef5f0b54, 0x1, = 0xfe401000), at 0x579e0 I know it is not enough information for debugging, but I am not well = versed in the interpreter code. So any hint will be welcome. Thanks, Praveen. ------=_NextPart_000_007D_01C10DF4.68B1AB20 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
 
I would like to add some more details regarding the operation = scenario=20 --
 
The program is being run in a client-server mode using UNIX = sockets.=20 When I am doing a <Cntrl-C> at the client side, at the server = I am=20 getting the Bus Error.
 
Just after the start, when I do a <Cntrl-C>, I am = getting the=20 error which I sent in the previous mail.
 
After the exchange of some messages, if I do the same i am getting = the core=20 dump in a slightly different place:
 
t@3211 (l@24) terminated by signal ABRT (Abort)

(dbx) where
current thread: t@3211
=3D>[1] = __sigprocmask(0x0,=20 0x63a2eec0, 0x0, 0xffffffff, 0xffffffff, 0x0), at 0xef5d4d34
  = [2]=20 _resetsig(0xef5e78bc, 0xeba0bdd8, 0xef5e6c08, 0x0, 0x0, 0xeba0be44), at=20 0xef5cba54
  [3] _sigon(0xef5ec7e0, 0xef5eb680, 0xeba0be3c, = 0xeba0bb94,=20 0x6, 0xc8b), at 0xef5cb19c
  [4] _thrp_kill(0x0, 0x8b, 0x6, = 0xef5e6c08,=20 0xeba0bdd8, 0xef5efd1c), at 0xef5cdff0
  [5] abort(0xef523180, = 0x39,=20 0xef52aa64, 0xef526b60, 0x219400, 0x0), at 0xef4ba600
  [6]=20 Py_FatalError(0x1d0110, 0xef529714, 0x0, 0x0, 0x0, 0x0), at = 0x30548
 =20 [7] PyThreadState_Delete(0x4ad9e8, 0x0, 0x49fa00, 0x0, 0x0, 0x0), at=20 0x2f22c
  [8] t_bootstrap(0x2932f0, 0xeec65d78, 0x0, 0xef5f0b54, = 0x1,=20 0xfe401000), at 0x579e0
 
I know it is not enough information for debugging, but I am = not well=20 versed in the interpreter code. So any hint will be welcome.
 
Thanks,
Praveen.
------=_NextPart_000_007D_01C10DF4.68B1AB20-- From wwwjessie@21cn.com Mon Jul 16 10:45:02 2001 From: wwwjessie@21cn.com (wwwjessie@21cn.com) Date: Mon, 16 Jul 2001 17:45:02 +0800 Subject: [Tutor] =?gb2312?B?tPPBrC0yMDAxxOq5+rzKwszJq8qzxrfT68jLwOC9ob+1sqnAwLvhKA==?= =?gb2312?B?QWdybyBBbm51YWwgTWVldGluZyBDaGluYSAyMDAxKQ0=?= Message-ID: <2af7a01c10ddb$fc6d6070$9300a8c0@ifood1gongxing> This is a multi-part message in MIME format. ------=_NextPart_000_2AF7B_01C10E1F.0A90A070 Content-Type: text/plain; charset="gb2312" Content-Transfer-Encoding: base64 MjAwMcTq1tC5+rn6vMrFqdK1v8a8vMTqu+ENCrn6vMrCzMmryrPGt9PryMvA4L2hv7WyqcDAu+G8 sNGnyvXM1sLbu+ENCg0KCQ0K1bnG2qO6IAmhoTIwMDHE6jnUwjTI1S03yNUJDQq12LXjo7ogCaGh tPPBrNDHuqO74dW51tDQxAkNCtb3sOyjuiAJoaHW0LuqyMvD8bmyus25+sWp0rWyvw0KoaHW0Ln6 v8bRp7y8yvXQrbvhDQqhobTzwazK0MjLw/HV/riuDQoJDQqz0LDso7ogCaGh1tC5+sLMyavKs8a3 t6LVudbQ0MQNCqGh1tC5+sWp0ae74Q0KoaHW0Ln6wszJq8qzxrfQrbvhDQqhobTzwazK0MWp0rW+ 1g0KoaG088Gs0Me6o7vh1bnW0NDEDQoJDQrN+MLnt/7O8czhuanJzKO60rzKs8a31tC5+s34IGh0 dHA6Ly93d3cuaWZvb2QxLmNvbQ0KPGh0dHA6Ly93d3cuaWZvb2QxLmNvbS9pbmRleC5hc3A/ZnI9 dHV0b3JAcHl0aG9uLm9yZz4gCQ0KIAkNCqH6IM2ouf3SvMqzxrfW0Ln6zfixqMP7ss7VuaO6vsXV 29PFu90oscjI58/W09DDv7j2IDNNIFggM00gtcSx6te81bnOu9StvNtSTUI0NTAwo6zNqLn9ztLD x9a70Oi4tlJNQjQwNTApo6wNCrGow/u92Na5yNXG2jIwMDHE6jfUwjIwyNUgPGh0dHA6Ly9ncmVl bjIwMDEuaWZvb2QxLmNvbS9mcm9tMS5hc3A+IA0Kofogu7bTrSDD4rfR16Ky4SA8aHR0cDovL3d3 dy5pZm9vZDEuY29tL3NpZ251cC9zZXZhZ3JlZW0uYXNwPiCzyc6quavLvrvh1LGhow0KN9TCMjDI 1cew16Ky4aOsxPq9q9TaN9TCMjXI1cewzai5/bXn19PTyrz+t73KvcPit9G78bXDMzDM9bLJubrQ xc+ioaMNCsjnufvE+rK7z+vK1bW9ztLDx7XE08q8/qOsx+sgwarPtc7Sw8cgPG1haWx0bzp1bnN1 YnNjcmliZUBpZm9vZDEuY29tPiCjrM7Sw8fS1Lrzvauyu9TZt6LTyrz+uPjE+qGjDQqy6dGvo7og c2FsZXNAaWZvb2QxLmNvbSA8bWFpbHRvOnNhbGVzQGlmb29kMS5jb20+ICChoaGhtee7sKO6MDc1 NS0zNzg2MzA5oaHP+srbsr8NCsny0KG94yC2xc/IyfoNCg0KDQogDQoNCrvYINa0IKOox+u0q9Xm o7owNzU1LTMyMzkwNDe78iC3orXn19PTyrz+o7ogc2FsZXNAaWZvb2QxLmNvbSA8bWFpbHRvOnNh bGVzQGlmb29kMS5jb20+DQqjqQkNCqH1ILG+uavLvtPQ0uLNqLn90rzKs8a31tC5+s34ss7VuSCh oaGhIKH1ILG+uavLvsTivfjSu7K9wcu94rjDsqnAwLvho6zH69PrztLDx8Gqz7UNCg0KuavLvsP7 s8ajul9fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fDQrBqs+1yMujul9fX19f X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX18NCrXnu7Cjul9fX19fX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fX18NCrSr1eajul9fX19fX19fX19fX19fX19fX19fX19fX19fX19f X19fX19fX18NCkUtbWFpbKO6X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fXw0K CQ0KIAkNCiAJDQogCQ0KIAkNCiAJDQo= ------=_NextPart_000_2AF7B_01C10E1F.0A90A070 Content-Type: text/html; charset="gb2312" Content-Transfer-Encoding: base64 PGh0bWw+DQo8aGVhZD4NCjx0aXRsZT5VbnRpdGxlZCBEb2N1bWVudDwvdGl0bGU+IDxtZXRhIGh0 dHAtZXF1aXY9IkNvbnRlbnQtVHlwZSIgY29udGVudD0idGV4dC9odG1sOyBjaGFyc2V0PWdiMjMx MiI+IA0KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4NCjwhLS0NCnRkIHsgIGxpbmUtaGVpZ2h0OiAy NHB4fQ0KLS0+DQo8L3N0eWxlPiANCjwvaGVhZD4NCg0KPGJvZHkgYmdjb2xvcj0iI0ZGRkZGRiIg dGV4dD0iIzAwMDAwMCI+DQo8ZGl2IGFsaWduPSJDRU5URVIiPjx0YWJsZSB3aWR0aD0iNzUlIiBi b3JkZXI9IjAiIGNlbGxzcGFjaW5nPSIwIiBjZWxscGFkZGluZz0iMCI+PHRyPjx0ZCBhbGlnbj0i Q0VOVEVSIj48YSBocmVmPSJodHRwOy8vZ3JlZW4yMDAxLmlmb29kMS5jb20iPjxiPjIwMDHE6tbQ ufq5+rzKxanStb/GvLzE6rvhPGJyPrn6vMrCzMmryrPGt9PryMvA4L2hv7WyqcDAu+G8sNGnyvXM 1sLbu+E8L2I+PC9hPjxicj48YnI+PC90ZD48L3RyPjx0cj48dGQgYWxpZ249IkNFTlRFUiI+PHRh YmxlIHdpZHRoPSI3NSUiIGJvcmRlcj0iMCIgY2VsbHNwYWNpbmc9IjAiIGNlbGxwYWRkaW5nPSIw Ij48dHI+PHRkIGhlaWdodD0iMTIiIHdpZHRoPSIzOSUiIGFsaWduPSJSSUdIVCI+PGI+PGZvbnQg c2l6ZT0iMiI+1bnG2qO6IA0KPC9mb250PjwvYj48L3RkPjx0ZCBoZWlnaHQ9IjEyIiB3aWR0aD0i NjElIj48Zm9udCBzaXplPSIyIj6hoTIwMDHE6jnUwjTI1S03yNU8L2ZvbnQ+PC90ZD48L3RyPjx0 cj48dGQgaGVpZ2h0PSIxMiIgd2lkdGg9IjM5JSIgYWxpZ249IlJJR0hUIj48Yj48Zm9udCBzaXpl PSIyIj612LXjo7ogDQo8L2ZvbnQ+PC9iPjwvdGQ+PHRkIGhlaWdodD0iMTIiIHdpZHRoPSI2MSUi Pjxmb250IHNpemU9IjIiPqGhtPPBrNDHuqO74dW51tDQxDwvZm9udD48L3RkPjwvdHI+PHRyPjx0 ZCBoZWlnaHQ9IjEyIiB3aWR0aD0iMzklIiBhbGlnbj0iUklHSFQiIHZhbGlnbj0iVE9QIj48Yj48 Zm9udCBzaXplPSIyIj7W97Dso7ogDQo8L2ZvbnQ+PC9iPjwvdGQ+PHRkIGhlaWdodD0iMTIiIHdp ZHRoPSI2MSUiPjxmb250IHNpemU9IjIiPqGhPC9mb250Pjxmb250IHNpemU9IjIiPtbQu6rIy8Px ubK6zbn6xanStbK/PGJyPqGh1tC5+r/G0ae8vMr10K274Txicj6hobTzwazK0MjLw/HV/riuPGJy PjwvZm9udD48L3RkPjwvdHI+PHRyPjx0ZCBoZWlnaHQ9IjEyIiB3aWR0aD0iMzklIiBhbGlnbj0i UklHSFQiIHZhbGlnbj0iVE9QIj48Yj48Zm9udCBzaXplPSIyIj6z0LDso7ogDQo8L2ZvbnQ+PC9i PjwvdGQ+PHRkIGhlaWdodD0iMTIiIHdpZHRoPSI2MSUiPjxmb250IHNpemU9IjIiPqGhPC9mb250 Pjxmb250IHNpemU9IjIiPtbQufrCzMmryrPGt7ei1bnW0NDEPGJyPqGh1tC5+sWp0ae74Txicj6h odbQufrCzMmryrPGt9Ctu+E8YnI+oaG088GsytDFqdK1vtY8YnI+oaG088Gs0Me6o7vh1bnW0NDE PGJyPjwvZm9udD48L3RkPjwvdHI+PHRyPjx0ZCBjb2xzcGFuPSIyIiBhbGlnbj0iQ0VOVEVSIj48 Zm9udCBzaXplPSIyIj7N+MLnt/7O8czhuanJzKO60rzKs8a31tC5+s34IA0KPGEgaHJlZj0iaHR0 cDovL3d3dy5pZm9vZDEuY29tL2luZGV4LmFzcD9mcj10dXRvckBweXRob24ub3JnIj5odHRwOi8v d3d3Lmlmb29kMS5jb208L2E+PC9mb250PjwvdGQ+PC90cj48dHI+PHRkIGNvbHNwYW49IjIiIGFs aWduPSJDRU5URVIiPiZuYnNwOzwvdGQ+PC90cj48dHI+PHRkIGNvbHNwYW49IjIiIGFsaWduPSJM RUZUIj48cD48Zm9udCBzaXplPSIyIj6h+iANCs2ouf3SvMqzxrfW0Ln6zfixqMP7ss7VuaO6PGI+ PGZvbnQgc2l6ZT0iMyIgY29sb3I9IiNGRjAwMDAiPr7F1dvTxbvdPC9mb250PjwvYj4oscjI58/W 09DDv7j2IDNNIFggM00gDQq1xLHq17zVuc671K2821JNQjQ1MDCjrM2ouf3O0sPH1rvQ6Li2Uk1C NDA1MCmjrCA8YSBocmVmPSJodHRwOi8vZ3JlZW4yMDAxLmlmb29kMS5jb20vZnJvbTEuYXNwIj48 Yj48Zm9udCBzaXplPSIzIiBjb2xvcj0iI0ZGMDAwMCI+sajD+73Y1rnI1cbaMjAwMcTqN9TCMjDI 1TwvZm9udD48L2I+PC9hPjxicj6h+iANCru20608YSBocmVmPSJodHRwOi8vd3d3Lmlmb29kMS5j b20vc2lnbnVwL3NldmFncmVlbS5hc3AiPsPit9HXorLhPC9hPrPJzqq5q8u+u+HUsaGjIDxmb250 IGNvbG9yPSIjRkYwMDAwIj48Yj48Zm9udCBzaXplPSIzIj431MIyMMjVx7DXorLho6zE+r2r1No3 1MIyNcjVx7DNqLn9tefX09PKvP63vcq9w+K30bvxtcMzMMz1ssm5utDFz6KhozwvZm9udD48L2I+ PC9mb250Pjxicj7I57n7xPqyu8/rytW1vc7Sw8e1xNPKvP6jrMfrPGEgaHJlZj0ibWFpbHRvOnVu c3Vic2NyaWJlQGlmb29kMS5jb20iPsGqz7XO0sPHPC9hPqOsztLDx9LUuvO9q7K71Nm3otPKvP64 +MT6oaM8YnI+sunRr6O6PGEgaHJlZj0ibWFpbHRvOnNhbGVzQGlmb29kMS5jb20iPnNhbGVzQGlm b29kMS5jb208L2E+IA0KoaGhobXnu7CjujA3NTUtMzc4NjMwOaGhz/rK27K/IMny0KG94yC2xc/I yfo8YnI+PC9mb250PjwvcD48cD4mbmJzcDs8L3A+PC90ZD48L3RyPjx0cj48dGQgaGVpZ2h0PSIz MCIgY29sc3Bhbj0iMiIgYWxpZ249IkNFTlRFUiI+PGZvbnQgc2l6ZT0iMiI+PGI+u9ggDQrWtCCj qMfrtKvV5qO6MDc1NS0zMjM5MDQ3u/Igt6K159fT08q8/qO6IDxhIGhyZWY9Im1haWx0bzpzYWxl c0BpZm9vZDEuY29tIj5zYWxlc0BpZm9vZDEuY29tPC9hPiANCqOpPC9iPjwvZm9udD48L3RkPjwv dHI+PHRyPjx0ZCBoZWlnaHQ9IjEyIiBjb2xzcGFuPSIyIj48Zm9udCBzaXplPSIyIj6h9SCxvrmr y77T0NLizai5/dK8yrPGt9bQufrN+LLO1bkgDQqhoaGhIKH1ILG+uavLvsTivfjSu7K9wcu94rjD sqnAwLvho6zH69PrztLDx8Gqz7U8YnI+PGJyPrmry77D+7PGo7pfX19fX19fX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fXzxicj7Bqs+1yMujul9fX19fX19fX19fX19fX19fX19fX19fX19f X19fX19fX19fX188YnI+PC9mb250Pjxmb250IHNpemU9IjIiPrXnu7Cjul9fX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fX19fX188YnI+tKvV5qO6X19fX19fX19fX19fX19fX19fX19fX19f X19fX19fX19fX19fXzxicj5FLW1haWyjul9fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f X19fX188YnI+PC9mb250PjwvdGQ+PC90cj48dHI+PHRkIGhlaWdodD0iMTIiIGNvbHNwYW49IjIi IGFsaWduPSJMRUZUIj4mbmJzcDs8L3RkPjwvdHI+PHRyPjx0ZCBoZWlnaHQ9IjEyIiBjb2xzcGFu PSIyIiBhbGlnbj0iTEVGVCI+Jm5ic3A7PC90ZD48L3RyPjx0cj48dGQgaGVpZ2h0PSIxMiIgY29s c3Bhbj0iMiIgYWxpZ249IkxFRlQiPiZuYnNwOzwvdGQ+PC90cj48L3RhYmxlPjwvdGQ+PC90cj48 dHI+PHRkPiZuYnNwOzwvdGQ+PC90cj48dHI+PHRkPiZuYnNwOzwvdGQ+PC90cj48L3RhYmxlPjwv ZGl2Pg0KPC9ib2R5Pg0KPC9odG1sPg0K ------=_NextPart_000_2AF7B_01C10E1F.0A90A070-- From onav@yahoo.com Mon Jul 16 17:09:01 2001 From: onav@yahoo.com (Mike Serpa) Date: Mon, 16 Jul 2001 09:09:01 -0700 (PDT) Subject: [Tutor] Online interpreter? In-Reply-To: Message-ID: <20010716160901.38183.qmail@web9605.mail.yahoo.com> There isn't an online interpreter of Python somewhere is there? Like this one I found for Ruby? http://www.ruby.ch/en/rubymain.shtml Sometimes I want to try some things out on Python when I'm away from my PC. Mike __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From dsh8290@rit.edu Mon Jul 16 17:14:23 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 16 Jul 2001 12:14:23 -0400 Subject: [Tutor] Bus Error - Core Dumped In-Reply-To: <005201c10dc0$7bb29e70$37ef87c0@ppathiyipc>; from ppathiyi@cisco.com on Mon, Jul 16, 2001 at 11:58:09AM +0530 References: <005201c10dc0$7bb29e70$37ef87c0@ppathiyipc> Message-ID: <20010716121423.L13256@harmony.cs.rit.edu> On Mon, Jul 16, 2001 at 11:58:09AM +0530, Praveen Pathiyil wrote: | Hi, | | I am using python 1.5.2 and running a Tkinter GUI and some python | code for processing. I am getting a Bus Error (Core Dumped). Ooohh, fun. You're not supposed to get Bus Errors, etc, with python. Can you try with a newer interpreter? This error probably means that there is/was a bug in python. | Can somebody (may be someone who has worked on UNIX platforms) give | me an idea, what could be the reason for such a system critical | error condition ? If you were writing, say, C or C++ code it would mean that you did something wrong either with your memory management or with pointer arithmatic. You don't manage memory in Python and you don't have pointers so you aren't supposed to see things like that. It is also conceivable that there is a bug in Tcl that causes the problem (python embeds the Tcl interpreter to give access to the Tk gui). Are you using threads? If so, do they synchronize properly? Do you have a signal handler for SIGINT (the signal sent when ^C is pressed)? Did you write the server? (you said the server gave the bus error when the client was aborted, right?) Maybe there is a problem with the server trying to read a socket that has been closed (I haven't done network programming yet so I am fuzzy on the details)? I would have expected python to give you an exception in such a situation, but who knows. Can you add a bunch of prints in the server's socket handling code to see what the last thing that gets executed is? Also print some of the current state as well. HTH, -D From pobrien@orbtech.com Mon Jul 16 17:29:34 2001 From: pobrien@orbtech.com (Patrick K. O'Brien) Date: Mon, 16 Jul 2001 11:29:34 -0500 Subject: [Tutor] Online interpreter? In-Reply-To: <20010716160901.38183.qmail@web9605.mail.yahoo.com> Message-ID: Not to my knowledge there isn't. I seem to recall some discussion about this, on this list or perhaps the edu sig. While I don't think it would be too hard to do, I think there are security issues and such. At least that is what I recall. I'm currently working on a regular python shell (PyCrust) so I'm somewhat familiar with how the regular shell stuff works. --- Patrick K. O'Brien Orbtech "I am, therefore I think." -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Mike Serpa Sent: Monday, July 16, 2001 11:09 AM To: tutor@python.org Subject: [Tutor] Online interpreter? There isn't an online interpreter of Python somewhere is there? Like this one I found for Ruby? http://www.ruby.ch/en/rubymain.shtml Sometimes I want to try some things out on Python when I'm away from my PC. Mike __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From rob@jam.rr.com Mon Jul 16 19:42:30 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 16 Jul 2001 13:42:30 -0500 Subject: [Tutor] Online interpreter? In-Reply-To: Message-ID: Heck, I'd love to see/use something like this. Must investigate further. I wouldn't mind having an insecure box that isn't connected to the rest of my LAN available for me to tinker remotely. If someone cracked it, I'd just restore the original image at the next opportunity. I do love toys, Rob "Perl is worse than Python because people wanted it worse." Larry Wall (Creator of Perl), 14 Oct 1998 Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # Patrick K. O'Brien # Sent: Monday, July 16, 2001 11:30 AM # To: Python Tutor # Subject: RE: [Tutor] Online interpreter? # # # Not to my knowledge there isn't. I seem to recall some discussion about # this, on this list or perhaps the edu sig. While I don't think it would be # too hard to do, I think there are security issues and such. At # least that is # what I recall. I'm currently working on a regular python shell # (PyCrust) so # I'm somewhat familiar with how the regular shell stuff works. # # --- # Patrick K. O'Brien # Orbtech # "I am, therefore I think." # # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # Mike Serpa # Sent: Monday, July 16, 2001 11:09 AM # To: tutor@python.org # Subject: [Tutor] Online interpreter? # # There isn't an online interpreter of Python somewhere is there? Like # this one I found for Ruby? http://www.ruby.ch/en/rubymain.shtml # # Sometimes I want to try some things out on Python when I'm away from my # PC. # # Mike # # # # __________________________________________________ # Do You Yahoo!? # Get personalized email addresses from Yahoo! Mail # http://personal.mail.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 wesc@deirdre.org Mon Jul 16 19:53:24 2001 From: wesc@deirdre.org (Wesley Chun) Date: Mon, 16 Jul 2001 11:53:24 -0700 (PDT) Subject: [Tutor] Copy and Deepcopy (List aliasing) In-Reply-To: Message-ID: On Sat, 14 Jul 2001, Christopher Smith wrote: > > I've run into a perplexing issue and would like to understand the issues > better: > > I create a list > >>> l=[0,0] > and make a copy with a new id (by using l+[] on the rhs instead of just l) > >>> n=l+[] > so that changes to one > >>> n[0]=42 > don't affect the other > >>> n > [42, 0] > >>> l > [0, 0] > > I try it with a *nested* list > >>> l=[[0,0],[0,0]] > >>> n=l+[] > >>> n[0][0]=42 > and find that even though the n and l are not the same > >>> id(n) > 59984352 > >>> id(l) > 60175248 > n[0] and l[0] *are the same* > >>> id(n[0]) > 59985088 > >>> id(l[0]) > 59985088 > so that changes to one *do affect* the other > >>> l[0] > [42, 0] > >>> n[0] > [42, 0] > > I know that using n=deepcopy(l) fixes the problem, but can anyone > help me understand what is going on? Is there any other simple > way to make a copy of l without using deepcopy? The "=" is a > little more tricky than I have suspected. christopher, you know, i discovered *exactly* the same thing as you!! danny's "diagrams" are definitely helpful too, but let me try to summarize what's going on. you made a copy of an object, a list, so now you have 2 different objects. by default, this copy is a shallow copy, meaning that only the container object is copied -- not the stuff *inside* it. those things are just references to the exact same objects. a deep copy not only copies the container object, but also makes copies of its contents too! more details, analysis, including an example which looks strangely like a "shallow copy" of yours can be found in Section 6.19 in Core Python Programming on pp. 201-203. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From dsh8290@rit.edu Mon Jul 16 20:11:32 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 16 Jul 2001 15:11:32 -0400 Subject: [Tutor] Online interpreter? In-Reply-To: ; from rob@jam.rr.com on Mon, Jul 16, 2001 at 01:42:30PM -0500 References: Message-ID: <20010716151132.A13735@harmony.cs.rit.edu> On Mon, Jul 16, 2001 at 01:42:30PM -0500, Rob Andrews wrote: | Heck, I'd love to see/use something like this. Must investigate further. I | wouldn't mind having an insecure box that isn't connected to the rest of my | LAN available for me to tinker remotely. If someone cracked it, I'd just | restore the original image at the next opportunity. It's not so much a problem that someone might crack the box (I think) but more like they could read/write various files and also DoS the system. Suppose they opened the web page and ran l = [] i = 0L while 1 : l.append( i ) i += 1 The CPU would be maxed and you would run out of memory and swap. It would be best if you could run the python code in a chroot jail and with CPU/memory quotas so the box can't get trashed. Of course you would still want this on a non-critical system that has a backup image. -D From arcege@speakeasy.net Mon Jul 16 20:20:29 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Mon, 16 Jul 2001 15:20:29 -0400 (EDT) Subject: [Tutor] Online interpreter? In-Reply-To: <20010716160901.38183.qmail@web9605.mail.yahoo.com> from "Mike Serpa" at Jul 16, 2001 09:09:01 AM Message-ID: <200107161920.f6GJKTF02688@dsl092-074-184.bos1.dsl.speakeasy.net> Mike Serpa wrote > There isn't an online interpreter of Python somewhere is there? Like > this one I found for Ruby? http://www.ruby.ch/en/rubymain.shtml > > Sometimes I want to try some things out on Python when I'm away from my > PC. The easiest method, imo, would be to make a JPython applet wrapped around an instance of code.InteractiveConsole. Otherwise, if you just had CGI, make a picklable rexec class and wrap the CGI around it. class PicklableRexec(rexec.RExec): # keep state between CGI calls def __getstate__(self): # modules loaded modnames = self.modules.keys() # main module values, do not include modules mainmod = self.modules['__main__'] mainvals = [] mainmods = [] for name, value in mainmod.__dict__.items(): if not isinstance(value, types.ModuleType): mainvals.append( (name, value) ) else: mainmods.append( name ) return (modnames, mainvals, mainmods) def __setstate__(self, (modnames, mainvals, mainmods)): self.__init__() for name in modnames: self.r_import(name) for name in mainmods: self.r_exec('input %s' % name) mainmod = self.modules['__main__'] for (name, value) in mainvals: setattr(mainmod, name, value) Pickling an instance of this will create a text string that can be passed to the next HTML form, properly quoted of course. When submitting the form, unpickle the string to get the current state. The input string can be called through the s_exec method. May have to fix up the I/O for CGI. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From Blake.Garretson@dana.com Mon Jul 16 21:59:06 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Mon, 16 Jul 2001 16:59:06 -0400 Subject: [Tutor] Re: Tutor digest, Vol 1 #958 - 10 msgs Message-ID: Kent, I haven't seen this before, but I bet this would be pretty simple. I'd use urllib to pull the page back. Then do a hash() and store the value in a file somewhere. Then compare the hash of the current file with the last time you did it (if the file exists of course.) For instance, this will get the hash value: import urllib myurl=urllib.open("www.google") pagesource=myurl.read() hash_value=hash(pagesource) Then just write a save to disk and comparison routine. If the page has changed at all the hash value will be different. That's my take on it anyway. Someone could probably think of a better way. -Blake Garretson >From: Kent Tenney >To: >Date: Sun, 15 Jul 2001 10:38:59 -0500 >Subject: [Tutor] Code to check for changed Web page > >Howdy, > >I would like to be able to check if a web page has changed >since the last time I checked it. > >Does this already exist? > >Thanks, >Kent > > >-- Kent Tenney, kent@springfed.com on 07/15/2001 From rob@jam.rr.com Mon Jul 16 22:58:08 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 16 Jul 2001 16:58:08 -0500 Subject: [Tutor] Online interpreter? In-Reply-To: <200107161920.f6GJKTF02688@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: It looks like Python Server Pages may provide a solution, as well. http://jpython.dhs.org/pspdocs/samples.htm (I snipped this out of some frames, FYI.) One of the samples (including source) is the *Run Code* example. I have yet to install PSP to verify this, but they profess that "Its purpose is to allow you to enter a block of JPython code, have that code executed, and return any results generated back to you." I'm really interested in PSP, but have yet to play with it. Rob "Perl is worse than Python because people wanted it worse." Larry Wall (Creator of Perl), 14 Oct 1998 Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # Michael P. Reilly # Sent: Monday, July 16, 2001 2:20 PM # To: Mike Serpa # Cc: tutor@python.org # Subject: Re: [Tutor] Online interpreter? # # # Mike Serpa wrote # > There isn't an online interpreter of Python somewhere is there? Like # > this one I found for Ruby? http://www.ruby.ch/en/rubymain.shtml # > # > Sometimes I want to try some things out on Python when I'm away from my # > PC. # # The easiest method, imo, would be to make a JPython applet wrapped around # an instance of code.InteractiveConsole. # # Otherwise, if you just had CGI, make a picklable rexec class and wrap # the CGI around it. # # class PicklableRexec(rexec.RExec): # # keep state between CGI calls # def __getstate__(self): # # modules loaded # modnames = self.modules.keys() # # main module values, do not include modules # mainmod = self.modules['__main__'] # mainvals = [] # mainmods = [] # for name, value in mainmod.__dict__.items(): # if not isinstance(value, types.ModuleType): # mainvals.append( (name, value) ) # else: # mainmods.append( name ) # return (modnames, mainvals, mainmods) # def __setstate__(self, (modnames, mainvals, mainmods)): # self.__init__() # for name in modnames: # self.r_import(name) # for name in mainmods: # self.r_exec('input %s' % name) # mainmod = self.modules['__main__'] # for (name, value) in mainvals: # setattr(mainmod, name, value) # # Pickling an instance of this will create a text string that can be passed # to the next HTML form, properly quoted of course. When submitting the # form, unpickle the string to get the current state. The input string can # be called through the s_exec method. May have to fix up the I/O for CGI. # # -Arcege # # -- # +----------------------------------+-----------------------------------+ # | Michael P. Reilly | arcege@speakeasy.net | # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From steve@purestfeeling.net Mon Jul 16 23:30:30 2001 From: steve@purestfeeling.net (steve@purestfeeling.net) Date: Mon, 16 Jul 2001 16:30:30 -0600 (MDT) Subject: [Tutor] Need help with random numbers Message-ID: Greetings my fellow fine Pythonistas. Don't want to give too much away on what I'm trying to do, so I'm asking for help in one field. I need to generate a random integer within certain bounds, say 1-10, and feed it into a variable for use elsewhere in the program, so A= the generated number. What I was hoping, as a newbie, is that someone could give me an idea on how to do this. More specifically, the simplest way to do this for a stone cold(ish) newbie. Thanks -- Steve - Editor - www.formulaoneupdate.com ------------------------------------------------------------------- "We put the 'M' in Stupid." From ak@silmarill.org Mon Jul 16 23:33:50 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Mon, 16 Jul 2001 18:33:50 -0400 Subject: [Tutor] Need help with random numbers In-Reply-To: <"from steve"@purestfeeling.net> References: Message-ID: <20010716183350.A2745@sill.silmarill.org> On Mon, Jul 16, 2001 at 04:30:30PM -0600, steve@purestfeeling.net wrote: > Greetings my fellow fine Pythonistas. > > Don't want to give too much away on what I'm trying to do, so I'm asking > for help in one field. > > I need to generate a random integer within certain bounds, say 1-10, and > feed it into a variable for use elsewhere in the program, so A= the > generated number. > > What I was hoping, as a newbie, is that someone could give me an idea on > how to do this. More specifically, the simplest way to do this for a stone > cold(ish) newbie. > > Thanks > > -- > Steve - Editor - www.formulaoneupdate.com > ------------------------------------------------------------------- > "We put the 'M' in Stupid." var = random.randrange(1,11) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From mike@daboyz.org Tue Jul 17 00:19:02 2001 From: mike@daboyz.org (Mike Barrett) Date: Mon, 16 Jul 2001 16:19:02 -0700 (PDT) Subject: [Tutor] urllib.urlopen & open differences Message-ID: Hi, I was just playing with urllib and decided to mess around with a simple website monitoring tool. The idea is that the script would go out, read a page, and if the page was different than a file stored (an assumed 'good' copy), then it would send an alert. I ran into a problem however, when I noticed that filedescriptors returned by open() act differently when they 'read' than filedescriptors returned by urllib.urlopen(). It seems that the open() fd's return raw data (\'s escaped) whereas urllib.urlopen() returns the data normally (no escaping). Does anyone know if there is a way to change this? I'd like to just compare the two strings, but as of now it looks like I'm going to have to do some line editing. Any suggestions on how to deal with this? ________________________________________________________________________ Mike Barrett | Beer is proof that God loves us mike@daboyz.org | and wants us to be happy. www.daboyz.org | -- Benjamin Franklin ------------------------+----------------------------------------------- From acannon@vcn.bc.ca Mon Jul 16 23:56:48 2001 From: acannon@vcn.bc.ca (Alex Cannon) Date: Mon, 16 Jul 2001 15:56:48 -0700 (PDT) Subject: [Tutor] Online interpreter? In-Reply-To: <20010716160901.38183.qmail@web9605.mail.yahoo.com> Message-ID: On Mon, 16 Jul 2001, Mike Serpa wrote: > There isn't an online interpreter of Python somewhere is there? Like > this one I found for Ruby? http://www.ruby.ch/en/rubymain.shtml > > Sometimes I want to try some things out on Python when I'm away from my > PC. > > Mike Steve Spicklemire has an online Python interpreter running at http://physics-earthsci.uindy.edu/ph280/ Click on the examples for the interpreter (imports have been disabled). This is a for a class in physics, so the examples are obviously from this area. The dynaGraph.py module is at http://starship.python.net/crew/sspickle/ although it may be out of date. Alex From dyoo@hkn.eecs.berkeley.edu Tue Jul 17 00:38:40 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 16 Jul 2001 16:38:40 -0700 (PDT) Subject: [Tutor] Need help with random numbers In-Reply-To: Message-ID: On Mon, 16 Jul 2001 steve@purestfeeling.net wrote: > I need to generate a random integer within certain bounds, say 1-10, and > feed it into a variable for use elsewhere in the program, so A= the > generated number. Sounds good. Have you looked at the 'random' module yet? It has several functions that might be useful for the kind of random numbers you're trying to generate. Take a look here: http://python.org/doc/lib/module-random.html From ak@silmarill.org Tue Jul 17 00:44:08 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Mon, 16 Jul 2001 19:44:08 -0400 Subject: [Tutor] urllib.urlopen & open differences In-Reply-To: <"from mike"@daboyz.org> References: Message-ID: <20010716194408.A3119@sill.silmarill.org> On Mon, Jul 16, 2001 at 04:19:02PM -0700, Mike Barrett wrote: > Hi, I was just playing with urllib and decided to mess around with > a simple website monitoring tool. The idea is that the script would go > out, read a page, and if the page was different than a file stored (an > assumed 'good' copy), then it would send an alert. I ran into a problem > however, when I noticed that filedescriptors returned by open() act > differently when they 'read' than filedescriptors returned by > urllib.urlopen(). > It seems that the open() fd's return raw data (\'s > escaped) whereas urllib.urlopen() returns the data normally (no > escaping). Does anyone know if there is a way to change this? I'd like > to just compare the two strings, but as of now it looks like I'm going to > have to do some line editing. > Any suggestions on how to deal with this? you can hash() what the urlopen returns and save that.. Just a guess. > > ________________________________________________________________________ > Mike Barrett | Beer is proof that God loves us > mike@daboyz.org | and wants us to be happy. > www.daboyz.org | -- Benjamin Franklin > ------------------------+----------------------------------------------- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From steve@purestfeeling.net Tue Jul 17 01:40:49 2001 From: steve@purestfeeling.net (steve@purestfeeling.net) Date: Mon, 16 Jul 2001 18:40:49 -0600 (MDT) Subject: [Tutor] Need help with random numbers In-Reply-To: Message-ID: > > I need to generate a random integer within certain bounds, say 1-10, and > > feed it into a variable for use elsewhere in the program, so A= the > > generated number. > > Sounds good. Have you looked at the 'random' module yet? It has several > functions that might be useful for the kind of random numbers you're > trying to generate. > > Take a look here: > > http://python.org/doc/lib/module-random.html Thanks. I just couldn't find anything helpful in all the docs I have here. Whereas most languages seem to have an absence of info, Python has an overabundance. Thanks again. -- Steve - Editor - www.formulaoneupdate.com ------------------------------------------------------------------- "We put the 'M' in Stupid." From wesc@deirdre.org Tue Jul 17 06:41:28 2001 From: wesc@deirdre.org (Wesley Chun) Date: Mon, 16 Jul 2001 22:41:28 -0700 (PDT) Subject: [Tutor] Need help with random numbers In-Reply-To: Message-ID: On Mon, 16 Jul 2001 steve@purestfeeling.net wrote: > > I need to generate a random integer within certain bounds, say 1-10, and > feed it into a variable for use elsewhere in the program, so A= the > generated number. you want the 'random' module. it's got the following useful functions: randint(a, b): takes two integer values and returns a random integer between those values inclusive, i.e., a <= N <= b uniform(a, b): does almost the same thing as randint(), but returns a float and is inclusive only of the smaller number (exclusive of the larger number), i.e. a <= N < b random(): works just like uniform() except that the smaller number is fixed at 0.0, and the larger number is fixed at 1.0, i.e., 0.0 <= N < 1.0 choice(seq): given a sequence, randomly selects and returns a sequence item randrange([start,] stop[, step]): obsoletes randint() in 2.0. Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)); recall that range(a, b) counts from a to (b-1), so randrange(a, b) returns an integer inclusive of a but exclusive of b, i.e. a <= N < b - - - - - - - - - - - - - - - - - - - - here's an example using random.randrange() and numbers b/w 1 and 10: >>> import random >>> for i in range(20): print random.randrange(1, 11), 6 8 8 1 9 10 7 3 6 1 3 1 6 7 4 2 7 7 7 3 >>> >>> for i in range(20): print random.randrange(1, 11), 5 9 6 8 3 3 9 10 4 9 9 9 3 10 9 1 7 4 7 5 >>> More information on random numbers is available in Section 5.7 in Core Python Programming on pp. 123-24. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From kp87@lycos.com Tue Jul 17 10:23:20 2001 From: kp87@lycos.com (kevin parks) Date: Tue, 17 Jul 2001 18:23:20 +0900 Subject: [Tutor] Need help with random numbers Message-ID: Since it has be brought up, I'd like to know: random.random() takes no args and returns a float in the range 0.0-1.0. How would you return random floats of a different range? say: 1.0 - 12.0? random() Return the next random floating point number in the range [0.0, 1.0). cheers, kevin parks seoul, korea Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From lonetwin@yahoo.com Tue Jul 17 10:53:36 2001 From: lonetwin@yahoo.com (steve) Date: Tue, 17 Jul 2001 15:23:36 +0530 Subject: [Tutor] Need help with random numbers In-Reply-To: References: Message-ID: <01071715233601.06120@mercury.in.cqsl.com> On Tuesday 17 July 2001 14:53, you wrote: > Since it has be brought up, I'd like to know: > > random.random() takes no args and returns a float in the range 0.0-1.0.= How > would you return random floats of a different range? say: 1.0 - 12.0? > > random() > Return the next random floating point number in the range [0.0, > 1.0). > > cheers, > > kevin parks > seoul, korea Although, I haven't had reason to use random yet (I'm still learning), I= 'd=20 assume a function >>> def func(x, y): =20 =2E.. return random.random() + random.choice(range(x,y)) should return random enough float values between x and y Peace Steve --=20 |||||||||||||||||||||| |||||||||#####|||||||| ||||||||#######||||||| ||||||||# O O #||||||| ||||||||#\ ~ /#||||||| ||||||##||\_/||##||||| |||||#||||||||||##|||| ||||#||||||||||||##||| ||||#|||||||||||||##||=09 |||/\##|||||||||##/\||=09 |/ \#########/ \=09 |\ \#######/ /=09 ||\____/#######\____/|=09 =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=09 Debug is human, de-fix divine. =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 From NHYTRO@compuserve.com Tue Jul 17 14:18:06 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Tue, 17 Jul 2001 09:18:06 -0400 Subject: [Tutor] Sporadical bug? Message-ID: <200107170918_MC3-D97A-DA5@compuserve.com> Hi tutors! here is a snippet of my ftp upload code: if ftpurls: ....global finalhtml ....for j, k in zip(allimagetags, modified_image_tags): ........finalhtml =3D string.replace(usercontent, j, k) ### where "allimagetags" is a list of image tags like c:\windows\temp\myimage.jpg modified_image_tags is a list of modified "allimagetags" example ..\users\myimage.jpg usercontent is a string block of HTML, this block also contains all imag= e tags. My problem is, upon storing "finalhtml" in a database, I noticed that the= image tags were not being properly replaced. If allimagetags contained 3 image tags, all 3 are stored in the database but only the 3 is really replaced in the string block "usercontent" . Am I using the "zip" commabd wrongly? Thanks Sharriff = From toodles@yifan.net Tue Jul 17 14:54:39 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Tue, 17 Jul 2001 21:54:39 +0800 Subject: [Tutor] Need help with random numbers In-Reply-To: Message-ID: > Since it has be brought up, I'd like to know: > > random.random() takes no args and returns a float in the range > 0.0-1.0. How would you return random floats of a different range? > say: 1.0 - 12.0? > *cuts and pastes from Wesley's post* uniform(a, b): does almost the same thing as randint(), but returns a float and is inclusive only of the smaller number (exclusive of the larger number), i.e. a <= N < b Regards, Andrew Wilkins From wesc@deirdre.org Tue Jul 17 15:20:24 2001 From: wesc@deirdre.org (Wesley Chun) Date: Tue, 17 Jul 2001 07:20:24 -0700 (PDT) Subject: [Tutor] Need help with random numbers In-Reply-To: Message-ID: On Tue, 17 Jul 2001, kevin parks wrote: > > Since it has be brought up, I'd like to know: > > random.random() takes no args and returns a float in the range > 0.0-1.0. How would you return random floats of a different range? say: > 1.0 - 12.0? > > random() > Return the next random floating point number in the range [0.0, 1.0). kevin, you must have just skipped over it... but it was in my post! uniform(a, b): does almost the same thing as randint(), but returns a float and is inclusive only of the smaller number (exclusive of the larger number), i.e. a <= N < b hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From onav@yahoo.com Tue Jul 17 16:59:39 2001 From: onav@yahoo.com (Mike Serpa) Date: Tue, 17 Jul 2001 08:59:39 -0700 (PDT) Subject: [Tutor] Online interpreter? In-Reply-To: Message-ID: <20010717155939.30988.qmail@web9608.mail.yahoo.com> Thanks! That's close enough. NumPy overwrites one of the functions I was playing with, but until something else comes up that will do nicely for trying smalls scripts online. Mike > > Message: 13 > Date: Mon, 16 Jul 2001 15:56:48 -0700 (PDT) > From: Alex Cannon > To: tutor@python.org > Subject: Re: [Tutor] Online interpreter? > > On Mon, 16 Jul 2001, Mike Serpa wrote: > > > There isn't an online interpreter of Python somewhere is there? > Like > > this one I found for Ruby? http://www.ruby.ch/en/rubymain.shtml > > > > Sometimes I want to try some things out on Python when I'm away > from my > > PC. > > > > Mike > > Steve Spicklemire has an online Python interpreter running at > > http://physics-earthsci.uindy.edu/ph280/ > > Click on the examples for the interpreter (imports have been > disabled). > This is a for a class in physics, so the examples are obviously from > this > area. The dynaGraph.py module is at > > http://starship.python.net/crew/sspickle/ > > although it may be out of date. > > Alex > > > __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From dyoo@hkn.eecs.berkeley.edu Tue Jul 17 17:14:46 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jul 2001 09:14:46 -0700 (PDT) Subject: [Tutor] Need help with random numbers In-Reply-To: Message-ID: On Tue, 17 Jul 2001, kevin parks wrote: > Since it has be brought up, I'd like to know: > > random.random() takes no args and returns a float in the range > 0.0-1.0. How would you return random floats of a different range? say: > 1.0 - 12.0? > > random() > Return the next random floating point number in the range [0.0, > 1.0). There's a good reason why random.random() gives us a floating point between 0.0 and 1.0: it allows us to "scale" it up to a larger range if we need it. For example, to get a random float between 0.0 and 10.0 (more precisely, "[0.0, 10.0)" ), we can do this: some_number = random.random() * 10.0 It's like "stretching" the random function. I'm curious: how does random.uniform() actually work? ### def uniform(self, a, b): """Get a random number in the range [a, b).""" return a + (b-a) * self.random() ### Yup, that's how they do it as well. They do a little bit more to move the range from: [0, b-a) to [a, b) but otherwise, they use the stretching principle. Hope this helps! From onav@yahoo.com Tue Jul 17 18:06:52 2001 From: onav@yahoo.com (Mike Serpa) Date: Tue, 17 Jul 2001 10:06:52 -0700 (PDT) Subject: [Tutor] print as columns In-Reply-To: Message-ID: <20010717170652.74022.qmail@web9604.mail.yahoo.com> > > I have a couple suggestions regarding your printListColumns: > > 1) you can find the longest in a list of lists by using the > reduce function which keeps applying the function to > successive pairs of elements from a list: > > n=len(reduce(lambda a,b:max(a,b),l)) > --- ------------------- - > ^ ^ ^->the list of lists (called Lists > in > your program) > | | > | |_ the function which returns the longer of two lists > | > |_ when the reduce is done we will know the longest list, len > gives the > length of it > > Example: > > a=[1,2,3,4] > b=[5,6,7] > c=[8,9,10,11,12] > > n=len( reduce( lambda a,b:max(a,b), [a,b,c] )) > > n is 5 Couldn't we shorten this to: n=len(max(lists)) It seems that everything I figure out how to do is already in a module somewhere. Question for expert Python coders (or any lang.) Do you ever get to the stage where you don't have to constantly look things up in the lang docs? > > 2) Instead of padding, you might consider using the try/except > construction to not print the list elements that don't > exist. Here's how it looks for a list of 3 elements which is to be > printed in 5 rows. > > for j in range(5): > try: > print str(l[j].ljust(20), #if l[j] exists, print it > except: > print ''.ljust(20) #otherwise format a null string > > Thanks for the thought provoking post. > So I don't have to lace them then. So we get: def printListColumns(*lists): longestLength=len(max(lists)) for row in range(longestLength): # number of rows for column in lists: # number of columns try: print str(column[row]).ljust(20), # print if exists except: print ''.ljust(20) # blank if not print Great! We've gone from 20 lines to 15 to 9. More importantly it's now much simpler. The only thing I can think to add is a max number of columns so it doesn't go off the screen. Or if columns is > 4 then split into two tables. Or adjust columns to largest element, etc. Don't need to yet for what I'm using if for, but will be easier now. Thanks. Mike __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From kromag@nsacom.net Tue Jul 17 22:05:09 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Tue, 17 Jul 2001 14:05:09 -0700 (PDT) Subject: [Tutor] Hooked on innumeracy.... Message-ID: <200107172105.f6HL59L16802@pop.nsacom.net> I have been attempting to make a little amortization calculator: -----------------begin mort-------------------- def mort(cash,interest, payment): count=1 bait=cash #retain the original amount for final calucation of total interest. screwing=interest/12 interest=screwing+1 try: while cash > payment: cash= cash * interest cash = cash - payment count=count +1 finally: ouch=payment * count + cash # number of payments * payment amount + remainder print `count` + ' payments of ' + `payment` + ' each.' print 'Plus one payment of ' + `cash` print `ouch -bait ` + ' total screwing.' -------------------end mort--------------------- Now I don't have any idea if my math is right here. It seems logical to me, but then, I majored in english and drama. I get the following weirdness when I attempt to use it: ---------------begin weirdnesss------------------ >>> from kersplort import mort >>> mort(4000,0.07,250.00) 17 payments of 250.0 each. Plus one payment of 210.26436268423424 460.26436268423458 total screwing. >>> mort(4000,0.07,350.00) 12 payments of 350.0 each. Plus one payment of 300.00544031562856 500.00544031562822 total screwing. >>> mort(4000,0.07,150.00) 30 payments of 150.0 each. Plus one payment of 10.313364085220485 510.3133640852202 total screwing. >>> ---------------end weirdness--------------------- You'll note that the amount of screwing (total interest payments) seems to be nonlinear with the payment amount. What am I missing here? I fully admit to being an arithmetic moron, so flame away! :-) From arcege@speakeasy.net Tue Jul 17 20:09:00 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 17 Jul 2001 15:09:00 -0400 (EDT) Subject: [Tutor] print as columns In-Reply-To: <20010717170652.74022.qmail@web9604.mail.yahoo.com> from "Mike Serpa" at Jul 17, 2001 10:06:52 AM Message-ID: <200107171909.f6HJ90E05340@dsl092-074-184.bos1.dsl.speakeasy.net> Mike Serpa wrote > > 1) you can find the longest in a list of lists by using the > > reduce function which keeps applying the function to > > successive pairs of elements from a list: > > > > n=len(reduce(lambda a,b:max(a,b),l)) > > --- ------------------- - > > ^ ^ ^->the list of lists (called Lists > > in > > your program) > > | | > > | |_ the function which returns the longer of two lists > > | > > |_ when the reduce is done we will know the longest list, len > > gives the > > length of it > > > > Example: > > > > a=[1,2,3,4] > > b=[5,6,7] > > c=[8,9,10,11,12] > > > > n=len( reduce( lambda a,b:max(a,b), [a,b,c] )) > > > > n is 5 > > Couldn't we shorten this to: > n=len(max(lists)) > > It seems that everything I figure out how to do is already in a module > somewhere. Question for expert Python coders (or any lang.) Do you > ever get to the stage where you don't have to constantly look things > up in the lang docs? Actually, none of these work. The max of a list of lists is to find out which list is greater, by component, not the longer. >>> a = [1, 2, 3] >>> b = [3, 4, 5, 6] >>> max(a, b) [3, 4, 5, 6] >>> c = [7, 8, 9] >>> max(b, c) [7, 8, 9] You probably want to use: reduce(max, map(len, seq_o_lists)) >>> reduce(max, map(len, (a, b, c))) 4 About the only thing I look to the docs for now are some of modules I use less frequently, or when trying to verify something for the list. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From memperad@iaware.org Tue Jul 17 20:27:45 2001 From: memperad@iaware.org (Michael Emperador) Date: Tue, 17 Jul 2001 12:27:45 -0700 (PDT) Subject: [Tutor] webbrowser Message-ID: I am new to Python and this mailing list. I have a question that I haven't found in the archives. I have a cgi script that uses the webbrowser module to open a new browser. I can run this from the interactive prompt, but when I run the script from the browser, I get the following output in the new browser window: Your Terminal type is unknown! Enter a terminal type: [vt100] TERMINAL TYPE IS SET TO vt100 Any ideas? Mike From dsh8290@rit.edu Tue Jul 17 21:17:59 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 17 Jul 2001 16:17:59 -0400 Subject: [Tutor] webbrowser In-Reply-To: ; from memperad@iaware.org on Tue, Jul 17, 2001 at 12:27:45PM -0700 References: Message-ID: <20010717161759.C16329@harmony.cs.rit.edu> On Tue, Jul 17, 2001 at 12:27:45PM -0700, Michael Emperador wrote: | I am new to Python and this mailing list. I have a question that I | haven't found in the archives. I have a cgi script that uses the | webbrowser module to open a new browser. I can run this from the | interactive prompt, but when I run the script from the browser, I get the | following output in the new browser window: | | Your Terminal type is unknown! | | Enter a terminal type: [vt100] | TERMINAL TYPE IS SET TO vt100 | | | Any ideas? What platform are you running on? What are you trying to do with the script? BTW, I don't think it makes sense for CGI scripts to run web browsers -- CGI scripts run on the server (ie www.foo.com) and not on the client's machine (ie your box). -D From DavidCraig@PIA.CA.GOV Tue Jul 17 21:27:37 2001 From: DavidCraig@PIA.CA.GOV (DavidCraig@PIA.CA.GOV) Date: Tue, 17 Jul 2001 13:27:37 -0700 Subject: [Tutor] Opening files - Newbie Question Message-ID: Example from Wes Chun's 'Core Python Programming' page 38: # Open files to window to read filename = raw_input('Enter file name: ') file = open(filename, 'r') allLines = file.readlines() file.close() for eachLine in allLines: print eachLine When I run the file and enter a text file to be read I get: Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> Enter file name: bruce Traceback (most recent call last): File "C:/Python21/Practice/File_open.py", line 4, in ? file = open(filename, 'r') IOError: [Errno 2] No such file or directory: 'bruce' What am I missing? I have tried to input the exact path. Must the file be a text file to be read? Thanks for any help. D. H. Craig, CSM From sheila@thinkspot.net Tue Jul 17 21:37:48 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 17 Jul 2001 13:37:48 -0700 Subject: [Tutor] Opening files - Newbie Question In-Reply-To: References: Message-ID: <43E99161E4B@kserver.org> The file doesn't have to be a text file to be opened. However, sometimes on the Windows operating system, the operating system hides the file extensions on the file names. Are you sure that your file is named exactly "bruce" ? What application did you use to create the file name "bruce"? If you used Notepad, it probably saved the file as "bruce.txt", or if you used WordPad or MS Word, it probably saved the file as "bruce.doc". Which Windows operating system are you running? Win98? WinNT? Win2000? I think that the key is to set your computer so that it is showing all the file extensions on your filenames, so that you can see for certain what the exact name of your "bruce" file is. Alternatively, you could get Python to list the filenames for all the files in the directory. Ah, something else I thought of... You need to type the full path to the file "bruce". Is it in the same directory as your script? If not, you must type the full path. When you are prompted to enter the file name, you need to enter something like: C:\path\to\file\bruce.ext HTH -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Tue, 17 Jul 2001 13:27:37 -0700, DavidCraig@PIA.CA.GOV wrote about [Tutor] Opening files - Newbie Question: :Example from Wes Chun's 'Core Python Programming' page 38: : : :# Open files to window to read : :filename = raw_input('Enter file name: ') :file = open(filename, 'r') :allLines = file.readlines() :file.close() :for eachLine in allLines: : print eachLine : :When I run the file and enter a text file to be read I get: : :Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 :Type "copyright", "credits" or "license" for more information. :IDLE 0.8 -- press F1 for help :>>> :Enter file name: bruce :Traceback (most recent call last): : File "C:/Python21/Practice/File_open.py", line 4, in ? : file = open(filename, 'r') :IOError: [Errno 2] No such file or directory: 'bruce' : :What am I missing? I have tried to input the exact path. Must the file be :a text file to be read? : :Thanks for any help. : :D. H. Craig, CSM : : : :_______________________________________________ :Tutor maillist - Tutor@python.org :http://mail.python.org/mailman/listinfo/tutor From DavidCraig@PIA.CA.GOV Tue Jul 17 21:42:11 2001 From: DavidCraig@PIA.CA.GOV (DavidCraig@PIA.CA.GOV) Date: Tue, 17 Jul 2001 13:42:11 -0700 Subject: [Tutor] Opening files - Newbie Question Message-ID: Thanks, Sheila!!!!!!! The file extensions and exact path got it. I'm running on WIN 98. D. H. Craig, CSM From rob@jam.rr.com Tue Jul 17 21:47:11 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 17 Jul 2001 15:47:11 -0500 Subject: [Tutor] Opening files - Newbie Question In-Reply-To: Message-ID: I've tried to reproduce your situation a bit. Here's what I found. I saved the code from your email into a file Untitled.py and as Bruce.txt in D:\Python21\ (Windows box). In PythonWin, the following occured when I ran Untitled.py >>> import Untitled # A separate window opened prompting me to 'Enter file name: ' and I tried 'Bruce' with no success, and 'D:\Python21\Bruce' with similar results (shown here): Traceback (most recent call last): File "", line 1, in ? File "d:\python21\Untitled.py", line 2, in ? file = open(filename, 'r') IOError: [Errno 2] No such file or directory: 'D:\\Python21\\Bruce' >>> import Untitled >>> reload(Untitled) # Success this time, as I entered 'D:\Python21\Bruce.txt' and saw its contents printed here. filename = raw_input('Enter file name: ') file = open(filename, 'r') allLines = file.readlines() file.close() for eachLine in allLines: print eachLine # But when I tried to open a GIF image file, it failed, as shown below. But this didn't surprise me too much, because your code specified line-by-line reading, which implied text to me. >>> import Untitled >>> reload(Untitled) GIF89aJ >>> No matter whether you're using Windows or not (or IDLE versus PythonWin), I'd expect you to get similar results. hopefully helpful, Rob "Perl is worse than Python because people wanted it worse." Larry Wall (Creator of Perl), 14 Oct 1998 Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # DavidCraig@PIA.CA.GOV # Sent: Tuesday, July 17, 2001 3:28 PM # To: tutor@python.org # Subject: [Tutor] Opening files - Newbie Question # # # Example from Wes Chun's 'Core Python Programming' page 38: # # # # Open files to window to read # # filename = raw_input('Enter file name: ') # file = open(filename, 'r') # allLines = file.readlines() # file.close() # for eachLine in allLines: # print eachLine # # When I run the file and enter a text file to be read I get: # # Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 # Type "copyright", "credits" or "license" for more information. # IDLE 0.8 -- press F1 for help # >>> # Enter file name: bruce # Traceback (most recent call last): # File "C:/Python21/Practice/File_open.py", line 4, in ? # file = open(filename, 'r') # IOError: [Errno 2] No such file or directory: 'bruce' # # What am I missing? I have tried to input the exact path. Must # the file be # a text file to be read? # # Thanks for any help. # # D. H. Craig, CSM # # # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From DavidCraig@PIA.CA.GOV Tue Jul 17 21:54:11 2001 From: DavidCraig@PIA.CA.GOV (DavidCraig@PIA.CA.GOV) Date: Tue, 17 Jul 2001 13:54:11 -0700 Subject: [Tutor] Opening files - Newbie Question Message-ID: Thanks Rob!! That was interesting to try with different types of files. I can see why it would not work with graphic files,etc. The reload was interesting too. Dave D. H. Craig, CSM From dsh8290@rit.edu Tue Jul 17 22:12:53 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 17 Jul 2001 17:12:53 -0400 Subject: [Tutor] Opening files - Newbie Question In-Reply-To: <43E99161E4B@kserver.org>; from sheila@thinkspot.net on Tue, Jul 17, 2001 at 01:37:48PM -0700 References: <43E99161E4B@kserver.org> Message-ID: <20010717171252.A16390@harmony.cs.rit.edu> On Tue, Jul 17, 2001 at 01:37:48PM -0700, Sheila King wrote: | You need to type the full path to the file "bruce". Is it in the same | directory as your script? If not, you must type the full path. It doesn't need to be an absolute path, a relative path is fine. A relative path must be relative to os.getcwd() | When you are prompted to enter the file name, you need to enter | something like: | | C:\path\to\file\bruce.ext ^^ ^^ This path, while bogus, shows why windows paths are particularly evil. Here is an example : >>> path = "C:\path\to\file\bruce.ext" >>> print path C:\path o?ilruce.ext >>> The '\t' expands to a tab and '\b' expands to a backspace character. It's not likely you have paths containing such characters. The backspace character might not even be legal on windows, I'm not sure. Ok, so if you get the input using raw_input it will work, but not if you write the paths in your code. Use forward slashes instead -- the open() function (and the underlying fopen() function) will be perfectly happy with them. -D From dyoo@hkn.eecs.berkeley.edu Tue Jul 17 22:23:06 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jul 2001 14:23:06 -0700 (PDT) Subject: [Tutor] print as columns [using apply()] In-Reply-To: <200107171909.f6HJ90E05340@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: On Tue, 17 Jul 2001, Michael P. Reilly wrote: > > Couldn't we shorten this to: > > n=len(max(lists)) > > > > It seems that everything I figure out how to do is already in a module > > somewhere. Question for expert Python coders (or any lang.) Do you > > ever get to the stage where you don't have to constantly look things > > up in the lang docs? > > Actually, none of these work. The max of a list of lists is to find out > which list is greater, by component, not the longer. > > >>> a = [1, 2, 3] > >>> b = [3, 4, 5, 6] > >>> max(a, b) > [3, 4, 5, 6] > >>> c = [7, 8, 9] > >>> max(b, c) > [7, 8, 9] > > You probably want to use: reduce(max, map(len, seq_o_lists)) > > >>> reduce(max, map(len, (a, b, c))) This problem shows one instance where apply() might be useful: max() can take in as many arguments as we can feed into it: ### >>> max(3, 1, 4, 1, 5, 9, 2, 6) 9 ### so we don't really even need the reduce if we use the apply() function: ### apply(max, map(len, (a, b, c))) ### If you have any questions, feel free to ask! From dyoo@hkn.eecs.berkeley.edu Tue Jul 17 22:35:58 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jul 2001 14:35:58 -0700 (PDT) Subject: [Tutor] print as columns [using apply()] In-Reply-To: Message-ID: On Tue, 17 Jul 2001, Danny Yoo wrote: > > You probably want to use: reduce(max, map(len, seq_o_lists)) > > > > >>> reduce(max, map(len, (a, b, c))) > > > This problem shows one instance where apply() might be useful: max() can > take in as many arguments as we can feed into it: > > ### > >>> max(3, 1, 4, 1, 5, 9, 2, 6) > 9 > ### > > so we don't really even need the reduce if we use the apply() function: > > ### > apply(max, map(len, (a, b, c))) > ### Whoops! I take it back --- there is one particularly evil case where apply() doesn't apply: ### >>> apply(max, map(len, ([1],))) ## oh no! Traceback (most recent call last): File "", line 1, in ? TypeError: min() or max() arg must be a sequence ### The guilt is not really on apply(), but max() --- max() can't handle a single argument: it always assumes that it works with at least two: ### >>> max(42) Traceback (most recent call last): File "", line 1, in ? TypeError: min() or max() arg must be a sequence ### On the other hand, reduce() should work on this pathological example: ### >>> reduce(max, map(len, ([1],))) 1 ### I must remind myself to test my programs with small "boundary" cases, just to make sure nothing leaks out... *grin* From arcege@speakeasy.net Tue Jul 17 22:55:47 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 17 Jul 2001 17:55:47 -0400 (EDT) Subject: [Tutor] print as columns [using apply()] In-Reply-To: from "Danny Yoo" at Jul 17, 2001 02:35:58 PM Message-ID: <200107172155.f6HLtmc05652@dsl092-074-184.bos1.dsl.speakeasy.net> Danny Yoo wrote > The guilt is not really on apply(), but max() --- max() can't handle a > single argument: it always assumes that it works with at least two: > [snipped] > > On the other hand, reduce() should work on this pathological example: > > ### > >>> reduce(max, map(len, ([1],))) > 1 > ### > > > I must remind myself to test my programs with small "boundary" cases, just > to make sure nothing leaks out... *grin* Actually, on this, I'm almost surprised. I'd think that you would have to add the trailing initial value to reduce. >>> reduce(max, map(len, ([1],)), 0) Interestingly, max((1,)) returns 1 (yikes). -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From onav@yahoo.com Tue Jul 17 23:02:54 2001 From: onav@yahoo.com (Mike Serpa) Date: Tue, 17 Jul 2001 15:02:54 -0700 (PDT) Subject: [Tutor] print as columns In-Reply-To: <200107171909.f6HJ90E05340@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: <20010717220255.39501.qmail@web9605.mail.yahoo.com> > > > > Couldn't we shorten this to: > > n=len(max(lists)) > > > > It seems that everything I figure out how to do is already in a > module > > somewhere. Question for expert Python coders (or any lang.) Do you > > ever get to the stage where you don't have to constantly look > things > > up in the lang docs? > > Actually, none of these work. The max of a list of lists is to find > out > which list is greater, by component, not the longer. > > >>> a = [1, 2, 3] > >>> b = [3, 4, 5, 6] > >>> max(a, b) > [3, 4, 5, 6] > >>> c = [7, 8, 9] > >>> max(b, c) > [7, 8, 9] > > You probably want to use: reduce(max, map(len, seq_o_lists)) > > >>> reduce(max, map(len, (a, b, c))) > 4 > Okay, yeah I see how max() works now. But we don't need reduce, do we? Just: max(map(len, (a, b, c))) right? Or am I missing something? __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From wesc@deirdre.org Tue Jul 17 23:15:06 2001 From: wesc@deirdre.org (Wesley Chun) Date: Tue, 17 Jul 2001 15:15:06 -0700 (PDT) Subject: [Tutor] Opening files - Newbie Question In-Reply-To: <20010717171252.A16390@harmony.cs.rit.edu> Message-ID: On Tue, 17 Jul 2001, D-Man wrote: > On Tue, Jul 17, 2001 at 01:37:48PM -0700, Sheila King wrote: > > | C:\path\to\file\bruce.ext > ^^ ^^ > > This path, while bogus, shows why windows paths are particularly evil. > Here is an example : > > >>> path = "C:\path\to\file\bruce.ext" > >>> print path > C:\path o?ilruce.ext > >>> > > The '\t' expands to a tab and '\b' expands to a backspace character. > It's not likely you have paths containing such characters. The > backspace character might not even be legal on windows, I'm not sure. > > Ok, so if you get the input using raw_input it will work, but not if > you write the paths in your code. Use forward slashes instead -- the > open() function (and the underlying fopen() function) will be > perfectly happy with them. the other thing you can do is to use raw strings: >>> path = r"C:\path\to\file\bruce.ext" >>> print path C:\path\to\file\bruce.ext >>> also, recall some of the useful attributes of the 'os' module that we talked about last week... it takes the pain out of manipulating the OS- dependent symbols used for file path names: Attribute Description --------- ----------- linesep string used to separate lines in a file sep string used to separate file pathname components pathsep string used to delimit a set of file pathnames curdir string name for current working directory pardir string name for parent (of current working dir) If you just "import os" in your script, no matter what platform that script is running on, the corect string values will be available in these attributes, i.e., on UNIX, os.sep == '/' and on the Mac, os.sep == ':', and on Windoze, os.sep == '\\'. The info above is basically Table 9.2 in Core Python Programming on p. 263. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Silicon Valley-SF Bay Area Python users group: http://baypiggies.org "Core Python Programming", Prentice Hall PTR, December 2000 http://starship.python.net/crew/wesc/cpp/ wesley.j.chun :: wesc@baypiggies.org cyberweb.consulting :: silicon.valley, ca http://www.roadkill.com/~wesc/cyberweb/ From DavidCraig@PIA.CA.GOV Tue Jul 17 23:32:43 2001 From: DavidCraig@PIA.CA.GOV (DavidCraig@PIA.CA.GOV) Date: Tue, 17 Jul 2001 15:32:43 -0700 Subject: [Tutor] Opening files - Newbie Question Message-ID: This helps alot. Thank you. I am trying to learn multiple ways to do things and this will provide additional methods for me. D. H. Craig, CSM From GBunting864@Worldsavings.com Wed Jul 18 00:04:52 2001 From: GBunting864@Worldsavings.com (Bunting, Glen, IG (x)) Date: Tue, 17 Jul 2001 18:04:52 -0500 Subject: [Tutor] http_proxy variable Message-ID: <97E9FA3149D0D311BE5800008349BB27018D5E8C@ok1ems1.worldsavings.com> Hi, I have just downloaded the NTLM Authorization proxy server fro the Vaults of Parnassus. I works pretty good. I can use other applications besides IE to access the internet from work now. However I am unable to get Python to use the proxy using urllib. According to the Library Reference, I need to: set the http_proxy, ftp_proxy or gopher_proxy environment variables to a URL that identifies the proxy server before starting the Python interpreter. For example (the "%" is the command prompt): % http_proxy="http://www.someproxy.com:3128" % export http_proxy % python Can someone tell me how to do this running Activestate Python on Windows 2000? Thanks Glen ***************************************************************************** If you are not the intended recipient of this e-mail, please notify the sender immediately. The contents of this e-mail do not amend any existing disclosures or agreements unless expressly stated. ***************************************************************************** From memperad@iaware.org Wed Jul 18 00:08:14 2001 From: memperad@iaware.org (Michael Emperador) Date: Tue, 17 Jul 2001 16:08:14 -0700 (PDT) Subject: [Tutor] webbrowser In-Reply-To: <20010717161759.C16329@harmony.cs.rit.edu> Message-ID: I am running on Linux Suse7.2. I have a form(on my personal site) that calls this cgi script. Based on input, it will redirect to another page on the server(i.e., a personal page). This is what I'm trying to open in a browser. I'm simply trying to get to a another page based on user input. I would greatly appreciate your input and any advice you could share. Mike On Tue, 17 Jul 2001, D-Man wrote: > Date: Tue, 17 Jul 2001 16:17:59 -0400 > From: D-Man > To: tutor@python.org > Subject: Re: [Tutor] webbrowser > > On Tue, Jul 17, 2001 at 12:27:45PM -0700, Michael Emperador wrote: > | I am new to Python and this mailing list. I have a question that I > | haven't found in the archives. I have a cgi script that uses the > | webbrowser module to open a new browser. I can run this from the > | interactive prompt, but when I run the script from the browser, I get the > | following output in the new browser window: > | > | Your Terminal type is unknown! > | > | Enter a terminal type: [vt100] > | TERMINAL TYPE IS SET TO vt100 > | > | > | Any ideas? > > What platform are you running on? > > What are you trying to do with the script? > > BTW, I don't think it makes sense for CGI scripts to run web browsers > -- CGI scripts run on the server (ie www.foo.com) and not on the > client's machine (ie your box). > > -D > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From onav@yahoo.com Wed Jul 18 00:12:02 2001 From: onav@yahoo.com (Mike Serpa) Date: Tue, 17 Jul 2001 16:12:02 -0700 (PDT) Subject: [Tutor] print as columns [using apply()] In-Reply-To: Message-ID: <20010717231202.50728.qmail@web9605.mail.yahoo.com> > > Danny Yoo wrote > > The guilt is not really on apply(), but max() --- max() can't > handle a > > single argument: it always assumes that it works with at least two: > > > [snipped] > > > > On the other hand, reduce() should work on this pathological > example: > > > > ### > > >>> reduce(max, map(len, ([1],))) > > 1 > > ### > > > > > > I must remind myself to test my programs with small "boundary" > cases, just > > to make sure nothing leaks out... *grin* > > Actually, on this, I'm almost surprised. I'd think that you would > have > to add the trailing initial value to reduce. > > >>> reduce(max, map(len, ([1],)), 0) > > Interestingly, max((1,)) returns 1 (yikes). > > -Arcege > Okay, I think I've got it now. You still don't need reduce or apply. a = [1,2,3] b = [4,5,6,7] c = [8,9] max(map(len, (a, b, c))) # or max(map(len, (a,))) still works even if there is only one list. the map function returns a list e.g. [3,4,2] # or [3] max([3]) works fine. If it's really preferable to use reduce or apply here please explain it to me because I don't get it. Mike __________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/ From kp87@lycos.com Wed Jul 18 00:18:24 2001 From: kp87@lycos.com (kevin parks) Date: Wed, 18 Jul 2001 08:18:24 +0900 Subject: [Tutor] curdling seq Message-ID: I've got a little function that takes a list and subdivides it randomly. so that i can say: >>> x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] >>> clump.clump(x) and it will return a list like any of the below lists: [[1], [2, 3], [4], [5, 6, 7, 8, 9], [10, 11, 12], [13, 14], [15], [16, 17], [18], [19, 20, 21], [22], [23, 24]] [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10, 11, 12], [13, 14], [15, 16], [17, 18, 19, 20], [21, 22], [23, 24]] [[1], [2, 3, 4], [5, 6], [7, 8], [9, 10, 11, 12, 13, 14], [15, 16, 17], [18], [19], [20, 21, 22], [23, 24]] [[1, 2, 3, 4], [5, 6], [7, 8], [9], [10, 11, 12, 13], [14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]] [[1, 2], [3], [4, 5], [6, 7], [8], [9], [10, 11, 12, 13], [14, 15, 16, 17, 18, 19, 20], [21, 22], [23, 24]] So, now what i'd like to do is make a function that would be like: curdle(seq, prob) where prob is the probability that there will be a partition between any two elements. So that should be something like: import random def curdle(seq, Prob): if not seq: return [] result = [seq[:1]] for e in seq[1:]: # either extend last clump or start a new one, depending on Prob if random.random() < Prob: # extend last lump result[-1].append(e) else: # start a new lump result.append([e]) return result But, i am not 100% sure i am getting the right results. It seems as though i am, but i was hoping that if it was off someone with knowledge of testing randomness would give it the once over. Prob set to 0.5 should give me 50% chance of a new subsequence. 0.0 should give me subdivisions all the time and 1.0 should give me the flat list back (or rather on big list nested as an element inside the list. cheers, kevin parks Seoul, Korea kp87@lycos.com Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From dsh8290@rit.edu Wed Jul 18 00:20:18 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 17 Jul 2001 19:20:18 -0400 Subject: [Tutor] webbrowser In-Reply-To: ; from memperad@iaware.org on Tue, Jul 17, 2001 at 04:08:14PM -0700 References: <20010717161759.C16329@harmony.cs.rit.edu> Message-ID: <20010717192018.A16480@harmony.cs.rit.edu> On Tue, Jul 17, 2001 at 04:08:14PM -0700, Michael Emperador wrote: | I am running on Linux Suse7.2. I have a form(on my personal site) that | calls this cgi script. | Based on input, it will redirect to another page on the server(i.e., a | personal page). This is what I'm trying to open in a browser. I'm simply | trying to get to a another page based on user input. I would greatly | appreciate your input and any advice you could share. Oh, I see. That's a bit different. You don't want to run a browser from the script, you want to return an HTTP redirect to the client (browser) that submitted the form. I just did a little skimming of the RFC and found these : http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3 http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4 It says that you want to return status code 303 ("See Other") to the client. If you are running your CGI script such that you must provide all the headers, then you can do this with a few print statements. If you are running it where apache fills in the headers for you then I don't know how to return the redirect. -D From kp87@lycos.com Wed Jul 18 00:28:03 2001 From: kp87@lycos.com (kevin parks) Date: Wed, 18 Jul 2001 08:28:03 +0900 Subject: [Tutor] Need help with random numbers Message-ID: >>uniform(a, b) Are there other distributions? Or does anyone know how to filter uniform to get 1/f or brownian values? like: brown(size, low, hi, step) """create a list of brownian values""" size = size of the list lo = lowerlimit of fill hi = upper bound of fill step = maximum interval size pink(size, low, hi) """create a list of 1/2 values from lo to high""" size = size of the list lo = lowerlimit of fill hi = upper bound of fill is something like what i imagine. Does such a thing exist? The random module is already quite cool, but having a few more noise generators and distributions would be really fun. cheers, kevin parks seoul, korea kp87@lycos.com Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From arcege@speakeasy.net Wed Jul 18 01:15:18 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 17 Jul 2001 20:15:18 -0400 (EDT) Subject: [Tutor] print as columns [using apply()] In-Reply-To: <20010717231202.50728.qmail@web9605.mail.yahoo.com> from "Mike Serpa" at Jul 17, 2001 04:12:02 PM Message-ID: <200107180015.f6I0FIP05905@dsl092-074-184.bos1.dsl.speakeasy.net> Mike Serpa wrote > If it's really preferable to use reduce or apply here please explain it > to me because I don't get it. Most times it will be preferable because most functions won't take the arguments as you might want them. The apply, filter, map and reduce functions, along with the lambda construct (generally called "functional programming"), are all to help process things more easily. Also, as you can see, some of us veterans got confused about the max function. Guido made an effort in 2.0 to kind of standardize the single value sequence vs. multiple value arguments. So if Guido continues that effort, max/min may no longer take a single sequence to process. Also, remember that in a somewhat un-python-like fashion (*wink*), it this can be done in other ways. Standard loops: >>> maxval = 0 >>> for l in [a, b, c]: ... maxval = max( len(l), maxval ) ... >>> maxval = 0 >>> list_o_lists = (a, b, c) >>> while list_o_lists: ... l, list_o_lists = list_o_lists[0], list_o_lists[1:] ... maxval = max( len(l), maxval) ... or even the yucky list comprehensions added in Python 2.0: >>> max( [len(l) for l in (a, b, c)] ) But IMO, list comprehensions are little more than perl-like syntax sugar and reduce readability. Basically to answer your question, it is often more helpful to use the above functions (apply, filter, etc.) together to get the desired results. But, use the tools available to you as seems natural: loops, map, etc. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From tbrauch@mindless.com Wed Jul 18 04:58:26 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Tue, 17 Jul 2001 23:58:26 -0400 Subject: [Tutor] Recursive Least Common Multiple Message-ID: <3B550962.E27A1EA8@mindless.com> I would like to break up a number into its addition parts. For example, with the number 7, I need a list returned like: [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[1,1,5],[1,2,4],[1,3,3],[1,4,2],[1,5,1],...[2,1,1,1,1,1],[1,1,1,1,1,1,1]] Ideally, I can make this list smaller by sorting the individual lists and removing duplicates. That is, I only need [1,6] not [6,1] and [2,5] not [5,2] and [1,1,1,1,1,2] not [2,1,1,1,1,1]. That part shouldn't be hard. And speed is not a concern right now (it might be if I start using very large numbers, but I should be using mostly small numbers). I tried a small program that can break it into the groups of two numbers... I just can't seem to figure out how to get it to go on to 3 numbers, 4 numbers, 5 numbers, and beyond. ------------------------------------------ def adder(n): count=0 dummy=n list=[] while (count I've been working on my Python CGI (thanks graciously to Wesley J. Chun for *Core Python Programming* and to Mark Lutz for *Programming Python, 2nd ed.*) and just remembered to post it in a presentable form to Useless to see if it sparked anyone else's interest. I've got a web version of zippy.py in development, but figured I'd post the Useless Comment System first. Here's the link, which is half-way finished by my estimation, not counting the tweaking that comes after it works. http://www.lowerstandard.com/python/ucs1.html I'd like to make it a simple way to post comments to code authors privately, as well as a bulletin board of sorts, where Python groups, companies, individuals, etc. can be heard. Which quickly leads to the necessity of administration, allowing certain Super Useless Users the ability to log in to a web interface and log in to make sure the site remains fit for family consumption. Anyway, if anyone else has any web-based material they'd like to demo for discussion on the site, just let me know. I'd like to get a healthy collection of little examples up for people to grok. Useless Peace, Rob "Perl is worse than Python because people wanted it worse." Larry Wall (Creator of Perl), 14 Oct 1998 Useless Python: http://www.lowerstandard.com/python/ From rob@jam.rr.com Wed Jul 18 05:11:30 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 17 Jul 2001 23:11:30 -0500 Subject: [Tutor] one more thing..... Message-ID: I pulled the log files and found that Useless Python on the main server has gotten about 40,000 legitimate hits so far, excluding those hits confirmed to be from my home or workplace. This isn't counting the mirror site. I'm currently working on a script to parse the log file in more detail, and just remembered to find out if there's any way to get the log file for the mirror site. It looks like people around the world are benefiting from your *Useless* code already. Kudos, Rob "Perl is worse than Python because people wanted it worse." Larry Wall (Creator of Perl), 14 Oct 1998 Useless Python: http://www.lowerstandard.com/python/ From dyoo@hkn.eecs.berkeley.edu Wed Jul 18 05:23:37 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jul 2001 21:23:37 -0700 (PDT) Subject: [Tutor] webbrowser In-Reply-To: <20010717192018.A16480@harmony.cs.rit.edu> Message-ID: On Tue, 17 Jul 2001, D-Man wrote: > On Tue, Jul 17, 2001 at 04:08:14PM -0700, Michael Emperador wrote: > | I am running on Linux Suse7.2. I have a form(on my personal site) that > | calls this cgi script. > | Based on input, it will redirect to another page on the server(i.e., a > | personal page). This is what I'm trying to open in a browser. I'm simply > | trying to get to a another page based on user input. I would greatly > | appreciate your input and any advice you could share. > > Oh, I see. That's a bit different. You don't want to run a browser > from the script, you want to return an HTTP redirect to the client > (browser) that submitted the form. There's a special META tag that can perform a redirect. If you send as your CGI's content the following tag: most web browsers will respect this and automatically redirect to whatever page you want. For another example, take a look here: http://www.cs.sunysb.edu/faq/howto/sample_redirect.html Good luck! From shalehperry@home.com Wed Jul 18 05:42:50 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Tue, 17 Jul 2001 21:42:50 -0700 (PDT) Subject: [Tutor] Recursive Least Common Multiple In-Reply-To: <3B550962.E27A1EA8@mindless.com> Message-ID: def adder(n): val = [] count = 1 dummy = n while((count < dummy) and ((2 * count) <= n)): dummy = dummy - 1 val.append([count, dummy]) count = count + 1 return val > I really feel like my code could be a lot shorter if I knew some trick, > and some other trick would actually do what I need. Any help would be > greatly appreciated. Also, I created the dummy variable so as not to > destroy n in case I need to use it later. > This solves the 2 operands case. The (2 * count) <= n helps when n is large, although this still results in a minimal list without it. $ /tmp/adder.py [[1, 29], [2, 28], [3, 27], [4, 26], [5, 25], [6, 24], [7, 23], [8, 22], [9, 21], [10, 20], [11, 19], [12, 18], [13, 17], [14, 16], [15, 15]] I swear there is an algorithm that solves this problem. The loop construct just feels like the wrong approach. So, then you want [1,1,1,1,...1]. Well, the value of n represents the largest list you will have (i.e. if n == 30, the last list will have len(list) == 30). Call adder for the right hand value until you end up with that list. From shalehperry@home.com Wed Jul 18 05:45:40 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Tue, 17 Jul 2001 21:45:40 -0700 (PDT) Subject: [Tutor] Recursive Least Common Multiple In-Reply-To: Message-ID: On 18-Jul-2001 Sean 'Shaleh' Perry wrote: > def adder(n): > val = [] > count = 1 > dummy = n > while((count < dummy) and ((2 * count) <= n)): > dummy = dummy - 1 > val.append([count, dummy]) > count = count + 1 > return val > of course the (count < dummy) is now superfluous (-: From dyoo@hkn.eecs.berkeley.edu Wed Jul 18 05:48:07 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 Jul 2001 21:48:07 -0700 (PDT) Subject: [Tutor] Recursive Least Common Multiple In-Reply-To: <3B550962.E27A1EA8@mindless.com> Message-ID: On Tue, 17 Jul 2001, Timothy M. Brauch wrote: > I would like to break up a number into its addition parts. For > example, with the number 7, I need a list returned like: > [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[1,1,5], > [1,2,4],[1,3,3],[1,4,2],[1,5,1],... > [2,1,1,1,1,1],[1,1,1,1,1,1,1]] > I really feel like my code could be a lot shorter if I knew some > trick, and some other trick would actually do what I need. Any help > would be greatly appreciated. Also, I created the dummy variable so > as not to destroy n in case I need to use it later. Your question sounds really similar to a somewhat involved problem in computer science called the "change-making" problem. The change-making problem asks us to give all possible ways of turning some about of money into a pocketful of change, if we're restricted to use quarters, nickles, dimes, and pennies. Your problem is a variant because it allows any denomination, even imaginary ones like ookles, limes, warters, and dennies. You also hit upon the key phrase for the solution: "recursive": there's a great recursive solution that's relatively short, beautiful, and utterly inefficient. *grin* (This is also a great way to introduce another CS idea called "dynamic programming", but let's talk about it later.) A simple example might help introduce the recursive idea. Let's say that we're trying to make all ways of making 15 cents in change, and we have an unlimited number of nickles, dimes, and pennies. One thing we can do is to set aside a dime, and try to find all ways of making 5 cents in change. Or we could set aside a nickle, and make 10 cents in change. Or we could set aside a penny, and try to make 14 cents of change. Since we have three smaller, but similar problems, we apply the same sort of reduction. Think about it for a while, and try it out. It's a fun program to write. Good luck! From csmith@blakeschool.org Wed Jul 18 08:15:04 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Wed, 18 Jul 2001 02:15:04 -0500 Subject: [Tutor] Re: Tutor digest, Vol 1 #962 - 15 msgs In-Reply-To: References: Message-ID: >From: Mike Serpa >> a=[1,2,3,4] >> b=[5,6,7] >> c=[8,9,10,11,12] >> >> n=len( reduce( lambda a,b:max(a,b), [a,b,c] )) >> >> n is 5 > >Couldn't we shorten this to: >n=len(max(lists)) Yep! Nice job. Strunk and White would be proud. That works, too: >>> a=range(3) >>> b=range(4) >>> c=range(2) >>> len( reduce( lambda a,b:max(a,b), [a,b,c] )) 4 >>> len(max(a,b,c)) 4 >>> reduce(max, map(len, (a, b, c))) 4 >>> apply(max, map(len, (a, b, c))) 4 >>> max(map(len, (a, b, c))) 4 Danny's pathological case could be handled by your approach by simply adding something else for the max to chew: len(max([1],[])) Which is a bit simpler than max(map(len,([1],))) (BTW, no particular reason for the reduce or apply, Mike...that's just how the problem posed itself to me: I have lists that I needed to repeatedly apply max to. I forgot that max already repeats itself.) So in a function you could have: def pcolumns(...,*lists): n=len(max(lists,[])) > >It seems that everything I figure out how to do is already in a module >somewhere. Question for expert Python coders (or any lang.) Do you >ever get to the stage where you don't have to constantly look things >up in the lang docs? It's like learning new words. If you never read books or talk to people with bigger vocabularies than yours you always have to use lots of little words to get your ideas across. As I read the documentation and Python FAQ (non-operative but lots of useful stuff). I get more ideas about solving problems in alternate ways and with less re-inventing. Those that came up with the modules had to have covered some of the same ground that you are covering. > > >> >> 2) Instead of padding, you might consider using the try/except >> construction to not print the list elements that don't >> exist. > >So I don't have to lace them then. Right! > >So we get: > > >Great! >We've gone from 20 lines to 15 to 9. More importantly it's now much >simpler. And you've learned a few tricks on the way. > > >The only thing I can think to add is a max number of columns so it >doesn't go off the screen. Or if columns is > 4 then split into two >tables. Or adjust columns to largest element, etc. Don't need to yet >for what I'm using if for, but will be easier now. Thanks. Exactly what I was thinking. Here's something else to think about. BBEdit has a 'tabulate' tool which will figure out teh optimal column spacings for you based on the widths of everything in the columns. You could add the column headers to your lists to print and then run through each list and find the longest element. Then print the titles on one line (if possible) and then the underscores ('_'*maxincolumni) and finally the data. /c From csmith@blakeschool.org Wed Jul 18 08:15:04 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Wed, 18 Jul 2001 02:15:04 -0500 Subject: [Tutor] Re: print as columns In-Reply-To: References: Message-ID: Sorry about the double post...forgot the Subject. I also added something about the pathology of Danny's approach. >From: Mike Serpa >> a=[1,2,3,4] >> b=[5,6,7] >> c=[8,9,10,11,12] >> >> n=len( reduce( lambda a,b:max(a,b), [a,b,c] )) >> >> n is 5 > >Couldn't we shorten this to: >n=len(max(lists)) Yep! Nice job. Strunk and White would be proud. That works, too: >>> a=range(3) >>> b=range(4) >>> c=range(2) >>> len( reduce( lambda a,b:max(a,b), [a,b,c] )) 4 >>> len(max(a,b,c)) 4 >>> reduce(max, map(len, (a, b, c))) 4 >>> apply(max, map(len, (a, b, c))) 4 >>> max(map(len, (a, b, c))) 4 Danny's pathological case could be handled by your approach by simply adding something else for the max to chew: len(max([1],[])) The reason it's pathological for len(max([1])) is that max([1]) returns a non-length item, 1, and this bothers len. But max([1],[]) returns [1] which does have length. Which is a bit simpler than max(map(len,([1],))) (BTW, no particular reason for the reduce or apply, Mike...that's just how the problem posed itself to me: I have lists that I needed to repeatedly apply max to. I forgot that max already repeats itself.) So in a function you could have: def pcolumns(...,*lists): n=len(max(lists,[])) > >It seems that everything I figure out how to do is already in a module >somewhere. Question for expert Python coders (or any lang.) Do you >ever get to the stage where you don't have to constantly look things >up in the lang docs? It's like learning new words. If you never read books or talk to people with bigger vocabularies than yours you always have to use lots of little words to get your ideas across. As I read the documentation and Python FAQ (non-operative but lots of useful stuff). I get more ideas about solving problems in alternate ways and with less re-inventing. Those that came up with the modules had to have covered some of the same ground that you are covering. > > >> >> 2) Instead of padding, you might consider using the try/except >> construction to not print the list elements that don't >> exist. > >So I don't have to lace them then. Right! > >So we get: > > >Great! >We've gone from 20 lines to 15 to 9. More importantly it's now much >simpler. And you've learned a few tricks on the way. > > >The only thing I can think to add is a max number of columns so it >doesn't go off the screen. Or if columns is > 4 then split into two >tables. Or adjust columns to largest element, etc. Don't need to yet >for what I'm using if for, but will be easier now. Thanks. Exactly what I was thinking. Here's something else to think about. BBEdit has a 'tabulate' tool which will figure out teh optimal column spacings for you based on the widths of everything in the columns. You could add the column headers to your lists to print and then run through each list and find the longest element. Then print the titles on one line (if possible) and then the underscores ('_'*maxincolumni) and finally the data. /c From iamgod@st.jyu.fi Wed Jul 18 12:41:58 2001 From: iamgod@st.jyu.fi (Risto Peranen) Date: Wed, 18 Jul 2001 14:41:58 +0300 (EEST) Subject: [Tutor] rexec-environ In-Reply-To: Message-ID: Hey all. I'm still making a game which I need your help once again. We are planning to do python applets for the game. That's way everyone can extend our engine very easily. I have read rexec-howto and it's seems quite nice for our purposes but how can one make more restricted environment. Since game will run also win32-platforms it's important that applets may not open files. How do you do that (with rexec(?))? Risto Peranen 040 756 94 12 iamgod@st.jyu.fi Ihminen on syntynyt vaivaan, kuten kipinat ovat syntyneet nousemaan taivaalle From kp87@lycos.com Wed Jul 18 13:34:29 2001 From: kp87@lycos.com (kevin parks) Date: Wed, 18 Jul 2001 21:34:29 +0900 Subject: [Tutor] Re: Bunch lists into sublists via alternation Message-ID: I am trying to figure out how to take a sequence and split it up into sub-lists by alternation. For example if i had a sequence like: x = [1,2,3,4,5,6,7,8,9] and i called a function that was: seqSplit(seq, sub-lists) seqSplit(x,2) would yield: ([1,3,5,7,9], [2,4,6,8,None]) # None pads lists that are short elements and seqSplit(x,3) --> ([1,4,7], [2,5,8], [3,6,9]) and seqSplit(x,4) --> ([1,6] [2,7], [3,8], [4,9], [5,None]) I've got something that bunches up consecutive elements into sub-lists: def bunch(mylist, times): """package up list elements in sub-lists n at a time. x=[1,2,3,4,5,6,7,8,9] bunch(x,1) --> [[1], [2], [3], [4], [5], [6], [7], [8], [9]] bunch(x, 2) --> [[1,2], [3,4], [5,6], [7,8], [9, None] bunch(x, 3) --> [[1,2,3], [4,5,6], [7,8,9]] bunch(x, 4) --> [1,2,3,4], [5,6,7,8] [9, None, None, None]]""" out = [mylist[i:i+times] for i in range(0, len(mylist), times)] if out: out[-1].extend([None] * (times - len(out[-1]))) return out # -- --------------------------------------- But i can't figure out how to get the: a = (1,9,1,9,1,9) b = (1,9,7,1,9,7,1,9,7) seqSplit(a,2) --> ([1, 1, 1], [9, 9, 9])""" seqSplit(b,3) --> ([1, 1, 1], [9, 9, 9], [7, 7, 7])""" type arrangement, particularly since i want it to work for any unpredetermined number of sub-lists. I've got a kludge that works only for the case of seqSplit(x,2), but i can't get anything to work for seqSplit(x,n) where n is anything else. cheers, kevin parks seoul, korea Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From arcege@speakeasy.net Wed Jul 18 13:54:38 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 18 Jul 2001 08:54:38 -0400 (EDT) Subject: [Tutor] rexec-environ In-Reply-To: from "Risto Peranen" at Jul 18, 2001 02:41:58 PM Message-ID: <200107181254.f6ICscI06737@dsl092-074-184.bos1.dsl.speakeasy.net> Risto Peranen wrote > Hey all. I'm still making a game which I need your help once again. > We are planning to do python applets for the game. That's way everyone > can extend our engine very easily. I have read rexec-howto and it's seems > quite nice for our purposes but how can one make more restricted > environment. Since game will run also win32-platforms it's important that > applets may not open files. How do you do that (with rexec(?))? By default, a RExec instance allows you to open files for reading only. But that is handled by a r_open method that you can override in a subclass. class NoOpenRExec(RExec): def r_open(self, file, mode='r', buf=-1): raise IOError, "can't open files in restricted mode" This method is set as the built-in 'open' function in the rexec environment. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From arcege@speakeasy.net Wed Jul 18 14:18:42 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 18 Jul 2001 09:18:42 -0400 (EDT) Subject: [Tutor] Re: print as columns In-Reply-To: from "Christopher Smith" at Jul 18, 2001 02:15:04 AM Message-ID: <200107181318.f6IDIg606787@dsl092-074-184.bos1.dsl.speakeasy.net> Christopher Smith wrote > So in a function you could have: > > def pcolumns(...,*lists): > n=len(max(lists,[])) > No, read the previous postings. The max function does not compare the length of the sequences unless all data is the same (to the point were the lengths are different). The max and min functions use the cmp function. >>> max([7, 9], [2, 4, 5]) [7, 9] >>> cmp([7, 9], [2, 4, 5]) 1 >>> class A: ... def __init__(self, i): self.i = i ... def __str__(self): return str(self.i) ... def __cmp__(self, other): ... print '__cmp__(%s, %s)' % (self, other) ... return cmp(self.i, other) ... def __rcmp__(self, other): ... print '__cmp__(%s, %s)' % (other, self) ... return cmp(other, self.i) ... >>> a = A(3) >>> b = A(10) >>> print max(a, b) __cmp__(10, 3) __cmp__(3, 10) 10 >>> Compare the lengths, not the content. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From chetumal23@excite.com Wed Jul 18 16:06:06 2001 From: chetumal23@excite.com (john smith smith) Date: Wed, 18 Jul 2001 08:06:06 -0700 (PDT) Subject: [Tutor] newbie question Message-ID: <10140986.995468766462.JavaMail.imail@goochy.excite.com> i was trying to upgrade to the latest edition of activepython. the problem is i had a earlier edition on. i uninstalled it but the new version still won't install. i read up and it says i have to have a clean PATH but i don't know how to clear it. any help would be greatly appreciated. i'm running windows 2000 _______________________________________________________ Send a cool gift with your E-Card http://www.bluemountain.com/giftcenter/ From csmith@blakeschool.org Wed Jul 18 16:39:42 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Wed, 18 Jul 2001 10:39:42 -0500 Subject: [Tutor] Re: print as columns In-Reply-To: <200107181318.f6IDIg606787@dsl092-074-184.bos1.dsl.speakeasy.net> References: <200107181318.f6IDIg606787@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: arcege@speakeasy.net writes: > Compare the lengths, not the content. Thanks for persisting in pointing out the error. I had a bad test case. I now see that len(max.. is wrong: >>> a=[1]*3 >>> b=[7] >>> len(max(a,b)) 1 Whereas what you said is right: >>> max(map(len,(a,b))) 3 Which works on the pathological case as long as you add a dummy list--or just a comma in the tuple of lists (b,) instead of (b): >>> max(map(len,(b,))) 1 If you forget the comma, you may get this: >>> max(map(len,(b))) Traceback (most recent call last): File "", line 1, in ? TypeError: len() of unsized object Finally, max applies itself iteratively so reduce isn't necessary but it works, too. >>> reduce(max,map(len,(b,))) 1 I wrote: > So in a function you could have: > > def pcolumns(...,*lists): > n=len(max(lists,[])) > Uh-humm, I should have said: n=max(map(len,(lists,))) Thanks again! /c From israel@lith.com Wed Jul 18 17:49:15 2001 From: israel@lith.com (Israel Evans) Date: Wed, 18 Jul 2001 09:49:15 -0700 Subject: [Tutor] newbie question Message-ID: On windows 2000 just go to "control panel" then "system" click on "advanced" then on "environment variables" and look for either "PYTHONPATH" in the system variables field and clear that or look in "PATH" and see if there is any mention of a python directory. I don't know much about the whole python path active python routine, but this is how I get to the Path stuff in win2000. The whole PythonPath thing is killing me anyway. It seems if I have PYTHONPATH defined Idle won't run. SO what I have to do is define my python dirs in PATH, and that only lets me import my modules in seperate dirs sometimes. Weird. Anyway, good luck! ~Israel~ -----Original Message----- From: john smith smith [mailto:chetumal23@excite.com] Sent: Wednesday, July 18, 2001 8:06 AM To: tutor@python.org Subject: [Tutor] newbie question i was trying to upgrade to the latest edition of activepython. the problem is i had a earlier edition on. i uninstalled it but the new version still won't install. i read up and it says i have to have a clean PATH but i don't know how to clear it. any help would be greatly appreciated. i'm running windows 2000 _______________________________________________________ Send a cool gift with your E-Card http://www.bluemountain.com/giftcenter/ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From hnowak@cuci.nl Wed Jul 18 18:32:27 2001 From: hnowak@cuci.nl (Hans Nowak) Date: Wed, 18 Jul 2001 19:32:27 +0200 Subject: [Tutor] Recursive Least Common Multiple In-Reply-To: <3B550962.E27A1EA8@mindless.com> Message-ID: <200107181734.f6IHYY917098@hera.cuci.nl> On 17 Jul 01, at 23:58, Timothy M. Brauch wrote: > I would like to break up a number into its addition parts. For example, > with the number 7, I need a list returned like: > [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[1,1,5],[1,2,4],[1,3,3],[1,4,2],[1,5, > 1],...[2,1,1,1,1,1],[1,1,1,1,1,1,1]] > > Ideally, I can make this list smaller by sorting the individual lists and > removing duplicates. That is, I only need [1,6] not [6,1] and [2,5] not > [5,2] and [1,1,1,1,1,2] not [2,1,1,1,1,1]. That part shouldn't be hard. > And speed is not a concern right now (it might be if I start using very > large numbers, but I should be using mostly small numbers). I tried a > small program that can break it into the groups of two numbers... I just > can't seem to figure out how to get it to go on to 3 numbers, 4 numbers, 5 > numbers, and beyond. Try this code: def sums(n): if n == 1: return [[1]] lst = [] for i in range(1, n): for r in sums(n-i) + [[n-i]]: t = [i] + r t.sort() if not t in lst: lst.append(t) return lst # test it for i in range(2, 9): print i, "=>", sums(i) I didn't test it very thoroughly, but it seems to work. :) HTH, --Hans Nowak (zephyrfalcon@hvision.nl) You call me a masterless man. You are wrong. I am my own master. May a stockbroker marry your monogram! From MLange@atmedicausa.com Wed Jul 18 18:35:50 2001 From: MLange@atmedicausa.com (Mike Lange) Date: Wed, 18 Jul 2001 11:35:50 -0600 Subject: [Tutor] re: Python for the Microsoft Scripting Engine Message-ID: This is a multipart message in MIME format. --=_alternative 00613D1387256A8D_= Content-Type: text/plain; charset="us-ascii" Is there a way to get Python to work with the Microsoft Scripting Engine. I've seen this done with Perl, and I've read that Python works, but I haven't been able to find a way. Any help will be greatly appreciated! Thanks! Mike Lange --=_alternative 00613D1387256A8D_= Content-Type: text/html; charset="us-ascii"
Is there a way to get Python to work with the Microsoft Scripting Engine.  I've seen this done with Perl, and I've read that Python works, but I haven't been able to find a way.  Any help will be greatly appreciated!  Thanks!

Mike Lange
--=_alternative 00613D1387256A8D_=-- From tbrauch@mindless.com Wed Jul 18 21:42:30 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Wed, 18 Jul 2001 16:42:30 -0400 Subject: [Tutor] Real LCM Message-ID: <3B55F4B6.9CD08B8B@mindless.com> It appears the search on Python.org is not working, at least I haven't been able to do a search on the site for a few days. I was wondering if there is a function somewhere in Python to find the Least Common Multiple of two numbers. Or, should I try to hack together something. - Tim P.S. This is the question I was going to ask with my last email, but then I remembered my other problem and forgot to change the subject line. From csmith@blakeschool.org Wed Jul 18 22:50:16 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Wed, 18 Jul 2001 16:50:16 -0500 Subject: [Tutor] Re: Bunch lists into sublists via alternation Message-ID: > Re: Bunch lists into sublists via alternation > But i can't figure out how to get the: > > a = (1,9,1,9,1,9) > b = (1,9,7,1,9,7,1,9,7) > seqSplit(a,2) --> ([1, 1, 1], [9, 9, 9])""" > seqSplit(b,3) --> ([1, 1, 1], [9, 9, 9], [7, 7, 7])""" > > type arrangement, particularly since i want it to work for any unpredetermined > number of sub-lists. I've got a kludge that works only for the case of seqSplit(x,2), > but i can't get anything to work for seqSplit(x,n) where n is anything else. By writing down the sequence you want to get you might see the pattern: seqSplit(a,2) you want 0,2,4 then 1,3,5 seqSplit(b,3) you want 0,3,6 then 1,4,7 then 2,5,8 What you don't see with these two examples is that the number of rows is always n and the number of columns will be however many n-steps could be taken through the list. If the seqeunce is nn units long then these indices can be given by: m = nn/n + nn % n # ceil(nn/n) for i in range(n): for j in range(i,i+m+n,n): # +m b/c you need that many past i # and +n to give you the last one print j, print When you try access elements from the list, however, if the list isn't m*n units long you will generate an IndexError which, as for the Column Printing program that we have been discussing can be handled with the try: construction: try: print l[j], except IndexError: print None /c From mall.com" Advertise Your Website for FREE. http://www.mall.com/freetraffic We would like to take this opportunity to introduce you to a unique online marketing opportunity at Mall.com and the services which we provide hundreds of online merchants like you. The Merchant Marketing Center at Mall.com will provide you with information and pricing for Mall.com’s entire suite of online marketing services, including a FREE listing on the Mall.com website. By registering your business for a FREE listing, you will be exposed to millions of qualified shoppers throughout the world. Follow this URL for your FREE listing.... http://www.mall.com/freesignup Or, if you are interested in upgrading to a "Packaged" service, including logo placement in our exclusive Mall Maps, e-mail campaigns to hundreds of thousands of pre-qualified shoppers, product placement, search engine optimization, plus much more, then click below to learn more about Mall.com’s Marketing Packages. At Mall.com, our goal is to deliver qualified shoppers to our online partners at the most cost effective price. Please feel free to contact us at anytime with your questions or comments @ 1-888-989-6255. Or click below to fill out our FREE Online Marketing Inquiry form. One of our representatives will contact you within the next 2 business days. Mall.com Home Page http://www.mall.com/freetraffic Merchant Marketing Center http://www.mall.com/getinfo FREE Online Registration http://www.mall.com/freesignup /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ THIS MESSAGE IS BEING SENT IN COMPLIANCE OF THE EMAIL BILL: SECTION 301. PER SECTION, PARAGRAPH (a) (2) (c) of S. 1618. To discontinue receipt of further notice at not cost and to be removed from our database, please reply with the word "Remove" in subject. Any attempts to disrupt the removal email address etc., will not allow us to be able to retrieve and process the remove requests. /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ From dyoo@hkn.eecs.berkeley.edu Thu Jul 19 00:12:40 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 18 Jul 2001 16:12:40 -0700 (PDT) Subject: [Tutor] Real LCM In-Reply-To: <3B55F4B6.9CD08B8B@mindless.com> Message-ID: On Wed, 18 Jul 2001, Timothy M. Brauch wrote: > It appears the search on Python.org is not working, at least I haven't > been able to do a search on the site for a few days. > > I was wondering if there is a function somewhere in Python to find the > Least Common Multiple of two numbers. Or, should I try to hack > together something. Hmmm... I can't think of one that's built into the Python library. Neither is there a gcd() (greatest common divisor) function that's built in. However, there's great algorithm by the mathematician Euclid called "Euclid's Algorithm" that calculates gcd's very quickly. Really quickly: ### def gcd(a, b): if b == 0: return a return gcd(b, a % b) ### Euclid's algorithm is really useful, especially for rationalizing fractions. Anyway, I did a quick lookup on google for the topic of "gcd's and lcm's", and got back this page: http://www.geocities.com/zabrodskyvlada/aat/a_eucl.html The gcd() and lcm() are related: if we get the GCD of two numbers, getting their lcm() is really easy: "lcm(a, b) = a * b / gcd(a, b)" The Python code for this reads very closely to the math. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu Jul 19 00:28:53 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 18 Jul 2001 16:28:53 -0700 (PDT) Subject: [Tutor] Sporadical bug? In-Reply-To: <200107170918_MC3-D97A-DA5@compuserve.com> Message-ID: On Tue, 17 Jul 2001, Sharriff Aina wrote: > Hi tutors! > > here is a snippet of my ftp upload code: > > > if ftpurls: > ....global finalhtml > ....for j, k in zip(allimagetags, modified_image_tags): > ........finalhtml = string.replace(usercontent, j, k) > > ### > where "allimagetags" is a list of image tags like > c:\windows\temp\myimage.jpg > modified_image_tags is a list of modified "allimagetags" example > ..\users\myimage.jpg > usercontent is a string block of HTML, this block also contains all image > tags. > > My problem is, upon storing "finalhtml" in a database, I noticed that the > image tags were not being properly replaced. If allimagetags contained 3 > image tags, all 3 are stored in the database but only the 3 is really > replaced in the string block "usercontent" . > Am I using the "zip" commabd wrongly? Hi Sharriff, Just catching up on this message; has anyone answered your question yet on this one? I think I see the bug in the program: > if ftpurls: > ....global finalhtml > ....for j, k in zip(allimagetags, modified_image_tags): > ........finalhtml = string.replace(usercontent, j, k) The problem is that you'll need to do the string replacement repeatedly on the same string. At the moment, the code always does the replacement on 'usercontent'. However, after it does this, it throws that result out and does another string replacment against another tag. As a result, finalhtml is always incompletely changed. Here's one way to correct the bug: ### if ftpurls: global finalhtml finalhtml = usercontent for j, k in zip(allimagetags, modified_image_tags): finalhtml = string.replace(finalhtml, j, k) ### Good luck! From tbrauch@mindless.com Thu Jul 19 02:03:43 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Wed, 18 Jul 2001 21:03:43 -0400 Subject: [Tutor] Real LCM References: Message-ID: <3B5631EF.443AD4CE@mindless.com> Forgetting to send to the whole list the first time... Danny Yoo presented us with, while talking about lcm(a,b): > Hmmm... I can't think of one that's built into the Python library. > Neither is there a gcd() (greatest common divisor) function that's built > in. However, there's great algorithm by the mathematician Euclid called > "Euclid's Algorithm" that calculates gcd's very quickly. Really quickly: > > ### > def gcd(a, b): > if b == 0: return a > return gcd(b, a % b) > ### > > Euclid's algorithm is really useful, especially for rationalizing > fractions. Anyway, I did a quick lookup on google for the topic of "gcd's > and lcm's", and got back this page: Yes, I was already using this algorithm in my code for this project. One of the goals of this set of functions a sort of extension to the current math module, and one that will work with a list with an arbitrary length of numbers for functions that aren't in the math module. I am still struggling a little with the gcd for a complete list of numbers, hopefully I will hack out a solution soon enough. The mean, median and mode was pretty simple. Oh, and all these 'fun' projects I keep coming up with are mostly just things I am coming up with to waste time. > > http://www.geocities.com/zabrodskyvlada/aat/a_eucl.html > > The gcd() and lcm() are related: if we get the GCD of two numbers, getting > their lcm() is really easy: > > "lcm(a, b) = a * b / gcd(a, b)" > > The Python code for this reads very closely to the math. > > Hope this helps! This relationship of gcd and lcm is new to me. It has helped with my lists of two numbers. As soon as I finish with the arbitrary length gcd, I will try to implement the arbitrary length lcm. Then, move on to possibly new functions. - Tim From tbrauch@mindless.com Thu Jul 19 02:12:01 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Wed, 18 Jul 2001 21:12:01 -0400 Subject: [Tutor] Real LCM References: <3B5631EF.443AD4CE@mindless.com> Message-ID: <3B5633E1.7D6EDF46@mindless.com> I previously wrote: > Yes, I was already using [the Euclidean] algorithm in my code for this project. > One of the goals of this set of functions a sort of extension to the > current math module, and one that will work with a list with an > arbitrary length of numbers for functions that aren't in the math > module. > > I am still struggling a little with the gcd for a complete list of > numbers, hopefully I will hack out a solution soon enough. The mean, > median and mode was pretty simple. Danny Yoo provided: > > The gcd() and lcm() are related: if we get the GCD of two numbers, getting > > their lcm() is really easy: > > > > "lcm(a, b) = a * b / gcd(a, b)" > > > > The Python code for this reads very closely to the math. > > > > Hope this helps! > > This relationship of gcd and lcm is new to me. It has helped with my > lists of two numbers. As soon as I finish with the arbitrary length > gcd, I will try to implement the arbitrary length lcm. Then, move on to > possibly new functions. I finally have the gcd and lcm for any length list of numbers. The code is as appears below... ---------------------------------------------------------- def __gcd__(a,b): if b==0: return a return __gcd__(b,a%b) def gcd(list): list.sort() g=list[0] for i in range(len(list)): g=__gcd__(g,list[i]) return g def __lcm__(a,b): l=a*b/__gcd__(a,b) return l def lcm(list): list.sort() l=list[0] for i in range(len(list)): l=__lcm__(l,list[i]) return l ---------------------------------------------------------- Any comments or criticism is appreciated. My code works on lists and can compute the following: mean (as in average) mode (if it exists) median lcm gcd Any other suggestions? - Tim From dyoo@hkn.eecs.berkeley.edu Thu Jul 19 05:38:19 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 18 Jul 2001 21:38:19 -0700 (PDT) Subject: [Tutor] Real LCM In-Reply-To: <3B5633E1.7D6EDF46@mindless.com> Message-ID: On Wed, 18 Jul 2001, Timothy M. Brauch wrote: > I finally have the gcd and lcm for any length list of numbers. The code > is as appears below... > > ---------------------------------------------------------- > def __gcd__(a,b): > if b==0: > return a > return __gcd__(b,a%b) > > def gcd(list): > list.sort() > g=list[0] > for i in range(len(list)): > g=__gcd__(g,list[i]) > return g Small warning: try to avoid using "list" as the name of a variable: it conflicts with a builtin function with the same name: ### >>> list >>> list("this is a test") ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't'] ### There's another neat way to get the gcd of a list of numbers: since you have something that can gcd() two numbers together, you can combine this with the reduce() function: ### >>> def __gcd__(a, b): ... if b == 0: return a ... return __gcd__(b, a%b) ... >>> def gcd(L): return reduce(__gcd__, L) ... >>> gcd([10, 20, 40, 80]) 10 >>> gcd([75, 35]) 5 ### Magic. *grin* reduce() isn't as usless as it might first appear, but it does take some practice to see what it's good for. Hope this helps! From Charlie Clark Thu Jul 19 09:54:31 2001 From: Charlie Clark (Charlie Clark) Date: Thu, 19 Jul 2001 10:54:31 +0200 Subject: [Tutor] Help with codecs Message-ID: <0003896e8f24e454_mailit@mail.isis.de> I often use the same text for a web page and e-mail newsletter and would like to write 2 codecs to generate HTML-equivalents and 7-bit-safe plain text for e-mails. A codec for HTML was initially suggested but then dropped and as far as I know no one wanted to do 7-bit (д -> ae, etc.). I have looked at the documentation of codecs but I'm afraid I don't know really where to start. I had initially written functions for the work but have since written a module which contains two incomplete dictionaries with the appropriate characters. Thanx for any help Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From kromag@nsacom.net Thu Jul 19 18:17:24 2001 From: kromag@nsacom.net (kromag@nsacom.net) Date: Thu, 19 Jul 2001 10:17:24 -0700 (PDT) Subject: [Tutor] variables within function - wha? Message-ID: <200107191717.f6JHHOL19785@pop.nsacom.net> I am trying to get a function to perfrom simple calculations based on 3 values. ----------------------------------- def filter(cc,rpm,type): cid=cc/16.387 ocg=(cid*rpm)/20839 foam=ocg*1.3767 paper=ocg*1.2181 if type==paper: return paper, elif type==foam: return foam, else: return ocg ----------------------------------- I can't figure out why: >>> filter(1800,7000,foam) Traceback (innermost last): File "", line 1, in ? filter(1800,7000,foam) NameError: There is no variable named 'foam' >>> occours. Have I been inhaling too much brake cleaner? d From SBrunning@trisystems.co.uk Thu Jul 19 16:12:39 2001 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Thu, 19 Jul 2001 16:12:39 +0100 Subject: [Tutor] variables within function - wha? Message-ID: <31575A892FF6D1118F5800600846864D78BEC1@intrepid> > From: kromag@nsacom.net [SMTP:kromag@nsacom.net] > def filter(cc,rpm,type): > cid=cc/16.387 > ocg=(cid*rpm)/20839 > foam=ocg*1.3767 > paper=ocg*1.2181 > if type==paper: > return paper, > elif type==foam: > return foam, > else: > return ocg You might want to replace lines 6 thru 9 with: if type=='paper': return paper elif type=='foam': return foam BTW, are you using tabs to indent your code? Don't! Use spaces instead. > I can't figure out why: > > >>> filter(1800,7000,foam) > Traceback (innermost last): > File "", line 1, in ? > filter(1800,7000,foam) > NameError: There is no variable named 'foam' > >>> > > occours. Have I been inhaling too much brake cleaner? Try: filter(1800,7000,'foam') and it should work. BTW, filter is a bad name for this function, because there is already a built-in with that name. Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From ggates@appliedtheory.com Thu Jul 19 16:17:02 2001 From: ggates@appliedtheory.com (George Gates) Date: Thu, 19 Jul 2001 11:17:02 -0400 Subject: [Tutor] variables within function - wha? In-Reply-To: <200107191717.f6JHHOL19785@pop.nsacom.net> References: <200107191717.f6JHHOL19785@pop.nsacom.net> Message-ID: <200107191117020670.00E418AB@smtp-server.twcny.rr.com> The problem is "type" is a built in function. Change the name of that= variable. Also, you are not passing or testing the type as a string. ie: def filter(cc,rpm,t): cid=3Dcc/16.387 ocg=3D(cid*rpm)/20839 foam=3Docg*1.3767 paper=3Docg*1.2181 if t=3D=3D'paper': return paper, elif t=3D=3D'foam': return foam, else: return ocg >>> filter(1800,7000,'foam') (50.7964695628,) >>> filter(1800,7000,'paper') (44.9445627765,) >>> *********** REPLY SEPARATOR *********** On 7/19/01 at 10:17 AM kromag@nsacom.net wrote: >I am trying to get a function to perfrom simple calculations based on 3 >values. > >----------------------------------- > >def filter(cc,rpm,type): > cid=3Dcc/16.387 > ocg=3D(cid*rpm)/20839 > foam=3Docg*1.3767 > paper=3Docg*1.2181 > if type=3D=3Dpaper: > return paper, > elif type=3D=3Dfoam: > return foam, > else: > return ocg > >----------------------------------- > >I can't figure out why: > >>>> filter(1800,7000,'foam') >Traceback (innermost last): > File "", line 1, in ? > filter(1800,7000,foam) >NameError: There is no variable named 'foam' >>>> > >occours. Have I been inhaling too much brake cleaner? > >d > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor George H. Gates System Administrator - OSOS Implementation Phone: (315) 453-2912 x5671 Email: ggates@appliedtheory.com Web: http://ggates.appliedtheory.com From alan.gauld@bt.com Thu Jul 19 16:56:25 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 19 Jul 2001 16:56:25 +0100 Subject: [Tutor] re: Python for the Microsoft Scripting Engine Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8BB@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C1106B.5D685BF0 Content-type: text/plain; charset="ISO-8859-1" Is there a way to get Python to work with the Microsoft Scripting Engine. I've seen this done with Perl, and I've read that Python works, but I haven't been able to find a way. Any help will be greatly appreciated! Yes, you need to install WSH on Windows then run a script from the winall(or activestate python distribution) that registers Python as a scripting language. (Its pyscript.py found in: $PYTHON/win32comext/axscript/client - obvious eh?! :-) Python scripts should then be created with an extension of .pys However I've failed to get this to work! On asking Mark Hammond on c.l.p he suggested that it was easier not to bother and just use native OLE to instantiate the WSH objects directly. (Try searching the newsnet archives on Google...) He gives some examples of this in his "Python Programming on Win32" book. Alan G PS The doc string for the script is: """Python ActiveX Scripting Implementation This module implements the Python ActiveX Scripting client. To register the implementation, simply "run" this Python program - ie either double-click on it, or run "python.exe pyscript.py" from the command line. """ ------_=_NextPart_001_01C1106B.5D685BF0 Content-type: text/html; charset="ISO-8859-1"
Is there a way to get Python to work with the Microsoft Scripting Engine.  I've seen this done with Perl, and I've read that Python works, but I haven't been able to find a way.  Any help will be greatly appreciated!  
Yes, you need to install WSH on Windows then run a script from
the winall(or activestate python distribution) that registers
Python as a scripting language. (Its pyscript.py found in:
$PYTHON/win32comext/axscript/client - obvious eh?! :-)
Python scripts should then be created with an extension of .pys
 
However I've failed to get this to work! On asking Mark Hammond
on c.l.p he suggested that it was easier not to bother and
just use native OLE to instantiate the WSH objects directly.
(Try searching the newsnet archives on Google...)
 
He gives some examples of this in his "Python Programming on
Win32" book.
 
Alan G
 
PS The doc string for the script is:
"""Python ActiveX Scripting Implementation
 
This module implements the Python ActiveX Scripting client.
 
To register the implementation, simply "run" this Python program - ie
either double-click on it, or run "python.exe pyscript.py" from the
command line.
"""
 

 

------_=_NextPart_001_01C1106B.5D685BF0-- From alan.gauld@bt.com Thu Jul 19 17:02:51 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 19 Jul 2001 17:02:51 +0100 Subject: [Tutor] Real LCM Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8BC@mbtlipnt02.btlabs.bt.co.uk> > I finally have the gcd and lcm for any length list of > numbers. > ---------------------------------------------------------- > def __gcd__(a,b): > if b==0: > return a > return __gcd__(b,a%b) > > def gcd(list): > list.sort() > g=list[0] > for i in range(len(list)): > g=__gcd__(g,list[i]) > return g def gcd(lst): lst.sort() return reduce(__gcd__, lst) I think that should do the same thing? Alan G From dsh8290@rit.edu Thu Jul 19 17:07:35 2001 From: dsh8290@rit.edu (D-Man) Date: Thu, 19 Jul 2001 12:07:35 -0400 Subject: [Tutor] variables within function - wha? In-Reply-To: <200107191717.f6JHHOL19785@pop.nsacom.net>; from kromag@nsacom.net on Thu, Jul 19, 2001 at 10:17:24AM -0700 References: <200107191717.f6JHHOL19785@pop.nsacom.net> Message-ID: <20010719120735.E20054@harmony.cs.rit.edu> On Thu, Jul 19, 2001 at 10:17:24AM -0700, kromag@nsacom.net wrote: | I am trying to get a function to perfrom simple calculations based on 3 | values. | | ----------------------------------- | | def filter(cc,rpm,type): | cid=cc/16.387 | ocg=(cid*rpm)/20839 | foam=ocg*1.3767 | paper=ocg*1.2181 | if type==paper: | return paper, | elif type==foam: | return foam, | else: | return ocg | | ----------------------------------- | | I can't figure out why: | | >>> filter(1800,7000,foam) | Traceback (innermost last): | File "", line 1, in ? | filter(1800,7000,foam) | NameError: There is no variable named 'foam' | >>> | | occours. Have I been inhaling too much brake cleaner? (this is in addition to the earlier response) You aren't in the function yet. You want to invoke it with filter( 1800 , 7000 , 'foam' ) (I like the extra spaces) Also, filter is a built-in function so I recommend changing the name to something else. In addition it is probably a good idea to make a "global" constant for FOAM and PAPER rather than duplicating string literals in several places (use the same "global" in the comparison in the function). Then you can change the value to anything you want and clients won't know or care that there was a difference. HTH, -D From bill-bell@bill-bell.hamilton.on.ca Thu Jul 19 17:15:07 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Thu, 19 Jul 2001 12:15:07 -0400 Subject: [Tutor] Re: re: Python for the Microsoft Scripting Engine In-Reply-To: Message-ID: <3B56CF4B.22200.381DA70@localhost> "Mike Lange" wrote, in part: re: Python for the Microsoft Scripting Engine > Is there a way to get Python to work with the Microsoft Scripting > Engine. I've seen this done with Perl, and I've read that Python > works, but I haven't been able to find a way. Any help will be > greatly appreciated! Thanks! Chapter 21 of Hammond and Robinson, "Python Programming on Win32" (O'Reilly) is a good treatment of this topic. In what context do you want to use scripting, IE or IIS? From csmith@blakeschool.org Thu Jul 19 18:03:01 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Thu, 19 Jul 2001 12:03:01 -0500 Subject: [Tutor] Re: Tutor digest, Vol 1 #965 - 15 msgs In-Reply-To: References: Message-ID: Christopher P. Smith writes: > m = nn/n + nn % n # ceil(nn/n) This should be the two lines m=(nn-nn%n)/n if (nn%n<>0):m=m+1 (You get the same with m=(nn-nn%/n)/n+(nn%n<>0), too, since logic results are 0 or 1. Watch out for division by zero, though.) > for i in range(n): > for j in range(i,i+m+n,n): # +m b/c you need that many past i And the range should be range(i,i+m*n,n) #m*n not m+n /c From csmith@blakeschool.org Thu Jul 19 18:03:01 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Thu, 19 Jul 2001 12:03:01 -0500 Subject: [Tutor] Re: Bunch lists into sublists via alternation In-Reply-To: References: Message-ID: Christopher P. Smith writes: > m = nn/n + nn % n # ceil(nn/n) This should be the two lines m=(nn-nn%n)/n if (nn%n<>0):m=m+1 (You get the same with m=(nn-nn%/n)/n+(nn%n<>0), too, since logic results are 0 or 1. Watch out for division by zero, though.) > for i in range(n): > for j in range(i,i+m+n,n): # +m b/c you need that many past i And the range should be range(i,i+m*n,n) #m*n not m+n /c From Charlie Clark Thu Jul 19 18:11:55 2001 From: Charlie Clark (Charlie Clark) Date: Thu, 19 Jul 2001 19:11:55 +0200 Subject: [Tutor] Re: Tutor digest, Vol 1 #965 - 15 msgs References: Message-ID: <0003897581fe4281_mailit@mail.isis.de> >From: kromag@nsacom.net [SMTP:kromag@nsacom.net] >> def filter(cc,rpm,type): >> cid=cc/16.387 >> ocg=(cid*rpm)/20839 >> foam=ocg*1.3767 >> paper=ocg*1.2181 >> if type==paper: >> return paper, >> elif type==foam: >> return foam, >> else: >> return ocg > Gives the error Traceback (innermost last): File "", line 1, in ? filter(1800,7000,foam) NameError: There is no variable named 'foam' It took me a second to spot this. Paper and foam are values for type ("paper", "foam") but also variables in their own right (paper, foam). But they are also local variables - they are confined to the function. Furthermore, you are trying to feed a variable (foam) to the function before it has been initialised. If you had written foam = "" or anything like that you would have generated different errors. It is very easy to make this kind of mistake as well as type errors - at least I do it all the time. Also you don't need the comma after a return. I don't know if it's just me but if you're taking the trouble to generate the intermediate local and thus hidden values like "cid" I'd introduce a special "return_value" in the conditions and just return that. I do this when I really need to be able step through my functions. It might also be an idea not to use "type" as a name as it is a built in function. So my solution would be def filter_type(cc,rpm,material): cid = cc/16.387 return_value = ocg = (cid*rpm)/20839 # assign the default value to be # returned foam_value = ocg*1.3767 paper_value = ocg*1.2181 if material == "paper": return_value = paper_value elif material == "foam": return_value = foam_value return return_value using it print filter_type(1800,7000,'water') print filter_type(1800,7000,'paper') print filter_type(1800,7000,'foam') gives respectively: 36.8972685137 44.9445627765 50.7964695628 >BTW, are you using tabs to indent your code? Don't! Use spaces instead. I noticed there was a heated discussion on the newsgroup about this a while back and I'm sure it crops up often. And the consensus seemed to be that spaces are the way to do things. But tabs are allowed. Maybe there is a page somewhere that presents the arguments? That would be useful to know. Charlie PS: I enjoyed working through this! From bwalkup@compuserve.com Thu Jul 19 19:20:25 2001 From: bwalkup@compuserve.com (Scott Walkup) Date: Thu, 19 Jul 2001 14:20:25 -0400 Subject: [Tutor] Tkinter widget config options help Message-ID: <3B5724E9.9164DBF4@compuserve.com> Hello everyone! I've been checking out the chapter in Programming Python 2nd Edition about GUI programming with Tkinter. While still on the early examples I've come across a rather embarissing/annoying bug somewhere in my python setup. One the first few examples of GUI programming specificaly dealing with passing config options to the Tkinter module: from Tkinter import * Label(text='Hello GUI World!').pack(expand=YES, fill=BOTH) mainloop() spit out errors about NameError YES not being defined. (well actualy now that works,*boggle* but another way I tried to setup this script was: #!/usr/bin/python import Tkinter widget = Tkinter.Label(None, text='Hello GUI world!') widget.pack(fill="both",expand=1) widget.mainloop() (I set it up as an executable for linux, so ingore the #!/usr/bin/python) The program this way works, but note that both config options, fill and expand have different settings that want the book said I could use (meaning YES instead of 1 and BOTH instead of passing it as a string, not a variable). But if I try using the books example of passing variables, python calls me stupid and says YES (and if I switch it around) and BOTH are not defined. I went and hunted down my Tkinter.py and searched in the code there (Thanks to python its easy to read and not be completely confused sometimes) and found I could pass 1 for expand and by experimentation I figured out I could use "both" to get what I wanted done. So anyway I also found out where all these variables where hiding from me, in Tkconstants.py, and I was able to verify that the variables I needed where in there, and also that Tkinter.py was calling that file, but somehow in all this weirdness, my script never seems to know that they do exist *grumble*. I've searched the newgroups, mailing list archives and checked out all the relevant FAQ's I could find for this problem, do I just have a problem in the code I was creating? (I could have sworn the books example didnt work last night) Another thing, I also checked out the Tkinter FAQ for unix and it talked of trying out import Tkinter Tkinter._test() and that does work. Ugh. Any help is appreciated, I'm sure I'm missing something obvious in my code, or maybe python just doesnt want to work with me today. TIA! From kp87@lycos.com Thu Jul 19 21:27:01 2001 From: kp87@lycos.com (kevin parks) Date: Fri, 20 Jul 2001 05:27:01 +0900 Subject: [Tutor] mixed tuples and lists to nested lists Message-ID: Here is a problem i come up against frequently and i guess i should know this by now, but i don't. Some times if you fiddle around with things you end up with a list whose list elements contain not only lists, but nested lists, and *gasp* those Beckett-esque immutable tuples. An example might be: [(1, 100, 'w'), (2, 101, 'x'), (3, 102, 'y'), (4, 103, 'z')] how do i change that to be: [[1, 100, 'w'], [2, 101, 'x'], [3, 102, 'y'], [4, 103, 'z']] A pathalogical example would be to turn something like this in to a list of lists: ['abc',[(1,2), ([3],4)],5] cheers, back to the interpreter kevin Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From rick@niof.net Thu Jul 19 21:57:35 2001 From: rick@niof.net (Rick Pasotto) Date: Thu, 19 Jul 2001 16:57:35 -0400 Subject: [Tutor] Tkinter widget config options help In-Reply-To: <3B5724E9.9164DBF4@compuserve.com> Message-ID: <20010719165735.C17321@tc.niof.net> On Thu, Jul 19, 2001 at 02:20:25PM -0400, Scott Walkup wrote: > Hello everyone! > > I've been checking out the chapter in Programming Python 2nd Edition > about GUI programming with Tkinter. While still on the early examples > I've come across a rather embarissing/annoying bug somewhere in my > python setup. > > One the first few examples of GUI programming specificaly dealing with > passing config options to the Tkinter module: > > from Tkinter import * > Label(text='Hello GUI World!').pack(expand=YES, fill=BOTH) > mainloop() > > spit out errors about NameError YES not being defined. I cut-and-pasted and it works for me (linux, python 1.5.2). -- Thus, there is not a single ill afflicting the nation for which the government has not voluntarily made itself responsible. Is it astonishing, then, that each little twinge should be a cause of revolution? -- Frйdйric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From kp87@lycos.com Thu Jul 19 22:39:29 2001 From: kp87@lycos.com (kevin parks) Date: Fri, 20 Jul 2001 06:39:29 +0900 Subject: [Tutor] Re: mixed tuples and lists to nested lists Message-ID: The following works fine, except it only goes one level deep. Hmmm... If i only understood recursion.... i have a feeling that's the next step..... I had no idea that you could just do: list(i), since tuples are supposed to be immutable i somehow expected that changing the type would be harder. All the books make such a big deal about how you have to be wearing special color socks and the moon as to be in the right phase. Bravo to Mr. Chun for unmasking tuples for what the really are: sort of immutable. imposters! def foo(seq): if type(seq)!=type([]): return 0 out=[] for i in seq: out.append(list(i)) return out --- On Fri, 20 Jul 2001 05:27:01 kevin parks wrote: >Here is a problem i come up against frequently and i guess i should know this by >now, but i don't. Some times if you fiddle around with things you end up with a list >whose list elements contain not only lists, but nested lists, and *gasp* >those Beckett-esque immutable tuples. > >An example might be: > >[(1, 100, 'w'), (2, 101, 'x'), (3, 102, 'y'), (4, 103, 'z')] > >how do i change that to be: > >[[1, 100, 'w'], [2, 101, 'x'], [3, 102, 'y'], [4, 103, 'z']] > >A pathalogical example would be to turn something like >this in to a list of lists: > >['abc',[(1,2), ([3],4)],5] > >cheers, > >back to the interpreter > >kevin > Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From dyoo@hkn.eecs.berkeley.edu Fri Jul 20 00:05:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 19 Jul 2001 16:05:24 -0700 (PDT) Subject: [Tutor] Re: mixed tuples and lists to nested lists (spoilers ahead) In-Reply-To: Message-ID: On Fri, 20 Jul 2001, kevin parks wrote: > The following works fine, except it only goes one level deep. Hmmm... > If i only understood recursion.... i have a feeling that's the next > step..... > > def foo(seq): > if type(seq)!=type([]): > return 0 > out=[] > for i in seq: > out.append(list(i)) > return out Let's give a name to this action that makes tuples into lists... how about "deeplyTransformTuplesToLists()"? It's fun to say quicky. *grin* I'll take a recursive approach to this problem, and try to informally say what what I'm thinking as I'm solving this. If recursion seems like a cool idea to you, you may want to look at Brian Harvey's "Simply Scheme", which is an introduction to computer science ideas like recursion. http://www.cs.berkeley.edu/~bh/simply-toc.html (I obviously have a university bias here. *grin* Sorry!) The key to recursion is to believe firmly that the function already works for certain "small" things. If wishing makes it so, then it does so especially with recursion. What we can wish for is that deeplyTransformTuplesToLists() works on things that are "smaller" than what we give it initially. We'd better clarify what that means. For example, let's say that we try the following: deeplyTransformTuplesToLists( [1, 2, (3, 4) ] ) If we think about solving this problem recursively, we can pretend that deeplyTransformTuplesToLists will work on these things: deeplyTransformTuplesToLists(1) deeplyTransformTuplesToLists(2) deeplyTransformTuplesToLists((3, 4)) That's what we mean by "smaller": it's a smaller piece of our original input. If we know the answers to the three smaller calls, then it's very simple to get the answer to our original question: deeplyTransformTuplesToLists( [1, 2, (3, 4)] ) == [ deeplyTransformTuplesToLists(1), deeplyTransformTuplesToLists(2) deeplyTransformTuplesToLists((3, 4)) ] That's how we could solve that example, if we assume that the function works for small things. More formally, if we give deeplyTransformTuplesToLists() some thingy, then it has the following things to think about: 1. If that thingy is a list or tuple sequence, then it can deeplyTransformTuplesToLists() on every element on that sequence. If we believe in recursion, we can trust that deeplyTransformTuplesToLists will work on those smaller portions of our sequence. 2. But what if it's not a sequence? That is, what should something like "deeplyTransformTuplesToLists(1)" return? It's not a sequence, and so it shouldn't be affected by deeplyTransformTuplesToLists() --- it should just leave it alone. Believe it or not, this is a complete definition that will work on anything we throw at it. (spoiler warning ahead. Try writing the code first before reading below.) ### from types import ListType, TupleType def deeplyTransformTuplesToLists(thingy): if type(thingy) in [ListType, TupleType]: return map(deeplyTransformTuplesToLists, thingy) else: return thingy ### And that's it. Here's some tests of the function: ### >>> l1 = [(1, 100, 'w'), (2, 101, 'x'), (3, 102, 'y'), (4, 103, 'z')] >>> deeplyTransformTuplesToLists(l1) [[1, 100, 'w'], [2, 101, 'x'], [3, 102, 'y'], [4, 103, 'z']] >>> l2 = ['abc',[(1,2), ([3],4)],5] >>> deeplyTransformTuplesToLists(l2) ['abc', [[1, 2], [[3], 4]], 5] ### So recursion is a very powerful tool. I rushed this example because it's just very exciting, so my apologies if this goes fast. If you have any questions, feel free to ask them. From hnowak@cuci.nl Fri Jul 20 06:15:23 2001 From: hnowak@cuci.nl (Hans Nowak) Date: Fri, 20 Jul 2001 07:15:23 +0200 Subject: [Tutor] variables within function - wha? In-Reply-To: <200107191717.f6JHHOL19785@pop.nsacom.net> Message-ID: <200107200517.f6K5HV916375@hera.cuci.nl> On 19 Jul 01, at 10:17, kromag@nsacom.net wrote: > I am trying to get a function to perfrom simple calculations based on 3 > values. > > ----------------------------------- > > def filter(cc,rpm,type): > cid=cc/16.387 > ocg=(cid*rpm)/20839 > foam=ocg*1.3767 > paper=ocg*1.2181 > if type==paper: > return paper, > elif type==foam: > return foam, > else: > return ocg > > ----------------------------------- > > I can't figure out why: > > >>> filter(1800,7000,foam) > Traceback (innermost last): > File "", line 1, in ? > filter(1800,7000,foam) > NameError: There is no variable named 'foam' > >>> > > occours. Have I been inhaling too much brake cleaner? If you call filter(1800, 7000, foam) then this only works if a variable 'foam' already exists outside of the 'filter' function. If it's an argument you call the function with, then it shouldn't be done like this. A possible variant (although I'm not sure what the function is doing, so I might be wrong) is: FOAM, PAPER = 1, 2 # just dummy values for the 'type' argument def filter(cc, rpm, type): cid = cc / 16.387 ocg = (cid * rpm) / 20839 if type == PAPER: return ocg * 1.2181, elif type == FOAM: return ocg * 1.3767, else: return ocg print filter(1800, 7000, FOAM) # (50.796469562756506,) A few side notes: did you mean to use a tuple for the return value? (As said, I don't know much about what this function does and what your intentions are, so you might have perfectly good reasons for it. But it strikes me as a bit odd that filter called with FOAM and PAPER will return a singleton tuple, while calling it with another value for 'type' will return a number. Also, note that this code overrides the built-in functions 'filter' and 'type'. If this code is part of a large program, you might want to consider renaming at least 'filter'. HTH, --Hans Nowak (zephyrfalcon@hvision.nl) You call me a masterless man. You are wrong. I am my own master. May Chickenlittle stab you in your your jugular! From scarblac@pino.selwerd.nl Fri Jul 20 08:59:35 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 20 Jul 2001 09:59:35 +0200 Subject: [Tutor] variables within function - wha? In-Reply-To: <200107191717.f6JHHOL19785@pop.nsacom.net>; from kromag@nsacom.net on Thu, Jul 19, 2001 at 10:17:24AM -0700 References: <200107191717.f6JHHOL19785@pop.nsacom.net> Message-ID: <20010720095935.A19988@pino.selwerd.nl> On 0, kromag@nsacom.net wrote: > I am trying to get a function to perfrom simple calculations based on 3 > values. > > ----------------------------------- > > def filter(cc,rpm,type): > cid=cc/16.387 > ocg=(cid*rpm)/20839 > foam=ocg*1.3767 > paper=ocg*1.2181 > if type==paper: > return paper, > elif type==foam: > return foam, > else: > return ocg > > ----------------------------------- > > I can't figure out why: > > >>> filter(1800,7000,foam) > Traceback (innermost last): > File "", line 1, in ? > filter(1800,7000,foam) > NameError: There is no variable named 'foam' > >>> > > occours. Have I been inhaling too much brake cleaner? Are you sure you want to give it some value in the variable foam? Or maybe do you want to give it the *word* foam? Then you need to put quotes around it, 'foam', and in the function as well: def filter(cc, rpm, type): cid = cc/16.387 ocg = (cid*rpm)/20839 foam = ocg*1.3767 paper = ocg*1.2181 # Here you set the variable to some value if type == 'paper': # But I assume you want to test against the *word* paper return paper # Return the value in the variable paper elif type == 'foam': return foam else: return ocg Now you can call it with, for instance, filter(18000,7000, 'foam') I've also removed the commas after the return statements: with the commas, you don't return the number, but a 1-element tuple containing the number. -- Remco Gerlich From w.richert@gmx.net Fri Jul 20 10:47:28 2001 From: w.richert@gmx.net (Willi Richert) Date: Fri, 20 Jul 2001 11:47:28 +0200 Subject: [Tutor] Multithreading and SocketServer.TCPServer Message-ID: <002401c11100$feb60b20$0500a8c0@willi> This is a multi-part message in MIME format. ------=_NextPart_000_0021_01C11111.C0B52DE0 Content-Type: text/plain Content-Transfer-Encoding: quoted-printable Hi, uses the TCPServer multithreading? If not, are there equivalent classes = that do? Examples? Thanks! willi ------=_NextPart_000_0021_01C11111.C0B52DE0 Content-Type: text/html Content-Transfer-Encoding: quoted-printable
Hi,
 
uses the TCPServer multithreading? If = not, are=20 there equivalent classes that do?
Examples?
 
Thanks!
willi
------=_NextPart_000_0021_01C11111.C0B52DE0-- From arcege@speakeasy.net Fri Jul 20 13:01:01 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Fri, 20 Jul 2001 08:01:01 -0400 (EDT) Subject: [Tutor] Multithreading and SocketServer.TCPServer In-Reply-To: from "Willi Richert" at Jul 20, 2001 11:47:28 AM Message-ID: <200107201201.f6KC11403130@dsl092-074-184.bos1.dsl.speakeasy.net> Willi Richert wrote > uses the TCPServer multithreading? If not, are there equivalent classes = > that do? > Examples? The TCPServer class does not use threading. But the subclass ThreadingTCPServer does. There is also a ForkingTCPServer and ThreadingUDPServer. They are all used the same way. You have a handler class to process a request. Create a subclass and override the "handle" method. Then pass the subclass to the Server class. >>> from SocketServer import ThreadingTCPServer, StreamRequestHandler >>> class EchoStreamRequestHandler(StreamRequestHandler): ... def handler(self): ... line = self.rfile.readline() # get info from client ... self.wfile.write(line) # write it back to client ... >>> server_address = ('', 9999) # dummy hostname and socket to listen on >>> server = ThreadingTCPServer( server_address, EchoStreamRequestHandler ) >>> server.serve_forever() # start up the server You might want to look at the BaseHTTPServer.py to see how the SocketServer module is used in other ways. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From rbl@hal.cwru.edu Fri Jul 20 13:23:10 2001 From: rbl@hal.cwru.edu (Robin B. Lake) Date: Fri, 20 Jul 2001 08:23:10 -0400 (EDT) Subject: [Tutor] Problem with urllib.openurl() Message-ID: <200107201223.IAA20772@hal.cwru.edu> On a Mac G3, OS 8.6, Python 2.0. For some time now, I've been using the myfile=urllib.openurl('URL path') construct to suck data files off the Web. Now I'm trying to use it to get both historical and real-time snapshots of stock portfolio prices. The historical data comes thru just fine, in that the Web site offers a "Download" button that sends it over as a comma-delimited file. The real-time data, however, does not make it into the Python-created file "myfile". I get HTML stuff showing in that file, but no data. I suspect that the problem arises in the Web site's use of cgi-bin to create the price table on the fly. Anyone have similar experiences? Is there a work-around? Thank you, Robin Lake lake@cwru.edu From lumbricus@gmx.net Fri Jul 20 13:57:29 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Fri, 20 Jul 2001 14:57:29 +0200 Subject: [Tutor] Problem with urllib.openurl() In-Reply-To: <200107201223.IAA20772@hal.cwru.edu>; from rbl@hal.cwru.edu on Fri, Jul 20, 2001 at 08:23:10AM -0400 References: <200107201223.IAA20772@hal.cwru.edu> Message-ID: <20010720145729.A18020@Laplace.localdomain> On Fri, Jul 20, 2001 at 08:23:10AM -0400, Robin B. Lake wrote: > > On a Mac G3, OS 8.6, Python 2.0. > > For some time now, I've been using the myfile=urllib.openurl('URL path') > construct to suck data files off the Web. Now I'm trying to use it to > get both historical and real-time snapshots of stock portfolio prices. > > The historical data comes thru just fine, in that the Web site offers a > "Download" button that sends it over as a comma-delimited file. > > The real-time data, however, does not make it into the Python-created > file "myfile". I get HTML stuff showing in that file, but no data. What does the HTML stuff say? I guess its the page from where the cgi script is called? >I suspect that the problem arises in the Web site's use of cgi-bin to > create the price table on the fly. I *guess* you are right. What input does the cgi script need? How does the url look like in your history file? > > Anyone have similar experiences? Is there a work-around? > Need more Info :-) > Thank you, > Robin Lake > lake@cwru.edu > Good luck J"o! -- To invent, you need a good imagination and a pile of junk. -- Thomas Edison From jack@oratrix.nl Fri Jul 20 14:17:44 2001 From: jack@oratrix.nl (Jack Jansen) Date: Fri, 20 Jul 2001 15:17:44 +0200 Subject: [Tutor] Re: [Pythonmac-SIG] Problem with urllib.openurl() In-Reply-To: Message by "Robin B. Lake" , Fri, 20 Jul 2001 08:23:10 -0400 (EDT) , <200107201223.IAA20772@hal.cwru.edu> Message-ID: <20010720131744.D5D12303181@snelboot.oratrix.nl> > For some time now, I've been using the myfile=urllib.openurl('URL path') > construct to suck data files off the Web. Now I'm trying to use it to > get both historical and real-time snapshots of stock portfolio prices. > [...] > The real-time data, however, does not make it into the Python-created > file "myfile". I get HTML stuff showing in that file, but no data. I > suspect that the problem arises in the Web site's use of cgi-bin to > create the price table on the fly. CGI or not on the server side shouldn't be a problem. A couple of things that would be a problem: - If the data isn't normally displayed as-is but interpreted by, say, a java applet or a plugin or something. The "html stuff" you mention could well be something that starts the plugin. It might even be java or javascript code that gets the data. Why not post the html code here? - There is a small possibility that the server-side looks at the browser type you're using and returns different info for explorer and netscape. If it only recognizes those two it could be that it returns nothing if your browser is not one of those. I've seen webpages do this:-( And, of course, urllib is neither Netscape nor Explorer. -- Jack Jansen | ++++ stop the execution of Mumia Abu-Jamal ++++ Jack.Jansen@oratrix.com | ++++ if you agree copy these lines to your sig ++++ www.oratrix.nl/~jack | see http://www.xs4all.nl/~tank/spg-l/sigaction.htm From Mark.Tobin@attcanada.com Fri Jul 20 19:16:31 2001 From: Mark.Tobin@attcanada.com (Tobin, Mark) Date: Fri, 20 Jul 2001 12:16:31 -0600 Subject: [Tutor] Lambda Message-ID: <3D7C088D6CCFD31190A5009027D30E9103391064@torex004.attcanada.ca> Is it fair to say that Lambda is just a shorthand for defining a function? I really haven't figured it out, and don't know where one might use it... anybody willing to write a paragraph on Lambdas or point me to an explanation? maybe trying to figure out lambdas and recursion in the same week was too lofty a goal... ;-) Mark From scarblac@pino.selwerd.nl Fri Jul 20 19:23:42 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 20 Jul 2001 20:23:42 +0200 Subject: [Tutor] Lambda In-Reply-To: <3D7C088D6CCFD31190A5009027D30E9103391064@torex004.attcanada.ca>; from Mark.Tobin@attcanada.com on Fri, Jul 20, 2001 at 12:16:31PM -0600 References: <3D7C088D6CCFD31190A5009027D30E9103391064@torex004.attcanada.ca> Message-ID: <20010720202342.A22933@pino.selwerd.nl> On 0, "Tobin, Mark" wrote: > Is it fair to say that Lambda is just a shorthand for defining a function? Yes. There are but a few differences between lambda and def: - A lambda doesn't have a name. - A lambda can only contain a single expression, of which the value is returned. No statements, control structures, etc. - Lambda is an expression, so you can use it as a function argument, and so on. Def is a statement, you have to define a function first, then you can give it to some function. > I really haven't figured it out, and don't know where one might use it... > anybody willing to write a paragraph on Lambdas or point me to an > explanation? You sometimes want to make a short throwaway function to use as a function argument, for instance to give a callback function to some GUI thingy, or as an argument to functions like map: L2 = map(lambda x: x*2, L) # Returns a list with all elements of L doubled That simply slightly easier to write than def double(x): return 2*x L2 = map(double, L) In many cases, list comprehensions can be used now where map/lambda used to be appropriate, and in my opinion at least they're more Pythonic: L2 = [x*2 for x in L] > maybe trying to figure out lambdas and recursion in the same week was too > lofty a goal... ;-) Well, recursion is a profound, fundamental concept, lambda is just a quick notation :) -- Remco Gerlich From shalehperry@home.com Fri Jul 20 19:29:33 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Fri, 20 Jul 2001 11:29:33 -0700 (PDT) Subject: [Tutor] Lambda In-Reply-To: <3D7C088D6CCFD31190A5009027D30E9103391064@torex004.attcanada.ca> Message-ID: On 20-Jul-2001 Tobin, Mark wrote: > Is it fair to say that Lambda is just a shorthand for defining a function? > I really haven't figured it out, and don't know where one might use it... > anybody willing to write a paragraph on Lambdas or point me to an > explanation? > yes, lamda just defines a function. lambda is a big thing in the functional programming world. Languages like lisp practically require it. But you are wondering "how does this affect me?". lambda lets you write code quickly, then change it later. For instance: map(lambda x: x + x, range(0, 10)) outputs [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]. Sure there are a few ways you could implement this. You could do: def x2(x): return x + x map(x2, range(0,10)) However, when you typed in the call to map you said "oh, i need a function here" and had to go write one. lambda lets you just do it, and make it pretty/efficient/whatever later. Plus who wants to declare silly functions like x2? From Mark.Tobin@attcanada.com Fri Jul 20 19:31:36 2001 From: Mark.Tobin@attcanada.com (Tobin, Mark) Date: Fri, 20 Jul 2001 12:31:36 -0600 Subject: [Tutor] Lambda Message-ID: <3D7C088D6CCFD31190A5009027D30E9103391065@torex004.attcanada.ca> Remco Gerlich wrote: > > In many cases, list comprehensions can be used now where > map/lambda used to > be appropriate, and in my opinion at least they're more Pythonic: Well maybe list comprehensions should be next, they don't look too scary ;-) And yes they look really similar to map/lambda now that I have an idea of what lambda does... Thanks Remco Mark > > L2 = [x*2 for x in L] > > > maybe trying to figure out lambdas and recursion in the > same week was too > > lofty a goal... ;-) > > Well, recursion is a profound, fundamental concept, lambda is > just a quick > notation :) > > -- > Remco Gerlich > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Mark.Tobin@attcanada.com Fri Jul 20 19:34:36 2001 From: Mark.Tobin@attcanada.com (Tobin, Mark) Date: Fri, 20 Jul 2001 12:34:36 -0600 Subject: [Tutor] Lambda Message-ID: <3D7C088D6CCFD31190A5009027D30E9103391066@torex004.attcanada.ca> > pretty/efficient/whatever later. Plus who wants to declare > silly functions > like x2? Not me! (anymore...) :-) Thanks Sean Mark > From memperad@iaware.org Fri Jul 20 20:11:26 2001 From: memperad@iaware.org (Michael Emperador) Date: Fri, 20 Jul 2001 12:11:26 -0700 (PDT) Subject: [Tutor] error message Message-ID: I get the following error message when running the script below. I am using python 2.0 on Suse 7.2. Error: Traceback (most recent call last): File "./test.py", line 20, in ? curr_cust(customers, name) File "./test.py", line 8, in curr_cust if x in ("seq2"): TypeError: 'in ' requires character as left operand Script: #! /usr/bin/python import cgi, os, string def curr_cust(seq1,seq2): cust = [] for x in seq1: if x in ("seq2"): cust.append(x) return cust file = open('/usr/local/httpd/htdocs/pp/opt/customers','r') customers = file.readlines() file.close() form = {'username':'Somers'} name = form['username'] curr_cust(customers, name) Mike From scarblac@pino.selwerd.nl Fri Jul 20 20:21:49 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 20 Jul 2001 21:21:49 +0200 Subject: [Tutor] error message In-Reply-To: ; from memperad@iaware.org on Fri, Jul 20, 2001 at 12:11:26PM -0700 References: Message-ID: <20010720212149.A23262@pino.selwerd.nl> On 0, Michael Emperador wrote: > I get the following error message when running the script below. I am > using python 2.0 on Suse 7.2. > > Error: > Traceback (most recent call last): > File "./test.py", line 20, in ? > curr_cust(customers, name) > File "./test.py", line 8, in curr_cust > if x in ("seq2"): > TypeError: 'in ' requires character as left operand > > Script: > > #! /usr/bin/python > > import cgi, os, string > > def curr_cust(seq1,seq2): > cust = [] > for x in seq1: > if x in ("seq2"): > cust.append(x) > return cust > > file = open('/usr/local/httpd/htdocs/pp/opt/customers','r') > customers = file.readlines() > file.close() > > form = {'username':'Somers'} > name = form['username'] > > curr_cust(customers, name) What happens is this: customers is a list of strings (returned by readlines()). name is equal to 'Somers' You pass the list and the string as arguments to curr_cust. Then, for each string in the list of lines: it tries to check if the line is in the string "seq2", e.g. suppose the first line of the file is "firstline\n", what it checks is whether "firstline\n" is in "seq2", which gives an error because you can only test if a character is inside a string this way, not a whole string (hence 'in ' requires character as left operand). For one thing, I think you meant simply seq2 where you wrote ("seq2"). The first is the name of a variable, the second is a string with () around it. But that won't work either since then it tries to check if the lines of the file are in the string 'Somers', and you can't do that. I'm actually not sure what you're trying to do, I hope this step by step explanation of what happens is clear enough. I'm tired. -- Remco Gerlich From dyoo@hkn.eecs.berkeley.edu Fri Jul 20 20:44:48 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 20 Jul 2001 12:44:48 -0700 (PDT) Subject: [Tutor] error message In-Reply-To: Message-ID: On Fri, 20 Jul 2001, Michael Emperador wrote: > def curr_cust(seq1,seq2): > cust = [] > for x in seq1: > if x in ("seq2"): > cust.append(x) > return cust Let me make sure I understand what you want curr_cust() to do first. Do you want it to do something like this? ### > curr_cust(['mary', 'had', 'lamb', 'chops'], ['mary', 'had', 'a', 'little', 'lamb']) ['mary', 'had', 'lamb'] ### (Sorry about the gruesome example --- it's lunchtime for me. *grin*) If so, then what you'll want to do is check if x is inside seq2. Assuming this is what you want, the correction will look like this: ### def curr_cust(seq1,seq2): cust = [] for x in seq1: if x in seq2: cust.append(x) return cust ### Another way we could define this function would be to use list comprehensions, like this: ### def curr_cust(seq1, seq2): return [x for x in seq1 if x in seq2] ### If you have more questions, please feel free to ask. Good luck to you! From jessefw@loop.com Fri Jul 20 21:34:45 2001 From: jessefw@loop.com (Jesse F. W) Date: Fri, 20 Jul 2001 13:34:45 -0700 Subject: [Tutor] Problem with urllib.openurl() In-Reply-To: <200107201223.IAA20772@hal.cwru.edu> Message-ID: <3B583375.25152.632849@localhost> Robin B. Lake wrote: > > On a Mac G3, OS 8.6, Python 2.0. > > For some time now, I've been using the myfile=urllib.openurl('URL > path') construct to suck data files off the Web. What?? urllib.openurl? When I try that, it gives me an attribute error. Did you mean urllib.urlopen('URL path')? ----------- > > Thank you, > Robin Lake > lake@cwru.edu Jesse Weinstein From jessefw@loop.com Fri Jul 20 21:40:47 2001 From: jessefw@loop.com (Jesse F. W) Date: Fri, 20 Jul 2001 13:40:47 -0700 Subject: [Tutor] Another problem with urllib Message-ID: <3B5834DF.16268.68AFC1@localhost> Dear Pythonics, When I attempt to grab a file from the net using urllib.urlopen, it thinks for a second, then gives me a 'Connection refused' socket error. I am using Python 2.0, Windows 95, and I am connecting to the net with the ISP: loop.com. I can access the net quite will in other programs. If anyone has any tests they could suggest, or possible solutions, please post. Thank you for your time, Jesse W From scarblac@pino.selwerd.nl Fri Jul 20 21:50:31 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 20 Jul 2001 22:50:31 +0200 Subject: [Tutor] Another problem with urllib In-Reply-To: <3B5834DF.16268.68AFC1@localhost>; from jessefw@loop.com on Fri, Jul 20, 2001 at 01:40:47PM -0700 References: <3B5834DF.16268.68AFC1@localhost> Message-ID: <20010720225031.A23986@pino.selwerd.nl> On 0, "Jesse F. W" wrote: > When I attempt to grab a file from the net using urllib.urlopen, it > thinks for a second, then gives me a 'Connection refused' socket > error. I am using Python 2.0, Windows 95, and I am connecting to > the net with the ISP: loop.com. I can access the net quite will in > other programs. The site is refusing connection for some reason; apparently it's down. That's not a Python problem. -- Remco Gerlich From memperad@iaware.org Fri Jul 20 21:52:57 2001 From: memperad@iaware.org (Michael Emperador) Date: Fri, 20 Jul 2001 13:52:57 -0700 (PDT) Subject: [Tutor] error message In-Reply-To: Message-ID: On Fri, 20 Jul 2001, Danny Yoo wrote: > Date: Fri, 20 Jul 2001 12:44:48 -0700 (PDT) > From: Danny Yoo > To: Michael Emperador > Cc: tutor@python.org > Subject: Re: [Tutor] error message > > On Fri, 20 Jul 2001, Michael Emperador wrote: > > > def curr_cust(seq1,seq2): > > cust = [] > > for x in seq1: > > if x in ("seq2"): > > cust.append(x) > > return cust > > Let me make sure I understand what you want curr_cust() to do first. Do > you want it to do something like this? > > ### > > curr_cust(['mary', 'had', 'lamb', 'chops'], > ['mary', 'had', 'a', 'little', 'lamb']) > ['mary', 'had', 'lamb'] > ### > > (Sorry about the gruesome example --- it's lunchtime for me. *grin*) > > If so, then what you'll want to do is check if x is inside seq2. > Assuming this is what you want, the correction will look like this: > > ### > def curr_cust(seq1,seq2): > cust = [] > for x in seq1: > if x in seq2: > cust.append(x) > return cust > ### Daniel, I did do exactly this and came up with the same error. I actually sent the wrong snippet of code--I was trying to modify based on some suggestions. The script is actually a cgi script I am attempting to write. The form dictionary is what is stored in cgi.FieldStorage. I wanted to simplify to test my first function. I've based the function on an example in Learning Python. I'm still at a loss. Thanks for your help Mike > > > Another way we could define this function would be to use list > comprehensions, like this: > > ### > def curr_cust(seq1, seq2): > return [x for x in seq1 if x in seq2] > ### > > If you have more questions, please feel free to ask. Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jessw@loop.com Fri Jul 20 21:59:12 2001 From: jessw@loop.com (Jesse W) Date: Fri, 20 Jul 2001 13:59:12 -0700 Subject: [Tutor] Another problem with urllib In-Reply-To: <20010720225031.A23986@pino.selwerd.nl> References: <3B5834DF.16268.68AFC1@localhost>; from jessefw@loop.com on Fri, Jul 20, 2001 at 01:40:47PM -0700 Message-ID: <3B583930.15673.798D7A@localhost> Remco Gerlich wrote: > On 0, "Jesse F. W" wrote: > > When I attempt to grab a file from the net using urllib.urlopen, it > > thinks for a second, then gives me a 'Connection refused' socket > > error. I am using Python 2.0, Windows 95, and I am connecting to > > the net with the ISP: loop.com. I can access the net quite will in > > other programs. > > The site is refusing connection for some reason; apparently it's down. > > That's not a Python problem. It's true that 'Connection refused' generaly refers to the site being down, which certianly is not a Python problem- But, I get that message when I try to access _any_ site, even sites that I am looking at in Netscape at the exact same time. That is why I suspect the problem has something to do with Python. ;-) The error messges I get are below: >>> urllib.urlopen('http://www.google.com') Traceback (innermost last): File "", line 1, in ? urllib.urlopen('http://www.google.com') File "c:\python20\lib\urllib.py", line 61, in urlopen return _urlopener.open(url) File "c:\python20\lib\urllib.py", line 166, in open return getattr(self, name)(url) File "c:\python20\lib\urllib.py", line 273, in open_http h.putrequest('GET', selector) File "c:\python20\lib\httplib.py", line 425, in putrequest self.send(str) File "c:\python20\lib\httplib.py", line 367, in send self.connect() File "c:\python20\lib\httplib.py", line 351, in connect self.sock.connect((self.host, self.port)) File "", line 1, in connect IOError: [Errno socket error] (10061, 'Connection refused') Thank you for your time, Jesse Weinstein From scarblac@pino.selwerd.nl Fri Jul 20 22:11:30 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 20 Jul 2001 23:11:30 +0200 Subject: [Tutor] Another problem with urllib In-Reply-To: <3B583930.15673.798D7A@localhost>; from jessw@loop.com on Fri, Jul 20, 2001 at 01:59:12PM -0700 References: <3B5834DF.16268.68AFC1@localhost>; <20010720225031.A23986@pino.selwerd.nl> <3B583930.15673.798D7A@localhost> Message-ID: <20010720231130.A24341@pino.selwerd.nl> On 0, Jesse W wrote: > It's true that 'Connection refused' generaly refers to the site being > down, which certianly is not a Python problem- But, I get that > message when I try to access _any_ site, even sites that I am > looking at in Netscape at the exact same time. That is why I suspect > the problem has something to do with Python. ;-) Python just opens a socket to a host and port, which uses the underlying socket code of your system, and it reports a 'connection refused', for some reason. Or you maybe behind some sort of proxy? It could be that Netscape is recognized or knows how to deal with the proxy, while Python doesn't? What happens when you start telnet, and try to make a connection to www.google.com on port 80, which is the same socket operation? -- Remco Gerlich From jwblist@olympus.net Fri Jul 20 23:02:08 2001 From: jwblist@olympus.net (John W Baxter) Date: Fri, 20 Jul 2001 15:02:08 -0700 Subject: [Tutor] Re: [Pythonmac-SIG] Problem with urllib.openurl() In-Reply-To: <20010720131744.D5D12303181@snelboot.oratrix.nl> References: <20010720131744.D5D12303181@snelboot.oratrix.nl> Message-ID: At 15:17 +0200 7/20/2001, Jack Jansen wrote: >And, of course, urllib is >neither Netscape nor Explorer. Given the number of sites which insist on sniffing the browser, the ability to lie about browser type might be a nice enhancement to urllib. But that's not a Mac thing. --John -- John Baxter jwblist@olympus.net Port Ludlow, WA, USA From scarblac@pino.selwerd.nl Fri Jul 20 23:04:24 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Sat, 21 Jul 2001 00:04:24 +0200 Subject: [jessw@loop.com: Re: [Tutor] Another problem with urllib] Message-ID: <20010721000424.A24572@pino.selwerd.nl> (forwarding because Jesse mailed to me accidentally - a *very* common problem for me as well) Jesse writes: > On 0, Jesse W wrote: > > It's true that 'Connection refused' generaly refers to the site > > being down, which certianly is not a Python problem- But, I get that > > message when I try to access _any_ site, even sites that I am > > looking at in Netscape at the exact same time. That is why I > > suspect the problem has something to do with Python. ;-) > > Python just opens a socket to a host and port, which uses the > underlying socket code of your system, and it reports a 'connection > refused', for some reason. > > Or you maybe behind some sort of proxy? It could be that Netscape is > recognized or knows how to deal with the proxy, while Python doesn't? > > What happens when you start telnet, and try to make a connection to > www.google.com on port 80, which is the same socket operation? > Since tenet is a GUI program on Win 95, I can't give you text results, but the connection appears to work. After I connect, when I type 'GET /index.html' it prints the google webpage, then disconnects. (end) Remco: Ok, then I have no idea at all what could cause it. Maybe you should try opening a socket from Python to narrow the problem down, but that's all I can offer. And it's time for bed now, 12:04 am... -- Remco Gerlich From rob@jam.rr.com Sat Jul 21 00:27:19 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 20 Jul 2001 18:27:19 -0500 Subject: [Tutor] more thanks than usual Message-ID: I was just offered my first paying Python job while building a MindStorms bot. This was triply excellent because I haven't been soliciting jobs coding. And yet I was requested by name because I apparently left a good impression on a consultant before losing my job. They just need a GUI by Monday morning, and don't want to pay big license fees to use the language. Hmmm... Whatever shall I recommend? heh! If the satellite doesn't go down during Farscape tonight, this will have been a basically perfect Friday. This good fortune would simply not have occurred if not for the Tutor list. You all rock, Rob "I do remain confident in Linda. She'll make a fine labor secretary. From what I've read in the press accounts, she's perfectly qualified." -- George W. Bush Useless Python: http://www.lowerstandard.com/python/ From jessefw@loop.com Sat Jul 21 01:10:34 2001 From: jessefw@loop.com (Jesse F. W) Date: Fri, 20 Jul 2001 17:10:34 -0700 Subject: [Tutor] Re: Your message to Tutor awaits moderator approval In-Reply-To: Message-ID: <3B58660A.1806.128C776@localhost> Hello all, tutor-admin@python.org wrote: > Your mail to 'Tutor' with the subject > > Re: [Tutor] Another problem with urllib > > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > Message may contain administrivia What is administrivia? Cute term, by the way. > > Either the message will get posted to the list, or you will receive > notification of the moderator's decision. > Thank you for your time, Jesse W From bill-bell@bill-bell.hamilton.on.ca Sat Jul 21 01:30:27 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Fri, 20 Jul 2001 20:30:27 -0400 Subject: [Tutor] Re: Lambda In-Reply-To: Message-ID: <3B5894E3.24285.21EC98F@localhost> "Tobin, Mark" wrote, in part: > Is it fair to say that Lambda is just a shorthand for defining a > function? I really haven't figured it out, and don't know where one > might use it... anybody willing to write a paragraph on Lambdas or > point me to an explanation? > > maybe trying to figure out lambdas and recursion in the same week was > too lofty a goal... ;-) I came upon a really good article about this topic yesterday. It's "Charming Python: Functional programming in Python, Parts 1 and 2" at http://www- 106.ibm.com/developerworks/library/l-prog.html by Dr David Metz. Notwithstanding what others have contributed on this list, you might enjoy Metz's article which is a fairly easy and informative read. Bill From w.richert@gmx.net Sat Jul 21 10:20:18 2001 From: w.richert@gmx.net (Willi Richert) Date: Sat, 21 Jul 2001 11:20:18 +0200 Subject: [Tutor] Problem with ThreadingTCPServer Message-ID: <008901c111c6$5d222480$0500a8c0@willi> This is a multi-part message in MIME format. ------=_NextPart_000_0086_01C111D7.1F1FC0A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, since 2 days I am debugging the Python socket stuff. First I had a simple following: class GameHandler(SocketServer.StreamRequestHandler): =20 def handle(self): request=3Dself.rfile.readline(512) # do interesting stuff result=3D"blabla" self.wfile.write(result) =20 server=3DSocketServer.TCPServer((HOST, PORT), GameHandler) server.serve_forever() and everything worked fine as long as only one client was accessing the = server. Then I changed to=20 ... server=3DSocketServer.ThreadingTCPServer((HOST, PORT), GameHandler) ... and I get now: server=3DSocketServer.TCPServer((HOST, PORT), GameHandler) Exception in thread Thread-1: Traceback (most recent call last): File "d:\python21\lib\threading.py", line 378, in __bootstrap self.run() File "d:\python21\lib\threading.py", line 366, in run apply(self.__target, self.__args, self.__kwargs) File "d:\python21\lib\SocketServer.py", line 247, in finish_request self.RequestHandlerClass(request, client_address, self) File "d:\python21\lib\SocketServer.py", line 497, in __init__ self.handle() File "D:\Hearts\Hearts\gameserver.py", line 223, in handle request=3Dself.rfile.readline(512) File "d:\python21\lib\socket.py", line 238, in readline new =3D self._sock.recv(self._rbufsize) AttributeError: 'int' object has no attribute 'recv' If I am right the socket in _fileobject.readline is 0. But why? Only because of the multithreading? Does anybody have an idea? Thanks very much for every hint, willi ------=_NextPart_000_0086_01C111D7.1F1FC0A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
 
since 2 days I am debugging the Python = socket=20 stuff.
 
First I had a simple = following:
 
class=20 GameHandler(SocketServer.StreamRequestHandler):  =20
    def handle(self):
       =20 request=3Dself.rfile.readline(512)
        # do=20 interesting stuff
       =20 result=3D"blabla"
       =20 self.wfile.write(result)  
 
server=3DSocketServer.TCPServer((HOST, = PORT),=20 GameHandler)
server.serve_forever()
 
and everything worked fine as long as = only one=20 client was accessing the server.
 
Then I changed to
...
server=3DSocketServer.ThreadingTCPServer((HOST,=20 PORT), GameHandler)
...
and I get now:
 
server=3DSocketServer.TCPServer((HOST, = PORT),=20 GameHandler)
Exception in thread = Thread-1:
Traceback (most=20 recent call last):
  File "d:\python21\lib\threading.py", line = 378, in=20 __bootstrap
    self.run()
  File=20 "d:\python21\lib\threading.py", line 366, in run
   =20 apply(self.__target, self.__args, self.__kwargs)
  File=20 "d:\python21\lib\SocketServer.py", line 247, in=20 finish_request
    self.RequestHandlerClass(request,=20 client_address, self)
  File "d:\python21\lib\SocketServer.py", = line=20 497, in __init__
    self.handle()
  File=20 "D:\Hearts\Hearts\gameserver.py", line 223, in = handle
   =20 request=3Dself.rfile.readline(512)
  File = "d:\python21\lib\socket.py",=20 line 238, in readline
    new =3D=20 self._sock.recv(self._rbufsize)
AttributeError: 'int' object has no = attribute=20 'recv'
If I am right the socket in = _fileobject.readline is=20 0.
But why? Only because of the=20 multithreading?
 
Does anybody have an idea?
 
Thanks very much for every = hint,
willi
------=_NextPart_000_0086_01C111D7.1F1FC0A0-- From w.richert@gmx.net Sat Jul 21 10:45:43 2001 From: w.richert@gmx.net (Willi Richert) Date: Sat, 21 Jul 2001 11:45:43 +0200 Subject: [Tutor] Problem with ThreadingTCPServer Part II Message-ID: <009601c111c9$ea4d07a0$0500a8c0@willi> This is a multi-part message in MIME format. ------=_NextPart_000_0093_01C111DA.AC9875A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, here is the second problem I have with ThreadingTCPServer. What I have forgotten to say: If I start the program the first time it = reads everything correct. But if it comes to writing in the = handle-Function I get: Exception in thread Thread-1: Traceback (most recent call last): File "d:\python21\lib\threading.py", line 378, in __bootstrap self.run() File "d:\python21\lib\threading.py", line 366, in run apply(self.__target, self.__args, self.__kwargs) File "d:\python21\lib\SocketServer.py", line 247, in finish_request self.RequestHandlerClass(request, client_address, self) File "d:\python21\lib\SocketServer.py", line 497, in __init__ self.handle() File "D:\Hearts\Hearts\gameserver.py", line 316, in handle self.wfile.write(result) File "d:\python21\lib\socket.py", line 195, in write self.flush() File "d:\python21\lib\socket.py", line 182, in flush self._sock.send(self._wbuf) AttributeError: 'int' object has no attribute 'send' After this also reading does not work and throws the Exception I have = told in the previous message. Then, if I wait for 5 minutes or so reading again works.... No idea what is wrong! Do you have one? willi ------=_NextPart_000_0093_01C111DA.AC9875A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi,
 
here is the second problem I have with=20 ThreadingTCPServer.
What I have forgotten to say: If I = start the=20 program the first time it reads everything correct. But if it comes to = writing=20 in the handle-Function I get:
 
Exception in thread = Thread-1:
Traceback (most=20 recent call last):
  File "d:\python21\lib\threading.py", line = 378, in=20 __bootstrap
    self.run()
  File=20 "d:\python21\lib\threading.py", line 366, in run
   =20 apply(self.__target, self.__args, self.__kwargs)
  File=20 "d:\python21\lib\SocketServer.py", line 247, in=20 finish_request
    self.RequestHandlerClass(request,=20 client_address, self)
  File "d:\python21\lib\SocketServer.py", = line=20 497, in __init__
    self.handle()
  File=20 "D:\Hearts\Hearts\gameserver.py", line 316, in = handle
   =20 self.wfile.write(result)
  File "d:\python21\lib\socket.py", = line 195,=20 in write
    self.flush()
  File=20 "d:\python21\lib\socket.py", line 182, in flush
   =20 self._sock.send(self._wbuf)
AttributeError: 'int' object has no = attribute=20 'send'
 
After this also reading does not work = and throws=20 the Exception I have told in the previous message.
Then, if I wait for 5 minutes or so = reading again=20 works....
 
No idea what is wrong!
Do you have one?
 
willi
------=_NextPart_000_0093_01C111DA.AC9875A0-- From steve@in.cqsl.com Sat Jul 21 11:32:08 2001 From: steve@in.cqsl.com (lonetwin@yahoo.com) Date: Sat, 21 Jul 2001 16:02:08 +0530 (IST) Subject: [Tutor] Name of a module within itself Message-ID: Hi there, One quick question, suppose I create a file (say 'foo.py'), that has classes MyFoo, HisFoo, HerFoo, and a function main(). Now, from main I need to refer to the name of the module (foo), such that, I could do something like: def main(): .... .... getattr([refer to this module], 'HisFoo') .... .... how do I do that ? from the prompt I can do: ============================================================ [steve@mercury ~]$ python Python 2.1 (#3, Jun 25 2001, 13:39:27) [GCC 2.95.3 19991030 (prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import foo >>> getattr(foo, 'HisFoo') >>> getattr(foo, 'HisFoo').x 'foo' >>> ============================================================== where the file 'foo.py' contains: =================================== #!/usr/bin/python class MyFoo: pass class HisFoo: x = 'foo' class HerFoo: x = 'bar' ==================================== ....ehe....Am I being clear enough ?...if not please tell me and I'll send some more code along. Peace Steve -- |||||||||||||||||||||| |||||||||#####|||||||| ||||||||#######||||||| ||||||||# O O #||||||| ||||||||#\ ~ /#||||||| ||||||##||\_/||##||||| |||||#||||||||||##|||| ||||#||||||||||||##||| ||||#|||||||||||||##|| |||/\##|||||||||##/\|| |/ \#########/ \ |\ \#######/ / ||\____/#######\____/| ===================================== Debug is human, de-fix divine. ==================================== From dsh8290@rit.edu Sat Jul 21 19:03:01 2001 From: dsh8290@rit.edu (D-Man) Date: Sat, 21 Jul 2001 14:03:01 -0400 Subject: [Tutor] Name of a module within itself In-Reply-To: ; from steve@in.cqsl.com on Sat, Jul 21, 2001 at 04:02:08PM +0530 References: Message-ID: <20010721140301.A22945@harmony.cs.rit.edu> On Sat, Jul 21, 2001 at 04:02:08PM +0530, lonetwin@yahoo.com wrote: | Hi there, | One quick question, suppose I create a file (say 'foo.py'), that has classes | MyFoo, HisFoo, HerFoo, and a function main(). Now, from main I need to | refer to the name of the module (foo), such that, I could do something like: | | def main(): | .... | .... | getattr([refer to this module], 'HisFoo') | .... | .... | | how do I do that ? Why do you want to use the getattr function? You could simply say def main() : ... HisFoo ... since main and HisFoo are in the same module. That will be clearer and works just as well. I don't think there is any way around accessing a module-level variable like that. Inside a module there is the __name__ attribute that is a string containing the name of the module. You could use sys.modules or __import__ to get the module object based on the name, but you have to get the name by referencing a module object and you might as well just get that class directly. HTH, -D From sheila@thinkspot.net Sun Jul 22 03:42:04 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 21 Jul 2001 19:42:04 -0700 Subject: [Tutor] subclassing Exceptions Message-ID: <1A1AAAED5664@kserver.org> OK, I've become fairly comfortable with defining my own classes and subclassing other classes and so on... Now I'm wanting to create some of my own exceptions. I've searched comp.lang.python at Google Groups, and the archives for this Tutor list, and faqts.python.com and my copy of Core Python Programming, but all I find on the subject is essentially this: """ You can create a new exception by subclassing one of the standard exceptions like this: class MyNewException(SomeStandardException): pass Just use the 'pass' statement unless you want to override some of the methods/data of the Standard Exception. """ And that's all the information I can find. I tried looking under the /Python20 directory for source or something for the Exception classes, but can't find it. For example, right now I'm working on subclassing the rfc822.py module, and I found the file rfc822.py in /Python20/Lib and studied the source until I understood it, and could subclass it. I'd like to find something similar for the standard exception classes. I looked in the /include directory and some others but can't find what I'm needing. Thanks for any pointers/tips. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dyoo@hkn.eecs.berkeley.edu Sun Jul 22 04:21:34 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 21 Jul 2001 20:21:34 -0700 (PDT) Subject: [Tutor] subclassing Exceptions In-Reply-To: <1A1AAAED5664@kserver.org> Message-ID: On Sat, 21 Jul 2001, Sheila King wrote: > I tried looking under the /Python20 directory for source or something > for the Exception classes, but can't find it. For example, right now > I'm working on subclassing the rfc822.py module, and I found the file > rfc822.py in /Python20/Lib and studied the source until I understood > it, and could subclass it. I'd like to find something similar for the > standard exception classes. I looked in the /include directory and > some others but can't find what I'm needing. There's a list of standard Python exceptions here: http://python.org/doc/current/lib/module-exceptions.html As to where they're defined... hmmm... I need to check... ah! They are very deeply embedded into Python's internal definition --- they aren't in a particular Python file. If you're curious, you can take a look at the: Python/exceptions.c file in the Python source code. I don't think that it will help, though, in understanding how to subclass exceptions for your own use: it's in C. Instead, it's probably better to look at specific examples of subclassed exceptions in the Python standard library. For example, we can take a look at the XML processing library, 'xml.sax', http://python.org/doc/current/lib/module-xml.sax.html which has a definition of a 'SAXException' in the xml/sax/_exceptions.py library file: ### class SAXException(Exception): """Encapsulate an XML error or warning. This class can contain basic error or warning information from either the XML parser or the application: you can subclass it to provide additional functionality, or to add localization. Note that although you will receive a SAXException as the argument to the handlers in the ErrorHandler interface, you are not actually required to throw the exception; instead, you can simply read the information in it.""" def __init__(self, msg, exception=None): """Creates an exception. The message is required, but the exception is optional.""" self._msg = msg self._exception = exception Exception.__init__(self, msg) def getMessage(self): "Return a message for this exception." return self._msg def getException(self): "Return the embedded exception, or None if there was none." return self._exception def __str__(self): "Create a string representation of the exception." return self._msg def __getitem__(self, ix): """Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.""" raise AttributeError("__getitem__") ### Wow! Here, they are making the exception class very elaborate. Maybe this was a bad example. *grin* The important thing is to make sure to call the parent's initializer: Exception.__init__(self, msg) somewhere within our exception subclass. We can see a simpler example in ConfigParser.py, which also defines its own "Error" exception class: ### # exception classes class Error(Exception): def __init__(self, msg=''): self._msg = msg Exception.__init__(self, msg) def __repr__(self): return self._msg __str__ = __repr__ ### Take a look at the library, and see how it defines and uses subclasses exceptions. If you have questions, feel free to ask. Good luck! From sheila@thinkspot.net Sun Jul 22 04:30:38 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 21 Jul 2001 20:30:38 -0700 Subject: [Tutor] subclassing Exceptions In-Reply-To: References: <1A1AAAED5664@kserver.org> Message-ID: <1A46D3075774@kserver.org> On Sat, 21 Jul 2001 20:21:34 -0700 (PDT), Danny Yoo wrote about Re: [Tutor] subclassing Exceptions: :There's a list of standard Python exceptions here: : : http://python.org/doc/current/lib/module-exceptions.html Right, seen that many a time, plus also in Core Python Programming as well... :As to where they're defined... hmmm... I need to check... ah! They are :very deeply embedded into Python's internal definition --- they aren't in :a particular Python file. If you're curious, you can take a look at the: : : Python/exceptions.c : :file in the Python source code. I don't think that it will help, though, :in understanding how to subclass exceptions for your own use: it's in C. Ah, source code...that doesn't come with the standard Windows install .exe version, does it? (It does come with the Unix installs, I'm sure.) I probably would have to go to python.org and grab it. Do you think it would be that difficult for me to understand the C code? (I have taught C++ for the past two years to AP Comp Sci students...granted, an Intro level College course...not overly in-depth.) :Instead, it's probably better to look at specific examples of subclassed :exceptions in the Python standard library. For example, we can take a look :at the XML processing library, 'xml.sax', : : http://python.org/doc/current/lib/module-xml.sax.html : :which has a definition of a 'SAXException' in the xml/sax/_exceptions.py :library file: [code and comments snipped] :somewhere within our exception subclass. We can see a simpler example in :ConfigParser.py, which also defines its own "Error" exception class: [code snipped] :Take a look at the library, and see how it defines and uses subclasses :exceptions. If you have questions, feel free to ask. Good luck! Thanks heaps for these pointers, Danny. I will look the examples over and ask if I have questions. Should I just forego downloading the Python C source? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dyoo@hkn.eecs.berkeley.edu Sun Jul 22 04:41:06 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 21 Jul 2001 20:41:06 -0700 (PDT) Subject: [Tutor] subclassing Exceptions In-Reply-To: <1A46D3075774@kserver.org> Message-ID: On Sat, 21 Jul 2001, Sheila King wrote: > :file in the Python source code. I don't think that it will help, though, > :in understanding how to subclass exceptions for your own use: it's in C. > > Ah, source code...that doesn't come with the standard Windows install > .exe version, does it? (It does come with the Unix installs, I'm sure.) > I probably would have to go to python.org and grab it. > > Do you think it would be that difficult for me to understand the C code? > (I have taught C++ for the past two years to AP Comp Sci > students...granted, an Intro level College course...not overly > in-depth.) The C source code isn't too hard to understand; it's certainly well designed and modular. I've always thought it would be cool for someone to write a book that explains how Python works internally. Anyway, you can download the source code here: http://www.python.org/ftp/python/2.1.1/Python-2.1.1.tgz It's in tar.gz format, which is comparable to the 'zip' format on Windows. WinZip should be able to handle it gracefully, and you can just unzip it to a convenient location. > :Take a look at the library, and see how it defines and uses subclasses > :exceptions. If you have questions, feel free to ask. Good luck! > > Thanks heaps for these pointers, Danny. I will look the examples over > and ask if I have questions. No problem. (Oh, guess what? I'll be visiting my parents in Northridge next week. Maybe we could meet for coffee then. It would be pretty neat to say hi in person, no? *grin*) > Should I just forego downloading the Python C source? The source code is useful, but you probably don't need to download it in its entirety. If there's a particular C source file that you're interested in, you can use the SourceForge system to browse it: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/ Good luck to you. From sheila@thinkspot.net Sun Jul 22 05:56:51 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 21 Jul 2001 21:56:51 -0700 Subject: [Tutor] subclassing Exceptions In-Reply-To: References: <1A46D3075774@kserver.org> Message-ID: <1A9558A633EA@kserver.org> On Sat, 21 Jul 2001 20:41:06 -0700 (PDT), Danny Yoo wrote about Re: [Tutor] subclassing Exceptions: :On Sat, 21 Jul 2001, Sheila King wrote: : :> :Take a look at the library, and see how it defines and uses subclasses :> :exceptions. If you have questions, feel free to ask. Good luck! :> :> Thanks heaps for these pointers, Danny. I will look the examples over :> and ask if I have questions. : :No problem. (Oh, guess what? I'll be visiting my parents in Northridge :next week. Maybe we could meet for coffee then. It would be pretty neat :to say hi in person, no? *grin*) Sounds like an idea. I will e-mail you about it. :> Should I just forego downloading the Python C source? : :The source code is useful, but you probably don't need to download it in :its entirety. If there's a particular C source file that you're :interested in, you can use the SourceForge system to browse it: : : http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/ Great pointer/URL. I've been looking over the C source for exceptions.c. I can make out quite a bit of what is going on, and I see that it is apparently calling methods defined in Python.h, which I don't think I'll snatch right now. But, it appears to me, that for all exceptions, there are basically: 3 methods (unless you write additional ones?): __init__ __str__ __getitem__ and 1 data member: __doc__ Does that sound about right? I know what __init__, __str__ and __doc__ are for. I guess I need to look up the __getitem__ method. Now, to study the Python source examples you pointed out previously... Oh, one additional question: Suppose one were defining a new class. Could you conceive of any situation where one might want to create an exception that is a data member of that class?? OK, well what I'm doing, is writing a class that I want to make some exceptions for. I can't envision these exceptions ever being used outside of this class. Should they be data members of the class? (I'm thinking...not?) Maybe I should just define them in the same file as the class, but not bound to the class. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From taibei@yahoo.com Sun Jul 22 06:47:24 2001 From: taibei@yahoo.com (Robert Storey) Date: Sat, 21 Jul 2001 22:47:24 -0700 (PDT) Subject: [Tutor] code generators Message-ID: <20010722054724.71901.qmail@web13302.mail.yahoo.com> I recently learned of the existence of Glade, a GUI "code generator" (for lack of a better term) for Python. I also seem to recall reading awhile back that there was another sort of code generator for Python, but I can't recall what it's called. Is there anyone on this list who can enlighten me? TIA, Robert Storey __________________________________________________ Do You Yahoo!? Make international calls for as low as $.04/minute with Yahoo! Messenger http://phonecard.yahoo.com/ From sheila@thinkspot.net Sun Jul 22 06:50:52 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 21 Jul 2001 22:50:52 -0700 Subject: [Tutor] code generators In-Reply-To: <20010722054724.71901.qmail@web13302.mail.yahoo.com> References: <20010722054724.71901.qmail@web13302.mail.yahoo.com> Message-ID: <1AC68C4D20D3@kserver.org> On Sat, 21 Jul 2001 22:47:24 -0700 (PDT), Robert Storey wrote about [Tutor] code generators: :I recently learned of the existence of Glade, a GUI :"code generator" :(for lack of a better term) for Python. I also seem to :recall reading :awhile back that there was another sort of code :generator for Python, :but I can't recall what it's called. Is there anyone :on this list who :can enlighten me? Perhaps you are referring to Boa Constructor (which can be found at sourceforge.net). Glade is for, hmm...GTK ? Or PyQT? I don't recall which. Boa Constructor is, I believe, for wxPython? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From lonetwin@yahoo.com Sun Jul 22 09:19:49 2001 From: lonetwin@yahoo.com (steve) Date: Sun, 22 Jul 2001 13:49:49 +0530 Subject: [Tutor] Name of a module within itself In-Reply-To: <20010721140301.A22945@harmony.cs.rit.edu> References: <20010721140301.A22945@harmony.cs.rit.edu> Message-ID: <01072213494900.22080@mercury.in.cqsl.com> On Saturday 21 July 2001 23:33, D-man wrote: > On Sat, Jul 21, 2001 at 04:02:08PM +0530, lonetwin@yahoo.com wrote: > | Hi there, > | One quick question, suppose I create a file (say 'foo.py'), that ha= s > | classes MyFoo, HisFoo, HerFoo, and a function main(). Now, from main = I > | need to refer to the name of the module (foo), such that, I could do > | something like: > | > | def main(): > | =09.... > | =09getattr([refer to this module], 'HisFoo') > | =09.... > | how do I do that ? > > Why do you want to use the getattr function? You could simply say > > def main() : > ... > HisFoo > ... > > since main and HisFoo are in the same module. That will be clearer > and works just as well. I don't think there is any way around > accessing a module-level variable like that. Inside a module there is > the __name__ attribute that is a string containing the name of the > module. You could use sys.modules or __import__ to get the module > object based on the name, but you have to get the name by referencing > a module object and you might as well just get that class directly. > Hi there D-man, Thanx for replying....although I can't really use it like you said. Let = me=20 explain, here's what I'm trying to do: class Base: =09.... =09.... =09.... class Sub1(Base): =09ObjA =3D 'foo' =09.... =09.... class Sub2(Base): =09ObjA =3D 'bar' def main(): =09.... =09.... =09x =3D funcReturnsSub1orSub2() # x can be either a Sub1 or a Sub2 =09y =3D getattr([refer to this module], x).ObjA =09# y would be an ObjA irrespective of what x is, so y=3D'foo' | y=3D'ba= r' what I wrote above can be done from the prompt, like I showed in my previ= ous=20 mail: =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=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D [steve@mercury ~]$ python Python 2.1 (#3, Jun 25 2001, 13:39:27) [GCC 2.95.3 19991030 (prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import foo >>> getattr(foo, 'HisFoo') >>> getattr(foo, 'HisFoo').x 'foo' >>> getattr(foo, 'HerFoo').x 'bar' >>> =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=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D where the file 'foo.py' contains: =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 #!/usr/bin/python =20 class MyFoo: pass class HisFoo: x =3D 'foo' class HerFoo: x =3D 'bar' =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 Please tell me there's a way to do this, else I'll have to rethink stuff,= an'=20 thinking is not something that is happening naturally these days :) !!! Peace Steve --=20 |||||||||||||||||||||| |||||||||#####|||||||| ||||||||#######||||||| ||||||||# O O #||||||| ||||||||#\ ~ /#||||||| ||||||##||\_/||##||||| |||||#||||||||||##|||| ||||#||||||||||||##||| ||||#|||||||||||||##||=09 |||/\##|||||||||##/\||=09 |/ \#########/ \=09 |\ \#######/ /=09 ||\____/#######\____/|=09 =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=09 Debug is human, de-fix divine. =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 From steve@in.cqsl.com Sun Jul 22 11:01:02 2001 From: steve@in.cqsl.com (lonetwin@yahoo.com) Date: Sun, 22 Jul 2001 15:31:02 +0530 (IST) Subject: [Tutor] Name of a module within itself In-Reply-To: <01072213494900.22080@mercury.in.cqsl.com> Message-ID: On Sun, 22 Jul 2001, steve wrote: >On Saturday 21 July 2001 23:33, D-man wrote: >> On Sat, Jul 21, 2001 at 04:02:08PM +0530, lonetwin@yahoo.com wrote: >> | Hi there, >> | One quick question, suppose I create a file (say 'foo.py'), that has >> | classes MyFoo, HisFoo, HerFoo, and a function main(). Now, from main I >> | need to refer to the name of the module (foo), such that, I could do >> | something like: >> | >> | def main(): >> | .... >> | getattr([refer to this module], 'HisFoo') >> | .... >> | how do I do that ? >> >> Why do you want to use the getattr function? You could simply say >> >> def main() : >> ... >> HisFoo >> ... >> <..snip..> >Hi there D-man, > Thanx for replying....although I can't really use it like you said. Let me >explain, here's what I'm trying to do: > >class Base: > .... > >class Sub1(Base): > ObjA = 'foo' > .... > >class Sub2(Base): > ObjA = 'bar' > >def main(): > .... > x = funcReturnsSub1orSub2() # x can be either a Sub1 or a Sub2 > > y = getattr([refer to this module], x).ObjA > # y would be an ObjA irrespective of what x is, so y='foo' | y='bar' > > <..snip..> Hi everybody, Yet again, I've proved I go around looking for complex solutions to simple problems donk donk donk !!! well, here's what I am happily doing now: the funcReturnsSub1orSub2() (..refer above..) used to return a string 'Sub1' or 'Sub2'(....how immensely dumb !!!...), when all that I needed was an actual Sub1 or Sub2, so, now instead of: x = funcReturnsSub1orSub2() y = getattr([refer to this module], x).ObjA I do: x = funcReturnsSub1orSub2() y = x.ObjA Sorry D-man, I think I wasted your time on this one :D When will I learn !!!! Peace Steve -- |||||||||||||||||||||| |||||||||#####|||||||| ||||||||#######||||||| ||||||||# O O #||||||| ||||||||#\ ~ /#||||||| ||||||##||\_/||##||||| |||||#||||||||||##|||| ||||#||||||||||||##||| ||||#|||||||||||||##|| |||/\##|||||||||##/\|| |/ \#########/ \ |\ \#######/ / ||\____/#######\____/| ===================================== Debug is human, de-fix divine. ==================================== From Charlie Clark Sun Jul 22 11:00:00 2001 From: Charlie Clark (Charlie Clark) Date: Sun, 22 Jul 2001 12:00:00 +0200 Subject: [Tutor] Re: Tutor digest, Vol 1 #970 - 5 msgs References: Message-ID: <000389abd2ded100_mailit@mail.isis.de> > Hi there, > One quick question, suppose I create a file (say 'foo.py'), that has >classes > MyFoo, HisFoo, HerFoo, and a function main(). Now, from main I need to > refer to the name of the module (foo), such that, I could do something >like: > >def main(): > .... > .... > getattr([refer to this module], 'HisFoo') > .... > .... > > how do I do that ? > >from the prompt I can do: >where the file 'foo.py' contains: >=================================== >#!/usr/bin/python > >class MyFoo: > pass >class HisFoo: > x = 'foo' >class HerFoo: > x = 'bar' I think those classes are not quite correctly constructed but that isn't important at the moment. >==================================== > ....ehe....Am I being clear enough ?...if not please tell me and I'll send > some more code along. If you don't have it already I can highly recommend "Learning Python" by Mark Lutz & David Ascher. On page 141 you'll find all the different but equivalent ways of checking attribute names and it's worth spending some time thinking about names and namespaces as they are very important in Python partly because it's so easy to overwrite them. The next page has an example script which extracts object names from other scripts and includes a test on itself. Let me know if you need the source so I can send it you outside of the list. What I haven't quite understood is why you need to get the name of the module itself: when the module is run it's name is in the global namespace outside of it and thus not directly accessible by the module itself. If you run dir() you'll get a list of all the current namespaces: >>> namespaces = dir() >>> namespaces >>> ['__builtins__', '__doc__', '__name__', 'test'] You could then try our_module = namespaces[3] but I think this not likely to be reliable. You can access all the names in the modules namespace either by using dir(module_name) or module_name.__dict__.keys(). Once you've done that you can ignore the built-ins to list your functions or classes. Does that make any sense? Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From arcege@speakeasy.net Sun Jul 22 12:10:45 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 22 Jul 2001 07:10:45 -0400 (EDT) Subject: [Tutor] subclassing Exceptions In-Reply-To: <1A46D3075774@kserver.org> from "Sheila King" at Jul 21, 2001 08:30:38 PM Message-ID: <200107221110.f6MBAjK13225@dsl092-074-184.bos1.dsl.speakeasy.net> Sheila King wrote > > On Sat, 21 Jul 2001 20:21:34 -0700 (PDT), Danny Yoo > wrote about Re: [Tutor] subclassing > : Python/exceptions.c > : > :file in the Python source code. I don't think that it will help, though, > :in understanding how to subclass exceptions for your own use: it's in C. > > Ah, source code...that doesn't come with the standard Windows install > .exe version, does it? (It does come with the Unix installs, I'm sure.) > I probably would have to go to python.org and grab it. > > Do you think it would be that difficult for me to understand the C code? > (I have taught C++ for the past two years to AP Comp Sci > students...granted, an Intro level College course...not overly > in-depth.) Then you might want to download Python 1.5.2 (binaries or sources). The exceptions were Python classes, not C classes (or a built-in module for that matter). The C code in the exceptions.c file aren't really going to help you subclass the exceptions in Python. It will help you if you ever decide to create C extension classes instead of C extension types. (There is no direct mechanism in the C API to create a Python class, only Python types (string, integer, list, etc.).) For the most part, you usually do not have to override the methods unless you want to handle the data in a very specific manner. The Exception class already handles data in versatile ways. The subclasses you had before usually suffice. If I need/want to make a more complicated structure, then I make a subclass of Exception, then subclasses from that. This is a snippet from my mimecntl module: # Exceptions class MimeError(Exception): """Signals that an error occured in the operation of the MIME document. For example, accessing a multipart doc as a file.""" class MimeTypeError(MimeError, TypeError): """The MIME document is not correct for the method called.""" class NoRecoding(MimeError): """The document was not recoded.""" Raising MimeTypeError could be caught with either "except TypeError" or "except MimeError" clauses. All three could be caught just with MimeError. It all depends on what your application requires. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From wheelege@tsn.cc Sun Jul 22 11:08:43 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Sun, 22 Jul 2001 20:08:43 +1000 Subject: [Tutor] Name of a module within itself References: Message-ID: <004001c1129e$5d262c00$0200a8c0@ACE> > > > Ha ha! Ah, hurling objects with impunity...I wish I wish oh how I wish I didn't have to program in lingo/go-near-director right now... Anywho, you guys get back to talking python, don't let me interrupt (ha ha, interrupt...oh dear, I think I've been assimilated) :) From Sugarpine.Sierra.West@greatbasin.net Sun Jul 22 11:50:41 2001 From: Sugarpine.Sierra.West@greatbasin.net (Sugarpine.Sierra.West@greatbasin.net) Date: Sun, 22 Jul 2001 04:50:41 -0600 Subject: [Tutor] Press Release Message-ID: <200172217441tutor@python.org> For Immediate Release Incline Village, Nevada Contact Corporate Communications www.sugarpinellc.com Sugarpine Sierra West, LLC is proud to announce 4 additional services, Sp= orts Memorabilia, Hair Raisers, Financial Services and Worlds-Best-4 the = worlds largest virtual shopping mall featuring over 2.2 million products!= Save time! Save money! Make money!!! These services and products are now available to everyone. To view these = tremendous opportunities, please visit our website. Sports Memorabilia ma= y be viewed simply by clicking on its front-page banner. Hair Raisers may= be viewed by visiting our web site, www.sugarpinellc.com, and select our= associates=92 link. Our Financial Services is linked and bannered on our= home page. As you all may already know, Sugarpine Sierra West, LLC is at its heart a= n asset hosting company. Please don=92t forget to look at our Asset Gall= ery to see some outstanding business and investment opportunities, as wel= l as collectables and real estate. Sugarpine Sierra West, LLC would like to extend its sincere thanks and ap= preciation to all! Please visit us at our web site at: www.sugarpinellc.com. Corporate Communications: Sugarpine Sierra West, LLC Mr. Charles J. Armstrong II or Ms. Denise Pavlo Phone: 775-832-2552 E-Mail: info@sugarpinellc.com To be removed from our e-mail list, reply to this e-mail with "REMOVE" in= the subject line of your reply. From seedseven@home.nl Sun Jul 22 16:18:47 2001 From: seedseven@home.nl (Ingo) Date: Sun, 22 Jul 2001 17:18:47 +0200 Subject: [Tutor] Press Release Message-ID: Sugarpine.Sierra.West@greatbasin.net, LLC wrote on 2001- 07-22 12:50:41: > >Sugarpine Sierra West, LLC is proud to announce 4 additional services, Sports >Memorabilia, Hair Raisers,..... Hair Raisers? For a moment I thought this to be a Monty Python sketch posted to the wrong list :) Ingo -- Photography: http://members.home.nl/ingoogni/ POV-Ray: http://members.home.nl/seed7/ From tcondit@gblx.net Sun Jul 22 17:04:49 2001 From: tcondit@gblx.net (Tim Condit) Date: Sun, 22 Jul 2001 09:04:49 -0700 Subject: [Tutor] problem with circular list Message-ID: <20010722090449.A23334@gblx.net> Greetings, I found this problem and thought it would be fun, but it's got me stumped. The full text is at http://www.karrels.org/Ed/ACM/weur94p/prob_b.html . To sum it up, there is a king, an executioner, and a variable number of condemned prisoners. Every year at the games, the prisoners are lined up, and starting at the first prisoner, the executioner counts off syllables of a song or nursery rhyme from his youth (enie, menie, miney, moe... ) and executes the prisoner he stops on. The same nursery rhyme is used for the whole "game". The last prisoner is set free. I looked around, and found some info about circular linked lists in C, but they are built using pointers. So I devised my own routine, which doesn't work. :) I figured for P number of prisoners, and S number of syllables, something like this would work: def prisoner(P, S) Plist = range(P) pos = S # current position of syllable count while len(Plist > 1): try: Plist.remove(prisoner referred to by pos) except: dist_to_end = len(Plist) - (index of pos) pos = S - dist_to_end # wrap to front of line Plist.remove(Plist[pos]) print "last man standing: %d" % (Plist[0] + 1) (this is pseudocode, but it's amazing to me how much easier it is to write it this way than to try and describe it in plain English!) There are a few things that this does not address at all, like dealing with S larger than P, but I'll get to that. This is what I have so far: def prisoner(P, S): import operator S = S - 1 Plist = range(P) pos = S while len(Plist) > 1: try: print "(try) removing prisoner %d" % (Plist[pos]) Plist.remove(Plist[pos]) pos = pos + S except IndexError: # increment this before taking len(Plist) from it pos = pos + S # need two things: len(Plist) (easy) and index of current # position of pos with respect to len(Plist) (not so easy) # then pos = (S + len(Plist)) - pos pos = pos - len(Plist) print "(except) pos: %d, Plist: %s" % (pos, Plist) #try: # pos_index = operator.indexOf(Plist, pos) #except TypeError: # print "funky error" print "(except) removing prisoner %d" % (Plist[pos]) Plist.remove(Plist[pos]) #pos = pos + S print "last man standing: %d" % (Plist[0] + 1) The problem I'm having is that pos is a number, but it needs to a location, if that makes sense. The first time through, until pos exceeds len(Plist), it *appears* to work correctly, even though it's not. After that, it bombs out. Thanks in advance, -- Tim Condit Detroit NCC 800-414-5028 Global Crossing The plan was simple. Unfortunately, so was Bullwinkle. From Charlie Clark Sun Jul 22 18:33:50 2001 From: Charlie Clark (Charlie Clark) Date: Sun, 22 Jul 2001 19:33:50 +0200 Subject: [Tutor] help on scope References: Message-ID: <000389b229eee793_mailit@mail.isis.de> Consider this: count = 0 def func(something): print count count += 1 This will print 0 but generate an error about the assignment. I know this is a scope problem but my brain is having trouble with accepting the fact that although I can access a variable I can't reference it. Do I have to use global to get around this? How does global actually work? def func(something): global count print count count += 1 Thanx for any help. Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From ak@silmarill.org Sun Jul 22 19:37:50 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Sun, 22 Jul 2001 14:37:50 -0400 Subject: [Tutor] help on scope In-Reply-To: <"from charlie"@begeistert.org> References: <000389b229eee793_mailit@mail.isis.de> Message-ID: <20010722143750.A689@sill.silmarill.org> On Sun, Jul 22, 2001 at 07:33:50PM +0200, Charlie Clark wrote: > Consider this: > > count = 0 > > def func(something): > print count > count += 1 > > This will print 0 but generate an error about the assignment. I know this is > a scope problem but my brain is having trouble with accepting the fact that > although I can access a variable I can't reference it. Do I have to use > global to get around this? How does global actually work? You can reference it, you just can't change it. Think of it as a safety mechanism, because, well, it is :-). > > def func(something): > global count > print count > count += 1 That's the accepted way of changing it.. Also, you can do this: class my_class: pass inst = my_class() # inst means 'instance', as in, "this classes' instance" inst.count = 0 inst.count += 1 def func(something): print inst.count inst.count += 1 I personally use globals very rarely, 5 or so at most in a medium sized program. Using instance members somehow 'feels' cleaner. > > Thanx for any help. > > Charlie > -- > Charlie Clark > Helmholtzstr. 20 > D?sseldorf > D- 40215 > Tel: +49-211-938-5360 > GSM: +49-178-463-6199 > http://www.begeistert.org > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From sheila@thinkspot.net Sun Jul 22 19:47:47 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 22 Jul 2001 11:47:47 -0700 Subject: [Tutor] subclassing Exceptions In-Reply-To: <200107221110.f6MBAjK13225@dsl092-074-184.bos1.dsl.speakeasy.net> References: <1A46D3075774@kserver.org> <200107221110.f6MBAjK13225@dsl092-074-184.bos1.dsl.speakeasy.net> Message-ID: <1D89E9E854AD@kserver.org> On Sun, 22 Jul 2001 07:10:45 -0400 (EDT), "Michael P. Reilly" wrote about Re: [Tutor] subclassing Exceptions: :Then you might want to download Python 1.5.2 (binaries or sources). :The exceptions were Python classes, not C classes (or a built-in module :for that matter). The C code in the exceptions.c file aren't really going :to help you subclass the exceptions in Python. It will help you if you :ever decide to create C extension classes instead of C extension types. :(There is no direct mechanism in the C API to create a Python class, :only Python types (string, integer, list, etc.).) Thanks for the tip. :For the most part, you usually do not have to override the methods unless :you want to handle the data in a very specific manner. The Exception :class already handles data in versatile ways. The subclasses you had :before usually suffice. Yes, I'm beginning to get a feel for it now. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From adam@netdoor.com Sun Jul 22 19:41:19 2001 From: adam@netdoor.com (Adam Seyfarth) Date: Sun, 22 Jul 2001 13:41:19 -0500 Subject: [Tutor] HOWTO exit Message-ID: <3B5B1E4F.8030901@netdoor.com> Hi, I have just started python, and want to know how to `exit'. I was=20 hoping for the equivilent of the shell's `exit' or C's `exit()' function. Note: when I tried=20 `exit', it didn't work... --=20 Hunter with gun: ``I love animals. That's why I love to kill them.'' -- Monty Python::sketch(``Graham Chapman''(maybe)) /|| Name: `Adam Seyfarth' Nicks: `Vonlia', `Fortuno' ||\ /=C2=AB|| ||=C2=BB= \ \=C2=AB|| ||=C2=BB= / \|| ||/ From ak@silmarill.org Sun Jul 22 19:55:50 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Sun, 22 Jul 2001 14:55:50 -0400 Subject: [Tutor] HOWTO exit In-Reply-To: <"from adam"@netdoor.com> References: <3B5B1E4F.8030901@netdoor.com> Message-ID: <20010722145550.A858@sill.silmarill.org> On Sun, Jul 22, 2001 at 01:41:19PM -0500, Adam Seyfarth wrote: > Hi, > I have just started python, and want to know how to `exit'. I was > hoping for the equivilent > of the shell's `exit' or C's `exit()' function. Note: when I tried > `exit', it didn't work... ctrl-d on unix, ctrl-z on windows (iirc). > > > > -- > Hunter with gun: ``I love animals. That's why I love to kill > them.'' > -- Monty Python::sketch(``Graham Chapman''(maybe)) > > /|| Name: `Adam Seyfarth' Nicks: `Vonlia', `Fortuno' ||\ > /??|| ||??\ > \??|| ||??/ > \|| ||/ > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From DOUGS@oceanic.com Sun Jul 22 20:00:14 2001 From: DOUGS@oceanic.com (Doug Stanfield) Date: Sun, 22 Jul 2001 09:00:14 -1000 Subject: [Tutor] help on scope Message-ID: <8457258D741DD411BD3D0050DA62365907A9A0@huina.oceanic.com> [Charlie Clark ] > Consider this: >=20 > count =3D 0 >=20 > def func(something): > print count > count +=3D 1 >=20 > This will print 0 but generate an error about the assignment.=20 > I know this is=20 > a scope problem but my brain is having trouble with accepting=20 > the fact that=20 > although I can access a variable I can't reference it. The easiest relief for the brain pain is to not cause it in the first = place. ;-) Avoid scope problems by explicitly moving all variables in and out = of functions. For yours it would change it thus: def func(something,count): print count count +=3D 1 return count If you have lots of variables that need to move through the function, organise them with classes. > Do I have to use=20 > global to get around this? How does global actually work? >=20 > def func(something): > global count > print count > count +=3D 1 Well, since you asked. The above should work. Did you try it? In = your first example, when you first referred to count on a RHS (right hand = side) Python searched first in the function namespace for a variable named = count. Not finding it, it moved up to the enclosing scope and found a 'count', whose value was printed. The second reference had 'count' in the LHS. = The rule for Python is that a LHS automatically creates a variable if it = doesn't exist in the current scope. So count was a new variable and when you = did that fancy augmented assignment stuff it knew that would be a problem = (I'm sure more guru like Pythonistas could be more correct in that = explanation, but its enough to get by). The keyword 'global' just changes the rule for any LHS variable = mentioned in the global statement so that Python goes searching through scopes for = it. I've found that using global is a lot more trouble than its worth. = I've never found a case that I used global that didn't become simpler if I = used some other method. The biggest problem is adjacency. When you use a = passed in variable reference, it is right in the function definition, staring = you in the face as it werre. Although using 'global' may seem explicit, it isn't dependable because changes in your program far from the function = may change what that global variable is. Worst is the implied globals, = where you don't ever have a LHS reference just RHS. Then you have no idea = where the variable comes from and if its buried in some complicated = calculating it can lead to very strange errors. I speak from experience. I'm sure that there is a perfectly good reason the the BDFL included 'global' in the language, but for most of us if we avoid it until the = use is obvious and inescapable, I think we'd be better off. HTH, -Doug- =20 > Thanx for any help. >=20 > Charlie > --=20 > Charlie Clark > Helmholtzstr. 20 > D=FCsseldorf > D- 40215 > Tel: +49-211-938-5360 > GSM: +49-178-463-6199 > http://www.begeistert.org >=20 >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor >=20 From dyoo@hkn.eecs.berkeley.edu Sun Jul 22 20:10:43 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 22 Jul 2001 12:10:43 -0700 (PDT) Subject: [Tutor] problem with circular list In-Reply-To: <20010722090449.A23334@gblx.net> Message-ID: On Sun, 22 Jul 2001, Tim Condit wrote: > I found this problem and thought it would be fun, but it's got me > stumped. The full text is at > http://www.karrels.org/Ed/ACM/weur94p/prob_b.html . To sum it up, there > is a king, an executioner, and a variable number of condemned prisoners. Ah, the Josephus problem! > Every year at the games, the prisoners are lined up, and starting at the > first prisoner, the executioner counts off syllables of a song or > nursery rhyme from his youth (enie, menie, miney, moe... ) and executes > the prisoner he stops on. The same nursery rhyme is used for the whole > "game". The last prisoner is set free. I looked around, and found some > info about circular linked lists in C, but they are built using > pointers. So I devised my own routine, which doesn't work. :) > > I figured for P number of prisoners, and S number of syllables, > something like this would work: > > def prisoner(P, S) > Plist = range(P) > pos = S # current position of syllable count > while len(Plist > 1): > try: > Plist.remove(prisoner referred to by pos) > except: > dist_to_end = len(Plist) - (index of pos) > pos = S - dist_to_end # wrap to front of line > Plist.remove(Plist[pos]) The only thing that might be missing is the moving of your pos; otherwise, you'll alwasy be removing the Sth person. Something like: pos = pos + S should be part of your pseudocode. If S = 2, for example, we want to make sure that we'll be eliminating the "even" numbered people first. > There are a few things that this does not address at all, like dealing > with S larger than P, but I'll get to that. This is what I have so far: > > def prisoner(P, S): > import operator > > S = S - 1 > Plist = range(P) > pos = S > while len(Plist) > 1: > try: > print "(try) removing prisoner %d" % (Plist[pos]) > Plist.remove(Plist[pos]) > pos = pos + S > except IndexError: Side note: you can avoid depending on IndexError altogether by using the "modulo" operator '%'. The modulo operator is traditionally used for things that "wrap around": ### >>> for i in range(10): ... print i % 3 ... 0 1 2 0 1 2 0 1 2 0 ### Anyway, let's look again at your code: > while len(Plist) > 1: > try: > print "(try) removing prisoner %d" % (Plist[pos]) > Plist.remove(Plist[pos]) > pos = pos + S > except IndexError: > pos = pos + S > pos = pos - len(Plist) > Plist.remove(Plist[pos]) > print "last man standing: %d" % (Plist[0] + 1) > > > The problem I'm having is that pos is a number, but it needs to a > location, if that makes sense. The first time through, until pos > exceeds len(Plist), it *appears* to work correctly, even though it's > not. After that, it bombs out. You don't want to use remove(): it removes items from a list based on an element's value, not position: ### Help on built-in function remove: remove(...) L.remove(value) -- remove first occurrence of value ### What you'll want to use, instead, is the deleting operator, 'del': ### >>> mylist = range(10) >>> del mylist[0] >>> mylist [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> del mylist[1] >>> mylist [1, 3, 4, 5, 6, 7, 8, 9] ### del would be a more appropriate way to... execute the deletion. Hope this helps! From arcege@speakeasy.net Sun Jul 22 20:17:37 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Sun, 22 Jul 2001 15:17:37 -0400 (EDT) Subject: [Tutor] HOWTO exit In-Reply-To: from "Adam Seyfarth" at Jul 22, 2001 01:41:19 PM Message-ID: <200107221917.f6MJHb314133@dsl092-074-184.bos1.dsl.speakeasy.net> Adam Seyfarth wrote > I have just started python, and want to know how to `exit'. I was > hoping for the equivilent > of the shell's `exit' or C's `exit()' function. Note: when I tried > `exit', it didn't work... >From the interpreter, you can use either Ctrl-D (UNIX) or Ctrl-Z (Win). >From a program, you can use the exit function in the sys module; but preferable, you should raise the SystemExit exception. This is more in keeping with catching or falling through toward the end of the program. For example, def do_something(): ... if done: raise SystemExit(0) ... try: ... do_something() ... except SystemExit: pass # continue (in this example)... but in reduced capacity? try: do_something() finally: close_all_files() # at this point, we'll terminate with a zero exit status The sys.exit() function raises the SystemExit function, so there is no difference. Both of these also work in the interpreter as well. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From alan.gauld@bt.com Sun Jul 22 20:26:08 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 22 Jul 2001 20:26:08 +0100 Subject: [Tutor] Lambda Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8C5@mbtlipnt02.btlabs.bt.co.uk> Try my online tutor at: http://www.crosswinds.net/~agauld Look at the "advanced topics" Functional Programming and GUI programming for info about lambdas Alan G > -----Original Message----- > From: Tobin, Mark [mailto:Mark.Tobin@attcanada.com] > Sent: 20 July 2001 19:17 > To: 'tutor@python.org' > Subject: [Tutor] Lambda > > > Is it fair to say that Lambda is just a shorthand for > defining a function? From alan.gauld@bt.com Sun Jul 22 20:34:44 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 22 Jul 2001 20:34:44 +0100 Subject: [Tutor] Lambda Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8C6@mbtlipnt02.btlabs.bt.co.uk> > Well, recursion is a profound, fundamental concept, lambda is > just a quick notation :) Actually IMHO lambdas are profound fundamental concepts too is just that Pythons half hearted way of implementing them makes them into "just a notation" - nested scopes do allow us to do most dynamic programming things now but disguise/hide the important concept of execvutable code blocks. Smalltalk or Lisp style lambdas can now be faked in Python but by being faked the basic idea of an anonymous function (or anonymous block of code) being treated as an object is in danger of being lost! Without that dynamic programming, functional programming and self modifying code all becomes much harder to comprehend IMHO. Now none of these are concepts for the raw beginner to worry about but one of the great things about Python is that the beginner doesn't usually have to learn a new language to learn a new, advanced concept. But with broken lambdas that was necessary, now its not necessary but may still be desirable... :-( Alan G From alan.gauld@bt.com Sun Jul 22 20:51:37 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 22 Jul 2001 20:51:37 +0100 Subject: [Tutor] Name of a module within itself Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8C7@mbtlipnt02.btlabs.bt.co.uk> > refer to the name of the module (foo), such that, I could > do something like: > > def main(): > .... > getattr([refer to this module], 'HisFoo') > > how do I do that ? getattr(foo,'HisFoo') works for me, what do you get? > >>> import foo > >>> getattr(foo, 'HisFoo') > Yes thats what I get from a script too. Alan g From alan.gauld@bt.com Sun Jul 22 20:57:03 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 22 Jul 2001 20:57:03 +0100 Subject: [Tutor] Name of a module within itself Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8C8@mbtlipnt02.btlabs.bt.co.uk> > Why do you want to use the getattr function? You could simply say > > def main() : > ... > HisFoo > ... Cancel my last post, I just realised you want to do it from within the same module - like using self in an object - sort of... Like D-Man says I can't think why you'd need to - if you know the name you know the object. I guess maybe if you were writing some kind of debugger where the object name was read from a file or the user maybe? In which case maybe you could use eval() or exec() after comparing with dir() to check validity? Alan G From alan.gauld@bt.com Sun Jul 22 21:04:19 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 22 Jul 2001 21:04:19 +0100 Subject: [Tutor] code generators Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8C9@mbtlipnt02.btlabs.bt.co.uk> > I recently learned of the existence of Glade, a GUI > "code generator" For GTk if I recall correctly Theres also Boa Constructor for wxPython(?) BlackAdder(commercial) for pyQt SpecTcl/SpecPy for Tkinter And probably others too. Alan G From jessefw@loop.com Sun Jul 22 21:02:35 2001 From: jessefw@loop.com (Jesse F. W) Date: Sun, 22 Jul 2001 13:02:35 -0700 Subject: [Tutor] problem with circular list In-Reply-To: <20010722090449.A23334@gblx.net> Message-ID: <3B5ACEEB.25412.A92D233@localhost> Dear Tim, and all of you large snake fanciers, I doubt if this will be much help to you, but after reading your message, the problem seemed so interesting to me that I hacked up a version of it myself. It seems to work. It uses linked lists, as I think you have to, though I am not sure why. ;-) If anyone wants to see it, I will post it. Thank you all for your time, Jesse W Tim Condit wrote: > Greetings, > > I found this problem and thought it would be fun, but it's got me > stumped. The full text is at > http://www.karrels.org/Ed/ACM/weur94p/prob_b.html . To sum it up, > there is a king, an executioner, and a variable number of condemned > prisoners. Every year at the games, the prisoners are lined up, and > starting at the first prisoner, the executioner counts off syllables > of a song or nursery rhyme from his youth (enie, menie, miney, moe... > ) and executes the prisoner he stops on. The same nursery rhyme is > used for the whole "game". The last prisoner is set free. I looked > around, and found some info about circular linked lists in C, but they > are built using pointers. So I devised my own routine, which doesn't > work. :) > I figured for P number of prisoners, and S number of syllables, > something like this would work: > > def prisoner(P, S) > Plist = range(P) > pos = S # current position of syllable count > while len(Plist > 1): > try: > Plist.remove(prisoner referred to by pos) > except: > dist_to_end = len(Plist) - (index of pos) > pos = S - dist_to_end # wrap to front of line > Plist.remove(Plist[pos]) > print "last man standing: %d" % (Plist[0] + 1) > > (this is pseudocode, but it's amazing to me how much easier it is to > write it this way than to try and describe it in plain English!) > > > There are a few things that this does not address at all, like dealing > with S larger than P, but I'll get to that. This is what I have so > far: > > def prisoner(P, S): > import operator > > S = S - 1 > Plist = range(P) > pos = S > while len(Plist) > 1: > try: > print "(try) removing prisoner %d" % (Plist[pos]) > Plist.remove(Plist[pos]) > pos = pos + S > except IndexError: > # increment this before taking len(Plist) from it > pos = pos + S > > # need two things: len(Plist) (easy) and index of current > # position of pos with respect to len(Plist) (not so easy) > # then pos = (S + len(Plist)) - pos pos = pos - len(Plist) > print "(except) pos: %d, Plist: %s" % (pos, Plist) > > #try: > # pos_index = operator.indexOf(Plist, pos) > #except TypeError: > # print "funky error" > > print "(except) removing prisoner %d" % (Plist[pos]) > Plist.remove(Plist[pos]) > #pos = pos + S > print "last man standing: %d" % (Plist[0] + 1) > > > The problem I'm having is that pos is a number, but it needs to a > location, if that makes sense. The first time through, until pos > exceeds len(Plist), it *appears* to work correctly, even though it's > not. After that, it bombs out. > > > Thanks in advance, > > -- > Tim Condit Detroit NCC > 800-414-5028 Global Crossing > > The plan was simple. Unfortunately, so was Bullwinkle. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld@bt.com Sun Jul 22 21:09:05 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 22 Jul 2001 21:09:05 +0100 Subject: [Tutor] Name of a module within itself Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8CA@mbtlipnt02.btlabs.bt.co.uk> > Thanx for replying....although I can't really use it like > you said. Let me explain, here's what I'm trying to do: > class Sub1(Base): > ObjA = 'foo' > .... > class Sub2(Base): > ObjA = 'bar' > > def main(): > .... > x = funcReturnsSub1orSub2() # x can be either a Sub1 or a Sub2 > y = getattr([refer to this module], x).ObjA y = x.ObjA should be exactly the same! You have x as areference to an object so just use it, thats what polymorphism is all about! Alan G From bsass@freenet.edmonton.ab.ca Sun Jul 22 21:17:59 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sun, 22 Jul 2001 14:17:59 -0600 (MDT) Subject: [Tutor] problem with circular list In-Reply-To: <20010722090449.A23334@gblx.net> Message-ID: Hi, > I found this problem and thought it would be fun, but it's got me > stumped. The full text is at > http://www.karrels.org/Ed/ACM/weur94p/prob_b.html . To sum it up, there > is a king, an executioner, and a variable number of condemned prisoners. > Every year at the games, the prisoners are lined up, and starting at the > first prisoner, the executioner counts off syllables of a song or > nursery rhyme from his youth (enie, menie, miney, moe... ) and executes > the prisoner he stops on. The same nursery rhyme is used for the whole > "game". The last prisoner is set free. I looked around, and found some > info about circular linked lists in C, but they are built using > pointers. So I devised my own routine, which doesn't work. :) > > I figured for P number of prisoners, and S number of syllables, > something like this would work: The way I see it... you have a list of prisoners, and an index which may point past the end of the list. So, you may need to reduce the index by some multiple of the length of the list. e.g., something along the lines of... while key >= len(list): key = key - len(list) Using this approach I came up with the following for the circular list part of the problem... ---8<--- class circList: def __init__(self, initial=None): if initial == None: self.data = [] else: self.data = initial def __getitem__(self, key): length = len(self.data) if length > 1: key = key % length return self.data[key] elif length == 1: return self.data[0] else: return None # or raise an exception if __name__ == '__main__': c = circList([0,1,2,3]) for i in range(10): print c[i], --->8--- Output: 0 1 2 3 0 1 2 3 0 1 [Getting it to work with negative indicies and slices, or having it behave more like a regular list would be interesting (but not really relevent to the problem)... check out the UserList module, Section 2 of the Library Reference and Section 3 of the Language Reference for more info.] To make circList a little nicer you should implement a "pop" and the "__len__" magic method, so you can do... ---8<--- rhyme = ["enie", "menie", "miney", "moe", "out", "you", "go"] p = circList(["Bob", "Carol", "Ted", "Alice"]) number = len(p) length = len(rhyme) while number != 1: p.pop(len) number = number - 1 print p[0], "gets a pardon." --->8--- Output: Alice gets a pardon. - Bruce From bsass@freenet.edmonton.ab.ca Sun Jul 22 21:35:05 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Sun, 22 Jul 2001 14:35:05 -0600 (MDT) Subject: [Tutor] problem with circular list In-Reply-To: Message-ID: On Sun, 22 Jul 2001, Bruce Sass wrote: mmm... > length = len(rhyme) > while number != 1: > p.pop(len) p.pop(length) > number = number - 1 > print p[0], "gets a pardon." From alan.gauld@bt.com Sun Jul 22 21:50:49 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 22 Jul 2001 21:50:49 +0100 Subject: [Tutor] HOWTO exit Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8CB@mbtlipnt02.btlabs.bt.co.uk> > I have just started python, and want to know how to > `exit'. There ae several ways but the most general, but least used is: raise SystemExit usually you see: import sys ... sys.exit() You can find explanations of this in my online beginners tutor: http://www.crosswinds.net/~agauld/ Alan G. From dsh8290@rit.edu Sun Jul 22 23:17:06 2001 From: dsh8290@rit.edu (D-Man) Date: Sun, 22 Jul 2001 18:17:06 -0400 Subject: [Tutor] Name of a module within itself In-Reply-To: ; from steve@in.cqsl.com on Sun, Jul 22, 2001 at 03:31:02PM +0530 References: <01072213494900.22080@mercury.in.cqsl.com> Message-ID: <20010722181706.A23779@harmony.cs.rit.edu> On Sun, Jul 22, 2001 at 03:31:02PM +0530, lonetwin@yahoo.com wrote: | On Sun, 22 Jul 2001, steve wrote: | Yet again, I've proved I go around looking for complex solutions to simple | problems donk donk donk !!! well, here's what I am | happily doing now: | the funcReturnsSub1orSub2() (..refer above..) used to return a string 'Sub1' | or 'Sub2'(....how immensely dumb !!!...), when all that I needed | was an actual Sub1 or Sub2, so, now instead of: | | x = funcReturnsSub1orSub2() | y = getattr([refer to this module], x).ObjA | | I do: | | x = funcReturnsSub1orSub2() | y = x.ObjA Yep . I was about to explain that from the prompt you had a string object, not the foo object you needed/intended to have, but you have now demonstrated that yourself. | Yes, in python classes are actually objects and your function is hurling all sorts of them at you :-). Just be sure to catch them in a variable or you won't be able to use it later. | Sorry D-man, I think I wasted your time on this one :D Nope, now that you have learned it must not have been a waste of time :-). -D From dsh8290@rit.edu Sun Jul 22 23:20:17 2001 From: dsh8290@rit.edu (D-Man) Date: Sun, 22 Jul 2001 18:20:17 -0400 Subject: [Tutor] HOWTO exit In-Reply-To: <3B5B1E4F.8030901@netdoor.com>; from adam@netdoor.com on Sun, Jul 22, 2001 at 01:41:19PM -0500 References: <3B5B1E4F.8030901@netdoor.com> Message-ID: <20010722182017.B23779@harmony.cs.rit.edu> On Sun, Jul 22, 2001 at 01:41:19PM -0500, Adam Seyfarth wrote: | Hi, | I have just started python, and want to know how to `exit'. I was | hoping for the equivilent | of the shell's `exit' or C's `exit()' function. Note: when I tried | `exit', it didn't work... In python it is in the 'sys' module. import sys sys.exit( [error code is optional] ) This raises the exception SystemExit (as others have mentioned). This allows calling code to perform the necessary cleanup (in a 'finally' block). There is also the _exit() function (in the sys module) that will terminate immediately, without performing any sort of cleanup. This is not really recommended to use unless you _really_ need to. That's why the name starts with an underscore (it is psuedo private). -D From jstanley@start.com.au Mon Jul 23 00:57:58 2001 From: jstanley@start.com.au (Jordan Stanley) Date: Mon, 23 Jul 2001 0:57:58 +0100 Subject: [Tutor] Advertising Message-ID: What the hell is this crap about sports memorabilia. what does it have to do with Python, is this are there any rules? if there are i'm sure this is against them Jordan __________________________________________________________________ Get your free Australian email account at http://www.start.com.au From dyoo@hkn.eecs.berkeley.edu Mon Jul 23 02:12:52 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 22 Jul 2001 18:12:52 -0700 (PDT) Subject: [Tutor] Advertising In-Reply-To: Message-ID: On Mon, 23 Jul 2001, Jordan Stanley wrote: > What the hell is this crap about sports memorabilia. what does it have > to do with Python, is this are there any rules? > > if there are i'm sure this is against them Wesley and Deirdre, the tutor list admins (and the Mailman mailing-list software) have been quietly intercepting spam for us --- for the most part, it doesn't reach the list. (Thank you guys!) Still, there's been widespread spamming of Python lists for quite a while now, and spam does trickle in occasionally. It is a bit sad that someone would spam an educational forum. Mailman is written in Python, and for someone motivated enough, perhaps someone could look at Mailman: http://www.list.org/ and see if any improvements could be made toward the spam filter; it might make a good summer project to see how the filter works. It would certainly help lots of people. From dyoo@hkn.eecs.berkeley.edu Mon Jul 23 02:18:43 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 22 Jul 2001 18:18:43 -0700 (PDT) Subject: [Tutor] Re: tabs vs spaces In-Reply-To: <0003897581fe4281_mailit@mail.isis.de> Message-ID: On Thu, 19 Jul 2001, Charlie Clark wrote: > >BTW, are you using tabs to indent your code? Don't! Use spaces instead. > I noticed there was a heated discussion on the newsgroup about this a > while back and I'm sure it crops up often. And the consensus seemed to > be that spaces are the way to do things. But tabs are allowed. Maybe > there is a page somewhere that presents the arguments? That would be > useful to know. Guido's "Python Style Guide" touches on the debate: http://python.sourceforge.net/peps/pep-0008.html He says to use either tabs or spaces, but make sure to stick to only one of those choices. Otherwise, dire catastrophe is bound to strike: tabs count for 8 spaces in Python, but some systems print out tabs as four. It's a big mess. *grin* If you use a text editor that's aware of Python, you usually don't need to worry about the distinction. In Emacs, PythonWin, and IDLE, pressing TAB will cause the editor to indent by four spaces, which is very nice. What text editor do you use to edit Python code? From dyoo@hkn.eecs.berkeley.edu Mon Jul 23 02:32:26 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 22 Jul 2001 18:32:26 -0700 (PDT) Subject: [Tutor] Re: Your message to Tutor awaits moderator approval In-Reply-To: <3B58660A.1806.128C776@localhost> Message-ID: On Fri, 20 Jul 2001, Jesse F. W wrote: > Hello all, > tutor-admin@python.org wrote: > > Your mail to 'Tutor' with the subject > > > > Re: [Tutor] Another problem with urllib > > > > Is being held until the list moderator can review it for approval. > > > > The reason it is being held: > > > > Message may contain administrivia > What is administrivia? Cute term, by the way. Hmmm... I'm guessing "administration stuff". The mailing list manager checks up on message sent on the tutor list, and if it sees certain phrases like "subscribe" or "unsubscribe me", it will send it off to the list moderator to prevent the whole list from seeing the request. (Hopefully, this message won't get intercepted either.) There's a great resource called WordNet that's better at this linguistic/philology stuff here: http://www.cogsci.princeton.edu/~wn/ According to WordNet, "administrivia" is... um... not a word. That didn't work out the way I expected. Hmmm... well, WordNet is still a fun program to play with, and there's even a nice Python module that works with it. http://www.cs.brandeis.edu/~steele/sources/wordnet-python.html *grin* From lumbricus@gmx.net Mon Jul 23 09:55:16 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon, 23 Jul 2001 10:55:16 +0200 Subject: [Tutor] Advertising In-Reply-To: ; from jstanley@start.com.au on Mon, Jul 23, 2001 at 12:57:58AM +0100 References: Message-ID: <20010723105516.A18603@Laplace.localdomain> On Mon, Jul 23, 2001 at 12:57:58AM +0100, Jordan Stanley wrote: > What the hell is this crap about sports memorabilia. > what does it have to do with Python, is this are there any rules? > You are talking about spam? subscribe to a unmoderated list ( in USENET ) and enjoy. And yes - spam is against the rules. You want to have a filterfile. > if there are i'm sure this is against them > If enough people complain to the senders provider ("mailto:abuse@") chances are he gets some trouble :-) > Jordan > > HTH J"o! -- "His great aim was to escape from civilization, and, as soon as he had money, he went to Southern California." From Charlie Clark Mon Jul 23 10:21:39 2001 From: Charlie Clark (Charlie Clark) Date: Mon, 23 Jul 2001 11:21:39 +0200 Subject: [Tutor] Re: tabs vs spaces References: Message-ID: <000389bf678d62db_mailit@mail.isis.de> >Guido's "Python Style Guide" touches on the debate: > > http://python.sourceforge.net/peps/pep-0008.html Thanx for the link. Quite a useful document. A prominent (top level) link to it in the Python documentation might be a good idea. >He says to use either tabs or spaces, but make sure to stick to only one >of those choices. Otherwise, dire catastrophe is bound to strike: tabs >count for 8 spaces in Python, but some systems print out tabs as >four. It's a big mess. *grin* It is. Which is why I found the original post somewhat offensive. >If you use a text editor that's aware of Python, you usually don't need to >worry about the distinction. In Emacs, PythonWin, and IDLE, pressing TAB >will cause the editor to indent by four spaces, which is very nice. What >text editor do you use to edit Python code? I use Pe for the BeOS and generally use tabs - most of my programming experience has been with HTML pages with windows editors where tabs are more convenient than spaces. Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From Charlie Clark Mon Jul 23 11:11:54 2001 From: Charlie Clark (Charlie Clark) Date: Mon, 23 Jul 2001 12:11:54 +0200 Subject: [Tutor] help on scope References: <8457258D741DD411BD3D0050DA62365907A9A0@huina.oceanic.com> Message-ID: <000389c01b4d9752_mailit@mail.isis.de> >The easiest relief for the brain pain is to not cause it in the first place. >;-) Avoid scope problems by explicitly moving all variables in and out of >functions. For yours it would change it thus: > >def func(something,count): > print count > count += 1 > return count that's a good tip even it looks a little clumsy. >If you have lots of variables that need to move through the function, >organise them with classes. I'm writing a little program that makes anagrams. Something I failed to do miserably in basic when I first dabbled in programming 20 years ago. I'm using count to help me check whether the algorithm is working properly. As I use a recursive function I need to initialise my counter outside the function but increment with each new word. Passing the counter as an argument removes problems of scope but feels wrong. I agree, however, that it is better than using global. Am I missing something? Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From Mark.Tobin@attcanada.com Mon Jul 23 13:33:47 2001 From: Mark.Tobin@attcanada.com (Tobin, Mark) Date: Mon, 23 Jul 2001 06:33:47 -0600 Subject: [Tutor] Lambda Message-ID: <3D7C088D6CCFD31190A5009027D30E9103391067@torex004.attcanada.ca> Thanks Alan, I went through your tutor when I first started Python, but definitely wasn't ready for anything entitled "advanced topics", and wasn't sure I wanted anything to do with "gooey" programming ;-). I guess it's time I went back to squeeze every drop out of it I can... Thanks again, Mark > -----Original Message----- > From: alan.gauld@bt.com [mailto:alan.gauld@bt.com] > Sent: Sunday, July 22, 2001 3:26 PM > To: Mark.Tobin@attcanada.com; tutor@python.org > Subject: RE: [Tutor] Lambda > > > Try my online tutor at: > > http://www.crosswinds.net/~agauld > > Look at the "advanced topics" Functional Programming > and GUI programming for info about lambdas > > Alan G > > > -----Original Message----- > > From: Tobin, Mark [mailto:Mark.Tobin@attcanada.com] > > Sent: 20 July 2001 19:17 > > To: 'tutor@python.org' > > Subject: [Tutor] Lambda > > > > > > Is it fair to say that Lambda is just a shorthand for > > defining a function? > From dsh8290@rit.edu Mon Jul 23 15:49:23 2001 From: dsh8290@rit.edu (dman) Date: Mon, 23 Jul 2001 10:49:23 -0400 Subject: [Tutor] Re: tabs vs spaces In-Reply-To: <000389bf678d62db_mailit@mail.isis.de>; from charlie@begeistert.org on Mon, Jul 23, 2001 at 11:21:39AM +0200 References: <000389bf678d62db_mailit@mail.isis.de> Message-ID: <20010723104923.B24263@harmony.cs.rit.edu> On Mon, Jul 23, 2001 at 11:21:39AM +0200, Charlie Clark wrote: | >If you use a text editor that's aware of Python, you usually don't need to | >worry about the distinction. In Emacs, PythonWin, and IDLE, pressing TAB | >will cause the editor to indent by four spaces, which is very nice. What | >text editor do you use to edit Python code? | | I use Pe for the BeOS and generally use tabs - most of my programming | experience has been with HTML pages with windows editors where tabs are more | convenient than spaces. Not to start an editor war, but FYI (g)vim has options so that you can have the indent level you want and spaces are inserted instead of tabs. You get all the editing convenience of tabs but spaces are stored in the file instead. I'm sure emacs and others have similar capabilities. -D From tcondit@gblx.net Mon Jul 23 15:59:46 2001 From: tcondit@gblx.net (Tim Condit) Date: Mon, 23 Jul 2001 07:59:46 -0700 Subject: [Tutor] problem with circular list In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Sun, Jul 22, 2001 at 12:10:43PM -0700 References: <20010722090449.A23334@gblx.net> Message-ID: <20010723075945.A21673@gblx.net> On Sun, Jul 22, 2001 at 12:10:43PM -0700, Danny Yoo wrote: > On Sun, 22 Jul 2001, Tim Condit wrote: > > > I found this problem and thought it would be fun, but it's got me > > stumped. The full text is at > > http://www.karrels.org/Ed/ACM/weur94p/prob_b.html . To sum it up, there > > is a king, an executioner, and a variable number of condemned prisoners. > > Ah, the Josephus problem! > [snip] > Side note: you can avoid depending on IndexError altogether by using the > "modulo" operator '%'. The modulo operator is traditionally used for > things that "wrap around": > > ### > >>> for i in range(10): > ... print i % 3 > ... > 0 > 1 > 2 > 0 > 1 > 2 > 0 > 1 > 2 > 0 > ### > I used this originally, then dropped it in favor of subtraction.. seemed like a good idea at the time. [snip] > > You don't want to use remove(): it removes items from a list based on > an element's value, not position: > > > ### > Help on built-in function remove: > > remove(...) > L.remove(value) -- remove first occurrence of value > ### > > > What you'll want to use, instead, is the deleting operator, 'del': > > ### > >>> mylist = range(10) > >>> del mylist[0] > >>> mylist > [1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> del mylist[1] > >>> mylist > [1, 3, 4, 5, 6, 7, 8, 9] > ### > > del would be a more appropriate way to... execute the deletion. > Ah! That's exactly what I wanted, and it's right under my nose. Time for a refresher of the basics. Thanks for the help, Tim --- end quoted text --- -- Tim Condit Detroit NCC 800-414-5028 Global Crossing The plan was simple. Unfortunately, so was Bullwinkle. From tcondit@gblx.net Mon Jul 23 16:03:02 2001 From: tcondit@gblx.net (Tim Condit) Date: Mon, 23 Jul 2001 08:03:02 -0700 Subject: [Tutor] problem with circular list In-Reply-To: ; from bsass@freenet.edmonton.ab.ca on Sun, Jul 22, 2001 at 02:17:59PM -0600 References: <20010722090449.A23334@gblx.net> Message-ID: <20010723080302.B21673@gblx.net> On Sun, Jul 22, 2001 at 02:17:59PM -0600, Bruce Sass wrote: > Hi, > > > I found this problem and thought it would be fun, but it's got me > > stumped. The full text is at > > http://www.karrels.org/Ed/ACM/weur94p/prob_b.html . To sum it up, there > > is a king, an executioner, and a variable number of condemned prisoners. > > Every year at the games, the prisoners are lined up, and starting at the > > first prisoner, the executioner counts off syllables of a song or > > nursery rhyme from his youth (enie, menie, miney, moe... ) and executes > > the prisoner he stops on. The same nursery rhyme is used for the whole > > "game". The last prisoner is set free. I looked around, and found some > > info about circular linked lists in C, but they are built using > > pointers. So I devised my own routine, which doesn't work. :) > > > > I figured for P number of prisoners, and S number of syllables, > > something like this would work: > > The way I see it... > you have a list of prisoners, > and an index which may point past the end of the list. > > So, you may need to reduce the index by some multiple of the > length of the list. e.g., something along the lines of... > > while key >= len(list): > key = key - len(list) > > Using this approach I came up with the following for the circular > list part of the problem... > > ---8<--- > class circList: > def __init__(self, initial=None): > if initial == None: > self.data = [] > else: > self.data = initial > > def __getitem__(self, key): > length = len(self.data) > if length > 1: > key = key % length > return self.data[key] > elif length == 1: > return self.data[0] > else: > return None # or raise an exception > > if __name__ == '__main__': > c = circList([0,1,2,3]) > for i in range(10): > print c[i], > --->8--- > > Output: > 0 1 2 3 0 1 2 3 0 1 > > [Getting it to work with negative indicies and slices, or having it > behave more like a regular list would be interesting (but not really > relevent to the problem)... check out the UserList module, Section > 2 of the Library Reference and Section 3 of the Language Reference > for more info.] I thought about using UserList, maybe after getting the simple case working.. I swear, if I don't write little programs regularly, I forget the basics.. it's pretty frustrating. > > To make circList a little nicer you should implement a "pop" and > the "__len__" magic method, so you can do... > > ---8<--- > rhyme = ["enie", "menie", "miney", "moe", "out", "you", "go"] > p = circList(["Bob", "Carol", "Ted", "Alice"]) > number = len(p) > length = len(rhyme) > while number != 1: > p.pop(len) > number = number - 1 > print p[0], "gets a pardon." > --->8--- > > Output: > Alice gets a pardon. > > > - Bruce > --- end quoted text --- Thanks for the ideas, -- Tim Condit Detroit NCC 800-414-5028 Global Crossing The plan was simple. Unfortunately, so was Bullwinkle. From rick@niof.net Mon Jul 23 16:04:29 2001 From: rick@niof.net (Rick Pasotto) Date: Mon, 23 Jul 2001 11:04:29 -0400 Subject: [Tutor] bug in uu library module? Message-ID: <20010723110428.B13983@tc.niof.net> I'm working on a program that needs to uudecode some files. The first line of a uuencoded file is 'begin [mode] [filename]'. The library module uses string.split to parse this line. If the filename has spaces in it the module does not recognize the line since it has more than three fields. What is the best way to deal with this? Should I cut-n-paste the library code into my program and then change that? Would it be better to re-write the file changing the 'begin' line by substituting underscores for spaces in the output file name? And finally, is this a bug? Spaces in filenames create all sorts of havoc but it looks like they're here to stay and we need to deal with them. -- Certain nations seem particularly liable to fall prey to governmental plunder. They are those in which men, lacking faith in their own dignity and capability, would feel themselves lost if they were not governed and administered every step of the way. -- Frйdйric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From Charlie Clark Mon Jul 23 16:07:44 2001 From: Charlie Clark (Charlie Clark) Date: Mon, 23 Jul 2001 17:07:44 +0200 Subject: [Tutor] Re: Tutor digest, Vol 1 #974 - 16 msgs References: Message-ID: <000389c43d3c7a22_mailit@mail.isis.de> >Not to start an editor war, but FYI (g)vim has options so that you can >have the indent level you want and spaces are inserted instead of >tabs. You get all the editing convenience of tabs but spaces are >stored in the file instead. I'm sure emacs and others have similar >capabilities. I know, I know but I just don't have the heritage. I used to have to write e- mails in vi (without any handbooks or tuition) once and hated it. vi does exist for the BeOS but I need a GUI and the X-Windows implementation is very poor. Pe is a bit more like emacs so I can probably switch it. Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From rob@jam.rr.com Mon Jul 23 16:22:33 2001 From: rob@jam.rr.com (Rob Andrews) Date: Mon, 23 Jul 2001 10:22:33 -0500 Subject: [Tutor] Re: Tutor digest, Vol 1 #974 - 16 msgs In-Reply-To: <000389c43d3c7a22_mailit@mail.isis.de> Message-ID: If a vi clone were written in Python, would it be called *pi*? ;->, Rob "I do remain confident in Linda. She'll make a fine labor secretary. From what I've read in the press accounts, she's perfectly qualified." -- Geor= ge W. Bush Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf O= f # Charlie Clark # Sent: Monday, July 23, 2001 10:08 AM # To: tutor@python.org # Subject: [Tutor] Re: Tutor digest, Vol 1 #974 - 16 msgs # # # >Not to start an editor war, but FYI (g)vim has options so that you can # >have the indent level you want and spaces are inserted instead of # >tabs. You get all the editing convenience of tabs but spaces are # >stored in the file instead. I'm sure emacs and others have similar # >capabilities. # # I know, I know but I just don't have the heritage. I used to have # to write e- # mails in vi (without any handbooks or tuition) once and hated it. vi do= es # exist for the BeOS but I need a GUI and the X-Windows # implementation is very # poor. Pe is a bit more like emacs so I can probably switch it. # # Charlie # -- # Charlie Clark # Helmholtzstr. 20 # D=FCsseldorf # D- 40215 # Tel: +49-211-938-5360 # GSM: +49-178-463-6199 # http://www.begeistert.org # # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From fleet@teachout.org Mon Jul 23 16:36:20 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Mon, 23 Jul 2001 11:36:20 -0400 (EDT) Subject: [Tutor] HOWTO exit In-Reply-To: Message-ID: I think I'm a little confused about importing modules. If I were to do the below, unless I needed other 'sys' functions, I'd be tempted to use "from sys import exit" and "exit()." I'm assuming the entire module uses more memory than just the one function and I would think one should conserve memory. (Even if one doesn't have to - I'm from the "waste not, want not" school.) Is there a rule of thumb regarding this issue? - fleet - On Mon, 23 Jul 2001 tutor-request@python.org wrote: > Message: 4 > From: alan.gauld@bt.com > To: adam@netdoor.com, tutor@python.org > Subject: RE: [Tutor] HOWTO exit > Date: Sun, 22 Jul 2001 21:50:49 +0100 > > > I have just started python, and want to know how to > > `exit'. > > There ae several ways but the most general, but least used is: > > raise SystemExit > > usually you see: > > import sys > ... > sys.exit() > > > You can find explanations of this in my online beginners tutor: > > http://www.crosswinds.net/~agauld/ > > Alan G. > > From arcege@speakeasy.net Mon Jul 23 16:43:44 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Mon, 23 Jul 2001 11:43:44 -0400 (EDT) Subject: [Tutor] bug in uu library module? In-Reply-To: <20010723110428.B13983@tc.niof.net> from "Rick Pasotto" at Jul 23, 2001 11:04:29 AM Message-ID: <200107231543.f6NFhip01245@dsl092-074-184.bos1.dsl.speakeasy.net> Rick Pasotto wrote > I'm working on a program that needs to uudecode some files. The first > line of a uuencoded file is 'begin [mode] [filename]'. The library > module uses string.split to parse this line. If the filename has spaces > in it the module does not recognize the line since it has more than > three fields. > > What is the best way to deal with this? Flog the person to send you silly filenames with spaces? ;) > Should I cut-n-paste the library code into my program and then change > that? Would it be better to re-write the file changing the 'begin' line > by substituting underscores for spaces in the output file name? I would suggest that latter; unless you wish to upgrade. > And finally, is this a bug? Spaces in filenames create all sorts of > havoc but it looks like they're here to stay and we need to deal with > them. It is a bug only in that uudecode(1) can handle filenames with spaces but uu.py cannot. (Not that it is a bug that spaces are allowed. ;)) It is fixed in Python 2.1, but not in Python 1.5.2 or 2.0. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From ak@silmarill.org Mon Jul 23 16:47:47 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Mon, 23 Jul 2001 11:47:47 -0400 Subject: [Tutor] HOWTO exit In-Reply-To: <"from fleet"@teachout.org> References: Message-ID: <20010723114747.A885@sill.silmarill.org> On Mon, Jul 23, 2001 at 11:36:20AM -0400, fleet@teachout.org wrote: > > I think I'm a little confused about importing modules. If I were to do > the below, unless I needed other 'sys' functions, I'd be tempted to use > "from sys import exit" and "exit()." > > I'm assuming the entire module uses more memory than just the one function > and I would think one should conserve memory. (Even if one doesn't have > to - I'm from the "waste not, want not" school.) > > Is there a rule of thumb regarding this issue? > > - fleet - Nah, it's only using up the memory if you use that function.. I think.. At any rate, even if they do waste more memory, it's not a big deal since everybody seems to do it. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From Charlie Clark Mon Jul 23 17:19:54 2001 From: Charlie Clark (Charlie Clark) Date: Mon, 23 Jul 2001 18:19:54 +0200 Subject: [Tutor] Rule of thumb for imports - Namespaces are important References: Message-ID: <000389c53f58061b_mailit@mail.isis.de> >I think I'm a little confused about importing modules. If I were to do >the below, unless I needed other 'sys' functions, I'd be tempted to use >"from sys import exit" and "exit()." Of course you can do that but you might end up writing another function called exit. Using import and then qualifying the function you want from the module you imported packages it up and makes it easier to work out what the function is doing. If nothing else it helps you when look at the code you wrote a while back but actually you must do this if you want to be able to reload your module. exit() -> go and look at the top of the module to see where exit is defined in the program you're looking at or whether it has been copied into it by a "from" sys.exit() alles klar! We know where this function is from >I'm assuming the entire module uses more memory than just the one function >and I would think one should conserve memory. (Even if one doesn't have >to - I'm from the "waste not, want not" school.) I don't know so much about that. Python manages memory for you and unless the module has a very large namespace I don't think this would be a problem and having clearly readable code is very important and worth the overhead. >Is there a rule of thumb regarding this issue? That's my own rule of thumb based on the code I've written from others. I do use from x import * for some very special (usually BeOS specific modules) when I'm too lazy to write the whole namespace out and I know I'm unlikely to write functions with similar names ie. from BeOS.fsattr import * gives me read_attrs, write_attr, remove_attr in the local namespace which is fine for my own stuff. If I were packaging something up for distribution, I'd probably take the trouble of fully qualifying the functions. Charlie PS: sorry for the BeOS-bias but extensible file system attributes which can be manipulated by Python are just too cool! -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From lumbricus@gmx.net Mon Jul 23 17:14:04 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon, 23 Jul 2001 18:14:04 +0200 Subject: [Tutor] Re: Tutor digest, Vol 1 #974 - 16 msgs In-Reply-To: <000389c43d3c7a22_mailit@mail.isis.de>; from charlie@begeistert.org on Mon, Jul 23, 2001 at 05:07:44PM +0200 References: <000389c43d3c7a22_mailit@mail.isis.de> Message-ID: <20010723181404.A19228@Laplace.localdomain> On Mon, Jul 23, 2001 at 05:07:44PM +0200, Charlie Clark wrote: > >Not to start an editor war, but FYI (g)vim has options so that you can > >have the indent level you want and spaces are inserted instead of > >tabs. You get all the editing convenience of tabs but spaces are > >stored in the file instead. I'm sure emacs and others have similar > >capabilities. > > I know, I know but I just don't have the heritage. I used to have to write e- > mails in vi (without any handbooks or tuition) once and hated it. vi does > exist for the BeOS but I need a GUI and the X-Windows implementation is very > poor. Pe is a bit more like emacs so I can probably switch it. > vi != vim "http://www-106.ibm.com/developerworks/education/r-vi.html" might help :-) > Charlie > -- > Charlie Clark > Helmholtzstr. 20 > Dьsseldorf > D- 40215 > Tel: +49-211-938-5360 > GSM: +49-178-463-6199 > http://www.begeistert.org > > HTH J"o! -- Nothing is so firmly believed as that which we least know. -- Michel de Montaigne From alan.gauld@bt.com Mon Jul 23 17:47:11 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 23 Jul 2001 17:47:11 +0100 Subject: [Tutor] HOWTO exit Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8CD@mbtlipnt02.btlabs.bt.co.uk> > I think I'm a little confused about importing modules. Probably :-) > tempted to use > "from sys import exit" and "exit()." > > I'm assuming the entire module uses more memory than just the > one function In fact when you import the "entire module" you are just making the name (sys in this case) available. Its roughly equivalent to adding one element to a dictionary. If you do "from ... exit" you import exit instead of sys but again its only one entry in the dictionary. The difference comes when you want to use something else in sys (say argv) then you have the choce of importing 2 names(exit and argv) or one name (sys) and using it to reference the others... Because of the dangers of overwriting a local name with an imported one most pythomnistas seem to prefer to avoid "from..." except for well defined cases such as tkinter. Alan G From dsh8290@rit.edu Mon Jul 23 18:48:13 2001 From: dsh8290@rit.edu (dman) Date: Mon, 23 Jul 2001 13:48:13 -0400 Subject: [Tutor] HOWTO exit In-Reply-To: ; from fleet@teachout.org on Mon, Jul 23, 2001 at 11:36:20AM -0400 References: Message-ID: <20010723134813.A24389@harmony.cs.rit.edu> On Mon, Jul 23, 2001 at 11:36:20AM -0400, fleet@teachout.org wrote: | | I think I'm a little confused about importing modules. If I were to do | the below, unless I needed other 'sys' functions, I'd be tempted to use | "from sys import exit" and "exit()." | | I'm assuming the entire module uses more memory than just the one function | and I would think one should conserve memory. (Even if one doesn't have | to - I'm from the "waste not, want not" school.) Actually, no, the same amount of memory is used regardless. You can't "unimport" modules. The module name might not exist in the current module's namespace, but the module still exists in memory. I don't think C can unload a shared library from memory (and some modules are implemented in C) so I think that might be one reason for not unloading modules. The other reason is the next time you import the module it takes very little time -- the module is already in memory so the only thing that is needed is an adding the reference in the current namespace. It is better to just import the module and use its members qualified with the module name for (future) readability and it takes no additional memory than the alternatives. | Is there a rule of thumb regarding this issue? Yeah, don't use from-import unless you _really_ _really_ need it. Just think of a module as a namespace and importing it is nothing more than making that namespace accessible. :-) -D From rortega@cfl.rr.com Mon Jul 23 15:27:28 2001 From: rortega@cfl.rr.com (rortega@cfl.rr.com) Date: Mon, 23 Jul 2001 14:27:28 US/Eastern Subject: [Tutor] ftplib Message-ID: <200107231827.f6NIRRD22519@smtp-server1.tampabay.rr.com> Hi I recently wrote my first python script. What it does is take a file and uploads it to an FTP server using ftplib. It works fine as long as the computer it runs on is conected to the internet directly but I would like to know if I can get this to work through a proxie server. Thanks From DOUGS@oceanic.com Mon Jul 23 19:29:05 2001 From: DOUGS@oceanic.com (Doug Stanfield) Date: Mon, 23 Jul 2001 08:29:05 -1000 Subject: [Tutor] Use of global (was: help on scope) Message-ID: <8457258D741DD411BD3D0050DA62365907A9A3@huina.oceanic.com> [Charlie Clark responded:] > >The easiest relief for the brain pain is to not cause it in > the first place. > >;-) Avoid scope problems by explicitly moving all variables > in and out of > >functions. For yours it would change it thus: > > > >def func(something,count): > > print count > > count += 1 > > return count > > that's a good tip even it looks a little clumsy. > > >If you have lots of variables that need to move through the function, > >organise them with classes. > > I'm writing a little program that makes anagrams. Something I > failed to do > miserably in basic when I first dabbled in programming 20 > years ago. I'm > using count to help me check whether the algorithm is working > properly. As I > use a recursive function I need to initialise my counter > outside the function > but increment with each new word. Passing the counter as an > argument removes > problems of scope but feels wrong. I agree, however, that it > is better than > using global. Am I missing something? This is probably one of those "feelings" left over from your 20 year old Basic experiences. Its sometimes called a paradigm shift. Explicitly passing of variables into functions makes it easier to understand what you're doing. As I said before, everytime I've used 'global' I've regretted it later when I started to do more with my functions than I originally thought. It may not be apparent to you with this program in its current form. It may be that starting to develop a habit now will pay off later. I know that now it just 'feels' right to me to _not_ use 'global if there is another way. -Doug- From qhe@ydyn.com Mon Jul 23 20:03:51 2001 From: qhe@ydyn.com (Peter He) Date: Mon, 23 Jul 2001 14:03:51 -0500 Subject: [Tutor] pass a function name as an argument Message-ID: <5.1.0.14.0.20010723135016.00ae8e38@mail.ydyn.com.criticalpath.net> Hi there, How can I pass a function name as an argument to another function? Something like this: class a: ... # call func_A to create a button with title -- text and function -- func_B func_A(text, func_B) ... func_A(self, text, func) ... buttonbox = Pmw.buttonbox(...) buttonbox.pack(...) buttonbox.add(text, func) ... func_B(self) ... do something here. ... In this way, I want to create command button dynamically. But how can I pass func_B as an argument here? Thank you! Peter From lumbricus@gmx.net Mon Jul 23 20:18:31 2001 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon, 23 Jul 2001 21:18:31 +0200 Subject: [Tutor] ftplib In-Reply-To: <200107231827.f6NIRRD22519@smtp-server1.tampabay.rr.com>; from rortega@cfl.rr.com on Mon, Jul 23, 2001 at 02:27:28PM +0000 References: <200107231827.f6NIRRD22519@smtp-server1.tampabay.rr.com> Message-ID: <20010723211831.A19573@Laplace.localdomain> Hi all! On Mon, Jul 23, 2001 at 02:27:28PM +0000, rortega@cfl.rr.com wrote: > Hi I recently wrote my first python script. What it does is take a file and > uploads it to an FTP server using ftplib. It works fine as long as the computer > it runs on is conected to the internet directly but I would like to know if I > can get this to work through a proxie server. > Thanks > hmm... the urllib module sees the environment variables http_proxy, gopher_proxy and ftp_proxy. so setting and exporting these variables should solve your problem but YMMV. HTH and Greetings J"o! :-) -- Nothing is so firmly believed as that which we least know. -- Michel de Montaigne From Blake.Garretson@dana.com Mon Jul 23 20:52:31 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Mon, 23 Jul 2001 15:52:31 -0400 Subject: [Tutor] Displaying animated gifs Message-ID: Is there any support from Tkinter or wxPython (wxWindows) for animated gif files? I just want to create a simple file viewer for gif files. A paired down version of my code goes something like this: from Tkinter import * import sys root=Tk() root.title("View Image") myframe=Frame(root,colormap="new",visual='truecolor') myframe.pack() myimage=PhotoImage(file=sys.argv[1]) mylabel=Label(myframe,image=myimage) mylabel.pack() quitbutton=Button(root,text="Quit",command=root.destroy).pack(fill=X) root.mainloop() This works fine for regular gifs, but not for animated gifs. There must be a module out there somewhere that handles it, but I have yet to find it. Any suggestions? Thanks, Blake Garretson From dyoo@hkn.eecs.berkeley.edu Mon Jul 23 21:01:42 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 23 Jul 2001 13:01:42 -0700 (PDT) Subject: [Tutor] problem with circular list In-Reply-To: <20010723075945.A21673@gblx.net> Message-ID: On Mon, 23 Jul 2001, Tim Condit wrote: > > Side note: you can avoid depending on IndexError altogether by using the > > "modulo" operator '%'. The modulo operator is traditionally used for > > things that "wrap around": > > > > ### > > >>> for i in range(10): > > ... print i % 3 > > ... > > 0 > > 1 > > 2 > > > > I used this originally, then dropped it in favor of subtraction.. seemed > like a good idea at the time. The problem with subtraction is that you have to make sure you do it enough. For example, let's say that we have 2 lone survivors left, and the executioner starts humming "Fee fi fo fum, I smell the blood of an Englishman." That's 8 syllablus. If our position is originally 0, then what we want is: (0 + 8) % 2 == 0 And the first person's gone. However, if we're not careful with the subtraction, what we get is something different: (0 + 8) - 2 == 6 and since there are only two people, that's a bug that will, justifiably, cause an IndexError. One solution to this is to use repeated subtraction in some sort of while loop, which I think someone suggested in a previous message. Hope this helps! From dsh8290@rit.edu Mon Jul 23 21:28:52 2001 From: dsh8290@rit.edu (dman) Date: Mon, 23 Jul 2001 16:28:52 -0400 Subject: [Tutor] pass a function name as an argument In-Reply-To: <5.1.0.14.0.20010723135016.00ae8e38@mail.ydyn.com.criticalpath.net>; from qhe@ydyn.com on Mon, Jul 23, 2001 at 02:03:51PM -0500 References: <5.1.0.14.0.20010723135016.00ae8e38@mail.ydyn.com.criticalpath.net> Message-ID: <20010723162852.A24451@harmony.cs.rit.edu> On Mon, Jul 23, 2001 at 02:03:51PM -0500, Peter He wrote: | Hi there, | | How can I pass a function name as an argument to another function? Either you can put it in a string literal or use the __name__ attribute of the function object. HTH, -D From dyoo@hkn.eecs.berkeley.edu Mon Jul 23 22:41:05 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 23 Jul 2001 14:41:05 -0700 (PDT) Subject: [Tutor] pass a function name as an argument In-Reply-To: <5.1.0.14.0.20010723135016.00ae8e38@mail.ydyn.com.criticalpath.net> Message-ID: On Mon, 23 Jul 2001, Peter He wrote: > How can I pass a function name as an argument to another function? Here's an example that might help show how to pass functions around: ### >>> def fixedPoint(func, initial_value): ... epsilon = 0.01 ... current_value = func(initial_value) ... while 1: ... new_value = func(current_value) ... if abs(new_value - current_value) < epsilon: ... break ... current_value = new_value ... return current_value ... >>> import math >>> fixedPoint(math.cos, 0) 0.74423735490055687 >>> math.cos(0.74423735490055687) 0.73560474043634738 ### In this example, fixedPoint() is a function that takes other functions as arguments. In math terms, it tries to find the "fixed point" of a given function. The call here: fixedPoint(math.cos, 0) passes math.cos off to the fixedPoint function. As long as we don't put parens like "math.cos()", Python will allow us to pass this function around like any other variable. It looks like you're trying to pass the member function of an instance. Can you show us an example of what you're doing? That will help us to tailor the example. Good luck! From dyoo@hkn.eecs.berkeley.edu Mon Jul 23 22:42:30 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 23 Jul 2001 14:42:30 -0700 (PDT) Subject: [Tutor] problem with circular list In-Reply-To: Message-ID: On Mon, 23 Jul 2001, Danny Yoo wrote: > > I used this originally, then dropped it in favor of subtraction.. seemed > > like a good idea at the time. > > The problem with subtraction is that you have to make sure you do it > enough. For example, let's say that we have 2 lone survivors left, and > the executioner starts humming "Fee fi fo fum, I smell the blood of an > Englishman." That's 8 syllablus. Err. Right. 13. I meant 13. I need to take remedial math. *grin* From tescoil@irtc.net Tue Jul 24 00:09:49 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 23 Jul 2001 18:09:49 -0500 Subject: [Tutor] Displaying animated gifs References: Message-ID: <3B5CAEBD.3F9D168@irtc.net> 23 July 2001, Blake Garretson wrote: > This works fine for regular gifs, but not for animated > gifs. There must be a module out there somewhere that > handles it, but I have yet to find it. Any suggestions? Haven't worked with it myself, but Python Imaging Library. http://www.pythonware.com/library/pil/handbook/tutorial.htm "Image Sequences" about 3/4 down the page, has example code. From Marco Scodeggio Tue Jul 24 09:41:08 2001 From: Marco Scodeggio (Marco Scodeggio) Date: Tue, 24 Jul 2001 10:41:08 +0200 (MET DST) Subject: [Tutor] code design problem Message-ID: <200107240841.KAA01753@hestia.ifctr.mi.cnr.it> Dear most helpful friends, I'm having a problem in the conceptual design of a piece of software, that certainly originates from a mix of my far from perfect Python knowledge and my total ignorance about object oriented programming..... What I'm trying to achieve is the following: a tool to manipulate and visualize data, that can get the data straight out of a database. The two requirements I need to satisfy are the following: 1) it should be possible (and easy) to use it with the database engine of choice; 2) it should be possible (and easy) to plug in new data handling modules to make the tool more powerful. Therefore I am trying to put the database connection code in a class by itself, that will take care of loading the module(s) implementing the database interface, open the connection, and always return a database "cursor", independently from the specific db engine. Then all the code needed to carry out database queries is in a separate class, since the queries only need the cursor to operate, and therefore this code can be completely db engine neutral. This class (in my naive model) should be initialized once and forever passing to it the db cursor "returned" by the connection class. Thus it would effectively represent the interface that the plug-in modules would use to communicate with the db. In this way if I use mySQL and user Joe uses Oracle, Joe needs only to change the connection class (or the class could already contain a number of connection alternatives, that's not important), and nothing else. And if he wants to add some functionality, he just needs to know what functions the query class offers to grab the required data. Thus the pseudo-code for this part of the tool would look something like this: import dbConncection import dbQuery class myTool: __init__(whatever): myConnection = dbConnection('mysql') myCursor = myConnection.doConnect() myQuery = dbQuery(myCursor) myResult = myQuery.doQuery( < list of parameters > ) and this works perfectly OK. Now here comes my big problem: I want to plug in a new module, containing class myPlugin, and I would like to be able to do something like this: import dbQuery class myPlugin: __init__(whatever): pluginResult = dbQuery.doQuery( < list of parameters > ) but of course if I do that I get the error "TypeError: unbound method must be called with class instance 1st argument" Therefore the question is: what should I do to get an equivalent result ?? I do not want to create a new instance of the dbQuery class (I presume) within myPlugin, because this new instance would not know what "myCursor" is, and I do not want to create one db connection for each plug-in module, as one such connection is certainly enough for all of them. So, if you were able to follow me this far, I would like to ask you guys for any suggestions that might help me achieve the objectives I have tried to describe. Thanks a lot in advance, Marco Scodeggio From wheelege@tsn.cc Tue Jul 24 10:57:27 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Tue, 24 Jul 2001 19:57:27 +1000 Subject: [Tutor] help on scope References: <8457258D741DD411BD3D0050DA62365907A9A0@huina.oceanic.com> <000389c01b4d9752_mailit@mail.isis.de> Message-ID: <03bc01c11429$e55126c0$0200a8c0@ACE> From: "Charlie Clark" > I'm writing a little program that makes anagrams. Something I failed to do > miserably in basic when I first dabbled in programming 20 years ago. I'm > using count to help me check whether the algorithm is working properly. As I > use a recursive function I need to initialise my counter outside the function > but increment with each new word. Passing the counter as an argument removes > problems of scope but feels wrong. I agree, however, that it is better than > using global. Am I missing something? > What what what, recursion for anagrams? I have been a little lax on the tutor list (go the integer division debate...well, it did go) but I'm pretty sure you don't need to do recursion for something like an anagram program. Unless of course you are trying to learn recursion - at which point I'll be quiet :) Carry on, Glen. From Charlie Clark Tue Jul 24 11:37:48 2001 From: Charlie Clark (Charlie Clark) Date: Tue, 24 Jul 2001 12:37:48 +0200 Subject: [Tutor] help on scope References: <8457258D741DD411BD3D0050DA62365907A9A0@huina.oceanic.com> <000389c01b4d9752_mailit@mail.isis.de> <03bc01c11429$e55126c0$0200a8c0@ACE> Message-ID: <000389d495beb520_mailit@mail.isis.de> > What what what, recursion for anagrams? I have been a little lax on the >tutor list (go the integer division debate...well, it did go) but I'm pretty >sure you don't need to do recursion for something like an anagram program. > Unless of course you are trying to learn recursion - at which point I'll >be quiet :) I don't know how to write an anagram program. It's something I've wanted to do for years but because I don't think like a programmer I never made it. At the moment I have to functions: one which rotates the letters in a word and another one that splits the word up. I get one to call the other. It's some kind of recursion and it nearly but not quite works. def switch(word): for letter in word: word += word[0] word = word [1:] #print word return word def chop(word): global count for letter in range(1, len(word) - 1): left = word[:letter] right = word[letter:] for letter in right: count += 1 right = switch(right) print left, right # prints our anagrams with a space so we can see them if __name__ == "__main__": count = 0 word = "charlie" for letter in word: word = switch(word) # rotate letter by letter chop(word) # move from left to right across a single word print "%d anagrams" %(count) -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From patrick@kirks.net Tue Jul 24 12:08:23 2001 From: patrick@kirks.net (Patrick Kirk) Date: Tue, 24 Jul 2001 12:08:23 +0100 Subject: [Tutor] Blackadder by the Kompany Message-ID: <006d01c11432$dbb50b00$1900a8c0@pod> Hi all, Some time ago I asked about the ability to create forms quickly and easily the way you can in products like MS Access. Apart from Boa, which looks like it will be good in a year or so if someone takes an interest in it, I found nothing 'til now. I just bought the Blackadder IDE which uses the Qt widget set. It set me back the princley sum for Ј30. So far it looks great. The forms are self sizing and the widgets very fetching. Question: will using Qt and Python mean that any executable on Windows I create has a huge amount of library compared by something done in wxPython. Patrick Kirk GSM: +44 7876 560 646 ICQ: 42219699 "After Careful Consideration, Bush Recommends Oil Drilling" - The Onion From dsh8290@rit.edu Tue Jul 24 16:59:34 2001 From: dsh8290@rit.edu (dman) Date: Tue, 24 Jul 2001 11:59:34 -0400 Subject: [Tutor] Blackadder by the Kompany In-Reply-To: <006d01c11432$dbb50b00$1900a8c0@pod>; from patrick@kirks.net on Tue, Jul 24, 2001 at 12:08:23PM +0100 References: <006d01c11432$dbb50b00$1900a8c0@pod> Message-ID: <20010724115933.B26434@harmony.cs.rit.edu> On Tue, Jul 24, 2001 at 12:08:23PM +0100, Patrick Kirk wrote: | Hi all, |=20 | Some time ago I asked about the ability to create forms quickly and | easily the way you can in products like MS Access. Apart from Boa, | which looks like it will be good in a year or so if someone takes an | interest in it, I found nothing 'til now. I just bought the | Blackadder IDE which uses the Qt widget set. It set me back the | princley sum for =A330. So far it looks great. The forms are self | sizing and the widgets very fetching. There are also wxDesigner for wxPython/wxWindows and Glade for the GTK+. | Question: will using Qt and Python mean that any executable on | Windows I create has a huge amount of library compared by something | done in wxPython. If you use Qt you will need the Qt library and the python bindings. If you use wxPython you need the wxWindows library and the python bindings. If you use GTK+ you will need the GTK+ library and the python bindings. It's more or less the same, though the size of the libraries may differ. The main issue with using Qt is licenseing. wxPython/wxWindows and PyGTK/GTK+ are both free (open) so there is no licensing issues. HTH, -D From sheila@thinkspot.net Tue Jul 24 17:07:45 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 24 Jul 2001 09:07:45 -0700 Subject: [Tutor] Blackadder by the Kompany In-Reply-To: <20010724115933.B26434@harmony.cs.rit.edu> References: <006d01c11432$dbb50b00$1900a8c0@pod> <20010724115933.B26434@harmony.cs.rit.edu> Message-ID: <6E44BA8191C@kserver.org> On Tue, 24 Jul 2001 11:59:34 -0400, dman wrote about Re: [Tutor] Blackadder by the Kompany: :The main issue with using Qt is licenseing. :wxPython/wxWindows and PyGTK/GTK+ are both free (open) so there is no :licensing issues. I believe, that purchasing Black Adder gets you the license to use the Qt libraries? However, there are different Black Adder licenses. Some are only licensing for personal use, not re-distribution? https://www.thekompany.com/products/order/catalog.php3 -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From kag_oz@yahoo.com.au Tue Jul 24 17:11:55 2001 From: kag_oz@yahoo.com.au (=?iso-8859-1?q?itchy=20shin?=) Date: Wed, 25 Jul 2001 02:11:55 +1000 (EST) Subject: [Tutor] Multiple flags using winsound... Message-ID: <20010724161155.98164.qmail@web11307.mail.yahoo.com> Hi I am new here and just started programming in Python. I was playing around with a module called winsound and got to play some wave sound using 1 flag but when I try to use multiple flags I get an error. Can someone please point out what I am doing wrong? This worked: import winsound winsound.PlaySound("C:\\path\\whatever.wav", winsound.SND_ASYNCLOOP) This gave a type error(PlaySound() takes exactly 2 arguments (3 given)): import winsound winsound.PlaySound("C:\\path\\whatever.wav", winsound.SND_ASYNC, winsound.SND_LOOP) ??? _____________________________________________________________________________ http://messenger.yahoo.com.au - Yahoo! Messenger - Voice chat, mail alerts, stock quotes and favourite news and lots more! From dsh8290@rit.edu Tue Jul 24 17:20:53 2001 From: dsh8290@rit.edu (dman) Date: Tue, 24 Jul 2001 12:20:53 -0400 Subject: [Tutor] Multiple flags using winsound... In-Reply-To: <20010724161155.98164.qmail@web11307.mail.yahoo.com>; from kag_oz@yahoo.com.au on Wed, Jul 25, 2001 at 02:11:55AM +1000 References: <20010724161155.98164.qmail@web11307.mail.yahoo.com> Message-ID: <20010724122053.D26434@harmony.cs.rit.edu> On Wed, Jul 25, 2001 at 02:11:55AM +1000, itchy shin wrote: | Hi I am new here and just started programming in | Python. | | I was playing around with a module called winsound | and got to play some wave sound using 1 flag but when | I try to use multiple flags I get an error. Can | someone please point out what I am doing wrong? | | This worked: | import winsound | winsound.PlaySound("C:\\path\\whatever.wav", | winsound.SND_ASYNCLOOP) | | This gave a type error(PlaySound() takes exactly 2 | arguments (3 given)): | import winsound | winsound.PlaySound("C:\\path\\whatever.wav", | winsound.SND_ASYNC, winsound.SND_LOOP) Try this : winsound.PlaySound("C:\\path\\whatever.wav", winsound.SND_ASYNC | winsound.SND_LOOP) flags are commonly just bit patterns and you need to use a bitwise or operation to combine both patterns together. Also be aware that Win9x ignores any parameters sent to it (I think that is with the Beep function, but I don't remember exactly). -D From tim@digicool.com Tue Jul 24 17:40:17 2001 From: tim@digicool.com (Tim Peters) Date: Tue, 24 Jul 2001 12:40:17 -0400 Subject: [Tutor] Multiple flags using winsound... In-Reply-To: <20010724122053.D26434@harmony.cs.rit.edu> Message-ID: [dman] > ... > Also be aware that Win9x ignores any parameters sent to it (I think > that is with the Beep function, but I don't remember exactly). The Windows function named "Beep" does ignore its arguments on Win9x, but the *Python" function winsound.Beep does not ignore them in Python 2.1 (we no longer use the useless Windows Beep under Win9x). From dsh8290@rit.edu Tue Jul 24 17:56:30 2001 From: dsh8290@rit.edu (dman) Date: Tue, 24 Jul 2001 12:56:30 -0400 Subject: [Tutor] Blackadder by the Kompany In-Reply-To: <6E44BA8191C@kserver.org>; from sheila@thinkspot.net on Tue, Jul 24, 2001 at 09:07:45AM -0700 References: <006d01c11432$dbb50b00$1900a8c0@pod> <20010724115933.B26434@harmony.cs.rit.edu> <6E44BA8191C@kserver.org> Message-ID: <20010724125630.C26573@harmony.cs.rit.edu> On Tue, Jul 24, 2001 at 09:07:45AM -0700, Sheila King wrote: | On Tue, 24 Jul 2001 11:59:34 -0400, dman wrote about | Re: [Tutor] Blackadder by the Kompany: | | :The main issue with using Qt is licenseing. | :wxPython/wxWindows and PyGTK/GTK+ are both free (open) so there is no | :licensing issues. | | I believe, that purchasing Black Adder gets you the license to use the | Qt libraries? However, there are different Black Adder licenses. Some | are only licensing for personal use, not re-distribution? IANAL and have no interest in deciphering the license restrictions. I like the LnF of GTK+ better anyways :-). -D From pkirk@enterprise-hr.com Tue Jul 24 20:06:10 2001 From: pkirk@enterprise-hr.com (Patrick Kirk) Date: Tue, 24 Jul 2001 20:06:10 +0100 Subject: [Tutor] Blackadder by the Kompany References: <006d01c11432$dbb50b00$1900a8c0@pod> <20010724115933.B26434@harmony.cs.rit.edu> <6E44BA8191C@kserver.org> <20010724125630.C26573@harmony.cs.rit.edu> Message-ID: <002d01c11475$6248ec80$1900a8c0@pod> [snip]| | IANAL and have no interest in deciphering the license restrictions. I | like the LnF of GTK+ better anyways :-). | WTF does that mean? Seriuosly, ianal? lnf? From ak@silmarill.org Tue Jul 24 20:22:51 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Tue, 24 Jul 2001 15:22:51 -0400 Subject: [Tutor] Blackadder by the Kompany In-Reply-To: <"from pkirk"@enterprise-hr.com> References: <006d01c11432$dbb50b00$1900a8c0@pod> <20010724115933.B26434@harmony.cs.rit.edu> <6E44BA8191C@kserver.org> <20010724125630.C26573@harmony.cs.rit.edu> <002d01c11475$6248ec80$1900a8c0@pod> Message-ID: <20010724152251.A8129@sill.silmarill.org> On Tue, Jul 24, 2001 at 08:06:10PM +0100, Patrick Kirk wrote: > [snip]| > | IANAL and have no interest in deciphering the license restrictions. I > | like the LnF of GTK+ better anyways :-). > | > WTF does that mean? Seriuosly, ianal? lnf? i am not a lawyer > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From sheila@thinkspot.net Tue Jul 24 20:31:13 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 24 Jul 2001 12:31:13 -0700 Subject: [Tutor] Blackadder by the Kompany References: <006d01c11432$dbb50b00$1900a8c0@pod> <20010724115933.B26434@harmony.cs.rit.edu> <6E44BA8191C@kserver.org> <20010724125630.C26573@harmony.cs.rit.edu> <002d01c11475$6248ec80$1900a8c0@pod> <"from pkirk"@enterprise-hr.com> <20010724152251.A8129@s Message-ID: ill.silmarill.org> In-Reply-To: <20010724152251.A8129@sill.silmarill.org> X-Mailer: Forte Agent 1.8/32.548 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <79E9D5D1203@kserver.org> On Tue, 24 Jul 2001 15:22:51 -0400, sill@optonline.net wrote about Re: [Tutor] Blackadder by the Kompany: :On Tue, Jul 24, 2001 at 08:06:10PM +0100, Patrick Kirk wrote: :> [snip]| :> | IANAL and have no interest in deciphering the license restrictions. I :> | like the LnF of GTK+ better anyways :-). :> | :> WTF does that mean? Seriuosly, ianal? lnf? : :i am not a lawyer Look and Feel -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From israel@lith.com Tue Jul 24 20:36:56 2001 From: israel@lith.com (Israel Evans) Date: Tue, 24 Jul 2001 12:36:56 -0700 Subject: [Tutor] Blackadder by the Kompany Message-ID: I love the PDOAs that crop up OCs! pdoa(pretty damn obscure abbreviations) oc(online communications) :) ~Israel~ -----Original Message----- From: Sheila King [mailto:sheila@thinkspot.net] Sent: Tuesday, July 24, 2001 12:31 PM To: pkirk@enterprise-hr.com Cc: tutor@python.org Subject: Re: [Tutor] Blackadder by the Kompany ill.silmarill.org> In-Reply-To: <20010724152251.A8129@sill.silmarill.org> X-Mailer: Forte Agent 1.8/32.548 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <79E9D5D1203@kserver.org> On Tue, 24 Jul 2001 15:22:51 -0400, sill@optonline.net wrote about Re: [Tutor] Blackadder by the Kompany: :On Tue, Jul 24, 2001 at 08:06:10PM +0100, Patrick Kirk wrote: :> [snip]| :> | IANAL and have no interest in deciphering the license restrictions. I :> | like the LnF of GTK+ better anyways :-). :> | :> WTF does that mean? Seriuosly, ianal? lnf? : :i am not a lawyer Look and Feel -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From pkirk@enterprise-hr.com Tue Jul 24 20:41:19 2001 From: pkirk@enterprise-hr.com (Patrick Kirk) Date: Tue, 24 Jul 2001 20:41:19 +0100 Subject: [Tutor] Blackadder by the Kompany References: <006d01c11432$dbb50b00$1900a8c0@pod> <20010724115933.B26434@harmony.cs.rit.edu> <6E44BA8191C@kserver.org> <20010724125630.C26573@harmony.cs.rit.edu> Message-ID: <000401c1147f$9829e890$1900a8c0@pod> This is a multi-part message in MIME format. ------=_NextPart_000_003F_01C11480.FDFA4010 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 8bit Hi dman, Now that I know what IANAL means, I have read the license and its not bad. The restrictions are as follows: - The "Personal Edition" is for home use only. It may not be used by or within any organization. - A single copy of "BlackAdder" may be used on only one system at a time. So if it turns out I can program, and I set up a company and hire an office, on top of all the lawyers costs for leases, rent, rates, etc. (Minimum costs Ј10,000) I've got to find Ј200 to pay for a business version of Blackadder. But logically, by that time I would already have made at least Ј10,000 from using BA or else I woudln't bother. I prefer the GPL but as non-free licenses go this isn't too oppressive. Patrick ------=_NextPart_000_003F_01C11480.FDFA4010 Content-Type: text/plain; name="LICENSE.txt" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="LICENSE.txt" THE BLACKADDER LICENSE Copyright (c) 2001 theKompany.com Scope This license covers all Beta versions of all editions of "BlackAdder" on all supported platforms. This includes executable programs, libraries, examples and documentation. "BlackAdder" has three editions: the "Demonstration Version", the "Personal Edition", and the "Business Edition". The eGenix.com mx Extensions for Python are covered by a separate license. Granted Rights 1. You are granted the non-exclusive rights set forth in this license provided you agree to and comply with any and all conditions in this license. 2. The copy of Qt GUI toolkit included with "BlackAdder" may not be used for any other purpose. 3. You may copy and distribute the "Demonstration Version" in unmodified form provided that the entire package, including - but not restricted to - copyright, trademark notices and disclaimers, is distributed. 4. The "Personal Edition" is for home use only. It may not be used by or within any organization. 5. A single copy of "BlackAdder" may be used on only one system at a time. Limitations of Liability In no event shall theKompany.com or any copyright holder be liable for any damages whatsoever, including - but not restricted to - lost revenue or profits or other direct, indirect, special, incidental or consequential damages, even if they have been advised of the possibility of such damages, except to the extent invariable law, if any, provides otherwise. No Warranty "BlackAdder" and this license document are provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ------=_NextPart_000_003F_01C11480.FDFA4010-- From alan.gauld@bt.com Tue Jul 24 22:02:03 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 24 Jul 2001 22:02:03 +0100 Subject: [Tutor] code design problem Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D8CE@mbtlipnt02.btlabs.bt.co.uk> > The two requirements I need to satisfy are the following: > 1) it should be possible (and easy) to use it with the > database engine > of choice; > 2) it should be possible (and easy) to plug in new data handling > modules to make the tool more powerful. > > Therefore I am trying to put the database connection code in a class > by itself, that will take care of loading the module(s) implementing > the database interface, open the connection, and always > return a database > "cursor", independently from the specific db engine. Far be it from me to spoil your fun but isn't this already done in the standard Python library? ISTR that it has a generic data access module which can be configured to use any of the vendor specific versions under the covers... Just a thought. Alan g From qhe@ydyn.com Tue Jul 24 22:16:34 2001 From: qhe@ydyn.com (Peter He) Date: Tue, 24 Jul 2001 16:16:34 -0500 Subject: [Tutor] list --> tuple Message-ID: <5.1.0.14.0.20010724161349.00ae5478@mail.ydyn.com.criticalpath.net> Hi, Is there anyway we can convert list into tuple? Thanks! Peter From ak@silmarill.org Tue Jul 24 22:38:57 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Tue, 24 Jul 2001 17:38:57 -0400 Subject: [Tutor] list --> tuple In-Reply-To: <"from qhe"@ydyn.com> References: <5.1.0.14.0.20010724161349.00ae5478@mail.ydyn.com.criticalpath.net> Message-ID: <20010724173857.A8707@sill.silmarill.org> On Tue, Jul 24, 2001 at 04:16:34PM -0500, Peter He wrote: > Hi, > > Is there anyway we can convert list into tuple? >>> l = [1,2,3] >>> tuple(l) (1, 2, 3) -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From tbrauch@mindless.com Tue Jul 24 22:46:23 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Tue, 24 Jul 2001 17:46:23 -0400 Subject: [Tutor] Pickling Message-ID: <3B5DECAF.6F0C59DD@mindless.com> I read the tutorial and I thought I actually understood what was going on, but appearently I didn't. I have some files whose contents are something like: [[1]] or [[1, 1], [2]] that is, lists of lists. I would like to access this data as lists of lists, which is where pickle comes in. But, I can't quite get it worked out. My interpreter session is as follows. ---------------------------------------------- >>> import pickle >>> file=open('part_001.cyc') >>> data=pickle.load(file) Traceback (innermost last): File "", line 1, in ? data=pickle.load(file) File "c:\cs\tools\python20\lib\pickle.py", line 896, in load return Unpickler(file).load() File "c:\cs\tools\python20\lib\pickle.py", line 516, in load dispatch[key](self) KeyError: [ >>> ----------------------------------------------------- I can't figure out what the problem is. - Tim P.S. I finally broke down and ordered some books. So, I can't wait until Wednesday when Alan Gauld's and Wesley Chun's books finally get here. That'll give me some reading for awhile... From steve@purestfeeling.net Tue Jul 24 22:47:58 2001 From: steve@purestfeeling.net (steve) Date: Tue, 24 Jul 2001 15:47:58 -0600 Subject: [Tutor] How to pull a random element from a list? Message-ID: <01072415475802.00916@localhost.localdomain> Greetings I'm trying to figure out how the heck to pull an element from a list or dictionary at random. I have a list of words and need to be able to pull one at random. (Yet to decide if a list is the right way to do it. Thoughts?) I've messed around with my limited knowledge, but haven't been able to figure out how to do it. I was going to use a random number generator to pick which element to retrieve. I am at your mercy oh mighty Pythonistas! HELP! -- Steve - Editor - www.formulaoneupdate.com -------------------------------- "Trish, she has a paddle." - Jeff Hardy From ak@silmarill.org Tue Jul 24 22:58:17 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Tue, 24 Jul 2001 17:58:17 -0400 Subject: [Tutor] Pickling In-Reply-To: <"from tbrauch"@mindless.com> References: <3B5DECAF.6F0C59DD@mindless.com> Message-ID: <20010724175817.A8812@sill.silmarill.org> On Tue, Jul 24, 2001 at 05:46:23PM -0400, Timothy M. Brauch wrote: > I read the tutorial and I thought I actually understood what was going > on, but appearently I didn't. > > I have some files whose contents are something like: > [[1]] > or > [[1, 1], [2]] > that is, lists of lists. I would like to access this data as lists of > lists, which is where pickle comes in. But, I can't quite get it worked > out. My interpreter session is as follows. > ---------------------------------------------- > >>> import pickle > >>> file=open('part_001.cyc') > >>> data=pickle.load(file) > Traceback (innermost last): > File "", line 1, in ? > data=pickle.load(file) > File "c:\cs\tools\python20\lib\pickle.py", line 896, in load > return Unpickler(file).load() > File "c:\cs\tools\python20\lib\pickle.py", line 516, in load > dispatch[key](self) > KeyError: [ > >>> > ----------------------------------------------------- pickle is something you first use to 'pickle' data into a file, then read it from there. It has a special format for storing the data. In your case, look into eval() function. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From ak@silmarill.org Tue Jul 24 23:06:40 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Tue, 24 Jul 2001 18:06:40 -0400 Subject: [Tutor] How to pull a random element from a list? In-Reply-To: <"from steve"@purestfeeling.net> References: <01072415475802.00916@localhost.localdomain> Message-ID: <20010724180640.A8879@sill.silmarill.org> On Tue, Jul 24, 2001 at 03:47:58PM -0600, steve wrote: > Greetings > > I'm trying to figure out how the heck to pull an element from a list or > dictionary at random. I have a list of words and need to be able to pull one > at random. (Yet to decide if a list is the right way to do it. Thoughts?) > > I've messed around with my limited knowledge, but haven't been able to figure > out how to do it. I was going to use a random number generator to pick which > element to retrieve. > > I am at your mercy oh mighty Pythonistas! HELP! >>> l = ['word1','word2','blah','drah'] >>> import random >>> random.choice(l) 'word2' > > -- > Steve - Editor - www.formulaoneupdate.com > -------------------------------- > "Trish, she has a paddle." - Jeff Hardy > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From arcege@speakeasy.net Tue Jul 24 23:25:48 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 24 Jul 2001 18:25:48 -0400 (EDT) Subject: [Tutor] Pickling In-Reply-To: from "Timothy M. Brauch" at Jul 24, 2001 05:46:23 PM Message-ID: <200107242225.f6OMPmM02406@dsl092-074-184.bos1.dsl.speakeasy.net> Timothy M. Brauch wrote > I read the tutorial and I thought I actually understood what was going > on, but appearently I didn't. > > I have some files whose contents are something like: > [[1]] > or > [[1, 1], [2]] > that is, lists of lists. I would like to access this data as lists of > lists, which is where pickle comes in. But, I can't quite get it worked > out. My interpreter session is as follows. Unpickling only works when the data in the file is already pickled. The pickled value looks nothing like the Python representation. >>> import pickle >>> pickle.dumps([[1]]) '(lp0\012(lp1\012I1\012aa.' >>> pickle.loads('(lp0\012(lp1\012I1\012aa.') [[1]] >>> If you want to handle this as text in the file, then I suggest using the eval function. >>> line = file.readline() '[[1]]\012' >>> line >>> expr = eval(line, {'__builtins__': {}}) >>> expr [[1]] >>> line = file.readline() >>> line '[[1, 1], [2]]\012' >>> expr = eval(line, {'__builtins__': {}}) >>> expr [[1, 1], [2]] >>> The "{'__builtins__': {}}" is to prevent the input from getting access to things like the built-in functions. Hope this has helped. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From jessefw@loop.com Sat Jul 21 00:17:08 2001 From: jessefw@loop.com (Jesse F. W) Date: Fri, 20 Jul 2001 16:17:08 -0700 Subject: [Tutor] Another problem with urllib Message-ID: <3B585984.1678.F7D9B5@localhost> I have now solved it. I got the debugging info to turn on, which showed me that openurl was choking on a host called 'localhost' I recognised that name as being related to a proxie that I run to remove ads when I am browsing on the net. I wandered arround in the urllib and httplib modules a bit, and finally found that if I used the URLopener classes, I could tell them to not use any proxies, and then it worked. Thank you, Remco, for your help, Thank you for your time, Jesse W ------- End of forwarded message ------- From dyoo@hkn.eecs.berkeley.edu Wed Jul 25 04:32:21 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 24 Jul 2001 20:32:21 -0700 (PDT) Subject: [Tutor] How to pull a random element from a list? In-Reply-To: <20010724180640.A8879@sill.silmarill.org> Message-ID: On Tue, 24 Jul 2001 sill@optonline.net wrote: > On Tue, Jul 24, 2001 at 03:47:58PM -0600, steve wrote: > > Greetings > > > > I'm trying to figure out how the heck to pull an element from a list or > > dictionary at random. I have a list of words and need to be able to pull one > > at random. (Yet to decide if a list is the right way to do it. Thoughts?) > > > > I've messed around with my limited knowledge, but haven't been able to > > figure out how to do it. I was going to use a random number generator > > to pick which element to retrieve. > > > > I am at your mercy oh mighty Pythonistas! HELP! > > >>> l = ['word1','word2','blah','drah'] > >>> import random > >>> random.choice(l) > 'word2' And for a dictionary, it depends if you want to choose a random key or value: ### >>> mydict = { 'a' : 'apple', ... 'b' : 'bear', ... 'c' : 'canada' } >>> import random >>> random.choice(mydict.keys()) 'a' >>> random.choice(mydict.keys()) 'b' >>> random.choice(mydict.values()) 'bear' >>> random.choice(mydict.values()) 'apple' >>> random.choice(mydict.values()) 'bear' >>> random.choice(mydict.values()) 'bear' >>> random.choice(mydict.values()) 'apple' >>> random.choice(mydict.values()) 'canada' ### That took a while to get Canada... I felt like Rosencranz and Guildenstern for a moment. Good luck! From dyoo@hkn.eecs.berkeley.edu Wed Jul 25 05:13:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 24 Jul 2001 21:13:11 -0700 (PDT) Subject: [Tutor] A small (but long) introduction to recursion Message-ID: I wrote this up today for a student in an introductory CS class; I thought it might be interesting for people on tutor, so here's a version of the introduction in Python. [warning: this is a somewhat long message.] --- Here's an example of a "recursive" problem: Let's say that we're trying to add up the numbers: 0 + 1 + 2 + ... + n together. In Python, this is pretty easy: ### ## non-recursive version of addUpToN def addUpToN(n): """Adds the numbers from zero to n, inclusive. 1 + 2 + ... + n""" sum = 0 for i in range(n+1): sum += i return sum ### And since it's so "easy" to define, let's make sure it works: ### >>> addUpToN(0) 0 >>> addUpToN(1) 1 >>> addUpToN(2) 3 >>> addUpToN(3) 6 >>> addUpToN(10) 55 >>> 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 55 >>> reduce(lambda x, y: x + y, range(11)) # just playing around... 55 ## Ok, it looks good. (Note: the first time I did this, I was off by a lot by accidently doing "range(n)" instead of "range(n+1)". Testing code is a very good idea. *grin*) However, there's a "recursive" way to view this problem, a way of boomeranging the problem around itself: to add the numbers from 0 to n, we can add the numbers from 0 to n-1. Once we have that, we can finish the sum by adding 'n'. What we mean is that: ### def addUpToNRecursive(n): if n == 0: return 0 return addUpToNRecursive(n-1) + n ### Let's test it out. ### >>> addUpToNRecursive(0) 0 >>> addUpToNRecursive(1) 1 >>> addUpToNRecursive(2) 3 >>> addUpToNRecursive(10) 55 ### When we think about recursive solutions to problems, we try to figure out a way of teasing out a smaller piece to help us out. The part that actually does the brunt of the work is this line: return addUpToNRecursive(n-1) + n What we're telling Python is that: "To add (1 + 2 + 3 + .... + n), all we need to do is add (1 + 2 + 3 + ... + n-1), and top it off with 'n'." It's very neat and short. In technical terms, this is called the "recursive step" --- the part that depends on a call to itself. The line right before, though, if n == 0: return 0 seems a bit arbitrary, no? What happens if we pull it out? ### def addUpToNBrokenRecursive(n): return addUpToNBrokenRecursive(n-1) + n ### The name gives a hint, but how is it "broken"? Let's try it out: ### >>> addUpToNBrokenRecursive(0) Traceback (most recent call last): File "", line 1, in ? File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive ... [lots and lots of lines later] File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive RuntimeError: maximum recursion depth exceeded ### Wow. This is akin to the "Are we there yet?" game that children use to gleefully madden their parents. "Are we there yet?" "No." "Are we there yet?" "No." "Are we there yet?" "No!" Unlike the road game, the road goes on and on in a recursion that doesn't say when to stop. In addUpToNBrokenRecursive(), ### def addUpToNBrokenRecursive(n): return addUpToNBrokenRecursive(n-1) + n ### what's missing is a "base case", something that the function is absolutely sure it knows how to answer without calling itself. It needs a solid foundation, and that's the role that the line, if n == 0: return 0 plays. Of course, if we pass something like -1 off to the function, we'll fall off the edge of the world again... But as long as we decide that 'n' needs to be >= 0, that's ok. (Anyway, what does it even mean to do "0 + 1 + ... + -42"?) Anyway, better stop here. If you have any questions, feel free to email the tutor list. If anyone requests it, we can show more examples of recursion. Not everything molds well to a recursive solution, but in some cases, it's a beautiful approach. Hope this helps! From abhiramkushwah@rediffmail.com Wed Jul 25 06:39:12 2001 From: abhiramkushwah@rediffmail.com (Abhiram Singh Kushwah) Date: 25 Jul 2001 05:39:12 -0000 Subject: [Tutor] how to pass list or dictionary via form Message-ID: <20010725053912.6719.qmail@mailweb22.rediffmail.com> Hi all, can any tell me how to pass list or dictionary from web form to another page or same page. Also tell me how to embed python script into HTML page. Please reply me anyone! Thanks in advance ! Abhiram _________________________________________________________ For Rs. 2,000,000 worth of Aptech scholarships click below http://events.rediff.com/aptechsch/scholarship.htm From abhiramkushwah@rediffmail.com Wed Jul 25 06:43:43 2001 From: abhiramkushwah@rediffmail.com (Abhiram Singh Kushwah) Date: 25 Jul 2001 05:43:43 -0000 Subject: [Tutor] how to pass list or dictionary via form Message-ID: <20010725054343.9753.qmail@mailweb20.rediffmail.com> Hi all, can any tell me how to pass list or dictionary from web form to another page or same page. Also tell me how to embed python script into HTML page. Please reply me anyone! Thanks in advance ! Abhiram _________________________________________________________ For Rs. 2,000,000 worth of Aptech scholarships click below http://events.rediff.com/aptechsch/scholarship.htm From wheelege@tsn.cc Wed Jul 25 06:58:40 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Wed, 25 Jul 2001 15:58:40 +1000 Subject: [Tutor] help on scope References: <8457258D741DD411BD3D0050DA62365907A9A0@huina.oceanic.com> <000389c01b4d9752_mailit@mail.isis.de> <03bc01c11429$e55126c0$0200a8c0@ACE> <000389d495beb520_mailit@mail.isis.de> Message-ID: <011b01c114ce$db1b4320$0200a8c0@ACE> > > What what what, recursion for anagrams? I have been a little lax on the > >tutor list (go the integer division debate...well, it did go) but I'm pretty > >sure you don't need to do recursion for something like an anagram program. > > Unless of course you are trying to learn recursion - at which point I'll > >be quiet :) > I don't know how to write an anagram program. It's something I've wanted to > do for years but because I don't think like a programmer I never made it. At > the moment I have to functions: one which rotates the letters in a word and > another one that splits the word up. I get one to call the other. It's some > kind of recursion and it nearly but not quite works. > Well, don't I look silly. I was thinking of something other than anagrams...but hmm if you really want to make an anagram program then you will have to check the resulting words against a very large dictionary...then somehow check out sentence structure, that's if your going to throw in a whole bunch of spaces. Man, there would be millions of combinations in any number over like 15... Yes, you will need recursion to get all permutations of the letters in a sentence. I think the real difficulty will be the whole filtering thing - I won't give you the recursive function to get all the permutations, more than likely you can write one yourself after ready Danny's recent post on recursion. HTH, Glen. From ak@silmarill.org Wed Jul 25 07:48:43 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Wed, 25 Jul 2001 02:48:43 -0400 Subject: [Tutor] how to pass list or dictionary via form In-Reply-To: <"from abhiramkushwah"@rediffmail.com> References: <20010725054343.9753.qmail@mailweb20.rediffmail.com> Message-ID: <20010725024843.A10105@sill.silmarill.org> On Wed, Jul 25, 2001 at 05:43:43AM -0000, Abhiram Singh Kushwah wrote: > Hi all, > > can any tell me how to pass list or dictionary from web form to another page or same page. > > Also tell me how to embed python script into HTML page. > Please reply me anyone! Look into cgi module in python documentation. If you have any trouble with it, feel free to ask here.. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From koen@behindthesofa.dhs.org Wed Jul 25 11:39:22 2001 From: koen@behindthesofa.dhs.org (Koen Bossers) Date: Wed, 25 Jul 2001 12:39:22 +0200 Subject: [Tutor] piping continuous output Message-ID: <3B5EA1DA.943F649@behindthesofa.dhs.org> Hi, I'm trying some stuff with popen2. The thing is that I want to parse the output from a program (will be the output of cdrecord or similar progams) that runs for a while (in this example indefinitely) and print out a progress indicator or something like that. For this purpose I created the following two scripts: [print_messages.py] #! /usr/bin/python import time, os counter = 0 while 1: counter += 1 print 'Hello from process', os.getpid() print '%d'%counter, time.sleep(0.05) [popentest.py] #! /usr/bin/python ## test popen with continuing output import os, time import popen2 (output, input) = popen2.popen2('./print_messages.py') count = 0 print "starting...", os.getpid() listing = '' while 1: test = output.read(1000) ## read next 1000 bytes listing += test if not test: ## wait for sufficient output time.sleep(0.5) listing = '' print listing print "\nRun",count count += 1 This works for me. The only thing is I find this a very dirty hack. Are there other ways to achieve the same result? Thanks, Koen Bossers From alan.gauld@bt.com Wed Jul 25 11:55:45 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 25 Jul 2001 11:55:45 +0100 Subject: [Tutor] Blackadder by the Kompany Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BDFF@mbtlipnt02.btlabs.bt.co.uk> > widget set. It set me back the princley sum for =A330. =20 > So far it looks great. =20 Good, thayts the first biut of unsolicited feedback=20 I've seen on BlackAdder. > Question: will using Qt and Python mean that any executable=20 > on Windows I create has a huge amount of library compared=20 > by something done in wxPython. I wouldn't have thought so. Qt is a professionally developed=20 library designed for commercial cross platform apps. If it was totally bloated nobody would use it! It might be a little bit bigger than something using another=20 library (and any library will be bigger than using raw win32) but it shouldn't be that bad. OTOH you gain in that the code should be highly portable=20 to Linux/Unix versions of Qt. Alan g From alan.gauld@bt.com Wed Jul 25 12:03:39 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 25 Jul 2001 12:03:39 +0100 Subject: [Tutor] How to pull a random element from a list? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE00@mbtlipnt02.btlabs.bt.co.uk> > I'm trying to figure out how the heck to pull an element from > a list or dictionary at random. I have a list of words and > need to be able to pull one at random. One way is to pull my guessing game object framework from Useless Python. It includes the code for selecting a random word from a list(which is read from a file). The essence is to generate a random integer between 0 and len(list)-1 randint() is your friend. Alan G From ak@silmarill.org Wed Jul 25 13:17:41 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Wed, 25 Jul 2001 08:17:41 -0400 Subject: [Tutor] piping continuous output In-Reply-To: <"from koen"@behindthesofa.dhs.org> References: <3B5EA1DA.943F649@behindthesofa.dhs.org> Message-ID: <20010725081741.B321@sill.silmarill.org> On Wed, Jul 25, 2001 at 12:39:22PM +0200, Koen Bossers wrote: > Hi, > > I'm trying some stuff with popen2. > > The thing is that I want to parse the output from a program (will be the > output of cdrecord or similar progams) that runs for a while (in this > example indefinitely) and print out a progress indicator or something > like that. For this purpose I created the following two scripts: progress indicator for infinity? How high is your monitor's resolution? :-) > > > [print_messages.py] > #! /usr/bin/python > > import time, os > > counter = 0 > while 1: > counter += 1 > print 'Hello from process', os.getpid() > print '%d'%counter, > time.sleep(0.05) > > > [popentest.py] > #! /usr/bin/python > > ## test popen with continuing output > > import os, time > import popen2 > > > (output, input) = popen2.popen2('./print_messages.py') > > count = 0 > > print "starting...", os.getpid() > listing = '' > > while 1: > test = output.read(1000) ## read next 1000 bytes > listing += test > > if not test: ## wait for sufficient output > time.sleep(0.5) > listing = '' > > print listing > print "\nRun",count > > count += 1 > > This works for me. The only thing is I find this a very dirty hack. Are > there other ways to achieve the same result? > > Thanks, > > Koen Bossers > Look at pctail.py program on vaults of parnassus, it does something similar (reads from growing log files). > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From ak@silmarill.org Wed Jul 25 13:19:35 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Wed, 25 Jul 2001 08:19:35 -0400 Subject: [Tutor] How to pull a random element from a list? In-Reply-To: <"from alan.gauld"@bt.com> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE00@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010725081935.C321@sill.silmarill.org> On Wed, Jul 25, 2001 at 12:03:39PM +0100, alan.gauld@bt.com wrote: > > I'm trying to figure out how the heck to pull an element from > > a list or dictionary at random. I have a list of words and > > need to be able to pull one at random. > > One way is to pull my guessing game object framework > from Useless Python. It includes the code for selecting > a random word from a list(which is read from a file). > > The essence is to generate a random integer between > 0 and len(list)-1 > > randint() is your friend. > > Alan G Isn't it easier to use random.choice()? Are there any advantages to this method i'm missing? > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From koen@behindthesofa.dhs.org Wed Jul 25 14:12:27 2001 From: koen@behindthesofa.dhs.org (Koen Bossers) Date: Wed, 25 Jul 2001 15:12:27 +0200 Subject: [Tutor] piping continuous output Message-ID: <3B5EC5BB.8D6C3CD1@behindthesofa.dhs.org> This is a multi-part message in MIME format. --------------976BC1FF29007423AF83F397 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit sill@optonline.net wrote: > Look at pctail.py program on vaults of parnassus, it does something similar > (reads from growing log files). Not what I had in mind. I want to avoid creating temporary files. That's why I chose popen, else I would have used something like os.system('command >> /tmp/tempfile') or something. OK second try: some VERY weird behaviour here: [print_messages.py] #! /usr/bin/python import time, os counter = 0 while counter < 5000: print '%d'%counter time.sleep(0.01) counter = counter + 1 [popentest.py] #! /usr/bin/python ## test popen with continuing output import os, time, string import popen2 child = popen2.Popen3('./print_messages.py') output = child.fromchild count = 1 print "starting...", os.getpid() listing = '' start = time.time() while child.poll() == -1: ## if child is still running... print count, time.time()-start test = output.read(100) count = count + 1 time.sleep(0.2) output when i run popentest.py: starting... 414 1 after 0.000128984451294 2 after 10.696469903 3 after 10.896476984 4 after 11.0964080095 5 after 11.2964220047 6 after 11.4964289665 7 after 11.6964190006 8 after 11.8964159489 9 after 12.0963799953 10 after 12.2964549065 11 after 12.4964559078 12 after 12.6964579821 13 after 12.8963899612 etc... Notice the major timediff between step 1 and 2! 10 seconds!!!! what the hell is happening here? I know Python isn't always that fast, but why this big delay? Enlighten me! Cheers, Koen Bossers --------------976BC1FF29007423AF83F397 Content-Type: message/rfc822 Content-Transfer-Encoding: 7bit Content-Disposition: inline X-Mozilla-Status2: 00000000 Message-ID: <3B5EC445.57AE55D0@behindthesofa.dhs.org> Date: Wed, 25 Jul 2001 15:06:13 +0200 From: Koen Bossers X-Mailer: Mozilla 4.78 [en] (X11; U; Linux 2.4.4 i686) X-Accept-Language: en MIME-Version: 1.0 To: ak@silmarill.org Subject: Re: [Tutor] piping continuous output References: <3B5EA1DA.943F649@behindthesofa.dhs.org> <20010725081741.B321@sill.silmarill.org> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit sill@optonline.net wrote: > Look at pctail.py program on vaults of parnassus, it does something similar > (reads from growing log files). Not what I had in mind. I want to avoid creating temporary files. That's why I chose popen, else I would have used something like os.system('command >> /tmp/tempfile') or something. OK second try: some VERY weird behaviour here: [print_messages.py] #! /usr/bin/python import time, os counter = 0 while counter < 5000: print '%d'%counter time.sleep(0.01) counter = counter + 1 [popentest.py] #! /usr/bin/python ## test popen with continuing output import os, time, string import popen2 child = popen2.Popen3('./print_messages.py') output = child.fromchild count = 1 print "starting...", os.getpid() listing = '' start = time.time() while child.poll() == -1: ## if child is still running... print count, time.time()-start test = output.read(100) count = count + 1 time.sleep(0.2) output when i run popentest.py: starting... 414 1 after 0.000128984451294 2 after 10.696469903 3 after 10.896476984 4 after 11.0964080095 5 after 11.2964220047 6 after 11.4964289665 7 after 11.6964190006 8 after 11.8964159489 9 after 12.0963799953 10 after 12.2964549065 11 after 12.4964559078 12 after 12.6964579821 13 after 12.8963899612 etc... Notice the major timediff between step 1 and 2! 10 seconds!!!! what the hell is happening here? I know Python isn't always that fast, but why this big delay? Enlighten me! Cheers, Koen Bossers --------------976BC1FF29007423AF83F397-- From koen@behindthesofa.dhs.org Wed Jul 25 14:36:05 2001 From: koen@behindthesofa.dhs.org (Koen Bossers) Date: Wed, 25 Jul 2001 15:36:05 +0200 Subject: [Tutor] piping continuous output References: <3B5EC5BB.8D6C3CD1@behindthesofa.dhs.org> Message-ID: <3B5ECB44.8B0C1DFB@behindthesofa.dhs.org> By the way, adding time.sleep(11) before entering the loop eliminates the time differences between outputs. They're nicely aligned at 0.2 secs. right now. Only that darned 10 second pause.... Koen Bossers wrote: > sill@optonline.net wrote: > > > Look at pctail.py program on vaults of parnassus, it does something > similar > > (reads from growing log files). > > Not what I had in mind. I want to avoid creating temporary files. That's > why I > chose popen, else I would have used something like os.system('command >> > > /tmp/tempfile') or something. > > OK second try: some VERY weird behaviour here: > > [print_messages.py] > #! /usr/bin/python > > import time, os > > counter = 0 > while counter < 5000: > > print '%d'%counter > > time.sleep(0.01) > counter = counter + 1 > > [popentest.py] > #! /usr/bin/python > > ## test popen with continuing output > > import os, time, string > import popen2 > > child = popen2.Popen3('./print_messages.py') > output = child.fromchild > > count = 1 > > print "starting...", os.getpid() > listing = '' > start = time.time() > > while child.poll() == -1: ## if child is still running... > > print count, time.time()-start > test = output.read(100) > > count = count + 1 > time.sleep(0.2) > > output when i run popentest.py: > > starting... 414 > 1 after 0.000128984451294 > 2 after 10.696469903 > 3 after 10.896476984 > 4 after 11.0964080095 > 5 after 11.2964220047 > 6 after 11.4964289665 > 7 after 11.6964190006 > 8 after 11.8964159489 > 9 after 12.0963799953 > 10 after 12.2964549065 > 11 after 12.4964559078 > 12 after 12.6964579821 > 13 after 12.8963899612 > etc... > > Notice the major timediff between step 1 and 2! 10 seconds!!!! what the > hell > is happening here? I know Python isn't always that fast, but why this > big > delay? Enlighten me! > > Cheers, > > Koen Bossers > From alan.gauld@bt.com Wed Jul 25 15:04:11 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 25 Jul 2001 15:04:11 +0100 Subject: [Tutor] How to pull a random element from a list? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE04@mbtlipnt02.btlabs.bt.co.uk> > > The essence is to generate a random integer between > > 0 and len(list)-1 > > > > randint() is your friend. > > Isn't it easier to use random.choice()? Are there any > advantages to this method i'm missing? Nope, its just that choice() is a recent addition and I keep forgetting it's there! randint() was the best alternative prior to choice(). In fact in the object framework I use random() and scale it manually just to show the technique, since many languages only have a randmizer that outputs 0-1 values. Alan G From arcege@speakeasy.net Wed Jul 25 15:32:28 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 25 Jul 2001 10:32:28 -0400 (EDT) Subject: [Tutor] How to pull a random element from a list? In-Reply-To: from "alan.gauld@bt.com" at Jul 25, 2001 03:04:11 PM Message-ID: <200107251432.f6PEWT502147@dsl092-074-184.bos1.dsl.speakeasy.net> alan.gauld@bt.com wrote > > > > The essence is to generate a random integer between > > > 0 and len(list)-1 > > > > > > randint() is your friend. > > > > Isn't it easier to use random.choice()? Are there any > > advantages to this method i'm missing? > > Nope, its just that choice() is a recent addition and I keep > forgetting it's there! randint() was the best alternative > prior to choice(). If you are working on an database file or similar construct and cannot put the values into a sequence object, then choice would not be very useful. You might be more inclined to use randint. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From kev@sat.net Wed Jul 25 16:06:19 2001 From: kev@sat.net (Kevin McCormick) Date: Wed, 25 Jul 2001 10:06:19 -0500 Subject: [Tutor] A small (but long) introduction to recursion References: Message-ID: <3B5EE06B.E34D47A9@sat.net> Danny Yoo wrote: > > I wrote this up today for a student in an introductory CS class; I thought > it might be interesting for people on tutor, so here's a version of the > introduction in Python. > > [warning: this is a somewhat long message.] > > --- > > Here's an example of a "recursive" problem: Let's say that we're trying > to add up the numbers: > > 0 + 1 + 2 + ... + n > > together. In Python, this is pretty easy: > > ### > ## non-recursive version of addUpToN > def addUpToN(n): > """Adds the numbers from zero to n, inclusive. 1 + 2 + ... + n""" > sum = 0 > for i in range(n+1): > sum += i > return sum > ### > > And since it's so "easy" to define, let's make sure it works: > > ### > >>> addUpToN(0) > 0 > >>> addUpToN(1) > 1 > >>> addUpToN(2) > 3 > >>> addUpToN(3) > 6 > >>> addUpToN(10) > 55 > >>> 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 > 55 > >>> reduce(lambda x, y: x + y, range(11)) # just playing around... > 55 > ## > > Ok, it looks good. (Note: the first time I did this, I was off by a lot > by accidently doing "range(n)" instead of "range(n+1)". Testing code is a > very good idea. *grin*) > > However, there's a "recursive" way to view this problem, a way of > boomeranging the problem around itself: to add the numbers from 0 to n, we > can add the numbers from 0 to n-1. Once we have that, we can finish the > sum by adding 'n'. What we mean is that: > > ### > def addUpToNRecursive(n): > if n == 0: return 0 > return addUpToNRecursive(n-1) + n > ### > > Let's test it out. > > ### > >>> addUpToNRecursive(0) > 0 > >>> addUpToNRecursive(1) > 1 > >>> addUpToNRecursive(2) > 3 > >>> addUpToNRecursive(10) > 55 > ### > > When we think about recursive solutions to problems, we try to figure out > a way of teasing out a smaller piece to help us out. The part that > actually does the brunt of the work is this line: > > return addUpToNRecursive(n-1) + n > > What we're telling Python is that: "To add (1 + 2 + 3 + .... + n), all we > need to do is add (1 + 2 + 3 + ... + n-1), and top it off with 'n'." > It's very neat and short. In technical terms, this is called the > "recursive step" --- the part that depends on a call to itself. > > The line right before, though, > > if n == 0: return 0 > > seems a bit arbitrary, no? What happens if we pull it out? > > ### > def addUpToNBrokenRecursive(n): > return addUpToNBrokenRecursive(n-1) + n > ### > > The name gives a hint, but how is it "broken"? Let's try it out: > > ### > >>> addUpToNBrokenRecursive(0) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive > File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive > ... [lots and lots of lines later] > File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive > RuntimeError: maximum recursion depth exceeded > ### > > Wow. This is akin to the "Are we there yet?" game that children use to > gleefully madden their parents. > > "Are we there yet?" > "No." > "Are we there yet?" > "No." > "Are we there yet?" > "No!" > > Unlike the road game, the road goes on and on in a recursion that doesn't > say when to stop. In addUpToNBrokenRecursive(), > > ### > def addUpToNBrokenRecursive(n): > return addUpToNBrokenRecursive(n-1) + n > ### > > what's missing is a "base case", something that the function is absolutely > sure it knows how to answer without calling itself. It needs a solid > foundation, and that's the role that the line, > > if n == 0: return 0 > > plays. Of course, if we pass something like -1 off to the function, we'll > fall off the edge of the world again... But as long as we decide that > 'n' needs to be >= 0, that's ok. > > (Anyway, what does it even mean to do "0 + 1 + ... + -42"?) > > Anyway, better stop here. If you have any questions, feel free to email > the tutor list. If anyone requests it, we can show more examples of > recursion. Not everything molds well to a recursive solution, but in some > cases, it's a beautiful approach. > > Hope this helps! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor I absolutely do not understand recursion. I took your example and tried to do some tracing, but I do not understand how the sum is stored or returned: def addUpToNRecursive(n): if n == 0: return 0 print n return addUpToNRecursive(n-1) + n x = addUpToNRecursive(10) print x From ak@silmarill.org Wed Jul 25 16:24:19 2001 From: ak@silmarill.org (ak@silmarill.org) Date: Wed, 25 Jul 2001 11:24:19 -0400 Subject: [Tutor] A small (but long) introduction to recursion In-Reply-To: <"from kev"@sat.net> References: <3B5EE06B.E34D47A9@sat.net> Message-ID: <20010725112419.A2538@sill.silmarill.org> On Wed, Jul 25, 2001 at 10:06:19AM -0500, Kevin McCormick wrote: > Danny Yoo wrote: > > > > I wrote this up today for a student in an introductory CS class; I thought > > it might be interesting for people on tutor, so here's a version of the > > introduction in Python. > > > > [warning: this is a somewhat long message.] > > > > --- > > > > Here's an example of a "recursive" problem: Let's say that we're trying > > to add up the numbers: > > > > 0 + 1 + 2 + ... + n > > > > together. In Python, this is pretty easy: > > > > ### > > ## non-recursive version of addUpToN > > def addUpToN(n): > > """Adds the numbers from zero to n, inclusive. 1 + 2 + ... + n""" > > sum = 0 > > for i in range(n+1): > > sum += i > > return sum > > ### > > > > And since it's so "easy" to define, let's make sure it works: > > > > ### > > >>> addUpToN(0) > > 0 > > >>> addUpToN(1) > > 1 > > >>> addUpToN(2) > > 3 > > >>> addUpToN(3) > > 6 > > >>> addUpToN(10) > > 55 > > >>> 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 > > 55 > > >>> reduce(lambda x, y: x + y, range(11)) # just playing around... > > 55 > > ## > > > > Ok, it looks good. (Note: the first time I did this, I was off by a lot > > by accidently doing "range(n)" instead of "range(n+1)". Testing code is a > > very good idea. *grin*) > > > > However, there's a "recursive" way to view this problem, a way of > > boomeranging the problem around itself: to add the numbers from 0 to n, we > > can add the numbers from 0 to n-1. Once we have that, we can finish the > > sum by adding 'n'. What we mean is that: > > > > ### > > def addUpToNRecursive(n): > > if n == 0: return 0 > > return addUpToNRecursive(n-1) + n > > ### > > > > Let's test it out. > > > > ### > > >>> addUpToNRecursive(0) > > 0 > > >>> addUpToNRecursive(1) > > 1 > > >>> addUpToNRecursive(2) > > 3 > > >>> addUpToNRecursive(10) > > 55 > > ### > > > > When we think about recursive solutions to problems, we try to figure out > > a way of teasing out a smaller piece to help us out. The part that > > actually does the brunt of the work is this line: > > > > return addUpToNRecursive(n-1) + n > > > > What we're telling Python is that: "To add (1 + 2 + 3 + .... + n), all we > > need to do is add (1 + 2 + 3 + ... + n-1), and top it off with 'n'." > > It's very neat and short. In technical terms, this is called the > > "recursive step" --- the part that depends on a call to itself. > > > > The line right before, though, > > > > if n == 0: return 0 > > > > seems a bit arbitrary, no? What happens if we pull it out? > > > > ### > > def addUpToNBrokenRecursive(n): > > return addUpToNBrokenRecursive(n-1) + n > > ### > > > > The name gives a hint, but how is it "broken"? Let's try it out: > > > > ### > > >>> addUpToNBrokenRecursive(0) > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive > > File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive > > ... [lots and lots of lines later] > > File "/usr/tmp/python-6609I5e", line 14, in addUpToNBrokenRecursive > > RuntimeError: maximum recursion depth exceeded > > ### > > > > Wow. This is akin to the "Are we there yet?" game that children use to > > gleefully madden their parents. > > > > "Are we there yet?" > > "No." > > "Are we there yet?" > > "No." > > "Are we there yet?" > > "No!" > > > > Unlike the road game, the road goes on and on in a recursion that doesn't > > say when to stop. In addUpToNBrokenRecursive(), > > > > ### > > def addUpToNBrokenRecursive(n): > > return addUpToNBrokenRecursive(n-1) + n > > ### > > > > what's missing is a "base case", something that the function is absolutely > > sure it knows how to answer without calling itself. It needs a solid > > foundation, and that's the role that the line, > > > > if n == 0: return 0 > > > > plays. Of course, if we pass something like -1 off to the function, we'll > > fall off the edge of the world again... But as long as we decide that > > 'n' needs to be >= 0, that's ok. > > > > (Anyway, what does it even mean to do "0 + 1 + ... + -42"?) > > > > Anyway, better stop here. If you have any questions, feel free to email > > the tutor list. If anyone requests it, we can show more examples of > > recursion. Not everything molds well to a recursive solution, but in some > > cases, it's a beautiful approach. > > > > Hope this helps! > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > I absolutely do not understand recursion. I took your example and tried > to do some tracing, but I do not understand how the sum is stored or > returned: > > def addUpToNRecursive(n): > if n == 0: return 0 > print n > return addUpToNRecursive(n-1) + n Picture it like this: function is called, runs, and returns addUpToNRecursive(10-1) + 10 then, from inside of return statement, function is called again, so you have addUpToNRecursive(10-1) + 10 ^^^^^^^^^^^^^^^^^^^^^^^ | v addUpToNRecursive(9-1) + 9 then again: addUpToNRecursive(9-1) + 9 --------------------- | v addUpToNRecursive(8-1) + 8 [...] until it reaches 0, at which point final value is ready and it looks like this: 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 I remember I had exactly the same problem, when I was studying C. My misconception was that when the function calls itself from inside, that first return statement is substituted by the new one instead of being added to it, whereas in fact it indeed get added. If your misconception is the same (or similar) maybe you'll benefit from me spelling it out like that.. maybe not. HTH, - Andrei > > x = addUpToNRecursive(10) > print x > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From dyoo@hkn.eecs.berkeley.edu Wed Jul 25 17:19:07 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 25 Jul 2001 09:19:07 -0700 (PDT) Subject: [Tutor] A small (but long) introduction to recursion In-Reply-To: <3B5EE06B.E34D47A9@sat.net> Message-ID: On Wed, 25 Jul 2001, Kevin McCormick wrote: > > I absolutely do not understand recursion. I took your example and tried > to do some tracing, but I do not understand how the sum is stored or > returned: > > def addUpToNRecursive(n): > if n == 0: return 0 > print n > return addUpToNRecursive(n-1) + n > > x = addUpToNRecursive(10) > print x Try small cases first, not just because they are simpler to do, but because they are a good way of understanding why the recursion works. I wouldn't go as far as 10 --- that's way too big of a number. *grin* Let's trace addUpToNRecursive(1): n is not equal to zero, so we'll do the inductive case: return addUpToNRecursive(0) + 1 Now to figure that one out, we need to know what addUpToNRecursive(0) looks like. However, that's our base case: we know that addUpToNRecursive(0) is 0. We end up with: return 0 + 1 Let's try the function for n == 2: It's not the base case, so addUpToNRecursive() will give back the value: return addUpToNRecursive(1) + 2 And now we're back to solving addUpToNRecursive(1). We have a good memory, and we know that addUpToNRecursive(1) is 1. As it stands though, addUpToNRecursive() needs to redo the work to compute addUpToNRecursive(1). The trace now looks something like this: addUpToNRecursive(2) addUpToNRecursive(1) + 2 addUpToNRecursive(0) + 1 + 2 0 + 1 + 2 And now it can finally start adding things up --- it couldn't do the addition until it expands the whole sum out. ### Recursion works because once we have a base case, the function can depend on that case to make things work for more things. addUpToNRecursive() works for 0, so it'll work for 1. So now we know that it works for 0 and 1. But since it works for 1, it'll work for 2. Now we know that it works for 0, 1, and 2. But since it works for 2, it works for 3... I'm not sure if that makes much sense yet: it works on a very different principle than explicitly storing some a "sum" variable, so it's bound to look very wacky at first. If anything, I hope that this sort of thing feels "magical": it really is a upside-down way of looking at something. I find it very neat, if impractical at times. *grin* From dyoo@hkn.eecs.berkeley.edu Wed Jul 25 17:25:54 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 25 Jul 2001 09:25:54 -0700 (PDT) Subject: [Tutor] A small (but long) introduction to recursion In-Reply-To: Message-ID: On Wed, 25 Jul 2001, Danny Yoo wrote: > > def addUpToNRecursive(n): > > if n == 0: return 0 > > print n > > return addUpToNRecursive(n-1) + n > > > > x = addUpToNRecursive(10) > > print x If it helps, try this version of the program: ### def addUpToN(n): if n == 0: return 0 print (' ' * n) + "Trying to figure out addUpToN(%s)" % n answer = addUpToN(n-1) + n print (' ' * n) + "The answer of addUpToN(%s) is %s" % (n, answer) return answer ### It's a little bit longer, but it does print something pretty: ### >>> addUpToN(5) Trying to figure out addUpToN(5) Trying to figure out addUpToN(4) Trying to figure out addUpToN(3) Trying to figure out addUpToN(2) Trying to figure out addUpToN(1) The answer of addUpToN(1) is 1 The answer of addUpToN(2) is 3 The answer of addUpToN(3) is 6 The answer of addUpToN(4) is 10 The answer of addUpToN(5) is 15 15 ### From kag_oz@yahoo.com.au Wed Jul 25 17:30:43 2001 From: kag_oz@yahoo.com.au (=?iso-8859-1?q?itchy=20shin?=) Date: Thu, 26 Jul 2001 02:30:43 +1000 (EST) Subject: [Tutor] Multiple flags using winsound... Message-ID: <20010725163043.85468.qmail@web11301.mail.yahoo.com> Yes, it worked! Thanks :) _____________________________________________________________________________ http://messenger.yahoo.com.au - Yahoo! Messenger - Voice chat, mail alerts, stock quotes and favourite news and lots more! From nstalkie@tvd.be Wed Jul 25 18:16:06 2001 From: nstalkie@tvd.be (Sammy Mannaert) Date: Wed, 25 Jul 2001 19:16:06 +0200 Subject: [Tutor] curses class problem Message-ID: <3B5EFED6.392DB468@tvd.be> hi, i'm trying to build a curses class wrapper (to abstract a screen). i'm not an experienced curses user though. i was trying to do a __init__ and a __del__ function and already it fails :) Exception exceptions.AttributeError: "'None' object has no attribute 'echo'" in ignored i have programmed in python quite some times before but i can't figure out why this doesn't work ... it DOES work however if i add self.curses = curses and call every curses function as 'self.curses.rest_of_the_function' ====== the code ====== # abstraction of a screen import curses class Screen: def __init__(self): self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.stdscr.keypad(1) def __del__(self): self.stdscr.keypad(0) curses.echo() curses.nocbreak() curses.endwin() # testroutine if __name__ == "__main__": screen = Screen() ===== end ===== any help/explenation is appreciated :) From van@lindbergs.org Wed Jul 25 18:12:18 2001 From: van@lindbergs.org (VanL) Date: Wed, 25 Jul 2001 11:12:18 -0600 Subject: [Tutor] Asyncore.py v. plain sockets? Message-ID: <3B5EFDF2.5090201@lindbergs.org> Hello, I am writing a client and server that exchange data over a non-privileged port. I have been using straight sockets, but I was recently looking at the asyncore module and it looks pretty cool. Has anyone any experience with straight socket code v. the asyncore module? Any gotchas to watch out for? Thanks, Van From arcege@speakeasy.net Wed Jul 25 18:29:13 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 25 Jul 2001 13:29:13 -0400 (EDT) Subject: [Tutor] curses class problem In-Reply-To: from "Sammy Mannaert" at Jul 25, 2001 07:16:06 PM Message-ID: <200107251729.f6PHTDH02361@dsl092-074-184.bos1.dsl.speakeasy.net> Sammy Mannaert wrote > i'm trying to build a curses class wrapper (to abstract a > screen). i'm not an experienced curses user though. > i was trying to do a __init__ and a __del__ function and > already it fails :) > > Exception exceptions.AttributeError: "'None' object has no attribute 'echo'" in Screen.__del__ of Screen instance at 0x819c92c> ignored > > i have programmed in python quite some times before but > i can't figure out why this doesn't work ... > > it DOES work however if i add self.curses = curses and call > every curses function as 'self.curses.rest_of_the_function' The destruction of modules does not follow any specific order, so the objects in the curses module are destroyed before Screen.__del__ is called. I would make sure that you ALWAYS destroy the Screen instance before the program terminates. Or, alternatively, create a method to shutdown curses explicitly. FYI: endwin() also resets the terminal settings to what they were when initscr() was called, so you likely do not need to call curses.echo(), curses.nocbreak(), etc.. -Arcege -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From mike@daboyz.org Wed Jul 25 19:34:37 2001 From: mike@daboyz.org (Mike Barrett) Date: Wed, 25 Jul 2001 11:34:37 -0700 (PDT) Subject: [Tutor] ping? Message-ID: I was just wondering if anyone out there has a good ping module they'd be willing to share? I found one off of the Vaults, written by Jeremy Hylton, but it's pretty old (1997). If anyone knows of a module or has written one themselves, I'd love to see it. Thanks in advance. ________________________________________________________________________ Mike Barrett | Beer is proof that God loves us mike@daboyz.org | and wants us to be happy. www.daboyz.org | -- Benjamin Franklin ------------------------+----------------------------------------------- From kalle@gnupung.net Wed Jul 25 19:36:23 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 25 Jul 2001 20:36:23 +0200 Subject: [Tutor] ping? In-Reply-To: ; from mike@daboyz.org on Wed, Jul 25, 2001 at 11:34:37AM -0700 References: Message-ID: <20010725203623.B17812@gandalf> Sez Mike Barrett: > I was just wondering if anyone out there has a good ping module > they'd be willing to share? Nope, but I have a (crufty, unreadable, sort-of-working) traceroute, if you're interested. It's no doubt filled with bad code, but some of it might be useful in a ping implementation. Peace, Kalle -- Free Dmitry Sklyarov! -- http://www.freedmitry.org/ PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD [ Not signed due to lossage. Blame Microsoft Outlook Express. ] From abhiramkushwah@rediffmail.com Wed Jul 25 20:40:31 2001 From: abhiramkushwah@rediffmail.com (Abhiram Singh Kushwah) Date: 25 Jul 2001 19:40:31 -0000 Subject: [Tutor] how to pass a list or a dictionary variable in cgi script Message-ID: <20010725194031.11258.qmail@mailweb25.rediffmail.com> hi, Thanks for reply! I've read cgi module already but my problem has not solved.please send me a example if you have. I'm repeating my question again: how to pass a list or a dictionary variable from one web page to another page. Anyway I'v pass a list or dictionary element separatly from one web page to another page but I want to pass whole list or dictionary as a single variable. Thanks again! Abhiram _________________________________________________________ For Rs. 2,000,000 worth of Aptech scholarships click below http://events.rediff.com/aptechsch/scholarship.htm From abhiramkushwah@rediffmail.com Wed Jul 25 20:44:16 2001 From: abhiramkushwah@rediffmail.com (Abhiram Singh Kushwah) Date: 25 Jul 2001 19:44:16 -0000 Subject: [Tutor] how to embed python-cgi script into HTML page Message-ID: <20010725194416.17546.qmail@mailweb15.rediffmail.com> Hi all, Please tell me how to embed python script into HTML page as a PHP script.Send me a example if anyone have. Please reply me anyone! Thanks in advance! _________________________________________________________ For Rs. 2,000,000 worth of Aptech scholarships click below http://events.rediff.com/aptechsch/scholarship.htm From ak@silmarill.org Wed Jul 25 20:38:15 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 25 Jul 2001 15:38:15 -0400 Subject: [Tutor] how to pass a list or a dictionary variable in cgi script In-Reply-To: <"from abhiramkushwah"@rediffmail.com> References: <20010725194031.11258.qmail@mailweb25.rediffmail.com> Message-ID: <20010725153815.A8266@sill.silmarill.org> On Wed, Jul 25, 2001 at 07:40:31PM -0000, Abhiram Singh Kushwah wrote: > hi, > Thanks for reply! > > I've read cgi module already but my problem has not solved.please send me a example if you have. > > I'm repeating my question again: > how to pass a list or a dictionary variable from one web page to another page. > > Anyway I'v pass a list or dictionary element separatly > from one web page to another page but I want to pass whole list or dictionary as a single variable. How do you mean, 'from one page to another'? Where does the list come from in the first place? Could you describe what you're trying to do in more detail? > > Thanks again! > Abhiram > > _________________________________________________________ > For Rs. 2,000,000 worth of Aptech scholarships click below > http://events.rediff.com/aptechsch/scholarship.htm > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From rob@jam.rr.com Wed Jul 25 21:08:35 2001 From: rob@jam.rr.com (Rob Andrews) Date: Wed, 25 Jul 2001 15:08:35 -0500 Subject: [Tutor] how to embed python-cgi script into HTML page In-Reply-To: <20010725194416.17546.qmail@mailweb15.rediffmail.com> Message-ID: # -----Original Message----- # # Please tell me how to embed python script into HTML page as a PHP # script.Send me a example if anyone have. # Were you looking for something along the lines of Python Server Pages, or CGI only? Here are a few notes on PSP from a Webware perspective: http://writewithme.com/Webware/PSP/Documentation/PSP.html Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ From dkennedy@acm.org Wed Jul 25 22:35:05 2001 From: dkennedy@acm.org (David Kennedy) Date: Wed, 25 Jul 2001 21:35:05 GMT Subject: [Tutor] Install Python (python2-2.1-5.i386.rpm) on a Redhat 7.0 system Message-ID: <20010725.21350564@dksy-win98.bconnected.net> the following error is displayed trying to install Python=20 (python2-2.1-5.i386.rpm) on a Redhat 7.0 system=20 error: failed dependencies: libcrypto.so.0.9.6 is needed by python2-2.1-5 libexpat.so.0 is needed by python2-2.1-5 libssl.so.0.9.6 is needed by python2-2.1-5 I installed openssl-0.9.6b.tar, rebooted but the same message is=20 displayed Any help would be greatly appreciated David dkennedy@acm.org From dkennedy@acm.org Wed Jul 25 23:07:35 2001 From: dkennedy@acm.org (David Kennedy) Date: Wed, 25 Jul 2001 22:07:35 GMT Subject: [Tutor] Make python 2.1.1 on Redhat 7.0 Message-ID: <20010725.22073588@dksy-win98.bconnected.net> The following error message is displayed trying to make python 2.1.1 on = Redhat 7.0 gcc -c -g -O2 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H = -o Modules/python.o Modules/python.c In file included from Include/Python.h:54, from Modules/python.c:3: Include/pyport.h:422:2: #error "LONG_BIT definition appears wrong for=20= platform (bad gcc/glibc config?)." make: *** [Modules/python.o] Error 1 Any help would be greatly appreciated David dkennedy@acm.org From kalle@gnupung.net Wed Jul 25 23:35:59 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 26 Jul 2001 00:35:59 +0200 Subject: [Tutor] Install Python (python2-2.1-5.i386.rpm) on a Redhat 7.0 system In-Reply-To: <20010725.21350564@dksy-win98.bconnected.net>; from dkennedy@acm.org on Wed, Jul 25, 2001 at 09:35:05PM +0000 References: <20010725.21350564@dksy-win98.bconnected.net> Message-ID: <20010726003559.B19969@gandalf> Sez David Kennedy: > the following error is displayed trying to install Python > (python2-2.1-5.i386.rpm) on a Redhat 7.0 system > > error: failed dependencies: > libcrypto.so.0.9.6 is needed by python2-2.1-5 > libexpat.so.0 is needed by python2-2.1-5 > libssl.so.0.9.6 is needed by python2-2.1-5 > > I installed openssl-0.9.6b.tar, rebooted but the same message is > displayed You've got to install libcrypto, libssl and libexpat with RPMs. All should be available from Redhat. They're probably called openssl-0.9.6.i386.rpm and expat-x.x.x.i386.rpm. Peace, Kalle -- Free Dmitry Sklyarov! -- http://www.freedmitry.org/ PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD [ Not signed due to lossage. Blame Microsoft Outlook Express. ] From kalle@gnupung.net Wed Jul 25 23:39:39 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 26 Jul 2001 00:39:39 +0200 Subject: [Tutor] Make python 2.1.1 on Redhat 7.0 In-Reply-To: <20010725.22073588@dksy-win98.bconnected.net>; from dkennedy@acm.org on Wed, Jul 25, 2001 at 10:07:35PM +0000 References: <20010725.22073588@dksy-win98.bconnected.net> Message-ID: <20010726003939.C19969@gandalf> Sez David Kennedy: > The following error message is displayed trying to make python 2.1.1 on > Redhat 7.0 > gcc -c -g -O2 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H > -o Modules/python.o Modules/python.c > In file included from Include/Python.h:54, > from Modules/python.c:3: > Include/pyport.h:422:2: #error "LONG_BIT definition appears wrong for > platform (bad gcc/glibc config?)." > make: *** [Modules/python.o] Error 1 This is a prblem with the glibc and gcc in Redhat 7.0. Upgrade to the latest versions from Redhat. They're available on ftp://your-favourite-redhat-mirror/redhat/linux/updates/7.0/en/os/i386/ or something like that. Peace, Kalle -- Free Dmitry Sklyarov! -- http://www.freedmitry.org/ PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD [ Not signed due to lossage. Blame Microsoft Outlook Express. ] From bsass@freenet.edmonton.ab.ca Wed Jul 25 23:52:20 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Wed, 25 Jul 2001 16:52:20 -0600 (MDT) Subject: [Tutor] proj: Python Learning Curve Calculator Message-ID: Hi, This may be a good `newbie to Python, but not programming', kind of project. Some recent posts to c.p.l and the explosion of PEP 238 in my INBOX got me to thinking about how changes to the language affect the learning curve from the perspective of the different groups that use Python (beginners to experts; coders of network, graphics, scientific, etc., problems). It would be kinda neat to be able to order the features/components of Python, assign them weights, degrees of difficulty, time to teach, etc.; the end result being a curve that represents the amount of mental effort and skill required to master more and more of Python. Of course, to be really useful, the PLCC would need to be able merge different points of view into one curve, ... There are probably a number of different ways one can look at a learning curve; 2D and 3D representations would probably be in order, along with user defined units on the axes. The skills needed to pull this off would be in the numerical, graphics, and user interface programming areas. - Bruce p.s. - I think it would be more fun to watch the the various factions try to decide on the one correct LC definition, but not so much fun to actually prompt me to attempt code... just so's I can watch the resulting mayhem. :) From steve@in.cqsl.com Thu Jul 26 09:50:25 2001 From: steve@in.cqsl.com (lonetwin@yahoo.com) Date: Thu, 26 Jul 2001 14:20:25 +0530 (IST) Subject: [Tutor] Any free python cgi hosting servers ?? Message-ID: Hi there everybody !!! I'd like to know if there are any web hosting servers that besides giving a 'lil amount of free space, also allow one to execute python cgi on them (for free). I know 'bout such servers existing for Java servlets, It made me think a python cgi supporting server would be nice, ....and yes I know google is my friend....but I thought of trying the easy way first :D Peace Steve ----------------------------------------- bug, n: A son of a glitch. ----------------------------------------- From alan.gauld@bt.com Thu Jul 26 10:48:10 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 26 Jul 2001 10:48:10 +0100 Subject: [Tutor] A small (but long) introduction to recursion Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE08@mbtlipnt02.btlabs.bt.co.uk> > I absolutely do not understand recursion. Don't worry it really is a weird concept until you get your head around it - then it seems obvious! :-) > I took your example and tried to do some tracing, > but I do not understand how the sum is stored or > returned: > > def addTo(n): > if n == 0: return 0 > return addTo(n-1) + n > > x = addTo(10) addTo(10) returns addTo(9) + 10 addTo(9) returns addTo(8) + 9 addTo(8) returns addTo(7) + 8 addTo(7) returns addTo(6) + 7 addTo(6) returns addTo(5) + 6 addTo(5) returns addTo(4) + 5 addTo(4) returns addTo(3) + 4 addTo(3) returns addTo(2) + 3 addTo(2) returns addTo(1) + 2 addTo(1) returns addTo(0) + 1 addTo(0) returns 0 So now... addTo(1) returns 0 + 1 = 1 addTo(2) returns 1 + 2 = 3 addTo(3) returns 3 + 3 = 6 addTo(4) returns 6 + 4 = 10 addTo(5) returns 10 + 5 = 15 addTo(6) returns 15 + 6 = 21 addTo(7) returns 21 + 7 = 28 addTo(8) returns 28 + 8 = 36 addTo(9) returns 36 + 9 = 45 addTo(10) returns 45 + 10 = 55 Which is the final answer. Does that help? Alan G From lsloan@umich.edu Thu Jul 26 13:10:14 2001 From: lsloan@umich.edu (Lance E Sloan) Date: Thu, 26 Jul 2001 08:10:14 -0400 Subject: [Tutor] how to pass a list or a dictionary variable in cgi script In-Reply-To: Your message of "25 Jul 2001 19:40:31 -0000." <20010725194031.11258.qmail@mailweb25.rediffmail.com> Message-ID: <200107261210.IAA06808@birds.us.itd.umich.edu> "Abhiram Singh Kushwah" wrote: > I'm repeating my question again: > how to pass a list or a dictionary variable from one web page to another page > > Anyway I'v pass a list or dictionary element separatly > from one web page to another page but I want to pass whole list or dictionary > as a single variable. That's not very difficult, really. Let's say you have a list, x, and you want to put it on a page, in a form, so that when the user submits the form, it will be submitted back to the CGI. Here's how you put it in the form: x = ['a', 'b', 'c'] print '' % (x) The resulting HTML will be: Of course, if your list had anything that could cause problems with HTML (for example, >, <, or "), you would have to do something with those before printing. For the CGI to turn it back into a list, you would have to do this: form = cgi.FieldStorage() x = eval(form.getvalue('x')) # Danger! See below. I think I'm using the cgi module correctly here. Of course, you will probably want to do some checking before the call to eval(), like, is there really a field "x" in this form, etc. And after the eval, check that the variable x really points at a list object, like you expected. A few words about security: This is very dangerous! Somebody could cause you a lot of trouble by editing their own copy of the form and putting something else in hidden field "x", then submit it to your CGI. They could put in some Python code that would delete files, crash your computer, just about anything. For example, what would the following do if submitted to this CGI: Assuming your CGI imported the sys module, your CGI would simply exit. For that reason, I do not use this method, even though it seems very clever. I always break lists up and store their elements in separate form fields, all with the same name, of course. I believe cgi.FieldStorage() will automatically assemble them back into a list. You can translate this into use with dictionaries, too. Using the dangerous eval() method, you could easily reassemble your dictionary with one command. Using the safer method, you would convert your dictionary to a list, break it up and put it in the form, then when it's submitted, recreate the list and convert it back into a dictionary. The safer method won't take that much more work and you will feel a lot more comfortable. From Blake.Garretson@dana.com Thu Jul 26 14:54:56 2001 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Thu, 26 Jul 2001 09:54:56 -0400 Subject: [Tutor] Any free python cgi hosting servers ?? Message-ID: The only one I know of is www.hobbiton.org. It is basically run by two guys for the fun of it. The free account provides a shell, email, and some web space. They do have pop up ads to cover their costs, but for $5 a year you can get rid of them. I use it as a testing ground for my Python CGI programming. Since this is not really a professional outfit, sometimes the server reliability can be flaky. -Blake >Date: Thu, 26 Jul 2001 14:20:25 +0530 (IST) >From: "lonetwin@yahoo.com" > >Hi there everybody !!! > I'd like to know if there are any web hosting servers that besides giving a >'lil amount of free space, also allow one to execute python cgi on them (for >free). I know 'bout such servers existing for Java servlets, It made me think a >python cgi supporting server would be nice, ....and yes I know google is my >friend....but I thought of trying the easy way first :D > >Peace >Steve From rob@jam.rr.com Thu Jul 26 15:25:03 2001 From: rob@jam.rr.com (Rob Andrews) Date: Thu, 26 Jul 2001 09:25:03 -0500 Subject: [Tutor] Any free python cgi hosting servers ?? In-Reply-To: Message-ID: Here's the small but growing list of Python-friendly ISPs on Useless. Perhaps some of these companies have what you need. Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # lonetwin@yahoo.com # Sent: Thursday, July 26, 2001 3:50 AM # To: Python Tutor list # Subject: [Tutor] Any free python cgi hosting servers ?? # # # Hi there everybody !!! # I'd like to know if there are any web hosting servers that # besides giving a # 'lil amount of free space, also allow one to execute python cgi # on them (for # free). I know 'bout such servers existing for Java servlets, It # made me think a # python cgi supporting server would be nice, ....and yes I know # google is my # friend....but I thought of trying the easy way first :D # # Peace # Steve # # ----------------------------------------- # bug, n: # A son of a glitch. # ----------------------------------------- # # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From dsh8290@rit.edu Thu Jul 26 17:04:59 2001 From: dsh8290@rit.edu (dman) Date: Thu, 26 Jul 2001 12:04:59 -0400 Subject: [Tutor] ping? In-Reply-To: ; from mike@daboyz.org on Wed, Jul 25, 2001 at 11:34:37AM -0700 References: Message-ID: <20010726120459.H29257@harmony.cs.rit.edu> On Wed, Jul 25, 2001 at 11:34:37AM -0700, Mike Barrett wrote: | I was just wondering if anyone out there has a good ping module | they'd be willing to share? I found one off of the Vaults, written by | Jeremy Hylton, but it's pretty old (1997). Have you tried it? I imagine that the ping protocol is pretty old and hasn't changed recently. -D From sheila@thinkspot.net Thu Jul 26 17:12:58 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 26 Jul 2001 09:12:58 -0700 Subject: [Tutor] ping? In-Reply-To: <20010726120459.H29257@harmony.cs.rit.edu> References: <20010726120459.H29257@harmony.cs.rit.edu> Message-ID: <21523FD214F@kserver.org> On Thu, 26 Jul 2001 12:04:59 -0400, dman wrote about Re: [Tutor] ping?: :On Wed, Jul 25, 2001 at 11:34:37AM -0700, Mike Barrett wrote: :| I was just wondering if anyone out there has a good ping module :| they'd be willing to share? I found one off of the Vaults, written by :| Jeremy Hylton, but it's pretty old (1997). : :Have you tried it? I imagine that the ping protocol is pretty old and :hasn't changed recently. All this talk about the ping protocol...I have to share... Go to Amazon at this link: http://www.amazon.com/exec/obidos/ASIN/0140502416/qid=996163814/sr=1-2/ref=sc_b_2/103-3496915-6583040 And read the reader reviews, the FIRST ONE (that has the comment "4114 of 4201 people found the following review helpful" ) It is SUCH a hoot! The first time I read it, I laughed SOOO hard! (It helps if you are familiar with the actual story itself, but apparently that isn't completely necessary, either.) A couple of months ago, I finally ordered the book to read to my four-year-old. So she is already starting to learn about ping. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From fleet@teachout.org Thu Jul 26 17:30:13 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Thu, 26 Jul 2001 12:30:13 -0400 (EDT) Subject: [Tutor] Clear Screen Message-ID: NO! WAIT! I know how to do it! I've written a function clear() as follows: def clear(): import os cls=os.popen("clear").read() eval(cls) It works fine except it leaves two lines at the top of the screen (a minor irritant - they usually display "SyntaxError" :) ). I would dearly love to assign this function to "cls" but (apparently due to the "eval") I've had no luck. Any hints - or am I stuck with "clear()" or (changing things around in the function) "cls()?" - fleet - From dsh8290@rit.edu Thu Jul 26 17:42:20 2001 From: dsh8290@rit.edu (dman) Date: Thu, 26 Jul 2001 12:42:20 -0400 Subject: [Tutor] Clear Screen In-Reply-To: ; from fleet@teachout.org on Thu, Jul 26, 2001 at 12:30:13PM -0400 References: Message-ID: <20010726124220.A29469@harmony.cs.rit.edu> On Thu, Jul 26, 2001 at 12:30:13PM -0400, fleet@teachout.org wrote: | NO! WAIT! I know how to do it! | | I've written a function clear() as follows: | | def clear(): | import os | cls=os.popen("clear").read() | eval(cls) eval()ing stuff can be dangerous unless you know what you are eval()ing. (Suppose you got 'open( "/file/to/destroy" , "w" )') | It works fine except it leaves two lines at the top of the screen (a minor | irritant - they usually display "SyntaxError" :) ). That means that the stuff you got from the pipe to 'clear' wasn't a valid Python expression. Why do you want to eval() it? Simply os.system( "clear") will work. Also note that it only works on Unix systems -- DOS doesn't have a 'clear' command. -D From kalle@gnupung.net Thu Jul 26 17:45:13 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 26 Jul 2001 18:45:13 +0200 Subject: [Tutor] Clear Screen In-Reply-To: ; from fleet@teachout.org on Thu, Jul 26, 2001 at 12:30:13PM -0400 References: Message-ID: <20010726184513.B27157@gandalf> Sez fleet@teachout.org: > I've written a function clear() as follows: > > def clear(): > import os > cls=os.popen("clear").read() > eval(cls) Why eval? eval() takes a string argument and evaluates it as a python expression. Most often, the output of the system "clear" command isn't a valid python expression... My guess is that you really want def clear(): import os, sys cls = os.popen("clear").read() sys.stdout.write(cls) or, perhaps even better def clear(): import os os.system("clear") This version can also be called cls without problems. Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freedmitry.org/ From rob@jam.rr.com Tue Jul 24 23:10:48 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 24 Jul 2001 17:10:48 -0500 Subject: [Tutor] How to pull a random element from a list? In-Reply-To: <01072415475802.00916@localhost.localdomain> Message-ID: Take a look at the random and whrandom modules for a number of ways to go about it. Here is an example, although probably a sloppy one, of the variable someSpam being used to call a random item from the list spam. PythonWin 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (MarkH@ActiveState.com) - see 'Help/About PythonWin' for further copyright information. >>> import whrandom >>> spam = ["parrot", "dead", "inquisition"] >>> spamLength = (len(spam))-1 >>> randomSpam = whrandom.randint(0, spamLength) >>> someSpam = spam[randomSpam] >>> someSpam 'inquisition' A peek at the whrandom documentation (http://www.python.org/doc/current/lib/module-whrandom.html) might clarify the steps quite a bit. Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # steve # Sent: Tuesday, July 24, 2001 4:48 PM # To: tutor@python.org # Subject: [Tutor] How to pull a random element from a list? # # # Greetings # # I'm trying to figure out how the heck to pull an element from a list or # dictionary at random. I have a list of words and need to be able # to pull one # at random. (Yet to decide if a list is the right way to do it. Thoughts?) # # I've messed around with my limited knowledge, but haven't been # able to figure # out how to do it. I was going to use a random number generator to # pick which # element to retrieve. # # I am at your mercy oh mighty Pythonistas! HELP! # # -- # Steve - Editor - www.formulaoneupdate.com # -------------------------------- # "Trish, she has a paddle." - Jeff Hardy # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From rob@jam.rr.com Thu Jul 26 19:49:25 2001 From: rob@jam.rr.com (Rob Andrews) Date: Thu, 26 Jul 2001 13:49:25 -0500 Subject: [Tutor] How to pull a random element from a list? In-Reply-To: Message-ID: Wow. I sent this message a day or two ago. These things can sure bounce around. Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # Rob Andrews # Sent: Tuesday, July 24, 2001 5:11 PM # To: steve; tutor@python.org # Subject: RE: [Tutor] How to pull a random element from a list? # # # Take a look at the random and whrandom modules for a number of ways to go # about it. Here is an example, although probably a sloppy one, of the # variable someSpam being used to call a random item from the list spam. # # PythonWin 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32. # Portions Copyright 1994-2001 Mark Hammond (MarkH@ActiveState.com) - see # 'Help/About PythonWin' for further copyright information. # >>> import whrandom # >>> spam = ["parrot", "dead", "inquisition"] # >>> spamLength = (len(spam))-1 # >>> randomSpam = whrandom.randint(0, spamLength) # >>> someSpam = spam[randomSpam] # >>> someSpam # 'inquisition' # # A peek at the whrandom documentation # (http://www.python.org/doc/current/lib/module-whrandom.html) might clarify # the steps quite a bit. # # Rob # # Your one-stop shop for newbie source code! # Useless Python: http://www.lowerstandard.com/python/ # # # -----Original Message----- # # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # # steve # # Sent: Tuesday, July 24, 2001 4:48 PM # # To: tutor@python.org # # Subject: [Tutor] How to pull a random element from a list? # # # # # # Greetings # # # # I'm trying to figure out how the heck to pull an element from a list or # # dictionary at random. I have a list of words and need to be able # # to pull one # # at random. (Yet to decide if a list is the right way to do it. # Thoughts?) # # # # I've messed around with my limited knowledge, but haven't been # # able to figure # # out how to do it. I was going to use a random number generator to # # pick which # # element to retrieve. # # # # I am at your mercy oh mighty Pythonistas! HELP! # # # # -- # # Steve - Editor - www.formulaoneupdate.com # # -------------------------------- # # "Trish, she has a paddle." - Jeff Hardy # # # # _______________________________________________ # # 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 rear@sirius.com Thu Jul 26 21:27:39 2001 From: rear@sirius.com (Bob Rea) Date: Thu, 26 Jul 2001 13:27:39 -0700 Subject: [Tutor] Clear Screen In-Reply-To: <20010726124220.A29469@harmony.cs.rit.edu> References: <20010726124220.A29469@harmony.cs.rit.edu> Message-ID: <01072613273901.00991@gandalf> On Thursday 26 July 2001 09:42 am, Da MANwrote: > Unix systems -- DOS doesn't have a 'clear' command. I seem to remember a DOS CLS command. No DOS refs hndy, too long ago. But then I could be totally incorrect. -- Bob Rea Fear of Hell is pernicious; So is fear of Heaven. rear@sirius.com http://www.sirius.com/~rear From dsh8290@rit.edu Thu Jul 26 21:45:21 2001 From: dsh8290@rit.edu (dman) Date: Thu, 26 Jul 2001 16:45:21 -0400 Subject: [Tutor] Clear Screen In-Reply-To: <01072613273901.00991@gandalf>; from rear@sirius.com on Thu, Jul 26, 2001 at 01:27:39PM -0700 References: <20010726124220.A29469@harmony.cs.rit.edu> <01072613273901.00991@gandalf> Message-ID: <20010726164520.A29667@harmony.cs.rit.edu> On Thu, Jul 26, 2001 at 01:27:39PM -0700, Bob Rea wrote: | On Thursday 26 July 2001 09:42 am, Da MANwrote: | > Unix systems -- DOS doesn't have a 'clear' command. | | I seem to remember a DOS CLS command. No DOS refs hndy, too long ago. Yes, DOS has the command spelled 'cls'. There's the problem with making a general "clear" function : on *nix it is spelled 'clear' and DOS it is spelled 'cls'. If you use ncurses, though, you don't have to worry about it -- it will work for every terminal. OTOH DOS doesn't have ncurses (unless you want to use cygwin). There is Fredrik Lundh's pure-python implementation though it isn't a complete ncurses. -D From csmith@blakeschool.org Thu Jul 26 23:02:30 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Thu, 26 Jul 2001 17:02:30 -0500 Subject: [Tutor] Shadow error Message-ID: Can you help me out here? I tried to create a function that would let me get function that would round to the number of desired digits. This is what I tried: from random import random as rnd l=[rnd() for i in range(3)] def dig(n=2): return lambda x:round(x,n) print map(dig(2),l) Here's what I got: :5: SyntaxWarning: local name 'n' in 'dig' shadows use of 'n' as global in nested scope 'lambda' [0.5, 0.28000000000000003, 0.84999999999999998] So it worked, but there was the complaint which I don't know how to make go away. Note: I know I can do the same thing like this: print map(lambda x:round(x,2),l) or this print [round(li,2) for li in l] #aren't list comp's nice :-) but I have generated the above error before and would like to know what I am doing wrong. /c From kalle@gnupung.net Thu Jul 26 23:27:00 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Fri, 27 Jul 2001 00:27:00 +0200 Subject: [Tutor] Shadow error In-Reply-To: ; from csmith@blakeschool.org on Thu, Jul 26, 2001 at 05:02:30PM -0500 References: Message-ID: <20010727002700.B30010@gandalf> Sez Christopher Smith: > :5: SyntaxWarning: local name 'n' in 'dig' shadows > use of 'n' as global in nested scope 'lambda' > [0.5, 0.28000000000000003, 0.84999999999999998] > > So it worked, but there was the complaint which I don't know how to make > go away. This warning was introduced in Python 2.1 together with new scoping features. Before, then variable n in the function dig wouldn't have been visible inside the lambda, and the n in the lambda would have been a reference to a global n. With the new nested scoping, which will become default in 2.2, n in dig is visible, which is changed behaviour between versions. Thus a warning is issued, to notify programmers that their code might have changed meaning. The warning will go away with time, perhaps in 2.4 or something like that. It's also possible to tell it to go away by using the warnings module in some way. I'm not sure exactly how, I've never needed it myself, but take a look at the docs: http://www.python.org/doc/current/lib/module-warnings.html Hope that made sense... Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freedmitry.org/ From dyoo@hkn.eecs.berkeley.edu Thu Jul 26 23:32:02 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 Jul 2001 15:32:02 -0700 (PDT) Subject: [Tutor] Shadow error In-Reply-To: Message-ID: On Thu, 26 Jul 2001, Christopher Smith wrote: > Can you help me out here? I tried to create a function that would let me No problem; let's take a look. > get function that would round to the number of desired digits. This > is what I tried: > > from random import random as rnd > > l=[rnd() for i in range(3)] > > def dig(n=2): > return lambda x:round(x,n) > print map(dig(2),l) > > Here's what I got: > > :5: SyntaxWarning: local name 'n' in 'dig' shadows > use of 'n' as global in nested scope 'lambda' > [0.5, 0.28000000000000003, 0.84999999999999998] The "problem" lies in the definition here: > def dig(n=2): > return lambda x:round(x,n) Python, by default, isn't "lexically scoped": that is, the only variables that the lambda knows about is 'x'. Nested functions, then, aren't allowed to borrow functions from the nester. To fix this, we could do a silly trick like this: ### def dig(n=2): return lambda x, n=n:round(x,n) ### which works on the principle that we're taking advantage of default arguments. It is a little ugly, but there are alternatives. As of Python 2.1, you can get Python to do lexical scoping by using a funny line: ### from __future__ import nested_scopes ### We're using stuff from the future. *grin* If you put that line in the top of your file, the warning should disappear. If you have questions, please feel free to ask them. From ak@silmarill.org Thu Jul 26 23:29:43 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Thu, 26 Jul 2001 18:29:43 -0400 Subject: [Tutor] Shadow error In-Reply-To: <"from kalle"@gnupung.net> References: <20010727002700.B30010@gandalf> Message-ID: <20010726182943.A3504@sill.silmarill.org> On Fri, Jul 27, 2001 at 12:27:00AM +0200, Kalle Svensson wrote: > Sez Christopher Smith: > > :5: SyntaxWarning: local name 'n' in 'dig' shadows > > use of 'n' as global in nested scope 'lambda' > > [0.5, 0.28000000000000003, 0.84999999999999998] > > > > So it worked, but there was the complaint which I don't know how to make > > go away. > > This warning was introduced in Python 2.1 together with new scoping > features. Before, then variable n in the function dig wouldn't have been > visible inside the lambda, and the n in the lambda would have been a > reference to a global n. With the new nested scoping, which will become > default in 2.2, n in dig is visible, which is changed behaviour between > versions. Thus a warning is issued, to notify programmers that their code > might have changed meaning. The warning will go away with time, perhaps in > 2.4 or something like that. > > It's also possible to tell it to go away by using the warnings module in > some way. I'm not sure exactly how, I've never needed it myself, but take a I think it's from __future__ import nested_scopes at the top of the file. > look at the docs: > http://www.python.org/doc/current/lib/module-warnings.html > > Hope that made sense... > > Peace, > Kalle > -- > Free Dmitry Sklyarov! - http://www.freedmitry.org/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From kalle@gnupung.net Fri Jul 27 00:09:06 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Fri, 27 Jul 2001 01:09:06 +0200 Subject: [Tutor] Shadow error In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Thu, Jul 26, 2001 at 03:32:02PM -0700 References: Message-ID: <20010727010906.C30010@gandalf> Sez Danny Yoo: [about nested scopes and stuff] > We're using stuff from the future. *grin* If you put that line in the top > of your file, the warning should disappear. If you have questions, please > feel free to ask them. I'd like to ask a question, anyway. Why is Cristopher's code working? When I try it with Python 2.1 I get [ kalle aragorn ~ 00:59:52 ]$ python2.1 scopetest.py scopetest.py:5: SyntaxWarning: local name 'n' in 'dig' shadows use of 'n' as global in nested scope 'lambda' def dig(n=2): Traceback (most recent call last): File "scopetest.py", line 8, in ? print map(dig(2),l) File "scopetest.py", line 6, in return lambda x:round(x,n) NameError: global name 'n' is not defined without from __future__ import nested_scopes, and with it I get [ kalle aragorn ~ 01:00:00 ]$ python2.1 scopetest.py [0.14999999999999999, 0.56000000000000005, 0.17999999999999999] no warning. I have no idea how I'm supposed to get both warning and result, except perhaps by using 2.2? Please enlighten me. Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freedmitry.org/ From sheila@thinkspot.net Fri Jul 27 02:07:35 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 26 Jul 2001 18:07:35 -0700 Subject: [Tutor] Baffled: why doesn't range work? Message-ID: <1A291E5083B@kserver.org> OK, here I think I know what I'm doing...? Done enough Python now that I feel pretty competent. Well, surprise. I can't get something really simple to work. I know I'm going to feel dumb when someone points out my error. OK, here is a module, called matrixprog.py: --------------------------------------------------- class mtrx: def __init__(self, numRows = 1, numCols = 1, initVal=0): self.numRows = numRows self.numCols = numCols self.data = {} if initVal != 0: for i in range(1, numRows + 1, 1): for j in range(1, numCols + 1, 1): self.data[(i, j)] = initVal def Display(self): for i in range(1, self.numRows + 1, 1): for j in range(1, self.numCols + 1, 1): if self.data.has_key( (i, j) ): print self.data[ (i, j) ], else: print str(0), print --------------------------------------------------- Here is an interactive session using the module: --------------------------------------------------- >>> import matrixprog >>> A = matrixprog.mtrx(2, 5, .2) >>> A.Display() 0.2 0.2 0.2 0.2 >>> A.data {(1, 6): 0.20000000000000001, (3, 6): 0.20000000000000001, (3, 1): 0.20000000000000001, (1, 1): 0.20000000000000001} >>> --------------------------------------------------- Now, something is very wrong. The matrix A should look like this: 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 Where did the six missing elements of my matrix go? I've tried a bunch of different things, but I can't get this stupid matrix to insert all the required elements. It seems to skip over most of them and just do the four corners of the matrix? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From ak@silmarill.org Fri Jul 27 02:15:30 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Thu, 26 Jul 2001 21:15:30 -0400 Subject: [Tutor] Baffled: why doesn't range work? In-Reply-To: <"from sheila"@thinkspot.net> References: <1A291E5083B@kserver.org> Message-ID: <20010726211530.A4189@sill.silmarill.org> On Thu, Jul 26, 2001 at 06:07:35PM -0700, Sheila King wrote: > OK, here I think I know what I'm doing...? Done enough Python now that I > feel pretty competent. > > Well, surprise. I can't get something really simple to work. I know I'm > going to feel dumb when someone points out my error. > > OK, here is a module, called matrixprog.py: > > --------------------------------------------------- > class mtrx: > def __init__(self, numRows = 1, numCols = 1, initVal=0): > self.numRows = numRows > self.numCols = numCols > self.data = {} > if initVal != 0: > for i in range(1, numRows + 1, 1): > for j in range(1, numCols + 1, 1): > self.data[(i, j)] = initVal > > def Display(self): > for i in range(1, self.numRows + 1, 1): > for j in range(1, self.numCols + 1, 1): > if self.data.has_key( (i, j) ): > print self.data[ (i, j) ], > else: > print str(0), > print > --------------------------------------------------- > > Here is an interactive session using the module: > > --------------------------------------------------- > >>> import matrixprog > >>> A = matrixprog.mtrx(2, 5, .2) > >>> A.Display() > 0.2 0.2 > 0.2 0.2 > >>> A.data > {(1, 6): 0.20000000000000001, (3, 6): 0.20000000000000001, (3, 1): > 0.20000000000000001, (1, 1): 0.20000000000000001} > >>> > --------------------------------------------------- > > Now, something is very wrong. The matrix A should look like this: > > 0.2 0.2 0.2 0.2 0.2 > 0.2 0.2 0.2 0.2 0.2 > > Where did the six missing elements of my matrix go? I've tried a bunch > of different things, but I can't get this stupid matrix to insert all > the required elements. It seems to skip over most of them and just do > the four corners of the matrix? It works fine here: >>> import mt >>> a = mt.mtrx(2,5,.2) >>> a.Display() 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 Python 2.1 on Debian linux. > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From brett@earthlight.co.nz Fri Jul 27 02:43:14 2001 From: brett@earthlight.co.nz (Brett Shand) Date: Fri, 27 Jul 2001 13:43:14 +1200 Subject: [Tutor] Baffled: why doesn't range work? In-Reply-To: <1A291E5083B@kserver.org> Message-ID: <3B616FF2.10306.B276F3A@localhost> > > Now, something is very wrong. The matrix A should look like this: > > 0.2 0.2 0.2 0.2 0.2 > 0.2 0.2 0.2 0.2 0.2 works fine for me too: ------------------------ >>> import matrix >>> A = matrix.mtrx(2, 5, .2) >>> A.Display() 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 >>> ------------------------- brett From sheila@thinkspot.net Fri Jul 27 03:29:22 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 26 Jul 2001 19:29:22 -0700 Subject: [Tutor] Baffled: why doesn't range work? In-Reply-To: <3B616FF2.10306.B276F3A@localhost> References: <1A291E5083B@kserver.org> <3B616FF2.10306.B276F3A@localhost> Message-ID: <5C6386B1A@kserver.org> OK, it's working fine for me, now, too. Uh...my machine locked up a few minutes ago. Then I had to reboot. (Love that Win98.) Now it works. OK. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Fri, 27 Jul 2001 13:43:14 +1200, "Brett Shand" wrote about Re: [Tutor] Baffled: why doesn't range work?: :> :> Now, something is very wrong. The matrix A should look like this: :> :> 0.2 0.2 0.2 0.2 0.2 :> 0.2 0.2 0.2 0.2 0.2 : :works fine for me too: : :------------------------ :>>> import matrix :>>> A = matrix.mtrx(2, 5, .2) :>>> A.Display() :0.2 0.2 0.2 0.2 0.2 :0.2 0.2 0.2 0.2 0.2 :>>> :------------------------- : :brett From fleet@teachout.org Fri Jul 27 03:51:59 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Thu, 26 Jul 2001 22:51:59 -0400 (EDT) Subject: [Tutor] Clear Screen Message-ID: >Date: Thu, 26 Jul 2001 18:45:13 +0200 >From: Kalle Svensson > >Why eval? eval() takes a string argument and evaluates it as a python >expression. Most often, the output of the system "clear" command isn't a >valid python expression... >My guess is that you really want > >def clear(): > import os, sys > cls = os.popen("clear").read() > sys.stdout.write(cls) This works! >or, perhaps even better > >def clear(): > import os > os.system("clear") This works like *my* clear() function works - leaves two lines at the top of the screen. ?? >This version can also be called cls without problems. If I write it as def cls(): why would there be a problem with any version? I was hoping there would be some way to change >>>cls() to simply >>>cls - but this is close enough! :) Thanks all. >Free Dmitry Sklyarov! - http://www.freedmitry.org/ Right on! - fleet - From csmith@blakeschool.org Fri Jul 27 04:10:47 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Thu, 26 Jul 2001 22:10:47 -0500 Subject: [Tutor] Re: Baffled: why doesn't range work? Message-ID: Sheila King wrote: | | OK, here I think I know what I'm doing...? Done enough Python now that | I feel pretty competent. | | Now, something is very wrong. The matrix A should look like this: | | 0.2 0.2 0.2 0.2 0.2 | 0.2 0.2 0.2 0.2 0.2 | That's exactly what I saw when I cut and pasted your code into my interpreter. :-) *Except*, I didn't save this class and load it like a module. But I have been working on some class material myself and ran into this sort of problem and found help from the following FAQ entry: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.008.htp 4.8. When I have imported a module, then edit it, and import it again (into the same Python process), the changes don't seem to take place. What is going on? For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. (Otherwise a program consisting of many modules, each of which imports the same basic module, would read the basic module over and over again.) To force rereading of a changed module, do this: import modname reload(modname) Warning: this technique is not 100% fool-proof. In particular, modules containing statements like from modname import some_objects will continue to work with the old version of the imported objects. ---- So try the reload() command after your import command...and, of course, be sure that the version that is being loaded is the one that you have been modifying. (I had an alias pointing to my module on a different disk and couldn't figure out why my modifications--even with the reload-- weren't working. /c From sheila@thinkspot.net Fri Jul 27 04:20:33 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 26 Jul 2001 20:20:33 -0700 Subject: [Tutor] Re: Baffled: why doesn't range work? In-Reply-To: References: Message-ID: <34B6826547@kserver.org> On Thu, 26 Jul 2001 22:10:47 -0500, "Christopher Smith" wrote about [Tutor] Re: Baffled: why doesn't range work?: :But I have been working on :some class material myself and ran into this sort of problem :and found help from the following FAQ entry: : :http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.008.htp : :4.8. When I have imported a module, then edit it, :and import it again (into the same Python process), :the changes don't seem to take place. What is going on? :For reasons of efficiency as well as consistency, Python only reads :the module file on the first time a module is imported. (Otherwise :a program consisting of many modules, each of which imports the :same basic module, would read the basic module over and over again.) :To force rereading of a changed module, do this: : : : : import modname : reload(modname) Thanks. I did do this: del modname import modname Is that not as good as reload(modname) ??? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From csmith@blakeschool.org Fri Jul 27 04:34:51 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Thu, 26 Jul 2001 22:34:51 -0500 Subject: [Tutor] Re: Shadow error Message-ID: Kalle Svensson wrote: | | | I'd like to ask a question, anyway. Why is Cristopher's code working? | When I try it with Python 2.1 I get | | [ kalle aragorn ~ 00:59:52 ]$ python2.1 scopetest.py | scopetest.py:5: SyntaxWarning: local name 'n' in 'dig' shadows use of | 'n' as global in nested scope 'lambda' | | without from __future__ import nested_scopes, and with it I get | | [ kalle aragorn ~ 01:00:00 ]$ python2.1 scopetest.py | [0.14999999999999999, 0.56000000000000005, 0.17999999999999999] | | no warning. I have no idea how I'm supposed to get both warning and | result, except perhaps by using 2.2? | Please enlighten me. When I retried it (after having ended my session for the day) I, too, got a traceback error and it wouldn't run at all. And I thought that I noticed during my experimenting that sometimes I would get this error. I suspect it has something to do with the environment becoming corrupted after making modifications. This behavior hasn't been consistent enough for me to get a handle on. Maybe, too, I did a run where I didn't call the function with problems but got the error. Like happens with the following: Here's one of the other scripts that invokes the error. I just tried it and did not get a traceback but did get the warning: :13: SyntaxWarning: local name 'm' in 'mtrx' shadows use of 'm' as global in nested scope 'a' def mtrx(m): def a(i,j): return m[i][j] return a l=[[1,2],[3,4]] a=mtrx(l) # no traceback unless I uncomment the next line: # print a(1,2) Here is a version that works without warnings. def mtrx(l): '''Returns a function which will accessess l[i][j] as l(i,j). ''' def a(i,j,m=l): return m[i][j] return a l=[[1,2],[3,4]] a=mtrx(l) print a(1,1) # results in # 4 /c From dsh8290@rit.edu Fri Jul 27 05:09:08 2001 From: dsh8290@rit.edu (dman) Date: Fri, 27 Jul 2001 00:09:08 -0400 Subject: [Tutor] Re: Baffled: why doesn't range work? In-Reply-To: <34B6826547@kserver.org>; from sheila@thinkspot.net on Thu, Jul 26, 2001 at 08:20:33PM -0700 References: <34B6826547@kserver.org> Message-ID: <20010727000907.A29935@harmony.cs.rit.edu> On Thu, Jul 26, 2001 at 08:20:33PM -0700, Sheila King wrote: | On Thu, 26 Jul 2001 22:10:47 -0500, "Christopher Smith" | wrote about [Tutor] Re: Baffled: why doesn't | range work?: | : import modname | : reload(modname) | | Thanks. I did do this: | | del modname | import modname | | Is that not as good as | reload(modname) | | ??? Nope -- the 'del' only tweaks the current namespace. Modules are never unloaded except when the interpreter exits. As a result the subsequent import sees that already loaded module and only performs a namespace modification. The reload() instructs the interpreter to look to the disk to load the module again even though it was already loaded before. -D From dsh8290@rit.edu Fri Jul 27 05:14:15 2001 From: dsh8290@rit.edu (dman) Date: Fri, 27 Jul 2001 00:14:15 -0400 Subject: [Tutor] Re: Shadow error In-Reply-To: ; from csmith@blakeschool.org on Thu, Jul 26, 2001 at 10:34:51PM -0500 References: Message-ID: <20010727001415.B29935@harmony.cs.rit.edu> On Thu, Jul 26, 2001 at 10:34:51PM -0500, Christopher Smith wrote: | :13: SyntaxWarning: local name 'm' in 'mtrx' | shadows use of 'm' as global in nested scope 'a' | | def mtrx(m): | def a(i,j): | return m[i][j] | return a | l=[[1,2],[3,4]] | a=mtrx(l) | # no traceback unless I uncomment the next line: | # print a(1,2) In this example you are relying on the local (argument) 'm' from funciton mtrx to be available inside the nested function 'a'. In old python (pre 2.1 with a __future__ statement) scopes were not nested so the 'm' inside 'a' would have referred to a global variable. If you put 'from __future__ import nested_scopes' at the top of the file it would work as expected (or use version 2.2 as nested scopes are mandatory then). | Here is a version that works without warnings. | | def mtrx(l): | '''Returns a function which will accessess l[i][j] as l(i,j). | ''' | def a(i,j,m=l): | return m[i][j] | return a | | l=[[1,2],[3,4]] | a=mtrx(l) | print a(1,1) | | # results in | # 4 In this version you used a different name in the inner vs. outer functions (hence no warnings) and explicitly created a variable that is local to 'a' which is why it works. -D From sheila@thinkspot.net Fri Jul 27 05:18:53 2001 From: sheila@thinkspot.net (Sheila King) Date: Thu, 26 Jul 2001 21:18:53 -0700 Subject: [Tutor] Re: Baffled: why doesn't range work? In-Reply-To: <20010727000907.A29935@harmony.cs.rit.edu> References: <34B6826547@kserver.org> <20010727000907.A29935@harmony.cs.rit.edu> Message-ID: <6A2A625887@kserver.org> On Fri, 27 Jul 2001 00:09:08 -0400, dman wrote about Re: [Tutor] Re: Baffled: why doesn't range work?: :| Thanks. I did do this: :| :| del modname :| import modname :| :| Is that not as good as :| reload(modname) :| :| ??? : :Nope -- the 'del' only tweaks the current namespace. Modules are :never unloaded except when the interpreter exits. As a result the :subsequent import sees that already loaded module and only performs a :namespace modification. The reload() instructs the interpreter to :look to the disk to load the module again even though it was already :loaded before. OK. That was my problem, then. I originally didn't have the word "range" in the lines: for i in range(1, numRows + 1, 1): for j in range(1, numCols + 1, 1): Failure of the module to reload after I modified the code would completely explain the output I was getting. OK, I learned another Python fact today. ;) -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sendme105@hotmail.com Fri Jul 27 08:09:53 2001 From: sendme105@hotmail.com (James) Date: Fri, 27 Jul 2001 00:09:53 -0700 Subject: [Tutor] help with _winreg Message-ID: I'm experimenting with _winreg on python 2.1, and I'm having problems with the RegLoadKey(key, sub_key, file_name) function. I get "NameError: name 'RegLoadKey' is not defined." On a hunch I tried LoadKey(key, sub_key, file_name) and it appeared to work. But when I checked the registry, I got an unexpected result. My code: rKey= ConnectRegistry(None,HKEY_LOCAL_MACHINE) aKey=OpenKey(rKey, r"Software\testkey1") dirKey=OpenKey(rKey, r"Software") SaveKey(aKey, r"c:\python\Scripts\tmpkey") LoadKey(rKey, r"SOFTWARE\testkey2", r"c:\python\Scripts\tmpkey") Result: I open regedit, and in the HKEY_LOCAL_MACHINE key/folder I get the expected 'Software' key/folder, then just below it I get a folder named "SOFTWARE\testkey2" that won't open and won't delete. If I reset the computer and check again, it is gone. (I also tried to use LoadKey(dirKey, r"testkey2", r"c:\python\Scripts\tmpkey") to no avail, the function objecting to dirKey as input.) Also, regarding 'DeleteKey(key, sub_key)' the documentation says : "sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the *key may not have subkeys.*" However, if I use this function to delete 'testkey1' above, it appears to work even if 'testkey1' has subkeys. As in: DeleteKey(dirKey, "testkey1") So I think I'm missing something... What I'm trying to accomplish: I want to rename HKEY_LOCAL_MACHINE\SOFTWARE\testkey1 to HKEY_LOCAL_MACHINE\SOFTWARE\testkey2. Maybe there are easier ways to do this? Thanks. From ak@silmarill.org Fri Jul 27 09:22:50 2001 From: ak@silmarill.org (Andrei Kulakov) Date: Fri, 27 Jul 2001 04:22:50 -0400 Subject: [Tutor] Clear Screen In-Reply-To: <"from fleet"@teachout.org> References: Message-ID: <20010727042250.A5182@sill.silmarill.org> On Thu, Jul 26, 2001 at 10:51:59PM -0400, fleet@teachout.org wrote: > >Date: Thu, 26 Jul 2001 18:45:13 +0200 > >From: Kalle Svensson > > > >Why eval? eval() takes a string argument and evaluates it as a python > >expression. Most often, the output of the system "clear" command isn't a > >valid python expression... > >My guess is that you really want > > > >def clear(): > > import os, sys > > cls = os.popen("clear").read() > > sys.stdout.write(cls) > > This works! > > >or, perhaps even better > > > >def clear(): > > import os > > os.system("clear") > > This works like *my* clear() function works - leaves two lines at the top > of the screen. ?? Humm, that's odd.. Well, if you run it like that in an interpreter, it does print out return value (0), you may get rid of it by doing throw_away = os.system('clear'). In a script, os.system('clear') shouldn't leave any lines at the top, and in fact I'm using it in my mp3 player cymbaline (plug, plug!), url in my sig, and it works great. [snip] -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: http://silmarill.org/cymbaline From koen@behindthesofa.dhs.org Fri Jul 27 10:52:04 2001 From: koen@behindthesofa.dhs.org (Koen Bossers) Date: Fri, 27 Jul 2001 11:52:04 +0200 Subject: [Tutor] piping continuous output References: <3B5EC5BB.8D6C3CD1@behindthesofa.dhs.org> <3B5ECB44.8B0C1DFB@behindthesofa.dhs.org> Message-ID: <3B6139C4.19F2D4E2@behindthesofa.dhs.org> OK, for your information, I solved the problem. It appears that print_messages.py does not print immediately after the print statement due to the popen2 routine. Adding the line 'sys.stdout.flush()' after the print statement made the delays dissappear. Cheers, Koen Bossers Koen Bossers wrote: > By the way, adding time.sleep(11) before entering the loop eliminates the time differences > between outputs. They're nicely aligned at 0.2 secs. right now. Only that darned 10 second > pause.... > > Koen Bossers wrote: > > > sill@optonline.net wrote: > > > > > Look at pctail.py program on vaults of parnassus, it does something > > similar > > > (reads from growing log files). > > > > Not what I had in mind. I want to avoid creating temporary files. That's > > why I > > chose popen, else I would have used something like os.system('command >> > > > > /tmp/tempfile') or something. > > > > OK second try: some VERY weird behaviour here: > > > > [print_messages.py] > > #! /usr/bin/python > > > > import time, os > > > > counter = 0 > > while counter < 5000: > > > > print '%d'%counter > > > > time.sleep(0.01) > > counter = counter + 1 > > > > [popentest.py] > > #! /usr/bin/python > > > > ## test popen with continuing output > > > > import os, time, string > > import popen2 > > > > child = popen2.Popen3('./print_messages.py') > > output = child.fromchild > > > > count = 1 > > > > print "starting...", os.getpid() > > listing = '' > > start = time.time() > > > > while child.poll() == -1: ## if child is still running... > > > > print count, time.time()-start > > test = output.read(100) > > > > count = count + 1 > > time.sleep(0.2) > > > > output when i run popentest.py: > > > > starting... 414 > > 1 after 0.000128984451294 > > 2 after 10.696469903 > > 3 after 10.896476984 > > 4 after 11.0964080095 > > 5 after 11.2964220047 > > 6 after 11.4964289665 > > 7 after 11.6964190006 > > 8 after 11.8964159489 > > 9 after 12.0963799953 > > 10 after 12.2964549065 > > 11 after 12.4964559078 > > 12 after 12.6964579821 > > 13 after 12.8963899612 > > etc... > > > > Notice the major timediff between step 1 and 2! 10 seconds!!!! what the > > hell > > is happening here? I know Python isn't always that fast, but why this > > big > > delay? Enlighten me! > > > > Cheers, > > > > Koen Bossers > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld@bt.com Fri Jul 27 10:54:46 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 27 Jul 2001 10:54:46 +0100 Subject: [Tutor] Shadow error Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE15@mbtlipnt02.btlabs.bt.co.uk> > def dig(n=2): > return lambda x:round(x,n) > print map(dig(2),l) > > Here's what I got: > > :5: SyntaxWarning: local name 'n' in 'dig' shadows > use of 'n' as global in nested scope 'lambda' So you need to do: def dig(n=2): return lambda x,m=n:round(x,m) Or using the new nested scopes do: from future import nested_scopes # or something like that... def dig(n=2): def f(x): return round(x,n) return f > but I have generated the above error before and would like to know > what I am doing wrong. You used n within the lambda but n is only visible inside dig() so when you pass the function to the map it can't see n. I get caught by this regularly... :-) Alan G From alan.gauld@bt.com Fri Jul 27 11:04:17 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 27 Jul 2001 11:04:17 +0100 Subject: [Tutor] Baffled: why doesn't range work? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE16@mbtlipnt02.btlabs.bt.co.uk> > class mtrx: > def __init__(self, numRows = 1, numCols = 1, initVal=0): > self.numRows = numRows > self.numCols = numCols > self.data = {} > if initVal != 0: > for i in range(1, numRows + 1, 1): > for j in range(1, numCols + 1, 1): > self.data[(i, j)] = initVal > I tried your code and got: >>> m = mtrx(2,5,0.2) >>> m.data {(2, 3): 0.20000000000000001, (2, 2): 0.20000000000000001, (1, 4): 0.20000000000000001, (1, 5): 0.20000000000000001, (1, 2): 0.20000000000000001, (1, 3): 0.20000000000000001, (2, 4): 0.20000000000000001, (1, 1): 0.20000000000000001, (2, 1): 0.20000000000000001, (2, 5): 0.20000000000000001} >>> ie. It looks fine... Alan G From iamgod@porri.cc.jyu.fi Fri Jul 27 13:29:23 2001 From: iamgod@porri.cc.jyu.fi (Risto Peranen) Date: Fri, 27 Jul 2001 15:29:23 +0300 (EEST) Subject: [Tutor] Tkinter licence(?) In-Reply-To: Message-ID: This may be silly answer but where do I wind legal issues of using Tkinter library? PyGTk is GPL as far as I know, but using Tkinker would be nice since my code works fine both win9x and linux. Is Tkinter licenced under GPL? (I'm trying not to use not GPL programs as long as I can :) secondly, I'm trying to learn making GUI. Is there such neat option as drag n' drop in PyGtk/Tkinter. thirtly, If there is good tutorials/HOWTO:s about principal of making GUIs please let me know -- Risto Peranen 040 756 94 12 iamgod@st.jyu.fi Vegetables rights and peace From patrick@kirks.net Fri Jul 27 16:31:34 2001 From: patrick@kirks.net (Patrick Kirk) Date: Fri, 27 Jul 2001 16:31:34 +0100 Subject: [Tutor] win os questions Message-ID: <000901c116b1$88e38880$1900a8c0@pod> Hi all, Is there a URL where I can see examples of simple things like: - pwd - import from y:\somefolder\somefolder\something - xcopy /d /s y:\somefolder\somefolder z:\somefolder\somefolder - and so on. In other words, the simole basics that you need to master before worrying about object orientated programming. Patrick Kirk GSM: +44 7876 560 646 ICQ: 42219699 From rob@jam.rr.com Fri Jul 27 16:54:11 2001 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 27 Jul 2001 10:54:11 -0500 Subject: [Tutor] win os questions In-Reply-To: <000901c116b1$88e38880$1900a8c0@pod> Message-ID: Actually, there are a number of places to look for source examples. Useless Python has a whole page of links to even more Python source out there. http://www.lowerstandard.com/python/ http://aspn.activestate.com/ASPN/Cookbook/Python http://www.vex.net/parnassus/ If you're curious about anything in particular, ask away. We're happy to help if we can. Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # Patrick Kirk # Sent: Friday, July 27, 2001 10:32 AM # To: Python Tutors # Subject: [Tutor] win os questions # # # Hi all, # # Is there a URL where I can see examples of simple things like: # # - pwd # - import from y:\somefolder\somefolder\something # - xcopy /d /s y:\somefolder\somefolder z:\somefolder\somefolder # - and so on. # # In other words, the simole basics that you need to master before worrying # about object orientated programming. # # Patrick Kirk # GSM: +44 7876 560 646 # ICQ: 42219699 # # # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From alan.gauld@bt.com Fri Jul 27 17:38:05 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 27 Jul 2001 17:38:05 +0100 Subject: [Tutor] Tkinter licence(?) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE21@mbtlipnt02.btlabs.bt.co.uk> > This may be silly answer but where do I wind legal issues of using > Tkinter library? PyGTk is GPL The Python license is approximately GPL (2.x should be fully compatible with GPL) - the same in spirit with minor divergences. > secondly, I'm trying to learn making GUI. Is there such neat > option as drag n' drop in PyGtk/Tkinter. GT may but I don't think Tk supports it. > If there is good tutorials/HOWTO:s about principal of making > GUIs please let me know A very basic intro is on my web site: http://www.crosswinds.net/~agauld/tutgui.htm And the Tkinter section of the python web site contains lots more advanced stuff. The official tutor and reference are both referenced there. Several books also cover Tkinter. HTH, Alan G From alan.gauld@bt.com Fri Jul 27 17:43:07 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 27 Jul 2001 17:43:07 +0100 Subject: [Tutor] win os questions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE22@mbtlipnt02.btlabs.bt.co.uk> > Is there a URL where I can see examples of simple things like: > > - pwd > - xcopy /d /s y:\somefolder\somefolder z:\somefolder\somefolder These are both OS system commands and are illustrated in the tutorial and module documentation. Look at: os.system() or result = popen() > - import from y:\somefolder\somefolder\something This isn't possible coz its a file path. You need to add "y:\somefolder\somefolder\something" to your PYTHONPATH environment variable thenb just import something Read about packages to find out how to go one better. > In other words, the simple basics that you need to > master before worrying about object orientated programming. Well there's also my online tutor - the concepts and basics sections teach you most of what you need prior to objects. Doesn't vcover the os module tho'... http://www.crosswinds.net/~agauld That should be more than adequate to let you read and understand the official tutorial. Anything more specific just ask. Alan G. From kalle@gnupung.net Fri Jul 27 17:58:25 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Fri, 27 Jul 2001 18:58:25 +0200 Subject: [Tutor] Tkinter licence(?) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE21@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Fri, Jul 27, 2001 at 05:38:05PM +0100 References: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE21@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010727185825.B3358@gandalf> Sez alan.gauld@bt.com: > > This may be silly answer but where do I wind legal issues of using > > Tkinter library? PyGTk is GPL > > The Python license is approximately GPL (2.x should > be fully compatible with GPL) - the same in spirit > with minor divergences. I have to disagree. The Python license is much more liberal then the GPL, it's much more like the BSD license. Tkinter is covered by the Python license. Tk, which is needed for Tkinter to work, is covered by a BSD license, AFAICT. This means there should be very few legal issues with using Tkinter, probably fewer than with something GPL-licensed like PyGTK. > > secondly, I'm trying to learn making GUI. Is there such neat > > option as drag n' drop in PyGtk/Tkinter. > > GT may but I don't think Tk supports it. There is support in PyGTK. Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From dyoo@hkn.eecs.berkeley.edu Fri Jul 27 21:50:51 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 27 Jul 2001 13:50:51 -0700 (PDT) Subject: [Tutor] help with _winreg In-Reply-To: Message-ID: On Fri, 27 Jul 2001, James wrote: > I'm experimenting with _winreg on python 2.1, and I'm having problems with > the > RegLoadKey(key, sub_key, file_name) function. I get "NameError: name > 'RegLoadKey' is not defined." > > On a hunch I tried LoadKey(key, sub_key, file_name) and it appeared to work. > But when I checked the registry, I got an unexpected result. > > My code: > > rKey= ConnectRegistry(None,HKEY_LOCAL_MACHINE) > aKey=OpenKey(rKey, r"Software\testkey1") > dirKey=OpenKey(rKey, r"Software") According to the documentation here: http://python.org/doc/lib/module--winreg.html you'll probably need to tell OpenKey() that you want to have write access to the registry keys: ### OpenKey(key, sub_key[, res = 0][, sam = KEY_READ]) [... some text cut] sam is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ ### That's probably why the changes aren't being saved. I don't know what the exact flag is, since I'm not running Windows, but I'm guessing it's something like KEY_WRITE. Back up your registry; it's tricky work! You might also want to ask questions on _winreg on the main comp.lang.python newsgroup; I'm not sure how many of us here are familiar enough with _winreg to help you effectively. Good luck to you! From allan.crooks@btinternet.com Fri Jul 27 23:10:12 2001 From: allan.crooks@btinternet.com (Allan Crooks) Date: Fri, 27 Jul 2001 23:10:12 +0100 Subject: [Tutor] Clear Screen Message-ID: Hi, > I was hoping there would be some way to change >>>cls() to simply >>>cls - > but this is close enough! :) It just occured to me how you could do this. class clear: def __repr__(self): import os, sys cls = os.popen("clear").read() sys.stdout.write(cls) return "" cls = clear() Now you can type cls, and it'll run the clear.__repr__ method, which will in turn clear the screen for you. :) Allan. From bill_tolbert@bigfoot.com Sat Jul 28 00:51:30 2001 From: bill_tolbert@bigfoot.com (Bill Tolbert) Date: Fri, 27 Jul 2001 19:51:30 -0400 (EDT) Subject: [Tutor] FTP: can't move a large file! Message-ID: I'm having trouble getting the ftplib to move a 20meg file. It works fine for small files, but it moves only a small chunk of the large file then quits! Here is a code sample: import ftplib datafile = open("e:\\temp\\bigfile") f = ftplib.FTP() f.connect("myserver.org") f.login("me","mypass") f.storbinary("STOR myfile", datafile, 1024) f.close() Is my file size the problem? Here's what the docs say: storbinary (command, file, blocksize) Store a file in binary transfer mode. command should be an appropriate "STOR" command, i.e. "STOR filename". file is an open file object which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored. Thanks a lot, Bill From bill_tolbert@bigfoot.com Sat Jul 28 03:49:58 2001 From: bill_tolbert@bigfoot.com (Bill Tolbert) Date: Fri, 27 Jul 2001 22:49:58 -0400 (EDT) Subject: [Tutor] Re: FTP: can't move a large file! In-Reply-To: Message-ID: Got it! I had failed to open the file with read binary. The open command should have been datafile = open("e:\\temp\\bigfile","rb") Bill On Fri, 27 Jul 2001, Bill Tolbert wrote: > I'm having trouble getting the ftplib to move a 20meg file. It works fine > for small files, but it moves only a small chunk of the large file then > quits! > > Here is a code sample: > > import ftplib > datafile = open("e:\\temp\\bigfile") > > f = ftplib.FTP() > f.connect("myserver.org") > f.login("me","mypass") > f.storbinary("STOR myfile", datafile, 1024) > f.close() > > Is my file size the problem? > > Here's what the docs say: > storbinary (command, file, blocksize) > Store a file in binary transfer mode. command should be an appropriate > "STOR" command, i.e. "STOR filename". file is an open file object which is > read until EOF using its read() method in blocks of size blocksize to > provide the data to be stored. > > Thanks a lot, > > Bill > > From jessw@loop.com Sat Jul 28 04:00:00 2001 From: jessw@loop.com (Jesse W) Date: Fri, 27 Jul 2001 20:00:00 -0700 Subject: [Tutor] Clear Screen In-Reply-To: Message-ID: <3B61C840.27164.7659EA6@localhost> Hey folks, Allan Crooks wrote: > Hi, > > > I was hoping there would be some way to change >>>cls() to simply > > >>>cls - but this is close enough! :) > > It just occured to me how you could do this. > > class clear: > > def __repr__(self): > import os, sys > cls = os.popen("clear").read() > sys.stdout.write(cls) > return "" > > cls = clear() > > Now you can type cls, and it'll run the clear.__repr__ method, which > will in turn clear the screen for you. :) Ogg... That's tricky! You could do _anything_ when the user thinks they are just finding out what the reference is. Ha ha, hee hee and ho ho.... Jesse F W. > Allan. From dyoo@hkn.eecs.berkeley.edu Sat Jul 28 04:23:39 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 27 Jul 2001 20:23:39 -0700 (PDT) Subject: [Tutor] Clear Screen In-Reply-To: Message-ID: On Fri, 27 Jul 2001, Allan Crooks wrote: > > I was hoping there would be some way to change >>>cls() to simply >>>cls - > > but this is close enough! :) > > It just occured to me how you could do this. > > class clear: > > def __repr__(self): > import os, sys > cls = os.popen("clear").read() > sys.stdout.write(cls) > return "" > > cls = clear() > > Now you can type cls, and it'll run the clear.__repr__ method, which > will in turn clear the screen for you. :) Very cool! They also use the same technique in pydoc --- take a look at the way they implemented repr() in pydoc.help(): ### ## Inside the pydoc.Helper class... def __repr__(self): if inspect.stack()[1][3] == '?': self() return '' return '' ### They're using a little bit of 'inspect'ion trickery to make __repr__ bootstrap into the help browser if we do pydoc.help at the interactive prompt, and otherwise return a "normal" representation string: ### >>> import pydoc >>> pydoc.help Welcome to Python 2.1! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://www.python.org/doc/tut/. [omitted text] To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". help> quit You're now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt. >>> def testHelpRepr(): ... return repr(pydoc.help) ... >>> testHelpRepr() '' ### From sendme105@hotmail.com Sat Jul 28 09:48:31 2001 From: sendme105@hotmail.com (James) Date: Sat, 28 Jul 2001 01:48:31 -0700 Subject: [Tutor] re: help with _winreg Message-ID: I couldn't get the LoadKey function working. So I tried a different approach. I wrote the following instead: from _winreg import * rKey = ConnectRegistry(None,HKEY_LOCAL_MACHINE) aKey= OpenKey(rKey, r"Software\testkey") newKey=CreateKey(rKey, r"Software\destination") def copy_str_values(fromKey, toKey): for i in range(QueryInfoKey(fromKey)[1]): value = str(EnumValue(fromKey, i)[0]) data = str(EnumValue(fromKey, i)[1]) SetValueEx(toKey, value, 0, REG_SZ, data) copy_str_values(aKey, newKey) CloseKey(aKey) CloseKey(newKey) DeleteKey(rKey, r"Software\testkey") CloseKey(rKey) I used it to make my first useful script! :) Thanks for the help, James. From bwgolling@home.com Sat Jul 28 13:33:20 2001 From: bwgolling@home.com (bwgolling) Date: Sat, 28 Jul 2001 12:33:20 -0000 Subject: [Tutor] Win Reg vs PYTHONPATH Message-ID: <003b01c11761$7c538740$bb510941@corlis1.pa.home.com> This is a multi-part message in MIME format. ------=_NextPart_000_0038_01C11761.7BF7F9C0 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable Can someone help me with a problem I am have concerning setting of the = environment? =20 Is it better to set the pythonpath etc. with a set command in dos or to = change the windows reg. I seem to get the impression that Active State Python prefers to set the = environment thru Reg rather than set commands. I dont like messing around with that registry stuff and would prefer to = set the environment by hand. Tks in advance Bruce ------=_NextPart_000_0038_01C11761.7BF7F9C0 Content-Type: text/html; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable
Can someone help me with a problem I = am have=20 concerning setting of the environment? 
Is it better to set the pythonpath = etc. with a=20 set command in dos or to change the windows reg.
I seem to get the impression that = Active State=20 Python prefers to set the environment thru Reg rather than set=20 commands.
I dont like messing around with that = registry=20 stuff and would prefer to set the environment by hand.
Tks in advance
Bruce
------=_NextPart_000_0038_01C11761.7BF7F9C0-- From dyoo@hkn.eecs.berkeley.edu Sat Jul 28 18:15:12 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 28 Jul 2001 10:15:12 -0700 (PDT) Subject: [Tutor] re: help with _winreg In-Reply-To: Message-ID: On Sat, 28 Jul 2001, James wrote: > I couldn't get the LoadKey function working. So I tried a different > approach. I wrote the following instead: > [code cut] > > I used it to make my first useful script! :) I'm sorry that the LoadKey stuff didn't work, but I'm happy that you found an alternative solution. Congrats! From fleet@teachout.org Sat Jul 28 19:13:22 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sat, 28 Jul 2001 14:13:22 -0400 (EDT) Subject: [Tutor] Clear Screen Message-ID: Absolutely wonderful! Tutor is my friend! :) I've actually gotten into the later chapters of "Learning Python" (two more days 'til it goes back to the library!) and believe I ran across something that told me I could do that - but hadn't gotten to try it yet. Thanks a million! - fleet - PS: This replaced the function in my startup file! :) >From: "Allan Crooks" >Date: Fri, 27 Jul 2001 23:10:12 +0100 > >Hi, > >> I was hoping there would be some way to change >>>cls() to simply >>>cls - >> but this is close enough! :) > >It just occured to me how you could do this. > >class clear: > > def __repr__(self): > import os, sys > cls = os.popen("clear").read() > sys.stdout.write(cls) > return "" > >cls = clear() > >Now you can type cls, and it'll run the clear.__repr__ method, which will in turn clear the screen for you. :) > >Allan. From csmith@blakeschool.org Sat Jul 28 19:23:48 2001 From: csmith@blakeschool.org (Christopher Smith) Date: Sat, 28 Jul 2001 13:23:48 -0500 Subject: [Tutor] using IDLE and changing variables In-Reply-To: References: Message-ID: Hi, One thing that has been discussed recently on Tutor is the fact that when you make changes to a module that you are importing, the changes won't be recognized unless you force a reload e.g., reload(mylibs). So the reload() takes care of that. My question concerns now the change of variables within a definition/program. Let's say at one point you had a variable x defined and you used it in several places. Then you change the variable from x to y but forget to change it everywhere. IDLE (at least from what I've seen) does not warn about the uninitialized variable. Is this just tough-luck-you-should-have-used-find-and-replace or is there some way to make sure this doesn't happen (other than quitting and restarting)? I guess what I'm looking for is something like BASIC's "new" command that flushes out everything of the session and begins fresh. /c From bill-bell@bill-bell.hamilton.on.ca Sat Jul 28 23:04:47 2001 From: bill-bell@bill-bell.hamilton.on.ca (Bill Bell) Date: Sat, 28 Jul 2001 18:04:47 -0400 Subject: [Tutor] Tkinter licence(?) In-Reply-To: Message-ID: <3B62FEBF.22102.484420D@localhost> Somebody wrote: > > ... I'm trying to learn making GUI. Is there such neat > > option as drag n' drop in PyGtk/Tkinter. > There is support in PyGTK. wxPython ( www.wxpython.org ) also supports drag 'n' drop. I can't compare it with other products for building Python GUIs. I would say though that for some purposes it compares very favourably with several commercial products. From fleet@teachout.org Sun Jul 29 03:39:32 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Sat, 28 Jul 2001 22:39:32 -0400 (EDT) Subject: [Tutor] Range limited? Message-ID: Just for fun, I imported the smallest of the RSA Challenge numbers into a file, then (looking for factors): from math import sqrt import sys a=long(open("rsa.num","r").read()) b=long(sqrt(a)) for i in range(3,b,2): if 5 % i == 0: pass if a % i == 0: print i, b/i sys.exit() Apparently python (5.2.1) doesn't much care for 84 digit ranges. I couldn't get this to work until I shortened the range number to 8 digits. (I skipped from 10 digits to 8, so maybe 9 digits will also work). Did I mess something up or is 'range' limited? I suspect my math skills are not up to solving this. Obviously, iterating through an 84-digit number in this manner would take some real time - even on a much faster PC than my 733! :) - fleet - From shalehperry@home.com Sun Jul 29 04:30:12 2001 From: shalehperry@home.com (Sean 'Shaleh' Perry) Date: Sat, 28 Jul 2001 20:30:12 -0700 (PDT) Subject: [Tutor] Range limited? In-Reply-To: Message-ID: On 29-Jul-2001 fleet@teachout.org wrote: > Just for fun, I imported the smallest of the RSA Challenge numbers into a > file, then (looking for factors): > > > Apparently python (5.2.1) doesn't much care for 84 digit ranges. I > couldn't get this to work until I shortened the range number to 8 digits. > (I skipped from 10 digits to 8, so maybe 9 digits will also work). > > Did I mess something up or is 'range' limited? > range creates a list containing every number in the range requested, so you just asked for a 1 gb list (or so). xrange returns an object that acts like a list of numbers but actually generates each number as it is requested by the loop. For loops of more than a few hundred, you probably should use xrange. In fact xrange should almost be used as a habit. From kp87@lycos.com Sun Jul 29 12:21:59 2001 From: kp87@lycos.com (kevin parks) Date: Sun, 29 Jul 2001 20:21:59 +0900 Subject: [Tutor] pydoc Message-ID: Is there anyway to learn more about what pydoc is and does? It's new as of 2.1 right? It seems really really cool, but i haven't found very much information on it, even on www.python.org. cheers, kevin parks seoul, korea kp87@lycos.com Get 250 color business cards for FREE! http://businesscards.lycos.com/vp/fastpath/ From jcosby@wolfenet.com Sun Jul 29 15:19:06 2001 From: jcosby@wolfenet.com (Jon Cosby) Date: Sun, 29 Jul 2001 07:19:06 -0700 Subject: [Tutor] Hit Counter Message-ID: I'd like to write a hit counter for my Web page. As easy as this would seem, it's got me stumped. I'm using a hidden form field:
but I suspect this is where the problem is. Why doesn't the script run each time the page loads? Jon Cosby -----------------Begin Script-------------------------------------- #! c:\python21\pythonw.exe print "Content-type: text/html" print print "Python Hit Counter" print "" form = cgi.FieldStorage() if form.has_key("Stats") # Hidden field InFile = open("count.dat", "r") # Text file with total hits Hits = InFile.readline() x = int(Hits) + 1 h = str(x) OutFile = open("count.dat", "w") OutFile.write(str(x)) OutFile.close() print "

Jon Cosby's web page - Total hits:



" for i in h: print "" print "" --------------End Script--------------------------------------------- From sheila@thinkspot.net Sun Jul 29 23:11:11 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 29 Jul 2001 15:11:11 -0700 Subject: [Tutor] Hit Counter In-Reply-To: References: Message-ID: <90161BB43AE@kserver.org> Well, I'm not sure this will fix your problem, but first off, I wouldn't use pythonw.exe which is the Windows GUI version of Python for CGI. Nor would I use any scripts ending with a .pyw extension. I would just use python.exe and .py. Like I said, I'm not sure this will solve the problem, but that was just something that jumped out at me. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Sun, 29 Jul 2001 07:19:06 -0700, "Jon Cosby" wrote about [Tutor] Hit Counter: :I'd like to write a hit counter for my Web page. As easy as this :would seem, it's got me stumped. I'm using a hidden form field: : :
: :
: :but I suspect this is where the problem is. Why doesn't the script :run each time the page loads? : :Jon Cosby : :-----------------Begin Script-------------------------------------- : :#! c:\python21\pythonw.exe : :print "Content-type: text/html" :print :print "Python Hit Counter" :print "" : : :form = cgi.FieldStorage() :if form.has_key("Stats") # Hidden field : InFile = open("count.dat", "r") # Text file with total hits : Hits = InFile.readline() : x = int(Hits) + 1 : h = str(x) :OutFile = open("count.dat", "w") :OutFile.write(str(x)) :OutFile.close() : : :print "

Jon Cosby's web page - Total hits:



" :for i in h: : print "" :print "" : :--------------End Script--------------------------------------------- : : : :_______________________________________________ :Tutor maillist - Tutor@python.org :http://mail.python.org/mailman/listinfo/tutor From sheila@thinkspot.net Sun Jul 29 23:13:31 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 29 Jul 2001 15:13:31 -0700 Subject: [Tutor] Hit Counter In-Reply-To: References: Message-ID: <903668734F3@kserver.org> On Sun, 29 Jul 2001 07:19:06 -0700, "Jon Cosby" wrote about [Tutor] Hit Counter: :I'd like to write a hit counter for my Web page. As easy as this :would seem, it's got me stumped. I'm using a hidden form field: : :
: :
: :but I suspect this is where the problem is. Why doesn't the script :run each time the page loads? : :Jon Cosby : :-----------------Begin Script-------------------------------------- : :#! c:\python21\pythonw.exe : :print "Content-type: text/html" :print :print "Python Hit Counter" :print "" : : :form = cgi.FieldStorage() :if form.has_key("Stats") # Hidden field : InFile = open("count.dat", "r") # Text file with total hits : Hits = InFile.readline() : x = int(Hits) + 1 : h = str(x) :OutFile = open("count.dat", "w") :OutFile.write(str(x)) :OutFile.close() : : :print "

Jon Cosby's web page - Total hits:



" :for i in h: : print "" :print "" : :--------------End Script--------------------------------------------- Your script, above, appears to be printing out the entire HTML page. Is that what you really want it to do? I would think that a counter script would just write some stuff to a file, and not produce any HTML output. I've never written a counter script, so I'm not sure how to handle the "no HTML output" part of the whole thing. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dyoo@hkn.eecs.berkeley.edu Mon Jul 30 01:54:34 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Jul 2001 17:54:34 -0700 (PDT) Subject: [Tutor] pydoc In-Reply-To: Message-ID: On Sun, 29 Jul 2001, kevin parks wrote: > Is there anyway to learn more about what pydoc is and does? It's new > as of 2.1 right? It seems really really cool, but i haven't found very > much information on it, even on www.python.org. Yes, pydoc is a pretty new module: there's a brief reference to it on the "What's new with Python 2.1" page: http://www.amk.ca/python/2.1 There is an article on OReilly's web site here: http://www.onlamp.com/pub/a/python/2001/04/18/pydoc.html which gives a high-level introduction to pydoc. Ironically enough, the documentation on pydoc itself seems a bit sparse: does anyone else know of a place that explains pydoc? From dyoo@hkn.eecs.berkeley.edu Mon Jul 30 02:12:01 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 Jul 2001 18:12:01 -0700 (PDT) Subject: [Tutor] Hit Counter In-Reply-To: Message-ID: On Sun, 29 Jul 2001, Jon Cosby wrote: > I'd like to write a hit counter for my Web page. As easy as this would > seem, it's got me stumped. I'm using a hidden form field: > >
> >
> > but I suspect this is where the problem is. Why doesn't the script run > each time the page loads? CGI programs don't run until you actually jump into that particular page: what you have above doesn't acually run the cgi program. You'll need to add something like a "submit" button to let people jump into the CGI program. Try: ###
### on your main web page. You'll see a button called "submit", and once your press that, then this will get counter.py program to run. By the way, there's a nice set of pages from devshed.com that explain more about CGI programming here: http://devshed.com/Server_Side/Python/CGI which might give some good information. Hmmm... Let's take a quick glance at your script: > form = cgi.FieldStorage() > if form.has_key("Stats") # Hidden field > InFile = open("count.dat", "r") # Text file with total hits > Hits = InFile.readline() > x = int(Hits) + 1 > h = str(x) > OutFile = open("count.dat", "w") > OutFile.write(str(x)) > OutFile.close() I think the lines starting from the OutFile stuff should also be part of the if block. The reason is: what happens if we're not asking our CGI program for 'stats'? What ends up happening is that Python won't know what 'x' or 'h' is in the rest of the program. It might be good to separate the stats handling part in a separate function: ### if form.has_key("Stats"): handleStats() def handleStats(): InFile = open("count.dat", "r") # Text file with total hits Hits = InFile.readline() x = int(Hits) + 1 h = str(x) OutFile = open("count.dat", "w") OutFile.write(str(x)) OutFile.close() print "

Jon Cosby's web page - Total hits:



" for i in h: print "" print "" ### Separating it like this should make it a little easier to add more commands to your CGI. Hope this helps! From dsh8290@rit.edu Mon Jul 30 02:45:41 2001 From: dsh8290@rit.edu (dman) Date: Sun, 29 Jul 2001 21:45:41 -0400 Subject: [Tutor] pydoc In-Reply-To: ; from kp87@lycos.com on Sun, Jul 29, 2001 at 08:21:59PM +0900 References: Message-ID: <20010729214541.C3173@harmony.cs.rit.edu> On Sun, Jul 29, 2001 at 08:21:59PM +0900, kevin parks wrote: | Is there anyway to learn more about what pydoc is and does? It's new | as of 2.1 right? It seems really really cool, but i haven't found | very much information on it, even on www.python.org. AFAIK it has been around for awhile, it just wasn't included in the standard dist. I think Ka-Ping Yee wrote it, so you might find more info on his site (use google). -D From alan.gauld@bt.com Mon Jul 30 10:21:58 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 30 Jul 2001 10:21:58 +0100 Subject: [Tutor] using IDLE and changing variables Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE26@mbtlipnt02.btlabs.bt.co.uk> > when you make changes to a module that you are importing, > the changes won't be recognized unless you force a reload Correct, at the interactive prompt. > Let's say at one point you had a variable x defined > and you used it in several places. Then you change > the variable from x to y but forget to change it > everywhere. That'd be a programmer error in every environment I've ever used. Some language compilers will tell you if you remove the original declaration/definition of the variable (x in your case) and then try to use it. Python will warn you in some situations. But it has nothing to do with IDLE per se, it's all to do with Python itself. > I guess what I'm looking for is something like BASIC's "new" > command that flushes out everything of the session and begins > fresh. The interactive prompt doesn't have that feature but working in IDLE the best thing IMHO is simply to create a new file using File|New... The >>> prompt is great for playing with ideas but if its more than a few lines of code I prefer to work in a file and edit/save/run - even if the file is just a throw-away like tmp.py of foo.py or whatever. Alan G From alan.gauld@bt.com Mon Jul 30 10:32:01 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 30 Jul 2001 10:32:01 +0100 Subject: [Tutor] Hit Counter Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66BE27@mbtlipnt02.btlabs.bt.co.uk> Hmm cgi is not my strongest area but I'll hazard a guess... >
> >
> but I suspect this is where the problem is. Why doesn't the script > run each time the page loads? How is the form submitted? AFAIK the action will only be activated by a submit? I think you need some Javascript or something in there to force the action. Now just a quick comment on the script: > x = int(Hits) + 1 > h = str(x) > OutFile = open("count.dat", "w") > OutFile.write(str(x)) you can miss out the h=str(x) line coz you dson't use h or alternatively Outfile.write(h).... > print "

Jon Cosby's web page - Total hits:



" > for i in h: > print "" No ALT tags - AAARGH! bad. bad. But OK you use h here so in that case use h in the write()... Alan g. From bwinton@tor.dhs.org Mon Jul 30 14:07:27 2001 From: bwinton@tor.dhs.org (Blake Winton) Date: Mon, 30 Jul 2001 09:07:27 -0400 Subject: [Tutor] pydoc In-Reply-To: <20010729214541.C3173@harmony.cs.rit.edu> References: <20010729214541.C3173@harmony.cs.rit.edu> Message-ID: <20010730090727.A10781@tor.dhs.org> * dman [010729 21:45]: > On Sun, Jul 29, 2001 at 08:21:59PM +0900, kevin parks wrote: > | Is there anyway to learn more about what pydoc is and does? It's new > | as of 2.1 right? It seems really really cool, but i haven't found > | very much information on it, even on www.python.org. > AFAIK it has been around for awhile, it just wasn't included in the > standard dist. I think Ka-Ping Yee wrote it, so you might find more > info on his site (use google). Or just go to http://web.lfw.org/python/ And while I'm here, I just thought I'ld say that the CGI TraceBack module he's produced looks far too cool for words. Check out the screenshot at: http://web.lfw.org/python/test4.html Later, Blake. -- 9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07 From kev@sat.net Mon Jul 30 14:21:39 2001 From: kev@sat.net (Kevin McCormick) Date: Mon, 30 Jul 2001 08:21:39 -0500 Subject: [Tutor] A small (but long) introduction to recursion References: Message-ID: <3B655F63.6684CF68@sat.net> Danny Yoo wrote: > > On Wed, 25 Jul 2001, Danny Yoo wrote: > > > > def addUpToNRecursive(n): > > > if n == 0: return 0 > > > print n > > > return addUpToNRecursive(n-1) + n > > > > > > x = addUpToNRecursive(10) > > > print x > > If it helps, try this version of the program: > > ### > def addUpToN(n): > if n == 0: return 0 > print (' ' * n) + "Trying to figure out addUpToN(%s)" % n > answer = addUpToN(n-1) + n > print (' ' * n) + "The answer of addUpToN(%s) is %s" % (n, answer) > return answer > ### > > It's a little bit longer, but it does print something pretty: > > ### > >>> addUpToN(5) > Trying to figure out addUpToN(5) > Trying to figure out addUpToN(4) > Trying to figure out addUpToN(3) > Trying to figure out addUpToN(2) > Trying to figure out addUpToN(1) > The answer of addUpToN(1) is 1 > The answer of addUpToN(2) is 3 > The answer of addUpToN(3) is 6 > The answer of addUpToN(4) is 10 > The answer of addUpToN(5) is 15 > 15 > ### > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Thanks very much, it is now clear as fog, which is better than mud. Sincee I am just a hacker and not a CS major, this basic understanding seems good enough for now. Thanks again! From fleet@teachout.org Mon Jul 30 16:16:18 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Mon, 30 Jul 2001 11:16:18 -0400 (EDT) Subject: [Tutor] Range limited? In-Reply-To: Message-ID: Thanks for the pointer to xrange. I circumvented the problem by switching to "while i < [long(sqrt(target number))]: " I set a print command to print 'i' in multiples of 10,000. About 10 hours later I had hit a billion (10 digits). Hmmmm, 74 digits to go! :) I think not. (Actually, I investigated primes a little and after finding that the 200,000th prime number is only 7 digits long, I pretty much decided I can't run with the big dogs - so I'll just stay on the porch!) :) - fleet - PS: Should the above be "while long(i) < upper-bound-of-many-digit-number"? Will "i" go flaky after 16 digits or is it sufficient that only one number be long? On Sat, 28 Jul 2001, Sean 'Shaleh' Perry wrote: > On 29-Jul-2001 fleet@teachout.org wrote: > > Apparently python (5.2.1) doesn't much care for 84 digit ranges. I > > couldn't get this to work until I shortened the range number to 8 digits. > > (I skipped from 10 digits to 8, so maybe 9 digits will also work). > > > > Did I mess something up or is 'range' limited? > > > > range creates a list containing every number in the range requested, so you > just asked for a 1 gb list (or so). xrange returns an object that acts like a > list of numbers but actually generates each number as it is requested by the > loop. For loops of more than a few hundred, you probably should use xrange. > In fact xrange should almost be used as a habit. > From dyoo@hkn.eecs.berkeley.edu Mon Jul 30 16:50:58 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 Jul 2001 08:50:58 -0700 (PDT) Subject: [Tutor] A small (but long) introduction to recursion In-Reply-To: <3B655F63.6684CF68@sat.net> Message-ID: On Mon, 30 Jul 2001, Kevin McCormick wrote: > > If it helps, try this version of the program: > > > > ### > > def addUpToN(n): > > if n == 0: return 0 > > print (' ' * n) + "Trying to figure out addUpToN(%s)" % n > > answer = addUpToN(n-1) + n > > print (' ' * n) + "The answer of addUpToN(%s) is %s" % (n, answer) > > return answer > > ### > > > > It's a little bit longer, but it does print something pretty: > > > > ### > > >>> addUpToN(5) > > Trying to figure out addUpToN(5) > > Trying to figure out addUpToN(4) > > Trying to figure out addUpToN(3) > > Trying to figure out addUpToN(2) > > Trying to figure out addUpToN(1) > > The answer of addUpToN(1) is 1 > > The answer of addUpToN(2) is 3 > > The answer of addUpToN(3) is 6 > > The answer of addUpToN(4) is 10 > > The answer of addUpToN(5) is 15 > > 15 > > ### > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > Thanks very much, it is now clear as fog, which is better than mud. > Sincee I am just a hacker and not a CS major, this basic understanding > seems good enough for now. Thanks again! *laugh* No problem, glad to introduce the subject. From dyoo@hkn.eecs.berkeley.edu Mon Jul 30 16:57:55 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 Jul 2001 08:57:55 -0700 (PDT) Subject: [Tutor] Range limited? In-Reply-To: Message-ID: On Mon, 30 Jul 2001 fleet@teachout.org wrote: > Thanks for the pointer to xrange. I circumvented the problem by switching > to "while i < [long(sqrt(target number))]: " I set a print command to > print 'i' in multiples of 10,000. About 10 hours later I had hit a > billion (10 digits). Hmmmm, 74 digits to go! :) I think not. > > (Actually, I investigated primes a little and after finding that the > 200,000th prime number is only 7 digits long, I pretty much decided I > can't run with the big dogs - so I'll just stay on the porch!) :) > > - fleet - > > PS: Should the above be > "while long(i) < upper-bound-of-many-digit-number"? > Will "i" go flaky after 16 digits or is it sufficient that only one number > be long? Theoretically, it shouldn't go flaky because 'long' integers are of unlimited length. Let's see, how many atoms are there in the universe? ### >>> atoms = "1" + ("0" * 68) >>> atoms '100000000000000000000000000000000000000000000000000000000000000000000' >>> long(atoms) 100000000000000000000000000000000000000000000000000000000000000000000L ### You should be fine with 16 digits. *grin* However, I think that Python doesn't automatically consider really large integers as longs, so you might need to long()ify the upper-bound-of-many-digit-number as well: ### >>> 1000000000000000000000000000000000000000000000000 OverflowError: integer literal too large ### From patrick@kirks.net Mon Jul 30 17:06:37 2001 From: patrick@kirks.net (Patrick Kirk) Date: Mon, 30 Jul 2001 17:06:37 +0100 Subject: [Tutor] Refreshing a script Message-ID: <000901c11911$9ccfff60$1900a8c0@pod> Hi all, If I write a script and them import it its functions are available as script.function() But how can I refresh this if I then edit the script? thanks in advance. -- Patrick Kirk GSM: +44 7876 560 646 ICQ: 42219699 From dsh8290@rit.edu Mon Jul 30 17:27:04 2001 From: dsh8290@rit.edu (dman) Date: Mon, 30 Jul 2001 12:27:04 -0400 Subject: [Tutor] Range limited? In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Mon, Jul 30, 2001 at 08:57:55AM -0700 References: Message-ID: <20010730122704.B3353@harmony.cs.rit.edu> On Mon, Jul 30, 2001 at 08:57:55AM -0700, Danny Yoo wrote: | However, I think that Python doesn't automatically consider really large | integers as longs, so you might need to long()ify the | upper-bound-of-many-digit-number as well: Integral literals are 'int' which is whatever the C platform's 'int' is. If you want a literal long you need | ### | >>> 1000000000000000000000000000000000000000000000000 | OverflowError: integer literal too large | ### 1000000000000000000000000000000000000000000000000L ^ and it will work fine >>> 1000000000000000000000000000000000000000000000000L 1000000000000000000000000000000000000000000000000L >>> -D From dsh8290@rit.edu Mon Jul 30 17:27:37 2001 From: dsh8290@rit.edu (dman) Date: Mon, 30 Jul 2001 12:27:37 -0400 Subject: [Tutor] Refreshing a script In-Reply-To: <000901c11911$9ccfff60$1900a8c0@pod>; from patrick@kirks.net on Mon, Jul 30, 2001 at 05:06:37PM +0100 References: <000901c11911$9ccfff60$1900a8c0@pod> Message-ID: <20010730122737.C3353@harmony.cs.rit.edu> On Mon, Jul 30, 2001 at 05:06:37PM +0100, Patrick Kirk wrote: | Hi all, | | If I write a script and them import it its functions are available as | script.function() | | But how can I refresh this if I then edit the script? reload( script ) (or restart the interpreter) -D From Charlie Clark Mon Jul 30 17:46:41 2001 From: Charlie Clark (Charlie Clark) Date: Mon, 30 Jul 2001 18:46:41 +0200 Subject: [Tutor] Hit Counter in Python References: Message-ID: <00038a52700d2ae6_mailit@mail.isis.de> >form = cgi.FieldStorage() >:if form.has_key("Stats") # Hidden field >: InFile = open("count.dat", "r") # Text file with total hits >: Hits = InFile.readline() >: x = int(Hits) + 1 >: h = str(x) >:OutFile = open("count.dat", "w") >:OutFile.write(str(x)) >:OutFile.close() >: >: >:print "

Jon Cosby's web page - Total hits:



" >:for i in h: >: print "" >:print "" Ha, finally something which I know a little about ;-) First of all counters are unreliable and unchic. The best thing to do is to read your logfile. There is a wonderful Python package out there from someone at Akamai which has all you need for it but implementing something like a counter has it's uses if you need to provide verifiable statistics (eg. for an online magazine). You can do this with script but you don't need a form. The usual way is to embed a tiny image in each page (say 1 x 1) and set the < img> tag to connect to the script, increment and supply the image to the browser. This can be configured to beat proxies and caches and you can choose to record additional information - of course anything that's in the header can also be automatically logged. This is how the ivw verifies online circulation in Germany. Your html maybe something like: Your script only needs to do read, increment and write... >InFile = open("count.dat", "r") # Text file with total hits >Hits = InFile.readline() >x = int(Hits) + 1 >h = str(x) mm, this isn't quite right in style. Someone posted a link to Guido's notes on style and convention for me the other week. "InFile" would look like a class to many a pythoneer. Sorry. I did read it but didn't bookmark it. But it was over on Sourceforge #! /bin/env python # or whatever you need to do this in windows # simple counter script try: file_in = open("count.txt", "r") count = int(file_in.readline()) # it *is* a text file file_in.close() except: open("count.txt", "w").write("0") # so we don't choke on the first open("count.txt", "r").close() # request count = 0 file_out = open("count.txt", "w") count += 1 file_out.write(str(count)) Write another script to display the counter. I think you might like to modify that as well. You've got a set of images 1..0silver.gif ? And you want to display the number of hits on the counter with a combination of those. I'm sure there's a nice way of doing that. I know you can loop through an integer but still you should separate the loop from it's contents Let's say you've had 773 pages called up. count = '773' def show_image(i): print '' %(i) # or your string addition for i in count: show_image(int(i)) Can anybody tell me of a nicer way of doing this? Charlie From fleet@teachout.org Mon Jul 30 18:12:36 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Mon, 30 Jul 2001 13:12:36 -0400 (EDT) Subject: [Tutor] Range limited? In-Reply-To: Message-ID: On Mon, 30 Jul 2001, Danny Yoo wrote: > > PS: Should the above be > > "while long(i) < upper-bound-of-many-digit-number"? > > Will "i" go flaky after 16 digits or is it sufficient that only one number > > be long? > > Theoretically, it shouldn't go flaky because 'long' integers are of > unlimited length. Let's see, how many atoms are there in the universe? If the expression is 'while i < upper-bound-of-many-digit-number' (ie, i is not long), then i appears to have an upper limit of 2147483647. >>> i 2147483647 >>> i=i+1 Traceback (innermost last): File "", line 1, in ? OverflowError: integer addition also tried: >>> lower 2147483447L #200 less than "i" above >>> upper 2147483847L #200 more than "i" above >>> step 1 >>> for i in xrange(lower,upper,step): ... print i ... Traceback (innermost last): File "", line 1, in ? OverflowError: long int too long to convert >>> AND ... while lower < upper: print lower lower=lower+1 [first 396 numbers deleted] 2147483644 2147483645 2147483646 2147483647 Traceback (innermost last): File "", line 3, in ? OverflowError: integer addition So it looks to me like range and xrange both attempt to convert the long arguments to integers and 2147483647 is the upper limit. - fleet - From dsh8290@rit.edu Mon Jul 30 18:34:21 2001 From: dsh8290@rit.edu (dman) Date: Mon, 30 Jul 2001 13:34:21 -0400 Subject: [Tutor] Range limited? In-Reply-To: ; from fleet@teachout.org on Mon, Jul 30, 2001 at 01:12:36PM -0400 References: Message-ID: <20010730133421.B3442@harmony.cs.rit.edu> On Mon, Jul 30, 2001 at 01:12:36PM -0400, fleet@teachout.org wrote: | On Mon, 30 Jul 2001, Danny Yoo wrote: | | > > PS: Should the above be | > > "while long(i) < upper-bound-of-many-digit-number"? | > > Will "i" go flaky after 16 digits or is it sufficient that only one number | > > be long? | > | > Theoretically, it shouldn't go flaky because 'long' integers are of | > unlimited length. Let's see, how many atoms are there in the universe? | | If the expression is 'while i < upper-bound-of-many-digit-number' (ie, i | is not long), then i appears to have an upper limit of 2147483647. For your system. It will always be sys.maxint. Here's some data from some of the interpreters I have access to : Python 2.1 (#1, Apr 17 2001, 09:45:01) [GCC 2.95.3-2 (cygwin special)] on cygwin_nt-4.01 Type "copyright", "credits" or "license" for more information. >>> import sys ; print sys.maxint 2147483647 >>> Jython 2.0 on java1.1.8 (JIT: none) Type "copyright", "credits" or "license" for more information. >>> import sys ; print sys.maxint 2147483647 >>> Python 2.0 (#18, Oct 31 2000, 13:55:49) [C] on sunos5 Type "copyright", "credits" or "license" for more information. >>> import sys ; print sys.maxint 2147483647 >>> Python 2.1 (#1, Jul 27 2001, 15:48:55) [GCC 2.95.2 19991024 (release)] on sunos5 Type "copyright", "credits" or "license" for more information. >>> import sys ; print sys.maxint 2147483647 >>> So apparently that is the maximum for an integer on Intel PII systems (widows -- cygwin and java) and whatever SPARC is in an Ultra 10 (Solaris 8). If you had an older machine it would be less (like maybe on a 386 or definitely a 286) or if you have a newer machine it will be more (such as the 64-bit SPARCs or the new IA-64). -D From fleet@teachout.org Mon Jul 30 18:36:54 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Mon, 30 Jul 2001 13:36:54 -0400 (EDT) Subject: [Tutor] closing files Message-ID: In the discussion about the non-operating CGI form, I noticed that noone mentioned that the file opened for reading was never closed. I recreated the situation in an interactive session (ie, opened a file for reading, then without closing it, opened it again for writing and wrote to it). Python didn't appear to care that the file opened for reading was not closed before the same file gets opened for writing. When opened files are not closed, what are the dangers? Are files closed by Python under some circumstances and, if so, which circumstances? If I write something like: open("writefile","w").write(open("readfile","r").read()) are both the read and write files closed on execution of the command - or should I spoil the beauty of a one-liner by adding: readfile.close() writefile.close() - fleet - From dyoo@hkn.eecs.berkeley.edu Mon Jul 30 21:59:48 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 Jul 2001 13:59:48 -0700 (PDT) Subject: [Tutor] closing files In-Reply-To: Message-ID: On Mon, 30 Jul 2001 fleet@teachout.org wrote: > In the discussion about the non-operating CGI form, I noticed that noone > mentioned that the file opened for reading was never closed. I recreated > the situation in an interactive session (ie, opened a file for reading, > then without closing it, opened it again for writing and wrote to it). > Python didn't appear to care that the file opened for reading was not > closed before the same file gets opened for writing. > > When opened files are not closed, what are the dangers? Are files closed > by Python under some circumstances and, if so, which circumstances? When the variable goes out of scope, Python will automagically close() the file for us. For example, your line: > open("writefile","w").write(open("readfile","r").read()) is ok because Python transparently is doing the close()ing for us. (I'm being a little handwavy: it has more to do with the fact that the _reference count_ of the file goes to zero.) Hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Jul 31 08:11:55 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 31 Jul 2001 00:11:55 -0700 (PDT) Subject: [Tutor] backquotes and str() are not exactly equivalent Message-ID: Hiya everyone, I'm doing a small project with Postgresql, and as I was inserting data into the database, I noticed that the backquote operator doesn't do exactly what str() does. Here's an example that shows what I mean: ### >>> myname = 'tutor-curator' >>> str(myname) 'tutor-curator' >>> `myname` "'tutor-curator'" >>> repr(myname) "'tutor-curator'" ### That is, backquotes (``) do a repr() of its input, and not an str() as I had thought before. Just wanted to share my goofup with everyone else... *grin* I'm having quite a bit of fun with the 'pygresql' and 'mailbox' modules, so if anyone has questions about these two modules, feel free to ask questions. From support@getiview.com Tue Jul 31 14:15:54 2001 From: support@getiview.com (support) Date: Tue, 31 Jul 2001 09:15:54 -0400 Subject: [Tutor] python source code Message-ID: <3B66AF8A.62378018@opticominc.com> I am trying to obtain the source code for python ver. 1.5.2 for purposes of rebuilding, as I need to change what functions are actually called in C for pythons calls of open, write close, etc... (File I/O).. currently python doesn't use the win32API funcs for this, which i need to use for the program im working on to operate on NT, and over networks. IF anyone knows where i can get the source or has done this or has any advice for this (such as how to include the win32API in the C file, or which functions from python are defined where in the source code) I would be greatly appreciated. adam From arcege@speakeasy.net Tue Jul 31 14:37:54 2001 From: arcege@speakeasy.net (Michael P. Reilly) Date: Tue, 31 Jul 2001 09:37:54 -0400 (EDT) Subject: [Tutor] python source code In-Reply-To: from "support" at Jul 31, 2001 09:15:54 AM Message-ID: <200107311337.f6VDbsQ22863@dsl092-074-184.bos1.dsl.speakeasy.net> support wrote > I am trying to obtain the source code for python ver. 1.5.2 for purposes > of rebuilding, as I need to change what functions are actually called in > C for pythons calls of open, write close, etc... (File I/O).. currently > python doesn't use the win32API funcs for this, which i need to use for > the program im working on to operate on NT, and over networks. IF > anyone knows where i can get the source or has done this or has any > advice for this (such as how to include the win32API in the C file, or > which functions from python are defined where in the source code) I > would be greatly appreciated. Yikes, that seems like a LOT of overkill. Firstly, as a bad thing to do, you could put other function in place of the built-in "open" file (in the __builtin__ module). Changing things in the __builtin__ module is not good because it makes for some dangerous side-effects when something you don't expect happens. The Python core does not use win32 APIs because it is not a win32 application; it is supported on multiple platforms. However there are full extensions for the win32 APIs, including CreateFile and CreatePipe. Before you start cracking the code, you probably want to download and look at those extensions: win32all at . The module you are looking for in that package is called "win32file". Mark Hammond has also written a good book called "Python Programming on Win32", which describe the win32all package and other things. Good luck, -Arcege P.S.: Python uses C's standard library for files. Win32all can give you better control for windoze, but won't let you get portable results. -- +----------------------------------+-----------------------------------+ | Michael P. Reilly | arcege@speakeasy.net | From rob@jam.rr.com Tue Jul 31 14:49:11 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 31 Jul 2001 08:49:11 -0500 Subject: [Tutor] python source code In-Reply-To: <3B66AF8A.62378018@opticominc.com> Message-ID: python.org is temporarily down, but here's a link to the 1.5.2 sources on a fast mirror: http://python.planetmirror.com/1.5/ And here's the link to ActiveState's Python distribution. It's pretty Windows-friendly. Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # support # Sent: Tuesday, July 31, 2001 8:16 AM # To: tutor@python.org # Subject: [Tutor] python source code # # # I am trying to obtain the source code for python ver. 1.5.2 for purposes # of rebuilding, as I need to change what functions are actually called in # C for pythons calls of open, write close, etc... (File I/O).. currently # python doesn't use the win32API funcs for this, which i need to use for # the program im working on to operate on NT, and over networks. IF # anyone knows where i can get the source or has done this or has any # advice for this (such as how to include the win32API in the C file, or # which functions from python are defined where in the source code) I # would be greatly appreciated. # # adam # # # _______________________________________________ # Tutor maillist - Tutor@python.org # http://mail.python.org/mailman/listinfo/tutor From rob@jam.rr.com Tue Jul 31 14:57:25 2001 From: rob@jam.rr.com (Rob Andrews) Date: Tue, 31 Jul 2001 08:57:25 -0500 Subject: [Tutor] python source code In-Reply-To: Message-ID: Rather, HERE's the ActiveState link: http://aspn.activestate.com/ASPN/Python/ oops, Rob Your one-stop shop for newbie source code! Useless Python: http://www.lowerstandard.com/python/ # -----Original Message----- # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # Rob Andrews # Sent: Tuesday, July 31, 2001 8:49 AM # To: support; tutor@python.org # Subject: RE: [Tutor] python source code # # # python.org is temporarily down, but here's a link to the 1.5.2 # sources on a # fast mirror: # # http://python.planetmirror.com/1.5/ # # And here's the link to ActiveState's Python distribution. It's pretty # Windows-friendly. # # Rob # # Your one-stop shop for newbie source code! # Useless Python: http://www.lowerstandard.com/python/ # # # -----Original Message----- # # From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of # # support # # Sent: Tuesday, July 31, 2001 8:16 AM # # To: tutor@python.org # # Subject: [Tutor] python source code # # # # # # I am trying to obtain the source code for python ver. 1.5.2 for purposes # # of rebuilding, as I need to change what functions are actually called in # # C for pythons calls of open, write close, etc... (File I/O).. currently # # python doesn't use the win32API funcs for this, which i need to use for # # the program im working on to operate on NT, and over networks. IF # # anyone knows where i can get the source or has done this or has any # # advice for this (such as how to include the win32API in the C file, or # # which functions from python are defined where in the source code) I # # would be greatly appreciated. # # # # adam # # # # # # _______________________________________________ # # 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 Charlie Clark Tue Jul 31 20:58:44 2001 From: Charlie Clark (Charlie Clark) Date: Tue, 31 Jul 2001 21:58:44 +0200 Subject: [Tutor] Note on style References: Message-ID: <00038a693cb769b4_mailit@mail.isis.de> >Someone posted a link to Guido's notes >on style and convention for me the other week. "InFile" would look like a >class to many a pythoneer. Sorry. I did read it but didn't bookmark it. But >it was over on Sourceforge In order to answer myself. Danny Yoo posted this link: http://python.sourceforge.net/peps/pep-0008.html Well worth reading for all newbies. Coming up with a good naming system (one which is easy to stick to and which others understand) is one of the most * underated* skills in programming in my opinion. Charlie -- Charlie Clark Helmholtzstr. 20 Dьsseldorf D- 40215 Tel: +49-211-938-5360 GSM: +49-178-463-6199 http://www.begeistert.org From fleet@teachout.org Tue Jul 31 20:53:18 2001 From: fleet@teachout.org (fleet@teachout.org) Date: Tue, 31 Jul 2001 15:53:18 -0400 (EDT) Subject: [Tutor] Range limited? Message-ID: Recap: The discussion of the limits of an integer would not have occured (perhaps) if I had checked more than one source! The "docs/ref/integers.html" says: "Plain integer decimal literals must be at most 2147483647 (i.e., the largest positive integer, using 32-bit arithmetic). Plain octal and hexadecimal literals may be as large as 4294967295, but values larger than 2147483647 are converted to a negative value by subtracting 4294967296. There is no limit for long integer literals apart from what can be stored in available memory." Unfortunately, I had checked "Learning Python" only - and that reference (the one I've most used to date!) doesn't mention this limitation (or I can't find it.) Two other sources - "Python Essential Reference" and "Core Python Programming" - both provide the bounds of the python integer. (These are recent purchases - and were lying on the desk unopened at the time I asked the original question.) Also found (while researching the integer question) - both range and xrange operate with "integers" as arguments. My uncomplicated (?simplistic?) mind had seen this as "integer == number == (integer, float, long, complex)." Range and Xrange both convert the numbers to integers and are therefore limited to a range of 2147483647 (or -2147483648). >>> range(long(5)) [0, 1, 2, 3, 4] >>> type(range(long(5))[2]) - fleet - From dsh8290@rit.edu Tue Jul 31 23:11:33 2001 From: dsh8290@rit.edu (dman) Date: Tue, 31 Jul 2001 18:11:33 -0400 Subject: [Tutor] [Long!] Varying degrees of precision In-Reply-To: <200107312353.f6VNrEY29493@pop.nsacom.net>; from kromag@nsacom.net on Tue, Jul 31, 2001 at 04:53:14PM -0700 References: <200107312353.f6VNrEY29493@pop.nsacom.net> Message-ID: <20010731181133.A5946@harmony.cs.rit.edu> On Tue, Jul 31, 2001 at 04:53:14PM -0700, kromag@nsacom.net wrote: | Hi all! | | Sorry I've been a stranger lately, but I have been decending into C. | | I have noticed that there are some weirdnesses occouring when converting | integers to floats in python. I wrote the following module as the beginnings | of a "hot rod math" project. The first function, suck() gives the proper cfm | flow for a carburetor on an engine of a given size at a given rpm. [...] | >>> from rodney import suck | >>> suck(2000,6000,'cc') | 155.61115518398728 | >>> suck(2000.00,6000.00,'cc') | 180.10550368517048 | >>> | ------------end rodney output------------ | | note the differences in the results! | | I figured this out when I wrote the following lame C program: [...] | which returns 180.105499 | | Is this a case of weak typing biting me on the backside, or is there a | pythonic way to specify a float? --- original answer, not really pertinent but might be interesting to some --- Floats cannot represent all values. They can only repesent values that follow the form 1.n * 2**m where n and m are integers and n is displayed in binary. Some numbers, for example .1 in decimal, can't be represent exactly so they are approximated. Anytime you perform arithmatic using approximations the uncertainty of the result increases (ie the amount of potential error from the correct answer). If you want a really accurate (may be, but not necessarily will be precise though) result use integers only. ---------------------------------------------------------------------- Anyways, I just noticed where your real problem lies >>> suck(2000,6000,'cc') ^^^^ ^^^^ Those are integers. Your function doesn't explicitly convert them to floats so when you do division you get an integer back. Think of integer division like in 5th grade, but you simply ignore the "remainder" part. For example : >>> 2 / 3 0 >>> 2.0 / 3.0 0.66666666666666663 >>> If you convert the arguments to floats using the float() built-in function before performing the division then it should work much better :-). HTH, -D From kalle@gnupung.net Tue Jul 31 23:18:36 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 1 Aug 2001 00:18:36 +0200 Subject: [Tutor] [Long!] Varying degrees of precision In-Reply-To: <200107312357.f6VNveY04968@pop.nsacom.net>; from kromag@nsacom.net on Tue, Jul 31, 2001 at 04:57:40PM -0700 References: <200107312357.f6VNveY04968@pop.nsacom.net> Message-ID: <20010801001836.A28703@gandalf> Sez kromag@nsacom.net: > Hi all! > > Sorry I've been a stranger lately, but I have been decending into C. Mmm. I looove doing all my memory allocation manually. > def suck(cc,rpm,increment): > if increment == 'sae': > cid=cc > else: > cid=cc/16.387 # This line converts from cc to cid- lazy. > cfm=( cid/2 )*( rpm/1728 )*.85 #Assumes 85% volumetric effeciency. This is the line where stuff breaks, and it can also be fixed here quite easily. cfm = (cid / 2.0) * (rpm / 1728.0) * .85 should give you the answers you want. This will force cid and rpm to float and avoid the integer division. As a side note, I might add that it seems this behaviour will change in Python 3.0, and that python-list/comp.lang.python has had a flamewar about that in the recent week more heated than anything I can recall from my few years of reading the list. Wow, 44 words in that sentence. Anyway, in Python 3.0 as Guido wants it, you wouldn't have had this problem, there '/' always yields a float (or rational, if they're added to the language). '//' is used for integer division. Peace, Kalle -- Free Dmitry Sklyarov! - http://www.freesklyarov.org/ From ramprasad@ncoretech.com Fri Jul 27 12:54:39 2001 From: ramprasad@ncoretech.com (ramprasad) Date: Fri, 27 Jul 2001 17:24:39 +0530 Subject: [Tutor] executing python script References: <20010927103531.4.cpmta@c012.sfo.cp.net> Message-ID: <005701c11692$eb108810$e101a8c0@ncoretech.com> This is a multi-part message in MIME format. ------=_NextPart_000_0054_01C116C1.03E82810 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hi , I think there was a problem with the indentation . The attached file is working... I don't know what it is doing .. Hope this helps you. Thanks Ramprasad ----- Original Message ----- From: Damian Coughlan To: Sent: Thursday, September 27, 2001 4:05 PM Subject: [Tutor] executing python script > Hi, > attached u will find a script called lotto1.py. When I run the script using __main__ > the interpreter does nothing and does not execute the function play. Please explain > > Thanks > > > > > Find the best deals on the web at AltaVista Shopping! > http://www.shopping.altavista.com > ------=_NextPart_000_0054_01C116C1.03E82810 Content-Type: text/plain; name="lotto1.py" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="lotto1.py" # to generate quick pick lotto numbers # author : Damien Coughlan - Date 25/9/01 import random import os import sys def lotto() : a = range(42) random.shuffle(a) print a[:6] def play(): completed=0 while not completed: try: x=raw_input('\npress enter for lotto quick pick (E to exit). ') except EOFError: x = 'e' if x and (x[0] == 'e' or x[0] == 'E'): completed = 1 print 'completed' else: print lotto() if __name__ == '__main__': play() else: print " Module random imported \n" print " to play type lotto1.play() \n" print " To reload type : reload.lotto1 \n" ------=_NextPart_000_0054_01C116C1.03E82810--