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/
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?
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
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
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 ?
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
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.
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.
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
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
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:
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>
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[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:
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 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