From dyoo at hkn.eecs.berkeley.edu  Sat Jul  1 00:01:34 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 30 Jun 2006 15:01:34 -0700 (PDT)
Subject: [Tutor] saving output in a text file
In-Reply-To: <BAY13-F79E6C1111A696BAD2AD8EBA7D0@phx.gbl>
References: <BAY13-F79E6C1111A696BAD2AD8EBA7D0@phx.gbl>
Message-ID: <Pine.LNX.4.64.0606301452300.25862@hkn.eecs.berkeley.edu>


Hi Hafsa,

> Can you guide me how to save the output returned by a regular expression 
> group, into a text file? for instance for the following regular 
> expression:

[regex cut]

> If the above regular expression is searched for in a file, how can i 
> save the output matches from the group "name" into a new text file?


I'm not sure the problem you have has to do with regular expressions.  Do 
you mind if we change the question to something slightly different?

If you were given a function that takes a string and returns another 
string, could you write a program that uses it and writes the result to 
disk?  For example, let's say that we have a string like "hello world", 
process it through, well:

     def double(s):
         "double: string -> string
         doubles up the input string s."
         return s + s

Would you be able to write a program that takes "hello world", runs it 
through double(), and writes out "hello worldhelloworld" to disk?

What I'm trying to isolate the problem: does it have to do with 
input/output, or regular expressions, or something else?


Best of wishes!

From dyoo at hkn.eecs.berkeley.edu  Sat Jul  1 00:04:41 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 30 Jun 2006 15:04:41 -0700 (PDT)
Subject: [Tutor] saving output in a text file
In-Reply-To: <Pine.LNX.4.64.0606301452300.25862@hkn.eecs.berkeley.edu>
References: <BAY13-F79E6C1111A696BAD2AD8EBA7D0@phx.gbl>
	<Pine.LNX.4.64.0606301452300.25862@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0606301502340.25862@hkn.eecs.berkeley.edu>

>    def double(s):
>        "double: string -> string
>        doubles up the input string s."
>        return s + s


Gaah.  Typos.  My apologies.  Here's a correction to double()

    def double(s):
        """double: string -> string
        Doubles up the input string s.  For example, double("abc")
        should return "abcabc".
        """
        return s + s


> Would you be able to write a program that takes "hello world", runs it 
> through double(), and writes out "hello worldhelloworld" to disk?

I meant to say that the expected content of the file should be:

     "hello worldhello world"

My apologies; I rushed that message too quickly.

From anilmrn at yahoo.com  Sat Jul  1 09:13:11 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sat, 1 Jul 2006 00:13:11 -0700 (PDT)
Subject: [Tutor] static variables - lock/semaphore
Message-ID: <20060701071311.79366.qmail@web55908.mail.re3.yahoo.com>

hi
i have a program that is run on a website, and as it
is run from a website, it can be called more than once
and hence could end up corrupting db/data
is there a way to use some sort of semaphore or lock
so that it is not accessed simultaneously
the problem is it can be done with static variables in
C but how is it done in python
thanks a lot

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From alan.gauld at freenet.co.uk  Sat Jul  1 15:06:25 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 1 Jul 2006 14:06:25 +0100
Subject: [Tutor] static variables - lock/semaphore
References: <20060701071311.79366.qmail@web55908.mail.re3.yahoo.com>
Message-ID: <001701c69d0f$28775fa0$0301a8c0@XPpro>

> i have a program that is run on a website, and as it
> is run from a website, it can be called more than once
> and hence could end up corrupting db/data
> is there a way to use some sort of semaphore or lock
> so that it is not accessed simultaneously

There are ways of doing this in Python but if you are using 
a relational database for the data its usually easier to 
apply row level locking at the database level.

> the problem is it can be done with static variables in
> C but how is it done in python

It could be done with a global variable in Python in the 
same way but there are other solutions based around
threads which have explicit locks etc. For a web 
application using Python threads would probably be 
a good bet.

But you may find the whole problem simplified by adopting a 
web framework such as TurboGears which will take care of 
a lot of these kinds of issues for you - but with a bit of a 
learning curve. But if you have several web apps to build 
I'd seriously consider this route.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From lipofib at yahoo.com  Sat Jul  1 16:03:47 2006
From: lipofib at yahoo.com (Liviu Antoniu)
Date: Sat, 1 Jul 2006 07:03:47 -0700 (PDT)
Subject: [Tutor] python debugger
Message-ID: <20060701140347.24131.qmail@web31901.mail.mud.yahoo.com>

Hi, guys,

I have a small  problem with python's debugger. I don't know how can I debugg a script through this debugger.
Can you tell me?
Thank you very much

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060701/e11f6fc8/attachment.html 

From kent37 at tds.net  Sat Jul  1 16:30:56 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 01 Jul 2006 16:30:56 +0200
Subject: [Tutor] static variables - lock/semaphore
In-Reply-To: <20060701071311.79366.qmail@web55908.mail.re3.yahoo.com>
References: <20060701071311.79366.qmail@web55908.mail.re3.yahoo.com>
Message-ID: <44A68720.4010007@tds.net>

anil maran wrote:
> hi
> i have a program that is run on a website, and as it
> is run from a website, it can be called more than once
> and hence could end up corrupting db/data
> is there a way to use some sort of semaphore or lock
> so that it is not accessed simultaneously
> the problem is it can be done with static variables in
> C but how is it done in python

If you are using a database for storage you should learn how to use the 
transactional features of the database. They are designed to let you 
control what happens when multiple users access the database at the same 
time.

To protect access to other kinds of data look at threading.Lock and RLock.

Kent


From dyoo at hkn.eecs.berkeley.edu  Sat Jul  1 19:18:00 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 1 Jul 2006 10:18:00 -0700 (PDT)
Subject: [Tutor] saving output in a text file (fwd)
Message-ID: <Pine.LNX.4.64.0607011017440.2333@hkn.eecs.berkeley.edu>

[forwarding to Tutor]

---------- Forwarded message ----------
Date: Sat, 01 Jul 2006 13:58:47 +0400
From: Hafsa raza <hafsaraza at hotmail.com>
To: dyoo at hkn.eecs.berkeley.edu
Subject: Re: [Tutor] saving output in a text file


Thank you for the quick reply. Let me put my question in a more
clearer way for you.

If we want to create a text file and write some text into it we use the
following command in Python:

myfile = open("test.txt","w")<?xml:namespace prefix = o ns =
"urn:schemas-microsoft-com:office:office" />

myfile.write("hello world")

But what if instead of writing the text 'hello world', i want to write
the output returned by a regular expression pattern, into the text file,
how would we specify that in the write command.

Regards,

Hafsa





________________________________________________________________________________
From:  Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
To:  Hafsa raza <hafsaraza at hotmail.com>
CC:  tutor at python.org
Subject:  Re: [Tutor] saving output in a text file
Date:  Fri, 30 Jun 2006 15:04:41 -0700 (PDT)
>    def double(s):
>        "double: string -> string
>        doubles up the input string s."
>        return s + s


Gaah.  Typos.  My apologies.  Here's a correction to double()

     def double(s):
         """double: string -> string
         Doubles up the input string s.  For example, double("abc")
         should return "abcabc".
         """
         return s + s


>Would you be able to write a program that takes "hello world",
runs
>it through double(), and writes out "hello worldhelloworld" to
disk?

I meant to say that the expected content of the file should be:

      "hello worldhello world"

My apologies; I rushed that message too quickly.


________________________________________________________________________________
FREE pop-up blocking with the new MSN Toolbar MSN Toolbar Get it now!

From dyoo at hkn.eecs.berkeley.edu  Sat Jul  1 19:40:20 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 1 Jul 2006 10:40:20 -0700 (PDT)
Subject: [Tutor] saving output in a text file (fwd)
In-Reply-To: <Pine.LNX.4.64.0607011017440.2333@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0607011017440.2333@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0607011027330.2333@hkn.eecs.berkeley.edu>

> If we want to create a text file and write some text into it we use the 
> following command in Python:
>
> myfile = open("test.txt","w")<?xml:namespace prefix = o ns =
> "urn:schemas-microsoft-com:office:office" />
>
> myfile.write("hello world")
>
> But what if instead of writing the text 'hello world', i want to write 
> the output returned by a regular expression pattern, into the text file, 
> how would we specify that in the write command.


Just as a disclaimer: I am doing my utmost not to give out The Answer 
here.  So if it sounds like I'm not being very direct, that's precisely 
because you have a good intuition.  *grin* I'm trying to poke at the 
source of the problem, and not the immediate side effects.



You still haven't tackled my initial question about:

>     def double(s):
>         """double: string -> string
>         Doubles up the input string s.  For example, double("abc")
>         should return "abcabc".
>         """
>         return s + s
>
>
> Would you be able to write a program that takes "hello world", runs it 
> through double(), and writes out "hello worldhello world" to disk?

Can you try this mini-problem first?  What you've done doesn't touch on 
the question: would you know how to use double() as a part of the write()?

Note that this is just a variation of your original question, replacing 
the regex part with the use of a helper function.  It seems like this 
should be even easier than the problem you're having now.

Here's why I'm asking this: if you're getting stuck at this point too, 
then I'll assume that the problem is that you are unfamiliar with using 
helper functions and function composition.  Then the group as a whole can 
help you with that, since that's a fundamental programming skill that 
you'll want to develop.

But if you can do the mini-exercise, then the focus shifts to the use of 
regular expressions, and things become much easier, since it'll mean that 
you're not familiar with the regex API.

From anilmrn at yahoo.com  Sun Jul  2 09:18:17 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sun, 2 Jul 2006 00:18:17 -0700 (PDT)
Subject: [Tutor] help regarding string
Message-ID: <20060702071817.39753.qmail@web55903.mail.re3.yahoo.com>

please help me format this string from 
input : 2006-06-16 16:23:27.703000 to
output: 2006-06-16 16:23:27

or 2006-06-16 4:23:27 PM

thanks a lot 

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From pythontut at pusspaws.net  Sun Jul  2 12:09:48 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 2 Jul 2006 11:09:48 +0100
Subject: [Tutor] can't import module
Message-ID: <200607021109.48893.pythontut@pusspaws.net>

Hi all,

I wrote some script a while back but can no longer get it to run, since then I 
have upgraded my system from breezy to dapper (kubuntu) I now cannot import a 
module I wrote. I just know its got to be simple and am somewhat embarrassed 
that I cannot see the problem :(

dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$ ./live_datad.py
Traceback (most recent call last):
  File "./live_datad.py", line 15, in ?
    from logger import log
ImportError: No module named logger

OK that's my problem 

dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$ echo $PYTHONPATH
/home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/my_gg/gg1.4/logs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_files/my_gg/gg1.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dave/my_files/my_gg/gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/common_utils
dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$
dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$ 
ls -al /home/dave/my_files/my_gg/gg1.4/gg_utils

total 92
drwxr-xr-x  2 dave dave 4096 2006-03-27 13:03 .
drwxr-xr-x 13 dave dave 4096 2006-06-07 22:12 ..
-rwxr-xr-x  1 dave dave 1301 2005-01-31 20:35 archive_read.py
-rw-r--r--  1 dave dave 1612 2005-02-06 10:18 archive_read.pyc
-rw-r--r--  1 dave dave 1612 2005-02-06 12:44 archive_read.pyo
-rwxr-xr-x  1 dave dave 2630 2005-02-04 22:54 convert_data.py
-rw-r--r--  1 dave dave 2631 2005-02-06 10:18 convert_data.pyc
-rw-r--r--  1 dave dave 2631 2005-02-06 12:44 convert_data.pyo
-rw-r--r--  1 dave dave 1146 2005-01-31 20:35 cookie_string.py
-rw-r--r--  1 dave dave 1315 2005-11-20 15:21 cookie_string.pyc
-rw-r--r--  1 dave dave 1420 2005-02-06 12:44 cookie_string.pyo
-rwxr-xr-x  1 dave dave 1531 2005-02-04 12:34 dump_key.py
-rw-r--r--  1 dave dave 1470 2005-02-04 12:34 dump_key.pyc
-rw-r--r--  1 dave dave 1470 2005-02-06 12:44 dump_key.pyo
-rwxr-xr-x  1 dave dave 1906 2005-01-31 20:35 html_strip.py
-rw-r--r--  1 dave dave 2069 2005-11-20 15:13 html_strip.pyc
-rw-r--r--  1 dave dave 2380 2005-02-06 12:44 html_strip.pyo
-rwxr--r--  1 dave dave 2646 2005-01-31 20:35 logger.py
-rw-r--r--  1 dave dave 3212 2005-11-20 15:13 logger.pyc
-rw-r--r--  1 dave dave 3546 2005-02-06 12:44 logger.pyo
-rwxr-xr-x  1 dave dave 1873 2005-01-31 20:35 tail_log.py
-rw-r--r--  1 dave dave 1990 2005-02-06 10:18 tail_log.pyc
-rw-r--r--  1 dave dave 1990 2005-02-06 12:44 tail_log.pyo
dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$
dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$    

so logger.py is in PYTHONPATH so why can't live_data.d see it ?

Any ideas .. 

Dave


From kent37 at tds.net  Sun Jul  2 12:20:58 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 02 Jul 2006 12:20:58 +0200
Subject: [Tutor] help regarding string
In-Reply-To: <20060702071817.39753.qmail@web55903.mail.re3.yahoo.com>
References: <20060702071817.39753.qmail@web55903.mail.re3.yahoo.com>
Message-ID: <44A79E0A.8070108@tds.net>

anil maran wrote:
> please help me format this string from 
> input : 2006-06-16 16:23:27.703000 to
> output: 2006-06-16 16:23:27
> 
> or 2006-06-16 4:23:27 PM

str.split() can extract everything up to the first period:
In [4]: '2006-06-16 16:23:27.703000'.split('.')[0]
Out[4]: '2006-06-16 16:23:27'

Kent


From kent37 at tds.net  Sun Jul  2 12:29:23 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 02 Jul 2006 12:29:23 +0200
Subject: [Tutor] can't import module
In-Reply-To: <200607021109.48893.pythontut@pusspaws.net>
References: <200607021109.48893.pythontut@pusspaws.net>
Message-ID: <44A7A003.1070206@tds.net>

Dave S wrote:
>  > dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$ ./live_datad.py
> Traceback (most recent call last):
>   File "./live_datad.py", line 15, in ?
>     from logger import log
> ImportError: No module named logger
> 
> dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$ echo $PYTHONPATH
> /home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/my_gg/gg1.4/logs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_files/my_gg/gg1.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dave/my_files/my_gg/gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/common_utils

I don't know why your import is failing, but from your PYTHONPATH it 
looks like you should consider making all the gg1.4 directories into 
packages, then you would have imports such as
from gg_utils.logger import log

This would simplify PYTHONPATH and I think reflect more accurately what 
you are doing.

Kent


From pythontut at pusspaws.net  Sun Jul  2 12:55:24 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 2 Jul 2006 11:55:24 +0100
Subject: [Tutor] can't import module
In-Reply-To: <44A7A003.1070206@tds.net>
References: <200607021109.48893.pythontut@pusspaws.net>
	<44A7A003.1070206@tds.net>
Message-ID: <200607021155.24065.pythontut@pusspaws.net>

On Sunday 02 July 2006 11:29, Kent Johnson wrote:
> Dave S wrote:
> >  > dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$ ./live_datad.py
> >
> > Traceback (most recent call last):
> >   File "./live_datad.py", line 15, in ?
> >     from logger import log
> > ImportError: No module named logger
> >
> > dave at dave-comp:~/my_files/my_gg/gg1.4/get_data$ echo $PYTHONPATH
> > /home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/my_gg/gg1.4/l
> >ogs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_files/my_gg/gg1
> >.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dave/my_files/my_gg/
> >gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/common_utils
>
> I don't know why your import is failing, but from your PYTHONPATH it
> looks like you should consider making all the gg1.4 directories into
> packages,
> then you would have imports such as 
> from gg_utils.logger import log
>
> This would simplify PYTHONPATH and I think reflect more accurately what
> you are doing.
>

Thanks for replying :)

The app is fairly big and distributed around the gg1.4 directory. I get the 
feeling that 'from logger import log' is the first of a lot of import 
problems, this script alone imports from another 7 modules

from urllib import urlopen
from time import strftime
from cPickle import dump
from datetime import datetime, time, timedelta
from os import remove

from logger import log
from html_strip import html_strip
from garbage_collect import garbage_collect
from valid_day import valid_day
from exact_sleep import sleep_delay,sleep_until
from cookie_string import cookie_string
from data_core import Data_Core

from config import data_dir,HTML_addr, ipc_dir

As far a putting everything into a package - I am a bit lost. Do you mean one 
big .py script or am I misunderstanding you ?

Dave



> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at freenet.co.uk  Sun Jul  2 16:15:09 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 2 Jul 2006 15:15:09 +0100
Subject: [Tutor] python debugger
References: <20060701140347.24131.qmail@web31901.mail.mud.yahoo.com>
Message-ID: <003101c69de1$ed68d230$0301a8c0@XPpro>

> I have a small  problem with python's debugger. 
> I don't know how can I debugg a script through this debugger.
> Can you tell me?

There are several debuggers available on top of the basic pdb module.
If you know the Gnu debugger gdb then pdb is closely modelled 
on that. If you don't know gdb you are probably better off with a 
graphical interface such as the debuggers in IDLE or Pythonwin.

If you really want to learn how to use pdb let us know and we 
can talk you through it - not a bad thing since text based 
debuggers are potentially powerful testing tools. But I'd try 
the graphical tools first.

If the IDLE/Pyhtonwin debuggers still don't make sense tell 
us specifically what the issues are and we can tryu to help 
there too.

OTOH if it is debugging in general that you are having difficulty 
with then its very possible you never bneed to start a debugger 
tool, simple test strategies can often be more effective.

Alan g.



From alan.gauld at freenet.co.uk  Sun Jul  2 16:24:41 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 2 Jul 2006 15:24:41 +0100
Subject: [Tutor] static variables - lock/semaphore
References: <20060701202246.19822.qmail@web55905.mail.re3.yahoo.com>
Message-ID: <005101c69de3$423c6870$0301a8c0@XPpro>

> if we compare rowlevel locking and global variables
> which scales and is better

>>Alan Gauld <alan.gauld at freenet.co.uk> wrote: 
>>> is there a way to use some sort of semaphore or lock
>>> so that it is not accessed simultaneously
> >
> > There are ways of doing this in Python but if you are using 
> > a relational database for the data its usually easier to 
> > apply row level locking at the database level.

Row level locking in the database is far more scaleable than 
global variables. They are more reliable, only apply during the 
actual database writes and cannot be circiumvented by 
programs forking or spawning clones of themselves or by 
other applications accessing the same data.

Almost all very high volume applicatoons use database locking
- everything from banking systems to airtline bookings etc.
Coupled to the transaction management features of a database 
(Commit, rollback etc) you can build very powerful, very scaleable 
databases capable of handling 100s of transactions per second.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From dkuhlman at rexx.com  Sun Jul  2 18:02:26 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sun, 2 Jul 2006 09:02:26 -0700
Subject: [Tutor] can't import module
In-Reply-To: <200607021155.24065.pythontut@pusspaws.net>
References: <200607021109.48893.pythontut@pusspaws.net>
	<44A7A003.1070206@tds.net>
	<200607021155.24065.pythontut@pusspaws.net>
Message-ID: <20060702160226.GA52212@cutter.rexx.com>

On Sun, Jul 02, 2006 at 11:55:24AM +0100, Dave S wrote:

[snip]
> 
> Thanks for replying :)
> 
> The app is fairly big and distributed around the gg1.4 directory. I get the 
> feeling that 'from logger import log' is the first of a lot of import 
> problems, this script alone imports from another 7 modules
> 
> from urllib import urlopen
> from time import strftime
> from cPickle import dump
> from datetime import datetime, time, timedelta
> from os import remove
> 
> from logger import log
> from html_strip import html_strip
> from garbage_collect import garbage_collect
> from valid_day import valid_day
> from exact_sleep import sleep_delay,sleep_until
> from cookie_string import cookie_string
> from data_core import Data_Core
> 
> from config import data_dir,HTML_addr, ipc_dir
> 

So, ask yourself:  Where is logger.py?  Modules logger,
html_strip, etc are not it the Python standard library (see:
http://docs.python.org/lib/lib.html).  Are they in your
application?  Are (were) they in some package that you had
previously installed (but that needs to be re-installed)?

One possible explanation for your problem is that when you
upgraded from Ubuntu/Kubuntu breezy to dapper, you also upgraded
from Python 2.3 to Python 2.4.  If so, Python is now importing
from:

    /usr/lib/python2.4/site-packages/

instead of:

    /usr/lib/python2.3/site-packages/

If so, there might be Python modules that need to be re-installed
by running Python 2.4 (instead of Python 2.3).  I know that on my
Kubuntu system, there is both Python 2.4 and 2.3.

If the above is *not* the problem, then you need to find out where
your application used to find these modules (e.g. logger).  That
will help you (or someone on this list) figure out how to enable
Python and your live_datad.py application to find them.

Hope this helps.

Dave K.

[snip]

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From pythontut at pusspaws.net  Sun Jul  2 18:30:03 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 2 Jul 2006 17:30:03 +0100
Subject: [Tutor] can't import module
In-Reply-To: <20060702160226.GA52212@cutter.rexx.com>
References: <200607021109.48893.pythontut@pusspaws.net>
	<200607021155.24065.pythontut@pusspaws.net>
	<20060702160226.GA52212@cutter.rexx.com>
Message-ID: <200607021730.03707.pythontut@pusspaws.net>

On Sunday 02 July 2006 17:02, Dave Kuhlman wrote:
> On Sun, Jul 02, 2006 at 11:55:24AM +0100, Dave S wrote:
>
> [snip]
>
> > Thanks for replying :)
> >
> > The app is fairly big and distributed around the gg1.4 directory. I get
> > the feeling that 'from logger import log' is the first of a lot of import
> > problems, this script alone imports from another 7 modules
> >
> > from urllib import urlopen
> > from time import strftime
> > from cPickle import dump
> > from datetime import datetime, time, timedelta
> > from os import remove
> >
> > from logger import log
> > from html_strip import html_strip
> > from garbage_collect import garbage_collect
> > from valid_day import valid_day
> > from exact_sleep import sleep_delay,sleep_until
> > from cookie_string import cookie_string
> > from data_core import Data_Core
> >
> > from config import data_dir,HTML_addr, ipc_dir
>
> So, ask yourself:  Where is logger.py?  Modules logger,
> html_strip, etc are not it the Python standard library (see:
> http://docs.python.org/lib/lib.html).  Are they in your
> application?  Are (were) they in some package that you had
> previously installed (but that needs to be re-installed)?
>

They are all from my fair hand - coded about a year ago. I have just copied 
the whole directory to my new dapper system, changed PYTHONPATH and was 
somewhat supprised it has not just worked.

> One possible explanation for your problem is that when you
> upgraded from Ubuntu/Kubuntu breezy to dapper, you also upgraded
> from Python 2.3 to Python 2.4.  If so, Python is now importing
> from:
>
>     /usr/lib/python2.4/site-packages/
>
> instead of:
>
>     /usr/lib/python2.3/site-packages/

I see your point but because these are all my own packages I would guess the 
python version would be irrelevant

>
> If so, there might be Python modules that need to be re-installed
> by running Python 2.4 (instead of Python 2.3).  I know that on my
> Kubuntu system, there is both Python 2.4 and 2.3.
>
> If the above is *not* the problem, then you need to find out where
> your application used to find these modules (e.g. logger).  That
> will help you (or someone on this list) figure out how to enable
> Python and your live_datad.py application to find them.

OK I am going to try a couple of real basic scripts and import a module to see 
where it all falls down. I will email back with the results :)

Cheers

Dave



>
> Hope this helps.
>
> Dave K.
>
> [snip]

From alan.gauld at freenet.co.uk  Sun Jul  2 18:47:43 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 2 Jul 2006 17:47:43 +0100
Subject: [Tutor] Fw: Reg refreshing cache in Cheetah Templates
Message-ID: <005e01c69df7$3d842070$0301a8c0@XPpro>


----- Original Message ----- 
From: "anil maran" <anilmrn at yahoo.com>
To: <alan.gauld at freenet.co.uk>
Sent: Saturday, July 01, 2006 9:46 PM
Subject: Reg refreshing cache in Cheetah Templates


> hi
> i m trying to use the cheetah templates do

Sorry Anil, I've only read the Cheetah overview, I've never
used them.... maybe someone else will know.
Its usually best to send questions to the list rather
than to individuals.

> cheetah - how do i use .refreshcaceh() in cheetah
> the doc is skimpy and doesnt tell more than you can use refreshcache
> with id to refresh a cache
> my code in html has
>
> #cache 30m, id =cachei
>
> #end cache

Alan G. 



From pythontut at pusspaws.net  Sun Jul  2 18:51:19 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 2 Jul 2006 17:51:19 +0100
Subject: [Tutor] can't import module
In-Reply-To: <20060702160226.GA52212@cutter.rexx.com>
References: <200607021109.48893.pythontut@pusspaws.net>
	<200607021155.24065.pythontut@pusspaws.net>
	<20060702160226.GA52212@cutter.rexx.com>
Message-ID: <200607021751.19063.pythontut@pusspaws.net>

Here goes ...

I have two files test1 and test2 ...


dave at dave-comp:~$ ls -l
total 37620
drwx------  8 dave dave     4096 2006-06-30 23:26 Desktop
drwxr-xr-x  9 dave dave     4096 2006-06-15 22:48 google-earth
drwxr-xr-x 13 dave dave     4096 2006-05-27 09:51 my_files
drwxr-xr-x  2 dave dave     4096 2006-06-24 21:29 Pictures
drwxr-xr-x  4 dave dave     4096 2006-07-02 03:00 PodCasts
drwxr-xr-x  2 dave dave     4096 2006-06-16 21:30 qemu
drwxr-xr-x  9 dave dave     4096 2006-06-30 22:30 SecondLife_1_10_5_1
-rw-r--r--  1 dave dave 38438806 2006-06-30 18:53 SecondLife_1_10_5_1.tar.bz2
drwxr-xr-x  2 dave dave     4096 2006-07-02 17:43 test1
drwxr-xr-x  2 dave dave     4096 2006-07-02 17:41 test2

Two simple scripts .... parent and child ...

dave at dave-comp:~$ cd test2
dave at dave-comp:~/test2$ cat child.py
#!/usr/bin/env python
# -*- coding: iso8859_1 -*-

def hello():
    print 'child says hello'

dave at dave-comp:~/test2$ cd ../test1
dave at dave-comp:~/test1$ cat parent.py
#!/usr/bin/env python
# -*- coding: iso8859_1 -*-

from child import hello

def test():
    print 'parent says hello'
    hello()

test()

And I hit my problem :(

dave at dave-comp:~/test1$ ./parent.py
Traceback (most recent call last):
  File "./parent.py", line 4, in ?
    from child import hello
ImportError: No module named child


PYTHONPATH ...

dave at dave-comp:~/test1$
dave at dave-comp:~/test1$
dave at dave-comp:~/test1$ echo $PYTHONPATH
/home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/my_gg/gg1.4/logs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_files/my_gg/gg1.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dave/my_files/my_gg/gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/common_utils:/home/dave/test2
dave at dave-comp:~/test1$


And where PYTHONPATH is set ...

dave at dave-comp:~/test1$ cat ~/.bashrc
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# don't put duplicate lines in the history. See bash(1) for more options
#export HISTCONTROL=ignoredups

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" -a -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm-color)
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:
\[\033[01;34m\]\w\[\033[00m\]\$ '
    ;;
*)
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
    ;;
esac

# Comment in the above and uncomment this below for a color prompt
#PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:
\[\033[01;34m\]\w\[\033[00m\]\$ '

# If this is an xterm set the title to user at host:dir
case "$TERM" in
xterm*|rxvt*)
    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007"'
    ;;
*)
    ;;
esac

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

#if [ -f ~/.bash_aliases ]; then
#    . ~/.bash_aliases
#fi

# enable color support of ls and also add handy aliases
if [ "$TERM" != "dumb" ]; then
    eval "`dircolors -b`"
    alias ls='ls --color=auto'
    #alias dir='ls --color=auto --format=vertical'
    #alias vdir='ls --color=auto --format=long'
fi

# some more ls aliases
#alias ll='ls -l'
#alias la='ls -A'
#alias l='ls -CF'

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
#if [ -f /etc/bash_completion ]; then
#    . /etc/bash_completion
#fi

PYTHONPATH=/home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/my_gg/gg1.4/logs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_files/my_gg/gg1.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dave/my_files/my_gg/gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/common_utils:/home/dave/test2
export EDITOR=vi

dave at dave-comp:~/test1$       


Dave            

From dyoo at hkn.eecs.berkeley.edu  Sun Jul  2 19:32:51 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 2 Jul 2006 10:32:51 -0700 (PDT)
Subject: [Tutor] can't import module
In-Reply-To: <200607021751.19063.pythontut@pusspaws.net>
References: <200607021109.48893.pythontut@pusspaws.net>
	<200607021155.24065.pythontut@pusspaws.net>
	<20060702160226.GA52212@cutter.rexx.com>
	<200607021751.19063.pythontut@pusspaws.net>
Message-ID: <Pine.LNX.4.64.0607021031550.28929@hkn.eecs.berkeley.edu>

> PYTHONPATH=/home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/my_gg/gg1.4/logs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_files/my_gg/gg1.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dave/my_files/my_gg/gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/common_utils:/home/dave/test2

Have you marked PYTHONPATH to be exportable?  Your shell may not do this 
automatically unless explicitely told to do so.

From dkuhlman at rexx.com  Sun Jul  2 19:48:43 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sun, 2 Jul 2006 10:48:43 -0700
Subject: [Tutor] can't import module
In-Reply-To: <Pine.LNX.4.64.0607021031550.28929@hkn.eecs.berkeley.edu>
References: <200607021109.48893.pythontut@pusspaws.net>
	<200607021155.24065.pythontut@pusspaws.net>
	<20060702160226.GA52212@cutter.rexx.com>
	<200607021751.19063.pythontut@pusspaws.net>
	<Pine.LNX.4.64.0607021031550.28929@hkn.eecs.berkeley.edu>
Message-ID: <20060702174843.GA57580@cutter.rexx.com>

On Sun, Jul 02, 2006 at 10:32:51AM -0700, Danny Yoo wrote:
> > PYTHONPATH=/home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/my_gg/gg1.4/logs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_files/my_gg/gg1.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dave/my_files/my_gg/gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/common_utils:/home/dave/test2
> 
> Have you marked PYTHONPATH to be exportable?  Your shell may not do this 
> automatically unless explicitely told to do so.

A simple test -- In order to check PYTHONPATH do the following:

    $ python
    Python 2.4.3 (#1, Apr 11 2006, 20:59:32)
    [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu9)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> import sys
    >>> print sys.path

Dave K.

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From alan.gauld at freenet.co.uk  Sun Jul  2 21:12:36 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 2 Jul 2006 20:12:36 +0100
Subject: [Tutor] can't import module
References: <200607021109.48893.pythontut@pusspaws.net><44A7A003.1070206@tds.net>
	<200607021155.24065.pythontut@pusspaws.net>
Message-ID: <002701c69e0b$7aad89a0$0301a8c0@XPpro>

> As far a putting everything into a package - I am a bit lost. Do you 
> mean one
> big .py script or am I misunderstanding you ?

You misunderstand him.

Python allows you to  reate a package structure of directories and 
files
such that all of the files within the top level directory and the 
subdirectories
are searched so you only need to specify the top level directory for 
all the
files in subndirectories to be found.

This requires creating some magic python definition files.
Check the docs for details.

The end result is that in pythonpath you add

/some/path/myPackage

and in your code you do

from myPackage import someModule

Check the docs for details.

Alan G. 



From pythontut at pusspaws.net  Sun Jul  2 21:16:49 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 2 Jul 2006 20:16:49 +0100
Subject: [Tutor] can't import module
In-Reply-To: <200607021155.24065.pythontut@pusspaws.net>
References: <200607021109.48893.pythontut@pusspaws.net>
	<44A7A003.1070206@tds.net>
	<200607021155.24065.pythontut@pusspaws.net>
Message-ID: <200607022016.49744.pythontut@pusspaws.net>

On Sunday 02 July 2006 20:12, Alan Gauld wrote:
> > As far a putting everything into a package - I am a bit lost. Do you
> > mean one
> > big .py script or am I misunderstanding you ?
>
> You misunderstand him.
>
> Python allows you to  reate a package structure of directories and
> files
> such that all of the files within the top level directory and the
> subdirectories
> are searched so you only need to specify the top level directory for
> all the
> files in subndirectories to be found.
>
> This requires creating some magic python definition files.
> Check the docs for details.
>
> The end result is that in pythonpath you add
>
> /some/path/myPackage
>
> and in your code you do
>
> from myPackage import someModule
>
> Check the docs for details.
>
> Alan G.

Thanks for that - I never realised you could do that. It sound like a good 
solution and a lot less messy than the way I have created my own modules & 
scripts.

Dave

From pythontut at pusspaws.net  Sun Jul  2 21:24:22 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 2 Jul 2006 20:24:22 +0100
Subject: [Tutor] SOLVED :)
In-Reply-To: <Pine.LNX.4.64.0607021031550.28929@hkn.eecs.berkeley.edu>
References: <200607021109.48893.pythontut@pusspaws.net>
	<200607021751.19063.pythontut@pusspaws.net>
	<Pine.LNX.4.64.0607021031550.28929@hkn.eecs.berkeley.edu>
Message-ID: <200607022024.22867.pythontut@pusspaws.net>

On Sunday 02 July 2006 18:32, Danny Yoo wrote:
> > PYTHONPATH=/home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/my
> >_gg/gg1.4/logs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_file
> >s/my_gg/gg1.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dave/my_f
> >iles/my_gg/gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/common_utils
> >:/home/dave/test2
>
> Have you marked PYTHONPATH to be exportable?  Your shell may not do this
> automatically unless explicitely told to do so.

You solved it !

starting my PYTHONPATH with export did the trick for my demo files & for 
live_datad.py. :)

Thank you so much, I knew it had to be something relatively simple but I could 
just not see it.

Cheers

Dave

From pythontut at pusspaws.net  Sun Jul  2 21:29:09 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 2 Jul 2006 20:29:09 +0100
Subject: [Tutor] can't import module
In-Reply-To: <20060702174843.GA57580@cutter.rexx.com>
References: <200607021109.48893.pythontut@pusspaws.net>
	<Pine.LNX.4.64.0607021031550.28929@hkn.eecs.berkeley.edu>
	<20060702174843.GA57580@cutter.rexx.com>
Message-ID: <200607022029.09785.pythontut@pusspaws.net>

On Sunday 02 July 2006 18:48, Dave Kuhlman wrote:
> On Sun, Jul 02, 2006 at 10:32:51AM -0700, Danny Yoo wrote:
> > > PYTHONPATH=/home/dave/my_files/my_gg/gg1.4/configs:/home/dave/my_files/
> > >my_gg/gg1.4/logs:/home/dave/my_files/my_gg/gg1.4/get_data:/home/dave/my_
> > >files/my_gg/gg1.4/gg_utils:/home/dave/my_files/my_gg/gg1.4/ipc:/home/dav
> > >e/my_files/my_gg/gg1.4/process_data:/home/dave/my_files/my_gg/gg1.4/comm
> > >on_utils:/home/dave/test2
> >
> > Have you marked PYTHONPATH to be exportable?  Your shell may not do this
> > automatically unless explicitely told to do so.
>
> A simple test -- In order to check PYTHONPATH do the following:
>
>     $ python
>     Python 2.4.3 (#1, Apr 11 2006, 20:59:32)
>     [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu9)] on linux2
>     Type "help", "copyright", "credits" or "license" for more information.
>
>     >>> import sys
>     >>> print sys.path
>
> Dave K.

Thank you also. inadvertently I think you have given me the key to another 
problem that has been bugging me for a couple of weeks to do with paths and 
library's a python app accesses.

['', '/home/dave/my_files/my_gg/gg1.4/configs', '/home/dave/my_files/my_gg/gg1.4/logs', '/home/dave/my_files/my_gg/gg1.4/get_data', '/home/dave/my_files/my_gg/gg1.4/gg_utils', '/home/dave/my_files/my_gg/gg1.4/ipc', '/home/dave/my_files/my_gg/gg1.4/process_data', '/home/dave/my_files/my_gg/gg1.4/common_utils', '/home/dave/test2', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/HTMLgen', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/PIL', '/usr/lib/python2.4/site-packages/cairo', '/usr/lib/python2.4/site-packages/gst-0.10', '/usr/lib/python2.4/site-packages/gtk-2.0']

One question, where is the rest of PYTHONPATH defined, my section in .bashrc 
is only the first part, where do you get to define the /usr/lib part ?

Dave


From kent37 at tds.net  Sun Jul  2 21:44:33 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 02 Jul 2006 21:44:33 +0200
Subject: [Tutor] can't import module
In-Reply-To: <200607022029.09785.pythontut@pusspaws.net>
References: <200607021109.48893.pythontut@pusspaws.net>	<Pine.LNX.4.64.0607021031550.28929@hkn.eecs.berkeley.edu>	<20060702174843.GA57580@cutter.rexx.com>
	<200607022029.09785.pythontut@pusspaws.net>
Message-ID: <44A82221.9040308@tds.net>

Dave S wrote:
> One question, where is the rest of PYTHONPATH defined, my section in .bashrc 
> is only the first part, where do you get to define the /usr/lib part ?

Much of sys.path is set up in site.py in the standard library. This 
module is always imported when the interpreter starts up. Read the 
source for details...

Kent


From kent37 at tds.net  Mon Jul  3 12:26:13 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 03 Jul 2006 12:26:13 +0200
Subject: [Tutor] help regarding string
In-Reply-To: <20060703050707.36533.qmail@web55908.mail.re3.yahoo.com>
References: <20060703050707.36533.qmail@web55908.mail.re3.yahoo.com>
Message-ID: <44A8F0C5.4010205@tds.net>

anil maran wrote:
> 
>     'datetime.datetime' object has no attribute 'split'
> 
> 
> thisis the error i get

Ah, then your data is not a string, it is a datetime.datetime object. 
You can format it using datetime.datetime.strftime():
In [1]: import datetime

In [2]: d=datetime.datetime.now()

In [3]: d
Out[3]: datetime.datetime(2006, 7, 3, 6, 24, 2, 93000)

In [4]: print d
2006-07-03 06:24:02.093000

In [5]: d.strftime('%Y-%m-%d %H:%M:%S')
Out[5]: '2006-07-03 06:24:02'

Kent

> */Kent Johnson <kent37 at tds.net>/* wrote:
> 
>     anil maran wrote:
>      > please help me format this string from
>      > input : 2006-06-16 16:23:27.703000 to
>      > output: 2006-06-16 16:23:27
>      >
>      > or 2006-06-16 4:23:27 PM
> 
>     str.split() can extract everything up to the first period:
>     In [4]: '2006-06-16 16:23:27.703000'.split('.')[0]
>     Out[4]: '2006-06-16 16:23:27'
> 
>     Kent
> 
>     _______________________________________________
>     Tutor maillist - Tutor at python.org
>     http://mail.python.org/mailman/listinfo/tutor
> 
> 
> Yahoo! Messenger with Voice. Make PC-to-Phone Calls 
> <http://us.rd.yahoo.com/mail_us/taglines/postman1/*http://us.rd.yahoo.com/evt=39663/*http://voice.yahoo.com> 
> to the US (and 30+ countries) for 2?/min or less.



From emily.fortuna at nist.gov  Mon Jul  3 17:10:51 2006
From: emily.fortuna at nist.gov (Emily Fortuna)
Date: Mon, 03 Jul 2006 11:10:51 -0400
Subject: [Tutor] storing dict objects in in a database through SQLObject
Message-ID: <44A9337B.3070404@nist.gov>

Hello all,
I am experiementing in storing Python objects in a SQLite databse using 
SQLOjbect.  I want to store dicts and tuples in the databse, but as far 
as I can tell the only way to do this is to create a PickleCol.  Is 
there some other better way to store this data?  EnumCol?  Would a 
different database interface support this idea better?
Many thanks,
Emily


From kent37 at tds.net  Mon Jul  3 17:39:43 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 03 Jul 2006 17:39:43 +0200
Subject: [Tutor] storing dict objects in in a database through SQLObject
In-Reply-To: <44A9337B.3070404@nist.gov>
References: <44A9337B.3070404@nist.gov>
Message-ID: <44A93A3F.1070207@tds.net>

Emily Fortuna wrote:
> Hello all,
> I am experiementing in storing Python objects in a SQLite databse using 
> SQLOjbect.  I want to store dicts and tuples in the databse, but as far 
> as I can tell the only way to do this is to create a PickleCol.  Is 
> there some other better way to store this data?  EnumCol?  Would a 
> different database interface support this idea better?

What is in the dicts and tuples? It sounds like you haven't matched your 
data structures and your database very well. To store a dict, maybe you 
want a table of key/value pairs. For the tuples, if they are all the 
same structure, each element of the tuple might correspond to a database 
field and each tuple would be one database record.

I'm not to familiar with SQLObject but you might make a persistent class 
for the key/value pair of the dictionary and another class to represent 
the contents of a tuple.

Kent


From dustin at v.igoro.us  Mon Jul  3 17:16:03 2006
From: dustin at v.igoro.us (Dustin J.Mitchell)
Date: Mon, 3 Jul 2006 10:16:03 -0500
Subject: [Tutor] storing dict objects in in a database through SQLObject
In-Reply-To: <44A9337B.3070404@nist.gov>
References: <44A9337B.3070404@nist.gov>
Message-ID: <df74c35073c5e597926896696f6f3d64@v.igoro.us>

You'll actually get better support from sqlite than from other 
databases.  The question is one of balance: are you more concerned with 
easily getting your dicts and tuples back intact, or with executing 
queries on the *contents* of those dicts and tuples?  Sqlite will treat 
pickles as opaque objects, and will be unable to do anything with their 
contents.

Dustin

On Jul 3, 2006, at 10:10 AM, Emily Fortuna wrote:

> I am experiementing in storing Python objects in a SQLite databse using
> SQLOjbect.  I want to store dicts and tuples in the databse, but as far
> as I can tell the only way to do this is to create a PickleCol.  Is
> there some other better way to store this data?  EnumCol?  Would a
> different database interface support this idea better?


From emily.fortuna at nist.gov  Mon Jul  3 18:00:32 2006
From: emily.fortuna at nist.gov (Emily Fortuna)
Date: Mon, 03 Jul 2006 12:00:32 -0400
Subject: [Tutor] storing dict objects in in a database through SQLObject
In-Reply-To: <df74c35073c5e597926896696f6f3d64@v.igoro.us>
References: <44A9337B.3070404@nist.gov>
	<df74c35073c5e597926896696f6f3d64@v.igoro.us>
Message-ID: <44A93F20.1080406@nist.gov>

 > The question is one of balance: are you more concerned with
 > easily getting your dicts and tuples back intact, or with executing
 > queries on the *contents* of those dicts and tuples?
Ideally, I'd like to be able to search the data in these dicts.  Is 
there a way to do this? If not, PickleCol seems to be the way to go...

To Kent:
 > What is in the dicts and tuples?
I am trying to store several different classes of objects into the 
database using SQLObject, some of which have dicts as attributes.  The 
classes may be extended and the dicts store variable amounts of entries. 
  I want this framework to be extensible as possible, but perhaps I am 
taking the wrong approach.  The object classes were designed with their 
manipulation in mind, in addition to simply database storage. Is there a 
better design you can suggest?
Emily


From kent37 at tds.net  Mon Jul  3 18:56:20 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 03 Jul 2006 18:56:20 +0200
Subject: [Tutor] storing dict objects in in a database through SQLObject
In-Reply-To: <44A93F20.1080406@nist.gov>
References: <44A9337B.3070404@nist.gov>	<df74c35073c5e597926896696f6f3d64@v.igoro.us>
	<44A93F20.1080406@nist.gov>
Message-ID: <44A94C34.4040505@tds.net>

Emily Fortuna wrote:
>  > The question is one of balance: are you more concerned with
>  > easily getting your dicts and tuples back intact, or with executing
>  > queries on the *contents* of those dicts and tuples?
> Ideally, I'd like to be able to search the data in these dicts.  Is 
> there a way to do this? If not, PickleCol seems to be the way to go...
> 
> To Kent:
>  > What is in the dicts and tuples?
> I am trying to store several different classes of objects into the 
> database using SQLObject, some of which have dicts as attributes.  The 
> classes may be extended and the dicts store variable amounts of entries. 
>   I want this framework to be extensible as possible, but perhaps I am 
> taking the wrong approach.  The object classes were designed with their 
> manipulation in mind, in addition to simply database storage. Is there a 
> better design you can suggest?

The objects have a one-to-many relationship with the attributes. Maybe 
you should have a class to hold an attribute and set up a one-to-many 
relationship in SQLObject. Then the main object would contain a list of 
attributes, rather than a dict.

As far as I know SQLObject doesn't support a named mapping in the style 
of a dict. But I am just a dabbler in SQLObject; you might want to ask 
on the SQLObject mailing list.

SQLAlchemy seems to support what you want; see this example:
http://www.sqlalchemy.org/docs/adv_datamapping.myt#advdatamapping_properties_customlist

Another alternative is an object database such as ZODB or Durus.

Kent


From a.m.i.x at web.de  Mon Jul  3 18:53:14 2006
From: a.m.i.x at web.de (Andreas)
Date: Mon, 03 Jul 2006 18:53:14 +0200
Subject: [Tutor] Moved Python installation. Need advice rebuilding all *.pyc
Message-ID: <44A94B7A.9010404@web.de>

Hi,

I thought, this would be more easy. I wonder why the PYTHONPATH is not
being considered here, but instead I find the path to modules being
hardcoded  in the *.pyc file.

I have about 50 3rd party modules installed and I moved my Python
installation from C:\Python24 to another partition (E:\Python24).

Now, what can I say ? It seems I need to rebuild all, but this would be
an immense amount of work (finding all the install-archives on the net,
etc.)

Is there any simple way ? Maybe a script, that iterates through
"Lib/site-packages" ?

Thanks a lot!

From adam.jtm30 at gmail.com  Mon Jul  3 20:45:58 2006
From: adam.jtm30 at gmail.com (Adam)
Date: Mon, 3 Jul 2006 19:45:58 +0100
Subject: [Tutor] Moved Python installation. Need advice rebuilding all
	*.pyc
In-Reply-To: <44A94B7A.9010404@web.de>
References: <44A94B7A.9010404@web.de>
Message-ID: <be4fbf920607031145k6eaacd6fi1f73b14b78f7bf4d@mail.gmail.com>

On 03/07/06, Andreas <a.m.i.x at web.de> wrote:
>
> Hi,
>
> I thought, this would be more easy. I wonder why the PYTHONPATH is not
> being considered here, but instead I find the path to modules being
> hardcoded  in the *.pyc file.
>
> I have about 50 3rd party modules installed and I moved my Python
> installation from C:\Python24 to another partition (E:\Python24).
>
> Now, what can I say ? It seems I need to rebuild all, but this would be
> an immense amount of work (finding all the install-archives on the net,
> etc.)
>
> Is there any simple way ? Maybe a script, that iterates through
> "Lib/site-packages" ?
>
> Thanks a lot!


Erm trying to remember exactly how to do this in windows but if you do the
equivalent of an rm -r E:\Python24\site-packages\*.pyc ie remove all the
*.pyc files they will be rebuilt as and when you next import those modules.
HTH.
Adam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060703/2980d705/attachment.html 

From a.m.i.x at web.de  Mon Jul  3 22:34:56 2006
From: a.m.i.x at web.de (Andreas)
Date: Mon, 03 Jul 2006 22:34:56 +0200
Subject: [Tutor] Moved Python installation. Need advice rebuilding all
 *.pyc
In-Reply-To: <be4fbf920607031145k6eaacd6fi1f73b14b78f7bf4d@mail.gmail.com>
References: <44A94B7A.9010404@web.de>
	<be4fbf920607031145k6eaacd6fi1f73b14b78f7bf4d@mail.gmail.com>
Message-ID: <44A97F70.6050305@web.de>

On 03.07.2006 20:45 Adam wrote

> Erm trying to remember exactly how to do this in windows but if you do the
> equivalent of an rm -r E:\Python24\site-packages\*.pyc ie remove all the
> *.pyc files they will be rebuilt as and when you next import those modules.

Thanks for the info. However, if this is being done automatically on
import, why does "python setup.py install" often do some compilation ?

From python at venix.com  Mon Jul  3 23:06:07 2006
From: python at venix.com (Python)
Date: Mon, 03 Jul 2006 17:06:07 -0400
Subject: [Tutor] Moved Python installation. Need advice rebuilding
	all	*.pyc
In-Reply-To: <44A97F70.6050305@web.de>
References: <44A94B7A.9010404@web.de>
	<be4fbf920607031145k6eaacd6fi1f73b14b78f7bf4d@mail.gmail.com>
	<44A97F70.6050305@web.de>
Message-ID: <1151960767.10267.859.camel@www.venix.com>

On Mon, 2006-07-03 at 22:34 +0200, Andreas wrote:
> On 03.07.2006 20:45 Adam wrote
> 
> > Erm trying to remember exactly how to do this in windows but if you do the
> > equivalent of an rm -r E:\Python24\site-packages\*.pyc ie remove all the
> > *.pyc files they will be rebuilt as and when you next import those modules.
> 
> Thanks for the info. However, if this is being done automatically on
> import, why does "python setup.py install" often do some compilation ?

There is a program called compileall.py.  I'm on linux and do not know
the default Windows location.

	cd E:\Python24\site-packages
	python ???\python2.4\???\compileall.py .

Linux:	/usr/lib/python2.4/compileall.py

It will provide some help info if asked.
	python ???\python2.4\???\compileall.py --help

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From tktucker at gmail.com  Tue Jul  4 09:56:53 2006
From: tktucker at gmail.com (Tom Tucker)
Date: Tue, 4 Jul 2006 03:56:53 -0400
Subject: [Tutor] stfftime question
Message-ID: <2a278ffe0607040056j20b854b5q4d438ada88ffb1f@mail.gmail.com>

Below is an example of me converting a datetime to milliseconds on a
Mac running Pythong 2.3.5.  The same working code on a Solaris system
with Python 2.3.2 fails.  Any thoughts? What arguments am I missing?



>From my Mac
#############
Python 2.3.5 (#1, Oct  5 2005, 11:07:27)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dtstr = datetime.datetime(1973,9,4,04,3,25,453)
>>> output = dtstr.strftime('%s.%%03d') % (dtstr.microsecond)
>>> print output
115977805.453


>From Work (Solaris)
################
Python 2.3.2 (#1, Nov 17 2003, 22:32:28)
[GCC 2.95.3 20010315 (release)] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dtstr = datetime.datetime(1973,9,4,04,3,25,453)
>>> output = dtstr.strftime('%s.%%03d') % (dtstr.microsecond)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: not enough arguments for format string
>>>

From govilakanksha at yahoo.com  Tue Jul  4 11:07:41 2006
From: govilakanksha at yahoo.com (Akanksha Govil)
Date: Tue, 4 Jul 2006 02:07:41 -0700 (PDT)
Subject: [Tutor] Query regarding Unittest module behaviour
Message-ID: <20060704090741.20791.qmail@web36513.mail.mud.yahoo.com>

Hi,

I have 2 scripts , abc.py and xyz.py, In both I have made unittest cases using the unittest module.

Script abc.py imports xyz.py.
Now when I execute abc.py from commandlline all unittestcases of xyz.py are also executed. 
Why is this happening and what can be the solution to this.

Also I have tried commenting the unittest.main() in xyz.py, but all in vain.


Please help

Akanksha

 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060704/29662f3d/attachment.html 

From tktucker at gmail.com  Tue Jul  4 12:21:53 2006
From: tktucker at gmail.com (Tom Tucker)
Date: Tue, 4 Jul 2006 06:21:53 -0400
Subject: [Tutor] stfftime question
In-Reply-To: <2a278ffe0607040056j20b854b5q4d438ada88ffb1f@mail.gmail.com>
References: <2a278ffe0607040056j20b854b5q4d438ada88ffb1f@mail.gmail.com>
Message-ID: <2a278ffe0607040321u611c1331s6813719c74ff1717@mail.gmail.com>

I found a temporary solution.  The goal in the end was to compare two
dates/times and  retrieve the millisecond delta between the two.

Work around
#############
import datetime
import time
t1 = datetime.datetime(1973,9,4,04,3,25,453)
t2 = datetime.datetime(1973,9,4,04,3,25,553)
t1tuple = time.mktime(t1.timetuple())+(t1.microsecond/1000.)
t2tuple = time.mktime(t2.timetuple())+(t2.microsecond/1000.)
delta  = (t2tuple - t1tuple) * 1000
print delta



On 7/4/06, Tom Tucker <tktucker at gmail.com> wrote:
> Below is an example of me converting a datetime to milliseconds on a
> Mac running Pythong 2.3.5.  The same working code on a Solaris system
> with Python 2.3.2 fails.  Any thoughts? What arguments am I missing?
>
>
>
> From my Mac
> #############
> Python 2.3.5 (#1, Oct  5 2005, 11:07:27)
> [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import datetime
> >>> dtstr = datetime.datetime(1973,9,4,04,3,25,453)
> >>> output = dtstr.strftime('%s.%%03d') % (dtstr.microsecond)
> >>> print output
> 115977805.453
>
>
> From Work (Solaris)
> ################
> Python 2.3.2 (#1, Nov 17 2003, 22:32:28)
> [GCC 2.95.3 20010315 (release)] on sunos5
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import datetime
> >>> dtstr = datetime.datetime(1973,9,4,04,3,25,453)
> >>> output = dtstr.strftime('%s.%%03d') % (dtstr.microsecond)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: not enough arguments for format string
> >>>
>

From adam.jtm30 at gmail.com  Tue Jul  4 12:27:38 2006
From: adam.jtm30 at gmail.com (Adam)
Date: Tue, 4 Jul 2006 11:27:38 +0100
Subject: [Tutor] Moved Python installation. Need advice rebuilding all
	*.pyc
In-Reply-To: <44A97F70.6050305@web.de>
References: <44A94B7A.9010404@web.de>
	<be4fbf920607031145k6eaacd6fi1f73b14b78f7bf4d@mail.gmail.com>
	<44A97F70.6050305@web.de>
Message-ID: <be4fbf920607040327p462f27bajc890caa75c3c41b0@mail.gmail.com>

On 03/07/06, Andreas <a.m.i.x at web.de> wrote:
>
> On 03.07.2006 20:45 Adam wrote
>
> > Erm trying to remember exactly how to do this in windows but if you do
> the
> > equivalent of an rm -r E:\Python24\site-packages\*.pyc ie remove all the
> > *.pyc files they will be rebuilt as and when you next import those
> modules.
>
> Thanks for the info. However, if this is being done automatically on
> import, why does "python setup.py install" often do some compilation ?


It reduces the loading time for the modules if there is already a *.pyc so
the setup script often does it in advance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060704/cef20c22/attachment.html 

From rabidpoobear at gmail.com  Tue Jul  4 12:36:55 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 04 Jul 2006 05:36:55 -0500
Subject: [Tutor] Query regarding Unittest module behaviour
In-Reply-To: <20060704090741.20791.qmail@web36513.mail.mud.yahoo.com>
References: <20060704090741.20791.qmail@web36513.mail.mud.yahoo.com>
Message-ID: <44AA44C7.7080801@gmail.com>

[snip]
> Script abc.py imports xyz.py.
> Now when I execute abc.py from commandlline all unittestcases of 
> xyz.py are also executed.
> Why is this happening and what can be the solution to this.
anything that's in the global scope  of an imported module gets executed.
For example...

------ a.py
print "hello"
------------

 >>> import a
This will cause the "hello" to be printed from 'a.py' because it's in 
the global scope.
so what you want to do is something like this:

-----a.py

def main():
    print "hello"

if __name__ == "__main__":
    main()
-------

Now if you do
 >>> import a
nothing will be printed.

But, if you do "python a.py" on command line, you'll see "hello" be printed.
I think this is the problem you're having.
HTH,
-Luke

From kent37 at tds.net  Tue Jul  4 13:13:35 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 04 Jul 2006 13:13:35 +0200
Subject: [Tutor] stfftime question
In-Reply-To: <2a278ffe0607040321u611c1331s6813719c74ff1717@mail.gmail.com>
References: <2a278ffe0607040056j20b854b5q4d438ada88ffb1f@mail.gmail.com>
	<2a278ffe0607040321u611c1331s6813719c74ff1717@mail.gmail.com>
Message-ID: <44AA4D5F.8050101@tds.net>

Tom Tucker wrote:
> I found a temporary solution.  The goal in the end was to compare two
> dates/times and  retrieve the millisecond delta between the two.
> 
> Work around
> #############
> import datetime
> import time
> t1 = datetime.datetime(1973,9,4,04,3,25,453)
> t2 = datetime.datetime(1973,9,4,04,3,25,553)
> t1tuple = time.mktime(t1.timetuple())+(t1.microsecond/1000.)
> t2tuple = time.mktime(t2.timetuple())+(t2.microsecond/1000.)
> delta  = (t2tuple - t1tuple) * 1000
> print delta

You could also subtract the datetimes directly to get a timedelta:
In [13]: t1 = datetime.datetime(1973,9,4,04,3,25,453)

In [14]: t2 = datetime.datetime(1973,9,4,04,3,25,553)

In [15]: diff = t2-t1

In [16]: diff
Out[16]: datetime.timedelta(0, 0, 100)

In [17]: diff.microseconds
Out[17]: 100

or if the diff can be bigger use
((diff.days * 24*60*60) * diff.seconds) * 1000 + diff.microseconds

> On 7/4/06, Tom Tucker <tktucker at gmail.com> wrote:
>> Below is an example of me converting a datetime to milliseconds on a
>> Mac running Pythong 2.3.5.  The same working code on a Solaris system
>> with Python 2.3.2 fails.  Any thoughts? What arguments am I missing?
>>
>>
>>
>> From my Mac
>> #############
>> Python 2.3.5 (#1, Oct  5 2005, 11:07:27)
>> [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>> import datetime
>>>>> dtstr = datetime.datetime(1973,9,4,04,3,25,453)
>>>>> output = dtstr.strftime('%s.%%03d') % (dtstr.microsecond)
>>>>> print output
>> 115977805.453

I think you want '%S.%%03d' as the format string (uppercase S). %s is 
not a standard format and it is probably handled differently on Mac OS 
and Solaris. What is the result of dtstr.strftime('%s.%%03d') on each 
machine? On Windows I get
In [11]: dtstr.strftime('%s.%%03d')
Out[11]: '.%03d'

Perhaps Solaris just passes the unknown format to output, that would 
give the error you see.

Kent

>>
>>
>> From Work (Solaris)
>> ################
>> Python 2.3.2 (#1, Nov 17 2003, 22:32:28)
>> [GCC 2.95.3 20010315 (release)] on sunos5
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>> import datetime
>>>>> dtstr = datetime.datetime(1973,9,4,04,3,25,453)
>>>>> output = dtstr.strftime('%s.%%03d') % (dtstr.microsecond)
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>> TypeError: not enough arguments for format string
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From funny_cow at hotmail.com  Tue Jul  4 19:20:26 2006
From: funny_cow at hotmail.com (StevenG the Judge)
Date: Tue, 04 Jul 2006 13:20:26 -0400
Subject: [Tutor] Correct way to code data or parse?
Message-ID: <BAY108-F20FDAE4C96E70D294134BC81710@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060704/32cca014/attachment.html 

From brian at daviesinc.com  Tue Jul  4 19:56:43 2006
From: brian at daviesinc.com (Brian Gustin)
Date: Tue, 04 Jul 2006 13:56:43 -0400
Subject: [Tutor] I Give Up. - Follow up post
In-Reply-To: <001c01c69324$b90a6610$0301a8c0@XPpro>
References: <loom.20060612T211646-24@post.gmane.org><7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com>	<20060618194636.GA22079@cutter.rexx.com>
	<001c01c69324$b90a6610$0301a8c0@XPpro>
Message-ID: <44AAABDB.4010400@daviesinc.com>

OK see, what I was doing originally (and I found time to finally get it 
partially working)

I have a configuration file that may be edited by webmaster thus

[Ports]

http = 80
https = 443
http1 = 81
smtp = 25
smtp2 = 587

(the above is a small example, it could be *anything* )

Now I have a function that takes machine, protocol, and a dictionary of 
last alerts (would be empty if none)

The whole is a small multiple machine monitoring script, By the way...

The configuration file needed to be read by config parser and assign the 
config name as if it were a variable, and the value along with it

I tried it by opening a file , but could find no way to do variable 
variables

(In PHP, you can do something to the effect of:
name = value
name1 = value1

and then read it in as a file , which builds an array (AKA dictionary)
and then just assign thus:

foreach ($filearray as $key => $value)
{
	$$key = $value
}

in python I could see no way to do so, so I ended up with configparser, 
which I *finally* got working - working code below
I am still working on this , as I wanna do it in python (currently 
operational in Perl , and running as a daemon, which I want this code to 
do eventually)

So, the below is a working example of reading a config file in python 
using configparser

Also note: I found that ConfigParser != configparser (it is case sensitive)

Just wanted to post this back in case anyone else needs to figure out 
how to use configparser in python.

import ConfigParser
cfg = ConfigParser.SafeConfigParser()
     cfg.read("/home/brian/pymon.cfg")
     if cfg.has_section("Parameters"):
         myparams = cfg.items("Parameters")
         for item in myparams:
             parameter[item[0]] = item[1]
     else:
         log_error("Parameters","not found")
     if cfg.has_section("Ports"):
         ports = cfg.items("Ports")
         for port in ports:
             watch_port[port[0]] = port[1]
     else:
         log_error("Ports","Not Found")
     if cfg.has_section("Hosts"):
         hostnames = cfg.items("Hosts")
         for hostname in hostnames:
             watch_hosts[hostname[0]] = hostname[1]
     else:
         log_error("Hosts","Not Found")
     if cfg.has_section("IP Addresses"):
         ips = cfg.items("IP Addresses")
         for ip in ips:
             watch_ips[ip[0]] = ip[1]
     else:
         log_error("IP Addresses","Not Found")
     if cfg.has_section("Alerts"):
         alerts_to = cfg.items("Alerts")
     else:
         log_error("Hosts","Not Found")
     print parameter
     print watch_port
     print watch_hosts
     print watch_ips
     print alerts_to

From dyoo at hkn.eecs.berkeley.edu  Tue Jul  4 20:41:32 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 4 Jul 2006 11:41:32 -0700 (PDT)
Subject: [Tutor] I Give Up. - Follow up post
In-Reply-To: <44AAABDB.4010400@daviesinc.com>
References: <loom.20060612T211646-24@post.gmane.org><7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com>
	<20060618194636.GA22079@cutter.rexx.com>
	<001c01c69324$b90a6610$0301a8c0@XPpro>
	<44AAABDB.4010400@daviesinc.com>
Message-ID: <Pine.LNX.4.64.0607041126270.19371@hkn.eecs.berkeley.edu>

> I tried it by opening a file , but could find no way to do variable 
> variables


Hi Brian,

Look for the concept of dictionaries in Python.  "Variable variables" in 
languages like PHP and Perl are doable in Python, but a dictionary usually 
handles such situations in a safer way.


> and then read it in as a file , which builds an array (AKA dictionary)
> and then just assign thus:
>
> foreach ($filearray as $key => $value)
> {
> 	$$key = $value
> }

This is not safe in Python, because the $key given could easily be the 
name of something that shouldn't be treated as configuration, such as the 
built-in functions.  It also makes debugging a bit harder if we have 
variables in a program that aren't explicitely named.

The safe way to do this is to sandbox these variables in a dictionary. 
Conceptually, the pseudocode looks like:

################################
config_options = {}
for (name, value) in the file:
     config_options[name] = value
################################

and the real code to do this doesn't look too much different.



Let's look at some of the config-reading code:

>     if cfg.has_section("Parameters"):
>         myparams = cfg.items("Parameters")
>         for item in myparams:
>             parameter[item[0]] = item[1]
>     else:
>         log_error("Parameters","not found")
>     if cfg.has_section("Ports"):
>         ports = cfg.items("Ports")
>         for port in ports:
>             watch_port[port[0]] = port[1]
>     else:
>         log_error("Ports","Not Found")
>     if cfg.has_section("Hosts"):
>         hostnames = cfg.items("Hosts")
>         for hostname in hostnames:
>             watch_hosts[hostname[0]] = hostname[1]
>     else:
>         log_error("Hosts","Not Found")
>     if cfg.has_section("IP Addresses"):
>         ips = cfg.items("IP Addresses")
>         for ip in ips:
>             watch_ips[ip[0]] = ip[1]
>     else:
>         log_error("IP Addresses","Not Found")
>     if cfg.has_section("Alerts"):
>         alerts_to = cfg.items("Alerts")
>     else:
>         log_error("Hosts","Not Found")


There's a lot of repetition here.  When we have the temptation to copy and 
paste, try to see if a helper function can do some lifting.

In fact, there's a bug there because of the copy-and-paste.  If there are 
no Alerts, the system will spuriously blame Hosts.  I resent being blamed 
for things I don't do, and I'm sure my programs feel the same.  *grin*

Here's a possible refactoring:

#########################################################
def read_config_section(section_name, output_dictionary):
     if cfg.has_section(section_name)
         section = cfg.items(section_name)
     else:
         log_error(section_name, "Not Found")
     for key_value in section:
         output_dictionary[key_value[0]] = key_value[1]
#########################################################

Once we have this, we can then do:

     read_config_section("Parameters", parameter)
     read_config_section("Ports", watch_port)
     ...

and eliminate a lot of that repetitive code.


Does this make sense?  Feel free to ask more questions.

From brian at daviesinc.com  Tue Jul  4 22:49:11 2006
From: brian at daviesinc.com (Brian Gustin)
Date: Tue, 04 Jul 2006 16:49:11 -0400
Subject: [Tutor] I Give Up. - Follow up post
In-Reply-To: <Pine.LNX.4.64.0607041126270.19371@hkn.eecs.berkeley.edu>
References: <loom.20060612T211646-24@post.gmane.org><7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com>
	<20060618194636.GA22079@cutter.rexx.com>
	<001c01c69324$b90a6610$0301a8c0@XPpro>
	<44AAABDB.4010400@daviesinc.com>
	<Pine.LNX.4.64.0607041126270.19371@hkn.eecs.berkeley.edu>
Message-ID: <44AAD447.6060601@daviesinc.com>



Danny Yoo wrote:
>> I tried it by opening a file , but could find no way to do variable 
>> variables
> 
> 
> 
> Hi Brian,
> 
> Look for the concept of dictionaries in Python.  "Variable variables" in 
> languages like PHP and Perl are doable in Python, but a dictionary 
> usually handles such situations in a safer way.

Yeah I am familiar with the concept , and it would work nicely for some 
applications, but I couldnt make it work the way I need it to for this 
application :)

Reason: It's more to do with the further functions in the application 
that I did not paste in the follow up :)

The issue, again is that I want to call a variable by *name* , but I do 
not *KNOW* what that variable's name is, exactly

For example, say I have apache running on port 80, apache-ssl on 443, 
apache2 on port 81, and Caudium on port 8080 (yes I do have a machine 
running not only those servers, but AOLServer, simultaneously)

If I want to configure a protocol to check, *for multiple machines*  I 
might do

(pseudo function)

Check_Host(machine,protocol,port,last_results)

Now, if I want to iterate over a list of machines , and check each 
machine for whatever it was set for (in the config file)

I cannot obviously have a config that says
(Protocol = Port)
http = 80
http = 81
http = 8080
smtp = 25

So the config file requires http to be the first part of the string , 
followed by something to make it unique (I.E. http1, http2, http3)

Now, if I pass each value in turn to check_host, how do I tell what type 
of check to make ? (Obviously if I want to get a string from a web page, 
I need to SEND a GET request, but if I am checking smtp, I cannot use 
that same function, SO.... )

I check for the base of the configuration (if http in protocol: then run 
http request, else something else)

so that I can run the correct request type on the correct port , and 
maintain a log, but I cannot do that as effectively if it is a 
dictionary or list or even a foreach ..

As I said, I have looked at this from every angle I could see, but using 
dictionary (which was my *first* choice) did not work the way I needed 
it to, nor did simply reading a file to get name value pairs  I needed 
the name to be an actual variable name..

believe me I have tried dictionaries, Ive tried parsing the file by 
other means, but the only way I could get results I needed was through 
configparser

> 
>> and then read it in as a file , which builds an array (AKA dictionary)
>> and then just assign thus:
>>
>> foreach ($filearray as $key => $value)
>> {
>>     $$key = $value
>> }

> 
> This is not safe in Python, because the $key given could easily be the 
> name of something that shouldn't be treated as configuration, such as 
> the built-in functions.  It also makes debugging a bit harder if we have 
> variables in a program that aren't explicitely named.
Yes, I am well aware of the dangers of  taking values unchecked into an 
array such as this method shows (simplified).. I rarely ever use it, or 
if I do, it is on *known* clean data (example, pulling config data out 
of a database , reading a .ini file, etc.. not untrusted user input)

I have seen people use this method to extract POST and GET data for 
example (untrusted user input) , which I find horrifying :)

> 
> The safe way to do this is to sandbox these variables in a dictionary. 
> Conceptually, the pseudocode looks like:
> 
> ################################
> config_options = {}
> for (name, value) in the file:
>     config_options[name] = value
> ################################
> 
> and the real code to do this doesn't look too much different.
> 
Yeah, basically you carry values in a dictionary named by keyname , 
but..  there have been situations where I need the key name as the 
variable name , I.E. config_options[name] = value could become

name = value as if it was explicitly defined that way

It's difficult to grasp or even effectively explain the concept or idea, 
but sometimes you need to KNOW the key name, *without* knowing the key 
name :)  (confused yet? hahaha)

> 
> 
> Let's look at some of the config-reading code:
> 
>>     if cfg.has_section("Parameters"):
>>         myparams = cfg.items("Parameters")
>>         for item in myparams:
>>             parameter[item[0]] = item[1]
>>     else:
>>         log_error("Parameters","not found")
>>     if cfg.has_section("Ports"):
>>         ports = cfg.items("Ports")
>>         for port in ports:
>>             watch_port[port[0]] = port[1]
>>     else:
>>         log_error("Ports","Not Found")
>>     if cfg.has_section("Hosts"):
>>         hostnames = cfg.items("Hosts")
>>         for hostname in hostnames:
>>             watch_hosts[hostname[0]] = hostname[1]
>>     else:
>>         log_error("Hosts","Not Found")
>>     if cfg.has_section("IP Addresses"):
>>         ips = cfg.items("IP Addresses")
>>         for ip in ips:
>>             watch_ips[ip[0]] = ip[1]
>>     else:
>>         log_error("IP Addresses","Not Found")
>>     if cfg.has_section("Alerts"):
>>         alerts_to = cfg.items("Alerts")
>>     else:
>>         log_error("Hosts","Not Found")
> 
> 
> 
> There's a lot of repetition here.  When we have the temptation to copy 
> and paste, try to see if a helper function can do some lifting.

Agreed. however I just set this as a preliminary - in no way is this 
code finished. :)  I actually intended to build a function to do this.
(In perl, I use Switch/Case statements, does Python have anything 
similar?  - with switch/case, you can set a final default "catch-all" at 
which point I log a "unknown event" message )

> 
> In fact, there's a bug there because of the copy-and-paste.  If there 
> are no Alerts, the system will spuriously blame Hosts.  I resent being 
> blamed for things I don't do, and I'm sure my programs feel the same.  
> *grin*

Yep. see above comment :-D
> 
> Here's a possible refactoring:
> 
> #########################################################
> def read_config_section(section_name, output_dictionary):
>     if cfg.has_section(section_name)
>         section = cfg.items(section_name)
>     else:
>         log_error(section_name, "Not Found")
>     for key_value in section:
>         output_dictionary[key_value[0]] = key_value[1]
> #########################################################
> 
> Once we have this, we can then do:
> 
>     read_config_section("Parameters", parameter)
>     read_config_section("Ports", watch_port)
>     ...
> 
> and eliminate a lot of that repetitive code.
> 
> 
> Does this make sense?  Feel free to ask more questions.

Yeah it makes sense,, a lot of what I posted here is just some 
preliminary stuff- related to the O.P. that I could not fnid sufficient 
documentation or examples of ConfigParser to get it to do what I needed, 
which is to set variable namespace according to defined config (ini) file

In php, I would make a .ini file and use parse_ini_file() function.

For the worknig perl monitoring script, I used Parse::RecDescent

Anyhow, the main point of this follow up is a basic example for the 
future if someone else runs into the same issues I did (Python's 
documentation is not well written at all, and difficult to use)




> 
> !DSPAM:44aac00477171290140515!
> 
> 

From xzu_seton at yahoo.com  Tue Jul  4 21:16:20 2006
From: xzu_seton at yahoo.com (DM)
Date: Tue, 4 Jul 2006 12:16:20 -0700 (PDT)
Subject: [Tutor] Correct way to code data or parse?
Message-ID: <20060704191620.79947.qmail@web50904.mail.yahoo.com>

Hi Everyone

*Please forgive me the repost ... I sent the first as
Html not Text .... Dumb, Doh!
 
I'm new to python and I want to write a rpg program
that is able to use the
Correct way to code data or parse?  I have pages of
.PDF file Data tables copied to text files.
I check out many python boards & Books with little
illumination to my problem.
I'm still not sure about what to use for this data
listing:
 
 Lists?, Tuple? there is some expressions with a
variable(WP) in the data!
 Dictionary? same as Tuple?
 Text file read?
 Function?, Module?, Class?

How would a Pro approch this ? 


What I'v been thinking is like this:
 
...................
 
Very basic Brakedown of program:  (#=Number Variables,
$=String Data)
=============================================
 
Which Damage Table? : ... 
Type .......... $(Cutting, Puncture, Bludgeon.
Three(3) Types of weapon inflicted wounds)
Zone .......... #(2d6 dice roll or Number generated by
players Attack choice. { A General Body Location.})
Which Row? : ............ Location ........... #(1d6
die roll. { A more Specific body location.})
Which Column? : ......... Wound Level .... #(Number
generated by Wounds Taken.)
 
 == WOUND (#$Blood-Loss, #$Shock, #$Pain, $##Wound
Description)

==============================================
 
........ Sample of One Zones Data ...........
 
ZONE: 14, ARM 
---------------------------------------------
# My data is like this: 
# Roll, Location, 
# Level One: .... BL, Shock, Pain, Wound Description
# Level Two: .... BL, Shock, Pain, Wound Description
# Level Three:... BL, Shock, Pain, Wound Description
# Level Four: .... BL, Shock, Pain, Wound Description
# Level Five: ..... BL, Shock, Pain, Wound Description

1, Hand
0, 6-WP, 5-WP, Surface graze. May drop anything held
in hand.
0, 3, 4-WP, Some flesh (like the palm) and bruised
bone. May drop at -3
2, 9-WP, 6-WP, Pierced hand totally. May drop handheld
items (at -4)
5, 7, 9-WP, Hit wrist bones (instantly drop whatever
may be held in that hand)
9, 8, 9-WP, As previous, a slashed artery or vein

2-3, Forearm
0 5-WP 4-WP,
1 5 6-WP,
2 5 6-WP,
6 7 8-WP,
7 8 9-WP,
Grazed 
Bone chipped (may drop handheld items)
As a level two, plus you automatically drop anything
held
Totally passes through, causing greater blood loss and
forcing any item to be dropped
As level four, with more blood and some bone damage
 
4, Elbow
0 6-WP 5-WP,
0 4 6-WP,
3 6 7-WP,
5 8 9-WP,
7 9 11-WP,
Glancing blow
Solid blow; funnybone effect. May drop items in that
hand
Torn ligament or similar wound; instantly drop items
in that hand
Dislocated or otherwise jacked up elbow. Use of arm
temporarily lost
Shattered elbow. Arm now useless
 
5-6, Upper arm
0 4-WP 4-WP,
1 3 5-WP,
3 5 6-WP,
5 6 7-WP,
7 7 8-WP,
Light laceration
Deeper puncture, including torn muscle
Serious flesh wound, including torn tendons
More serious damage and bleeding, including some bone
damage
As level four, but with more serious bleeding (a blood
vessel was hit)
 
.............end sample ...........
 
Thanks for any advice or help you can give me!
--
Steve Goodman




__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From dnelson at cae.wisc.edu  Tue Jul  4 23:37:37 2006
From: dnelson at cae.wisc.edu (dnelson at cae.wisc.edu)
Date: Tue, 04 Jul 2006 16:37:37 -0500
Subject: [Tutor] Two Newbile Questions: porting drawmap.c,
	& Python as a lifetime	language
Message-ID: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>

Relying heavily on the "newbies treated well" advertisment... :^)

I'm an old C programmer, which is to say (a) I am old, and (b) even  
when young, I somehow managed to program in "old C".

I have been working--for years--on creating a personal variant of  
drawmap.c, Fred M. Erickson's wonderful  
USGS-maps-to-shaded-relief-or-contour-map-renderer, and I have finally  
hit the wall. I have managed to make things sooo complex that the  
effort to learn a new language no longer seems unaffordable.

I am seeking opinions from seasoned veterans on the following two questions:

1. What's involved in a port of a C program into Python?  (drawmap is  
offered in
    a number of linux distributions btw.)

2. Seeing Python hailed as a good language for learning programming,  
how do you
    rate it as a lifetime language? (I can imagine that many people have
    settled into one language for doing the remainder of their life's work. If
    I am pressed, I will choose Perl at this point.)

Humbly,
--
David


From dyoo at hkn.eecs.berkeley.edu  Wed Jul  5 00:11:54 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 4 Jul 2006 15:11:54 -0700 (PDT)
Subject: [Tutor] I Give Up. - Follow up post
In-Reply-To: <44AAD447.6060601@daviesinc.com>
References: <loom.20060612T211646-24@post.gmane.org><7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com>
	<20060618194636.GA22079@cutter.rexx.com>
	<001c01c69324$b90a6610$0301a8c0@XPpro>
	<44AAABDB.4010400@daviesinc.com>
	<Pine.LNX.4.64.0607041126270.19371@hkn.eecs.berkeley.edu>
	<44AAD447.6060601@daviesinc.com>
Message-ID: <Pine.LNX.4.64.0607041445210.19371@hkn.eecs.berkeley.edu>

> Now, if I want to iterate over a list of machines , and check each 
> machine for whatever it was set for (in the config file)

> So the config file requires http to be the first part of the string , 
> followed by something to make it unique (I.E. http1, http2, http3)


Hi Brian,

Have you considered using something other than the INI-style file format? 
ConfigParser works best when there is a fixed, known set of keys: it 
doesn't work so well when you want to use an arbitrary collection where 
you do not know the keys in advance.


Bluntly put: it does sound like the INI file format and what you 
ultimately want is not meshing well together.

Let's clarify the requirement: you want to have a mapping from services to 
their configurations.  Ignoring the format of the configuration file for 
the moment, it sounds like you ultimately want to parse the configruation 
and get:

     { 'apache'     : ('http', 80),
       ... }

where a 'machine' is the key into the corresponding (protocol, port) 
value.

If you are just prototyping this, a 'module' file like:

####################################
### machine_config.py
machines = { 'apache': ('http', 80),
              ## fill me in with the config of other machines
}
####################################

could be used as your configuration file format.  The value portion of a 
dictionary can be an arbitrary value.  Here, we map a machine's name to a 
tuple containing the protocol and port.  No string hackery is involved 
here.



> believe me I have tried dictionaries, Ive tried parsing the file by 
> other means, but the only way I could get results I needed was through 
> configparser

I think you're making this problem too hard for yourself.



> Yeah, basically you carry values in a dictionary named by keyname , 
> but..  there have been situations where I need the key name as the 
> variable name , I.E. config_options[name] = value could become
>
> name = value as if it was explicitly defined that way


Can you show us the situation you're talking about that requires this?



> It's difficult to grasp or even effectively explain the concept or idea,

Try to do so.  I think this is a real point that needs to be cleared up.



> Agreed. however I just set this as a preliminary - in no way is this 
> code finished. :)  I actually intended to build a function to do this. 
> (In perl, I use Switch/Case statements, does Python have anything 
> similar?  - with switch/case, you can set a final default "catch-all" at 
> which point I log a "unknown event" message )

Take a look at:

http://www.python.org/doc/faq/general.html#why-isn-t-there-a-switch-or-case-statement-in-python

If you need more examples, ask, and someone here on the list will be happy 
to help.

From python-tutor at v.igoro.us  Wed Jul  5 00:13:25 2006
From: python-tutor at v.igoro.us (Dustin J. Mitchell)
Date: Tue, 04 Jul 2006 17:13:25 -0500
Subject: [Tutor] Two Newbile Questions: porting drawmap.c,
 & Python as a lifetime	language
In-Reply-To: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>
References: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>
Message-ID: <44AAE805.9030903@v.igoro.us>

dnelson at cae.wisc.edu wrote:
> 1. What's involved in a port of a C program into Python?  (drawmap is  
> offered in a number of linux distributions btw.)

It really (really) depends on the C program -- C's so flexible that you
can write in a "Pythonish" style (specifically, avoiding pointer tricks,
keeping OS-specific stuff to a minimum, and using good functional / data
abstractions) or in a style that's so obfuscated as to make any sort of
translation impossible.  The flip side of that is that Python is
flexible enough to accommodate many programming styles.  It sounds like
this program basically parses an input file and produces an output file,
 so I would bet that you can find some existing code that will read the
input file, and some other existing code that will write the output
file.  Then you just have to write the middle part.

> 2. Seeing Python hailed as a good language for learning programming,  
> how do you
>     rate it as a lifetime language? (I can imagine that many people have
>     settled into one language for doing the remainder of their life's work. If
>     I am pressed, I will choose Perl at this point.)

Eep, Perl!  Once a polyglot, always a polyglot.  My choice of language
depends on the context.  For quick web stuff, PHP (O! How I hate thee!).
 For quick manipulation of files and/or using lots of external programs,
shell.  For just about everything else, Python.

From brian at daviesinc.com  Wed Jul  5 01:15:22 2006
From: brian at daviesinc.com (Brian Gustin)
Date: Tue, 04 Jul 2006 19:15:22 -0400
Subject: [Tutor] I Give Up. - Follow up post
In-Reply-To: <Pine.LNX.4.64.0607041445210.19371@hkn.eecs.berkeley.edu>
References: <loom.20060612T211646-24@post.gmane.org><7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com>
	<20060618194636.GA22079@cutter.rexx.com>
	<001c01c69324$b90a6610$0301a8c0@XPpro>
	<44AAABDB.4010400@daviesinc.com>
	<Pine.LNX.4.64.0607041126270.19371@hkn.eecs.berkeley.edu>
	<44AAD447.6060601@daviesinc.com>
	<Pine.LNX.4.64.0607041445210.19371@hkn.eecs.berkeley.edu>
Message-ID: <44AAF68A.2010605@daviesinc.com>

OK .. so far so good.. :)
> ultimately want is not meshing well together.
> 
> Let's clarify the requirement: you want to have a mapping from services 
> to their configurations.  Ignoring the format of the configuration file 
> for the moment, it sounds like you ultimately want to parse the 
> configruation and get:

> ####################################
> ### machine_config.py
> machines = { 'apache': ('http', 80),
>              ## fill me in with the config of other machines
> }
> ####################################
> 
> could be used as your configuration file format.  The value portion of a 
> dictionary can be an arbitrary value.  Here, we map a machine's name to 
> a tuple containing the protocol and port.  No string hackery is involved 
> here.
Umm well it would work nicely . *if* the configuration never changed- on 
the other hand, if it is to do as intended, the user of the application 
needs to be able to add and edit the configuration.

Unless they are well versed with python and/or programming and syntax, 
(in which case they probably arent going to use this script anyway)
it is easier for a non programmer to edit a configuration that makes 
some sort of logical sense and is easy to edit, without screwing up 
(need to make it more "forgiving" of things like line endings, spacing 
between name , = and value elements, etc)

So the ideal format is a configuration file where they can set up 
(within documented settings parameters) additional machines or protocols 
or ports to suit their own network or layout..

Easiest = a simple file where I set name = value and import it.
HOWEVER, if it is to be imported, it must follow proper python syntax, 
correct? so if it doesnt, they break it

an INI file on the other hand is a bit more forgiving, thus the choice 
to use it.

> 
> 
> 
>> believe me I have tried dictionaries, Ive tried parsing the file by 
>> other means, but the only way I could get results I needed was through 
>> configparser
> 
> 
> I think you're making this problem too hard for yourself.
> 
perhaps, when I get back to the project I plan to do a code review of 
code to date..
I have no problem with refactoring if I can find a better, momre 
effective way, but it *must* also be user friendly (ease of use and 
configuration for a non-programmer)

Another option I had was to do a web based interface for setting up 
additional machines, etc, but web based is non-ideal for this application.


> 
> 
>> Yeah, basically you carry values in a dictionary named by keyname , 
>> but..  there have been situations where I need the key name as the 
>> variable name , I.E. config_options[name] = value could become
>>
>> name = value as if it was explicitly defined that way
> 
> 
> 
> Can you show us the situation you're talking about that requires this?

if cfg.has_section("Hosts"):
         hostnames = cfg.items("Hosts")
         for hostname in hostnames:
             watch_hosts[hostname[0]] = hostname[1]

would result in like
watch_hosts = {"http" : "80","https" : "443"}

Sure, I could also do this by reading a config file and parsing it , but ..

Say you split at the = , and the config file is like

http = 80 #standard http port
  https=443#https port

Are you going to be 100% certain that when you call watch_hosts[http], 
that you are gonna GET string "80"?
  what about the space between http and =  ?

if you wanted to check if watch_hosts[keyname] == "http" , it would 
never work, right?(because if you split at =, you have string "http " <- 
see the space char?)

if I, however use configparser, I will always get "http" and "80" where 
I expect them to be , I dont have to worry (or send values through a 
cleanup or trim() function) if it has a comment for the line or not, I 
dont need to worry if there is whitespace. right?

This is intended for an end user to be able to edit a config file with a 
minimum of trouble, and be able to leave comments so they remember what 
each is for.. :)
(and if they do mess up somehow, I can catch that kind of thing in the 
code)

I just didnt see any more effective way to get this than to use 
ConfigParser as opposed to attempting to parse a file using regular 
expressions , trim, split, etc

> 
> 
> 
>> It's difficult to grasp or even effectively explain the concept or idea,
> 
> 
> Try to do so.  I think this is a real point that needs to be cleared up.

I understand the concept/idea behind it, I think above is about as good 
an explanation as it gets - I tried to express how Im 
thinking/approaching this issue. Keeping in mind this is going to be 
edited by someone who may or may not know how to write a single line of 
program code.. :)
> 

> Take a look at:
> 
> http://www.python.org/doc/faq/general.html#why-isn-t-there-a-switch-or-case-statement-in-python 
> 
Thanks. reading up on it now.

> 
> If you need more examples, ask, and someone here on the list will be 
> happy to help.
> 
> !DSPAM:44aae7ac185203757830825!
> 
> 

From kent37 at tds.net  Wed Jul  5 04:24:23 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 05 Jul 2006 04:24:23 +0200
Subject: [Tutor] Two Newbile Questions: porting drawmap.c,
 & Python as a lifetime	language
In-Reply-To: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>
References: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>
Message-ID: <44AB22D7.30602@tds.net>

dnelson at cae.wisc.edu wrote:
> 2. Seeing Python hailed as a good language for learning programming,  
> how do you
>     rate it as a lifetime language? (I can imagine that many people have
>     settled into one language for doing the remainder of their life's work. If
>     I am pressed, I will choose Perl at this point.)
Python is great as a general-purpose programming language and it is my 
language of choice today. But I'll be pretty surprised if it keeps the 
spot on the top of the heap for the rest of my working life...

Kent


From clsdaniel at gmail.com  Wed Jul  5 06:14:15 2006
From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela)
Date: Tue, 4 Jul 2006 21:14:15 -0700
Subject: [Tutor] Two Newbile Questions: porting drawmap.c,
	& Python as a lifetime language
In-Reply-To: <44AB22D7.30602@tds.net>
References: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>
	<44AB22D7.30602@tds.net>
Message-ID: <4fae7dfa0607042114q335783a0tf045f94dcceb4f1a@mail.gmail.com>

Really depends on what you do, if you program for a living most
probably you'll use whatever your employer tells you to use, if you
work by yourself you can choose, personally i like python because of
the enormous amount of modules available to do all sort of stuff, from
GUI programing, to unittest, database, compression, graphics (OpenGL),
etc.

I like it because is crossplatform, it may not be fast but most
modules are written in C already and are fast.

I like the ability to use py2exe and generate a windows executable in
a folder with ALL that i need to deploy on windows, i just copy the
folder and i'm done.

The Python comunity is very nice too, this is a big plus if you are
learning a new languaje, the tutor list is always very helpful and
active.

You can always make use of your C skills even on Python, by writting
modules to extend python functionability or to speed it up.

Good Luck!

Regards
Carlos Daniel Ruvalcaba Valenzuela

On 7/4/06, Kent Johnson <kent37 at tds.net> wrote:
> dnelson at cae.wisc.edu wrote:
> > 2. Seeing Python hailed as a good language for learning programming,
> > how do you
> >     rate it as a lifetime language? (I can imagine that many people have
> >     settled into one language for doing the remainder of their life's work. If
> >     I am pressed, I will choose Perl at this point.)
> Python is great as a general-purpose programming language and it is my
> language of choice today. But I'll be pretty surprised if it keeps the
> spot on the top of the heap for the rest of my working life...
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From rxdamian at gmail.com  Wed Jul  5 09:05:54 2006
From: rxdamian at gmail.com (Damian)
Date: Wed, 5 Jul 2006 02:05:54 -0500
Subject: [Tutor] program-code dilemma
Message-ID: <1eac597d0607050005t584235f6lbe1cd8004f6dee79@mail.gmail.com>

 Lately I've been researching about the general definitions of program
and code, and I've realized that the difference is not so convincent
(without mentioning simple and precise); that's why I'm sending this.

 My frame of reference has been very reliable (several programming
books, dictionaries, etc.), but I'll not mention it because it's not
so important for the objective of the post.

 Although, from what I've found I been able to get this conclusions.

   Program.-  A sequence of instructions that can be executed by the computer.

   Code.- Just the instructions of the program.

 Nevertheless for the few experience that I have, I know that a
program also have comments; wich at the same time could be what
differences a program from a code:

 Example:

   Program.- A sequence of instructions (with or without comments)
that can be executed
                  by the computer.

 The problem is that it seems too complicated for a definition so
important and essential to start learning to program (that without
getting account of what is missing for the completeness of the
definition).

 Although, I have clear that a program is like a container, and the
code is like the internal structure that conform it. I think that a
good analogy would be: "a code is to a program, what a GUI design is
to a graphic application."

 Please, do not doubt in telling me your experiences and opinions,
preferably with different languages. Always they're well founded.

PD: This will help me to extend my frame of reference.

From alan.gauld at freenet.co.uk  Wed Jul  5 10:50:07 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 5 Jul 2006 09:50:07 +0100
Subject: [Tutor] I Give Up. - Follow up post
References: <loom.20060612T211646-24@post.gmane.org><7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com><20060618194636.GA22079@cutter.rexx.com><001c01c69324$b90a6610$0301a8c0@XPpro><44AAABDB.4010400@daviesinc.com><Pine.LNX.4.64.0607041126270.19371@hkn.eecs.berkeley.edu><44AAD447.6060601@daviesinc.com><Pine.LNX.4.64.0607041445210.19371@hkn.eecs.berkeley.edu>
	<44AAF68A.2010605@daviesinc.com>
Message-ID: <001f01c6a010$04466140$0301a8c0@XPpro>

>> ####################################
>> ### machine_config.py
>> machines = { 'apache': ('http', 80),
>>              ## fill me in with the config of other machines
>> }
>> ####################################
>>
>> could be used as your configuration file format.  The value portion 
>> of a

> Umm well it would work nicely . *if* the configuration never 
> changed- on the other hand, if it is to do as intended, the user of 
> the application needs to be able to add and edit the configuration.

Ok, would an XML format work better? There are several good XML
parsers available.

<machine name='apache'>
    <protocol name = 'http'>
        <port=80/>
    </protocol>
    <protocol name='smtp'>
      etc...
</machine>

or something similar?

> it is easier for a non programmer to edit a configuration that makes 
> some sort of logical sense and is easy to edit, without screwing up 
> (need to make it more "forgiving" of things like line endings, 
> spacing between name , = and value elements, etc)

The other alternative is to provide a tool for editing the file in 
which
case the format is less important sionce hiumans "never" need to
touch it.

>>> believe me I have tried dictionaries, Ive tried parsing the file 
>>> by other means, but the only way I could get results I needed was 
>>> through configparser

If you are using ini file format config parser is the right choice.
But there are other file formats and making the data match the
problem is usually the biggest breakthrough in creating clean code.
So although ini format might be simplest to maintain by non technical
users if it forces you to ju7mp through hoops mayber a slihghtly more
complex format would be better.
(An example is the XF86 setup file used in Linux which uses a
syntax somewhat like a Python dictionary mixed with an ini file)

> Another option I had was to do a web based interface for setting up 
> additional machines, etc, but web based is non-ideal for this 
> application.

How about command line tools?
Somewhat like the commonly found adduser command in Unix?

>>> Yeah, basically you carry values in a dictionary named by keyname 
>>> , but..  there have been situations where I need the key name as 
>>> the variable name , I.E. config_options[name] = value could become
>>>
>>> name = value as if it was explicitly defined that way

While I understand the usefulness of this in an interactive 
environment
I'm puzzled about how this would work in a pre-written script. If you 
are
creating variables from a config file how do you know what those 
variables
are called? If you don;lt know how can you reference them later in the
code? And if you don;t reference them of what value is the variable
name? Therefore the logical conclusion(to me!) is that you must
know what names you expect to read and therefore can use a dictionary?

Typically the examples I've seen are where people use a known
name as the root and append a sequence number:

foo1 = 43
foo2 = 45
etc

then they use a loop later in the code to reconstitute the variable 
names.

But if a list is used inside a dictionary the same effect is achieved 
with
about the  same or less work:

vars['port'].append(42)
vars['port'].append(45)
for port in vars['port']:
    use port here.

The other scenario that often arises is that you know the variable 
names
you expect to find and only use those names, thus if a user causes
an unexpected name you just ignore it.

In this case you can create a dictionary of the known variable names
for validation purposes and link them to a set of helper functions 
(one
per variable) for storing the values in your variables:

Something like this:

machine = []  # list variable
port = None   # scalar value

def addMachine(value): machine.append(value)
def addPort(value):
     global port
     port = int(value)

vars = {'machine':addMachine,'port':addPort}

name = parseConfig()
if name in vars.keys():
    vars[name](parseConfig())

And if you don't like the helper functions you could use lambdas:

vars = {'machine':  lambda val: machine.append(val),
           'port':        lambda val: port = int(val)
          }

One you finish parsing the data you can now use machine and
port as normal variables, since that's what they are.
(Note: by converting the string value to an int I remove the issue
of extraneous spaces. Not a universal cure but a step forward)

>> Can you show us the situation you're talking about that requires 
>> this?

I'm not sure the stuff above actually addresses what you need,
but it might give some ideas? Like Danny I'd like to see an example
where the dictionary approach wouldn't work.

> Sure, I could also do this by reading a config file and parsing it , 
> but ..
>
> Say you split at the = , and the config file is like
>
> http = 80 #standard http port
>  https=443#https port
>
> Are you going to be 100% certain that when you call 
> watch_hosts[http], that you are gonna GET string "80"?
>  what about the space between http and =  ?

Yes, user errors like added spaces, mixed case, dropped or wrong
syntax(semi-colons/colons etc) are perennial problems and why a
pre-written parser is the best approach if you can finfd one that fits
your need. But it looks like maybe config parser is just a bit too
simplistic for the data you are trying to manage?

> I just didnt see any more effective way to get this than to use 
> ConfigParser as opposed to attempting to parse a file using regular 
> expressions , trim, split, etc

Python does support other data types including CSV and XML.
Maybe one of those can give you what you want more easily?

>>> It's difficult to grasp or even effectively explain the concept or 
>>> idea,
>>
>> Try to do so.  I think this is a real point that needs to be 
>> cleared up.
>
> I understand the concept/idea behind it, I think above is about as 
> good an explanation as it gets

I'm not sure I understand where exactly you are having the problems
(other than the admnittedly poor configparser documentation! - the
quality of python docs tends to be directly proportional to its 
frequency
of use and inversely proportional to age - more recent modules tend to
be better documented than ancient ones. Unfortunately for you config
parser doesn't seem to be used that much and has been there for ever!)

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From janos.juhasz at VELUX.com  Wed Jul  5 14:07:00 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Wed, 5 Jul 2006 14:07:00 +0200
Subject: [Tutor]  I Give Up. - Follow up post
Message-ID: <OF93AB280D.730A8672-ONC12571A2.0040B776-C12571A2.00428F44@velux.com>

Dear Brian,

The best parser is python itself :)

let's make ports.py with your original content:
http = 80
https = 443
http1 = 81
smtp = 25
smtp2 = 587

In this case, you can import ports.py with simple 
>>> import ports
>>> ports.http
80
>>> 

You don't need to define a new file format, just use the python syntax and 
it will work.
The only problem is that the format has to follow the python systax.
So the next wont work
## Ports.py
http = 80
https = 443
http1 = 81
  smtp = 25
smtp2 = 587

>>> import ports
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "ports.py", line 5
    smtp = 25
    ^
SyntaxError: invalid syntax
>>> 

The same method can be used for making more complex ini files.
I like it very much.
It is because Python is a dynamic language.


Yours sincerely, 
______________________________
Janos Juhasz 


From alan.gauld at freenet.co.uk  Wed Jul  5 15:41:53 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 5 Jul 2006 14:41:53 +0100
Subject: [Tutor] program-code dilemma
References: <1eac597d0607050005t584235f6lbe1cd8004f6dee79@mail.gmail.com>
Message-ID: <001301c6a038$d3606340$0301a8c0@XPpro>

> Lately I've been researching about the general definitions of 
> program
> and code, and I've realized that the difference is not so convincent
> (without mentioning simple and precise); that's why I'm sending 
> this.

It is very confusing especially for beginners, partly because both
words have multiple meanings dependant on context.

Thus:

>   Program.-  A sequence of instructions that can be executed by the 
> computer.

Is one definition. But program can have a wider application too,
as used by computer users. For example my "Word Processing
program" is actually a whole group of executable files and libraries.
All of which can be viewed as a program.

program is sometimes used to mean the end product of a programming
task, thus a DLL or other library once compiled into fina;l form might 
be
called a program.

>   Code.- Just the instructions of the program.

Usually code refers to the "source code", ie the program text
produced by a programmer or tool.

Code can also refer to "Object code" which is the preliminary output
from a compiler. This will be a binary format but one which is not
yet executable  - a link stage is needed for that to add in some
stanbdard header information and pointers to the standard libraries
used by the code - all of this extra stuff is used by the operating
system to create a running process.

And we can also get "Byte code" which is a kind of hybrid between
true object code and interpreted script. Python and Java use this
technique. The byte code for python is the compiled form found
in .pyc files.

And in a pure interpreted environment the difference between a program
and code is very hard to define since the interpreter executes the
code directly.

> Nevertheless for the few experience that I have, I know that a
> program also have comments; wich at the same time could be what
> differences a program from a code:

The comments are generally included in the definition of source code.
The compiler will remove comments so that they do not appear in the
object code (there are some exceptions to this). Comments are 
intrinsic
to an interpreted program so they a[popear inboth the code and the
program (it actually taleds the interprteter a small amount of effort
to throw away a comment. This is why modern interpreters
(Ruby, Python, Perl etc) usually compile the code into byte
code before executing it.

> The problem is that it seems too complicated for a definition so
> important and essential to start learning to program

Unfortunately computing has grown out of many different sciences
and engineering disciplines. Different terms arec used for the same
concept and the same term used for multiple concepts. It is a great
irony that a science which requires such preciusion of expression
as programming has not got a precisely defined set of terms to
describe itself!

> Although, I have clear that a program is like a container, and the
> code is like the internal structure that conform it. I think that a
> good analogy would be: "a code is to a program, what a GUI design is
> to a graphic application."

That depends on the GUI and the application environment.
Most GUIs are a combination of source code and graphical images,
its just that they use tools to generate it.

A better analogy might be that the source code is like the
sheet music that a musician processes to produce a tune.

This confusion of terminology is one of the reasons I spend a lot of
time in my tutorial attempting to clarify exactly what these different
terms mean in their various contexts.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at freenet.co.uk  Wed Jul  5 16:03:23 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 5 Jul 2006 15:03:23 +0100
Subject: [Tutor] Two Newbile Questions: porting drawmap.c,
	& Python as a lifetime	language
References: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>
	<44AB22D7.30602@tds.net>
Message-ID: <001501c6a03b$c7c726b0$0301a8c0@XPpro>

I missed the original post but I'll chip in anyway...

> dnelson at cae.wisc.edu wrote:
>> 2. Seeing Python hailed as a good language for learning 
>> programming,  how do you rate it as a lifetime language? (I can 
>> imagine that many people have settled into one language for doing 
>> the remainder of their life's work.

There is no such thing as a lifetime language (unless maybe its COBOL
or Fortran) because lanmguages are conmstantly changing.

When I started programming in the mid 70's I was using BASIC and
Assembler. Then when I went to University (as an adult student) I was
tought Pascal and C. (While there I also came across Smalltalk and
OOP but they weren't part of the core curriculum) After some years
using C (and some Lisp) at work I needed to learn Objective C and
then C++ which became my prime language for about 5 years.
(During all this time my personal projects were being done in
Pascal or Lisp  -- or Tcl which I'd found by accident...).

Nowadays almost all my work is done in either Python,
Pascal (Windows GUIs), Objective C (for my Apple) or Java.
I only use Java while at work - I detest it as a language.
But I've used over 30 languages in total over the years,
some I've forgotten, others I still dabble with (such as Smalltalk
and Lisp).

The language is pretty well irrelevant, you can do almost
anything in almost any language. The important thing is to
understand how to structure code and to lay it out clearly
for ease of maintenance. You can learn almost any new
language in less than a week. Learning all the common idioms
may take a few months.

>>     I am pressed, I will choose Perl at this point.)

Perl is just too lmited in scale for my purposes, it's great for
small scripts and up to a thousand lines or so of code.
But I had to maintain a 5000 line Perl program (ie quite small)
and it was not much fun - too many different styles used
and inconsistent design patterns, something Perl actively
encourages.

Once you get to large programs, say over 100,000 lines,
and certainly over a million you need a language with good
support for that kind of work. ADA, Eiffel, COBOL,
(and just maybe C++)  etc

The main reason COBOL has remained the most commonly
used language for large projects is its superlative support for
that kind of environment. Small COBOL programs are a pain
because you have to do so much to set it up, but on big projects
those very same constraints become a godsend. It's interesting
to note that most of the very big projects that fail have tried to use
other languages than COBOL and run into problems. COBOL isn't
necessary but it has a huge culture behind it for these kinds of
jobs - we have learned how to do it in COBOL, we are still
learing in Java, C++ etc.

Alan G. 



From python at venix.com  Wed Jul  5 16:53:30 2006
From: python at venix.com (Python)
Date: Wed, 05 Jul 2006 10:53:30 -0400
Subject: [Tutor] Two Newbile Questions: porting drawmap.c,
	& Python as	a lifetime	language
In-Reply-To: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>
References: <20060704163737.pnwcccew1woocs0g@www.cae.wisc.edu>
Message-ID: <1152111210.10267.940.camel@www.venix.com>

On Tue, 2006-07-04 at 16:37 -0500, dnelson at cae.wisc.edu wrote:
> I am seeking opinions from seasoned veterans on the following two
> questions:
> 
You're getting plenty of replies.  Here's a bit more.

You're probably aware that ESRI has adopted Python for scripting with
their applications.

> 1. What's involved in a port of a C program into Python?  (drawmap is 
> offered in a number of linux distributions btw.)

http://ldots.org/pyrex-guide/
pyrex integrates Python and C into a hybrid language that might be
useful for porting existing C code.

> 
> 2. Seeing Python hailed as a good language for learning programming,  
> how do you rate it as a lifetime language? (I can imagine that many
> people have settled into one language for doing the remainder of their
> life's work. If I am pressed, I will choose Perl at this point.)

I think it is easier to learn to write complex applications in Python
than Perl.  Certainly Perl is rich in features and capabilities, but I
find the rules for keeping everything straight are more complex than
Python's and the possibility of uncaught errors in Perl seems much
higher than in Python.  My favorite example of this is:

cat test.pl
if ("abc" == "def") {print "all letters are =\n"};

perl test.pl
all letters are =

)

 
== is the numeric comparison.  The strings are evaluated to numbers and
both are treated as zero. 0 = 0 is true.
"abc" eq "def" will behave as expected.  Python has its own pitfalls,
but I find the Python pitfalls much easier to live with.

Python continues to evolve while preserving backwards compatibility.
Recent additions such as list comprehension, generators, generator
expressions, display a growth and dynamism that I think will continue to
make Python a great choice among programming languages into the future.

(You didn't really think you'd find people on this list urging you to
use Perl.)

-- 
Lloyd Kvam
Venix Corp


From tinoloc at gmail.com  Wed Jul  5 16:49:27 2006
From: tinoloc at gmail.com (Tino Dai)
Date: Wed, 5 Jul 2006 10:49:27 -0400
Subject: [Tutor] More assistance with queues and global variables
Message-ID: <e033edfb0607050749m4598559ub5971df2e3d6c18c@mail.gmail.com>

Hi All,

     My project is almost working (and without global variables!), and there
is one more hurdle that I want to jump. That is using the SocketServer
module and passing a queue (or for that matter any kind of variable) to the
handle method. I took a look at SocketServer to see what classes I need to
override/extend, and see that I will be need to extending a couple of inits
and methods out of the TCPServer and the BaseServer class. I don't see an
easy way to do this [passing in a variable] , so I figured that I would
extend the classes. I can to realize that I would be extending not only the
base TCPServer class but also the BaseServer class. My question is: When I
extend those classes, can I put all the methods from both of the classes
into my own extended class or would I need to do something funky?

-Tino

Example:

class BaseServer:
       def __init__(self, server_address, RequestHandlerClass):
        """Constructor.  May be extended, do not override."""
        self.server_address = server_address
        self.RequestHandlerClass = RequestHandlerClass

       def handle_request(self):
        """Handle one request, possibly blocking."""
        try:
            request, client_address = self.get_request()
        except socket.error:
            return
        if self.verify_request(request, client_address):
            try:
                self.process_request(request, client_address)
            except:
                self.handle_error(request, client_address)
                self.close_request(request)


class TCPServer(BaseServer):
   address_family = socket.AF_INET

    socket_type = socket.SOCK_STREAM

    request_queue_size = 5

    allow_reuse_address = False

    def __init__(self, server_address, RequestHandlerClass):
        """Constructor.  May be extended, do not override."""
        BaseServer.__init__(self, server_address, RequestHandlerClass)
        self.socket = socket.socket(self.address_family,
                                    self.socket_type)
        self.server_bind()
        self.server_activate()

""" Above are the classes that I will need to extend/override

class MyTCPServer (SockertServer.TCPServer):
     """Would all the extended methods go in this class or would look
different? And how would I get the queue up to BaseServer without overriding
TCPServer's init?

-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060705/7b08acb0/attachment.htm 

From kent37 at tds.net  Wed Jul  5 18:25:22 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 05 Jul 2006 12:25:22 -0400
Subject: [Tutor] More assistance with queues and global variables
In-Reply-To: <e033edfb0607050749m4598559ub5971df2e3d6c18c@mail.gmail.com>
References: <e033edfb0607050749m4598559ub5971df2e3d6c18c@mail.gmail.com>
Message-ID: <44ABE7F2.8010405@tds.net>

Tino Dai wrote:
> Hi All,
>
>      My project is almost working (and without global variables!), and 
> there is one more hurdle that I want to jump. That is using the 
> SocketServer module and passing a queue (or for that matter any kind 
> of variable) to the handle method. I took a look at SocketServer to 
> see what classes I need to override/extend, and see that I will be 
> need to extending a couple of inits and methods out of the TCPServer 
> and the BaseServer class. I don't see an easy way to do this [passing 
> in a variable] , so I figured that I would extend the classes. I can 
> to realize that I would be extending not only the base TCPServer class 
> but also the BaseServer class. My question is: When I extend those 
> classes, can I put all the methods from both of the classes into my 
> own extended class or would I need to do something funky?
If I understand correctly, you want the server to have a queue that is 
shared among requests. You can do this without replacing any of the 
functions below. I would pass the queue to the __init__() method of your 
server class, override finish_request() to pass the queue to the request 
handler, the request handler __init__() just saves the queue for access 
by the handle() method. Something like this:

class MyServer(TCPServer):
  def __init__(self, server_address, RequestHandlerClass, queue):
    TCPServer.__init__(self, server_address, RequestHandlerClass)
    self.queue = queue

  def finish_request(self, request, client_address):
        """Finish one request by instantiating RequestHandlerClass."""
        self.RequestHandlerClass(request, client_address, self, self.queue)


class MyRequest(BaseRequestHandler):
  def __init__(self, request, client_address, server, queue):
    BaseRequestHandler.__init__(self, request, client_address, server)
    self.queue = queue

  def handle(self):
    # do something with self.queue

Kent
>
> -Tino
>
> Example:
>
> class BaseServer:
>        def __init__(self, server_address, RequestHandlerClass):
>         """Constructor.  May be extended, do not override."""
>         self.server_address = server_address
>         self.RequestHandlerClass = RequestHandlerClass
>
>        def handle_request(self):
>         """Handle one request, possibly blocking."""
>         try:
>             request, client_address = self.get_request()
>         except socket.error:
>             return
>         if self.verify_request(request, client_address):
>             try:
>                 self.process_request(request, client_address)
>             except:
>                 self.handle_error(request, client_address)
>                 self.close_request(request)
>
>
> class TCPServer(BaseServer):
>    address_family = socket.AF_INET
>
>     socket_type = socket.SOCK_STREAM
>
>     request_queue_size = 5
>
>     allow_reuse_address = False
>
>     def __init__(self, server_address, RequestHandlerClass):
>         """Constructor.  May be extended, do not override."""
>         BaseServer.__init__(self, server_address, RequestHandlerClass)
>         self.socket = socket.socket(self.address_family ,
>                                     self.socket_type)
>         self.server_bind()
>         self.server_activate()
>
> """ Above are the classes that I will need to extend/override
>
> class MyTCPServer ( SockertServer.TCPServer):
>      """Would all the extended methods go in this class or would look 
> different? And how would I get the queue up to BaseServer without 
> overriding TCPServer's init?
>
> -Tino
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From tinoloc at gmail.com  Wed Jul  5 19:24:01 2006
From: tinoloc at gmail.com (Tino Dai)
Date: Wed, 5 Jul 2006 13:24:01 -0400
Subject: [Tutor] More assistance with queues and global variables
In-Reply-To: <44ABE7F2.8010405@tds.net>
References: <e033edfb0607050749m4598559ub5971df2e3d6c18c@mail.gmail.com>
	<44ABE7F2.8010405@tds.net>
Message-ID: <e033edfb0607051024v37e8a401la1810beb34e544ca@mail.gmail.com>

On 7/5/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Tino Dai wrote:
> > Hi All,
> >
> >      My project is almost working (and without global variables!), and
> > there is one more hurdle that I want to jump. That is using the
> > SocketServer module and passing a queue (or for that matter any kind
> > of variable) to the handle method. I took a look at SocketServer to
> > see what classes I need to override/extend, and see that I will be
> > need to extending a couple of inits and methods out of the TCPServer
> > and the BaseServer class. I don't see an easy way to do this [passing
> > in a variable] , so I figured that I would extend the classes. I can
> > to realize that I would be extending not only the base TCPServer class
> > but also the BaseServer class. My question is: When I extend those
> > classes, can I put all the methods from both of the classes into my
> > own extended class or would I need to do something funky?
> If I understand correctly, you want the server to have a queue that is
> shared among requests. You can do this without replacing any of the
> functions below. I would pass the queue to the __init__() method of your
> server class, override finish_request() to pass the queue to the request
> handler, the request handler __init__() just saves the queue for access
> by the handle() method. Something like this:
>
> class MyServer(TCPServer):
>   def __init__(self, server_address, RequestHandlerClass, queue):
>     TCPServer.__init__(self, server_address, RequestHandlerClass)
>     self.queue = queue
>
>   def finish_request(self, request, client_address):
>         """Finish one request by instantiating RequestHandlerClass."""
>         self.RequestHandlerClass(request, client_address, self, self.queue
> )
>
>
> class MyRequest(BaseRequestHandler):
>   def __init__(self, request, client_address, server, queue):
>     BaseRequestHandler.__init__(self, request, client_address, server)
>     self.queue = queue
>
>   def handle(self):
>     # do something with self.queue
>
> Kent


Do you ever wish that you could pull back an email? This is one of those
times. I got the same exact solution as you about 30 minutes ago. I did have
to switch the lines in BaseRequestHandler and self.queue for it to work.
Thanks!

-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060705/0cdfe34d/attachment.html 

From jeffpeery at yahoo.com  Wed Jul  5 20:53:05 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Wed, 5 Jul 2006 11:53:05 -0700 (PDT)
Subject: [Tutor] modbus communication with python?
Message-ID: <20060705185305.63887.qmail@web30501.mail.mud.yahoo.com>

Hello, I need to talk read write to a modbus so that I can work with a PLC. I have not a clue how this all works. does python have a modbus module or where might I look to find how to do this? thanks.

Jeff
 		
---------------------------------
Do you Yahoo!?
 Everyone is raving about the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060705/631f79d6/attachment.html 

From jeffpeery at yahoo.com  Wed Jul  5 20:49:28 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Wed, 5 Jul 2006 11:49:28 -0700 (PDT)
Subject: [Tutor] modbus communication with python?
Message-ID: <20060705184928.62228.qmail@web30501.mail.mud.yahoo.com>

Hello, I need to talk read write to a modbus so that I can work with a PLC. I have not a clue how this all works. does python have a modbus module or where might I look to find how to do this? thanks.

Jeff

 		
---------------------------------
How low will we go? Check out Yahoo! Messenger?s low  PC-to-Phone call rates.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060705/aa1ad9b6/attachment.html 

From jason.massey at gmail.com  Wed Jul  5 21:05:07 2006
From: jason.massey at gmail.com (Jason Massey)
Date: Wed, 5 Jul 2006 14:05:07 -0500
Subject: [Tutor] modbus communication with python?
In-Reply-To: <20060705184928.62228.qmail@web30501.mail.mud.yahoo.com>
References: <20060705184928.62228.qmail@web30501.mail.mud.yahoo.com>
Message-ID: <7e3eab2c0607051205l24fab97ak54aa857a567743bd@mail.gmail.com>

Googling for modbus python turned up:

https://lintouch.org/repos/lintouch/lsp-modbus/trunk/tests/



On 7/5/06, Jeff Peery <jeffpeery at yahoo.com> wrote:
>
> Hello, I need to talk read write to a modbus so that I can work with a
> PLC. I have not a clue how this all works. does python have a modbus module
> or where might I look to find how to do this? thanks.
>
> Jeff
>
> ------------------------------
> How low will we go? Check out Yahoo! Messenger's low PC-to-Phone call
> rates.
> <http://us.rd.yahoo.com/mail_us/taglines/postman8/*http://us.rd.yahoo.com/evt=39663/*http://voice.yahoo.com>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060705/ad696b5d/attachment.htm 

From brian at daviesinc.com  Wed Jul  5 22:09:33 2006
From: brian at daviesinc.com (Brian Gustin)
Date: Wed, 05 Jul 2006 16:09:33 -0400
Subject: [Tutor] I Give Up. - Follow up post
In-Reply-To: <001f01c6a010$04466140$0301a8c0@XPpro>
References: <loom.20060612T211646-24@post.gmane.org><7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com><20060618194636.GA22079@cutter.rexx.com><001c01c69324$b90a6610$0301a8c0@XPpro><44AAABDB.4010400@daviesinc.com><Pine.LNX.4.64.0607041126270.19371@hkn.eecs.berkeley.edu><44AAD447.6060601@daviesinc.com><Pine.LNX.4.64.0607041445210.19371@hkn.eecs.berkeley.edu>
	<44AAF68A.2010605@daviesinc.com>
	<001f01c6a010$04466140$0301a8c0@XPpro>
Message-ID: <44AC1C7D.6080101@daviesinc.com>


> 
> The other alternative is to provide a tool for editing the file in which
> case the format is less important sionce hiumans "never" need to
> touch it.
> 
Heh. good analysis.. now I feel a little dumb- I should have thought of 
this *LONG* ago. yeah I knew about the xml parser , and how to do xml 
markup (it's one of the methods we use on intranet communications 
channels for certain scriptable tasks) ...

My sticking point was, I wanted it to be super easy for a newbie or 
beginner or "sysadmin trainee" to install and set up the monitoring 
without needing to know much more than maybe basic command line..

That's when it finally hit me (thanks to your commentary below) , why 
use a config file at all? all I have to do is create a simple "setup" 
utility that will write the "configuration" data I need in *correct and 
perfect* python syntax, which I can simply reload, or re-import into the 
daemon ... no need to even have a text editor, all I need is a little 
shell script or python utility to ask for and wait for the user's input 
at each prompt, and check data at each step to get it right..

Yep, I think I was *absolutely* over-thinking the issue here. :)

> How about command line tools?
> Somewhat like the commonly found adduser command in Unix?
> 
>>>> Yeah, basically you carry values in a dictionary named by keyname , 
>>>> but..  there have been situations where I need the key name as the 
>>>> variable name , I.E. config_options[name] = value could become
>>>>
>>>> name = value as if it was explicitly defined that way
> 
> 
> While I understand the usefulness of this in an interactive environment
> I'm puzzled about how this would work in a pre-written script. If you are
> creating variables from a config file how do you know what those variables
> are called? If you don;lt know how can you reference them later in the
> code? And if you don;t reference them of what value is the variable
> name? Therefore the logical conclusion(to me!) is that you must
> know what names you expect to read and therefore can use a dictionary?
> 
> I'm not sure I understand where exactly you are having the problems
> (other than the admnittedly poor configparser documentation! - the
> quality of python docs tends to be directly proportional to its frequency
> of use and inversely proportional to age - more recent modules tend to
> be better documented than ancient ones. Unfortunately for you config
> parser doesn't seem to be used that much and has been there for ever!)

Yeah this kind of confused the whole issue- and snowballed a little 
bit.. got off track ..

Point originally was, I wanted to be able to read in a config file as a 
name => value pair , and then actually have a variable named by name in 
the script, which you cannot do using a dictionary, you could use the 
key, yes, but at the time it didnt make sense to me to have 4 or 5 
dictionaries laying around in memory when they only have one or two keys 
, and I wanted to use single variables..

Comes from wanting to minimize how much stuff I have loaded into memory, 
and my impression is, a dictionary of 2 elements (name:value pairs)
takes up more space in memory than two single variables (name points to 
value in memory), and the conversation just ultimately got mixed up, and 
I couldnt even remember, in the end why I needed the variable names Vs. 
a dict, until I went back to SubVersion and dug out the first 2 versions 
of my code :)

(Got to love Revision control systems! )

Anyhow, that's now a moot point. :) I have no valid reason at this point 
to insist on knowing variable names.

However to make a point, my original thinking was along the lines of a 
way to do variable variables, (there are certain instances where they 
can be handy) , however since python has no $ to start a variable, I saw 
no way it was possible... Oh well

I have yet to get back in this project, it's working as needed in Perl 
(with a somewhat kludgy configuration, and really, IMHO, more code than 
is really necesary for something so simple as this) but it does the job, 
and I have other things I must do :)

> 
> HTH,
> 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 
> !DSPAM:44ab7d4d293088057919449!
> 
> 

From wescpy at gmail.com  Wed Jul  5 23:41:47 2006
From: wescpy at gmail.com (w chun)
Date: Wed, 5 Jul 2006 14:41:47 -0700
Subject: [Tutor] ANN: (Intensive) Intro to Python course, Aug 16-18,
	San Francisco
In-Reply-To: <78b3a9580607051440j9779487u48331bf26018d83d@mail.gmail.com>
References: <78b3a9580607051440j9779487u48331bf26018d83d@mail.gmail.com>
Message-ID: <78b3a9580607051441v24cc9295vd2c5d86f98d3a5ab@mail.gmail.com>

Greetings!

Below is the announcement we've just made this morning to CLP about
our upcoming Python course.  Please forward this msg to anyone whom
you think would be interested or would benefit from Python training
courses.  This includes Plone, Zope, Django, TurboGears, and Mailman
groups as well.

http://mail.python.org/pipermail/python-list/2006-July/350187.html

Thanks for your time!
-Wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
   http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


-- 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From alan.gauld at freenet.co.uk  Thu Jul  6 00:25:29 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 5 Jul 2006 23:25:29 +0100
Subject: [Tutor] I Give Up. - Follow up post
References: <loom.20060612T211646-24@post.gmane.org><7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com><20060618194636.GA22079@cutter.rexx.com><001c01c69324$b90a6610$0301a8c0@XPpro><44AAABDB.4010400@daviesinc.com><Pine.LNX.4.64.0607041126270.19371@hkn.eecs.berkeley.edu><44AAD447.6060601@daviesinc.com><Pine.LNX.4.64.0607041445210.19371@hkn.eecs.berkeley.edu>
	<44AAF68A.2010605@daviesinc.com>
	<001f01c6a010$04466140$0301a8c0@XPpro>
	<44AC1C7D.6080101@daviesinc.com>
Message-ID: <000301c6a081$ec4d1da0$0301a8c0@XPpro>

> Comes from wanting to minimize how much stuff I have loaded into 
> memory, and my impression is, a dictionary of 2 elements (name:value 
> pairs)
> takes up more space in memory than two single variables (name points 
> to value in memory),

Dangerous assumption since Python ultimately uses dictionaries for 
*all*
its variables, its just that some of them are somewhat hidden from 
view...
So evern if you declare

foo = 42

it gets turned into

local_vars[foo'] = 42

or something similar....

So by declaring your own dictionary the only overhead is the extra
dictionary entry to point at your explicit doictionary.

Dictionaries in Python are pretty efficient since they are
the bedrock of the interpreter.

HTH,

Alan G. 



From hxianping at gmail.com  Thu Jul  6 03:35:53 2006
From: hxianping at gmail.com (=?GB2312?B?uqvP3Ma9?=)
Date: Thu, 6 Jul 2006 09:35:53 +0800
Subject: [Tutor] what %s=%s means?
Message-ID: <702805a90607051835y1d9f5811qd1ed269c82963e96@mail.gmail.com>

I realy new to python.I try on learning it by code examples.The
following one from "Dive into python":

def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim", \
                "database":"master", \
                "uid":"sa", \
                "pwd":"secret" \
                }
    print buildConnectionString(myParams)

Whant ";"means
%s=%s?
join?
>>>help(items) no matched.
Where can i find stuff helpful?

From ismaelgf at adinet.com.uy  Thu Jul  6 04:08:38 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Wed, 05 Jul 2006 23:08:38 -0300
Subject: [Tutor] what %s=%s means?
In-Reply-To: <702805a90607051835y1d9f5811qd1ed269c82963e96@mail.gmail.com>
References: <702805a90607051835y1d9f5811qd1ed269c82963e96@mail.gmail.com>
Message-ID: <44AC70A6.2080306@adinet.com.uy>

??? wrote:
> I realy new to python.I try on learning it by code examples.The
> following one from "Dive into python":
>
> def buildConnectionString(params):
>     """Build a connection string from a dictionary of parameters.
>
>     Returns string."""
>     return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
>
> if __name__ == "__main__":
>     myParams = {"server":"mpilgrim", \
>                 "database":"master", \
>                 "uid":"sa", \
>                 "pwd":"secret" \
>                 }
>     print buildConnectionString(myParams)
>
> Whant ";"means
> %s=%s?
> join?
>   
>>>> help(items) no matched.
>>>>         
> Where can i find stuff helpful?

"%s" % (param) is called string formatting. It builds a new string from 
a format (the first part, that looks like a regular string with %s) and 
the arguments. The idea is that the %s get replaced with the value of 
the params.

String formatting allows many complex uses (for example, format decimal 
numbers with 3 digits before the . and 2 after). If you want to learn 
more about this you should look for the python docs or some tutorial 
(Google is your Friend). Alan Gauld's tutorial is really good :) 
http://www.freenetpages.co.uk/hp/alan.gauld/ (though it seems it doesn't 
cover this particular topic).

";".method is a string method. Strings ("") are objects, and as such 
they can be called (look for Object Oriented Programming if you don't 
know what an object is). -Alan's tutorial does have this topic :) -. The 
idea is basically that you ask a string to do something (in this case, 
join the elements in the list with itself in the middle).


Ismael

From Senthil_OR at Dell.com  Thu Jul  6 06:11:49 2006
From: Senthil_OR at Dell.com (Senthil_OR at Dell.com)
Date: Thu, 6 Jul 2006 09:41:49 +0530
Subject: [Tutor] program-code dilemma
In-Reply-To: <1eac597d0607050005t584235f6lbe1cd8004f6dee79@mail.gmail.com>
Message-ID: <427B13C6627A0B41BACA6564CE668C3B0423E1@blrx3m03.blr.amer.dell.com>

-----Original Message-----
From:  Damian
Sent: Wednesday, July 05, 2006 12:36 PM
To: tutor at python.org
Subject: [Tutor] program-code dilemma

 Although, from what I've found I been able to get this conclusions.

   Program.-  A sequence of instructions that can be executed by the
computer.

   Code.- Just the instructions of the program.

 The problem is that it seems too complicated for a definition so
important and essential to start learning to program (that without
getting account of what is missing for the completeness of the
definition).
_______________________________________________

Damian:
	I don't understand how much 'programming' will you learn by
understanding the difference between the terminologies of 'code' and
'program'.
My suggestion will be ignore that, see them as one and the same and
carry forward with learning other things and concepts. I doubt, you will
be confused with any concept which is exaplained using either of the
terminologies.

Frankly speaking, I don't know the difference between 'code' and the
'program'. For me,  its synonymous. I write Code. I do programming.I
program.

Do you get it?

-- 
Senthil


From andreengels at gmail.com  Thu Jul  6 06:19:33 2006
From: andreengels at gmail.com (Andre Engels)
Date: Thu, 6 Jul 2006 06:19:33 +0200
Subject: [Tutor] what %s=%s means?
In-Reply-To: <702805a90607051835y1d9f5811qd1ed269c82963e96@mail.gmail.com>
References: <702805a90607051835y1d9f5811qd1ed269c82963e96@mail.gmail.com>
Message-ID: <6faf39c90607052119n4b5edacbw548c342d68a43379@mail.gmail.com>

2006/7/6, ??? <hxianping at gmail.com>:
> I realy new to python.I try on learning it by code examples.The
> following one from "Dive into python":
>
> def buildConnectionString(params):
>     """Build a connection string from a dictionary of parameters.
>
>     Returns string."""
>     return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

> Whant ";"means

";" simply means the string consisting of the one character ;

> %s=%s?

You'll have to look at the more complete expression here:
"%s=%s" % (k, v)

%s then means, in this string replace me by the next element in the
tuple following the %. Thus, the above will evaluate to the string
consisting of the string representation of k followed by the character
= followed by the string representation of v.

Some examples to make it clearer:
"I am %s"%("John")
will evaluate to:
"I am John"

"%s is a number"%(7)
will evaluate to:
"7 is a number", because the stuff in the tuple doesn't need to be a string

If x equals 1 and y equals 2, "%s+%s=%s"%(x,y,x+y)
will evaluate to:
"1+2=3"

> join?

Join is a method of a string. Its syntax is:
x.join(y)
where x must be a string and y a sequence of strings. It denotes a
string, consisting of the strings in y, with x between each pair.
Again, a few examples will make it more clear:

" ".join(["I","am","a","boat"])
evaluates to:
"I am a boat"

"-abc-".join(["I","am","a","boat"])
evaluates to:
"I-abc-am-abc-a-abc-boat"

and
"".join(["I","am","a","boat"])
evaluates to:
"Iamaboat"

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels

From kp8 at mac.com  Thu Jul  6 07:39:30 2006
From: kp8 at mac.com (kevin parks)
Date: Thu, 6 Jul 2006 14:39:30 +0900
Subject: [Tutor] time(duration) formats & basic time math query
In-Reply-To: <mailman.29381.1152138335.27774.tutor@python.org>
References: <mailman.29381.1152138335.27774.tutor@python.org>
Message-ID: <3BB63B5D-B7E9-478B-BF5B-C7C67453B380@mac.com>

I have been handed a huge number of documents which have hundreds of  
pages of times and durations, all calculated and notated by several  
different people over the course of many years. Sadly, no made any  
guidelines at all about how this work would proceed and all the  
documenters had their own ideas about how times/durations would be  
specified so the doc are a mess. Furthermore the person i work for  
changes her mind every 15 minutes so i have no idea what she will  
want at any given moment. This sounds to me like a job for Python  
<hee hee>

Essentially, I am trying to do 2 things:

move fluidly between different duration formats (take any, specify  
and display any). Such as:

pure miliseconds
seconds. msec
mm:ss.msec
hh:mm:ss.msec

So the input doc would be grepped for times and i could just  
uncomment the line i need and get he format my boss wants at this  
particular moment.
So a recording that is 71 minutes and 33 seconds could be printed as:
4293 seconds
71:33.0000
01:11.33.0000      or whatever....

also i need to be able to adjust start times, durations, and end  
times which means doing a little time math.
Like if a recording is 71 minute and 33 seconds.. but there are  
several sonic events in that recording and i
need to specify the duration, or start time etc of those individual  
events... then i need to subtract... Additionally i
know that i will need to subtract pure minutes from an hh:mm format....

I having a real hard time getting my head round the labyrinthian  
datetime module in the docs (i am guessing
that this is what i should use). I wonder if anyone could give me a  
hand and point me in the right direction.

cheers,

kevin



From python-tutor at v.igoro.us  Thu Jul  6 08:00:57 2006
From: python-tutor at v.igoro.us (Dustin J. Mitchell)
Date: Thu, 06 Jul 2006 01:00:57 -0500
Subject: [Tutor] time(duration) formats & basic time math query
In-Reply-To: <3BB63B5D-B7E9-478B-BF5B-C7C67453B380@mac.com>
References: <mailman.29381.1152138335.27774.tutor@python.org>
	<3BB63B5D-B7E9-478B-BF5B-C7C67453B380@mac.com>
Message-ID: <44ACA719.3010402@v.igoro.us>

kevin parks wrote:
> I have been handed a huge number of documents which have hundreds of  
> pages of times and durations, all calculated and notated by several  
> different people over the course of many years. Sadly, no made any  
> guidelines at all about how this work would proceed and all the  
> documenters had their own ideas about how times/durations would be  
> specified so the doc are a mess. Furthermore the person i work for  
> changes her mind every 15 minutes so i have no idea what she will  
> want at any given moment. This sounds to me like a job for Python  
> <hee hee>
> 
> Essentially, I am trying to do 2 things:
> 
> move fluidly between different duration formats (take any, specify  
> and display any). Such as:
> 
> pure miliseconds
> seconds. msec
> mm:ss.msec
> hh:mm:ss.msec
> 
> So the input doc would be grepped for times and i could just  
> uncomment the line i need and get he format my boss wants at this  
> particular moment.
> So a recording that is 71 minutes and 33 seconds could be printed as:
> 4293 seconds
> 71:33.0000
> 01:11.33.0000      or whatever....
> 
> also i need to be able to adjust start times, durations, and end  
> times which means doing a little time math.
> Like if a recording is 71 minute and 33 seconds.. but there are  
> several sonic events in that recording and i
> need to specify the duration, or start time etc of those individual  
> events... then i need to subtract... Additionally i
> know that i will need to subtract pure minutes from an hh:mm format....
> 
> I having a real hard time getting my head round the labyrinthian  
> datetime module in the docs (i am guessing
> that this is what i should use). I wonder if anyone could give me a  
> hand and point me in the right direction.

datetime may do the trick for you, but I would use it only for its
conversional abilities -- it sounds like this is a good time for you to
implement your own "Duration" class, with some kind of flexible system
for parsing (possibly even recognizing) different time formats, and
producing different time formats, e.g.,

class Duration:
  def __init__(self, duration_string, format='guess'):
    if format == 'guess': format = self.guess_format(duration_string)
    self.format = format

    parse, output = self.format_fns[self.format]
    self.seconds = parse(self, duration_string)

  def output(self, format='original'):
    if format == 'original': format = self.format
    parse, output = self.format_fns[format]
    return output(self)

  def parse_milliseconds(self, duration_string): ...
  def output_milliseconds(self): ...
  def parse_fracseconds(self, duration_string): ...
  def output_fracseconds(self): ...

  format_fns = {
    'milliseconds' : (parse_milliseconds, output_milliseconds),
    'fracseconds' : (parse_fracseconds, ouput_fracseconds),
  }

Then you can just parse the thing up like this:

  durations = [ Duration(line.strip()) for line in f.xreadlines() ]

and print it out like this:

  for dur in durations:
    print dur.output('milliseconds')

Dustin

From sanelson at gmail.com  Thu Jul  6 10:53:38 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Thu, 6 Jul 2006 09:53:38 +0100
Subject: [Tutor] Beer Bottles
Message-ID: <b6131fdc0607060153t220650d7meef32dd95019dca3@mail.gmail.com>

A bunch of my friends and I have been chatting about "99 bottles of
beer" - and how to make the shortest code to do it.  I have:

for i in range(100,0,-1):
   print "%s bottles of beer on the wall, %s bottles of beer\nTake on
down, pass it around.."%(i,i)
print "Go to the store, buy some more"

I'm curious to know other ways to handle this - could it be done
functionally?  How could we obfuscate this (not that we'd want to in
real life)?  Or make it a (close to) one liner?

Thanks.

S.

From sanelson at gmail.com  Thu Jul  6 10:59:17 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Thu, 6 Jul 2006 09:59:17 +0100
Subject: [Tutor] Test
Message-ID: <b6131fdc0607060159m4a2ba361k695230addb6431d4@mail.gmail.com>

I got a bounce... but have been on this list for months...

S.

From rabidpoobear at gmail.com  Thu Jul  6 11:13:03 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 06 Jul 2006 04:13:03 -0500
Subject: [Tutor] Beer Bottles
In-Reply-To: <b6131fdc0607060153t220650d7meef32dd95019dca3@mail.gmail.com>
References: <b6131fdc0607060153t220650d7meef32dd95019dca3@mail.gmail.com>
Message-ID: <44ACD41F.3000002@gmail.com>

Steve Nelson wrote:
> A bunch of my friends and I have been chatting about "99 bottles of
> beer" - and how to make the shortest code to do it.  I have:
>
> for i in range(100,0,-1):
>    print "%s bottles of beer on the wall, %s bottles of beer\nTake on
> down, pass it around.."%(i,i)
> print "Go to the store, buy some more"
>
> I'm curious to know other ways to handle this - could it be done
> functionally?  How could we obfuscate this (not that we'd want to in
> real life)?  Or make it a (close to) one liner?
>
> Thanks.
>
> S.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   
one way to do it functionally:

def beer(i):a='%s bottles of beer';print "%s on the wall, %s.\nTake one 
down, pass it around.."%(a%i,a%i)
map(beer,range(100,0,-1))
print "Go to the store, buy some more"

definitely check out http://www.99-bottles-of-beer.net

the smallest version there is

By Oliver Xymoron (133 Bytes)

a,t="\n%s bottles of beer on the wall","\nTake one down, pass it around"
for d in range(99,0,-1):print(a%d*2)[:-12]+t+a%(d-1 or'No')


Note both of our examples and Oliver's examples don't handle the 
singular form correctly.
"1 bottles of beer" is not correct. "0 bottles of beer" is pushing it, 
it should be "no bottles of beer."
If you're trying to obfuscate it there are examples of that too,
just check out the python section.
http://www.99-bottles-of-beer.net/language-python-748.html

Enjoy!

From kent37 at tds.net  Thu Jul  6 12:28:41 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 06 Jul 2006 06:28:41 -0400
Subject: [Tutor] time(duration) formats & basic time math query
In-Reply-To: <3BB63B5D-B7E9-478B-BF5B-C7C67453B380@mac.com>
References: <mailman.29381.1152138335.27774.tutor@python.org>
	<3BB63B5D-B7E9-478B-BF5B-C7C67453B380@mac.com>
Message-ID: <44ACE5D9.4010806@tds.net>

kevin parks wrote:
> I have been handed a huge number of documents which have hundreds of  
> pages of times and durations, all calculated and notated by several  
> different people over the course of many years. Sadly, no made any  
> guidelines at all about how this work would proceed and all the  
> documenters had their own ideas about how times/durations would be  
> specified so the doc are a mess. Furthermore the person i work for  
> changes her mind every 15 minutes so i have no idea what she will  
> want at any given moment. This sounds to me like a job for Python  
> <hee hee>
>   
Yep!
> Essentially, I am trying to do 2 things:
>
> move fluidly between different duration formats (take any, specify  
> and display any). Such as:
>
> pure miliseconds
> seconds. msec
> mm:ss.msec
> hh:mm:ss.msec
>
> So the input doc would be grepped for times and i could just  
> uncomment the line i need and get he format my boss wants at this  
> particular moment.
> So a recording that is 71 minutes and 33 seconds could be printed as:
> 4293 seconds
> 71:33.0000
> 01:11.33.0000      or whatever....
>
> also i need to be able to adjust start times, durations, and end  
> times which means doing a little time math.
> Like if a recording is 71 minute and 33 seconds.. but there are  
> several sonic events in that recording and i
> need to specify the duration, or start time etc of those individual  
> events... then i need to subtract... Additionally i
> know that i will need to subtract pure minutes from an hh:mm format....
>
> I having a real hard time getting my head round the labyrinthian  
> datetime module in the docs (i am guessing
> that this is what i should use). I wonder if anyone could give me a  
> hand and point me in the right direction.

time.strptime() can help with the parsing, though it doesn't handle 
milliseconds so you will have to do that part yourself. You can 
construct a datetime.datetime object from the output of strptime(). Use 
datetime.timedelta to do the offsets. Use datetime.strftime() to format 
the output. For example:

In [1]: from datetime import datetime, timedelta

In [2]: import time

In [6]: time.strptime('01:11.33', '%H:%M.%S')
Out[6]: (1900, 1, 1, 1, 11, 33, 0, 1, -1)

In [7]: time.strptime('01:11.33', '%H:%M.%S')[:6]
Out[7]: (1900, 1, 1, 1, 11, 33)

In [11]: td=timedelta(minutes=2, seconds=5)

In [15]: d=datetime(*time.strptime('01:11.33', '%H:%M.%S')[:6])

In [16]: d
Out[16]: datetime.datetime(1900, 1, 1, 1, 11, 33)

In [17]: d+td
Out[17]: datetime.datetime(1900, 1, 1, 1, 13, 38)

In [18]: (d+td).strftime('%H:%M.%S')
Out[18]: '01:13.38'

Kent


From samrobertsmith at gmail.com  Thu Jul  6 12:32:16 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Thu, 6 Jul 2006 03:32:16 -0700
Subject: [Tutor] trace the changes
Message-ID: <1d987df30607060332y529a991ayf20532da5b8ea8e2@mail.gmail.com>

I am reading a long python code with many if...then; I wonder whether
there is any way to trace the changes of the variables in the code. I
can not find debugger tutorial in detail in PythonWin. Thanks for any
suggestions.
Linda

From alan.gauld at freenet.co.uk  Thu Jul  6 12:59:51 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 6 Jul 2006 11:59:51 +0100
Subject: [Tutor] what %s=%s means?
References: <702805a90607051835y1d9f5811qd1ed269c82963e96@mail.gmail.com>
Message-ID: <00c101c6a0eb$58048dd0$0301a8c0@XPpro>

>I really new to python.I try on learning it by code examples.The
> following one from "Dive into python":

If you know another language then the official tutorial is the best
place to start, it explains all of the items on your question list.

Dive into Python is very good but it is really intended for 
intermediate
users who want to "dive into" the deeper areas, its not ideal as
a starter tutorial. Once you go through the official tutor then "Dive"
should make a lot more sense.

OTOH IF you are new to programming in general then the official
tutor might still be too deep. There is a non programmers page
on the python web site with a list of tutorials for absolute 
beginners.

Othrs seem to have answered most of your specific questions.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From devayani.barve at gmail.com  Thu Jul  6 13:06:34 2006
From: devayani.barve at gmail.com (devayani barve)
Date: Thu, 6 Jul 2006 16:36:34 +0530
Subject: [Tutor] the lambda func
Message-ID: <301929340607060406g2c110487me6c40c4f16f02074@mail.gmail.com>

Hi,
I have just started learning python...
Following is an example from dive into python:

def info(object,spacing=10,collapse=1):
    """Print methods and doc strings.
    Takes module,class,list,dictionary or string."""
    methodList=[method for method in dir(object) if
callable(getattr(object,method))]
    processFunc=collapse and (lambda s: " ".join(s.split())) or (lambda s:s)
    print "\n".join(["%s %s"
%(method.ljust(spacing),processFunc(str(getattr(object,method).__doc__)))
for method in methodList])
if __name__=="__main__":
    print info.__doc__



now if i do the following:

li=[]
info(li)

i get the expected output

what i dont understand is the use of variable *processFunc* and i dont see
the lambda function being called anywhere.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060706/d592ba57/attachment.html 

From alan.gauld at freenet.co.uk  Thu Jul  6 13:07:58 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 6 Jul 2006 12:07:58 +0100
Subject: [Tutor] time(duration) formats & basic time math query
References: <mailman.29381.1152138335.27774.tutor@python.org>
	<3BB63B5D-B7E9-478B-BF5B-C7C67453B380@mac.com>
Message-ID: <00c701c6a0ec$70a279a0$0301a8c0@XPpro>

> So the input doc would be grepped for times and i could just  
> uncomment the line i need and get he format my boss wants at this  
> particular moment.

You shouldn't need to uncomment it if you can specify an 
argument that describes which format you want. Then have 
a bunch of formatting functions that have the same protocol

func(string) -> string

you can then assign your formatting function as an argument 
to the "grep" function:

def f(s): ....
def g(s): ....
def h(s): ...

if arg == 'hms':
    filter = h
id arg == 's'
    filter = g
etc

print grep(theFile, filter)


Or use a dictionary instead of the if/elif chain

filter = {'hms': h,
            's': g,
            etc...}

print grep(thefile, filter[arg])

Now to write the filter functions you still need to grok datetime 
but this might save any commenting out shenannigans... :-)

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld at freenet.co.uk  Thu Jul  6 13:15:55 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 6 Jul 2006 12:15:55 +0100
Subject: [Tutor] Beer Bottles
References: <b6131fdc0607060153t220650d7meef32dd95019dca3@mail.gmail.com>
Message-ID: <00cd01c6a0ed$8d190bc0$0301a8c0@XPpro>

> for i in range(100,0,-1):
>   print > print "Go to the store, buy some more"
>
> I'm curious to know other ways to handle this - could it be done
> functionally?  How could we obfuscate this (not that we'd want to in
> real life)?  Or make it a (close to) one liner?

print "".join(['%s bottles of beer on the wall, %s bottles of 
beer\nTake on
 down, pass it around..'%(i,i) for i in range(100,0,-1)])+ "\nGo to 
the store, buy some more"

Is a one liner based on your code...

Not very obfuscated though...

Alan G.



From sanelson at gmail.com  Thu Jul  6 15:43:20 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Thu, 6 Jul 2006 14:43:20 +0100
Subject: [Tutor] Functional Programming
Message-ID: <b6131fdc0607060643i50f28a99k52094863d82ca15@mail.gmail.com>

Hi All,

I've just today starting thinking more about programming in a more
functional style, and came across the following article which I
thought was really good:

http://www.amk.ca/python/writing/functional

I know there's a section in Alan's tutorial on FP too, but can anyone
else recommend some good references?  It is all a very new approach
for me, but it is also fascinating, and rather fun!

S.

From dyoo at hkn.eecs.berkeley.edu  Thu Jul  6 16:02:15 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 6 Jul 2006 07:02:15 -0700 (PDT)
Subject: [Tutor] Functional Programming
In-Reply-To: <b6131fdc0607060643i50f28a99k52094863d82ca15@mail.gmail.com>
References: <b6131fdc0607060643i50f28a99k52094863d82ca15@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0607060656120.7071@hkn.eecs.berkeley.edu>



On Thu, 6 Jul 2006, Steve Nelson wrote:

> I've just today starting thinking more about programming in a more 
> functional style, and came across the following article which I thought 
> was really good:
>
> http://www.amk.ca/python/writing/functional

Hi Steve,

The references on the bottom are sparse, but solid; Structure and 
Interpretation of Computer Programs can't be recommended enough.

I would add to that list another textbook:

     How to Design Programs
     http://htdp.org

It goes slower than Structure and Interpretation of Computer Programs, but 
is also a very good text.  I have to admit I felt sorta sleepy on the 
first few sections, but starting around Section 9 things picked up quite a 
bit and I woke up.


Best of wishes!

From kent37 at tds.net  Thu Jul  6 16:36:42 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 06 Jul 2006 10:36:42 -0400
Subject: [Tutor] Functional Programming
In-Reply-To: <b6131fdc0607060643i50f28a99k52094863d82ca15@mail.gmail.com>
References: <b6131fdc0607060643i50f28a99k52094863d82ca15@mail.gmail.com>
Message-ID: <44AD1FFA.5030800@tds.net>

Steve Nelson wrote:
> Hi All,
>
> I've just today starting thinking more about programming in a more
> functional style, and came across the following article which I
> thought was really good:
>
> http://www.amk.ca/python/writing/functional
>   

> I know there's a section in Alan's tutorial on FP too, but can anyone
> else recommend some good references?  It is all a very new approach
> for me, but it is also fascinating, and rather fun!
For more examples of using the tools in AMK's article, the Python 
Cookbook is a good place to look.

David Mertz writes Python in an extreme functional style. Take a look at 
some of his Charming Python columns for examples - three columns from 
2001 are specifically about functional programming.
http://www-128.ibm.com/developerworks/views/linux/libraryview.jsp?search_by=charming+python:

Kent


From carroll at tjc.com  Fri Jul  7 00:58:34 2006
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 6 Jul 2006 15:58:34 -0700 (PDT)
Subject: [Tutor] Beer Bottles
In-Reply-To: <00cd01c6a0ed$8d190bc0$0301a8c0@XPpro>
Message-ID: <Pine.LNX.4.44.0607061555370.10120-100000@violet.rahul.net>

On Thu, 6 Jul 2006, Alan Gauld wrote:

> Not very obfuscated though...

For *true* obfuscation, nothing matches perl:


-------------------------------- cut here ------------------------------


    ''=~(        '(?{'        .('`'        |'%')        .('['        ^'-')
    .('`'        |'!')        .('`'        |',')        .'"'.        '\\$'
    .'=='        .('['        ^'+')        .('`'        |'/')        .('['
    ^'+')        .'||'        .(';'        &'=')        .(';'        &'=')
    .';-'        .'-'.        '\\$'        .'=;'        .('['        ^'(')
    .('['        ^'.')        .('`'        |'"')        .('!'        ^'+')
   .'_\\{'      .'(\\$'      .';=('.      '\\$=|'      ."\|".(      '`'^'.'
  ).(('`')|    '/').').'    .'\\"'.+(    '{'^'[').    ('`'|'"')    .('`'|'/'
 ).('['^'/')  .('['^'/').  ('`'|',').(  '`'|('%')).  '\\".\\"'.(  '['^('(')).
 '\\"'.('['^  '#').'!!--'  .'\\$=.\\"'  .('{'^'[').  ('`'|'/').(  '`'|"\&").(
 '{'^"\[").(  '`'|"\"").(  '`'|"\%").(  '`'|"\%").(  '['^(')')).  '\\").\\"'.
 ('{'^'[').(  '`'|"\/").(  '`'|"\.").(  '{'^"\[").(  '['^"\/").(  '`'|"\(").(
 '`'|"\%").(  '{'^"\[").(  '['^"\,").(  '`'|"\!").(  '`'|"\,").(  '`'|(',')).
 '\\"\\}'.+(  '['^"\+").(  '['^"\)").(  '`'|"\)").(  '`'|"\.").(  '['^('/')).
 '+_,\\",'.(  '{'^('[')).  ('\\$;!').(  '!'^"\+").(  '{'^"\/").(  '`'|"\!").(
 '`'|"\+").(  '`'|"\%").(  '{'^"\[").(  '`'|"\/").(  '`'|"\.").(  '`'|"\%").(
 '{'^"\[").(  '`'|"\$").(  '`'|"\/").(  '['^"\,").(  '`'|('.')).  ','.(('{')^
 '[').("\["^  '+').("\`"|  '!').("\["^  '(').("\["^  '(').("\{"^  '[').("\`"|
 ')').("\["^  '/').("\{"^  '[').("\`"|  '!').("\["^  ')').("\`"|  '/').("\["^
 '.').("\`"|  '.').("\`"|  '$')."\,".(  '!'^('+')).  '\\",_,\\"'  .'!'.("\!"^
 '+').("\!"^  '+').'\\"'.  ('['^',').(  '`'|"\(").(  '`'|"\)").(  '`'|"\,").(
 '`'|('%')).  '++\\$="})'  );$:=('.')^  '~';$~='@'|  '(';$^=')'^  '[';$/='`';

-------------------------------- cut here ------------------------------

(Not mine: stolen from 
http://www.99-bottles-of-beer.net/language-perl-737.html)



From carroll at tjc.com  Fri Jul  7 01:39:59 2006
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 6 Jul 2006 16:39:59 -0700 (PDT)
Subject: [Tutor] Functional Programming
In-Reply-To: <b6131fdc0607060643i50f28a99k52094863d82ca15@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0607061636420.10120-100000@violet.rahul.net>

On Thu, 6 Jul 2006, Steve Nelson wrote:

> I know there's a section in Alan's tutorial on FP too, but can anyone
> else recommend some good references?  

I happened upon this column a few days ago, whic I found a good read to 
explain the basic idea, for non-FPers like me:

http://www.defmacro.org/ramblings/fp.html

Also, while trying to re-find the above URL, I found Simon Thompson's
"Type Theory and Functional Programming," which looks like an interesting
378-page read and can be found online at
http://www.cs.kent.ac.uk/people/staff/sjt/TTFP/

Neither of these is particularly directed to Python, though.



From ms at cerenity.org  Fri Jul  7 03:09:12 2006
From: ms at cerenity.org (Michael)
Date: Fri, 7 Jul 2006 02:09:12 +0100
Subject: [Tutor] Functional Programming
In-Reply-To: <Pine.LNX.4.44.0607061636420.10120-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0607061636420.10120-100000@violet.rahul.net>
Message-ID: <200607070209.12977.ms@cerenity.org>

On Friday 07 July 2006 00:39, Terry Carroll wrote:
> Neither of these is particularly directed to Python, though.

Also, much as I like python, it's not really suited to functional programming
approaches, given recursion isn't tail optimised, lambda is by comparison
crippled, some aspects of pythons approach to closures aren't as robust as
I'd like, mutablity of values, and things like currying aren't as simple as
they could be.

That said, functional programming is fun, and these days probably the best
introductions are either SML books or Haskell.

I also think that having an understanding of functional programming will 
generally improve someone's code, but I would suggest that learning the ideas 
in a language where functional programming is the norm rather the exception 
is a good idea. The come back to python, and learn to undo your recursive 
instincts!


Michael

From jakieabraham at yahoo.com  Fri Jul  7 10:23:02 2006
From: jakieabraham at yahoo.com (Jacob Abraham)
Date: Fri, 7 Jul 2006 01:23:02 -0700 (PDT)
Subject: [Tutor] Windows Domain Authentication
In-Reply-To: <mailman.29526.1152226718.27774.tutor@python.org>
Message-ID: <20060707082302.38779.qmail@web54114.mail.yahoo.com>

Dear Tutors,

   I am about to start on a project that would reuse
Windows Domain Authentication over XML-RPC in python.
This may involve the rewrite of the XML-RPC client and
server. Could someone point me in the right direction
so that I can run from there.

Cheers,
Jacob Abraham

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From alan.gauld at freenet.co.uk  Fri Jul  7 12:15:27 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 7 Jul 2006 11:15:27 +0100
Subject: [Tutor] Functional Programming
References: <Pine.LNX.4.44.0607061636420.10120-100000@violet.rahul.net>
	<200607070209.12977.ms@cerenity.org>
Message-ID: <000c01c6a1ae$44bce790$0301a8c0@XPpro>

> Also, much as I like python, it's not really suited to functional 
> programming

I'd modify that to say its not ideally suited to FP, but an FP style 
is
certainly possible. Pyhon is adequate to learn the principles but it 
would
be nearly impossible to write a real world solution using pure FP
in Python.

> That said, functional programming is fun, and these days probably 
> the best
> introductions are either SML books or Haskell.

Or good old Lisp. And there are lots of good introductory tutorials 
for
Lisp whereas the FP material tends to be very math oriented, if you
don't have a strong math background it simply won't make much sense.

> I also think that having an understanding of functional programming 
> will
> generally improve someone's code, but I would suggest that learning 
> the ideas
> in a language where functional programming is the norm rather the 
> exception
> is a good idea. The come back to python, and learn to undo your 
> recursive
> instincts!

This is good advice if you want more than just an appreciation of the
concepts. If you want to try writing a real world application using FP
then definitely try Lisp, ML or Haskell. But be prepared for a 
completely
different division of your time over the project, much more time up 
front
thinking about the specification of the problem, much less time 
debugging
the functionality (the same amount of time debugging the detailed
code though!)

Alan G. 



From kent37 at tds.net  Fri Jul  7 12:56:43 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 07 Jul 2006 06:56:43 -0400
Subject: [Tutor] Windows Domain Authentication
In-Reply-To: <20060707082302.38779.qmail@web54114.mail.yahoo.com>
References: <20060707082302.38779.qmail@web54114.mail.yahoo.com>
Message-ID: <44AE3DEB.4080701@tds.net>

Jacob Abraham wrote:
>    I am about to start on a project that would reuse
> Windows Domain Authentication over XML-RPC in python.
> This may involve the rewrite of the XML-RPC client and
> server. Could someone point me in the right direction
> so that I can run from there.
I'm not at all sure what you are asking for. Are you writing an XML-RPC 
system that authenticates clients via Windows Domain Auth, or an 
authorization server that exposes an XML-RPC API? Do you want to rewrite 
the XML-RPC client and server from the standard lib? If so the source 
for them is in C:\Python24\Lib or the equivalent (see xmlrpclib.py and 
SimpleXMLRPCServer.py).

Kent


From jakieabraham at yahoo.com  Fri Jul  7 14:08:59 2006
From: jakieabraham at yahoo.com (Jacob Abraham)
Date: Fri, 7 Jul 2006 05:08:59 -0700 (PDT)
Subject: [Tutor] Windows Domain Authentication
Message-ID: <20060707120859.58226.qmail@web54113.mail.yahoo.com>

Hi Kent

I am trying to write a XML-RPC system that
authenticates clients via Windows Domain Auth. I just
wanted to know how best to go about doing this, since
I come from a Linux background and am not familiar
with the win32 API.

I've just started looking at "named pipes" as a
possible solution.

Thanks.
Jacob Abraham

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From eklitzke at gmail.com  Fri Jul  7 19:09:20 2006
From: eklitzke at gmail.com (Evan Klitzke)
Date: Fri, 7 Jul 2006 10:09:20 -0700
Subject: [Tutor] Logical Sorting
Message-ID: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>

Hi,

I am trying to sort a list of directories that correspond to kernel
sources under /usr/src/linux.  I wrote some code that gets a list like
this:
['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r11/', 'linux-2.6.16-gentoo-r7/']

When I sort the list, I want it to go from oldest (lowest version) to
newest, so the sorted list should look like this:
['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r7/', 'linux-2.6.16-gentoo-r11/']

The problem is that since the built in string comparisons compare
character by character, so the sort puts 2.6.16 before 2.6.9, and -r11
before -r7.  This is obviously not what I want.  My question is: are
there any modules or built in methods that will do a logical sort on a
list like this, and sort it the way I want, or will I have to write my
own sorting function?

-- Evan Klitzke

P.S. I know that the simplest way is just to use ls to sort by time,
but it is not necessarily true that older kernel versions have an
older time stamp :-)

From eklitzke at gmail.com  Fri Jul  7 19:12:32 2006
From: eklitzke at gmail.com (Evan Klitzke)
Date: Fri, 7 Jul 2006 10:12:32 -0700
Subject: [Tutor] Logical Sorting
In-Reply-To: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
Message-ID: <fab7f7b40607071012l4e6f53bcmd0fc4a8217ed6133@mail.gmail.com>

On 7/7/06, Evan Klitzke <eklitzke at gmail.com> wrote:
> Hi,
>
> I am trying to sort a list of directories that correspond to kernel
> sources under /usr/src/linux.

Err, this is under /usr/src... not that it is really pertinent to my question.

-- Evan Klitzke

From carroll at tjc.com  Fri Jul  7 19:40:58 2006
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 7 Jul 2006 10:40:58 -0700 (PDT)
Subject: [Tutor] Is implicit underscore assignment documented?
Message-ID: <Pine.LNX.4.44.0607071034330.26249-100000@violet.rahul.net>

Is implicit underscore assignment documented anywhere?  I've seen 
reference to this, and it seems to be simply that, when Python 
interactively prints a value in response to a user entering an expression, 
that value is assigned to the variable _.  

As far as I can tell, the following transcript shows its workings:

ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on 
Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> _
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name '_' is not defined
>>> a = 0
>>> _
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name '_' is not defined
>>> a
0
>>> _
0
>>>
>>> a = 5
>>> _
0
>>> a
5
>>> _
5
>>> a = 5
>>> _
0
>>> a
5
>>> _
5
>>> #value unchanged, because a's value was not printed (the interpreter 
does not print None).
...
>>> a = 10
>>> print a
10
>>> _
5
>>> # value unchanged, because print is a statement, not an expression.
...
>>>

Is this documented anywhere?


From kent37 at tds.net  Fri Jul  7 19:41:47 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 07 Jul 2006 13:41:47 -0400
Subject: [Tutor] Logical Sorting
In-Reply-To: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
Message-ID: <44AE9CDB.6030605@tds.net>

Evan Klitzke wrote:
> Hi,
>
> I am trying to sort a list of directories that correspond to kernel
> sources under /usr/src/linux.  I wrote some code that gets a list like
> this:
> ['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r11/', 'linux-2.6.16-gentoo-r7/']
>
> When I sort the list, I want it to go from oldest (lowest version) to
> newest, so the sorted list should look like this:
> ['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r7/', 'linux-2.6.16-gentoo-r11/']
>
> The problem is that since the built in string comparisons compare
> character by character, so the sort puts 2.6.16 before 2.6.9, and -r11
> before -r7.  This is obviously not what I want.  My question is: are
> there any modules or built in methods that will do a logical sort on a
> list like this, and sort it the way I want, or will I have to write my
> own sorting function?

You don't have to write your own sorting function. You do have to write 
a function that extracts a key from a data item that will sort in the 
order you want. Here is a version that uses a regular expression to 
extract the four fields from the data, converts the numbers to integers, 
and returns a tuple of values that sorts correctly. It works with the 
data you show but it probably needs tweaks to be more robust, for 
example it will fail if the version is not three numbers or if the -rxx 
is missing.

In [1]: data = ['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r11/', 
'linux-2.6.16-gentoo-r7/']

In [2]: import re

In [3]: def makeKey(entry):
   ...:     m=re.search(r'-(\d+)\.(\d+)\.(\d+)-[^-]+-r(\d+)', entry)
   ...:     if not m: return entry
   ...:     return map(int, m.group(1, 2, 3, 4))
   ...:

In [4]: data.sort(key=makeKey)

In [5]: data
Out[5]:
['linux-2.6.9-gentoo-r4',
 'linux-2.6.16-gentoo-r7/',
 'linux-2.6.16-gentoo-r11/']

Kent


From jeffpeery at yahoo.com  Fri Jul  7 20:36:05 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Fri, 7 Jul 2006 11:36:05 -0700 (PDT)
Subject: [Tutor] how to post an event?
Message-ID: <20060707183605.43657.qmail@web30512.mail.mud.yahoo.com>

Hello, I am having a bit of trouble figuring out how to post an event. I attached my sample program. I assigned a button event to each button in the program. I want to post an event when the second button is pressed that executes the first button. thanks.

Jeff

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060707/02ecd8f8/attachment.html 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: App1.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060707/02ecd8f8/attachment.pot 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Frame1.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060707/02ecd8f8/attachment.asc 

From python at venix.com  Fri Jul  7 21:44:25 2006
From: python at venix.com (Python)
Date: Fri, 07 Jul 2006 15:44:25 -0400
Subject: [Tutor] Logical Sorting
In-Reply-To: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
Message-ID: <1152301465.10267.1097.camel@www.venix.com>

On Fri, 2006-07-07 at 10:09 -0700, Evan Klitzke wrote:
> Hi,
> 
> I am trying to sort a list of directories that correspond to kernel
> sources under /usr/src/linux.  I wrote some code that gets a list like
> this:
> ['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r11/', 'linux-2.6.16-gentoo-r7/']
> 
> When I sort the list, I want it to go from oldest (lowest version) to
> newest, so the sorted list should look like this:
> ['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r7/', 'linux-2.6.16-gentoo-r11/']
> 
> The problem is that since the built in string comparisons compare
> character by character, so the sort puts 2.6.16 before 2.6.9, and -r11
> before -r7.  This is obviously not what I want.  My question is: are
> there any modules or built in methods that will do a logical sort on a
> list like this, and sort it the way I want, or will I have to write my
> own sorting function?

There is an rpm-python package that probably includes much of what you
want.  I have it installed, but never used it.  It appears to be pretty
light on documentation.  I expect it is a python wrapper to a C
library.  

You may find it easier to simply pick apart your data and sort the
numbers numerically than wrestle with learning this package unless you
have other RPM related tasks.

> 
> -- Evan Klitzke
> 
> P.S. I know that the simplest way is just to use ls to sort by time,
> but it is not necessarily true that older kernel versions have an
> older time stamp :-)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From marc_a_poulin at yahoo.com  Fri Jul  7 21:52:56 2006
From: marc_a_poulin at yahoo.com (Marc Poulin)
Date: Fri, 7 Jul 2006 12:52:56 -0700 (PDT)
Subject: [Tutor] Logical Sorting
In-Reply-To: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
Message-ID: <20060707195256.59563.qmail@web34102.mail.mud.yahoo.com>

I did a Google search for "python numeric sort" and
found

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/135435

It seems to do what you want.

Marc

--- Evan Klitzke <eklitzke at gmail.com> wrote:

> Hi,
> 
> I am trying to sort a list of directories that
> correspond to kernel
> sources under /usr/src/linux.  I wrote some code
> that gets a list like
> this:
> ['linux-2.6.9-gentoo-r4',
> 'linux-2.6.16-gentoo-r11/',
> 'linux-2.6.16-gentoo-r7/']
> 
> When I sort the list, I want it to go from oldest
> (lowest version) to
> newest, so the sorted list should look like this:
> ['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r7/',
> 'linux-2.6.16-gentoo-r11/']
> 
> The problem is that since the built in string
> comparisons compare
> character by character, so the sort puts 2.6.16
> before 2.6.9, and -r11
> before -r7.  This is obviously not what I want.  My
> question is: are
> there any modules or built in methods that will do a
> logical sort on a
> list like this, and sort it the way I want, or will
> I have to write my
> own sorting function?
> 
> -- Evan Klitzke
> 
> P.S. I know that the simplest way is just to use ls
> to sort by time,
> but it is not necessarily true that older kernel
> versions have an
> older time stamp :-)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From alan.gauld at freenet.co.uk  Fri Jul  7 22:59:32 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 7 Jul 2006 21:59:32 +0100
Subject: [Tutor] how to post an event?
References: <20060707183605.43657.qmail@web30512.mail.mud.yahoo.com>
Message-ID: <002f01c6a208$3f284680$0301a8c0@XPpro>

> Hello, I am having a bit of trouble figuring out how to post an 
> event.

Do you really need to post an event?

>        self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
>              id=wxID_FRAME1BUTTON2)

could you just bi8nd the same method to both buttons?

>    def OnButton1Button(self, event):
>        print 'hello'
>
>    def OnButton2Button(self, event):
>        event.Skip()
>        """what do I do here to post an event that executes 
> 'OnButton1Button()' ?"""

Or could you call OnButton1Button(self,event) directly?

Does it have to involve an event being posted to the Q - sometimes
needed I know but not often...

Alan G.

> 



From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=  Sat Jul  8 00:21:13 2006
From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=)
Date: Sat, 08 Jul 2006 01:21:13 +0300
Subject: [Tutor] Logical Sorting [Off-Topic]
In-Reply-To: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
Message-ID: <1152310873.25553.3.camel@localhost.localdomain>

On Fri, 2006-07-07 at 10:09 -0700, Evan Klitzke wrote:
> Hi,
> 
> I am trying to sort a list of directories that correspond to kernel
> sources under /usr/src/linux.  I wrote some code that gets a list like
> this:
> ['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r11/', 'linux-2.6.16-gentoo-r7/']
> 
> When I sort the list, I want it to go from oldest (lowest version) to
> newest, so the sorted list should look like this:
> ['linux-2.6.9-gentoo-r4', 'linux-2.6.16-gentoo-r7/', 'linux-2.6.16-gentoo-r11/']
> 
> The problem is that since the built in string comparisons compare
> character by character, so the sort puts 2.6.16 before 2.6.9, and -r11
> before -r7.  This is obviously not what I want.  My question is: are
> there any modules or built in methods that will do a logical sort on a
> list like this, and sort it the way I want, or will I have to write my
> own sorting function?
> 
> -- Evan Klitzke
> 
> P.S. I know that the simplest way is just to use ls to sort by time,
> but it is not necessarily true that older kernel versions have an
> older time stamp :-)
Or use ?ls -v?.  (I said it's ?off topic? on the subject, sorry!  It
might escaped you, but ?ls? _does_ have a proper sort by version.)

Ziyad.


From carroll at tjc.com  Sat Jul  8 02:08:52 2006
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 7 Jul 2006 17:08:52 -0700 (PDT)
Subject: [Tutor] Is implicit underscore assignment documented?
In-Reply-To: <Pine.LNX.4.44.0607071034330.26249-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0607071707390.30830-100000@violet.rahul.net>

On Fri, 7 Jul 2006, Terry Carroll wrote:

> As far as I can tell, the following transcript shows its workings:

Orri has privately pointed out to me that I have a copy-paste error in the 
transcript; but that aside, my question still is:

> Is this documented anywhere?


From alan.gauld at freenet.co.uk  Sat Jul  8 14:00:17 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 8 Jul 2006 13:00:17 +0100
Subject: [Tutor] Logical Sorting [Off-Topic]
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
	<1152310873.25553.3.camel@localhost.localdomain>
Message-ID: <000c01c6a286$145b8f60$0301a8c0@XPpro>

> Or use ?ls -v?.  (I said it's ?off topic? on the subject, sorry!  It
> might escaped you, but ?ls? _does_ have a proper sort by version.)

But very interesting, I'd never seen that feature of 'ls' before
and the man pages don't say much about it, you need to
go to the info pages. But it does indeed look like it would
do the job here.

Alan G. 



From alan.gauld at freenet.co.uk  Sat Jul  8 14:03:36 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 8 Jul 2006 13:03:36 +0100
Subject: [Tutor] Is implicit underscore assignment documented?
References: <Pine.LNX.4.44.0607071707390.30830-100000@violet.rahul.net>
Message-ID: <001901c6a286$8b0de9a0$0301a8c0@XPpro>

>> Is this documented anywhere?

The language reference has this to say:
2.3.2 Reserved classes of identifiers
Certain classes of identifiers (besides keywords) have special 
meanings.
These classes are identified by the patterns of leading and trailing
underscore characters:


  _* Not imported by "from module import *". The special identifier 
"_"
  is used in the interactive interpreter to store the result of the 
last evaluation;
  it is stored in the __builtin__ module. When not in interactive 
mode, "_"
  has no special meaning and is not defined.
HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From noka at gmx.net  Sat Jul  8 14:39:18 2006
From: noka at gmx.net (Norbert Kaufmann)
Date: Sat, 08 Jul 2006 14:39:18 +0200
Subject: [Tutor] Logical Sorting [Off-Topic]
In-Reply-To: <1152310873.25553.3.camel@localhost.localdomain>
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
	<1152310873.25553.3.camel@localhost.localdomain>
Message-ID: <44AFA776.20002@gmx.net>

???? ?? ????????? ??????? wrote:
[...]
> Or use ?ls -v?.  (I said it's ?off topic? on the subject, sorry!  It
> might escaped you, but ?ls? _does_ have a proper sort by version.)
> 

Which OS?

~$ uname -mrs
FreeBSD 6.1-STABLE i386
~$ ls -v
ls: illegal option -- v
usage: ls [-ABCFGHILPRSTUWZabcdfghiklmnopqrstuwx1] [file ...]

'The Open Group Base Specifications' does not list '-v' either.

Norbert

-- 
Warning at the Gates of Bill:
Abandon hope, all ye who press <ENTER> here...

From w.damen at gmail.com  Sat Jul  8 15:28:14 2006
From: w.damen at gmail.com (Rinzwind)
Date: Sat, 8 Jul 2006 15:28:14 +0200
Subject: [Tutor] Logical Sorting [Off-Topic]
In-Reply-To: <44AFA776.20002@gmx.net>
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
	<1152310873.25553.3.camel@localhost.localdomain>
	<44AFA776.20002@gmx.net>
Message-ID: <4677730607080628r3671be62s45bc1f80ae209d6f@mail.gmail.com>

Ubuntu Linux does:

rinzwind at diskworld:~$ ls -v
Desktop   GDM-DarkGno.tar.gz  foktopicstart   test.py~
Examples  Muziek              foktopicstart~
rinzwind at diskworld:~$

Here's a copy of a complete ls
http://www.mediacollege.com/cgi-bin/man/page.cgi?topic=ls


On my system it's also included in both the man (man ls) and the info (info
ls) page
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060708/43b9c89c/attachment.htm 

From rschroev_nospam_ml at fastmail.fm  Sat Jul  8 15:30:37 2006
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sat, 08 Jul 2006 15:30:37 +0200
Subject: [Tutor] Logical Sorting [Off-Topic]
In-Reply-To: <44AFA776.20002@gmx.net>
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>	<1152310873.25553.3.camel@localhost.localdomain>
	<44AFA776.20002@gmx.net>
Message-ID: <e8oc1t$3t0$1@sea.gmane.org>

Norbert Kaufmann schreef:
> ???? ?? ????????? ??????? wrote:
> [...]
>> Or use ?ls -v?.  (I said it's ?off topic? on the subject, sorry!  It
>> might escaped you, but ?ls? _does_ have a proper sort by version.)
>>
> 
> Which OS?

The one from GNU. It's commonly in GNU/Linux distributions, but it's 
possible to install on many other OS's too. Many GNU versions of all 
kinds of tools have extra options and features (for better or for worse, 
I'm not the one to judge).

$ ls --version
ls (coreutils) 5.2.1
Written by Richard Stallman and David MacKenzie.

Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ ls
100  20  4

$ ls -v
4  20  100

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven


From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=  Sat Jul  8 18:49:44 2006
From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=)
Date: Sat, 08 Jul 2006 19:49:44 +0300
Subject: [Tutor] Logical Sorting [Off-Topic]
In-Reply-To: <44AFA776.20002@gmx.net>
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com>
	<1152310873.25553.3.camel@localhost.localdomain>
	<44AFA776.20002@gmx.net>
Message-ID: <1152377385.16365.3.camel@localhost.localdomain>

On Sat, 2006-07-08 at 14:39 +0200, Norbert Kaufmann wrote:
 <???? ?? ????????? ??????? wrote:
> [...]
> > Or use ?ls -v?.  (I said it's ?off topic? on the subject, sorry!  It
> > might escaped you, but ?ls? _does_ have a proper sort by version.)
> > 
> 
> Which OS?
> 
> ~$ uname -mrs
> FreeBSD 6.1-STABLE i386
> ~$ ls -v
> ls: illegal option -- v
> usage: ls [-ABCFGHILPRSTUWZabcdfghiklmnopqrstuwx1] [file ...]
> 
> 'The Open Group Base Specifications' does not list '-v' either.
> 
> Norbert
> 
Almost all Linux flavours a used have that.  I'm currently using ?Ubuntu
5.10?.  Here's the output of ?ls --version?:
        zamb ~ $ ls --version
        ls (coreutils) 5.2.1
        Written by Richard Stallman and David MacKenzie.
        
        Copyright (C) 2004 Free Software Foundation, Inc.
        This is free software; see the source for copying conditions.  There
        is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
        PARTICULAR PURPOSE.

Ziyad.


From dyoo at hkn.eecs.berkeley.edu  Sat Jul  8 22:37:57 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 8 Jul 2006 13:37:57 -0700 (PDT)
Subject: [Tutor] activestate
In-Reply-To: <CFC2D6BC-2AEE-45BE-986B-5948BC75B3C4@mac.com>
References: <Pine.LNX.4.44.0603112012190.27816-100000@hkn.eecs.berkeley.edu>
	<CFC2D6BC-2AEE-45BE-986B-5948BC75B3C4@mac.com>
Message-ID: <Pine.LNX.4.64.0607081330380.6602@hkn.eecs.berkeley.edu>



On Thu, 6 Jul 2006, kevin parks wrote:

> The same thing is happening again. The archive:
>
> http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor
>
> seems stalled out at April 20th

Hi Kevin,

Sorry for the late response.  I'm not as active on Python-tutor as I've 
been in the past because my time is now focused on graduate school.  I've 
transferred most of my list-admin responsibilities to Kent.  In the 
future, send administrative questions to: tutor-owner at python.org; this 
will hit both Kent and me.


I'm not sure what ActiveState is doing about this.  In the meantime, try 
gmane's service:

     http://dir.gmane.org/gmane.comp.python.tutor

If it turns out that this is a good long-term solution, we'll change the 
links on the Tutor mailing list page from ActiveState's searchable archive 
to the one on gmane.


Best of wishes!

From alan.gauld at btinternet.com  Sun Jul  9 10:23:03 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 9 Jul 2006 09:23:03 +0100
Subject: [Tutor] Logical Sorting [Off-Topic]
References: <fab7f7b40607071009g55876b25j96fc9bc9b34cd73a@mail.gmail.com><1152310873.25553.3.camel@localhost.localdomain>
	<44AFA776.20002@gmx.net>
Message-ID: <e8qed7$9hj$1@sea.gmane.org>

>> Or use 'ls -v'.  (I said it's "off topic" on the subject, sorry! 
>> It
>> might escaped you, but 'ls' _does_ have a proper sort by version.)
>>
>
> Which OS?

Most of them, its the GNU version of ls...

works on cygwin, linux, bsd, solaris....

Alan G




From johnsonv3 at sbcglobal.net  Sun Jul  9 21:55:56 2006
From: johnsonv3 at sbcglobal.net (johnsonv3)
Date: Sun, 9 Jul 2006 15:55:56 -0400
Subject: [Tutor] keystroke via software
Message-ID: <001b01c6a391$b1786280$05dfd445@home>

Hi,
How can one make a networked Windows XP  think a keystroke has been made every 13 minutes?  What would a python program to do this look like?

Thanks for your help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060709/b9860c95/attachment.html 

From daniel at thewatkins.org.uk  Sun Jul  9 18:12:47 2006
From: daniel at thewatkins.org.uk (Daniel Watkins)
Date: Sun, 09 Jul 2006 17:12:47 +0100
Subject: [Tutor] activestate
References: <Pine.LNX.4.44.0603112012190.27816-100000@hkn.eecs.berkeley.edu>
	<CFC2D6BC-2AEE-45BE-986B-5948BC75B3C4@mac.com>
	<Pine.LNX.4.64.0607081330380.6602@hkn.eecs.berkeley.edu>
Message-ID: <e8r9si$dis$1@sea.gmane.org>

Danny Yoo wrote:
> If it turns out that this is a good long-term solution, we'll change the
> links on the Tutor mailing list page from ActiveState's searchable archive
> to the one on gmane.

I've been using gmane for a few months now, without any problems.

Dan


From alan.gauld at btinternet.com  Mon Jul 10 01:45:22 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 10 Jul 2006 00:45:22 +0100
Subject: [Tutor] keystroke via software
References: <001b01c6a391$b1786280$05dfd445@home>
Message-ID: <e8s4ek$k59$1@sea.gmane.org>

> How can one make a networked Windows XP
> think a keystroke has been made every 13 minutes?

I've never done it over a network but I have done it in Delphi.

The API function you need is:

PostMessage(hwnd, idMessage, wParam, lParam)

Post a message to a window.


Parameters

hwnd : int The hWnd of the window to receive the message.
idMessage : int  The ID of the message to post.
wParam : int The wParam for the message
lParam : int The lParam for the message

> What would a python program to do this look like?

Like I say I've never tried it from Python, but you need to
find a way to getb the handle of the window to which you
want to post the message. A tool like WinSpy will provide that info.

The Keypress messages are all defined in the API reference
material, there are subtle differences so check the docs.

Finally the wparam/lparams will depend on the actual
message you choose, aghain refer to the docs. BBut in
theory its a case of importing the win32 modules and
sending the message wiith a 15 second sleep() in between...

HTH,

Alan G. 




From gwhjr at cox.net  Mon Jul 10 03:10:20 2006
From: gwhjr at cox.net (Grady Henry)
Date: Sun, 9 Jul 2006 18:10:20 -0700
Subject: [Tutor] error: (10054, 'Connection reset by peer')
Message-ID: <001901c6a3bd$9d160410$8b4a6244@valued61da873e>

Here is a program that I wrote using the first example at 12.2.13 Examples at the www.python.org website,

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.MIMEText import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open('C:\Documents and Settings\User\Desktop\\text3.txt','rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % 'C:\Documents and Settings\User\Desktop\\text3.txt'
msg['From'] = 'gwhjr at cox.net'
msg['To'] = 'gwhjr at bigfoot.com'

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.connect()
s.sendmail(me, [you], msg.as_string())
s.close()

When I run the program using IDLE, I get the following message:

Traceback (most recent call last):
  File "C:\Documents and Settings\User\Desktop\textsender.py", line 23, in ?
    s.connect()
  File "C:\Python24\lib\smtplib.py", line 307, in connect
    (code, msg) = self.getreply()
  File "C:\Python24\lib\smtplib.py", line 348, in getreply
    line = self.file.readline()
  File "C:\Python24\lib\socket.py", line 340, in readline
    data = self._sock.recv(self._rbufsize)
error: (10054, 'Connection reset by peer')

What does this mean, and how can I fix it?

Grady Henry
gwhjr at bigfoot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060709/819bd42b/attachment.htm 

From hxianping at gmail.com  Mon Jul 10 05:22:41 2006
From: hxianping at gmail.com (=?GB2312?B?uqvP3Ma9?=)
Date: Mon, 10 Jul 2006 11:22:41 +0800
Subject: [Tutor] How to learn messages frim help()?
Message-ID: <702805a90607092022j493c28cend0cd5d5f8b930bd8@mail.gmail.com>

Hi,all.For example,I want learn build-in function TYPE,do help(type)
and get message as following:

Help on class type in module __builtin__:

class type(object)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type
 |
 |  Methods defined here:
 |
 |  __call__(...)
 |      x.__call__(...) <==> x(...)
 |
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |
 |  __delattr__(...)
 |      x.__delattr__('name') <==> del x.name
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
......
Have TYPE defined these methods?
What relation with __call__,__cam__ etc?

Steve

From abhinavtester at yahoo.co.uk  Mon Jul 10 05:54:03 2006
From: abhinavtester at yahoo.co.uk (Abhinav Gaurav)
Date: Mon, 10 Jul 2006 04:54:03 +0100 (BST)
Subject: [Tutor] Splitting
Message-ID: <20060710035403.38926.qmail@web86904.mail.ukl.yahoo.com>

HI,
   
  I was working on example of splitting using delimiter ;
   
  Example :-
  >>> a="43;dsds;d" 
>>> 
>>> b=a.split(';')
   
  Here I encountered the following error :-
   
  Traceback (innermost last):
  File "<stdin>", line 1, in ?
AttributeError: 'string' object has no attribute 'split'
   
  Can anybody help on resolving this issue?
   
  Thanks
  Abhinav

 		
---------------------------------
 Try the all-new Yahoo! Mail . "The New Version is radically easier to use" ? The Wall Street Journal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060710/5f519c26/attachment.html 

From daniel at thewatkins.org.uk  Mon Jul 10 06:29:19 2006
From: daniel at thewatkins.org.uk (Daniel Watkins)
Date: Mon, 10 Jul 2006 05:29:19 +0100
Subject: [Tutor] Splitting
References: <20060710035403.38926.qmail@web86904.mail.ukl.yahoo.com>
Message-ID: <e8sl1h$rkr$1@sea.gmane.org>

Abhinav Gaurav wrote:
>   Example :-
>   >>> a="43;dsds;d"
>>>> 
>>>> b=a.split(';')
    
>   Can anybody help on resolving this issue?

This is what it looks like on my computer:
        >>> a="43;dsds;d"
        >>> b=a.split(";")
        >>> print b
        ['43', 'dsds', 'd']

This is using Python 2.4.2, though AFAI can recall this behaviour hasn't
changed in a while... Weird...

Sorry I couldn't be more help,
Dan


From abhinavtester at yahoo.co.uk  Mon Jul 10 06:38:52 2006
From: abhinavtester at yahoo.co.uk (Abhinav Gaurav)
Date: Mon, 10 Jul 2006 05:38:52 +0100 (BST)
Subject: [Tutor] Splitting
In-Reply-To: <e8sl1h$rkr$1@sea.gmane.org>
Message-ID: <20060710043852.54790.qmail@web86906.mail.ukl.yahoo.com>

Hi,
   
  Thanks for your help! I am wondering if it works fine then why it failing on my comp. And what is the remedy for it?
   
  Thanks
  Abhinav

Daniel Watkins <daniel at thewatkins.org.uk> wrote:
  Abhinav Gaurav wrote:
> Example :-
> >>> a="43;dsds;d"
>>>> 
>>>> b=a.split(';')

> Can anybody help on resolving this issue?

This is what it looks like on my computer:
>>> a="43;dsds;d"
>>> b=a.split(";")
>>> print b
['43', 'dsds', 'd']

This is using Python 2.4.2, though AFAI can recall this behaviour hasn't
changed in a while... Weird...

Sorry I couldn't be more help,
Dan

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


 		
---------------------------------
 Try the all-new Yahoo! Mail . "The New Version is radically easier to use" ? The Wall Street Journal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060710/6389e9ff/attachment.html 

From john at fouhy.net  Mon Jul 10 06:46:37 2006
From: john at fouhy.net (John Fouhy)
Date: Mon, 10 Jul 2006 16:46:37 +1200
Subject: [Tutor] Splitting
In-Reply-To: <20060710043852.54790.qmail@web86906.mail.ukl.yahoo.com>
References: <e8sl1h$rkr$1@sea.gmane.org>
	<20060710043852.54790.qmail@web86906.mail.ukl.yahoo.com>
Message-ID: <5e58f2e40607092146t52629e58u99fb687d693417b7@mail.gmail.com>

On 10/07/06, Abhinav Gaurav <abhinavtester at yahoo.co.uk> wrote:
>
> Hi,
>
> Thanks for your help! I am wondering if it works fine then why it failing on
> my comp. And what is the remedy for it?

What version of python are you running?

-- 
John.

From john at fouhy.net  Mon Jul 10 07:01:02 2006
From: john at fouhy.net (John Fouhy)
Date: Mon, 10 Jul 2006 17:01:02 +1200
Subject: [Tutor] Splitting
In-Reply-To: <20060710045318.32304.qmail@web86903.mail.ukl.yahoo.com>
References: <5e58f2e40607092146t52629e58u99fb687d693417b7@mail.gmail.com>
	<20060710045318.32304.qmail@web86903.mail.ukl.yahoo.com>
Message-ID: <5e58f2e40607092201h43afd9c2n9d12f7af39ea742d@mail.gmail.com>

On 10/07/06, Abhinav Gaurav <abhinavtester at yahoo.co.uk> wrote:
> John Fouhy <john at fouhy.net> wrote:
> > What version of python are you running?
> 1.5.2 is the version.

Right.  Well, you're slightly over 7 years out of date :-)  Do you
have the ability to upgrade?  You or your system administrator can
download the latest release from http://python.org/ -- python 2.4.3 is
the latest stable release.  You will probably find that much of what
you read on the web is incorrect for python 1.5.2.

-- 
John.

From rabidpoobear at gmail.com  Mon Jul 10 07:39:45 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 10 Jul 2006 00:39:45 -0500
Subject: [Tutor] How to learn messages frim help()?
In-Reply-To: <702805a90607092022j493c28cend0cd5d5f8b930bd8@mail.gmail.com>
References: <702805a90607092022j493c28cend0cd5d5f8b930bd8@mail.gmail.com>
Message-ID: <44B1E821.9060002@gmail.com>


> and get message as following:
[snip help output]
> Have TYPE defined these methods?
> What relation with __call__,__cam__ etc?
don't think you're supposed to actually deal with the class called 'type'.
I assume you're referring to typecasting variables.
What it means when it says 'type()' is, for example,
str( ), int( ) etc.

Take the following example.
 >>> a = 2
 >>> print a
2
 >>>print 'your number is '+a
TypeError: cannot concatenate str and int objects.
 >>>print 'your number is '+str(a)
your number is 2

note that you could just do
 >>> print 'your number is %s.' % a
your number is 2.

that will take care of the type conversion for you.

HTH,
Luke

From carroll at tjc.com  Mon Jul 10 09:12:20 2006
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 10 Jul 2006 00:12:20 -0700 (PDT)
Subject: [Tutor] Splitting
In-Reply-To: <5e58f2e40607092201h43afd9c2n9d12f7af39ea742d@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0607100010190.3479-100000@violet.rahul.net>

On Mon, 10 Jul 2006, John Fouhy wrote:

> On 10/07/06, Abhinav Gaurav <abhinavtester at yahoo.co.uk> wrote:
> > John Fouhy <john at fouhy.net> wrote:
> > > What version of python are you running?
> > 1.5.2 is the version.
> 
> Right.  Well, you're slightly over 7 years out of date :-)  Do you
> have the ability to upgrade?  

Abhinav, I second upgrading.  There's been so much great stuff added to 
Python since 1.5, it's well worth the upgrade.

If you're stuck on 1.5.2, I *think* this will do what you want (I'm 
actually executing under 2.4.1, but I think this should work under 1.5 as 
well):

>>> import string
>>> a="43;dsds;d"
>>> b=string.split(a,';')
>>> b
['43', 'dsds', 'd']
>>>



From ewald.ertl at hartter.com  Mon Jul 10 09:21:24 2006
From: ewald.ertl at hartter.com (Ewald Ertl)
Date: Mon, 10 Jul 2006 09:21:24 +0200
Subject: [Tutor] error: (10054, 'Connection reset by peer')
In-Reply-To: <001901c6a3bd$9d160410$8b4a6244@valued61da873e>
References: <001901c6a3bd$9d160410$8b4a6244@valued61da873e>
Message-ID: <44B1FFF4.2070005@hartter.com>

Hello!

Grady Henry wrote:
> Here is a program that I wrote using the first example at 12.2.13
> Examples at the www.python.org <http://www.python.org> website,
>  
> # Import smtplib for the actual sending function
> import smtplib
>  
> # Import the email modules we'll need
> from email.MIMEText import MIMEText
>  
> # Open a plain text file for reading.  For this example, assume that
> # the text file contains only ASCII characters.
> fp = open('C:\Documents and Settings\User\Desktop\\text3.txt','rb')
> # Create a text/plain message
> msg = MIMEText(fp.read())
> fp.close()
>  
> # me == the sender's email address
> # you == the recipient's email address
> msg['Subject'] = 'The contents of %s' % 'C:\Documents and
> Settings\User\Desktop\\text3.txt'
> msg['From'] = 'gwhjr at cox.net' <mailto:'gwhjr at cox.net'>
> msg['To'] = 'gwhjr at bigfoot.com' <mailto:'gwhjr at bigfoot.com'>
>  
> # Send the message via our own SMTP server, but don't include the
> # envelope header.
> s = smtplib.SMTP()
> s.connect()
> s.sendmail(me, [you], msg.as_string())
> s.close()
>  
> When I run the program using IDLE, I get the following message:
>  
> Traceback (most recent call last):
>   File "C:\Documents and Settings\User\Desktop\textsender.py", line 23, in ?
>     s.connect()
>   File "C:\Python24\lib\smtplib.py", line 307, in connect
>     (code, msg) = self.getreply()
>   File "C:\Python24\lib\smtplib.py", line 348, in getreply
>     line = self.file.readline()
>   File "C:\Python24\lib\socket.py", line 340, in readline
>     data = self._sock.recv(self._rbufsize)
> error: (10054, 'Connection reset by peer')
>  
> What does this mean, and how can I fix it?
You try to connect to your localhost on Port 25 for sending email. Because of
the Windows-Error 10054 'Connection reset by peer', I think you do not have an
email server running on your server.
Perhaps you can supply your email server in smtplib.SMTP().
Here is the pydoc of the init-Method:

__init__(self, host='', port=0, local_hostname=None)
    Initialize a new instance.

    If specified, `host' is the name of the remote host to which to
    connect.  If specified, `port' specifies the port to which to connect.
    By default, smtplib.SMTP_PORT is used.  An SMTPConnectError is raised
    if the specified `host' doesn't respond correctly.  If specified,
    `local_hostname` is used as the FQDN of the local host.  By default,
    the local hostname is found using socket.getfqdn().

HTH
Ewald


From alan.gauld at freenet.co.uk  Mon Jul 10 09:37:46 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 10 Jul 2006 08:37:46 +0100
Subject: [Tutor] How to learn messages frim help()?
References: <702805a90607092022j493c28cend0cd5d5f8b930bd8@mail.gmail.com>
Message-ID: <001e01c6a3f3$bd1ca7b0$0301a8c0@XPpro>

> Hi,all.For example,I want learn build-in function TYPE,do help(type)
> and get message as following:
> 
> Help on class type in module __builtin__:
> 
> class type(object)
> |  type(object) -> the object's type
> |  type(name, bases, dict) -> a new type
> |
> |  Methods defined here:
> |
> |  __call__(...)
> |      x.__call__(...) <==> x(...)
> |
> |  __cmp__(...)
> |      x.__cmp__(y) <==> cmp(x,y)

> Have TYPE defined these methods?
> What relation with __call__,__cam__ etc?

I'm not sure what you are asking but yes, the help screen 
is telling you that the type class implements these 
methods and subtypes can overrride them.

Thus the type int is callable so we can do things like:

print int('45')

Similarly we can compare items of a given type 
because the cmp method is implemented, so 
we can do 

print type(5) == type(42)

Does that answer your question?

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at freenet.co.uk  Mon Jul 10 09:42:11 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 10 Jul 2006 08:42:11 +0100
Subject: [Tutor] Splitting
References: <20060710035403.38926.qmail@web86904.mail.ukl.yahoo.com>
Message-ID: <002a01c6a3f4$5affa950$0301a8c0@XPpro>

>  Example :-
>  >>> a="43;dsds;d" 
>>>> 
>>>> b=a.split(';')
>   
>  Here I encountered the following error :-
>   
>  Traceback (innermost last):
>  File "<stdin>", line 1, in ?
> AttributeError: 'string' object has no attribute 'split'
>   
>  Can anybody help on resolving this issue?

>>> a="43;dsds;d"
>>> b=a.split(';')
>>> b
['43', 'dsds', 'd']
>>>

Works for me in Python 2.4

Are you using an old version of Python? pre v2.0?
If so you need to use the string module rather than string methods.
Otherwise I don't know what might be wrong.

Alan G.


From hxianping at gmail.com  Mon Jul 10 09:55:52 2006
From: hxianping at gmail.com (=?GB2312?B?uqvP3Ma9?=)
Date: Mon, 10 Jul 2006 15:55:52 +0800
Subject: [Tutor] How to learn messages frim help()?
In-Reply-To: <001e01c6a3f3$bd1ca7b0$0301a8c0@XPpro>
References: <702805a90607092022j493c28cend0cd5d5f8b930bd8@mail.gmail.com>
	<001e01c6a3f3$bd1ca7b0$0301a8c0@XPpro>
Message-ID: <702805a90607100055o7f561510o6a8373dc2fa79f0f@mail.gmail.com>

On 7/10/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> > Hi,all.For example,I want learn build-in function TYPE,do help(type)
> > and get message as following:
> >
> > Help on class type in module __builtin__:
> >
> > class type(object)
> > |  type(object) -> the object's type
> > |  type(name, bases, dict) -> a new type
> > |
> > |  Methods defined here:
> > |
> > |  __call__(...)
> > |      x.__call__(...) <==> x(...)
> > |
> > |  __cmp__(...)
> > |      x.__cmp__(y) <==> cmp(x,y)
>
> > Have TYPE defined these methods?
> > What relation with __call__,__cam__ etc?
>
> I'm not sure what you are asking but yes, the help screen
> is telling you that the type class implements these
> methods and subtypes can overrride them.
>
> Thus the type int is callable so we can do things like:
>
> print int('45')
>
> Similarly we can compare items of a given type
> because the cmp method is implemented, so
> we can do
>
> print type(5) == type(42)
>
> Does that answer your question?
>
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
Thank you Alan.That exactelly my question!!

From jeffpeery at yahoo.com  Mon Jul 10 22:16:40 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Mon, 10 Jul 2006 13:16:40 -0700 (PDT)
Subject: [Tutor] how to post an event?
In-Reply-To: <002f01c6a208$3f284680$0301a8c0@XPpro>
Message-ID: <20060710201640.80640.qmail@web30505.mail.mud.yahoo.com>

Ah, yes it works, thanks. I had previously tried to simply call the function (OnButton1Button() from OnButton2Button()) instead of posting an event but I guess I did this wrong and abandoned the effort assuming that it wouldn't work. Anyhow, I got it working now, thanks again!

Jeff

Alan Gauld <alan.gauld at freenet.co.uk> wrote: > Hello, I am having a bit of trouble figuring out how to post an 
> event.

Do you really need to post an event?

>        self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
>              id=wxID_FRAME1BUTTON2)

could you just bi8nd the same method to both buttons?

>    def OnButton1Button(self, event):
>        print 'hello'
>
>    def OnButton2Button(self, event):
>        event.Skip()
>        """what do I do here to post an event that executes 
> 'OnButton1Button()' ?"""

Or could you call OnButton1Button(self,event) directly?

Does it have to involve an event being posted to the Q - sometimes
needed I know but not often...

Alan G.

> 




 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060710/e0e72541/attachment.html 

From rfquerin at gmail.com  Tue Jul 11 05:50:03 2006
From: rfquerin at gmail.com (Richard Querin)
Date: Mon, 10 Jul 2006 23:50:03 -0400
Subject: [Tutor] How can I copy files recursively?
Message-ID: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>

I know this is probably a dumb question:

I've got mp3 files that are downloaded (by ipodder) into individual
subfolders. I'd like to write a quick script to move (not copy) all the mp3
files in those folders into a single destination folder. I was thinking I
could do it easily from the linux command line (cp -r copies the subfolders
out as well) but I can't figure out how to do it. Is there an easy way to
achieve this using Python? I am assuming this would be something Python was
designed to make easy..
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060710/ee98332c/attachment.html 

From python-tutor at v.igoro.us  Tue Jul 11 05:57:32 2006
From: python-tutor at v.igoro.us (Dustin J. Mitchell)
Date: Mon, 10 Jul 2006 22:57:32 -0500
Subject: [Tutor] How can I copy files recursively?
In-Reply-To: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
Message-ID: <44B321AC.8090509@v.igoro.us>

Richard Querin wrote:
> I know this is probably a dumb question:
> 
> I've got mp3 files that are downloaded (by ipodder) into individual
> subfolders. I'd like to write a quick script to move (not copy) all the
> mp3 files in those folders into a single destination folder. I was
> thinking I could do it easily from the linux command line (cp -r copies
> the subfolders out as well) but I can't figure out how to do it. Is
> there an easy way to achieve this using Python? I am assuming this would
> be something Python was designed to make easy..

Python's not always the best with complex manipulations like that.  You
could use os.path.walk, but here's the same thing in bash:

 find $IPODDER_DIR -type f -exec mv \{} $DEST_DIR \;

Dustin

From john at fouhy.net  Tue Jul 11 06:15:09 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 11 Jul 2006 16:15:09 +1200
Subject: [Tutor] How can I copy files recursively?
In-Reply-To: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
Message-ID: <5e58f2e40607102115j401f9683k407b2ab7abcb4145@mail.gmail.com>

On 11/07/06, Richard Querin <rfquerin at gmail.com> wrote:
> I know this is probably a dumb question:
>
> I've got mp3 files that are downloaded (by ipodder) into individual
> subfolders. I'd like to write a quick script to move (not copy) all the mp3
> files in those folders into a single destination folder. I was thinking I
> could do it easily from the linux command line (cp -r copies the subfolders
> out as well) but I can't figure out how to do it. Is there an easy way to
> achieve this using Python? I am assuming this would be something Python was
> designed to make easy..

You could do it from the command line with something like:

$ for f in `find ./ -name *.mp3`; do mv $f /foo/bar/$f; done

(actually, that won't work; you'll need to find a way to convert
"/x/y/z.mp3" to "z.mp3".  I don't have a linux commandline handy to
test.. basename, maybe? You could do it with awk --

$ for f in `find ./ -name *.mp3`; do mv $f /foo/bar/`echo $f | awk -F
'/' '{print $NF}'`; done

but that's pretty hairy and may not work :-/
)

In python, you can use os.rename to move and os.walk to walk your
directory structure.  Something like:

source = '/ipodder'
dest = '/foo/bar'
for root, dirs, files in os.walk(source):
    for f in files:
        os.rename(os.path.join(root, f), os.path.join(dest, f))

(although I would do a test run first, if I were you, since I often
get os.walk wrong :-) )

-- 
John.

From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=  Tue Jul 11 06:21:47 2006
From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=)
Date: Tue, 11 Jul 2006 07:21:47 +0300
Subject: [Tutor] How can I copy files recursively? [Off Topic, AGAIN]
In-Reply-To: <44B321AC.8090509@v.igoro.us>
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
	<44B321AC.8090509@v.igoro.us>
Message-ID: <1152591707.31272.17.camel@localhost.localdomain>

This is ?Off Topic? regarding the mailing list!

On Mon, 2006-07-10 at 22:57 -0500, Dustin J. Mitchell wrote: (altered by
Ziyad)
> Richard Querin wrote:
> > ...
> > I was thinking I could do it easily from the linux command line
> > (cp -r copies the subfolders out as well) but I can't figure out
> > how to do it.
> > ...
> Python's not always the best with complex manipulations like that.  You
> could use os.path.walk, but here's the same thing in bash:
> 
>  find $IPODDER_DIR -type f -exec mv \{} $DEST_DIR \;
> 
> Dustin
You could use something like this:
        find SOURCE_DIR -type f -print0 | xargs -0 -i mv {} DIST_DIR

Where SOURCE_DIR is the top level directory holding the files and
DIST_DIR is the directory you want to move the files to.

Make sure there are no conflict in file names otherwise some files will
be overwritten!

Dustin's version will work perfectly but if there's a lot files it'll
exhaust your system because it will create a new process for each file
it finds (plus another process for the ?find? command itself), while the
other version will only create *three* processes only! (One for ?find?,
another for ?xargs? and the third is for *one* ?mv? move command.)

(There's another way by using two piped ?tar? commands, but that's
overkilling it and the above solution is much more elegant.)

A side note:
        I apologise for the list as it seems I'm only good at posting
        anything *but* Python related.

Ziyad.


From cspears2002 at yahoo.com  Tue Jul 11 06:34:23 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Mon, 10 Jul 2006 21:34:23 -0700 (PDT)
Subject: [Tutor] printing 00
Message-ID: <20060711043423.92652.qmail@web51605.mail.yahoo.com>

I'm working on a problem from "How To Think Like A
Computer Scientist".  I created  a Time class:

class Time:
	
	def __init__(self, hours, minutes, seconds):
		self.hours = hours
		self.minutes = minutes
		self.seconds = seconds

I created a function to print the Time object:

def printTime(time):
	print "%d:%d:%d" % (time.hours, time.minutes,
time.seconds)
		
However, when I type '00', I get the following:
>>> time = Time(12,34.4,00)
>>> printTime(time)
12:34:0
>>> time.seconds
0

How do I get around this problem?  I know there is a
time module.  However, I think that is overkill for
this particular assignment.


From dyoo at hkn.eecs.berkeley.edu  Tue Jul 11 07:45:01 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 10 Jul 2006 22:45:01 -0700 (PDT)
Subject: [Tutor] printing 00
In-Reply-To: <20060711043423.92652.qmail@web51605.mail.yahoo.com>
References: <20060711043423.92652.qmail@web51605.mail.yahoo.com>
Message-ID: <Pine.LNX.4.64.0607102243080.5087@hkn.eecs.berkeley.edu>

> I created a function to print the Time object:
>
> def printTime(time):
> 	print "%d:%d:%d" % (time.hours, time.minutes,
> time.seconds)
>
> However, when I type '00', I get the following:
>>>> time = Time(12,34.4,00)
>>>> printTime(time)
> 12:34:0

Hi Chris,

You'll want to check some of the details on "String Formatting" -- there's 
an option to format a number using two (or more) digits:

     http://www.python.org/doc/lib/typesseq-strings.html

Good luck!

From dyoo at hkn.eecs.berkeley.edu  Tue Jul 11 08:05:13 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 10 Jul 2006 23:05:13 -0700 (PDT)
Subject: [Tutor] How can I copy files recursively?
In-Reply-To: <5e58f2e40607102115j401f9683k407b2ab7abcb4145@mail.gmail.com>
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
	<5e58f2e40607102115j401f9683k407b2ab7abcb4145@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0607102252280.5087@hkn.eecs.berkeley.edu>

> directory structure.  Something like:
>
> source = '/ipodder'
> dest = '/foo/bar'
> for root, dirs, files in os.walk(source):
>    for f in files:
>        os.rename(os.path.join(root, f), os.path.join(dest, f))

A helper function here will be useful.  We can simulate something like:

     find . -name '*.mp3'

with:

#####################################################
import os, fnmatch

def find_with_glob(dir, pattern):
     """find_with_glob: string string -> listof(string)
     Returns a list of all the files that can be found
     in dir or subdirectories, matching the globbing pattern.

     For example: find_with_glob('.', '*.mp3').
     """
     results = []
     for root, dirs, files in os.walk(dir):
         for f in files:
             if fnmatch.fnmatch(f, pattern):
                 results.append(os.path.join(root, f))
     return results
#####################################################

The reason this ends up a bit verbose compared to the shell is because the 
shell's 'find' utility is doing a lot of work too.  But if we were to do a 
simple lookup for mp3 files, I agree that using Unix's 'find' would be the 
simplest approach.

One advantage we have in using Python here is generality: we can, with a 
little work, plug in a different kind of filter here: rather than use 
globs, we can use full-fledged regular expressions.

From kent37 at tds.net  Tue Jul 11 13:07:54 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 11 Jul 2006 07:07:54 -0400
Subject: [Tutor] How can I copy files recursively?
In-Reply-To: <5e58f2e40607102115j401f9683k407b2ab7abcb4145@mail.gmail.com>
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
	<5e58f2e40607102115j401f9683k407b2ab7abcb4145@mail.gmail.com>
Message-ID: <44B3868A.1090106@tds.net>

John Fouhy wrote:
> On 11/07/06, Richard Querin <rfquerin at gmail.com> wrote:
>   
>> I know this is probably a dumb question:
>>
>> I've got mp3 files that are downloaded (by ipodder) into individual
>> subfolders. I'd like to write a quick script to move (not copy) all the mp3
>> files in those folders into a single destination folder. I was thinking I
>> could do it easily from the linux command line (cp -r copies the subfolders
>> out as well) but I can't figure out how to do it. Is there an easy way to
>> achieve this using Python? I am assuming this would be something Python was
>> designed to make easy..
>>     
>
> In python, you can use os.rename to move and os.walk to walk your
> directory structure.  Something like:
>
> source = '/ipodder'
> dest = '/foo/bar'
> for root, dirs, files in os.walk(source):
>     for f in files:
>         os.rename(os.path.join(root, f), os.path.join(dest, f))
This will copy all the files into the dest directory - it doesn't copy 
the folder structure.

I highly recommend Jason Orendorff's path module for any code involving 
walking directories. Something like this:

from path import path
source = path('/ipodder')
dest = '/foo/bar'

for mp3 in source.walkfiles('*.mp3'):
  relpath = source.relpathto(mp3)
  destmp3 = dest / relpath
  os.rename(mp3, destmp3)

http://www.jorendorff.com/articles/python/path/index.html
Kent


From john.j.shappelljr at us.army.mil  Mon Jul 10 21:14:21 2006
From: john.j.shappelljr at us.army.mil (Shappell, John J CW2)
Date: Mon, 10 Jul 2006 14:14:21 -0500
Subject: [Tutor]  Need Help
Message-ID: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>

Here is the assignment

1.	You've been given an assignment by your supervisor to program a
small application to monitor the current status of the cash account in the
firm's petty cash fund (the amount of cash kept on hand in the office for
incidental purchases). The requirements for the program are to allow users
to input the amount of cash deposited, the amount of cash withdrawn and to
get a report of the balance at any given time. You will need to also add the
date of each deposit and the date of each withdrawal and provide a date with
the balance returned upon a given query. The program should be able to
provide a printed report and support a command line query.
		You are to use the object oriented properties of Python to
accomplish this task. 

This is where I am at so far.  I don't understand how to get the Account
class into the program. Can you help a little,  Just looking for an idea or
some guidance
#!/usr/bin/python
# Filename: petty cash.py

print "Welcome to the petty cash account"
print "Did you deposit or withdrawl money today"
print

# print out menu
print "please select a number"
print "1 for deposit"
print "2 for withdrawl"

# Get user's choice:
number = input (">")
#
if number == 1:
    deposit = input ("how much?")
    print "I deposited:", deposit
    
elif number == 2:
    withdrawl = input ("How Much?")
    print "I withdrew:", withdrawl
    
print "what is today's date?"
# Get date from user
date = input (">")

This is where I get stuck. The program will allow me to input the deposit or
withdrawl ammount and the date but does nothing ownce it gets here
class Account:
     def __init__(self, initial):
         self.balance = initial
     def deposit(self, amt):
         self.balance = self.balance + amt
     def withdraw(self,amt):
         self.balance = self.balance - amt
     def getbalance(self):
         return self.balance 

V/R

CW2 John Shappell
HHB 2-44 ADA BN
Work 270-798-6823
FAX 775-618-2455
john.shappell at campbell.army.mil
john.j.shappelljr at us.army.mil




-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060710/654e4831/attachment.html 

From rabidpoobear at gmail.com  Tue Jul 11 13:41:23 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 11 Jul 2006 06:41:23 -0500
Subject: [Tutor] Need Help
In-Reply-To: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
References: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
Message-ID: <44B38E63.5090202@gmail.com>

Hi.
Shappell, John J CW2 wrote:
>
> Here is the assignment
>
[snip assignment]
Please don't ask about homework in the future.  Did your professor tell 
you to submit queries to this list?  If so, could you ask him not to? 
it's against the policies of the tutor mailing list to give homework 
help.  However, I can give you a few hints about python in general.  The 
rules may be different but my impression was that there was no homework 
to be submitted here.  If I'm wrong please correct me.
>
> This is where I am at so far.  I don't understand how to get the 
> Account class into the program. Can you help a little,  Just looking 
> for an idea or some guidance
>
> #!/usr/bin/python
> # Filename: petty cash.py
>
> print "Welcome to the petty cash account"
> print "Did you deposit or withdrawl money today"
>
> print
>
> # print out menu
> print "please select a number"
> print "1 for deposit"
> print "2 for withdrawl"
>
> # Get user's choice:
> number = input (">")
>
I suggest doing something like
number = int(raw_input("> "))
I'm pretty sure the 'input' statement is a no-no, unless your Professor 
says, and then you should use it.
>
> #
> if number == 1:
>     deposit = input ("how much?")
>     print "I deposited:", deposit
>    
> elif number == 2:
>     withdrawl = input ("How Much?")
>     print "I withdrew:", withdrawl
>    
> print "what is today's date?"
> # Get date from user
> date = input (">")
>
> *This is where I get stuck. The program will allow me to input the 
> deposit or withdrawl ammount and the date but does nothing ownce it 
> gets here*
>
> class Account:
>      def __init__(self, initial):
>          self.balance = initial
>      def deposit(self, amt):
>          self.balance = self.balance + amt
>      def withdraw(self,amt):
>          self.balance = self.balance - amt
>      def getbalance(self):
>          return self.balance
>
What you have there is a class, not an instance of a class.  read more 
about the difference at http://www.python.org/doc/2.2.3/tut/node11.html
or some other tutorial site.
Also, make it clear to your instructor that you had trouble here.  If he 
doesn't know what's hanging people up he won't be able to help you with it.

>
> john.shappell at campbell.army.mil
> john.j.shappelljr at us.army.mil
>
What was your job in the Army, if you don't mind my asking?
Cheers.
-Luke

From shantanoo at gmail.com  Tue Jul 11 14:29:17 2006
From: shantanoo at gmail.com (Shantanoo Mahajan)
Date: Tue, 11 Jul 2006 17:59:17 +0530
Subject: [Tutor] printing 00
In-Reply-To: <20060711043423.92652.qmail@web51605.mail.yahoo.com>
References: <20060711043423.92652.qmail@web51605.mail.yahoo.com>
Message-ID: <20060711122917.GA1865@madhosh.dhoomketu.net.in>

+++ Christopher Spears [10-07-06 21:34 -0700]:
| I'm working on a problem from "How To Think Like A
| Computer Scientist".  I created  a Time class:
| 
| class Time:
| 	
| 	def __init__(self, hours, minutes, seconds):
| 		self.hours = hours
| 		self.minutes = minutes
| 		self.seconds = seconds
| 
| I created a function to print the Time object:
| 
| def printTime(time):
| 	print "%d:%d:%d" % (time.hours, time.minutes,
| time.seconds)
| 		
| However, when I type '00', I get the following:
| >>> time = Time(12,34.4,00)
| >>> printTime(time)
| 12:34:0
| >>> time.seconds
| 0

instead of %d you may use %02d.

Shantanoo
-- 
It's not what you look at that matters, it's what you see.  ~Henry David
Thoreau

From arcege at gmail.com  Tue Jul 11 16:24:13 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Tue, 11 Jul 2006 10:24:13 -0400
Subject: [Tutor] How can I copy files recursively?
In-Reply-To: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
Message-ID: <7e5ba9220607110724v6ee7c229w331d70697cbe25db@mail.gmail.com>

On 7/10/06, Richard Querin <rfquerin at gmail.com> wrote:
>
> I know this is probably a dumb question:
>
> I've got mp3 files that are downloaded (by ipodder) into individual
> subfolders. I'd like to write a quick script to move (not copy) all the mp3
> files in those folders into a single destination folder. I was thinking I
> could do it easily from the linux command line (cp -r copies the subfolders
> out as well) but I can't figure out how to do it. Is there an easy way to
> achieve this using Python? I am assuming this would be something Python was
> designed to make easy..
>
>
Python makes things easy, from a certain point of view.  You have to think
that Python is a program language and not a command language (like Bourne
shell).

Others have a number of solutions that will move your files with os.walk and
os.path.walk.  They are nice, but sometimes it's better to traverse the tree
individually.  Also, you didn't specify if the destination "folder"
structure already existed, or if it will need to be created (which cp -r
will do).  The following should handle that case for you:

import fnmatch, os
def movetree(srcdir, dstdir, pattern=None):
    # dstdir must exist first
    srcnames = os.listdir(srcdir)
    for name in srcnames:
        srcfname = os.path.join(srcdir, name)
        dstfname = os.path.join(dstdir, name)
        if os.path.isdir(srcfname):
            os.mkdir(dstfname, 00)
            movetree(srcfname, dstfname)
        elif pattern is None or fnmatch.fnmatch(name, pattern):
            os.rename(srcfname, dstfname)

>
You could do the same with os.walk or os.path.walk, but the recursive nature
of the function takes care of itself a bit better, IMO.

  -Arcege
-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060711/eb4e8fb4/attachment.html 

From gsf at panix.com  Tue Jul 11 20:48:33 2006
From: gsf at panix.com (Gabriel Farrell)
Date: Tue, 11 Jul 2006 14:48:33 -0400
Subject: [Tutor] tempfile and passing files around
Message-ID: <20060711184833.GD26881@panix.com>

I have an issue with the tempfile module that I can't figure out.

Snippet of relevant script looks like so:

1   bob = tempfile.NamedTemporaryFile()
2   bob.write('Hallo!')
3   bob.read()
4   sam = tempfile.NamedTemporaryFile()
5   bobHandle = file(bob.name)
6   bobHandle.read()

As you can see, I'm creating two NamedTemporaryFiles and then reading
from the first.  Line 3 doesn't really do anything, there's no output
because we're reading at the end of the file, but as long as I leave
it in, line 6 will output the expected 'Hallo!'.  If I remove it,
there's no output from line 6.

I really stumbled upon this, and it looks like, if you create a
tempfile and write to it, then create another tempfile, you can only
open up the first to read it again if you do a read method on the
first file before you open it.  I dunno, just kinda baffled.

TIA, gabe

From kent37 at tds.net  Tue Jul 11 21:04:02 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 11 Jul 2006 15:04:02 -0400
Subject: [Tutor] tempfile and passing files around
In-Reply-To: <20060711184833.GD26881@panix.com>
References: <20060711184833.GD26881@panix.com>
Message-ID: <44B3F622.4070807@tds.net>

Gabriel Farrell wrote:
> I have an issue with the tempfile module that I can't figure out.
>
> Snippet of relevant script looks like so:
>
> 1   bob = tempfile.NamedTemporaryFile()
> 2   bob.write('Hallo!')
> 3   bob.read()
> 4   sam = tempfile.NamedTemporaryFile()
> 5   bobHandle = file(bob.name)
> 6   bobHandle.read()
>
> As you can see, I'm creating two NamedTemporaryFiles and then reading
> from the first.  Line 3 doesn't really do anything, there's no output
> because we're reading at the end of the file, but as long as I leave
> it in, line 6 will output the expected 'Hallo!'.  If I remove it,
> there's no output from line 6.
>   
Try bob.flush() instead of bob.read(), my guess is the read() is forcing 
a flush().

Kent



From monashee88 at shaw.ca  Tue Jul 11 21:13:08 2006
From: monashee88 at shaw.ca (John or Margaret Montgomery)
Date: Tue, 11 Jul 2006 12:13:08 -0700
Subject: [Tutor] Need Help
In-Reply-To: <44B38E63.5090202@gmail.com>
References: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
	<44B38E63.5090202@gmail.com>
Message-ID: <20060711121308.f14477ca.monashee88@shaw.ca>

On Tue, 11 Jul 2006 06:41:23 -0500
Luke Paireepinart <rabidpoobear at gmail.com> wrote:

> Hi.
> Shappell, John J CW2 wrote:
> >
> > Here is the assignment
> >
> [snip assignment]
> Please don't ask about homework in the future.  Did your professor tell 
> you to submit queries to this list?  If so, could you ask him not to? 
> it's against the policies of the tutor mailing list to give homework 
> help.  However, I can give you a few hints about python in general.  The 
> rules may be different but my impression was that there was no homework 
> to be submitted here.  If I'm wrong please correct me.
> >

Perhaps I am wrong, Luke but my impression was that this request was fine. He openly stated it was homework and he did considerable work on it before getting stuck. Also he specifically did not ask for a solution but wished to be nudged in the right direction.

I am sorry that I do not have the knowledge to help but perhaps your tip did the trick.

Perhaps Danny or Kent would clarify this situation.

John Montgomery

From gsf at panix.com  Tue Jul 11 21:24:44 2006
From: gsf at panix.com (Gabriel Farrell)
Date: Tue, 11 Jul 2006 15:24:44 -0400
Subject: [Tutor] tempfile and passing files around
In-Reply-To: <44B3F622.4070807@tds.net>
References: <20060711184833.GD26881@panix.com> <44B3F622.4070807@tds.net>
Message-ID: <20060711192444.GE26881@panix.com>

On Tue, Jul 11, 2006 at 03:04:02PM -0400, Kent Johnson wrote:
> Try bob.flush() instead of bob.read(), my guess is the read() is forcing 
> a flush().

That works!  Thanks, Kent.  If I understand flush (looking at [1]), I
got no output because the data for the stream wasn't written to the
file before I tried to read it.  Is that right?

[1] http://www.opengroup.org/pubs/online/7908799/xsh/fflush.html

From kent37 at tds.net  Tue Jul 11 21:43:55 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 11 Jul 2006 15:43:55 -0400
Subject: [Tutor] tempfile and passing files around
In-Reply-To: <20060711192444.GE26881@panix.com>
References: <20060711184833.GD26881@panix.com> <44B3F622.4070807@tds.net>
	<20060711192444.GE26881@panix.com>
Message-ID: <44B3FF7B.7090904@tds.net>

Gabriel Farrell wrote:
> On Tue, Jul 11, 2006 at 03:04:02PM -0400, Kent Johnson wrote:
>   
>> Try bob.flush() instead of bob.read(), my guess is the read() is forcing 
>> a flush().
>>     
>
> That works!  Thanks, Kent.  If I understand flush (looking at [1]), I
> got no output because the data for the stream wasn't written to the
> file before I tried to read it.  Is that right?

Yes, that's right.

Kent


From kent37 at tds.net  Tue Jul 11 21:48:13 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 11 Jul 2006 15:48:13 -0400
Subject: [Tutor] Need Help
In-Reply-To: <20060711121308.f14477ca.monashee88@shaw.ca>
References: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>	<44B38E63.5090202@gmail.com>
	<20060711121308.f14477ca.monashee88@shaw.ca>
Message-ID: <44B4007D.3090308@tds.net>

John or Margaret Montgomery wrote:
> On Tue, 11 Jul 2006 06:41:23 -0500
> Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
>   
>> Hi.
>> Shappell, John J CW2 wrote:
>>     
>>> Here is the assignment
>>>
>>>       
>> [snip assignment]
>> Please don't ask about homework in the future.  Did your professor tell 
>> you to submit queries to this list?  If so, could you ask him not to? 
>> it's against the policies of the tutor mailing list to give homework 
>> help.  However, I can give you a few hints about python in general.  The 
>> rules may be different but my impression was that there was no homework 
>> to be submitted here.  If I'm wrong please correct me.
>>     
>
> Perhaps I am wrong, Luke but my impression was that this request was fine. He openly stated it was homework and he did considerable work on it before getting stuck. Also he specifically did not ask for a solution but wished to be nudged in the right direction.
>
> I am sorry that I do not have the knowledge to help but perhaps your tip did the trick.
>
> Perhaps Danny or Kent would clarify this situation.

By posting the entire homework problem, John Shappell did give the 
impression that he wanted us to do the problem for him, but as John 
Montgomery notes he is just looking for a hint in an area where he is 
stuck. That is fine for the tutor list. Since we know it is homework we 
can use a light touch and avoid giving the entire solution.

Kent


From bugracakir at gmail.com  Tue Jul 11 21:55:23 2006
From: bugracakir at gmail.com (Bugra Cakir)
Date: Tue, 11 Jul 2006 22:55:23 +0300
Subject: [Tutor] Help IDLE Compile Problem
Message-ID: <5a00f6240607111255i3fa3ea3el76b8491106404c0a@mail.gmail.com>

Hi,

I have two Python source files within editing them via IDLE.
I have a problem. The second file is used by the first file. Some parts
i mean from the second file is used. But when i change the contents of the
second file and while i'm running the first file with F5, change doesnt
reflect
to the runtime. If i close two IDLE windows and delete .pyc of the second
file
then it is ok. What is the problem ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060711/c5721279/attachment.html 

From alan.gauld at freenet.co.uk  Tue Jul 11 22:03:13 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 11 Jul 2006 21:03:13 +0100
Subject: [Tutor] How can I copy files recursively?
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
Message-ID: <003301c6a525$0a9fb6d0$0201a8c0@XPpro>

> subfolders. I'd like to write a quick script to move (not copy) all 
> the mp3
> files in those folders into a single destination folder. I was 
> thinking I
> could do it easily from the linux command line (cp -r copies the 
> subfolders
> out as well) but I can't figure out how to do it. Is there an easy 
> way to
> achieve this using Python? I am assuming this would be something 
> Python was
> designed to make easy..

Things which are easy in the shell are usually less easy in Python.
In your case a simple cp -r will copy the files and an rm -rf will
delete the originals.

Or you could just use mv on the top level folder.

However the OS topic in my tutor provides all the bits you need
to write a python script if you really need to.

Alan G. 



From rfquerin at gmail.com  Tue Jul 11 22:14:34 2006
From: rfquerin at gmail.com (Richard Querin)
Date: Tue, 11 Jul 2006 16:14:34 -0400
Subject: [Tutor] How can I copy files recursively?
In-Reply-To: <003301c6a525$0a9fb6d0$0201a8c0@XPpro>
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
	<003301c6a525$0a9fb6d0$0201a8c0@XPpro>
Message-ID: <7d81675b0607111314j4171f0cdoadc015a536a5906c@mail.gmail.com>

On 7/11/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
>
> Things which are easy in the shell are usually less easy in Python.
> In your case a simple cp -r will copy the files and an rm -rf will
> delete the originals.
>
> Or you could just use mv on the top level folder.
>
>
>
But I don't want the sub folders to come along with the copy. I'd like to
grab the mp3 files out of a set of subfolders and place them all into a
single folder somewhere else.

I'm completely lost when it comes to bash scripting, so I may take Michael
P. Reilly's suggestion as a starting point since it's the only one I
understand at first glance ;).

I'm really a newbie to python programming so readability and understanding
it is first on my list. Efficiency and speed is secondary to me at the
moment.

Thanks to all for the help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060711/e499270e/attachment.html 

From alan.gauld at freenet.co.uk  Tue Jul 11 22:15:42 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 11 Jul 2006 21:15:42 +0100
Subject: [Tutor] Need Help
References: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
	<44B38E63.5090202@gmail.com>
Message-ID: <005901c6a526$c91896d0$0201a8c0@XPpro>

> [snip assignment]
> Please don't ask about homework in the future.  Did your professor 
> tell you to submit queries to this list?  If so, could you ask him 
> not to? it's against the policies of the tutor mailing list to give 
> homework help.

Thats a bit extreme. We don't mind giving help on specific queries
where an attempt has been made to do the work.
We will rarely give a direct answer but might ask questions or
make suggestions to lead you towards the answer.

What we will not do is accept a simple query saying, in effect,
"here is the assignment, how do I do it?"

>> This is where I am at so far.  I don't understand how to get the 
>> Account class into the program. Can you help a little,  Just 
>> looking for an idea or some guidance

Do you understand the difference between classes and objects?
Do you understand how to create an object, as opposed to a class?
Do you know how to call the methods of an object once created?

If not find almost any Python tutorial. They all answer those 
questions.

>> class Account:
>>      def __init__(self, initial):
>>          self.balance = initial
>>      def deposit(self, amt):
>>          self.balance = self.balance + amt
>>      def withdraw(self,amt):
>>          self.balance = self.balance - amt
>>      def getbalance(self):
>>          return self.balance
>>
> What you have there is a class, not an instance of a class.  read 
> more about the difference at 
> http://www.python.org/doc/2.2.3/tut/node11.html
> or some other tutorial site.

Seconded.

> Also, make it clear to your instructor that you had trouble here. 
> If he doesn't know what's hanging people up he won't be able to help 
> you with it.

But I think Luke is being a wee bit hard here, you clearly have
tried to solve it, you just need some direction. I'd say that was
within the tutor list rules.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From bgailer at alum.rpi.edu  Tue Jul 11 22:18:04 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 11 Jul 2006 13:18:04 -0700
Subject: [Tutor] Help IDLE Compile Problem
In-Reply-To: <5a00f6240607111255i3fa3ea3el76b8491106404c0a@mail.gmail.com>
References: <5a00f6240607111255i3fa3ea3el76b8491106404c0a@mail.gmail.com>
Message-ID: <44B4077C.7050700@alum.rpi.edu>

Bugra Cakir wrote:
> Hi,
>
> I have two Python source files within editing them via IDLE.
> I have a problem. The second file is used by the first file. Some parts
> i mean from the second file is used. But when i change the contents of 
> the
> second file and while i'm running the first file with F5, change 
> doesnt reflect
> to the runtime. If i close two IDLE windows and delete .pyc of the 
> second file
> then it is ok. What is the problem ?
Your question is hard to address because we don't know what you mean by 
"The second file is used by the first file". I will assume you are 
importing it. Import runs the imported module once. Subsequent 
executions of import do NOT rerun the module. Therefore any changes you 
make to it are not showing up. To work around this "problem", after 
importing, use the reload function:
import foo
reload(foo)

-- 
Bob Gailer
510-978-4454


From dyoo at hkn.eecs.berkeley.edu  Tue Jul 11 22:25:30 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 11 Jul 2006 13:25:30 -0700 (PDT)
Subject: [Tutor] Need Help
In-Reply-To: <44B4007D.3090308@tds.net>
References: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
	<44B38E63.5090202@gmail.com>
	<20060711121308.f14477ca.monashee88@shaw.ca>
	<44B4007D.3090308@tds.net>
Message-ID: <Pine.LNX.4.64.0607111310270.12835@hkn.eecs.berkeley.edu>

> By posting the entire homework problem, John Shappell did give the 
> impression that he wanted us to do the problem for him, but as John 
> Montgomery notes he is just looking for a hint in an area where he is 
> stuck. That is fine for the tutor list. Since we know it is homework we 
> can use a light touch and avoid giving the entire solution.


The idea is to try attacking the core of the problem the questioner has. 
In that sense, I try not to look at the details of the homework problem.


As a concrete example, if someone comes up and says:

     I don't know how to get my name-asking program to stop when the user
     enters "quit".  Help!


I'll translate this to:

     1.  I might not know how to use boolean conditionals.

     2.  I might not know how to use loops.

     3.  I might not know how to use these two things together.

     4.  I don't understand the question I'm being asked, or why
         this is useful.


That is, I'd ignore the surface details about asking about string 
comparison, but concentrate on figuring out which of these things the 
questioner is confused with.  Or there may be something that hasn't been 
accounted for... The questions we ask from then on are meant to probe.

It would be very cruel to not address the core reason why the student's 
struggling.  That's why we don't "answer" homework questions: it doesn't 
address what's often a much bigger problem with the student's concepts of 
programming.

From alan.gauld at freenet.co.uk  Tue Jul 11 22:34:37 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 11 Jul 2006 21:34:37 +0100
Subject: [Tutor] How can I copy files recursively?
References: <7d81675b0607102050o2bf39651h59cf142edab811f0@mail.gmail.com>
	<003301c6a525$0a9fb6d0$0201a8c0@XPpro>
	<7d81675b0607111314j4171f0cdoadc015a536a5906c@mail.gmail.com>
Message-ID: <007f01c6a529$6d7f2890$0201a8c0@XPpro>

>> Or you could just use mv on the top level folder.
>>
> But I don't want the sub folders to come along with the copy. I'd 
> like to
> grab the mp3 files out of a set of subfolders and place them all 
> into a
> single folder somewhere else.

Ah, sorry, I misunderstood the question.

In that case os.walk and shutil.copy provide a fairly easy solution.
Take a look at the findfile() function in the OS tutor topic.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From jeffpeery at yahoo.com  Tue Jul 11 23:53:42 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Tue, 11 Jul 2006 14:53:42 -0700 (PDT)
Subject: [Tutor] modbus communication with python?
In-Reply-To: <7e3eab2c0607051205l24fab97ak54aa857a567743bd@mail.gmail.com>
Message-ID: <20060711215342.86435.qmail@web30515.mail.mud.yahoo.com>

okay, yes thank you! I have seen this, although I looked a the code and it appears that this is actually a modbus server (please correct me if I am wrong, I am really new to modbus and PLC's). We are already using a modbus server (KEPDirect for PLC's, automation direct) and I beleive we are using a Koyo PLC. but I simply want to read and write values stored on the modbus server, I don't actually want to create a new server. I'm not sure that this module is the way to go (although again I might be wrong), what might be my other options and where should I go to learn about this? thanks!

Jeff

Jason Massey <jason.massey at gmail.com> wrote: Googling for modbus python turned up:

https://lintouch.org/repos/lintouch/lsp-modbus/trunk/tests/



 On 7/5/06, Jeff Peery <jeffpeery at yahoo.com> wrote: Hello, I need to talk read write to a modbus so that I can work with a PLC. I have not a clue how this all works. does python have a modbus module or where might I look to find how to do this? thanks. 

Jeff

    

---------------------------------
How low will we go? Check out Yahoo! Messenger's low   PC-to-Phone call rates. 


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




 

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1&cent;/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060711/0d1b3186/attachment.html 

From arcege at gmail.com  Wed Jul 12 00:34:29 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Tue, 11 Jul 2006 18:34:29 -0400
Subject: [Tutor] Need Help
In-Reply-To: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
References: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
Message-ID: <7e5ba9220607111534m6e6c5303hdd980e68cb961108@mail.gmail.com>

On 7/10/06, Shappell, John J CW2 <john.j.shappelljr at us.army.mil> wrote:
>
>  Here is the assignment
>
>    1. You've been given an assignment by your supervisor to program a
>       small application to monitor the current status of the cash account in the
>       firm's petty cash fund (the amount of cash kept on hand in the office for
>       incidental purchases). The requirements for the program are to allow users
>       to input the amount of cash deposited, the amount of cash withdrawn and to
>       get a report of the balance at any given time. You will need to also add the
>       date of each deposit and the date of each withdrawal and provide a date with
>       the balance returned upon a given query. The program should be able to
>       provide a printed report and support a command line query.
>
>       You are to use the object oriented properties of Python to
>       accomplish this task.
>
> This is where I am at so far.  I don't understand how to get the Account
> class into the program. Can you help a little,  Just looking for an idea or
> some guidance
>
> #!/usr/bin/python
> # Filename: petty cash.py
>
> print "Welcome to the petty cash account"
> print "Did you deposit or withdrawl money today"
> print
>
> # print out menu
> print "please select a number"
> print "1 for deposit"
> print "2 for withdrawl"
>
> # Get user's choice:
> number = input (">")
> #
> if number == 1:
>     deposit = input ("how much?")
>     print "I deposited:", deposit
>
> elif number == 2:
>     withdrawl = input ("How Much?")
>     print "I withdrew:", withdrawl
>
> print "what is today's date?"
> # Get date from user
> date = input (">")
>
> *This is where I get stuck. The program will allow me to input the deposit
> or withdrawl ammount and the date but does nothing ownce it gets here*
>
> class Account:
>      def __init__(self, initial):
>          self.balance = initial
>      def deposit(self, amt):
>          self.balance = self.balance + amt
>      def withdraw(self,amt):
>          self.balance = self.balance - amt
>      def getbalance(self):
>          return self.balance
>
John,
  Another aspect of your assignment will be to be able to use this
functionality from the "command-line".  This means: without asking questions
from the user, but input is being passed as arguments.  You will eventually
have to think how this will affect the structure of your program.
  -Arcege
-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060711/41929b17/attachment.htm 

From kent37 at tds.net  Wed Jul 12 00:42:21 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 11 Jul 2006 18:42:21 -0400
Subject: [Tutor] Need Help
In-Reply-To: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
References: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>
Message-ID: <44B4294D.9060306@tds.net>

Shappell, John J CW2 wrote:
>
> Here is the assignment
>
>          1. You've been given an assignment by your supervisor to
>             program a small application to monitor the current status
>             of the cash account in the firm's petty cash fund (the
>             amount of cash kept on hand in the office for incidental
>             purchases). The requirements for the program are to allow
>             users to input the amount of cash deposited, the amount of
>             cash withdrawn and to get a report of the balance at any
>             given time. You will need to also add the date of each
>             deposit and the date of each withdrawal and provide a date
>             with the balance returned upon a given query. The program
>             should be able to provide a printed report and support a
>             command line query.
>
>             You are to use the object oriented properties of Python to
>             accomplish this task.
>
> This is where I am at so far.  I don't understand how to get the 
> Account class into the program. Can you help a little,  Just looking 
> for an idea or some guidance
>
> #!/usr/bin/python
> # Filename: petty cash.py
>
> print "Welcome to the petty cash account"
> print "Did you deposit or withdrawl money today"
> print
>
> # print out menu
> print "please select a number"
> print "1 for deposit"
> print "2 for withdrawl"
>
> # Get user's choice:
> number = input (">")
> #
> if number == 1:
>     deposit = input ("how much?")
>     print "I deposited:", deposit
>    
> elif number == 2:
>     withdrawl = input ("How Much?")
>     print "I withdrew:", withdrawl
>    
> print "what is today's date?"
> # Get date from user
> date = input (">")
>
> *This is where I get stuck. The program will allow me to input the 
> deposit or withdrawl ammount and the date but does nothing ownce it 
> gets here*
>
> class Account:
>      def __init__(self, initial):
>          self.balance = initial
>      def deposit(self, amt):
>          self.balance = self.balance + amt
>      def withdraw(self,amt):
>          self.balance = self.balance - amt
>      def getbalance(self):
>          return self.balance
>

Hi John,

You need to create an instance of Account and post the transactions to 
it by calling instance methods on the account. The Account class may 
need to keep track of the individual postings as well as the total balance.

There is a lot to the assignment - is this one of your first assignments 
or a later one? Without a bit of context of where you are in the course 
it's hard to know what is expected. It sounds like you may need some 
kind of persistent storage like a database but I don't know if you have 
learned anything about that yet.

Kent


From cspears2002 at yahoo.com  Wed Jul 12 01:08:36 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Tue, 11 Jul 2006 16:08:36 -0700 (PDT)
Subject: [Tutor] no loops
Message-ID: <20060711230836.56159.qmail@web51615.mail.yahoo.com>

I am working on another problem from "How To Think
Like A Computer Scientist".  Here is a function:

def increment(time, seconds):
  time.seconds = time.seconds + seconds

  while time.seconds >= 60:
    time.seconds = time.seconds - 60
    time.minutes = time.minutes + 1

  while time.minutes >= 60:
    time.minutes = time.minutes - 60
    time.hours = time.hours + 1 

Here is the function in action:

>>> from time import *
>>> atime = Time()
>>> atime.hours = 1
>>> atime.minutes = 60
>>> atime.seconds = 120
>>> printTime(atime)
1:60:120
>>> increment(atime,1)
>>> printTime(atime)
2:2:1

Now the exercise is:
As an exercise, rewrite this function so that it
doesn't contain any loops.

I have been staring at this function and drawing a
blank.  Something tells me that I need to use
iteration, but I am not sure how I could implement it.

-Chris


From glingl at aon.at  Wed Jul 12 01:13:58 2006
From: glingl at aon.at (Gregor Lingl)
Date: Wed, 12 Jul 2006 01:13:58 +0200
Subject: [Tutor] no loops
In-Reply-To: <20060711230836.56159.qmail@web51615.mail.yahoo.com>
References: <20060711230836.56159.qmail@web51615.mail.yahoo.com>
Message-ID: <44B430B6.1080406@aon.at>

Christopher Spears schrieb:

IF you know that it's 20000 seconds after midnight,
how many hours, minutes, seconds after midnight ist this.

If you should compute this by hand, how would you proceed?

Best wishes,
Gregor

> I am working on another problem from "How To Think
> Like A Computer Scientist".  Here is a function:
>
> def increment(time, seconds):
>   time.seconds = time.seconds + seconds
>
>   while time.seconds >= 60:
>     time.seconds = time.seconds - 60
>     time.minutes = time.minutes + 1
>
>   while time.minutes >= 60:
>     time.minutes = time.minutes - 60
>     time.hours = time.hours + 1 
>
> Here is the function in action:
>
>   
>>>> from time import *
>>>> atime = Time()
>>>> atime.hours = 1
>>>> atime.minutes = 60
>>>> atime.seconds = 120
>>>> printTime(atime)
>>>>         
> 1:60:120
>   
>>>> increment(atime,1)
>>>> printTime(atime)
>>>>         
> 2:2:1
>
> Now the exercise is:
> As an exercise, rewrite this function so that it
> doesn't contain any loops.
>
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.
>
> -Chris
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   


From john at fouhy.net  Wed Jul 12 01:23:19 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 12 Jul 2006 11:23:19 +1200
Subject: [Tutor] no loops
In-Reply-To: <20060711230836.56159.qmail@web51615.mail.yahoo.com>
References: <20060711230836.56159.qmail@web51615.mail.yahoo.com>
Message-ID: <5e58f2e40607111623h762a14d8j66d0a8c959e9167f@mail.gmail.com>

On 12/07/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
> Now the exercise is:
> As an exercise, rewrite this function so that it
> doesn't contain any loops.
>
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.

Hi Chris,

You are using iteration.  That's what loops are :-)

Perhaps you meant to say "recursion", which is where a function calls
itself.  You could solve this recursively, but I think Gregor's
comment is closer to what they want you to do.

-- 
John.

From carroll at tjc.com  Wed Jul 12 02:59:18 2006
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 11 Jul 2006 17:59:18 -0700 (PDT)
Subject: [Tutor] Need Help
In-Reply-To: <7e5ba9220607111534m6e6c5303hdd980e68cb961108@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0607111756500.17983-100000@violet.rahul.net>

On Tue, 11 Jul 2006, Michael P. Reilly wrote:

>   Another aspect of your assignment will be to be able to use this
> functionality from the "command-line".  This means: without asking questions
> from the user, but input is being passed as arguments.  

John should get clarification from his instructor, but I did not read it 
that way.  I read that requirement to "support a command line query" as 
meaning the program should prompt the user to enter a query command; as 
opposed to hard-coding the transactions in the coe itself (as is sometimes 
done at an intro level).



From magoldfish at gmail.com  Wed Jul 12 03:20:25 2006
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Tue, 11 Jul 2006 21:20:25 -0400
Subject: [Tutor] quickie: a better dynamic dictionary update?
Message-ID: <5e183f3d0607111820x6d4e57ech2b72c6484df78d2@mail.gmail.com>

Hi,

I need to keep an updated dictionary of pictures in my application.  I have
a function which takes snapshots of the current pictures available.  Some of
the pictures in my dictionary have been deleted, so their dict entry needs
to be removed.  Here is a snippet of very ugly code I have which works.  I'm
looking for quick suggestions for a better implementation-- all nice replies
welcomed!

Thanks,
Marcus

-- code snippet

# 1st, find the 'stale' items in our dictionary to delete
# lstKeepers is a list of current pictures
# Note: if I try to iterate over the keys of the dict and
# remove-as-I-go, I get an exception (dict size changed
# during iteration)
lstRemove = []
for key in myDict:
   if key not in lstKeepers:
       lstRemove.append(key)

# 2nd, remove them
for oldKey in lstRemove:
   del myDict[oldKey]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060711/20816b5d/attachment.htm 

From marc_a_poulin at yahoo.com  Wed Jul 12 03:42:16 2006
From: marc_a_poulin at yahoo.com (Marc Poulin)
Date: Tue, 11 Jul 2006 18:42:16 -0700 (PDT)
Subject: [Tutor] no loops
In-Reply-To: <5e58f2e40607111623h762a14d8j66d0a8c959e9167f@mail.gmail.com>
Message-ID: <20060712014216.40145.qmail@web34105.mail.mud.yahoo.com>


--- John Fouhy <john at fouhy.net> wrote:

> On 12/07/06, Christopher Spears
> <cspears2002 at yahoo.com> wrote:
> > Now the exercise is:
> > As an exercise, rewrite this function so that it
> > doesn't contain any loops.
> >
> > I have been staring at this function and drawing a
> > blank.  Something tells me that I need to use
> > iteration, but I am not sure how I could implement
> it.
> 
> Hi Chris,
> 
> You are using iteration.  That's what loops are :-)
> 
> Perhaps you meant to say "recursion", which is where
> a function calls
> itself.  You could solve this recursively, but I
> think Gregor's
> comment is closer to what they want you to do.
> 
> -- 
> John.

I agree with Gregor and John. What makes the problem
difficult is the fact that time is represented using 3
different units of measure: hours, minutes, and
seconds. The math becomes much simpler if you convert
the time value to a single unit (such as seconds).

But it doesn't have to be seconds. I recall seeing one
 database that stores time as fractional hours where a
minute is worth 1/60 of an hour and a second is worth
1/3600 of an hour. 

In other words, 1:15 is stored as 1.25 hours, 4:30 is
stored as 4.5 hours, and so forth. Converting from
(hours, minutes, seconds) to fractional hours is
pretty easy, but going the other way is not so simple.




__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From marc_a_poulin at yahoo.com  Wed Jul 12 03:45:55 2006
From: marc_a_poulin at yahoo.com (Marc Poulin)
Date: Tue, 11 Jul 2006 18:45:55 -0700 (PDT)
Subject: [Tutor] Need Help
In-Reply-To: <Pine.LNX.4.44.0607111756500.17983-100000@violet.rahul.net>
Message-ID: <20060712014555.18256.qmail@web34109.mail.mud.yahoo.com>


--- Terry Carroll <carroll at tjc.com> wrote:

> On Tue, 11 Jul 2006, Michael P. Reilly wrote:
> 
> >   Another aspect of your assignment will be to be
> able to use this
> > functionality from the "command-line".  This
> means: without asking questions
> > from the user, but input is being passed as
> arguments.  
> 
> John should get clarification from his instructor,
> but I did not read it 
> that way.  I read that requirement to "support a
> command line query" as 
> meaning the program should prompt the user to enter
> a query command; as 
> opposed to hard-coding the transactions in the coe
> itself (as is sometimes 
> done at an intro level).
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

This may be the most important lesson to learn from
this exercise: even experienced programmers can (and
do) interpret requirements differently. When in doubt,
ask!



__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From carroll at tjc.com  Wed Jul 12 03:47:11 2006
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 11 Jul 2006 18:47:11 -0700 (PDT)
Subject: [Tutor] quickie: a better dynamic dictionary update?
In-Reply-To: <5e183f3d0607111820x6d4e57ech2b72c6484df78d2@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0607111843210.17983-100000@violet.rahul.net>

On Tue, 11 Jul 2006, Marcus Goldfish wrote:

> # 1st, find the 'stale' items in our dictionary to delete
> # lstKeepers is a list of current pictures
> # Note: if I try to iterate over the keys of the dict and
> # remove-as-I-go, I get an exception (dict size changed
> # during iteration)
> lstRemove = []
> for key in myDict:
>    if key not in lstKeepers:
>        lstRemove.append(key)
> 
> # 2nd, remove them
> for oldKey in lstRemove:
>    del myDict[oldKey]


lstDeleters = [key for key in myDict.keys() if key not in lstKeepers]
for key in lstDeleters:
    del myDict[key]

It's still a two-passer, but I don't see straightforward any way around
that, if you want to update the dictionary (as opposed to making a new
dictionary with the result, which could probably be done with an
excessively clever list comprehension).


From carroll at tjc.com  Wed Jul 12 03:57:26 2006
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 11 Jul 2006 18:57:26 -0700 (PDT)
Subject: [Tutor] quickie: a better dynamic dictionary update?
In-Reply-To: <Pine.LNX.4.44.0607111843210.17983-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0607111855350.17983-100000@violet.rahul.net>

On Tue, 11 Jul 2006, Terry Carroll wrote:

> On Tue, 11 Jul 2006, Marcus Goldfish wrote:
> 
> > # 1st, find the 'stale' items in our dictionary to delete
> > # lstKeepers is a list of current pictures
> > # Note: if I try to iterate over the keys of the dict and
> > # remove-as-I-go, I get an exception (dict size changed
> > # during iteration)
> > lstRemove = []
> > for key in myDict:
> >    if key not in lstKeepers:
> >        lstRemove.append(key)
> > 
> > # 2nd, remove them
> > for oldKey in lstRemove:
> >    del myDict[oldKey]
> 
> [snip code]
> It's still a two-passer, but I don't see straightforward any way around
> that, if you want to update the dictionary (as opposed to making a new
> dictionary with the result, which could probably be done with an
> excessively clever list comprehension).

Actually, it turns out not to be excessively clever at all (if I could do
it):

myDict = dict([(key, myDict[key]) for key in myDict.keys()
               if key in lstKeepers])

I'm not sure it's any nicer looking, though, than my first suggestion 
(although my first suggestion is probably a little slower).



From bgailer at alum.rpi.edu  Wed Jul 12 03:53:03 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 11 Jul 2006 18:53:03 -0700
Subject: [Tutor] no loops
In-Reply-To: <20060711230836.56159.qmail@web51615.mail.yahoo.com>
References: <20060711230836.56159.qmail@web51615.mail.yahoo.com>
Message-ID: <44B455FF.4000000@alum.rpi.edu>

Christopher Spears wrote:
> I am working on another problem from "How To Think
> Like A Computer Scientist".  Here is a function:
>
> def increment(time, seconds):
>   time.seconds = time.seconds + seconds
>
>   while time.seconds >= 60:
>     time.seconds = time.seconds - 60
>     time.minutes = time.minutes + 1
>
>   while time.minutes >= 60:
>     time.minutes = time.minutes - 60
>     time.hours = time.hours + 1 
>
> Here is the function in action:
>
>   
>>>> from time import *
>>>> atime = Time()
>>>> atime.hours = 1
>>>> atime.minutes = 60
>>>> atime.seconds = 120
>>>> printTime(atime)
>>>>         
> 1:60:120
>   
>>>> increment(atime,1)
>>>> printTime(atime)
>>>>         
> 2:2:1
>
> Now the exercise is:
> As an exercise, rewrite this function so that it
> doesn't contain any loops.
>
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.
>   
take a look at the divmod built-in function.
>   


-- 
Bob Gailer
510-978-4454


From john at fouhy.net  Wed Jul 12 04:03:51 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 12 Jul 2006 14:03:51 +1200
Subject: [Tutor] quickie: a better dynamic dictionary update?
In-Reply-To: <5e183f3d0607111820x6d4e57ech2b72c6484df78d2@mail.gmail.com>
References: <5e183f3d0607111820x6d4e57ech2b72c6484df78d2@mail.gmail.com>
Message-ID: <5e58f2e40607111903u2d2b1169ic3d06fe04fa4e757@mail.gmail.com>

On 12/07/06, Marcus Goldfish <magoldfish at gmail.com> wrote:
> # 1st, find the 'stale' items in our dictionary to delete
> # lstKeepers is a list of current pictures
> # Note: if I try to iterate over the keys of the dict and
> # remove-as-I-go, I get an exception (dict size changed
> # during iteration)

Try this:

for key in myDict.keys():
  if key not in lstKeepers:
    del myDict[key]

The difference here is that myDict.keys() creates a list containing
the keys of myDict at the start of the loop, and then iterates over
the list.

If lstKeepers is big, it might be more efficient to make it into a set first ---

keepSet = set(lstKeepers)
for key in myDict.keys():
  if key not in keepSet:
    del myDict[key]

-- 
John.

From gwhjr at cox.net  Wed Jul 12 04:57:54 2006
From: gwhjr at cox.net (Grady Henry)
Date: Tue, 11 Jul 2006 19:57:54 -0700
Subject: [Tutor] How do I get my machine to run an SMTP server?
Message-ID: <001a01c6a55e$f8d07e00$8b4a6244@valued61da873e>

This is a program that I wrote using the third example at 12.2.13 Examples at python.org.

#!/usr/bin/env python

"""Send the contents of a directory as a MIME message.

Usage: dirmail [options] from to [to ...]*

Options:
    -h / --help
        Print this message and exit.

    -d directory
    --directory=directory
        Mail the contents of the specified directory, otherwise use the
        current directory.  Only the regular files in the directory are sent,
        and we don't recurse to subdirectories.

`from' is the email address of the sender of the message.

`to' is the email address of the recipient of the message, and multiple
recipients may be given.

The email is sent by forwarding to your local SMTP server, which then does the
normal delivery process.  Your local machine must be running an SMTP server.
"""

import sys
import os
import getopt
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from email import Encoders
from email.Message import Message
from email.MIMEAudio import MIMEAudio
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEImage import MIMEImage
from email.MIMEText import MIMEText

COMMASPACE = ', '


def usage(code, msg=''):
    print >> sys.stderr, __doc__
    if msg:
        print >> sys.stderr, msg
    sys.exit(code)


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'C:', ['help', 'directory='])
    except getopt.error, msg:
        usage(1, msg)

    dir = os.curdir
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('-d', '--directory'):
            dir = arg

    if len(args) < 2:
        usage(1)

    sender = args[0]
    recips = args[1:]

    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'Contents of directory %s' % os.path.abspath('C:\Documents and Settings\User\\My Documents')
    outer['To'] = COMMASPACE.join('gwhjr at bigfoot.com')
    outer['From'] = 'gwhjr at cox.net'
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
    # To guarantee the message ends with a newline
    outer.epilogue = ''

    for filename in os.listdir('C:\Documents and Settings\User'):
        path = os.path.join('C:\Documents and Settings\User', 'My Documents')
        if not os.path.isfile('C:\Documents and Settings\User'):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type('C:\Documents and Settings\User\\My Documents')
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        if maintype == 'text':
            fp = open('C:\Documents and Settings\User\\My Documents')
            # Note: we should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open('C:\Documents and Settings\User\\My Documents', 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open('C:\Documents and Settings\User\\My Documents', 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open('C:\Documents and Settings\User\\My Documents', 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            Encoders.encode_base64(msg)
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        outer.attach(msg)

    # Now send the message
    s = smtplib.SMTP()
    s.connect()
    __init__(self, host='', port=25, local_hostname=None)
    s.sendmail('gwhjr at cox.net', 'gwhjr at bigfoot.com', outer.as_string())
    s.close()


if __name__ == '__main__':
    main()

When I run the program using IDLE, I get the following:

Send the contents of a directory as a MIME message.

Usage: dirmail [options] from to [to ...]*

Options:
    -h / --help
        Print this message and exit.

    -d directory
    --directory=directory
        Mail the contents of the specified directory, otherwise use the
        current directory.  Only the regular files in the directory are sent,
        and we don't recurse to subdirectories.

`from' is the email address of the sender of the message.

`to' is the email address of the recipient of the message, and multiple
recipients may be given.

The email is sent by forwarding to your local SMTP server, which then does the
normal delivery process.  Your local machine must be running an SMTP server.

Traceback (most recent call last):
  File "C:\Documents and Settings\User\Desktop\EB2.py", line 125, in ?
    main()
  File "C:\Documents and Settings\User\Desktop\EB2.py", line 65, in main
    usage(1)
  File "C:\Documents and Settings\User\Desktop\EB2.py", line 48, in usage
    sys.exit(code)
SystemExit: 1

I guess that my first question is how do I get my machine to run an SMTP server?

Also, I'd like to say that I greatly appreciate all of the help that I've gotten in the past.

Grady Henry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060711/dbcf9e73/attachment-0001.htm 

From rabidpoobear at gmail.com  Wed Jul 12 05:24:21 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 11 Jul 2006 22:24:21 -0500
Subject: [Tutor] Need Help
In-Reply-To: <Pine.LNX.4.64.0607111310270.12835@hkn.eecs.berkeley.edu>
References: <C263EE2611C81E4993BA66EC7387096903F76C98@campb1aga006.campbell.army.mil>	<44B38E63.5090202@gmail.com>	<20060711121308.f14477ca.monashee88@shaw.ca>	<44B4007D.3090308@tds.net>
	<Pine.LNX.4.64.0607111310270.12835@hkn.eecs.berkeley.edu>
Message-ID: <44B46B65.2030101@gmail.com>

[snip]
> It would be very cruel to not address the core reason why the student's 
> struggling.  That's why we don't "answer" homework questions: it doesn't 
> address what's often a much bigger problem with the student's concepts of 
> programming.
Thank you for this explanation, Danny.  I thought there was a 
zero-tolerance policy on homework, not that we were supposed to give 
them more general help than a specific answer.
I agree my original choice of words was harsh.  It didn't sound that way 
to me when I wrote it, and I apologize to the OP.
It's also better that they tell us it's a homework problem than trying 
to mislead us, I reckon.
Anyway, does the Original Poster have any more questions or have we 
answered them all?
-Luke

From rabidpoobear at gmail.com  Wed Jul 12 05:29:56 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 11 Jul 2006 22:29:56 -0500
Subject: [Tutor] How do I get my machine to run an SMTP server?
In-Reply-To: <001a01c6a55e$f8d07e00$8b4a6244@valued61da873e>
References: <001a01c6a55e$f8d07e00$8b4a6244@valued61da873e>
Message-ID: <44B46CB4.6090201@gmail.com>

[snip code]
> *When I run the program using IDLE, I get the following:*
>  
> Send the contents of a directory as a MIME message.
>  
> Usage: dirmail [options] from to [to ...]*
>  
> Options:
>     -h / --help
>         Print this message and exit.
>  
>     -d directory
>     --directory=directory
>         Mail the contents of the specified directory, otherwise use the
>         current directory.  Only the regular files in the directory 
> are sent,
>         and we don't recurse to subdirectories.
>  
> `from' is the email address of the sender of the message.
>  
> `to' is the email address of the recipient of the message, and multiple
> recipients may be given.
>  
> The email is sent by forwarding to your local SMTP server, which then 
> does the
> normal delivery process.  Your local machine must be running an SMTP 
> server.
>  
> Traceback (most recent call last):
>   File "C:\Documents and Settings\User\Desktop\EB2.py", line 125, in ?
>     main()
>   File "C:\Documents and Settings\User\Desktop\EB2.py", line 65, in main
>     usage(1)
>   File "C:\Documents and Settings\User\Desktop\EB2.py", line 48, in usage
>     sys.exit(code)
> SystemExit: 1
>  
> *I guess that my first question is how do I get my machine to run an 
> SMTP server?*
That's not what's causing the error.  It's raising an error because your 
program expects arguments to be passed to it.
Did you know that?
Other than that, if you're on Linux, Sendmail is an SMTP server that 
comes with most/all flavors of Linux, I believe.
If you're on Windows, I have no idea what kind of SMTP server you should 
use.
Sorry I can't be of more help.
> ** 
> *Also, I'd like to say that I greatly appreciate all of the help that 
> I've gotten in the past.*
>  
> Grady Henry
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From alan.gauld at freenet.co.uk  Wed Jul 12 08:48:38 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 12 Jul 2006 07:48:38 +0100
Subject: [Tutor] no loops
References: <20060711230836.56159.qmail@web51615.mail.yahoo.com>
Message-ID: <002401c6a57f$349de330$04000100@XPpro>

> def increment(time, seconds):
>  time.seconds = time.seconds + seconds
> 
>  while time.seconds >= 60:
>    time.seconds = time.seconds - 60
>    time.minutes = time.minutes + 1

Tale a look at what this loop is doing.
Think about its purpose. If you werre doing this 
with paper and pencil would you really use iteration?
Think division....

> As an exercise, rewrite this function so that it
> doesn't contain any loops.
> 
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.

The loops are implementing a mathematical function 
which doesn't need a loop. Look at the division and 
modulo operators.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From sanelson at gmail.com  Wed Jul 12 12:18:36 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Wed, 12 Jul 2006 11:18:36 +0100
Subject: [Tutor] Python on AIX
Message-ID: <b6131fdc0607120318xcaa264eq3763f02cfe857e04@mail.gmail.com>

Hello all,

Just started a new job - most of the machines I am administering are
AIX, and don't have Python at all.  What is going to me the most
pain-free, scaleable and supportable way of getting Python onto these
machines?  I need to take this request to change advisory board.

Also, I could find myself facing a barrage of questions along the
lines of "Why not use perl or just shell?" Has anyone had much joy in
winning over such people?

S.

From kent37 at tds.net  Wed Jul 12 12:51:13 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 12 Jul 2006 06:51:13 -0400
Subject: [Tutor] How do I get my machine to run an SMTP server?
In-Reply-To: <001a01c6a55e$f8d07e00$8b4a6244@valued61da873e>
References: <001a01c6a55e$f8d07e00$8b4a6244@valued61da873e>
Message-ID: <44B4D421.8050901@tds.net>

Grady Henry wrote:
> *I guess that my first question is how do I get my machine to run an 
> SMTP server?*
Rather than running a new SMTP server on your local machine, you 
probably should use the same server your mail client already uses. Look 
for the *outgoing* server in the configuration of your mail client - for 
example in Thunderbird there is a panel called "Outgoing Server (SMTP)". 
Use the same server in your program.

Kent


From devayani.barve at gmail.com  Wed Jul 12 12:54:24 2006
From: devayani.barve at gmail.com (devayani barve)
Date: Wed, 12 Jul 2006 16:24:24 +0530
Subject: [Tutor] need problems to solve
Message-ID: <301929340607120354j4ce0e735l92f32b54cf45c9fe@mail.gmail.com>

Hi,
I was wondering where I could get problems in python for practicing.
Thanks
Regards

Devayani
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060712/82874dcc/attachment.htm 

From kent37 at tds.net  Wed Jul 12 12:58:40 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 12 Jul 2006 06:58:40 -0400
Subject: [Tutor] Python on AIX
In-Reply-To: <b6131fdc0607120318xcaa264eq3763f02cfe857e04@mail.gmail.com>
References: <b6131fdc0607120318xcaa264eq3763f02cfe857e04@mail.gmail.com>
Message-ID: <44B4D5E0.7060309@tds.net>

Steve Nelson wrote:
> Hello all,
>
> Just started a new job - most of the machines I am administering are
> AIX, and don't have Python at all.  What is going to me the most
> pain-free, scaleable and supportable way of getting Python onto these
> machines?  I need to take this request to change advisory board.
>   
According to this page Python binaries for AIX are available. If you 
click through the links, the versions actually available are more recent 
than those listed on the first page.
http://www.python.org/download/other/

Kent


From josipl2000 at yahoo.com  Wed Jul 12 12:54:13 2006
From: josipl2000 at yahoo.com (josip)
Date: Wed, 12 Jul 2006 03:54:13 -0700 (PDT)
Subject: [Tutor] abs beginner first project
Message-ID: <20060712105413.469.qmail@web60817.mail.yahoo.com>

Hi!
   
  I have finished learning python book and python for absolute beginners book.
  Now I want to start my first project.
   
  Can someone sugest me project for first time (and some pointers,please)?
   
  I'm thinking about text editor.
   
  Thanks people!

 		
---------------------------------
Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060712/7ffedc55/attachment.html 

From sanelson at gmail.com  Wed Jul 12 13:05:06 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Wed, 12 Jul 2006 12:05:06 +0100
Subject: [Tutor] Python on AIX
In-Reply-To: <44B4D5E0.7060309@tds.net>
References: <b6131fdc0607120318xcaa264eq3763f02cfe857e04@mail.gmail.com>
	<44B4D5E0.7060309@tds.net>
Message-ID: <b6131fdc0607120405s500ee9v86a7c342b0ec3de7@mail.gmail.com>

On 7/12/06, Kent Johnson <kent37 at tds.net> wrote:

> According to this page Python binaries for AIX are available. If you
> click through the links, the versions actually available are more recent
> than those listed on the first page.
> http://www.python.org/download/other/

Thanks - that's perfect - there's lots of other useful stuff there too.

Now to construct a convincing argument that I should be allowed to
install it across the environment...

> Kent

S.

From rabidpoobear at gmail.com  Wed Jul 12 13:48:44 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 12 Jul 2006 06:48:44 -0500
Subject: [Tutor] abs beginner first project
In-Reply-To: <20060712105413.469.qmail@web60817.mail.yahoo.com>
References: <20060712105413.469.qmail@web60817.mail.yahoo.com>
Message-ID: <44B4E19C.7060809@gmail.com>

josip wrote:
> Hi!
>  
> I have finished learning python book and python for absolute beginners 
> book.
> Now I want to start my first project.
>  
> Can someone sugest me project for first time (and some pointers,please)?
>  
> I'm thinking about text editor.
>  
> Thanks people!

GUIs aren't the most Pythonic thing you could find to write.
I'd suggest something that's more focused on the Python itself and less 
on figuring out the quirks of Tk/Tcl or WxWindows or whatever GUI 
toolkit you're using.
For example, in Tkinter, you can bind buttons to function calls, but you 
can't have buttons pass arguments to the functions.  So you have to 
somehow make a separate function for each button, or do some weird 
backend event handling stuff that you can look up  if you're really 
interested.  Point is, you don't want to be hindered by having to figure 
out stuff like that when you're just learning how to use a new language.
That said, I don't really have an alternative to recommend.  I don't 
know what kind of stuff you're interested in.  You could try writing a 
game in Pygame or something like that.  Pygame is easier to learn than 
Tkinter and WxWindows imho.
But if you want to make the text editor anyway, I wish you luck, and 
I'll help wherever I can.
Or were you suggesting a console-based text editor?
Cheers,
-Luke

From andrew.arobert at gmail.com  Wed Jul 12 18:23:47 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Wed, 12 Jul 2006 12:23:47 -0400
Subject: [Tutor] Python module and HP OpenView
Message-ID: <44B52213.30208@gmail.com>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi everyone,

Does anyone know if there are Python modules available for dealing with
HP OpenView?

I found documentation for connecting to the service navigator and
parsing the data via ElementTree or similar XML parsers.

I was just wondering if there were anything specifically created.

Any insight you might have on this would be greatly appreciated.



- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  arobert at mfs.com
Linux User Number: #201204
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEtSITDvn/4H0LjDwRAkeJAJ45nfP3OCuvj/o40dhqh2J7yPPCigCZAZb6
rIMNmIoK1RI+tvaqAMkagRc=
=RErH
-----END PGP SIGNATURE-----

From tinoloc at gmail.com  Wed Jul 12 19:29:17 2006
From: tinoloc at gmail.com (Tino Dai)
Date: Wed, 12 Jul 2006 13:29:17 -0400
Subject: [Tutor] Python on AIX
In-Reply-To: <b6131fdc0607120318xcaa264eq3763f02cfe857e04@mail.gmail.com>
References: <b6131fdc0607120318xcaa264eq3763f02cfe857e04@mail.gmail.com>
Message-ID: <e033edfb0607121029w78144375ia8cb0e3b20c191de@mail.gmail.com>

On 7/12/06, Steve Nelson <sanelson at gmail.com> wrote:
>
> Hello all,
>
> Just started a new job - most of the machines I am administering are
> AIX, and don't have Python at all.  What is going to me the most
> pain-free, scaleable and supportable way of getting Python onto these
> machines?  I need to take this request to change advisory board.
>
> Also, I could find myself facing a barrage of questions along the
> lines of "Why not use perl or just shell?" Has anyone had much joy in
> winning over such people?


I'm going to take a stab at this. The advisory board like all human don't
like uncertain. And even though a programming language has an element of
uncertainately built it, not all programming languages are equal.
Maintainablility, readability, and extendability are all keys of
"non-throwaway programs". I have use Perl/shell over the past ten years and
can pretty much do anything Perl and shell (you should see my camel book). I
see a couple of drawbacks to using Perl over Python.

1 - Perl can look like a cartoon character cursing a lot
2 - Perl and can become very unwieldy and very unmanageable very quickly - I
have regular expressions and code that I wrote and would take me a good deal
of time for me to re-understand
3 - Object oriented - Python is object oriented right out of the box, perl
is not. I have read somewhere that the OO part of perl is "bolted on". Adds
to manageability factor

Another compelling reason:
4 - Google uses it for all of their scripting internally

The second which is off topic is human nature and really is off topic. If
you are interested in this, email me directly. Thanks!

HTH,
-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060712/da57189d/attachment.htm 

From klappnase at freenet.de  Wed Jul 12 19:58:28 2006
From: klappnase at freenet.de (Michael Lange)
Date: Wed, 12 Jul 2006 19:58:28 +0200
Subject: [Tutor] abs beginner first project
In-Reply-To: <44B4E19C.7060809@gmail.com>
References: <20060712105413.469.qmail@web60817.mail.yahoo.com>
	<44B4E19C.7060809@gmail.com>
Message-ID: <20060712195828.720539d3.klappnase@freenet.de>

On Wed, 12 Jul 2006 06:48:44 -0500
Luke Paireepinart <rabidpoobear at gmail.com> wrote:

> For example, in Tkinter, you can bind buttons to function calls, but you 
> can't have buttons pass arguments to the functions.  So you have to 
> somehow make a separate function for each button, or do some weird 
> backend event handling stuff that you can look up  if you're really 
> interested.

BTW, that is not really true:

>>> from Tkinter import *
>>> def test(*args):
...     print args
... 
>>> root = Tk()
>>> b = Button(root, text='Hi', command=lambda widget=b: test(widget))
>>> b.pack()

Now when you press the button, you get:

>>> (<Tkinter.Button instance at 0xb78a478c>,)

>>>

so the callback actually "knows" which widget called it, and you could easily perform
different actions for several buttons.

I know that is not what this thread is about, I just could not resist...

Michael

From ryan_gm at sbcglobal.net  Wed Jul 12 20:06:16 2006
From: ryan_gm at sbcglobal.net (ryan luna)
Date: Wed, 12 Jul 2006 11:06:16 -0700 (PDT)
Subject: [Tutor] unbound method function()
Message-ID: <20060712180616.59559.qmail@web80829.mail.yahoo.com>

I have two Classes, I have a method in the first class (using Pygame/livewires moduls)

Class1(games.Sprite):
       function1(self):

That is being called by the second class

Class2(games.Sprite):
       function2(self):
          Class1.function1()

When the code runs i get this error

"unbound method function() must be called with Class2 instance as first argument
(got nothing instead)"

Its weird (to me) b/c i have other methods calling methods from other classes just fine, but on this one method i get that error.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060712/671a999a/attachment.htm 

From Mike.Hansen at atmel.com  Wed Jul 12 20:24:45 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Wed, 12 Jul 2006 12:24:45 -0600
Subject: [Tutor] need problems to solve
Message-ID: <57B026980605A64F9B23484C5659E32E179DA4@poccso.US.ad.atmel.com>

 

	Hi,
	I was wondering where I could get problems in python for
practicing.
	Thanks
	Regards
	 
	Devayani 
	 
	
http://pyfaq.infogami.com/tutor-im-learning-python-what-should-i-program
has some suggestions.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060712/59479774/attachment.htm 

From alan.gauld at freenet.co.uk  Wed Jul 12 20:37:01 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 12 Jul 2006 19:37:01 +0100
Subject: [Tutor] abs beginner first project
References: <20060712105413.469.qmail@web60817.mail.yahoo.com>
	<44B4E19C.7060809@gmail.com>
Message-ID: <002801c6a5e2$2a4b7ce0$04000100@XPpro>

>> I'm thinking about text editor.

> GUIs aren't the most Pythonic thing you could find to write.

Text editor != GUI

Many of the most interesting text editors are not GUI bsased
and in fact there is a gap(IMHO) at the moment for a really good batch
oriented text editor(*) - sed is OK but it is really stream based,
not batch. So a really nice batch oriented text editor would
be a potentially useful tool.

Now a beginner won't write a killer batch editor first time out
but it sure would be an interesting starter project and potentially
easy to add features later.

(*)By batch oriented I mean the ability to edit a text filke by
loading a set of prewritten editing commands, these can then
be applied to a whole set of files from a shell loop say.

Of course you could write a Python program to do this or
an elisp function for emacs etc. But a true batch oriented
editor (as used to be found on mainframe and midi computers
- Think EDT on VAX; except it had inrteractive mode too)

You invoke it like:

$ myeditor -dfilename=foobar.py myfile.txt mycommands.cmd

and mycommands .cmd looks something like:

g25                            # go line 25
s/mystring/otherstring/   # replace string
df/startRE/finishRE/     # delete from start to finish
g+7                            # move down 7 lines
3w                             # move in 3 words
i$filename                   # insert the value of filename (defined 
in the commandline
x                               # save and exit

That's in vi like pseudo code but hopefully gives an idea. Its
easy enough to make up your own, maybe an SGML style.
EDT used words like:

LINE 25
SUBSTR mystring newstrinhg
DELETE FROM mystring TO endstring
etc...

You can of course include loops and subroutines/macros too.

The value of this as a beginner project is that no display magic
needs to happen, simple status messages are enough...

> For example, in Tkinter, you can bind buttons to function calls, but 
> you can't have buttons pass arguments to the functions.  So you have 
> to somehow make a separate function for each button, or do some 
> weird backend event handling stuff that you can look up

Its almost trivially simple to do that. I wouldn't think it would
deter too many beginners. (ie a lambda calling a function providing
the arguments needed)

> interested.  Point is, you don't want to be hindered by having to 
> figure out stuff like that when you're just learning how to use a 
> new language.

But the basic point is well made, you don't want to be learning
new frameworks when you are really trying to learn core python.

> Or were you suggesting a console-based text editor?

Console based is possible, either in line mode like ex, ed
or in screen mode like vi, or in batch mode as discussed above.
You could even use page mode like ISPF on MVS, so far as I
know there are no page mode editors on Wondows/Unix, it
might be an interesting challenge! (OTOH hand there is a
good reason there are no page mode editors oin those OS! :-)

Alan G 



From bill at celestial.net  Wed Jul 12 20:54:57 2006
From: bill at celestial.net (Bill Campbell)
Date: Wed, 12 Jul 2006 11:54:57 -0700
Subject: [Tutor] Library for rtf to text?
Message-ID: <20060712185457.GA42219@alexis.mi.celestial.com>

I'm looking for a python library to convert rtf to plain text
(parsing Delicious Library XML files for other use), but haven't
found anything python-specific in the python Library Reference or
in a google search.

I have found a C program that will convert rtf2html, and I could
use that if necessary, but would prefer a pure python solution.

Any hints on this?

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

``I have no reason to suppose that he, who would take away my Liberty, would
not when he had me in his Power, take away everything else.''  John Locke

From john at fouhy.net  Wed Jul 12 23:30:31 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 13 Jul 2006 09:30:31 +1200
Subject: [Tutor] abs beginner first project
In-Reply-To: <20060712105413.469.qmail@web60817.mail.yahoo.com>
References: <20060712105413.469.qmail@web60817.mail.yahoo.com>
Message-ID: <5e58f2e40607121430j61c51bcfr24798e84659588ac@mail.gmail.com>

On 12/07/06, josip <josipl2000 at yahoo.com> wrote:
>
> Hi!
>
> I have finished learning python book and python for absolute beginners book.
> Now I want to start my first project.
>
> Can someone sugest me project for first time (and some pointers,please)?

Do you listen to music on your computer?  You could write a program to
catalogue your MP3 files.  For example, you could type something like:

  python findMP3s.py -artist Beatles

and it would return all the mp3s you have by the Beatles.  There's a
few modules around that will help you read id3 tags (unless you're
using an intel mac :-/ ) and the rest should be fun stuff with data
structures.

-- 
John.

From kyxaxa at gmail.com  Wed Jul 12 23:41:06 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Thu, 13 Jul 2006 00:41:06 +0300
Subject: [Tutor] parsing
Message-ID: <bf6cdbf10607121441t1918f212ha60638bf1bd30a57@mail.gmail.com>

First, excuse me my English... English is not my native language, but I hope

that I will be able to describe my problem.

I am new in python for web, but I want to do such thing:

Suppose I have a html-page, like this:
"""
<title>TITLE</title>
<body>
body_1
<h1>1_1</h1>
<h2>2_1</h2>
<div id=one>div_one_1</div>
<p>p_1</p>
<p>p_2</p>
<div id=one>div_one_2</div>
<span class=sp_1>
sp_text
<div id=one>div_one_2</div>
<div id=one>div_one_3</div>
</span>
<h3>3_1</h3>
<h2>2_2</h2>
<p>p_3</p>
body_2
<h1>END</h1>
<table>
<tr><td>td_1</td>
<td class=sp_2>td_2</td>
<td>td_3</td>
<td>td_4</td></tr>
...
</body>

"""

I want to get all info from this html in a dictionary that looks like this:

rezult = [{'title':['TITLE'],
{'body':['body_1', 'body_2']},
{'h1':['1_1', 'END']},
{'h2':['2_1', '2_2']},
{'h3':['3_1']},
{'p':['p_1', 'p_2']},
{'id_one':['div_one_1', 'div_one_2', 'div_one_3']},
{'span_sp_1':['sp_text']},
{'td':['td_1', 'td_3', 'td_4']},
{'td_sp_2':['td_2']},
....
]

Huh, hope you understand what I need.
Can you advise me what approaches exist to solve tasks of such type... and
may be show some practical examples....
Thanks in advance for help of all kind...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060713/5ea1df60/attachment.htm 

From shashikant.ramakrish at smartm.com  Wed Jul 12 23:38:17 2006
From: shashikant.ramakrish at smartm.com (Ramakrishnan, Shashikanth)
Date: Thu, 13 Jul 2006 05:38:17 +0800
Subject: [Tutor] Hi, need help on zip commands for windows
Message-ID: <5DB7DA8F9E5405418E073ABC68308556117868@sr-png-exc02.smartm.internal>

Hi,

I have just started using Python and would appreciate if somebody could
help me out on zip commands.

I am using C H Swaroop's book "A byte of python" as my beginners guide.

 

One example states to use >>>zip_command = "zip -qr '%s' %s" % (target,
' '.join(source))

for zipping the target and source.

However, "zip_command" as I understand is for Linux.

 

What would be the quivalent command for windows( I am using IDLE 1.1.3,
Python version 2.4.3)

 

Really appreciate your help.

 

Thanks,

Shashi.

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060713/0c5496af/attachment.htm 

From bgailer at alum.rpi.edu  Thu Jul 13 01:15:20 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 12 Jul 2006 16:15:20 -0700
Subject: [Tutor] Python on AIX
In-Reply-To: <e033edfb0607121029w78144375ia8cb0e3b20c191de@mail.gmail.com>
References: <b6131fdc0607120318xcaa264eq3763f02cfe857e04@mail.gmail.com>
	<e033edfb0607121029w78144375ia8cb0e3b20c191de@mail.gmail.com>
Message-ID: <44B58288.5040606@alum.rpi.edu>

Tino Dai wrote:
> On 7/12/06, *Steve Nelson* <sanelson at gmail.com 
> <mailto:sanelson at gmail.com>> wrote:
>
>     Hello all,
>
>     Just started a new job - most of the machines I am administering are
>     AIX, and don't have Python at all.  What is going to me the most
>     pain-free, scaleable and supportable way of getting Python onto these
>     machines?  I need to take this request to change advisory board.
>
>     Also, I could find myself facing a barrage of questions along the
>     lines of "Why not use perl or just shell?" Has anyone had much joy in
>     winning over such people?
>
>  
> I'm going to take a stab at this. The advisory board like all human 
> don't like uncertain. And even though a programming language has an 
> element of uncertainately built it, not all programming languages are 
> equal. Maintainablility, readability, and extendability are all keys 
> of "non-throwaway programs". I have use Perl/shell over the past ten 
> years and can pretty much do anything Perl and shell (you should see 
> my camel book). I see a couple of drawbacks to using Perl over Python.
>
> 1 - Perl can look like a cartoon character cursing a lot
> 2 - Perl and can become very unwieldy and very unmanageable very 
> quickly - I have regular expressions and code that I wrote and would 
> take me a good deal of time for me to re-understand
> 3 - Object oriented - Python is object oriented right out of the box, 
> perl is not. I have read somewhere that the OO part of perl is "bolted 
> on". Adds to manageability factor
>
> Another compelling reason:
> 4 - Google uses it for all of their scripting internally
>
> The second which is off topic is human nature and really is off topic. 
> If you are interested in this, email me directly. Thanks!
Please include me on this discussion if you have it. I'm very interested 
in this aspect, and may have something to contribute.

-- 
Bob Gailer
510-978-4454


From glingl at aon.at  Thu Jul 13 01:34:14 2006
From: glingl at aon.at (Gregor Lingl)
Date: Thu, 13 Jul 2006 01:34:14 +0200
Subject: [Tutor] Alias for a class name
Message-ID: <44B586F6.4070402@aon.at>

Hi everyoen,

say in some module I have defined a class Pen
and I want an alias for the class name, say
Turtle

I can do this:

class Turtle(Pen):
    pass

or simply (after having defined Pen):

Turtle = Pen

Are those two variants different in effect?
Are there pros or cons for one of both
variants?

Regards,
Gregor

From ismaelgf at adinet.com.uy  Thu Jul 13 01:49:12 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Wed, 12 Jul 2006 20:49:12 -0300
Subject: [Tutor] Alias for a class name
In-Reply-To: <44B586F6.4070402@aon.at>
References: <44B586F6.4070402@aon.at>
Message-ID: <44B58A78.40904@adinet.com.uy>

Gregor Lingl wrote:
> Hi everyoen,
>
> say in some module I have defined a class Pen
> and I want an alias for the class name, say
> Turtle
>
> I can do this:
>
> class Turtle(Pen):
>     pass
>
> or simply (after having defined Pen):
>
> Turtle = Pen
>
> Are those two variants different in effect?
> Are there pros or cons for one of both
> variants?
>
> Regards,
> Gregor
If you are making an alias... use Turtle = Pen...
Inheritance for this seems WAY too weird. It took me a minute to realise 
what you were trying to do. Instead, Turtle = Pen is clear and direct... 
More "pythonic" perhaps.

Also, Inheritance may cause some variables to be hardly accesible (like 
if they're __mangled).

Ismael

From ismaelgf at adinet.com.uy  Thu Jul 13 02:04:15 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Wed, 12 Jul 2006 21:04:15 -0300
Subject: [Tutor] parsing
In-Reply-To: <bf6cdbf10607121441t1918f212ha60638bf1bd30a57@mail.gmail.com>
References: <bf6cdbf10607121441t1918f212ha60638bf1bd30a57@mail.gmail.com>
Message-ID: <44B58DFF.9030007@adinet.com.uy>

?????? wrote:
> First, excuse me my English... English is not my native language, but 
> I hope
> that I will be able to describe my problem.
>
> I am new in python for web, but I want to do such thing:
>
> Suppose I have a html-page, like this:
> """
> <title>TITLE</title>
> <body>
> body_1
> <h1>1_1</h1>
> <h2>2_1</h2>
> <div id=one>div_one_1</div>
> <p>p_1</p>
> <p>p_2</p>
> <div id=one>div_one_2</div>
> <span class=sp_1>
> sp_text
> <div id=one>div_one_2</div>
> <div id=one>div_one_3</div>
> </span>
> <h3>3_1</h3>
> <h2>2_2</h2>
> <p>p_3</p>
> body_2
> <h1>END</h1>
> <table>
> <tr><td>td_1</td>
> <td class=sp_2>td_2</td>
> <td>td_3</td>
> <td>td_4</td></tr>
> ...
> </body>
>
> """
>
> I want to get all info from this html in a dictionary that looks like 
> this:
>
> rezult = [{'title':['TITLE'],
> {'body':['body_1', 'body_2']},
> {'h1':['1_1', 'END']},
> {'h2':['2_1', '2_2']},
> {'h3':['3_1']},
> {'p':['p_1', 'p_2']},
> {'id_one':['div_one_1', 'div_one_2', 'div_one_3']},
> {'span_sp_1':['sp_text']},
> {'td':['td_1', 'td_3', 'td_4']},
> {'td_sp_2':['td_2']},
> ....
> ]
>
> Huh, hope you understand what I need.
> Can you advise me what approaches exist to solve tasks of such type... 
> and
> may be show some practical examples....
> Thanks in advance for help of all kind...

Try ElementTree or Amara.
http://effbot.org/zone/element-index.htm
http://uche.ogbuji.net/tech/4suite/amara/

If you only cared about contents, BeautifulSoup is the answer.

Ismael

From kent37 at tds.net  Thu Jul 13 02:05:33 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 12 Jul 2006 20:05:33 -0400
Subject: [Tutor] Alias for a class name
In-Reply-To: <44B586F6.4070402@aon.at>
References: <44B586F6.4070402@aon.at>
Message-ID: <44B58E4D.3010500@tds.net>

Gregor Lingl wrote:
> Hi everyoen,
>
> say in some module I have defined a class Pen
> and I want an alias for the class name, say
> Turtle
>
> I can do this:
>
> class Turtle(Pen):
>     pass
>
> or simply (after having defined Pen):
>
> Turtle = Pen
>
> Are those two variants different in effect?
> Are there pros or cons for one of both
> variants?

They are different. Turtle = Pen creates an alias - another name that 
refers to the same object. Changes made through either name will affect 
both. This is similar to what happens if you give two names to a list, 
for example.

In [1]: class Pen(object):
   ...:     value = 3
   ...:     def show(self):
   ...:         print type(self), self.value
   ...:
   ...:

In [2]: Turtle = Pen

In [3]: p = Pen()

In [4]: p.show()
<class '__main__.Pen'> 3

In [5]: t = Turtle()

In [6]: t.show()
<class '__main__.Pen'> 3

In [7]: Turtle.value = 'new value'

In [8]: p.show()
<class '__main__.Pen'> new value

In [9]: type(p) == type(t)
Out[9]: True

Creating a subclass makes a new class that inherits all the behaviour of 
the original class. However you may modify the subclass after it is 
created and the modifications won't affect the base class, and objects 
of the new class have a different type than objects of the base class:

In [10]: class Turtle(Pen): pass
   ....:

In [11]: t=Turtle()

In [12]: t.show()
<class '__main__.Turtle'> new value

In [13]: Turtle.value = 'turtle'

In [14]: t.show()
<class '__main__.Turtle'> turtle

In [15]: p.show()
<class '__main__.Pen'> new value

If you want an alias, use an alias. If you need a subclass, make a 
subclass. They're not the same!

Kent


From anilmrn at yahoo.com  Thu Jul 13 02:28:19 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 12 Jul 2006 17:28:19 -0700 (PDT)
Subject: [Tutor] question about metaclasses
Message-ID: <20060713002819.32383.qmail@web55910.mail.re3.yahoo.com>

hi pygurus
can you please tell me why we need metaclasses and how to use them
thanks a lot
Anil

 		
---------------------------------
Do you Yahoo!?
 Everyone is raving about the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060712/84d93787/attachment.htm 

From anilmrn at yahoo.com  Thu Jul 13 02:29:02 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 12 Jul 2006 17:29:02 -0700 (PDT)
Subject: [Tutor] email anonymizing
Message-ID: <20060713002902.54363.qmail@web55906.mail.re3.yahoo.com>

i m trying to do email anonymizing like cl in a webapp can you suggest how to do it
thanks a lot

 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060712/4da70518/attachment.html 

From kent37 at tds.net  Thu Jul 13 03:12:12 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 12 Jul 2006 21:12:12 -0400
Subject: [Tutor] question about metaclasses
In-Reply-To: <20060713002819.32383.qmail@web55910.mail.re3.yahoo.com>
References: <20060713002819.32383.qmail@web55910.mail.re3.yahoo.com>
Message-ID: <44B59DEC.9010508@tds.net>

anil maran wrote:
> hi pygurus
> can you please tell me why we need metaclasses and how to use them

Hmm...metaclasses are an advanced topic, first exposure to them usually 
causes one's brain to explode. Fortunately the condition is only 
temporary :-)

Basically a metaclass is the type of a class, or the type of a type. 
Think about it this way - every object has a type. The type of 1 is int, 
the type of 'a' is str.

In [16]: type(1)
Out[16]: <type 'int'>

In [17]: type('a')
Out[17]: <type 'str'>

Note that <type 'int'> is just the printed representation of the type int:
In [19]: type(1) == int
Out[19]: True

In [20]: print int
<type 'int'>

But int and str are themselves objects - what is their type?

In [18]: type(int)
Out[18]: <type 'type'>

In [21]: type(str)
Out[21]: <type 'type'>

Why might you care? In general, it is the type of an object that 
determines its behaviour. The behaviour of an int is determined by the 
int type. What determines the behaviour of a class? Its type! So if you 
want to customize the behaviour of a class, you create a custom metatype 
for the class.

That is a very brief introduction. Here are some relatively introductory 
articles. You can find more examples by searching the Python Cookbook 
and comp.lang.python for "metaclass". Don't expect to understand this 
the first time.
http://www-128.ibm.com/developerworks/linux/library/l-pymeta.html
http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/

Here is Guido's brief explanation:
http://www.python.org/download/releases/2.2.3/descrintro/#metaclasses

Kent


From bgailer at alum.rpi.edu  Thu Jul 13 03:47:03 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 12 Jul 2006 18:47:03 -0700
Subject: [Tutor] email anonymizing
In-Reply-To: <20060713002902.54363.qmail@web55906.mail.re3.yahoo.com>
References: <20060713002902.54363.qmail@web55906.mail.re3.yahoo.com>
Message-ID: <44B5A617.1000503@alum.rpi.edu>

anil maran wrote:
> i m trying to do email anonymizing like cl in a webapp can you suggest 
> how to do it
I can't, but then I don't understand the terms you're using.

And how does this relate to Python?

-- 
Bob Gailer
510-978-4454


From justin.mailinglists at gmail.com  Thu Jul 13 04:31:41 2006
From: justin.mailinglists at gmail.com (Justin Ezequiel)
Date: Thu, 13 Jul 2006 10:31:41 +0800
Subject: [Tutor] Library for rtf to text?
Message-ID: <3c6718980607121931n204214e5h11f0e664cd1339cd@mail.gmail.com>

Bill Campbell wrote:
> I'm looking for a python library to convert rtf to plain text
> ...
> I have found a C program that will convert rtf2html, and I could
> use that if necessary, but would prefer a pure python solution.

I know I saw something months ago...
Have been meaning to look at it but just did not have the time...
Ha! Found it!

https://sourceforge.net/projects/rtf2xml/

From anilmrn at yahoo.com  Thu Jul 13 04:52:17 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 12 Jul 2006 19:52:17 -0700 (PDT)
Subject: [Tutor] email anonymizing
In-Reply-To: <44B5A617.1000503@alum.rpi.edu>
Message-ID: <20060713025218.80549.qmail@web55915.mail.re3.yahoo.com>

hi i m trying to anonymize emails
everytime someone enters
email at domain.com

i want to generate

cost-1234 at myweb.com and use this email in the web application 

I want to do this in python
can you please explain how to do this
thanks a lot

Bob Gailer <bgailer at alum.rpi.edu> wrote: anil maran wrote:
> i m trying to do email anonymizing like cl in a webapp can you suggest 
> how to do it
I can't, but then I don't understand the terms you're using.

And how does this relate to Python?

-- 
Bob Gailer
510-978-4454



 		
---------------------------------
Do you Yahoo!?
 Get on board. You're invited to try the new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060712/8ddc0fae/attachment.htm 

From rabidpoobear at gmail.com  Thu Jul 13 05:05:29 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 12 Jul 2006 22:05:29 -0500
Subject: [Tutor] unbound method function()
In-Reply-To: <20060712180616.59559.qmail@web80829.mail.yahoo.com>
References: <20060712180616.59559.qmail@web80829.mail.yahoo.com>
Message-ID: <44B5B879.7030404@gmail.com>

I noticed no one has answered your question yet, so here's my answer, and
someone should come along and correct me if I give you any wrong info.
ryan luna wrote:
> I have two Classes, I have a method in the first class (using 
> Pygame/livewires moduls)
>
> Class1(games.Sprite):
>        function1(self):
because of the 'self' here, 'function1' expects you to have an instance 
of the class 'Class1' already.
example:
 >>> classinstance = Class1() #i think you'll need an init function in 
Class1, not sure

 >>> Class1.function1(classinstance) #this is how you would call it
 >>> classinstance.function1() #this is shorthand for the above.
>
> That is being called by the second class
>
> Class2(games.Sprite):
>        function2(self):
>          Class1.function1()
Here you're trying to call 'function1' which takes a 'self' argument,
but you're not giving it one.
>
> When the code runs i get this error
>
> "unbound method function() must be called with Class2 instance as 
> first argument
> (got nothing instead)"
'unbound method' means 'needs class instance to call but didn't get 
called with one.'
>
> Its weird (to me) b/c i have other methods calling methods from other 
> classes just fine, but on this one method i get that error.
You're probably calling methods defined without a 'self' argument, or 
you're using an instance of the class (not the original class name) 
without noticing.

HTH,
-Luke

From rabidpoobear at gmail.com  Thu Jul 13 05:11:12 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 12 Jul 2006 22:11:12 -0500
Subject: [Tutor] abs beginner first project
In-Reply-To: <20060712195828.720539d3.klappnase@freenet.de>
References: <20060712105413.469.qmail@web60817.mail.yahoo.com>	<44B4E19C.7060809@gmail.com>
	<20060712195828.720539d3.klappnase@freenet.de>
Message-ID: <44B5B9D0.8010403@gmail.com>

Michael Lange wrote:
[snip awesomeness with lambda]
> so the callback actually "knows" which widget called it, and you could easily perform
> different actions for several buttons.
>
> I know that is not what this thread is about, I just could not resist...
>
> Michael
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   
I had no idea you could do this.  I've been just defining multiple 
functions because I couldn't figure out how to make this work!
I need to learn what lamdba does, clearly.
Thanks a ton for telling me.

To Alan,
Yeah, I guess it is trivially simple to do use lambda.
I didn't realize.  Thanks for your help too.

-Luke

Also, when I reply to a message, should I 'cc:' to tutor at python, add an 
extra 'to:' field with tutor at python, or change the original 'to:' field 
to tutor at python?
What is the difference between 'cc:' and 'to:'?

From rabidpoobear at gmail.com  Thu Jul 13 05:24:37 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 12 Jul 2006 22:24:37 -0500
Subject: [Tutor] Hi, need help on zip commands for windows
In-Reply-To: <5DB7DA8F9E5405418E073ABC68308556117868@sr-png-exc02.smartm.internal>
References: <5DB7DA8F9E5405418E073ABC68308556117868@sr-png-exc02.smartm.internal>
Message-ID: <44B5BCF5.7000106@gmail.com>

Ramakrishnan, Shashikanth wrote:
>
> Hi,
>
Hi.
>
> I have just started using Python and would appreciate if somebody 
> could help me out on zip commands.
>
> I am using C H Swaroop?s book ?A byte of python? as my beginners guide.
>
> One example states to use >>>zip_command = "zip -qr '%s' %s" % 
> (target, ' '.join(source))
>
> for zipping the target and source.
>
> However, ?zip_command? as I understand is for Linux.
>
You're right.
I assume later in the example he uses a method from the 'os' module to 
run this command?
>
> What would be the quivalent command for windows( I am using IDLE 
> 1.1.3, Python version 2.4.3)
>
Well, the example you gave would work on Windows if you had a zipping 
program in your PATH environment variable
called 'zip' that took the same arguments as the 'zip' command on Linux.
This is probably not likely, however, so you have three routes as I see it.
1. look into zipping files with the 'zlib' library.
2. find a port of the linux 'zip' program and put it in the same 
directory as your program (or add it to PATH).
3. find a different command-line zipping program and change zip_command 
to add the correct arguments to it.

HTH,
-Luke
>
> Really appreciate your help.
>
> Thanks,
>
> Shashi.
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From rabidpoobear at gmail.com  Thu Jul 13 05:40:50 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 12 Jul 2006 22:40:50 -0500
Subject: [Tutor] email anonymizing
In-Reply-To: <20060713025218.80549.qmail@web55915.mail.re3.yahoo.com>
References: <20060713025218.80549.qmail@web55915.mail.re3.yahoo.com>
Message-ID: <44B5C0C2.3010206@gmail.com>

anil maran wrote:
> hi i m trying to anonymize emails
hi.
> everytime someone enters
> email at domain.com
>
> i want to generate
>
> cost-1234 at myweb.com and use this email in the web application
>
> I want to do this in python
> can you please explain how to do this
Yes.

Are you trying to anonymize their e-mail before it's sent to the server 
or server-side?
More info please.
Are you using python cgi?

From Senthil_OR at Dell.com  Thu Jul 13 07:14:07 2006
From: Senthil_OR at Dell.com (Senthil_OR at Dell.com)
Date: Thu, 13 Jul 2006 10:44:07 +0530
Subject: [Tutor] Hi, need help on zip commands for windows
In-Reply-To: <5DB7DA8F9E5405418E073ABC68308556117868@sr-png-exc02.smartm.internal>
Message-ID: <D6ED7B7268DC0F4C9BF6AF2537BCE5C604D614@blrx3m03.blr.amer.dell.com>

There is no zip command in as such in windows. You can install
www.7-zip.com software and trying withh command command line interface
as belodw
zip_command = "7z -a %s %s" % (target, ''.join(source))
 
If you like to zip files using python:
 
import zipfile
#create a zip
zipf = zipfile.ZipFile('myzipfile.zip','w',zipfile.ZIP_DEFLATED)
for path,dirs,files in os.walk('Directory_To_Zip'):
    for filen in files:
        filen = os.path.join(path,filen)
        print filen,'...'
        zipf.write(filen)
print 'done'
zipf.close()
 
-- 
Senthil
 


________________________________

From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of Ramakrishnan, Shashikanth
Sent: Thursday, July 13, 2006 3:08 AM
To: tutor at python.org
Subject: [Tutor] Hi, need help on zip commands for windows



Hi,

I have just started using Python and would appreciate if somebody could
help me out on zip commands.

I am using C H Swaroop's book "A byte of python" as my beginners guide.

 

One example states to use >>>zip_command = "zip -qr '%s' %s" % (target,
' '.join(source))

for zipping the target and source.

However, "zip_command" as I understand is for Linux.

 

What would be the quivalent command for windows( I am using IDLE 1.1.3,
Python version 2.4.3)

 

Really appreciate your help.

 

Thanks,

Shashi.

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060713/21576b33/attachment.htm 

From alan.gauld at freenet.co.uk  Thu Jul 13 08:50:59 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 13 Jul 2006 07:50:59 +0100
Subject: [Tutor] Alias for a class name
References: <44B586F6.4070402@aon.at>
Message-ID: <002f01c6a648$b31742a0$04000100@XPpro>

> say in some module I have defined a class Pen
> and I want an alias for the class name, say
> Turtle
> 
> I can do this:
> 
> class Turtle(Pen):
>    pass
> 
> or simply (after having defined Pen):
> 
> Turtle = Pen
> 
> Are those two variants different in effect?

Yes, the first  creates a new class which is a subclass of Pen. 
When you cxall a method on an instance Pyhon will go 
through the usual lookup routine of searching Turtle first 
then looking in Pen.

The second is just an alias of Pen so an instance of Turtle 
is an instance of Pen. Method invocation looks in Pemn 
immediately.

> Are there pros or cons for one of both
> variants?

I can't think of any real advantage to the first one and 
its slightly slower. If you want an alias use the second method.
OTOH If you might want to subclass Turtle then the first 
might be better - although I can't think of a really good 
reason why.... It just reflects the intention better.

HTH,

Alan G.


From alan.gauld at freenet.co.uk  Thu Jul 13 09:01:03 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 13 Jul 2006 08:01:03 +0100
Subject: [Tutor] abs beginner first project
References: <20060712105413.469.qmail@web60817.mail.yahoo.com>	<44B4E19C.7060809@gmail.com><20060712195828.720539d3.klappnase@freenet.de>
	<44B5B9D0.8010403@gmail.com>
Message-ID: <005e01c6a64a$1b4ed620$04000100@XPpro>

> Also, when I reply to a message, should I 'cc:' to tutor at python, add 
> an extra 'to:' field with tutor at python, or change the original 'to:' 
> field to tutor at python?
> What is the difference between 'cc:' and 'to:'?

To indicates the primary recipient, CC is a carbon copy for 
information.
It follows standard (ancient) office practice of sending the original
version of a letter to the main recipient and a carbon copy 
(literally)
to the other people who need to know (like your boss maybe)

So in general you will send the reply to the OP and CC to the list.
But in practice most mailers have a Reply-All button that will do
whats needed automatically!

Also a few folks don't like getting two copies if they read the list,
so they would prefer you sent the reply to the list only. As a
digest user I prefer two copies since the digest only comes in
much later. Which just shows you can't please everyone... :-)

Alan G 



From johan at accesstel.co.za  Thu Jul 13 11:02:17 2006
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Thu, 13 Jul 2006 11:02:17 +0200
Subject: [Tutor] parsing
In-Reply-To: <44B58DFF.9030007@adinet.com.uy>
References: <bf6cdbf10607121441t1918f212ha60638bf1bd30a57@mail.gmail.com>
	<44B58DFF.9030007@adinet.com.uy>
Message-ID: <44B60C19.50804@accesstel.co.za>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060713/9984066d/attachment.html 

From Carlo.Capuano at iter.org  Thu Jul 13 12:00:01 2006
From: Carlo.Capuano at iter.org (Carlo Capuano)
Date: Thu, 13 Jul 2006 12:00:01 +0200
Subject: [Tutor] parsing
In-Reply-To: <44B60C19.50804@accesstel.co.za>
Message-ID: <0F4FBAD10465E047ADB7E8C74B4C189B62A739@de-iws-xch01.iter.org>


Hi!

Give a look at http://www.crummy.com/software/BeautifulSoup/

BeautifulSoup is a python module designed for parsing html

Carlo
 
what is ITER? www.iter.org
 
 
>>
>>		First, excuse me my English... English is not my native
>>language, but
>>		I hope
>>		that I will be able to describe my problem.
>>
>>		I am new in python for web, but I want to do such thing:
>>
>>		Suppose I have a html-page, like this:
>>		"""
>>		<title>TITLE</title>
>>		<body>
>>		body_1
>>		<h1>1_1</h1>
>>		<h2>2_1</h2>
>>		<div id=one>div_one_1</div>
>>		<p>p_1</p>
>>		<p>p_2</p>
>>		<div id=one>div_one_2</div>
>>		<span class=sp_1>
>>		sp_text
>>		<div id=one>div_one_2</div>
>>		<div id=one>div_one_3</div>
>>		</span>
>>		<h3>3_1</h3>
>>		<h2>2_2</h2>
>>		<p>p_3</p>
>>		body_2
>>		<h1>END</h1>
>>		<table>
>>		<tr><td>td_1</td>
>>		<td class=sp_2>td_2</td>
>>		<td>td_3</td>
>>		<td>td_4</td></tr>
>>		...
>>		</body>
>>
>>		"""
>>
>>		I want to get all info from this html in a dictionary
that
>>looks like
>>		this:
>>
>>		rezult = [{'title':['TITLE'],
>>		{'body':['body_1', 'body_2']},
>>		{'h1':['1_1', 'END']},
>>		{'h2':['2_1', '2_2']},
>>		{'h3':['3_1']},
>>		{'p':['p_1', 'p_2']},
>>		{'id_one':['div_one_1', 'div_one_2', 'div_one_3']},
>>		{'span_sp_1':['sp_text']},
>>		{'td':['td_1', 'td_3', 'td_4']},
>>		{'td_sp_2':['td_2']},
>>		....
>>		]
>>
>>		Huh, hope you understand what I need.
>>		Can you advise me what approaches exist to solve tasks
of such
>>type...
>>		and
>>		may be show some practical examples....
>>		Thanks in advance for help of all kind...
>>
>>
>>
>>	Try ElementTree or Amara.
>>	http://effbot.org/zone/element-index.htm
>>	http://uche.ogbuji.net/tech/4suite/amara/
>>
>>	If you only cared about contents, BeautifulSoup is the answer.
>>
>>	Ismael
>>	_______________________________________________
>>	Tutor maillist  -  Tutor at python.org
>>	http://mail.python.org/mailman/listinfo/tutor
>>


From gsf at panix.com  Thu Jul 13 21:47:12 2006
From: gsf at panix.com (Gabriel Farrell)
Date: Thu, 13 Jul 2006 15:47:12 -0400
Subject: [Tutor] piping to system commands
Message-ID: <20060713194711.GC7252@panix.com>

I'm trying to create a master dictionary in aspell, and I can do so
with the following:

    inFile = tempfile.NamedTemporaryFile()
    inFile.write(wordList)
    inFile.flush()
    command = 'aspell --lang=en --dont-validate-words create master %s < %s' % \
        ('./dict.cwl', inFile.name)
    os.system(command)

or, in 2.4, instead of os.system(command):
    
    retcode = subprocess.call(command, shell = True)

I'm wondering, is there a way to do this more directly, without the
need for a temp file, and in a way where I the stdout coming from
aspell won't go to sys.stdout?  The following seems to work, but the
end of the input gets cut off.

    command = 'aspell --lang=en --dont-validate-words create master ./dict.cwl'
    pipe = subprocess.Popen(command, stdin = subprocess.PIPE, shell=True).stdin
    pipe.write()
    pipe.flush()
    pipe.close()

gsf

From anilmrn at yahoo.com  Thu Jul 13 22:20:33 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 13 Jul 2006 13:20:33 -0700 (PDT)
Subject: [Tutor] email anonymizing
In-Reply-To: <44B5C0C2.3010206@gmail.com>
Message-ID: <20060713202033.78737.qmail@web55901.mail.re3.yahoo.com>

hi
the user inputs the email in a form
and then they have an option to anonymize it
the server has a copy of their original and anonymous email id
and the anon email is posted on the relevant page
when some1 needs to contact them, they would email the anon email id, 
the server or py program will take the ano email id and lookup real email id and send out the email

i want to know how to generate
user at yahoo.com =>  cause-11341 at mydomain.com
and then how do i do the translation
cause-11341 at mydomain.com => user at yahoo.com

thanks
anil
Luke Paireepinart <rabidpoobear at gmail.com> wrote: anil maran wrote:
> hi i m trying to anonymize emails
hi.
> everytime someone enters
> email at domain.com
>
> i want to generate
>
> cost-1234 at myweb.com and use this email in the web application
>
> I want to do this in python
> can you please explain how to do this
Yes.

Are you trying to anonymize their e-mail before it's sent to the server 
or server-side?
More info please.
Are you using python cgi?


 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060713/938dbb9c/attachment.htm 

From anilmrn at yahoo.com  Thu Jul 13 22:21:37 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 13 Jul 2006 13:21:37 -0700 (PDT)
Subject: [Tutor] hi
Message-ID: <20060713202138.83171.qmail@web55904.mail.re3.yahoo.com>

hi you wonderful energetic pygurus
i need to send out lot of emails and sms messages from a python program
please let me know if you know of any library like java sms library or possible solutions
i m clueless and lost here
thanks a lot

 		
---------------------------------
Yahoo! Music Unlimited - Access over 1 million songs.Try it free. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060713/58dfaa04/attachment.html 

From anilmrn at yahoo.com  Thu Jul 13 22:32:38 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 13 Jul 2006 13:32:38 -0700 (PDT)
Subject: [Tutor] digging more into metaclasses
In-Reply-To: <44B624FC.1070409@tds.net>
Message-ID: <20060713203238.81694.qmail@web55911.mail.re3.yahoo.com>

hi guys

are metaclasses like templates in C++
thanks for your explanations

 			
---------------------------------
Sneak preview the  all-new Yahoo.com. It's not radically different. Just radically better. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060713/2de2a1c4/attachment.htm 

From john at fouhy.net  Thu Jul 13 22:42:22 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 14 Jul 2006 08:42:22 +1200
Subject: [Tutor] email anonymizing
In-Reply-To: <20060713202033.78737.qmail@web55901.mail.re3.yahoo.com>
References: <44B5C0C2.3010206@gmail.com>
	<20060713202033.78737.qmail@web55901.mail.re3.yahoo.com>
Message-ID: <5e58f2e40607131342v4a423b77r976c4ce7527a218a@mail.gmail.com>

On 14/07/06, anil maran <anilmrn at yahoo.com> wrote:
> i want to know how to generate
> user at yahoo.com =>  cause-11341 at mydomain.com
> and then how do i do the translation
> cause-11341 at mydomain.com => user at yahoo.com

Hi Anil,

Do you have any programming experience in other languages?

-- 
John.

From bgailer at alum.rpi.edu  Thu Jul 13 23:49:39 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 13 Jul 2006 14:49:39 -0700
Subject: [Tutor] email anonymizing
In-Reply-To: <44B5C0C2.3010206@gmail.com>
References: <20060713025218.80549.qmail@web55915.mail.re3.yahoo.com>
	<44B5C0C2.3010206@gmail.com>
Message-ID: <44B6BFF3.1040608@alum.rpi.edu>

Luke Paireepinart wrote:
> anil maran wrote:
>   
>> hi i m trying to anonymize emails
>>     
> hi.
>   
>> everytime someone enters
>> email at domain.com
>>
>> i want to generate
>>
>> cost-1234 at myweb.com and use this email in the web application
>>
>> I want to do this in python
>> can you please explain how to do this
>>     
> Yes.
>
> Are you trying to anonymize their e-mail before it's sent to the server 
> or server-side?
> More info please.
> Are you using python cgi?
>   
To amplify Luke's and others' questions - we need a lot more 
information, and at this point in the process it seems painfully slow to 
extract it from you. If you want our help please tell us:
1) how much programming experience you have.
2) how new to Python are you.
3) why do you want to solve this problem in Python?
4) what can you apply from other languages you know (you refer to Java 
and C++) to this problem
5) have you written any Python code toward solving this problem?
6) do you need help in how to do string substitutions? how to randomly 
generate names? how to store persistently and retrieve mappings of real 
to anonymous addresses?
7) anything else you can tell us so we can give specific help.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454


From anilmrn at yahoo.com  Fri Jul 14 02:00:59 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 13 Jul 2006 17:00:59 -0700 (PDT)
Subject: [Tutor] email anonymizing
In-Reply-To: <44B6BFF3.1040608@alum.rpi.edu>
Message-ID: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com>


1) how much programming experience you have.
i have programmed in cfor about 1 year or so
2) how new to Python are you.
very new 1 week
3) why do you want to solve this problem in Python?
i m tryin to do a web app so i want to do in python
4) what can you apply from other languages you know (you refer to Java 
and C++) to this problem
i dont know how to go about this, and hence i was asking for possible solns from u guys
5) have you written any Python code toward solving this problem?
no i havent 
6) do you need help in how to do string substitutions? how to randomly 
generate names? how to store persistently and retrieve mappings of real 
to anonymous addresses?
this is exactly what i want
7) anything else you can tell us so we can give specific help.
i want to store the mapping in postgres table or a disk file/
i want to input the user email and choice via a form and then 
take it to a func called anon(email_id, choice)
if choice == yes:
  geneate new anon email id correspondin to email_id
  create or update a translation table to hold the link
  return the anon email to create the new page with anon email id

much like craiglist does



Bob Gailer <bgailer at alum.rpi.edu> wrote: Luke Paireepinart wrote:
> anil maran wrote:
>   
>> hi i m trying to anonymize emails
>>     
> hi.
>   
>> everytime someone enters
>> email at domain.com
>>
>> i want to generate
>>
>> cost-1234 at myweb.com and use this email in the web application
>>
>> I want to do this in python
>> can you please explain how to do this
>>     
> Yes.
>
> Are you trying to anonymize their e-mail before it's sent to the server 
> or server-side?
> More info please.
> Are you using python cgi?
>   
To amplify Luke's and others' questions - we need a lot more 
information, and at this point in the process it seems painfully slow to 
extract it from you. If you want our help please tell us:
1) how much programming experience you have.
2) how new to Python are you.
3) why do you want to solve this problem in Python?
4) what can you apply from other languages you know (you refer to Java 
and C++) to this problem
5) have you written any Python code toward solving this problem?
6) do you need help in how to do string substitutions? how to randomly 
generate names? how to store persistently and retrieve mappings of real 
to anonymous addresses?
7) anything else you can tell us so we can give specific help.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454



 		
---------------------------------
Yahoo! Music Unlimited - Access over 1 million songs.Try it free. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060713/cdfa1822/attachment.htm 

From online330983 at telkomsa.net  Fri Jul 14 03:18:04 2006
From: online330983 at telkomsa.net (Alan Collins)
Date: Fri, 14 Jul 2006 03:18:04 +0200
Subject: [Tutor] Help with strings and lists.
Message-ID: <44B6F0CC.20201@telkomsa.net>

Hi,

I do a far bit of data manipulation and decided to try one of my 
favourite utilities in Python. I'd really appreciate some optimization 
of the script. I'm sure that I've missed many tricks in even this short 
script.

Let's say you have a file with this data:

Monday 7373 3663657 2272 547757699 reached 100%
Tuesday 7726347 552 766463 2253 under-achieved 0%
Wednesday 9899898 8488947 6472 77449 reached 100%
Thursday 636648 553 22344 5699 under-achieved 0%
Friday 997 3647757 78736632 357599 over-achieved 200%

You now want columns 1, 5, and 7 printed and aligned (much like a 
spreadsheet). For example:

Monday    547757699 100%
Wednesday     77449 100%
...

This script does the job, but I reckon there are better ways.  In the 
interests of brevity, I have dropped the command-line argument handling 
and hard-coded the columns for the test and I hard-coded the input file 
name.

-------------------------------------------------------
"""
PrintColumns

Print specified columns, alignment based on data type.

The script works by parsing the input file twice.  The first pass gets 
the maximum length of
all values on the columns.  This value is used to pad the column on the 
second pass.

"""
import sys

columns = [0]     # hard-code the columns to be printed.
colwidth = [0]          # list into which the maximum field lenths will 
be stored.

"""
This part is clunky.  Can't think of another way to do it without making 
the script
somewhat longer and slower. What it does is that if the user specifies 
column 0, all
columns will be printed.  This bit builds up the list of columns, from 1 
to 100.
"""

if columns[0] == 0:
     columns = [1]
     while len(columns) < 100:
         columns.append(len(columns)+1)

"""
First pass.  Read all lines and determine the maximum width of each 
selected column.
"""
infile = file("mylist", "r")
indata = infile.readlines()
for myline in indata:
     mycolumns = myline.split()
     colindex = 0
     for column in columns:
         if column <= len(mycolumns):
             if len(colwidth)-1 < colindex:
                 colwidth.append(len(mycolumns[column-1]))
             else:
                 if colwidth[colindex] < len(mycolumns[column-1]):
                     colwidth[colindex] = len(mycolumns[column-1])
         colindex += 1
infile.close()

"""
Second pass. Read all lines and print the selected columns.  Text values 
are left
justified, while numeric values are right justified.
"""
infile = file("mylist", "r")
indata = infile.readlines()
for myline in indata:
     mycolumns = myline.split()
     colindex = 0
     for column in columns:
         if column <= len(mycolumns):
             if mycolumns[column-1].isdigit():
                 x = mycolumns[column-1].rjust(colwidth[colindex]) + ' '
             else:
                 x = mycolumns[column-1].ljust(colwidth[colindex]+1)
             print x,
         colindex += 1
     print ""
infile.close()
-------------------------------------------------------

Any help greatly appreciated.
Regards,
Alan.

From rabidpoobear at gmail.com  Fri Jul 14 06:25:00 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 13 Jul 2006 23:25:00 -0500
Subject: [Tutor] email anonymizing
In-Reply-To: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com>
References: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com>
Message-ID: <44B71C9C.9010907@gmail.com>

One way to do it:
have your form submit the body of the email,the email address, and a 
checkbox value of whether they want to anonymize it.
have a SQL table called Anonymize and if they want to anonymize the 
e-mail do
'SELECT anon FROM Anonymize WHERE email = %s' % email_from_form_submisson

to get the original email from the anonymous one do
'SELECT email FROM Anonymize WHERE anon = %s' % anon_email_value

beyond that, give us more info and we'll try to help.
Are you having trouble with SQL queries?  Are you having trouble with 
Python?
Are you having trouble with your SQL module in Python?
I suggest you try to write the program and when you get stuck,
try to find help in FAQs or the documentation of whichever module is 
giving you trouble,
and if you still can't determine what to do, we'll give ya a hand.

The thing is, there are a bunch of different ways you could do what 
you're trying to do.
First of all, you can use any database system you wanted, mySQL, 
PostgreSQL, MS ACCESS, etc etc.
Or you could even use single/multiple files, in single or multiple 
directories, depending.
You could try to anonymize the email client-side using Javascript or 
serverside using Python.

Why do you think Python is the best thing to user here?
It sounds like PHP would be better.  It's designed for this kind of thing.

You need to plan out what you're trying to do and figure out what the 
best solution is.
It's much easier for us to help you with the implementation when you 
have the design already.

That said, here's what I'd do (I don't have my Python Apache server 
running so this is going to be from memory I.E. probably not working code)
And it uses mysqldb because that's the database module I'm familiar with.

#!/usr/bin/python
#blah.cgi
#blah.cgi gets the user's e-mail address and anonymizes it.  Tru dat.

dbuser,dbpass = 'bob','pass'

print "Content-Type: text/plain\r\n\r\n"
print "<html><head><title='sample e-mail anonymizing skript'></head><body>"
import cgi, MySQLdb
from random import randint
info = cgi.FieldStorage()
try:
    #if this fails then this is their first time accessing the page.
    email=form.getfirst("email","").upper()
    #okay it didn't fail so we have their email now.
    #let's check the database to see if their email is there.
    database = MySQLdb.connect(host="localhost", user=dbuser,passwd=dbpass)
    cursor = database.cursor()
    cursor.execute('SELECT anon FROM Anonymize WHERE email = %s' % email)
    tmp = cursor.fetchall()
    if tmp == ():#or whatever the 'fetchall' method returns if it can't 
find the entry...  
       tmp = "%i at domain.com" % random.randint(1000,9999)#make their 
random address.
       #TODO: make sure the randomly-generated key here isn't already in 
use.
       cursor.execute("INSERT INTO Anonymize (email,anon) VALUES 
('%s','%s')" % (email,tmp))#adds their crap to the table.
   
    print "The e-mail address '%s' anonymized is '%s'" % (email,tmp)

except:
    print """
    <form>
       <input type='text' name='email' width=40></input>
       <input type='Submit' value='Login'></input>
    </form>
    """
print '</html>'

Hope that works.
Also, if you haven't already, you should read 
http://www.catb.org/~esr/faqs/smart-questions.html
-Luke

anil maran wrote:
> 1) how much programming experience you have.
> i have programmed in cfor about 1 year or so
> 2) how new to Python are you.
> very new 1 week
> 3) why do you want to solve this problem in Python?
> i m tryin to do a web app so i want to do in python
> 4) what can you apply from other languages you know (you refer to Java 
> and C++) to this problem
> i dont know how to go about this, and hence i was asking for possible solns from u guys
> 5) have you written any Python code toward solving this problem?
> no i havent 
> 6) do you need help in how to do string substitutions? how to randomly 
> generate names? how to store persistently and retrieve mappings of real 
> to anonymous addresses?
> this is exactly what i want
> 7) anything else you can tell us so we can give specific help.
> i want to store the mapping in postgres table or a disk file/
> i want to input the user email and choice via a form and then 
> take it to a func called anon(email_id, choice)
> if choice == yes:
>   geneate new anon email id correspondin to email_id
>   create or update a translation table to hold the link
>   return the anon email to create the new page with anon email id
>
> much like craiglist does
>
>
> */Bob Gailer <bgailer at alum.rpi.edu>/* wrote:
>
>     Luke Paireepinart wrote:
>     > anil maran wrote:
>     >
>     >> hi i m trying to anonymize emails
>     >>
>     > hi.
>     >
>     >> everytime someone enters
>     >> email at domain.com
>     >>
>     >> i want to generate
>     >>
>     >> cost-1234 at myweb.com and use this email in the web application
>     >>
>     >> I want to do this in python
>     >> can you please explain how to do this
>     >>
>     > Yes.
>     >
>     > Are you trying to anonymize their e-mail before it's sent to the
>     server
>     > or server-side?
>     > More info please.
>     > Are you using python cgi?
>     >
>     To amplify Luke's and others' questions - we need a lot more
>     information, and at this point in the process it seems painfully
>     slow to
>     extract it from you. If you want our help please tell us:
>     1) how much programming experience you have.
>     2) how new to Python are you.
>     3) why do you want to solve this problem in Python?
>     4) what can you apply from other languages you know (you refer to
>     Java
>     and C++) to this problem
>     5) have you written any Python code toward solving this problem?
>     6) do you need help in how to do string substitutions? how to
>     randomly
>     generate names? how to store persistently and retrieve mappings of
>     real
>     to anonymous addresses?
>     7) anything else you can tell us so we can give specific help.
>     > _______________________________________________
>     > Tutor maillist - Tutor at python.org
>     > http://mail.python.org/mailman/listinfo/tutor
>     >
>     >
>
>
>     -- 
>     Bob Gailer
>     510-978-4454
>
>
> ------------------------------------------------------------------------
> Yahoo! Music Unlimited - Access over 1 million songs. Try it free. 
> <http://pa.yahoo.com/*http://us.rd.yahoo.com/evt=36035/*http://music.yahoo.com/unlimited/%20> 
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From john at fouhy.net  Fri Jul 14 06:43:32 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 14 Jul 2006 16:43:32 +1200
Subject: [Tutor] Help with strings and lists.
In-Reply-To: <44B6F0CC.20201@telkomsa.net>
References: <44B6F0CC.20201@telkomsa.net>
Message-ID: <5e58f2e40607132143s56f8c701x7a5ebf1e829bef16@mail.gmail.com>

On 14/07/06, Alan Collins <online330983 at telkomsa.net> wrote:
> You now want columns 1, 5, and 7 printed and aligned (much like a
> spreadsheet). For example:
>
> Monday    547757699 100%
> Wednesday     77449 100%

Let me attempt to be the first to say:

String substitutions!!!

The docs are here: http://docs.python.org/lib/typesseq-strings.html

At their simplest, you can do things like:

s = '%s || %s || %s' % (columns[0], columns[4], columns[6])

This will print:

    Monday || 547757699 || 100%

Next, you can specify padding as well:

s = '%12s || %12s || %5s' % (columns[0], columns[4], columns[6])

and the first string will be padded with spaces to 12 characters, the
second to 12, and the last to 5.  You can change which side it pads on
by specifying negative field widths --- eg, %-12s instead of %12s.
(one will produce "      Monday", the other "Monday      ".  I forget
which.)

Next, you can tell python to read the field width from a variable:

s = '%*s || %*s || %*s' % (12, columns[0], 12, columns[4], 5, columns[6])
(ie: width first)

So all you need to do is find the maximum field width (have a look at
list comprehensions and the max() function), then use string
formatting operators to lay everything out :-)

-- 
John.

From gwhjr at cox.net  Fri Jul 14 07:19:58 2006
From: gwhjr at cox.net (Grady Henry)
Date: Thu, 13 Jul 2006 22:19:58 -0700
Subject: [Tutor] Python Programming Books
References: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com>
	<44B71C9C.9010907@gmail.com>
Message-ID: <001001c6a705$26a5c130$8b4a6244@valued61da873e>

I have three books on Python programming, "Learning Python" by O'Reilly, 
"Beginning Python" by Hetland, and "Python in a Nutshell" by O'Reilly.  Are 
these good (recommended) books?  Any others that might be recommended? 



From alan.gauld at freenet.co.uk  Fri Jul 14 08:15:27 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 14 Jul 2006 07:15:27 +0100
Subject: [Tutor] digging more into metaclasses
References: <20060713203238.81694.qmail@web55911.mail.re3.yahoo.com>
Message-ID: <002101c6a70c$e6d39570$04000100@XPpro>

> are metaclasses like templates in C++
> thanks for your explanations

No, there is no direct concept of metaclasses in C++.
You need to ook to languages like Lisp and Smaltalk for those.

The nearest you get to meta-classes in C++ is static members 
and methods. But they don't allow you to alter things like method 
lookup algorithms etc. Very few, if any, statically typed languages 
support meta programming in a full sense.

Alan G.


From hokkakada at khmeros.info  Fri Jul 14 09:21:45 2006
From: hokkakada at khmeros.info (kakada)
Date: Fri, 14 Jul 2006 14:21:45 +0700
Subject: [Tutor] error when installing sip-4.4.5
Message-ID: <44B74609.50802@khmeros.info>

Hello list,

I am on the way of learning QT design.
I need to have pyQT installed. In the meanwhile, It needs sip-4.4.5
before proceed.
I went across with the steps:
python configure.py ...........ok
make

In this step, I got alot of errors as follow and some more:

siplib.c: In function ?sipGetAddress?:
siplib.c:4473: error: ?sipWrapper? has no member named ?flags?
siplib.c:4474: error: ?sipWrapper? has no member named ?u?
siplib.c:4476: error: ?sipWrapper? has no member named ?flags?
siplib.c:4477: error: ?sipWrapper? has no member named ?u?
siplib.c:4479: error: ?sipWrapper? has no member named ?u?

I try to search for sip in yast, and try to install all relevant
package, still I got the same error.
Could any body can help me, please?

Thanks,
da


From sanelson at gmail.com  Fri Jul 14 11:02:38 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 14 Jul 2006 10:02:38 +0100
Subject: [Tutor] Regular Expression Misunderstanding
Message-ID: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>

Hello,

I am reading the "Regular Expression HOWTO" at
http://www.amk.ca/python/howto/regex/

I am at the bit where "greediness" is discussed with respect to
metacharacters enabling repetition of sections of a RE.  I understand
the concept.

The author gives a step by step example of how the matching engine
goes through the RE step by step, and when the repitition
metacharacter appears it tries the maximum first, and then effectively
reels back until the last step of the RE will pass.

This made sense after a bit of time with pen and paper.

What I don't understand is how in the end the RE *does* actually match
- which may indicate a serious misunderstanding on my part.

>>> re.match("a[bcd]*b", "abcbd")
<_sre.SRE_Match object at 0x186b7b10>

I don't see how abcbd matches! It ends with a d and the RE states it
should end with a b!

What am I missing?

S.

From matthew at CuneiformSoftware.com  Fri Jul 14 11:11:19 2006
From: matthew at CuneiformSoftware.com (Matthew Webber)
Date: Fri, 14 Jul 2006 10:11:19 +0100
Subject: [Tutor] Python Programming Books
In-Reply-To: <001001c6a705$26a5c130$8b4a6244@valued61da873e>
Message-ID: <000b01c6a725$7830a400$0200a8c0@kookaburra>

It depends a lot on what your prior programming experience in other
languages is.

I have a large amount of prior programming experience, and I found "Learning
Python" very good. The "Python Cookbook" (Martelli et. al., also O'Reilly)
is very useful for learning the idioms.
 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Grady Henry
Sent: 14 July 2006 06:20
To: tutor at python.org
Subject: [Tutor] Python Programming Books

I have three books on Python programming, "Learning Python" by O'Reilly, 
"Beginning Python" by Hetland, and "Python in a Nutshell" by O'Reilly.  Are 
these good (recommended) books?  Any others that might be recommended? 



From john at fouhy.net  Fri Jul 14 11:15:44 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 14 Jul 2006 21:15:44 +1200
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>
Message-ID: <5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>

On 14/07/06, Steve Nelson <sanelson at gmail.com> wrote:
> What I don't understand is how in the end the RE *does* actually match
> - which may indicate a serious misunderstanding on my part.
>
> >>> re.match("a[bcd]*b", "abcbd")
> <_sre.SRE_Match object at 0x186b7b10>
>
> I don't see how abcbd matches! It ends with a d and the RE states it
> should end with a b!
>
> What am I missing?

It doesn't have to match the _whole_ string.

[bcd]* will match, amongst other things, the empty string (ie: 0
repetitions of either a b, a c, or a d).  So "a[bcd]*b" will match
"ab", which is in the string abcbd.

It will also match "abcb", which is the longest match, and thus
probably the one it found.

If you look at the match object returned, you should se that the match
starts at position 0 and is four characters long.

Now, if you asked for "a[bcd]*b$", that would be a different matter!

HTH :-)

-- 
John.

From sanelson at gmail.com  Fri Jul 14 12:03:52 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 14 Jul 2006 11:03:52 +0100
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>
	<5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>
Message-ID: <b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>

On 7/14/06, John Fouhy <john at fouhy.net> wrote:

> It doesn't have to match the _whole_ string.

Ah right - yes, so it doesn't say that it has to end with a b - as per
your comment about ending with $.

> If you look at the match object returned, you should se that the match
> starts at position 0 and is four characters long.

How does one query a match object in this way?  I am learning by
fiddling interactively.

> John.

S.

From janos.juhasz at VELUX.com  Fri Jul 14 12:12:42 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Fri, 14 Jul 2006 12:12:42 +0200
Subject: [Tutor] Help with strings and lists.
In-Reply-To: <mailman.30432.1152868546.27774.tutor@python.org>
Message-ID: <OFB413F236.A7BCF1CE-ONC12571AB.0036011C-C12571AB.0038186F@velux.com>

Dear Alan,

Probably you will be interested about list comprehension and zip(), as it 
can simplify all the similar tasks.

>>> s = ('Monday 7373 3663657 2272 547757699 reached 100%','Tuesday 
7726347 552 766463 2253 under-achieved 0%','Wednesday 9899898 8488947 6472 
77449 reached 100%','Thursday 636648 553 22344 5699 under-achieved 
0%','Friday 997 3647757 78736632 357599 over-achieved 200%')
>>> # I made a table from your list
>>> table = [line.split() for line in s]
>>> # it is possible to transpose the table
>>> transposed = zip(*(table))
>>> transposed
[('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'), ('7373', 
'7726347', '9899898', '636648', '997'), ('3663657', '552', '8488947', 
'553', '3647757'), ('2272', '766463', '6472', '22344', '78736632'), 
('547757699', '2253', '77449', '5699', '357599'), ('reached', 
'under-achieved', 'reached', 'under-achieved', 'over-achieved'), ('100%', 
'0%', '100%', '0%', '200%')]
>>> # calc the max(len(str(cell))) for each row,
>>> # that means columns in the original table
>>> maxWidths = [max([len(str(cell)) for cell in column]) for column in 
transposed]
>>> maxWidths
[9, 7, 7, 8, 9, 14, 4]
>>> # format it
>>> [ str.ljust(str(field),w) for (field, w) in zip(table[0], maxWidths)]
['Monday   ', '7373   ', '3663657', '2272    ', '547757699', 'reached  ', 
'100%']
>>> # join it to give a line
>>> '|'.join([ str.ljust(str(field),w) for (field, w) in zip(table[0], 
maxWidths)])
'Monday   |7373   |3663657|2272    |547757699|reached       |100%'
>>> # it can be made for all of the lines
>>> '\n'.join(['|'.join([ str.ljust(str(field),w) for (field, w) in 
zip(line, maxWidths)]) for line in table])
'Monday   |7373   |3663657|2272    |547757699|reached       |100%\nTuesday 
 |7726347|552    |766463  |2253     |under-achieved|0% 
\nWednesday|9899898|8488947|6472    |77449    |reached |100%\nThursday 
|636648 |553    |22344   |5699     |under-achieved|0%  \nFriday   |997 
|3647757|78736632|357599   |over-achieved |200%'
>>> # and can be printed in this form
>>> print '\n'.join(['|'.join([ str.ljust(str(field),w) for (field, w) in 
zip(line, maxWidths)]) for line in table])
Monday   |7373   |3663657|2272    |547757699|reached       |100%
Tuesday  |7726347|552    |766463  |2253     |under-achieved|0% 
Wednesday|9899898|8488947|6472    |77449    |reached       |100%
Thursday |636648 |553    |22344   |5699     |under-achieved|0% 
Friday   |997    |3647757|78736632|357599   |over-achieved |200%
>>> 

I know it is a different way of thinking, but it works well with python.
It is the functional way instead of your procedural one.

> Hi,

> I do a far bit of data manipulation and decided to try one of my
> favourite utilities in Python. I'd really appreciate some optimization
> of the script. I'm sure that I've missed many tricks in even this short
> script.

> Let's say you have a file with this data:

> Monday 7373 3663657 2272 547757699 reached 100%
> Tuesday 7726347 552 766463 2253 under-achieved 0%
> Wednesday 9899898 8488947 6472 77449 reached 100%
> Thursday 636648 553 22344 5699 under-achieved 0%
> Friday 997 3647757 78736632 357599 over-achieved 200%

> You now want columns 1, 5, and 7 printed and aligned (much like a
> spreadsheet). For example:

> Monday    547757699 100%
> Wednesday     77449 100%
> ...

> This script does the job, but I reckon there are better ways.  In the
> interests of brevity, I have dropped the command-line argument handling
> and hard-coded the columns for the test and I hard-coded the input file
> name.


> Any help greatly appreciated.
> Regards,
> Alan.

Best Regards,
J?nos Juh?sz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060714/690ab168/attachment.htm 

From devayani.barve at gmail.com  Fri Jul 14 12:32:38 2006
From: devayani.barve at gmail.com (devayani barve)
Date: Fri, 14 Jul 2006 16:02:38 +0530
Subject: [Tutor] I cant find link
Message-ID: <301929340607140332o5dd6ab25xa45bfc0b26ccf6a2@mail.gmail.com>

Hi
I'm a begginner in python,tried the link pythonchallenge.com solved the
first level, but i dont know how to go to the next one.
Can somebody tell me how?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060714/fa1ce4dd/attachment.html 

From kent37 at tds.net  Fri Jul 14 12:44:42 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 06:44:42 -0400
Subject: [Tutor] digging more into metaclasses
In-Reply-To: <20060713203238.81694.qmail@web55911.mail.re3.yahoo.com>
References: <20060713203238.81694.qmail@web55911.mail.re3.yahoo.com>
Message-ID: <44B7759A.10105@tds.net>

anil maran wrote:
> hi guys
>
> are metaclasses like templates in C++

No. Templates are a way to make generic functions that will work with a 
variety of types of data. Because Python is dynamically typed, all 
functions are generic in this sense and templates are not needed.

See http://en.wikipedia.org/wiki/Duck_typing

Kent


From kent37 at tds.net  Fri Jul 14 12:50:14 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 06:50:14 -0400
Subject: [Tutor] hi
In-Reply-To: <20060713202138.83171.qmail@web55904.mail.re3.yahoo.com>
References: <20060713202138.83171.qmail@web55904.mail.re3.yahoo.com>
Message-ID: <44B776E6.6040703@tds.net>

anil maran wrote:
> hi you wonderful energetic pygurus
> i need to send out lot of emails and sms messages from a python program
> please let me know if you know of any library like java sms library or 
> possible solutions
smtplib will help with sending emails. I hope they are not spam!

Kent


From kent37 at tds.net  Fri Jul 14 12:50:57 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 06:50:57 -0400
Subject: [Tutor] I cant find link
In-Reply-To: <301929340607140332o5dd6ab25xa45bfc0b26ccf6a2@mail.gmail.com>
References: <301929340607140332o5dd6ab25xa45bfc0b26ccf6a2@mail.gmail.com>
Message-ID: <44B77711.9060008@tds.net>

devayani barve wrote:
> Hi
> I'm a begginner in python,tried the link pythonchallenge.com 
> <http://pythonchallenge.com/> solved the first level, but i dont know 
> how to go to the next one.
> Can somebody tell me how?
In general the answer to one challenge becomes part of the URL for the next.

Kent


From kent37 at tds.net  Fri Jul 14 12:55:17 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 06:55:17 -0400
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>	<5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>
	<b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>
Message-ID: <44B77815.2090002@tds.net>

Steve Nelson wrote:
> On 7/14/06, John Fouhy <john at fouhy.net> wrote:
>
>   
>> It doesn't have to match the _whole_ string.
>>     
>
> Ah right - yes, so it doesn't say that it has to end with a b - as per
> your comment about ending with $.
>   
The matched portion must end with b, but it doesn't have to coincide 
with the end of the string. The whole regex must be used for it to 
match; the whole string does not have to be used - the matched portion 
can be a substring.
>   
>> If you look at the match object returned, you should se that the match
>> starts at position 0 and is four characters long.
>>     
>
> How does one query a match object in this way?  I am learning by
> fiddling interactively.
The docs for match objects are here:
http://docs.python.org/lib/match-objects.html

match.start() and match.end() will tell you where it matched.

You might like to try the regex demo that comes with Python; on Windows 
it is installed at C:\Python24\Tools\Scripts\redemo.py. It gives you an 
easy way to experiment with regexes.

Kent


From john at fouhy.net  Fri Jul 14 12:57:38 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 14 Jul 2006 22:57:38 +1200
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>
	<5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>
	<b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>
Message-ID: <5e58f2e40607140357s7d413433y62ea83b95986a748@mail.gmail.com>

On 14/07/06, Steve Nelson <sanelson at gmail.com> wrote:
> How does one query a match object in this way?  I am learning by
> fiddling interactively.

If you're fiddling interactively, try the dir() command --

ie:

>>> m = re.match(...)
>>> dir(m)

It will tell you what attributes the match object has.

Or you can read the documentation --- a combination of both approaches
usually works quite well :-)

-- 
John.

From kent37 at tds.net  Fri Jul 14 13:08:56 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 07:08:56 -0400
Subject: [Tutor] Help with strings and lists.
In-Reply-To: <44B6F0CC.20201@telkomsa.net>
References: <44B6F0CC.20201@telkomsa.net>
Message-ID: <44B77B48.5050707@tds.net>

Alan Collins wrote:
> Hi,
>
> I do a far bit of data manipulation and decided to try one of my 
> favourite utilities in Python. I'd really appreciate some optimization 
> of the script. I'm sure that I've missed many tricks in even this short 
> script.
>
> Let's say you have a file with this data:
>
> Monday 7373 3663657 2272 547757699 reached 100%
> Tuesday 7726347 552 766463 2253 under-achieved 0%
> Wednesday 9899898 8488947 6472 77449 reached 100%
> Thursday 636648 553 22344 5699 under-achieved 0%
> Friday 997 3647757 78736632 357599 over-achieved 200%
>
> You now want columns 1, 5, and 7 printed and aligned (much like a 
> spreadsheet). For example:
>
> Monday    547757699 100%
> Wednesday     77449 100%
> ...
>
> This script does the job, but I reckon there are better ways.  In the 
> interests of brevity, I have dropped the command-line argument handling 
> and hard-coded the columns for the test and I hard-coded the input file 
> name.
>   
You might like to see how it is done in this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662
> -------------------------------------------------------
> """
> PrintColumns
>
> Print specified columns, alignment based on data type.
>
> The script works by parsing the input file twice.  The first pass gets 
> the maximum length of
> all values on the columns.  This value is used to pad the column on the 
> second pass.
>
> """
> import sys
>
> columns = [0]     # hard-code the columns to be printed.
> colwidth = [0]          # list into which the maximum field lenths will 
> be stored.
>
> """
> This part is clunky.  Can't think of another way to do it without making 
> the script
> somewhat longer and slower. What it does is that if the user specifies 
> column 0, all
> columns will be printed.  This bit builds up the list of columns, from 1 
> to 100.
> """
>
> if columns[0] == 0:
>      columns = [1]
>      while len(columns) < 100:
>          columns.append(len(columns)+1)
>   
columns = range(1, 100)
> """
> First pass.  Read all lines and determine the maximum width of each 
> selected column.
> """
> infile = file("mylist", "r")
> indata = infile.readlines()
> for myline in indata:
>      mycolumns = myline.split()
>      colindex = 0
>      for column in columns:
>          if column <= len(mycolumns):
>              if len(colwidth)-1 < colindex:
>                  colwidth.append(len(mycolumns[column-1]))
>              else:
>                  if colwidth[colindex] < len(mycolumns[column-1]):
>                      colwidth[colindex] = len(mycolumns[column-1])
>          colindex += 1
> infile.close()
>
> """
> Second pass. Read all lines and print the selected columns.  Text values 
> are left
> justified, while numeric values are right justified.
> """
> infile = file("mylist", "r")
> indata = infile.readlines()
>   
No need to read the file again, you still have indata.
> for myline in indata:
>      mycolumns = myline.split()
>      colindex = 0
>      for column in columns:
>          if column <= len(mycolumns):
>              if mycolumns[column-1].isdigit():
>                  x = mycolumns[column-1].rjust(colwidth[colindex]) + ' '
>              else:
>                  x = mycolumns[column-1].ljust(colwidth[colindex]+1)
>              print x,
>          colindex += 1
>      print ""
> infile.close()
>   
Hmm...you really should make columns be the correct length. If you use a 
list comp to make colwidth then you can just make columns the same 
length as colwidth. Then if you make a helper function for the formatting
def format(value, width):
  if value.isdigit():
     return value.rjust(width) + ' '
  else:
     return value.ljust(width)

Now the formatting becomes
  values = [ format(column[i], colwidth[i] for i in columns ]
which you print with
  print ''.join(values)

Kent

> -------------------------------------------------------
>
> Any help greatly appreciated.
> Regards,
> Alan.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From sanelson at gmail.com  Fri Jul 14 15:02:42 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 14 Jul 2006 14:02:42 +0100
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <5e58f2e40607140357s7d413433y62ea83b95986a748@mail.gmail.com>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>
	<5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>
	<b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>
	<5e58f2e40607140357s7d413433y62ea83b95986a748@mail.gmail.com>
Message-ID: <b6131fdc0607140602i4a81c6aeg23fd0b6c0aa39412@mail.gmail.com>

On 7/14/06, John Fouhy <john at fouhy.net> wrote:

> >>> m = re.match(...)
> >>> dir(m)
>
> It will tell you what attributes the match object has.

Useful - thank you.

I am now confuse on this:

I have a file full of lines beginning with the letter "b".  I want a
RE that will return the whole line if it begins with b.

I find if I do eg:

>>> m = re.search("^b", "b spam spam spam")
>>> m.group()
'b'

How do I get it to return the whole line if it begins with a b?

S.

From kent37 at tds.net  Fri Jul 14 15:09:48 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 09:09:48 -0400
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <b6131fdc0607140602i4a81c6aeg23fd0b6c0aa39412@mail.gmail.com>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>	<5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>	<b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>	<5e58f2e40607140357s7d413433y62ea83b95986a748@mail.gmail.com>
	<b6131fdc0607140602i4a81c6aeg23fd0b6c0aa39412@mail.gmail.com>
Message-ID: <44B7979C.9010801@tds.net>

Steve Nelson wrote:
> On 7/14/06, John Fouhy <john at fouhy.net> wrote:
>
>   
>>>>> m = re.match(...)
>>>>> dir(m)
>>>>>           
>> It will tell you what attributes the match object has.
>>     
>
> Useful - thank you.
>
> I am now confuse on this:
>
> I have a file full of lines beginning with the letter "b".  I want a
> RE that will return the whole line if it begins with b.
>
> I find if I do eg:
>
>   
>>>> m = re.search("^b", "b spam spam spam")
>>>> m.group()
>>>>         
> 'b'
>
> How do I get it to return the whole line if it begins with a b?
Use the match object in a test. If the search fails it will return None 
which tests false:

for line in lines:
  m = re.search(...)
  if m:
    # do something with line that matches

But for this particular application you might as well use 
line.startswith('b') instead of a regex.

Kent


From rabidpoobear at gmail.com  Fri Jul 14 15:10:09 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 14 Jul 2006 08:10:09 -0500
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <b6131fdc0607140602i4a81c6aeg23fd0b6c0aa39412@mail.gmail.com>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>	<5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>	<b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>	<5e58f2e40607140357s7d413433y62ea83b95986a748@mail.gmail.com>
	<b6131fdc0607140602i4a81c6aeg23fd0b6c0aa39412@mail.gmail.com>
Message-ID: <44B797B1.4040609@gmail.com>


> I have a file full of lines beginning with the letter "b".  I want a
> RE that will return the whole line if it begins with b.
>
> I find if I do eg:
>
>   
>>>> m = re.search("^b", "b spam spam spam")
>>>> m.group()
>>>>         
> 'b'
>
> How do I get it to return the whole line if it begins with a b?
>
> S.
for line in file:
    if line.strip()[0] == 'b':
       print line

or
print [a for a in file if a.strip()[0] == b]
if you want to use list comprehension.
As for the RE way, I've no idea.

From sanelson at gmail.com  Fri Jul 14 15:24:06 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 14 Jul 2006 14:24:06 +0100
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <44B7979C.9010801@tds.net>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>
	<5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>
	<b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>
	<5e58f2e40607140357s7d413433y62ea83b95986a748@mail.gmail.com>
	<b6131fdc0607140602i4a81c6aeg23fd0b6c0aa39412@mail.gmail.com>
	<44B7979C.9010801@tds.net>
Message-ID: <b6131fdc0607140624m1ed7583bse6792161aaad9bbc@mail.gmail.com>

On 7/14/06, Kent Johnson <kent37 at tds.net> wrote:

> But for this particular application you might as well use
> line.startswith('b') instead of a regex.

Ah yes, that makes sense.

Incidentally continuing my reading of the HOWTO I have sat and puzzled
for about 30 mins on the difference the MULTILINE flag makes.  I can't
quite see the difference.  I *think* it is as follows:

Under normal circumstances, ^ matches the start of a line, only.  On a
line by line basis.

With the re.M flag, we get a match after *any* newline?

Similarly with $ - under normal circumstances, $ matches the end of
the string, or that which precedes a newline.

With the MULTILINE flag, $ matches before *any* newline?

Is this correct?

> Kent

S.

From devayani.barve at gmail.com  Fri Jul 14 15:30:14 2006
From: devayani.barve at gmail.com (devayani barve)
Date: Fri, 14 Jul 2006 19:00:14 +0530
Subject: [Tutor] I cant find link
In-Reply-To: <7e3eab2c0607140620y76eba092g357c2de7881b6325@mail.gmail.com>
References: <301929340607140332o5dd6ab25xa45bfc0b26ccf6a2@mail.gmail.com>
	<44B77711.9060008@tds.net>
	<7e3eab2c0607140619p2cd7718atcafaf8ef885d30e3@mail.gmail.com>
	<7e3eab2c0607140620y76eba092g357c2de7881b6325@mail.gmail.com>
Message-ID: <301929340607140630l3d9b3d46rdfeb055dc24844a8@mail.gmail.com>

On 7/14/06, Jason Massey <jason.massey at gmail.com> wrote:
>
> Devayani,
>
> What answer did you get?  One of the things to rember on the challenge is
> to take your answer and put ".html" (no qutoes) on the end of it in the url.
>
> So for the first problem the url would be:
>
> http://www.pythonchallenge.com/pc/def/ <your answer>.html
>
>
>
> On 7/14/06, Jason Massey <jason.massey at gmail.com > wrote:
> >
> > Devayani,
> >
> > What answer did you get?  One of the things to rember on the challengeis to take your answer and put ".html" (no qutoes) on the end of it in the
> > url.
> >
> > So for the first problem the url would be:
> >
> > http://www.pythonchallenge.com/pc/def/ <your answer>.html
> >
>
>
>
> On 7/14/06, Kent Johnson < kent37 at tds.net> wrote:
> >
> > devayani barve wrote:
> > > Hi
> > > I'm a begginner in python,tried the link pythonchallenge.com
> > > <http://pythonchallenge.com/ > solved the first level, but i dont know
> > > how to go to the next one.
> > > Can somebody tell me how?
> > In general the answer to one challenge becomes part of the URL for the
> > next.
> >
> > Kent
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
>

Thanks to all
Regarding the pythonchallenge.com,
finally got the hang of it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060714/4ba2e7d1/attachment.html 

From kent37 at tds.net  Fri Jul 14 15:35:26 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 09:35:26 -0400
Subject: [Tutor] Regular Expression Misunderstanding
In-Reply-To: <b6131fdc0607140624m1ed7583bse6792161aaad9bbc@mail.gmail.com>
References: <b6131fdc0607140202v27a9e666ga9cd64bb6ee10574@mail.gmail.com>	
	<5e58f2e40607140215k1fbb5c89pc6c33fbdca34895a@mail.gmail.com>	
	<b6131fdc0607140303ib3629bdxa2d551abe8d07676@mail.gmail.com>	
	<5e58f2e40607140357s7d413433y62ea83b95986a748@mail.gmail.com>	
	<b6131fdc0607140602i4a81c6aeg23fd0b6c0aa39412@mail.gmail.com>	
	<44B7979C.9010801@tds.net>
	<b6131fdc0607140624m1ed7583bse6792161aaad9bbc@mail.gmail.com>
Message-ID: <44B79D9E.2000707@tds.net>

Steve Nelson wrote:
> Incidentally continuing my reading of the HOWTO I have sat and puzzled
> for about 30 mins on the difference the MULTILINE flag makes.  I can't
> quite see the difference.  I *think* it is as follows:
>
> Under normal circumstances, ^ matches the start of a line, only.  On a
> line by line basis.
>
> With the re.M flag, we get a match after *any* newline?
>
> Similarly with $ - under normal circumstances, $ matches the end of
> the string, or that which precedes a newline.
>
> With the MULTILINE flag, $ matches before *any* newline?
>
> Is this correct?
I'm not sure, I think you are a little confused. MULTILINE only matters 
if the string you are matching contains newlines. Without MULTILINE, ^ 
will match only at the beginning of the string. With it, ^ will match 
after any newline. For example,
In [1]: import re

A string  containing two lines:
In [2]: s='one\ntwo'

The first line matches without MULTILINE:
In [3]: re.search('^one', s)
Out[3]: <_sre.SRE_Match object at 0x00C3E640>

The second one does not (result of the search is None so nothing prints):
In [4]: re.search('^two', s)

With MULTILINE ^two will match:
In [5]: re.search('^two', s, re.MULTILINE)
Out[5]: <_sre.SRE_Match object at 0x00E901E0>

Kent


From emily.fortuna at nist.gov  Fri Jul 14 17:10:52 2006
From: emily.fortuna at nist.gov (Emily Fortuna)
Date: Fri, 14 Jul 2006 11:10:52 -0400
Subject: [Tutor] dynamically executing a statement
Message-ID: <44B7B3FC.4010107@nist.gov>

Hello all,
I am writing a function in which (in its simplified form) I am trying to 
return a list of a specified attribute, given a list of objects.  It is 
best if I write some hypothetical code to explain:
class foo:
	def __init__(self, name, data):
		self.name = name
		self.data = data

def getAttrs(fooObjs, attr):
	return map(lambda item: eval('%s.%s' % (item, attr)), fooObjs)

f = foo('oscar', 'green')
g = foo('bert', 'yellow')
e = foo('ernie', 'orange')
list = [f, e, g]
getNames(list, 'name')
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 2, in getNames
   File "<interactive input>", line 2, in <lambda>
   File "<string>", line 1
     <__main__.foo instance at 0x00F358F0>.name
     ^
SyntaxError: invalid syntax

It seems to me like the issue is that Python is converting my object to 
a string representation before attempting to evaluate the expression. 
However, when I looked at the documenation 
[http://docs.python.org/lib/typesseq-strings.html] (thanks from earlier 
post today), I couldn't find anything that would allow python to 
reference the object itself in a string.  Is there a way (or a different 
method entirely) to do this?
Your help is very much appreciated,
Emily


From mistobaan at gmail.com  Fri Jul 14 18:29:37 2006
From: mistobaan at gmail.com (Fabrizio Milo aka misto)
Date: Fri, 14 Jul 2006 18:29:37 +0200
Subject: [Tutor] dynamically executing a statement
In-Reply-To: <44B7B3FC.4010107@nist.gov>
References: <44B7B3FC.4010107@nist.gov>
Message-ID: <e437f2f0607140929k5697a5e8k1946ce6af78e658e@mail.gmail.com>

Did you considered getattr?

> def getAttrs(fooObjs, attr):
>         return map(lambda item: getattr(item, attr), fooObjs)

From kent37 at tds.net  Fri Jul 14 19:05:57 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 13:05:57 -0400
Subject: [Tutor] dynamically executing a statement
In-Reply-To: <44B7B3FC.4010107@nist.gov>
References: <44B7B3FC.4010107@nist.gov>
Message-ID: <44B7CEF5.9070608@tds.net>

Emily Fortuna wrote:
> Hello all,
> I am writing a function in which (in its simplified form) I am trying to 
> return a list of a specified attribute, given a list of objects.  It is 
> best if I write some hypothetical code to explain:
> class foo:
> 	def __init__(self, name, data):
> 		self.name = name
> 		self.data = data
>
> def getAttrs(fooObjs, attr):
> 	return map(lambda item: eval('%s.%s' % (item, attr)), fooObjs)
>
> f = foo('oscar', 'green')
> g = foo('bert', 'yellow')
> e = foo('ernie', 'orange')
> list = [f, e, g]
> getNames(list, 'name')
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
>    File "<interactive input>", line 2, in getNames
>    File "<interactive input>", line 2, in <lambda>
>    File "<string>", line 1
>      <__main__.foo instance at 0x00F358F0>.name
>      ^
> SyntaxError: invalid syntax
>
> It seems to me like the issue is that Python is converting my object to 
> a string representation before attempting to evaluate the expression. 
>   
Yes, that is correct. When you execute
'%s' % f
you get a string containing a string representation of f. It doesn't 
really make sense (to me, anyway) to talk about referencing "the object 
itself" in a string - a string can't contain a reference, it is just text.

You would have to make a list of *names* for your solution to work, e.g.
list = ['f', 'g', 'e']
Then the eval would be something like eval('f.name') which would work.

But in general it's better to use Python's built-in introspection for 
something like this. Fabrizio has shown one way. I would use a list 
comprehension instead of map and lambda:
def getAttrs(fooObjs, attr):
         return [getattr(item, attr) for item in fooObjs]

(Docs for getattr() and other handy built-in functions are here: 
http://docs.python.org/lib/built-in-funcs.html)

Kent
> However, when I looked at the documenation 
> [http://docs.python.org/lib/typesseq-strings.html] (thanks from earlier 
> post today), I couldn't find anything that would allow python to 
> reference the object itself in a string.  Is there a way (or a different 
> method entirely) to do this?
> Your help is very much appreciated,
> Emily
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From Barry.Carroll at psc.com  Fri Jul 14 19:10:37 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 14 Jul 2006 10:10:37 -0700
Subject: [Tutor] Python Programming Books
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36DD@eugsrv400.psc.pscnet.com>

Greetings:

Like Matthew, I have a been programming for several years, mostly in
C-like languages and various assembly languages.  I started using Python
about two years ago. "Learning Python" is my text book; "Python in a
Nutshell" is my language reference.  Both are excellent.  I use one or
both nearly every day.  I haven't used the "Python Cookbook" much.  

For those learning to program with Python as their language, I recommend
Alan Gauld's online guide "Learning to Program":

     http://www.freenetpages.co.uk/hp/alan.gauld/

It is well written and easy to follow.  For those who like to read hard
copy, you can download a pdf version of the guide

     http://www.freenetpages.co.uk/hp/alan.gauld/tutor.pdf

and print it out.  

Best of luck.  

Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


> ------------------------------
> Date: Fri, 14 Jul 2006 10:11:19 +0100
> From: "Matthew Webber" <matthew at CuneiformSoftware.com>
> Subject: Re: [Tutor] Python Programming Books
> To: "'Grady Henry'" <gwhjr at cox.net>, <tutor at python.org>
> Message-ID: <000b01c6a725$7830a400$0200a8c0 at kookaburra>
> Content-Type: text/plain;	charset="us-ascii"
> 
> It depends a lot on what your prior programming experience in other
> languages is.
> 
> I have a large amount of prior programming experience, and I found
> "Learning
> Python" very good. The "Python Cookbook" (Martelli et. al., also
O'Reilly)
> is very useful for learning the idioms.
> 
> 
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf
> Of Grady Henry
> Sent: 14 July 2006 06:20
> To: tutor at python.org
> Subject: [Tutor] Python Programming Books
> 
> I have three books on Python programming, "Learning Python" by
O'Reilly,
> "Beginning Python" by Hetland, and "Python in a Nutshell" by O'Reilly.
> Are
> these good (recommended) books?  Any others that might be recommended?
> 


From carroll at tjc.com  Fri Jul 14 19:36:51 2006
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 14 Jul 2006 10:36:51 -0700 (PDT)
Subject: [Tutor] Python Programming Books
In-Reply-To: <001001c6a705$26a5c130$8b4a6244@valued61da873e>
Message-ID: <Pine.LNX.4.44.0607141031290.17874-100000@violet.rahul.net>

On Thu, 13 Jul 2006, Grady Henry wrote:

> I have three books on Python programming, "Learning Python" by O'Reilly,
> "Beginning Python" by Hetland, and "Python in a Nutshell" by O'Reilly.  
> Are these good (recommended) books?  Any others that might be
> recommended?

I don't know the Hetland book.

I think a book-based approach (which is my favorite approach) to starting 
off in Python requires two books: one to introduce you to the language, 
and one to serve as a reference once your feet are wet.  "Learning Python" 
is an excellent book for the former, and "Python in a Nutshell" is an 
excellent book for the latter.  They're actually my favorites for those 
purposes, although there are certainly others.

I'd go with those for a while and wait until you find your curiosity
taking you into a particular area, whether it's database, Jython, GUI,
XML, patterns, or whatever, and then either get an appropriate book for
where your interests take you, or meybe pick up the Cookbook, which is an
excellent book for browsing and stimulating ideas.


From andre.roberge at gmail.com  Fri Jul 14 19:48:35 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Fri, 14 Jul 2006 14:48:35 -0300
Subject: [Tutor] Python Programming Books
In-Reply-To: <Pine.LNX.4.44.0607141031290.17874-100000@violet.rahul.net>
References: <001001c6a705$26a5c130$8b4a6244@valued61da873e>
	<Pine.LNX.4.44.0607141031290.17874-100000@violet.rahul.net>
Message-ID: <7528bcdd0607141048s63208c2ake6321f0f792d0ed2@mail.gmail.com>

On 7/14/06, Terry Carroll <carroll at tjc.com> wrote:
> On Thu, 13 Jul 2006, Grady Henry wrote:
>
> > I have three books on Python programming, "Learning Python" by O'Reilly,
> > "Beginning Python" by Hetland, and "Python in a Nutshell" by O'Reilly.
> > Are these good (recommended) books?  Any others that might be
> > recommended?
>
> I don't know the Hetland book.

I have about 10 Python books including the three books listed above.
Of all the books I own, my first recommendation would be to start with
Hetland's book, which I much prefer over "Learning Python".  "Python
in a Nutshell" is my favourite reference book and I find the "Python
Cookbook" to be a great reference to learn advanced stuff from.

Andr?

From online330983 at telkomsa.net  Fri Jul 14 19:24:59 2006
From: online330983 at telkomsa.net (Alan Collins)
Date: Fri, 14 Jul 2006 19:24:59 +0200
Subject: [Tutor] Help with strings and lists.
Message-ID: <44B7D36B.5070302@telkomsa.net>

> Date: Fri, 14 Jul 2006 16:43:32 +1200
> From: "John Fouhy" <john at fouhy.net>
>
> Let me attempt to be the first to say:
>
> String substitutions!!!
>
> The docs are here: http://docs.python.org/lib/typesseq-strings.html
>
<snip>

Thanks John, that looks way better. I'll also check out the page.

Alan.


From online330983 at telkomsa.net  Fri Jul 14 19:36:01 2006
From: online330983 at telkomsa.net (Alan Collins)
Date: Fri, 14 Jul 2006 19:36:01 +0200
Subject: [Tutor] Help with strings and lists
In-Reply-To: <mailman.30443.1152875344.27774.tutor@python.org>
References: <mailman.30443.1152875344.27774.tutor@python.org>
Message-ID: <44B7D601.70405@telkomsa.net>


> Date: Fri, 14 Jul 2006 12:12:42 +0200
> From: J?nos Juh?sz <janos.juhasz at VELUX.com>
> Subject: [Tutor] Help with strings and lists.
> To: <online330983 at telkomsa.net>, tutor at python.org
> Message-ID:
> 	<OFB413F236.A7BCF1CE-ONC12571AB.0036011C-C12571AB.0038186F at velux.com>
> Content-Type: text/plain; charset="iso-8859-2"
> 
> Dear Alan,
> 
> Probably you will be interested about list comprehension and zip(), as it 
> can simplify all the similar tasks.
> 
<snip>

Hi Janos,

What a sexy piece of code! Oh man, I have a lot to learn.

The code didn't justify as required, so I combined your code with 
something from Kent. The code is now:

def format (value, width):
     if value.isdigit():
         return value.rjust(width) + ' '
     else:
         return value.ljust(width)

s = ('Monday 7373 3663657 2272 547757699 reached 100%',
'Tuesday 7726347 552 766463 2253 under-achieved 0%',
'Wednesday 9899898 8488947 6472 77449 reached 100%',
'Thursday 636648 553 22344 5699 under-achieved 0%',
'Friday 997 3647757 78736632 357599 over-achieved 200%')

table = [line.split() for line in s]
transposed = zip(*(table))
maxWidths = [max([len(str(cell)) for cell in column]) for column in 
transposed]
print '\n'.join([' '.join([ format(field,w) for (field, w) in zip(line, 
maxWidths)]) for line in table])


I noticed that if one line has less items than the rest (i.e. one less 
column), that column is ignored for all lines.  I'll work around that 
somehow.

Thanks, I will stare in wonder at that code for years to come.

From pythontut at pusspaws.net  Fri Jul 14 20:21:07 2006
From: pythontut at pusspaws.net (Dave S)
Date: Fri, 14 Jul 2006 19:21:07 +0100
Subject: [Tutor] Basic QT query
Message-ID: <200607141921.07778.pythontut@pusspaws.net>

Hi all,

I am trying to get to grips with QT, putting a friendly face on some of my 
apps :) Its early days and my first attempt but I expected the following to 
print 'hi it works' every second. 

There problem I am stuck with is ...

The debugged program raised the exception unhandled RuntimeError
"underlying C/C++ object has been deleted" At line 24 

ie "self.timer = self.startTimer(1000)". First of all I did not have an 
assignment ie I just had "self.startTimer(1000)" realising Python would 
garbage collect I added an assignment but still the same problem.

Also I am struggling with "QObject.connect(self.tickerevent, 
PYSIGNAL("ticker"), self.hello)" I am unsure of what the source of the 
connect is - I suspect my guess of self.tickerevent is wrong. The source of 
the event should be PYSIGNAL("ticker") ?

Any ideas or suggestions much appreciated

Cheers

Dave

** MY QT MASTERPIECE :) **


import sys
from qt import *
from frm_livedata import frm


class Ticker(QObject):

	def __init__(self):
		QObject.__init__, (self)
		self.timer = self.startTimer(1000)
		
	def timerEvent(self, ev):
		self.emit(PYSIGNAL("ticker")())
		QObject.connect(self.tickerevent, PYSIGNAL("ticker"), self.hello)

	def hello():
		print 'hi it works'
	
x=Ticker()

if __name__ == '__main__':

	app = QApplication(sys.argv)
	win = frm()
	app.setMainWidget(win)
	win.show()
	QObject.connect(app, SIGNAL('lastWindowClosed()'),app, SLOT('quit()'))
	app.exec_loop()
	
	
	

From wescpy at gmail.com  Fri Jul 14 21:26:04 2006
From: wescpy at gmail.com (wesley chun)
Date: Fri, 14 Jul 2006 12:26:04 -0700
Subject: [Tutor] Python Programming Books
In-Reply-To: <001001c6a705$26a5c130$8b4a6244@valued61da873e>
References: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com>
	<44B71C9C.9010907@gmail.com>
	<001001c6a705$26a5c130$8b4a6244@valued61da873e>
Message-ID: <78b3a9580607141226h5acd44e5y7191efa3f04d1bed@mail.gmail.com>

> I have three books on Python programming, "Learning Python" by O'Reilly,
> "Beginning Python" by Hetland, and "Python in a Nutshell" by O'Reilly.  Are
> these good (recommended) books?  Any others that might be recommended?

Learning is a good book to learn from if you already know C.
Beginning is a good book that is a general high-level introduction to
Python.  finally, Nutshell is a reference book, not a book to "learn"
Python from. if you're looking for references, you may also consider
the excellent Python Essential Reference (Beazley).

if you want to demphasize the C, get more knowledge than just
high-level, want a pseudo-reference, want to learn Python by trying
all kinds of interesting exercises, and can wait a month and a half,
i'm wrapping up the 2nd edition of "Core Python" now.

for more info, click the link below to get to the book's website.
there is also a link to the Reviews page so that you can see all
feedback on the 1st edition.

while it would be a conflict-of-interest for me to give *my* opinion
of the book, it appears to be pretty well-received (mostly by
word-of-mouth) based on comments i've seen so far.  :-)

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From andre.roberge at gmail.com  Fri Jul 14 21:45:53 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Fri, 14 Jul 2006 16:45:53 -0300
Subject: [Tutor] Python Programming Books
In-Reply-To: <78b3a9580607141226h5acd44e5y7191efa3f04d1bed@mail.gmail.com>
References: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com>
	<44B71C9C.9010907@gmail.com>
	<001001c6a705$26a5c130$8b4a6244@valued61da873e>
	<78b3a9580607141226h5acd44e5y7191efa3f04d1bed@mail.gmail.com>
Message-ID: <7528bcdd0607141245p5a52a2c8i86bd6152d5655f0a@mail.gmail.com>

On 7/14/06, wesley chun <wescpy at gmail.com> wrote:
> while it would be a conflict-of-interest for me to give *my* opinion
> of the book, it appears to be pretty well-received (mostly by
> word-of-mouth) based on comments i've seen so far.  :-)
>
I don't know about others, but I think it might be of benefit if you
could give an assessment that would include a description of the
weaknesses of the book (e.g. [making this up] "Core Python" is not the
best beginner's book for people primarily interested in making GUI
based applications or games [Dawson's book is better in that
respect.]) as well as its strengths. It might help us in deciding to
point beginners to it (or not) as a potential choice based on their
interests.

[I could be in a minority opinion here.  People like Kent, Alan,
Danny, etc. should probably comment.]
Andr?

From jhill at maingauche.org  Fri Jul 14 22:00:51 2006
From: jhill at maingauche.org (Jeremiah Hill)
Date: Fri, 14 Jul 2006 16:00:51 -0400
Subject: [Tutor] Mysterious syntax errors and file-reading issues
Message-ID: <a46b7150607141300h7763d1d4r9d8f0ae1b5da06f5@mail.gmail.com>

I'm trying to write a program that will read a text file and return a random
subset of the words contained therein.  (Its purpose is to generate lists of
words for spelling bees.  I'm a teacher.)  Here's what I have so far:

************ CODE STARTS *******************
L1 = []                # create an empty list
L2 = []                # and another one
import os
def exists('/Users/username/Documents/python/word_bank.txt'):
    return os.access('/Users/usernameDocuments/python/word_bank.txt',
os.F_OK)
for line in
open('/Users/username/Documents/python/word_bank.txt').readlines():
L1.append(line)    # empty the word bank into a list
for i in range(len(L1)):    # trim off the newlines
    L1[i] [:-1]
import random
random.shuffle(L1)        # shuffle the words
L1[0:3]

************ CODE ENDS **********************

Two problems have appeared:

1.  I get a "syntax error" message at the line that starts with "def
exists", but I don't see the mistake.

2.  If I take out that line, I get "errno 2" at the next line; the
interpreter seems convinced that that file doesn't exist, though it does.  I
actually tried putting os.path.exists() into the interpreter, and it
returned 'true', but it still doesn't see the file when I try to run this
program.

How can I solve or circumvent these problems?  I appreciate any help, even
hints, but frankly if anyone's willing to explain the solution outright I'd
be grateful.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060714/9d910dd3/attachment.html 

From alan.gauld at freenet.co.uk  Fri Jul 14 23:07:42 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 14 Jul 2006 22:07:42 +0100
Subject: [Tutor] Python Programming Books
References: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com><44B71C9C.9010907@gmail.com><001001c6a705$26a5c130$8b4a6244@valued61da873e><78b3a9580607141226h5acd44e5y7191efa3f04d1bed@mail.gmail.com>
	<7528bcdd0607141245p5a52a2c8i86bd6152d5655f0a@mail.gmail.com>
Message-ID: <007901c6a789$8c60a560$04000100@XPpro>

> I don't know about others, but I think it might be of benefit if you
> could give an assessment that would include a description of the
> weaknesses of the book

> [I could be in a minority opinion here.  People like Kent, Alan,
> Danny, etc. should probably comment.]

I'm no expert since I've only browsed Wesley's book in a store
a few times but it seemed to be solid introductory material and
a fair reference. It gets good reviews from readers.

My only negative comment was that it was a very big book for
its content, mainly because the layout had a biggish font and
a lot of white space. But some folks like that. And I'd definitely
prefer too big a font over too small (cf Beasley's Essential 
Reference,
its just too small for comfort for my ageing eyes)

Alan G.



From alan.gauld at freenet.co.uk  Fri Jul 14 23:13:54 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 14 Jul 2006 22:13:54 +0100
Subject: [Tutor] Mysterious syntax errors and file-reading issues
References: <a46b7150607141300h7763d1d4r9d8f0ae1b5da06f5@mail.gmail.com>
Message-ID: <008501c6a78a$699844b0$04000100@XPpro>

> def exists('/Users/username/Documents/python/word_bank.txt'):
>    return os.access('/Users/usernameDocuments/python/word_bank.txt',

> 1.  I get a "syntax error" message at the line that starts with "def
> exists", but I don't see the mistake.


You are defining a function with a constant as an agument.
You cannot do that you need a variable (technically a parameter)
The parameter can have a default value if you like so:

> def 
> exists(filename='/Users/username/Documents/python/word_bank.txt'):
>    return os.access(filename,



> os.F_OK)
> for line in
> open('/Users/username/Documents/python/word_bank.txt').readlines():

> 2.  If I take out that line, I get "errno 2" at the next line; the
> interpreter seems convinced that that file doesn't exist, though it 
> does.

defining a function is different from executing it. After the 
definition
you still need to call it and check the result.

However usually its good enough just to use a try/except to catch
errors for missing files. In pseudo code like this:

try:
    for line in open(filename):
       process line
except: print ooops couldn't process file!

You only need to use exists() if you really need the detail of why
it failed - maybe with a view to taking corrective action before 
trying
again...

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From pythontut at pusspaws.net  Sat Jul 15 00:21:27 2006
From: pythontut at pusspaws.net (Dave S)
Date: Fri, 14 Jul 2006 23:21:27 +0100
Subject: [Tutor] Basic QT query #2
In-Reply-To: <200607141921.07778.pythontut@pusspaws.net>
References: <200607141921.07778.pythontut@pusspaws.net>
Message-ID: <200607142321.28045.pythontut@pusspaws.net>

On Friday 14 July 2006 19:21, Dave S wrote:
> Hi all,
>
> I am trying to get to grips with QT, putting a friendly face on some of my
> apps :) Its early days and my first attempt but I expected the following to
> print 'hi it works' every second.
>
> There problem I am stuck with is ...
>
> The debugged program raised the exception unhandled RuntimeError
> "underlying C/C++ object has been deleted" At line 24
>
> ie "self.timer = self.startTimer(1000)". First of all I did not have an
> assignment ie I just had "self.startTimer(1000)" realising Python would
> garbage collect I added an assignment but still the same problem.
>
> Also I am struggling with "QObject.connect(self.tickerevent,
> PYSIGNAL("ticker"), self.hello)" I am unsure of what the source of the
> connect is - I suspect my guess of self.tickerevent is wrong. The source of
> the event should be PYSIGNAL("ticker") ?
>
> Any ideas or suggestions much appreciated
>
> Cheers
>
> Dave
>
> ** MY QT MASTERPIECE :) **
>
>
> import sys
> from qt import *
> from frm_livedata import frm
>
>
> class Ticker(QObject):
>
> 	def __init__(self):
> 		QObject.__init__, (self)
> 		self.timer = self.startTimer(1000)
>
> 	def timerEvent(self, ev):
> 		self.emit(PYSIGNAL("ticker")())
> 		QObject.connect(self.tickerevent, PYSIGNAL("ticker"), self.hello)
>
> 	def hello():
> 		print 'hi it works'
>
> x=Ticker()
>
> if __name__ == '__main__':
>
> 	app = QApplication(sys.argv)
> 	win = frm()
> 	app.setMainWidget(win)
> 	win.show()
> 	QObject.connect(app, SIGNAL('lastWindowClosed()'),app, SLOT('quit()'))
> 	app.exec_loop()
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Doh - Sorted it rearranged the defs &  '__init__,' becomes '__init__' its 
always the simple things that eat the hours :) 

I am writting a QT front end displaying some information about my demon 
script 'live_datad.py'. The QT display now comes up (cheer!) but I need a 
couple of things ,,.

First I need to know if if a 'live_datad' is running - Already tried looking 
in modules & os.system('ps ax') no go. I need an equivalent of ps ax | grep 
live_datad.

Second I need to get some simple data from the daemon, no more than 2-3 
strings would do it reflecting the daemons status. I don't want to re-code it 
in classes, or do anything with sockets (they seem way too complex for me) is 
there a more elegant way than the daemon writing its status in an ascii file 
every few seconds and my QT app reading it - or is this an OK way of doing 
it ?

Dave







 

From wescpy at gmail.com  Sat Jul 15 01:08:48 2006
From: wescpy at gmail.com (wesley chun)
Date: Fri, 14 Jul 2006 16:08:48 -0700
Subject: [Tutor] Python Programming Books
In-Reply-To: <007901c6a789$8c60a560$04000100@XPpro>
References: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com>
	<44B71C9C.9010907@gmail.com>
	<001001c6a705$26a5c130$8b4a6244@valued61da873e>
	<78b3a9580607141226h5acd44e5y7191efa3f04d1bed@mail.gmail.com>
	<7528bcdd0607141245p5a52a2c8i86bd6152d5655f0a@mail.gmail.com>
	<007901c6a789$8c60a560$04000100@XPpro>
Message-ID: <78b3a9580607141608l838ba72o2673eceaafdcb84d@mail.gmail.com>

(LONG... you've been warned ;-) )

> > andre wrote:
> >
> > I don't know about others, but I think it might be of benefit if you
> > could give an assessment that would include a description of the
> > weaknesses of the book
>
> I'm no expert since I've only browsed Wesley's book in a store
> a few times but it seemed to be solid introductory material and
> a fair reference. It gets good reviews from readers.
>
> My only negative comment was that it was a very big book for
> its content, mainly because the layout had a biggish font and
> a lot of white space. But some folks like that. And I'd definitely
> prefer too big a font over too small (cf Beasley's Essential
> Reference,
> its just too small for comfort for my ageing eyes)


andre,

good idea.  i should have done this in my earlier post.  Core Python
is definitely targeted at programmers already knowledgeable in one
other high-level language, so it is not the right book for the
absolute beginner and/or those with no programming skills.  the main
goal of the book is to get someone up2speed with Python as quickly and
as deeply as possible, because teaching Python's syntax isn't that
hard, but getting someone to be as *effective* a Python programmer as
possible in the shortest amount of time is the challenge.  (you know
that feeling, after you've just learned a language, where you can sort
of write code in it but doesn't feel like 2nd nature yet?  i want to
shorten that time as well as minimize the number of bugs by teaching
not to write them to begin with.)

as alan has mentioned, the book is rather large and a burden to carry.
 this was partially my fault, and for the second edition, *definitely*
my fault.  let me explain with a short anecdote:

for the 1st ed, the publisher wanted 500 pages, and i said, "what, are
you crazy?  i can't write that much! how about 300?"  they repled with
something to the effect of, "ok, how about 350 and we'll order the
extra thick paper."

so i wrote and wrote, and came up with something around the original
500 pagecount they wanted, but this was plain text and images without
any formatting.  so when they took the manuscript
and reformatted everything to conform to the "Core" series, margins,
logos, paragraph types, etc., it suddenly exploded to 800 pages, and
the thick paper had already been ordered.  so apologies to alan and
everyone for the fact that this book was so thick.

for the 2nd edition, the plan was to split up the book like Core
Java... a Vol1 with the main core material and Vol2 with the advanced
stuff.  the publishers didn't feel there was a market need for
advanced books so they canned my idea.  so now, with every edition, i
will continually add more and more materials until they have no choice
but to split it up.  :-)  so that's why it's my fault for the upcoming
edition.  hopefully the publisher will order then thinner paper this
time.

back to weaknesses...

i want to have full chapters on XML, Win32 programming, XML,
Java/Jython, web frameworks (Django, TuroboGears), content mgmt
systems (Zope, Plone), Embedding Python, web tools (Cheetah,
SQLObject, Kid, Myghty, FormEncode, CherryPy, etc.), Web Services/APIs
(REST, XML, SOAP), other GUIs (wxWidgets, GTK+, KDE/Qt), etc.  but
sadly i don't have the time or expertise to have done all of those
chapters -- this is definitely for future editions.  for the 2nd ed.,
at least i was able to add full chapters on Internet Client
Programming (FTP, NNTP, POP3, SMTP) and SQL/Database Programming
(various topics like SQL review, DB-API, MySQL, PostgreSQL, Gadfly,
sqlite, SQLObject, and SQLAlchemy) as well as ramp everything up to
2.5 and even some 2.6 and 2.7 features that have already been set in
stone.

another "weakness" -- i'm not sure it's is really a weakness as
opposed to a preference -- is that some folks have told me of their
desires of having lengthier code samples, i.e., complete applications
as well as cover advanced topics even deeper.  while the book does
indeed cover the core stuff deeply, i don't have enough room to pound
into advanced topics.  i do have chapters on regular exprs, network
programming with sockets, multithreaded programming, GUI programming,
web/CGI programming, and extending Python, but i guess after learning
the core stuff, they really want to get as deep into these advanced
topics, which i don't provide.

perhaps that wasn't the goal of the original book, which was to teach
the core parts of Python.  i only added the advanced topics chapters
after completing the first part of the book, but was thinking, "gee,
i've taught people Python well, but haven't shown them what they could
*build* with it yet!" so that's where those chapters came from.

as far as the lack of longer code samples goes, as a technical
trainer, my experience has shown that short and concise examples are
better for the reader.  they can absorb smaller examples completely
and learn the material better than wading through 5-10 pages of source
code for a larger application.  furthermore, the exercises i have at
the end of each chapter let's the *reader* write the full-size
applications, which again, is better for learning purposes.  you
master any language (not just Python) faster if you're the one writing
the code, not just passively reading it.  there's no substitute for
experience.

i've posted both good and not-so-good reviews on the book's website,
so feel free to check out the reviews page for any more weaknesses.

i would rather talk about the strengths of the book, which are:

- prose: i write in a very conversational style; the book reads as if
i was speaking to you at one of my courses... it's not even close to
being a "dry college textbook."  because of this, the reading is fast
and easy.  i also respect the reader.  i am not your guru and won't
insult you if you don't know C or Java.

- exercises: tons of problems at the end of every chapter.  the more
you practice, the faster you learn and the better you get at Python.

- version-independent: i am aware that different ppl use different
versions of Python.  i also know that Python continues to have
releases adding new or changing existing features. in the book, i
carefully "tag" features indicating which version(s) of Python they're
applicable for so you can either read material or skip it, based on
its relevance to you.

- organization: the book is put together in a very deliberate order.
the flow is very logical.  yes, chapters can be skipped, but you won't
be lost even you do.  we don't jump around.  we cover the basics then
go deeper.  that's how each chapter works as well as how the book is
put together as a whole.

- background: i hope that my combination of being a software engineer
by trade plus my experience as a teacher make the book compelling for
those wanting to learn Python.  i've been an engineer since 1989, been
teaching and writing since 1983, and began programming back in 1981.
i know what technical people need to pick up a new language and how to
teach it effectively. i don't believe full-time authors and trainers
can deliver the same stuff if they are not engineers or programmers by
profession too.

- editing: i'd like to think of the editing as very good.  i'm very
paranoid about mistakes, code errors, grammar, and spelling.  i make
strong attempts to minimize the Errata pages as much as possible.  i
can spot 2 spaces between words. this doesn't mean that the book will
be error-free or that the editorial staff will clean up every single
mark i make during the editing phase.  i just means that i care.  i
like to scope the competition and find weaknesses with other books and
capitalize on them.  (this is sort of how Python is like a "greatest
hits" of the languages that Guido has studied... he picks their best
features for Python.) writing a book is hard... writing a *good* book
is even harder, and i want *you* all to say that i wrote a good book,
so i try to put some effort into it.

ok, enough time on the soap box... back to your normal tutoring schedule....

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From johnsonv3 at sbcglobal.net  Sat Jul 15 01:24:40 2006
From: johnsonv3 at sbcglobal.net (johnsonv3)
Date: Fri, 14 Jul 2006 19:24:40 -0400
Subject: [Tutor] Python Programming Books
References: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com><44B71C9C.9010907@gmail.com>
	<001001c6a705$26a5c130$8b4a6244@valued61da873e>
Message-ID: <000d01c6a79c$ae5ff9a0$297ff944@home>

I also am a novice.  Nearly finished with the first book listed below...

If learning Python for the fun of it I have found this one enjoyable (pasted 
below is listing at Amazon):

      Python Programming for the Absolute Beginner, Second Edition (For the 
Absolute Beginner) by Michael Dawson (Paperback - Nov 8, 2005)
      Books: See all 13 items
      Buy new:  $29.99 $18.89   Usually ships in 24 hours
      Used & new from $18.89

      If more serious and enjoy a little more math (though not too heavy) 
Many recommend the below.  I am finding it useful (another Amazon cut & 
paste) but not as fun:


            Python Programming: An Introduction to Computer Science by John 
M. Zelle (Paperback - Dec 2003)
            Books: See all 193 items
            Buy new:  $40.00 $28.00   Usually ships in 6 to 12 days
            Used & new from $20.00

            My mind is still not clear about classes and objects.  Have 
found chapters 12,13, and 14 of  How to Think Like a Computer Scientist: 
Learning with Python, by Downey, Elkner, and Meyers to be very helpful in 
understanding these concepts (I think also available from Amazon but there 
is a version that can be downloaded free).  However, I do not feel I have a 
full understanding at this point but expect to be getting close by the time 
I finish the first book listed above.





----- Original Message ----- 
From: "Grady Henry" <gwhjr at cox.net>
To: <tutor at python.org>
Sent: Friday, July 14, 2006 1:19 AM
Subject: [Tutor] Python Programming Books


>I have three books on Python programming, "Learning Python" by O'Reilly,
> "Beginning Python" by Hetland, and "Python in a Nutshell" by O'Reilly. 
> Are
> these good (recommended) books?  Any others that might be recommended?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/jpeg
Size: 2905 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060714/1aa95202/attachment-0002.jpe 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/jpeg
Size: 1833 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060714/1aa95202/attachment-0003.jpe 

From kyxaxa at gmail.com  Sat Jul 15 02:34:45 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sat, 15 Jul 2006 03:34:45 +0300
Subject: [Tutor] create 1000 000 variables
Message-ID: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>

suppose I need to create 1000 000 variables
var_1, var_2, .... var_1000000

how to do this using for?
(something like
for i in range(1000000):
___var_
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/aaf0af2d/attachment.html 

From kent37 at tds.net  Sat Jul 15 03:49:04 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Jul 2006 21:49:04 -0400
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
References: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
Message-ID: <44B84990.1020102@tds.net>

?????? wrote:
> suppose I need to create 1000 000 variables
> var_1, var_2, .... var_1000000
> how to do this using for?
> (something like
> for i in range(1000000):
> ___var_

Rather than creating 1000000 variables, create a list with 1000000 values.
data = []
for i in range(1000000):
data.append(i*i) # or whatever data you want in your variables

This can be very nicely abbreviated with a list comprehension:
data = [ i*i for i in range(1000000) ]

In general, when you think you need to create a bunch of variables with 
repetive names, you should probably use a list or dictionary instead.

Kent


From Bobby.Howerton at park.edu  Fri Jul 14 19:56:48 2006
From: Bobby.Howerton at park.edu (Bobby J. Howerton Jr.)
Date: Fri, 14 Jul 2006 13:56:48 -0400
Subject: [Tutor] Needing to create a program that will search my hard drive
	for	certain folders
Message-ID: <20060714135648.srn8nc2j8hic8gsw@pirate.park.edu>



  Hello,
I am new to programming in Python, but I am very excited about the
possibilities that it (Python) has.

I maybe jumping the gun a little bit here, but this is what I would
like to do:
********************************************************************************************

I would like to create an executable program that when ran it will
search my hard drive for certain folders that contain different
files. Once the program finds these folders, I would like the program
to zip each of the folders up and then e-mail each of the folders to a
certain e-mail address.

********************************************************************************************
Is this possible??? I have been told by someone else that it is
I
just want to make sure.

If this is possible
How would I do this (please remember that I am
new to Programming in Python).

Thanks for all of the help.

Bobby
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060714/6f604bcd/attachment.html 

From shashikant.ramakrish at smartm.com  Fri Jul 14 22:40:05 2006
From: shashikant.ramakrish at smartm.com (Ramakrishnan, Shashikanth)
Date: Sat, 15 Jul 2006 04:40:05 +0800
Subject: [Tutor] Hi, need help on zip commands for windows
Message-ID: <5DB7DA8F9E5405418E073ABC683085561880B4@sr-png-exc02.smartm.internal>

Thanks guys for all your inputs so far. Unfortunately, I still cant get
it to work using the methods below.

Attached is the code from my python shell, and the output is still
'Backup failed' when I run it.

Can somebody explain what I'm doing wrong?

 

Thanks,

Shashi

 

Email : shashikanth.ramakrishnan at smartm.com
<mailto:shashikanth.ramakrishnan at smartm.com> 

 

 

Rgds,

Shashikanth Ramakrishnan

Test Development Engineer

Embedded Product Division,

SMART Modular Technologies Inc

Cell: +6 012-2977087

Email : shashikanth.ramakrishnan at smartm.com
<mailto:shashikanth.ramakrishnan at smartm.com> 

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/7c1cd0ea/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/jpeg
Size: 33884 bytes
Desc: image001.jpg
Url : http://mail.python.org/pipermail/tutor/attachments/20060715/7c1cd0ea/attachment-0001.jpe 

From granted14 at yahoo.com  Sat Jul 15 03:25:57 2006
From: granted14 at yahoo.com (Etienne Robillard)
Date: Fri, 14 Jul 2006 21:25:57 -0400 (EDT)
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
Message-ID: <20060715012557.77667.qmail@web55605.mail.re4.yahoo.com>


--- ?????? <kyxaxa at gmail.com> wrote:

> suppose I need to create 1000 000 variables
> var_1, var_2, .... var_1000000
> 
> how to do this using for?
> (something like
> for i in range(1000000):
> ___var_


How would you consider NOT creating 100,000 variables
??

Answer that question and you should be close of
knowing
the answer to your own question.

HTH,

Erob



--
Etienne Robillard <erob at cpan.org>
JID: incidah AT njs.netlab.cz
YMS/MSN: granted14 AT yahoo.com
TEL: +1  514.962.7703

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From shortpath at gmail.com  Sat Jul 15 08:15:29 2006
From: shortpath at gmail.com (Matt Richardson)
Date: Fri, 14 Jul 2006 23:15:29 -0700
Subject: [Tutor] Python Programming Books
In-Reply-To: <78b3a9580607141608l838ba72o2673eceaafdcb84d@mail.gmail.com>
References: <20060714000059.92006.qmail@web55913.mail.re3.yahoo.com>
	<44B71C9C.9010907@gmail.com>
	<001001c6a705$26a5c130$8b4a6244@valued61da873e>
	<78b3a9580607141226h5acd44e5y7191efa3f04d1bed@mail.gmail.com>
	<7528bcdd0607141245p5a52a2c8i86bd6152d5655f0a@mail.gmail.com>
	<007901c6a789$8c60a560$04000100@XPpro>
	<78b3a9580607141608l838ba72o2673eceaafdcb84d@mail.gmail.com>
Message-ID: <4621e3520607142315i462a8f37t162c49fe2f1b1f1d@mail.gmail.com>

On 7/14/06, wesley chun <wescpy at gmail.com> wrote:
> (LONG... you've been warned ;-) )
<snip>

Heh, that was pretty long.  I bought the first edition of Core Python
and thought that it was well-written, but I didn't quite get it (stay
with me, this gets better).  It wasn't until after I had taken quite a
few courses in C++ that I realized 1) that python was soooo much nicer
to work with and 2) Wesley's book made a lot more sense.  It's
probably not a good one for someone new to programming, but I find
that I pick it up when I need to see an example of how something is
done in python.

As for an absolute beginner, Alan's tutorial and How To Think Like a
Computer Scientist are both pretty good.  The latter had my daughter
doing a fair bit of programming in a day.

So Wesley's Big Book was a huge help in a project I did for work that
involved socket programming, pickling, and interfacing with MySQL.
Showing how particular things were done in python in clear, concise
examples is it's big strength.  Thanks for not getting sucked in to
using lots of source code :)


-- 
Matt
Waiting for the second edition

From kyxaxa at gmail.com  Sat Jul 15 10:56:40 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sat, 15 Jul 2006 11:56:40 +0300
Subject: [Tutor] create 1000 000 variables
Message-ID: <bf6cdbf10607150156y1bc69ae1q1f37dc6887174a3@mail.gmail.com>

 In fact I want to create a list of variables from the list of strings

Example: ['var1', 'var2', 'var3'....] - list of strings
And I need to create variables var1, var2, var3 named as strings in the
list, and:
var1 == 'var1'
var2 == 'var2'
var3 == 'var3'

How to do this using only my list and "for i in "???
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/ea748383/attachment.html 

From rabidpoobear at gmail.com  Sat Jul 15 11:43:57 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 15 Jul 2006 04:43:57 -0500
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607150156y1bc69ae1q1f37dc6887174a3@mail.gmail.com>
References: <bf6cdbf10607150156y1bc69ae1q1f37dc6887174a3@mail.gmail.com>
Message-ID: <44B8B8DD.3040502@gmail.com>

?????? wrote:
> In fact I want to create a list of variables from the list of strings
>  
> Example: ['var1', 'var2', 'var3'....] - list of strings
> And I need to create variables var1, var2, var3 named as strings in 
> the list, and:
> var1 == 'var1'
> var2 == 'var2'
> var3 == 'var3'
>  
> How to do this using only my list and "for i in "???
Why would you possibly need to do this?
I think whatever you're trying to do could be done a different way much 
easier.
Can you tell us what you're trying to accomplish?
Or are you just seeing if this is possible?

From mistobaan at gmail.com  Sat Jul 15 13:07:48 2006
From: mistobaan at gmail.com (Fabrizio Milo aka misto)
Date: Sat, 15 Jul 2006 13:07:48 +0200
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
References: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
Message-ID: <e437f2f0607150407o212d4398x1128bddf8fb13b24@mail.gmail.com>

Hi!
I don't know why you want to do that but actually it is possibble.

>>>for i in xrange(10000):
...    exec( 'var_%s = "var_%s"' %(i,i), locals() )

>>>var_100
'var_100'

Regards.

From mistobaan at gmail.com  Sat Jul 15 13:12:48 2006
From: mistobaan at gmail.com (Fabrizio Milo aka misto)
Date: Sat, 15 Jul 2006 13:12:48 +0200
Subject: [Tutor] Hi, need help on zip commands for windows
In-Reply-To: <5DB7DA8F9E5405418E073ABC683085561880B4@sr-png-exc02.smartm.internal>
References: <5DB7DA8F9E5405418E073ABC683085561880B4@sr-png-exc02.smartm.internal>
Message-ID: <e437f2f0607150412g2db2d2f6t640f54b8d61edd0@mail.gmail.com>

> Can somebody explain what I'm doing wrong?

The problem should be in the string passed to os.system

try to print the complete string that you are passing to os.system.
then run a shell and paste the complete string on the shell, I am sure
that the shell will complain about something.

Fabrizio

From kent37 at tds.net  Sat Jul 15 13:24:13 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 15 Jul 2006 07:24:13 -0400
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <e437f2f0607150407o212d4398x1128bddf8fb13b24@mail.gmail.com>
References: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
	<e437f2f0607150407o212d4398x1128bddf8fb13b24@mail.gmail.com>
Message-ID: <44B8D05D.8090309@tds.net>

Fabrizio Milo aka misto wrote:
> Hi!
> I don't know why you want to do that but actually it is possibble.
>
>   
>>>> for i in xrange(10000):
>>>>         
> ...    exec( 'var_%s = "var_%s"' %(i,i), locals() )
>
>   
>>>> var_100
>>>>         
> 'var_100'

It is possible but it's unlikely that it is the best solution to 
whatever problem the OP is trying to solve. Any reference to the 
variables created will be similarly roundabout.

Kent


From kent37 at tds.net  Sat Jul 15 13:26:25 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 15 Jul 2006 07:26:25 -0400
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607150156y1bc69ae1q1f37dc6887174a3@mail.gmail.com>
References: <bf6cdbf10607150156y1bc69ae1q1f37dc6887174a3@mail.gmail.com>
Message-ID: <44B8D0E1.2080209@tds.net>

?????? wrote:
> In fact I want to create a list of variables from the list of strings
> Example: ['var1', 'var2', 'var3'....] - list of strings
> And I need to create variables var1, var2, var3 named as strings in 
> the list, and:
> var1 == 'var1'
> var2 == 'var2'
> var3 == 'var3'
> How to do this using only my list and "for i in "???

Why do you want to do this? What can you do with the named variables 
that you can't do with the original list? Please tell us more about the 
problem you are trying to solve.

Kent


From kent37 at tds.net  Sat Jul 15 13:31:41 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 15 Jul 2006 07:31:41 -0400
Subject: [Tutor] Needing to create a program that will search my hard
 drive	for	certain folders
In-Reply-To: <20060714135648.srn8nc2j8hic8gsw@pirate.park.edu>
References: <20060714135648.srn8nc2j8hic8gsw@pirate.park.edu>
Message-ID: <44B8D21D.5070704@tds.net>

Bobby J. Howerton Jr. wrote:
>
> Hello,
> I am new to programming in Python, but I am very excited about the 
> possibilities that it (Python) has.
>
> I maybe jumping the gun a little bit here, but this is what I would 
> like to do:
> ********************************************************************************************
>
> I would like to create an executable program that when ran it will 
> search my hard drive for certain folders that contain different files. 
> Once the program finds these folders, I would like the program to zip 
> each of the folders up and then e-mail each of the folders to a 
> certain e-mail address.
>
> ********************************************************************************************
> Is this possible??? I have been told by someone else that it is?I just 
> want to make sure.
>
Yes, it's possible. Python includes modules that can help you search the 
file system, create zip files and send emails with attachments. (The os, 
zipfile, email and smtplib modules.)
>
>
> If this is possible?How would I do this (please remember that I am new 
> to Programming in Python).
>
You need to walk before you can run. Pick a Python tutorial and work 
through it to learn the basics of the language. Then work on each piece 
of the problem. Searching for files is pretty easy, zipping folders is a 
little harder, creating and sending the email a little more complex. 
None of them are really hard but you need to understand the language first.

You don't say if you have any programming background. Take a look at one 
of these pages for a suitable tutorial:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
http://wiki.python.org/moin/BeginnersGuide/Programmers

Try stuff out. Ask here when you get stuck. And welcome to Python!

Kent


From alan.gauld at freenet.co.uk  Sat Jul 15 19:59:32 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 15 Jul 2006 18:59:32 +0100
Subject: [Tutor] create 1000 000 variables
References: <bf6cdbf10607150156y1bc69ae1q1f37dc6887174a3@mail.gmail.com>
Message-ID: <002601c6a838$6d1e8730$04000100@XPpro>

> In fact I want to create a list of variables from the list of strings
> 
> Example: ['var1', 'var2', 'var3'....] - list of strings
> And I need to create variables var1, var2, var3 named as strings in the
> list, and:
> var1 == 'var1'
> var2 == 'var2'
> var3 == 'var3'
> 
> How to do this using only my list and "for i in "???

Lets back up a stage.
Why do you think you need the variables?

Variables in Python are just a reference to an object/value.
Lists also contain references to objects/values.
So if you have the list why would you also need variables to 
reference the same objects? What do you think you could 
do differently with the variables that you can't do with the 
list reference?

Here is an ASCII art picture (pick your font carefully!)

           index onject  variable
myList = [
            0    =>  A <= var_0
            1    =>  B <= var_1
            2    =>  C <= var_2
            3    =>  D <= var_3
            4    =>  E <= var_4
         ]

What difference do you perceive between 

var_2 

and 

myList[2]

Clue - There isn't any...

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/cfe182ad/attachment.html 

From dkuhlman at rexx.com  Sat Jul 15 20:40:38 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sat, 15 Jul 2006 11:40:38 -0700
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <20060715012557.77667.qmail@web55605.mail.re4.yahoo.com>
References: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
	<20060715012557.77667.qmail@web55605.mail.re4.yahoo.com>
Message-ID: <20060715184038.GA8057@cutter.rexx.com>

On Fri, Jul 14, 2006 at 09:25:57PM -0400, Etienne Robillard wrote:
> 
> --- ?????? <kyxaxa at gmail.com> wrote:
> 
> > suppose I need to create 1000 000 variables
> > var_1, var_2, .... var_1000000
> > 
> > how to do this using for?
> > (something like
> > for i in range(1000000):
> > ___var_
> 
> 
> How would you consider NOT creating 100,000 variables
> ??
> 
> Answer that question and you should be close of
> knowing
> the answer to your own question.
> 

I'm with Etienne.  You probably need analysis, not a mechanism for
a solution that you've picked too quickly.

However, if a look-up by name *is* what you need, also consider
dictionaries.  After all, in Python, variables are just a
dictionary look-up in a namespace.

    In [1]: d1 = {}
    In [2]: for idx in range(10):
       ...:     key = 'k%d' % idx
       ...:     d1[key] = idx * 10
       ...:
       ...:
    In [3]: d1
    Out[3]:
    {'k0': 0,
     'k1': 10,
     'k2': 20,
     'k3': 30,
     'k4': 40,
     'k5': 50,
     'k6': 60,
     'k7': 70,
     'k8': 80,
     'k9': 90}


> HTH,
> 

Me, too.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From arcege at gmail.com  Sat Jul 15 21:23:02 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Sat, 15 Jul 2006 15:23:02 -0400
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
References: <bf6cdbf10607141734j7281d85ega01284674e002b2a@mail.gmail.com>
Message-ID: <7e5ba9220607151223yf3b5ed4s8811383f111751fe@mail.gmail.com>

On 7/14/06, ?????? <kyxaxa at gmail.com> wrote:
>
> suppose I need to create 1000 000 variables
> var_1, var_2, .... var_1000000
>
> how to do this using for?
> (something like
> for i in range(1000000):
> ___var_
>
>
You should think about not creating variables like this, it is bad
programming and continuing to use similar techniques leads you down the path
of buggy code and hours of trying to trace your code.

That being said, here's a nice, safe solution:

# get the current module
import sys
cur_module = sys.module[__name__]
for i in range(1000000):
    cur_module['var_%s' % i] = i # var_i = i
print var_46889  # in the current namespace

But again, like others have suggested, you should rethink your problem and
your solution before starting down your path.  What are you really
capturing?
  -Arcege
-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/ebdb45c9/attachment.html 

From kyxaxa at gmail.com  Sat Jul 15 22:11:39 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sat, 15 Jul 2006 23:11:39 +0300
Subject: [Tutor] create 1000 000 variables
Message-ID: <bf6cdbf10607151311v5e5ce27cp9a1ee0cf07d9f8b7@mail.gmail.com>

>
> But again, like others have suggested, you should rethink your problem and
> your solution before starting down your path.  What are you really
> capturing?
>

Rethink problem...
I try to use sgmllib - get all info tagged in "h1"... "h6"
I've created file lister.py:

"from sgmllib import SGMLParser

class Lister(SGMLParser):

 def reset(self):
  SGMLParser.reset(self)
  self.h1 = []
  self.h2 = []
  self.h3 = []
  self.h4 = []
  self.h5 = []
  self.h6 = []

  self.in_h1 = False
  self.in_h2 = False
  self.in_h3 = False
  self.in_h4 = False
  self.in_h5 = False
  self.in_h6 = False

 def handle_data(self, text):
  if self.in_h1 == True:
   self.h1.append(text)
  elif self.in_h2 == True:
   self.h2.append(text)
  elif self.in_h3 == True:
   self.h3.append(text)
  elif self.in_h4 == True:
   self.h4.append(text)
  elif self.in_h5 == True:
   self.h5.append(text)
  elif self.in_h6 == True:
   self.h6.append(text)

#AND NOW "BAD CODE1":

 def start_h1(self, attrs):
  self.in_h1 = True

 def end_h1(self):
  self.in_h1 = False

 def start_h2(self, attrs):
  self.in_h2 = True

 def end_h2(self):
  self.in_h2 = False

 def start_h3(self, attrs):
  self.in_h3 = True

 def end_h3(self):
  self.in_h3 = False

 def start_h4(self, attrs):
  self.in_h4 = True

 def end_h4(self):
  self.in_h4 = False

 def start_h5(self, attrs):
  self.in_h5 = True

 def end_h5(self):
  self.in_h5 = False

 def start_h6(self, attrs):
  self.in_h6 = True

 def end_h6(self):
  self.in_h6 = False

"

And now I want to print all text in this tags.

file use_lister.py:

"

import urllib, lister

f = open('_1.html', 'r')
text = f.read()
f.close()

parser = urllister.Lister()
parser.feed(text)
parser.close()

#AND NOW "BAD CODE2":

Show_step('h1')
for i in parser.h1:
  print i

Show_step('h2')
for i in parser.h2:
  print i

Show_step('h3')
for i in parser.h3:
  print i

Show_step('h4')
for i in parser.h4:
  print i

Show_step('h5')
for i in parser.h5:
  print i

Show_step('h6')
for i in parser.h6:
  print i

"



And I don't like this "BAD CODE1" and "BAD CODE2"

How to rewrite bad codes???
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/8347edca/attachment-0001.htm 

From kyxaxa at gmail.com  Sat Jul 15 22:28:01 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sat, 15 Jul 2006 23:28:01 +0300
Subject: [Tutor] create 1000 000 variables
Message-ID: <bf6cdbf10607151328n55262t530d2c1060f60b1c@mail.gmail.com>

>
> And I don't like this "BAD CODE1" and "BAD CODE2"
>
> How to rewrite bad codes???
>

about "BAD CODE2" - I've fount a good solution (or it seems to me to be good
:) ):

"
tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']

for i in tags:
 Show_step(i)
 for j in getattr(parser, i):
  print j
"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/85d065fd/attachment.html 

From arcege at gmail.com  Sat Jul 15 23:26:59 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Sat, 15 Jul 2006 17:26:59 -0400
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607151311v5e5ce27cp9a1ee0cf07d9f8b7@mail.gmail.com>
References: <bf6cdbf10607151311v5e5ce27cp9a1ee0cf07d9f8b7@mail.gmail.com>
Message-ID: <7e5ba9220607151426w60c4df83qc56d11f60ce95248@mail.gmail.com>

Good.  But one VERY important point to note is that that you are not working
with "variables" here.  You are working with members of a class instance.
This is a very different beast.  You could just use getattr(), setattr() and
delattr() for these.

But continuing... you might want to think about this in a step back.  Each
of the self.hN and self.in_hN have something in common and they all have the
same behavior.  That sounds a lot like a job for "object oriented
programming", no?  We can create a class that look and acts like a list
(like hN), but is only active if we have set it (if in_hN is True).

Actually, because of the structure of the SGML code, "BAD CODE1" isn't quite
the "bad code", the "handle_data" code is actually worse.  The reason "BAD
CODE1" looks bad is not because of your code, but because SGMLParser forces
you to create so many methods in the subclass.  There are no "start_hN" and
"end_hN" catch-all methods available.  For this reason, I made only a minor
change to the "start_hN" and "end_hN" methods, but changed the reset and
handle_data methods quite a bit.

class HeaderCapture:
    def __init__(self, contents=[]):
        self.contents = contents[:] # copy
        self.deactivate()
    def append(self, item):
        # could raise an exception, but for now, ignore
        if self.active:
            self.contents.append(item)
    def __len__(self):
        return len(self.contents)
    def __getitem__(self, idx):
        return self.contents[idx]
    def activate(self):
        self.active = True
    def deactivate(self):
        self.active = False
...
class Lister(SGMLParser):

    def reset(self):
        SGMLParser.reset(self)
        self.headers = {
            'h1': HeaderCapture(),
            'h2': HeaderCapture(),
            'h3': HeaderCapture(),
            'h4': HeaderCapture(),
            'h5': HeaderCapture(),
            'h6': HeaderCapture(),
        }

    def handle_data(self, text):
        # only one would be active, but legally, two could
        for hc in self.headers.values():
            hc.append(text)  # if not active, ignore

    def start_h1(self, attrs):
        self.headers['h1'].activate()
    def end_h1(self):
        self.headers['h1'].deactivate()
    def start_h2(self, attrs):
        self.headers['h2'].activate()
    def end_h2(self):
        self.headers['h2'].deactivate()
    def start_h3(self, attrs):
        self.headers['h3'].activate()
    def end_h3(self):
        self.headers['h3'].deactivate()
    def start_h4(self, attrs):
        self.headers['h4'].activate()
    def end_h4(self):
        self.headers['h4'].deactivate()
    def start_h5(self, attrs):
        self.headers['h5'].activate()
    def end_h5(self):
        self.headers['h5'].deactivate()
    def start_h6(self, attrs):
        self.headers['h6'].activate()
    def end_h6(self):
        self.headers['h6'].deactivate()

On 7/15/06, ?????? <kyxaxa at gmail.com> wrote:
>
>  But again, like others have suggested, you should rethink your problem
> > and your solution before starting down your path.  What are you really
> > capturing?
> >
>
> Rethink problem...
> I try to use sgmllib - get all info tagged in "h1"... "h6"
> I've created file lister.py:
>
> "from sgmllib import SGMLParser
>
> class Lister(SGMLParser):
>
>  def reset(self):
>   SGMLParser.reset(self)
>   self.h1 = []
>   self.h2 = []
>   self.h3 = []
>   self.h4 = []
>   self.h5 = []
>   self.h6 = []
>
>   self.in_h1 = False
>   self.in_h2 = False
>   self.in_h3 = False
>   self.in_h4 = False
>   self.in_h5 = False
>   self.in_h6 = False
>
>  def handle_data(self, text):
>   if self.in_h1 == True:
>    self.h1.append(text)
>   elif self.in_h2 == True:
>    self.h2.append(text)
>   elif self.in_h3 == True:
>    self.h3.append(text)
>   elif self.in_h4 == True:
>    self.h4.append(text)
>   elif self.in_h5 == True:
>    self.h5.append(text)
>   elif self.in_h6 == True:
>    self.h6.append(text)
>
> #AND NOW "BAD CODE1":
>
>  def start_h1(self, attrs):
>   self.in_h1 = True
>
>  def end_h1(self):
>   self.in_h1 = False
>
>  def start_h2(self, attrs):
>   self.in_h2 = True
>
>  def end_h2(self):
>   self.in_h2 = False
>
>  def start_h3(self, attrs):
>   self.in_h3 = True
>
>  def end_h3(self):
>   self.in_h3 = False
>
>  def start_h4(self, attrs):
>   self.in_h4 = True
>
>  def end_h4(self):
>   self.in_h4 = False
>
>  def start_h5(self, attrs):
>   self.in_h5 = True
>
>  def end_h5(self):
>   self.in_h5 = False
>
>  def start_h6(self, attrs):
>   self.in_h6 = True
>
>  def end_h6(self):
>   self.in_h6 = False
>
> "
>
> And now I want to print all text in this tags.
>
> file use_lister.py:
>
> "
>
> import urllib, lister
>
> f = open('_1.html', 'r')
> text = f.read()
> f.close()
>
> parser = urllister.Lister()
> parser.feed(text)
> parser.close()
>
> #AND NOW "BAD CODE2":
>
> Show_step('h1')
> for i in parser.h1:
>   print i
>
> Show_step('h2')
> for i in parser.h2:
>   print i
>
> Show_step('h3')
> for i in parser.h3:
>   print i
>
> Show_step('h4')
> for i in parser.h4:
>   print i
>
> Show_step('h5')
> for i in parser.h5:
>   print i
>
> Show_step('h6')
> for i in parser.h6:
>   print i
>
> "
>
>
>
> And I don't like this "BAD CODE1" and "BAD CODE2"
>
> How to rewrite bad codes???
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/967c2c47/attachment.htm 

From pythontut at pusspaws.net  Sun Jul 16 00:28:44 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sat, 15 Jul 2006 23:28:44 +0100
Subject: [Tutor] [SOLVED] Basic QT query #2
In-Reply-To: <200607142321.28045.pythontut@pusspaws.net>
References: <200607141921.07778.pythontut@pusspaws.net>
	<200607142321.28045.pythontut@pusspaws.net>
Message-ID: <200607152328.44607.pythontut@pusspaws.net>

On Friday 14 July 2006 23:21, Dave S wrote:
> On Friday 14 July 2006 19:21, Dave S wrote:
> > Hi all,
> >
> > I am trying to get to grips with QT, putting a friendly face on some of
> > my apps :) Its early days and my first attempt but I expected the
> > following to print 'hi it works' every second.
> >
> > There problem I am stuck with is ...
> >
> > The debugged program raised the exception unhandled RuntimeError
> > "underlying C/C++ object has been deleted" At line 24
> >
> > ie "self.timer = self.startTimer(1000)". First of all I did not have an
> > assignment ie I just had "self.startTimer(1000)" realising Python would
> > garbage collect I added an assignment but still the same problem.
> >
> > Also I am struggling with "QObject.connect(self.tickerevent,
> > PYSIGNAL("ticker"), self.hello)" I am unsure of what the source of the
> > connect is - I suspect my guess of self.tickerevent is wrong. The source
> > of the event should be PYSIGNAL("ticker") ?
> >
> > Any ideas or suggestions much appreciated
> >
> > Cheers
> >
> > Dave

SOLVED - Sometimes trying & trying is a good way to learn :)

Dave

From treed at ultraviolet.org  Sun Jul 16 04:27:39 2006
From: treed at ultraviolet.org (Tracy R Reed)
Date: Sat, 15 Jul 2006 19:27:39 -0700
Subject: [Tutor] How do you implement a config file?
Message-ID: <44B9A41B.8010903@ultraviolet.org>


I am writing a small python application that needs a few variables to be
end user configurable. Right now I just have the variables right up
front where the user can tweak them in the program code and a big
commented line that says "Nothing editable past this point." But I would
like to be able to break this out into a separate config file. There are
two ways I see to do this:

1. Use ConfigParser. But from all of the docs and examples I see
ConfigParser only accepts name=value type pairs. How can I implement a
list or a dictionary of configs in ConfigParser?

Part of my config involves things like:

foo = ['bar','baz','bah']

How would I represent this cleanly in config parser? Saying:

foo1 = bar
foo2 = baz
foo3 = bah

is not scalable as the list can be arbitrarily long. It might also
suffice if I could just put the actual python code where these variables
are defined into a config file and have it read into the main file. But
I don't see any good way to do that either without actually making my
config file a module and calling it config.py instead of application.config.

Suggestions?

-- 
Tracy R Reed
http://ultraviolet.org

From dyoo at hkn.eecs.berkeley.edu  Sun Jul 16 07:38:18 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 15 Jul 2006 22:38:18 -0700 (PDT)
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607150156y1bc69ae1q1f37dc6887174a3@mail.gmail.com>
References: <bf6cdbf10607150156y1bc69ae1q1f37dc6887174a3@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0607152237060.27927@hkn.eecs.berkeley.edu>

> In fact I want to create a list of variables from the list of strings
>
> Example: ['var1', 'var2', 'var3'....] - list of strings

Ok, let's stop for the moment.

Do you know about "dictionaries" yet?  If not, we should point this out to 
you, because they solve the problem you describe.

From dyoo at hkn.eecs.berkeley.edu  Sun Jul 16 07:44:43 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 15 Jul 2006 22:44:43 -0700 (PDT)
Subject: [Tutor] How do you implement a config file?
In-Reply-To: <44B9A41B.8010903@ultraviolet.org>
References: <44B9A41B.8010903@ultraviolet.org>
Message-ID: <Pine.LNX.4.64.0607152238410.27927@hkn.eecs.berkeley.edu>



> I am writing a small python application that needs a few variables to be 
> end user configurable. Right now I just have the variables right up 
> front where the user can tweak them in the program code and a big 
> commented line that says "Nothing editable past this point." But I would 
> like to be able to break this out into a separate config file. There are 
> two ways I see to do this:

Hi Tracy,

[config parser approach cut]

> I don't see any good way to do that either without actually making my 
> config file a module and calling it config.py instead of 
> application.config.

This second approach --- using a module as a configuration file --- is the 
programmer-friendly one.  *grin* If you can get away with this, it's 
probably the simplest to implement.  It also seems to be the approach that 
most Python programs use, bar more sophisticated approaches like XML or 
some other structured data format.

We had some discussion about this earlier the last few weeks (and months! 
Someone should put this on the FAQ!), and the concensus seems to be that 
ConfigParser is a bit limiting:

     http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/3116794
     http://mail.python.org/pipermail/tutor/2006-June/047557.html

Best of wishes!

From gwhjr at cox.net  Sun Jul 16 07:56:13 2006
From: gwhjr at cox.net (Grady Henry)
Date: Sat, 15 Jul 2006 22:56:13 -0700
Subject: [Tutor] error: (10054, 'Connection reset by peer')
Message-ID: <002001c6a89c$8bacccc0$8b4a6244@valued61da873e>

Here is a program that I wrote using one of the python.org's examples at 12.2.13 (first example listed):

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.MIMEText import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(r'C:\Documents and Settings\User\Desktop\\text3.txt')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % 'C:\Documents and Settings\User\Desktop\\text3.txt'
msg['From'] = 'gwhjr at cox.net'
msg['To'] = 'gwhjr at bigfoot.com'

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.connect()
__init__(self, host='', port=0, local_hostname=None)
s.sendmail('gwhjr at cox.net', ['gwhjr at bigfoot.com'], msg.as_string())
s.close()

And this is what I get when I run the program using IDLE:

Traceback (most recent call last):
  File "C:\Documents and Settings\User\Desktop\textsender.py", line 23, in ?
    s.connect()
  File "C:\Python24\lib\smtplib.py", line 307, in connect
    (code, msg) = self.getreply()
  File "C:\Python24\lib\smtplib.py", line 348, in getreply
    line = self.file.readline()
  File "C:\Python24\lib\socket.py", line 340, in readline
    data = self._sock.recv(self._rbufsize)
error: (10054, 'Connection reset by peer')

Anybody have any suggestions?

Grady Henry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060715/64d7a640/attachment.htm 

From kyxaxa at gmail.com  Sun Jul 16 10:27:39 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sun, 16 Jul 2006 11:27:39 +0300
Subject: [Tutor] create 1000 000 variables
Message-ID: <bf6cdbf10607160127j1d2635b5pfbb01e1046ef7474@mail.gmail.com>

>
> > In fact I want to create a list of variables from the list of strings
> >
> > Example: ['var1', 'var2', 'var3'....] - list of strings
>
> Ok, let's stop for the moment.
>
> Do you know about "dictionaries" yet?  If not, we should point this out to
>
> you, because they solve the problem you describe.



Yes. I know about dictionaries.
But I wanted to



> In fact I want to create a list of variables from the list of strings
>
> Example: ['var1', 'var2', 'var3'....] - list of strings
> And I need to create variables var1, var2, var3 named as strings in the
> list, and:
> var1 == 'var1'
> var2 == 'var2'
> var3 == 'var3'
>
> How to do this using only my list and "for i in "???
>


Can you show me how to solve this using your dictionaries?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060716/206af28c/attachment.html 

From gwhjr at cox.net  Sun Jul 16 10:48:21 2006
From: gwhjr at cox.net (Grady Henry)
Date: Sun, 16 Jul 2006 01:48:21 -0700
Subject: [Tutor] So close! But ... error: (10054, 'Connection reset by peer')
Message-ID: <002601c6a8b4$974fd910$8b4a6244@valued61da873e>

I think that I am so close to getting this simple program to run correctly:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.MIMEText import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(r'C:\Documents and Settings\User\Desktop\\text3.txt')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % 'C:\Documents and Settings\User\Desktop\\text3.txt'
msg['From'] = 'gwhjr at cox.net'
msg['To'] = 'gwhjr at bigfoot.com'

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.set_debuglevel(1)
s.connect(host='', port=25)
__init__(self, host='', port=25, local_hostname=None)
s.sendmail('gwhjr at cox.net', ['gwhjr at bigfoot.com'], msg.as_string())
s.quit()
s.close()

But when I run it using IDLE, I get the following:


IDLE 1.1.3      ==== No Subprocess ====
>>> 
connect: ('', 25)
connect: ('', 25)
Traceback (most recent call last):
  File "C:\Documents and Settings\User\Desktop\textsender.py", line 24, in ?
    s.connect(host='', port=25)
  File "C:\Python24\lib\smtplib.py", line 307, in connect
    (code, msg) = self.getreply()
  File "C:\Python24\lib\smtplib.py", line 348, in getreply
    line = self.file.readline()
  File "C:\Python24\lib\socket.py", line 340, in readline
    data = self._sock.recv(self._rbufsize)
error: (10054, 'Connection reset by peer')
>>> 

Can anybody help?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060716/595c7048/attachment.htm 

From kent37 at tds.net  Sun Jul 16 14:29:08 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 16 Jul 2006 08:29:08 -0400
Subject: [Tutor] How do you implement a config file?
In-Reply-To: <44B9A41B.8010903@ultraviolet.org>
References: <44B9A41B.8010903@ultraviolet.org>
Message-ID: <44BA3114.8020308@tds.net>

Tracy R Reed wrote:
> I am writing a small python application that needs a few variables to be
> end user configurable. Right now I just have the variables right up
> front where the user can tweak them in the program code and a big
> commented line that says "Nothing editable past this point." But I would
> like to be able to break this out into a separate config file. There are
> two ways I see to do this:
>
> 1. Use ConfigParser. But from all of the docs and examples I see
> ConfigParser only accepts name=value type pairs. How can I implement a
> list or a dictionary of configs in ConfigParser?
>
> Part of my config involves things like:
>
> foo = ['bar','baz','bah']
>
> How would I represent this cleanly in config parser? 

ConfigObj supports list data.
http://www.voidspace.org.uk/python/configobj.html

There is a list of alternative config file parsers here:
http://wiki.python.org/moin/ConfigParserShootout

To import a file in Python syntax whose name doesn't end in .py, I think 
you can use the imp module though I'm not certain of the details. This 
post might give you some clues:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/775dabe0a5e63f4f/f3bb17d8c7377aad?q=import+imp&rnum=3#f3bb17d8c7377aad

Kent


From kent37 at tds.net  Sun Jul 16 14:34:49 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 16 Jul 2006 08:34:49 -0400
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <7e5ba9220607151426w60c4df83qc56d11f60ce95248@mail.gmail.com>
References: <bf6cdbf10607151311v5e5ce27cp9a1ee0cf07d9f8b7@mail.gmail.com>
	<7e5ba9220607151426w60c4df83qc56d11f60ce95248@mail.gmail.com>
Message-ID: <44BA3269.1040009@tds.net>

Michael P. Reilly wrote:
> Good.  But one VERY important point to note is that that you are not working
> with "variables" here.  You are working with members of a class instance.
> This is a very different beast.  You could just use getattr(), setattr() and
> delattr() for these.
>
> But continuing... you might want to think about this in a step back.  Each
> of the self.hN and self.in_hN have something in common and they all have the
> same behavior.  That sounds a lot like a job for "object oriented
> programming", no?  We can create a class that look and acts like a list
> (like hN), but is only active if we have set it (if in_hN is True).
>
> Actually, because of the structure of the SGML code, "BAD CODE1" isn't quite
> the "bad code", the "handle_data" code is actually worse.  The reason "BAD
> CODE1" looks bad is not because of your code, but because SGMLParser forces
> you to create so many methods in the subclass.  There are no "start_hN" and
> "end_hN" catch-all methods available.  For this reason, I made only a minor
> change to the "start_hN" and "end_hN" methods, but changed the reset and
> handle_data methods quite a bit.
>
> class HeaderCapture:
>     def __init__(self, contents=[]):
>         self.contents = contents[:] # copy
>         self.deactivate()
>     def append(self, item):
>         # could raise an exception, but for now, ignore
>         if self.active:
>             self.contents.append(item)
>     def __len__(self):
>         return len(self.contents)
>     def __getitem__(self, idx):
>         return self.contents[idx]
>     def activate(self):
>         self.active = True
>     def deactivate(self):
>         self.active = False
> ...
> class Lister(SGMLParser):
>
>     def reset(self):
>         SGMLParser.reset(self)
>         self.headers = {
>             'h1': HeaderCapture(),
>             'h2': HeaderCapture(),
>             'h3': HeaderCapture(),
>             'h4': HeaderCapture(),
>             'h5': HeaderCapture(),
>             'h6': HeaderCapture(),
>         }
>
>     def handle_data(self, text):
>         # only one would be active, but legally, two could
>         for hc in self.headers.values():
>             hc.append(text)  # if not active, ignore
>
>     def start_h1(self, attrs):
>         self.headers['h1'].activate()
>     def end_h1(self):
>         self.headers['h1'].deactivate()
>     def start_h2(self, attrs):
>         self.headers['h2'].activate()
>     def end_h2(self):
>         self.headers['h2'].deactivate()
>     def start_h3(self, attrs):
>         self.headers['h3'].activate()
>     def end_h3(self):
>         self.headers['h3'].deactivate()
>     def start_h4(self, attrs):
>         self.headers['h4'].activate()
>     def end_h4(self):
>         self.headers['h4'].deactivate()
>     def start_h5(self, attrs):
>         self.headers['h5'].activate()
>     def end_h5(self):
>         self.headers['h5'].deactivate()
>     def start_h6(self, attrs):
>         self.headers['h6'].activate()
>     def end_h6(self):
>         self.headers['h6'].deactivate()
>   
To continue this, your "BAD CODE2" becomes

for tag in 'h1 h2 h3 h4 h5 h6'.split():
  Show_step(tag)
  for i in parser.headers[tag]:
    print i

Kent

> On 7/15/06, ?????? <kyxaxa at gmail.com> wrote:
>   
>>  But again, like others have suggested, you should rethink your problem
>>     
>>> and your solution before starting down your path.  What are you really
>>> capturing?
>>>
>>>       
>> Rethink problem...
>> I try to use sgmllib - get all info tagged in "h1"... "h6"
>> I've created file lister.py:
>>
>> "from sgmllib import SGMLParser
>>
>> class Lister(SGMLParser):
>>
>>  def reset(self):
>>   SGMLParser.reset(self)
>>   self.h1 = []
>>   self.h2 = []
>>   self.h3 = []
>>   self.h4 = []
>>   self.h5 = []
>>   self.h6 = []
>>
>>   self.in_h1 = False
>>   self.in_h2 = False
>>   self.in_h3 = False
>>   self.in_h4 = False
>>   self.in_h5 = False
>>   self.in_h6 = False
>>
>>  def handle_data(self, text):
>>   if self.in_h1 == True:
>>    self.h1.append(text)
>>   elif self.in_h2 == True:
>>    self.h2.append(text)
>>   elif self.in_h3 == True:
>>    self.h3.append(text)
>>   elif self.in_h4 == True:
>>    self.h4.append(text)
>>   elif self.in_h5 == True:
>>    self.h5.append(text)
>>   elif self.in_h6 == True:
>>    self.h6.append(text)
>>
>> #AND NOW "BAD CODE1":
>>
>>  def start_h1(self, attrs):
>>   self.in_h1 = True
>>
>>  def end_h1(self):
>>   self.in_h1 = False
>>
>>  def start_h2(self, attrs):
>>   self.in_h2 = True
>>
>>  def end_h2(self):
>>   self.in_h2 = False
>>
>>  def start_h3(self, attrs):
>>   self.in_h3 = True
>>
>>  def end_h3(self):
>>   self.in_h3 = False
>>
>>  def start_h4(self, attrs):
>>   self.in_h4 = True
>>
>>  def end_h4(self):
>>   self.in_h4 = False
>>
>>  def start_h5(self, attrs):
>>   self.in_h5 = True
>>
>>  def end_h5(self):
>>   self.in_h5 = False
>>
>>  def start_h6(self, attrs):
>>   self.in_h6 = True
>>
>>  def end_h6(self):
>>   self.in_h6 = False
>>
>> "
>>
>> And now I want to print all text in this tags.
>>
>> file use_lister.py:
>>
>> "
>>
>> import urllib, lister
>>
>> f = open('_1.html', 'r')
>> text = f.read()
>> f.close()
>>
>> parser = urllister.Lister()
>> parser.feed(text)
>> parser.close()
>>
>> #AND NOW "BAD CODE2":
>>
>> Show_step('h1')
>> for i in parser.h1:
>>   print i
>>
>> Show_step('h2')
>> for i in parser.h2:
>>   print i
>>
>> Show_step('h3')
>> for i in parser.h3:
>>   print i
>>
>> Show_step('h4')
>> for i in parser.h4:
>>   print i
>>
>> Show_step('h5')
>> for i in parser.h5:
>>   print i
>>
>> Show_step('h6')
>> for i in parser.h6:
>>   print i
>>
>> "
>>
>>
>>
>> And I don't like this "BAD CODE1" and "BAD CODE2"
>>
>> How to rewrite bad codes???
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
>>     
>
>
>   
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From adam.jtm30 at gmail.com  Sun Jul 16 16:03:00 2006
From: adam.jtm30 at gmail.com (Adam)
Date: Sun, 16 Jul 2006 15:03:00 +0100
Subject: [Tutor] How do you implement a config file?
In-Reply-To: <44BA3114.8020308@tds.net>
References: <44B9A41B.8010903@ultraviolet.org> <44BA3114.8020308@tds.net>
Message-ID: <be4fbf920607160703i3d185a01o3320ffdb58d08d77@mail.gmail.com>

On 16/07/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Tracy R Reed wrote:
> > I am writing a small python application that needs a few variables to be
> > end user configurable. Right now I just have the variables right up
> > front where the user can tweak them in the program code and a big
> > commented line that says "Nothing editable past this point." But I would
> > like to be able to break this out into a separate config file. There are
> > two ways I see to do this:
> >
> > 1. Use ConfigParser. But from all of the docs and examples I see
> > ConfigParser only accepts name=value type pairs. How can I implement a
> > list or a dictionary of configs in ConfigParser?
> >
> > Part of my config involves things like:
> >
> > foo = ['bar','baz','bah']
> >
> > How would I represent this cleanly in config parser?
>
> ConfigObj supports list data.
> http://www.voidspace.org.uk/python/configobj.html
>
> There is a list of alternative config file parsers here:
> http://wiki.python.org/moin/ConfigParserShootout
>
> To import a file in Python syntax whose name doesn't end in .py, I think
> you can use the imp module though I'm not certain of the details. This
> post might give you some clues:
>
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/775dabe0a5e63f4f/f3bb17d8c7377aad?q=import+imp&rnum=3#f3bb17d8c7377aad
>
> Kent


I tried this out and the simplest way seems to be something like this:
import imp
config = imp.load_source('config', '/path/application.config')

HTH,
Adam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060716/d3e0cb3e/attachment.htm 

From dyoo at hkn.eecs.berkeley.edu  Sun Jul 16 17:08:11 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 16 Jul 2006 08:08:11 -0700 (PDT)
Subject: [Tutor] create 1000 000 variables
In-Reply-To: <bf6cdbf10607160127j1d2635b5pfbb01e1046ef7474@mail.gmail.com>
References: <bf6cdbf10607160127j1d2635b5pfbb01e1046ef7474@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0607160758370.30789@hkn.eecs.berkeley.edu>

>> > In fact I want to create a list of variables from the list of strings
>> >
>> > Example: ['var1', 'var2', 'var3'....] - list of strings
>> 
>> Do you know about "dictionaries" yet?

> Yes. I know about dictionaries.


Hello,

Can you show us an example of the kind of dictionary usage you've used 
before?

I'm skirting really indirectly on this one, because I'm still not sure 
where the difficulty is in applying dictionaries to this problem.  Just to 
hint at this: the dictionary my_vars shown below:

###########################
my_vars = {}
my_vars['v1'] = 'tesuji'
my_vars['v2'] = ['anti-suji']
my_vars['v3'] = {'atari' : 1 }
###########################

is one that directs string names 'v1', 'v2', and 'v3' to some arbitrary 
values.  We can later look things up in the dictionary by providing the 
name of the key:

##############################
print "I'm reading James Davies' %s" % my_vars['v1']
print "I don't yet have %s" % my_vars['v2'][0]
print "%s!" % my_vars['v3'].keys()[0]
##############################

From arcege at gmail.com  Sun Jul 16 23:31:23 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Sun, 16 Jul 2006 17:31:23 -0400
Subject: [Tutor] So close! But ... error: (10054,
	'Connection reset by peer')
In-Reply-To: <002601c6a8b4$974fd910$8b4a6244@valued61da873e>
References: <002601c6a8b4$974fd910$8b4a6244@valued61da873e>
Message-ID: <7e5ba9220607161431k78f5bd62xc744f97f7029522@mail.gmail.com>

You are running on a PC, which doesn't have a SMTP server running on it.
The default hostname for smtplib.SMTP().connect() is to localhost (your own
machine).   You will need to find out the hostname of the mail server that
your ISP provides.  You probably set it when you set up your email (based on
a little research, it looks to be "smtp.cox.net").
  -Arcege

On 7/16/06, Grady Henry <gwhjr at cox.net> wrote:
>
>  *I think that I am so close to getting this simple program to run
> correctly:*
> **
> # Import smtplib for the actual sending function
> import smtplib
>
> # Import the email modules we'll need
> from email.MIMEText import MIMEText
>
> # Open a plain text file for reading.  For this example, assume that
> # the text file contains only ASCII characters.
> fp = open(r'C:\Documents and Settings\User\Desktop\\text3.txt')
> # Create a text/plain message
> msg = MIMEText(fp.read())
> fp.close()
>
> # me == the sender's email address
> # you == the recipient's email address
> msg['Subject'] = 'The contents of %s' % 'C:\Documents and
> Settings\User\Desktop\\text3.txt'
> msg['From'] = 'gwhjr at cox.net' <%27gwhjr at cox.net%27>
> msg['To'] = 'gwhjr at bigfoot.com' <%27gwhjr at bigfoot.com%27>
>
> # Send the message via our own SMTP server, but don't include the
> # envelope header.
> s = smtplib.SMTP()
> s.set_debuglevel(1)
> s.connect(host='', port=25)
> __init__(self, host='', port=25, local_hostname=None)
> s.sendmail('gwhjr at cox.net' <%27gwhjr at cox.net%27>, ['gwhjr at bigfoot.com'],
> msg.as_string())
> s.quit()
> s.close()
>
> *But when I run it using IDLE, I get the following:*
> **
>
> IDLE 1.1.3      ==== No Subprocess ====
> >>>
> connect: ('', 25)
> connect: ('', 25)
> Traceback (most recent call last):
>   File "C:\Documents and Settings\User\Desktop\textsender.py", line 24, in
> ?
>     s.connect(host='', port=25)
>   File "C:\Python24\lib\smtplib.py", line 307, in connect
>     (code, msg) = self.getreply()
>   File "C:\Python24\lib\smtplib.py", line 348, in getreply
>     line = self.file.readline()
>   File "C:\Python24\lib\socket.py", line 340, in readline
>     data = self._sock.recv(self._rbufsize)
> error: (10054, 'Connection reset by peer')
> >>>
>
> *Can anybody help?*
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060716/f45d9d9f/attachment.html 

From Barry.Carroll at psc.com  Mon Jul 17 18:47:56 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 17 Jul 2006 09:47:56 -0700
Subject: [Tutor] How do you implement a config file?
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36E2@eugsrv400.psc.pscnet.com>

Tracy:

> Date: Sat, 15 Jul 2006 22:44:43 -0700 (PDT)
> From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] How do you implement a config file?
> To: Tracy R Reed <treed at ultraviolet.org>
> Cc: tutor at python.org
> Message-ID: <Pine.LNX.4.64.0607152238410.27927 at hkn.eecs.berkeley.edu>
> Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed
> 
> 
> 
> > I am writing a small python application that needs a few variables
to be
> > end user configurable. Right now I just have the variables right up
> > front where the user can tweak them in the program code and a big
> > commented line that says "Nothing editable past this point." But I
would
> > like to be able to break this out into a separate config file. There
are
> > two ways I see to do this:
> 
> Hi Tracy,
> 
> [config parser approach cut]
> 
> > I don't see any good way to do that either without actually making
my
> > config file a module and calling it config.py instead of
> > application.config.
> 
> This second approach --- using a module as a configuration file --- is
the
> programmer-friendly one.  *grin* If you can get away with this, it's
> probably the simplest to implement.  It also seems to be the approach
that
> most Python programs use, bar more sophisticated approaches like XML
or
> some other structured data format.
> 
> We had some discussion about this earlier the last few weeks (and
months!
> Someone should put this on the FAQ!), and the concensus seems to be
that
> ConfigParser is a bit limiting:
> 
>
http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/3116794
>      http://mail.python.org/pipermail/tutor/2006-June/047557.html

I like to implement config data as a Python dictionary.  Doing so makes
things almost trivial. To use your example:

In config.py
>>>>>>>
configdata = {
  "foo": ['bar','baz','bah']
  .
  .
  .
}
>>>>>>>

In application.py
>>>>>>>
from config import configdata
.
.
.
foo = configdata["foo"]
>>>>>>>

The drawback, of course, is that the application's administrator must
understand enough Python to fill in a dictionary.  As Danny says, if you
can get away with that caveat, the dictionary approach is easy to
implement.  

Another method is to store your config data in XML format.  This is a
little more complex to implement, but has a couple of advantages. First,
since XML is a pretty widely accepted standard, is reasonable to expect
the application's administrator to know it.  Second, you can name the
config file whatever you want: "application.config" works just fine
(although you might want to add "XML" to the file name somewhere).

Again, from your example:

In appXML.config:
>>>>>>>
[configdata]
  [foo]
    bar
    baz
    bah
  [/foo]
  .
  .
  .
[/configdata]
>>>>>>>

I haven't used XML for this purpose (yet), so I can't help you with the
Python XML parser, but you can get more information on the WEB:

      http://pyxml.sourceforge.net/topics/

HTH.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



From tiagosaboga at terra.com.br  Tue Jul 18 03:22:49 2006
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Mon, 17 Jul 2006 22:22:49 -0300
Subject: [Tutor] python file browser with urwid
Message-ID: <200607172222.50120.tiagosaboga@terra.com.br>

I'm trying to write a file browser with urwid. In the future, I want to make a 
light front-end for cds burning, but for now I'm doing it as an exercise. The 
problem is I'm a little stuck now. I'm sending my actual working code, with 
some working functionality, but I would like to know if I should go ahead or 
if I stop now to make it better.

In fact, I don't know why I'm using a pyrun class, so I think I should get rid 
of it. And I think my try/except clause in pyrun's __init__ method is ugly, 
but I couldn't find nothing better.

Ah, and thanks everybody who helped me some months ago; I had some personal 
problems and couldn't answer, but it really helped.

Tiago.

The code:

#!/usr/bin/python

import urwid
import urwid.curses_display
import os

ui = urwid.curses_display.Screen()

ui.register_palette( [
	('splash', 'black', 'dark red'),
	('bg_splash', 'black', 'dark blue'),
	('header', 'white', 'black'),
	('footer', 'dark red', 'light gray'),
	('browser', 'white', 'dark blue'),
	('selected', 'white', 'dark red'),
	('file', 'light gray', 'dark blue'),
	('dir', 'light magenta', 'dark blue')
	  ])

def run():
	size = ui.get_cols_rows()
	inst = pyrun()
	inst.main()

class pyrun:
	def __init__(self):
		try:
			self.items = self.get_file_names( self.cwd )
		except AttributeError:
			self.initial_cwd = os.getcwd()
			self.cwd = self.initial_cwd
			self.items = self.get_file_names( self.cwd )
		self.listbox = urwid.AttrWrap ( urwid.ListBox( self.items ), 'browser')
		menu_txt = urwid.Text("F1 - Help     F2 - Options     F10 - Quit    
Now: %s" % self.cwd)
		header = urwid.AttrWrap( menu_txt, 'header')
		down_txt = urwid.Text("pybrowser. Left Arrow: Parent.")
		footer = urwid.AttrWrap( down_txt, 'footer')
		self.top = urwid.Frame( self.listbox, header, footer )
		
	def main(self):
		size = ui.get_cols_rows()
				
		while True:
			self.draw_screen( size )
			keys = ui.get_input()
			if "f10" in keys:
				break
			for k in keys:
				if k == "window resize":
					size = ui.get_cols_rows()
					continue
				elif k == "left":
					self.cwd = os.path.split(self.cwd)[0]
					self.__init__()
					continue
	def draw_screen( self, size ):
		canvas = self.top.render( size, focus=True )
		ui.draw_screen( size, canvas )
	
	def get_file_names(self, cwd):
		desc_list = os.listdir( cwd )
		dir_list = []
		file_list = []
		
		for f in desc_list:
			if os.path.isdir(os.path.join(cwd, f)):
				dir_list.append(f)
			elif os.path.isfile(os.path.join(cwd,f)):
				file_list.append(f)
		
		
		file_list = [ urwid.AttrWrap ( urwid.Text(f) , 'file') for f in file_list ] 
		dir_list = [ urwid.AttrWrap ( urwid.Text(f) , 'dir')  for f in dir_list ]
		
		return ( dir_list + file_list )
		
ui.run_wrapper( run )

From kent37 at tds.net  Tue Jul 18 04:00:11 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 17 Jul 2006 22:00:11 -0400
Subject: [Tutor] python file browser with urwid
In-Reply-To: <200607172222.50120.tiagosaboga@terra.com.br>
References: <200607172222.50120.tiagosaboga@terra.com.br>
Message-ID: <44BC40AB.3040802@tds.net>

Tiago Saboga wrote:
> I'm trying to write a file browser with urwid. In the future, I want to make a 
> light front-end for cds burning, but for now I'm doing it as an exercise. The 
> problem is I'm a little stuck now. I'm sending my actual working code, with 
> some working functionality, but I would like to know if I should go ahead or 
> if I stop now to make it better.
>
> In fact, I don't know why I'm using a pyrun class, so I think I should get rid 
> of it. And I think my try/except clause in pyrun's __init__ method is ugly, 
> but I couldn't find nothing better.
>   
The class seems to be mostly used as a container for a few variables. 
That's an OK reason to use a class. You might be able to use functions 
with a few more parameters, but if the alternative is to use global 
variables I would use a class. I don't know urwid but in my experience 
GUI programs tend to be object-oriented so I wouldn't sweat that.

get_file_names() doesn't use self at all so it could be a module function.

I would break up __init__() into two parts, an actual initializer that just initializes self.initial_cwd and self.cwd, and a new function (reset()?) that does the rest of the work. Then __init__() and main() would both call reset() and you could get rid of the try/except.

Kent 

> Ah, and thanks everybody who helped me some months ago; I had some personal 
> problems and couldn't answer, but it really helped.
>
> Tiago.
>
> The code:
>
> #!/usr/bin/python
>
> import urwid
> import urwid.curses_display
> import os
>
> ui = urwid.curses_display.Screen()
>
> ui.register_palette( [
> 	('splash', 'black', 'dark red'),
> 	('bg_splash', 'black', 'dark blue'),
> 	('header', 'white', 'black'),
> 	('footer', 'dark red', 'light gray'),
> 	('browser', 'white', 'dark blue'),
> 	('selected', 'white', 'dark red'),
> 	('file', 'light gray', 'dark blue'),
> 	('dir', 'light magenta', 'dark blue')
> 	  ])
>
> def run():
> 	size = ui.get_cols_rows()
> 	inst = pyrun()
> 	inst.main()
>
> class pyrun:
> 	def __init__(self):
> 		try:
> 			self.items = self.get_file_names( self.cwd )
> 		except AttributeError:
> 			self.initial_cwd = os.getcwd()
> 			self.cwd = self.initial_cwd
> 			self.items = self.get_file_names( self.cwd )
> 		self.listbox = urwid.AttrWrap ( urwid.ListBox( self.items ), 'browser')
> 		menu_txt = urwid.Text("F1 - Help     F2 - Options     F10 - Quit    
> Now: %s" % self.cwd)
> 		header = urwid.AttrWrap( menu_txt, 'header')
> 		down_txt = urwid.Text("pybrowser. Left Arrow: Parent.")
> 		footer = urwid.AttrWrap( down_txt, 'footer')
> 		self.top = urwid.Frame( self.listbox, header, footer )
> 		
> 	def main(self):
> 		size = ui.get_cols_rows()
> 				
> 		while True:
> 			self.draw_screen( size )
> 			keys = ui.get_input()
> 			if "f10" in keys:
> 				break
> 			for k in keys:
> 				if k == "window resize":
> 					size = ui.get_cols_rows()
> 					continue
> 				elif k == "left":
> 					self.cwd = os.path.split(self.cwd)[0]
> 					self.__init__()
> 					continue
> 	def draw_screen( self, size ):
> 		canvas = self.top.render( size, focus=True )
> 		ui.draw_screen( size, canvas )
> 	
> 	def get_file_names(self, cwd):
> 		desc_list = os.listdir( cwd )
> 		dir_list = []
> 		file_list = []
> 		
> 		for f in desc_list:
> 			if os.path.isdir(os.path.join(cwd, f)):
> 				dir_list.append(f)
> 			elif os.path.isfile(os.path.join(cwd,f)):
> 				file_list.append(f)
> 		
> 		
> 		file_list = [ urwid.AttrWrap ( urwid.Text(f) , 'file') for f in file_list ] 
> 		dir_list = [ urwid.AttrWrap ( urwid.Text(f) , 'dir')  for f in dir_list ]
> 		
> 		return ( dir_list + file_list )
> 		
> ui.run_wrapper( run )
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From devayani.barve at gmail.com  Tue Jul 18 07:30:48 2006
From: devayani.barve at gmail.com (devayani barve)
Date: Tue, 18 Jul 2006 11:00:48 +0530
Subject: [Tutor] python challenge 2
Message-ID: <301929340607172230i69567cf5m75aaae0ea025c8d8@mail.gmail.com>

this is what i did for level 2 of python challenge:


dict={'a':'c','b':'d','c':'e','d':'f','e':'g','f':'h','g':'i','h':'j','i':'k','j':'l','k':'m','l':'n','m':'o','n':'p','o':'q','p':'r','q':'s','r':'t','s':'u','t':'v','u':'w','v':'x','w':'y','x':'z','y':'a','z':'b','.':'.',"'":"'","(":"(",")":")","
":" "}

s="g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp.
bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle.
sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
f=file('book.txt','w')
f.write(s)
f.close()
f=file('book.txt')
k=[]
while True:
    line=f.readline()
    if len(line)==0:
        break
    k=[line]
    list=[]
    for elem in k:
        for c in elem:
             temp=dict[c]
             print dict[c],


And i got this:



i   h o p e   y o u   d i d n t   t r a n s l a t e   i t   b y   h a n d
.   t h a t s   w h a t   c o m p u t e r s   a r e   f o r .   d o i n g
i t   i n   b y   h a n d   i s   i n e f f i c i e n t   a n d   t h a t '
s   w h y   t h i s   t e x t   i s   s o   l o n g .   u s i n g   s t r i
n g . m a k e t r a n s ( )   i s   r e c o m m e n d e d .   n o w   a p p
l y   o n   t h e   u r l .



I pasted the above text in the url before .html  and got permission
denied!!!

is my solution wrong?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060718/ab509268/attachment.htm 

From rabidpoobear at gmail.com  Tue Jul 18 08:14:19 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 18 Jul 2006 01:14:19 -0500
Subject: [Tutor] python challenge 2
In-Reply-To: <301929340607172230i69567cf5m75aaae0ea025c8d8@mail.gmail.com>
References: <301929340607172230i69567cf5m75aaae0ea025c8d8@mail.gmail.com>
Message-ID: <44BC7C3B.5020103@gmail.com>

devayani barve wrote:
> this is what i did for level 2 of python challenge:
>  
>
> dict={'a':'c','b':'d','c':'e','d':'f','e':'g','f':'h','g':'i','h':'j','i':'k','j':'l','k':'m','l':'n','m':'o','n':'p','o':'q','p':'r','q':'s','r':'t','s':'u','t':'v','u':'w','v':'x','w':'y','x':'z','y':'a','z':'b','.':'.',"'":"'","(":"(",")":")"," 
> ":" "}
>
> s="g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc 
> dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm 
> jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
> f=file('book.txt','w')
> f.write(s)
> f.close()
> f=file('book.txt')
> k=[]
> while True:
>     line=f.readline()
>     if len(line)==0:
>         break
>     k=[line]
>     list=[]
>     for elem in k:
>         for c in elem:
>              temp=dict[c]              
>              print dict[c],
>
>  
> And i got this:
>
>  
>
> i   h o p e   y o u   d i d n t   t r a n s l a t e   i t   b y   h a 
> n d .   t h a t s   w h a t   c o m p u t e r s   a r e   f o r .   d 
> o i n g   i t   i n   b y   h a n d   i s   i n e f f i c i e n t   a 
> n d   t h a t ' s   w h y   t h i s   t e x t   i s   s o   l o n g 
> .   u s i n g   s t r i n g . m a k e t r a n s ( )   i s   r e c o m 
> m e n d e d .   n o w   a p p l y   o n   t h e   u r l .
>
>  
>
> I pasted the above text in the url before .html  and got permission 
> denied!!!
>
> is my solution wrong?
>
>   
"apply on the url."
run the previous solution's url through your program.

From samrobertsmith at gmail.com  Tue Jul 18 09:40:36 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Tue, 18 Jul 2006 00:40:36 -0700
Subject: [Tutor] about copy.copy
Message-ID: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>

what is the difference between b and c in the following code?
import copy
a=[1,4,5]
b=a
c=copy.copy(a)

Linda

From rabidpoobear at gmail.com  Tue Jul 18 09:47:56 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 18 Jul 2006 02:47:56 -0500
Subject: [Tutor] about copy.copy
In-Reply-To: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>
Message-ID: <44BC922C.8090504@gmail.com>

linda.s wrote:
> what is the difference between b and c in the following code?
#---copyexample.py
import copy
a=[1,4,5]
b=a
c=copy.copy(a)

del(a[0])
print a
print b
print c

#---eof

output:
[4, 5]
[4, 5]
[1, 4, 5]


I.E. 'b' is just a reference to 'a', so modifying 'a' by deleting an 
element changed the value of 'b' (since they are really both just 
references to the
same data structure in memory.)

From samrobertsmith at gmail.com  Tue Jul 18 09:58:00 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Tue, 18 Jul 2006 00:58:00 -0700
Subject: [Tutor] about copy.copy
In-Reply-To: <44BC922C.8090504@gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>
	<44BC922C.8090504@gmail.com>
Message-ID: <1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>

But in the following example, a/b/c change and it looks like there is
no difference.
>>> a=[[1,2,3], [4,5,6]]
>>> b=a
>>> c=copy.copy(a)
>>> a[0][0]='a'
>>> a
[['a', 2, 3], [4, 5, 6]]
>>> b
[['a', 2, 3], [4, 5, 6]]
>>> c
[['a', 2, 3], [4, 5, 6]]

On 7/18/06, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> linda.s wrote:
> > what is the difference between b and c in the following code?
> #---copyexample.py
> import copy
> a=[1,4,5]
> b=a
> c=copy.copy(a)
>
> del(a[0])
> print a
> print b
> print c
>
> #---eof
>
> output:
> [4, 5]
> [4, 5]
> [1, 4, 5]
>
>
> I.E. 'b' is just a reference to 'a', so modifying 'a' by deleting an
> element changed the value of 'b' (since they are really both just
> references to the
> same data structure in memory.)
>

From rabidpoobear at gmail.com  Tue Jul 18 10:00:49 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 18 Jul 2006 03:00:49 -0500
Subject: [Tutor] about copy.copy
In-Reply-To: <1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>	
	<44BC922C.8090504@gmail.com>
	<1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
Message-ID: <44BC9531.4070406@gmail.com>

linda.s wrote:
> But in the following example, a/b/c change and it looks like there is
> no difference. 
I don't know then :)
I'm sure Kent or Alan can give you the lowdown.  They're probably 
sleepin' right now or something.
I'd say try googling 'copy.copy documentation', see what you get.

From kent37 at tds.net  Tue Jul 18 11:51:08 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Jul 2006 05:51:08 -0400
Subject: [Tutor] python challenge 2
In-Reply-To: <301929340607172230i69567cf5m75aaae0ea025c8d8@mail.gmail.com>
References: <301929340607172230i69567cf5m75aaae0ea025c8d8@mail.gmail.com>
Message-ID: <44BCAF0C.7040804@tds.net>

devayani barve wrote:
> this is what i did for level 2 of python challenge:
Please don't post verbatim solutions to the challenges, let's leave some 
challenge in it for those who come after.

Kent


From kent37 at tds.net  Tue Jul 18 11:54:42 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Jul 2006 05:54:42 -0400
Subject: [Tutor] about copy.copy
In-Reply-To: <44BC9531.4070406@gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>		<44BC922C.8090504@gmail.com>	<1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
	<44BC9531.4070406@gmail.com>
Message-ID: <44BCAFE2.3050704@tds.net>

Luke Paireepinart wrote:
> linda.s wrote:
>   
>> But in the following example, a/b/c change and it looks like there is
>> no difference. 
>>     
> I don't know then :)
> I'm sure Kent or Alan can give you the lowdown.  They're probably 
> sleepin' right now or something.

The python tutors never sleep. We are carefully distributed around the 
globe to ensure 24-hour coverage of the list ;)

Hmm, come to think of it our coverage in east Asia might be a little thin...

Kent


From kraus at hagen-partner.de  Tue Jul 18 11:58:06 2006
From: kraus at hagen-partner.de (Wolfram Kraus)
Date: Tue, 18 Jul 2006 11:58:06 +0200
Subject: [Tutor] about copy.copy
In-Reply-To: <1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>	<44BC922C.8090504@gmail.com>
	<1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
Message-ID: <e9ibbe$6nv$1@sea.gmane.org>

On 18.07.2006 09:58, linda.s wrote:
> But in the following example, a/b/c change and it looks like there is
> no difference.
>>>> a=[[1,2,3], [4,5,6]]
>>>> b=a
>>>> c=copy.copy(a)
>>>> a[0][0]='a'
>>>> a
> [['a', 2, 3], [4, 5, 6]]
>>>> b
> [['a', 2, 3], [4, 5, 6]]
>>>> c
> [['a', 2, 3], [4, 5, 6]]
> 

If you wanna do this, you need copy.deepcopy. See
http://docs.python.org/lib/module-copy.html for an explanation

HTH,
Wolfram


From kent37 at tds.net  Tue Jul 18 12:07:18 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Jul 2006 06:07:18 -0400
Subject: [Tutor] about copy.copy
In-Reply-To: <44BC922C.8090504@gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>
	<44BC922C.8090504@gmail.com>
Message-ID: <44BCB2D6.7030804@tds.net>

Luke Paireepinart wrote:
> linda.s wrote:
>   
>> what is the difference between b and c in the following code?
>>     
> #---copyexample.py
> import copy
> a=[1,4,5]
> b=a
> c=copy.copy(a)
>
> del(a[0])
> print a
> print b
> print c
>
> #---eof
>
> output:
> [4, 5]
> [4, 5]
> [1, 4, 5]
>
>
> I.E. 'b' is just a reference to 'a', so modifying 'a' by deleting an 
> element changed the value of 'b' (since they are really both just 
> references to the
> same data structure in memory.)
>   
Assignment makes a new reference to the same object. When you say
  b = a
b and a now refer to the same object, in this case a list. Another way 
to say this is, a and b are aliases of the same object. If the object is 
mutable (can be changed), then any change to the object through either 
reference is equivalent.

Note that some objects, like ints and strings, are immutable - they 
can't be changed. If you say
  a = 1
  b = a
  a = a + 1
you are actually making a refer to a new integer with the value two, so 
b doesn't change.

When you use copy.copy(), you create a /shallow copy/ of a. A shallow 
copy only copies one level deep. So when a is a list, a shallow copy 
makes a new list populated with references to the same objects as 
contained in the original list.

This is a situation very similar to a=b, except it is pushed down one 
level. If the list elements themselves are mutable then changes to the 
elements in one list will be reflected in the other list. In your case, 
you made a list of lists. Copying with copy.copy() makes a new list 
whose elements are references to the same lists as contained in the 
original list. Changing one of the elements is reflected in both lists.

Try copy.deepcopy() if you want to make copies all the way down.

This article might help you understand the semantics of assignment in 
Python:
http://effbot.org/zone/python-objects.htm

Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From sanelson at gmail.com  Tue Jul 18 12:08:31 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Tue, 18 Jul 2006 11:08:31 +0100
Subject: [Tutor] Comparing times
Message-ID: <b6131fdc0607180308n1f3f3d0cw2040feb5687e2616@mail.gmail.com>

Hello there,

I need to be able to compare time on a process tree with system time,
and take action accordingly.

Here's how I get the time on the process  tree:

>>> for line in os.popen("ps -ef", "r"):
...     if "telnet" in line:
...             print line.split()[4]
...
11:00:25
11:01:31
10:01:25
09:57:38
09:15:15

I can get the system time like this:

>>> print time.ctime(time.time()).split()[3]
11:02:58

What I want to do is establish if the time of the process is *later*
than the system date.  For example, we might have a process with a
time of 11:15:00, when the system time is 10:00:00.  In practice this
means that the process is from 11am yesterday.

Other than splitting the string up more and saying is 11 bigger than
10, how can I go about this?

Also, is my time getting method above ok?  Or are there better / more
elegant / more pythonic ways?

S.

From tinoloc at gmail.com  Tue Jul 18 14:20:50 2006
From: tinoloc at gmail.com (Tino Dai)
Date: Tue, 18 Jul 2006 08:20:50 -0400
Subject: [Tutor] General programming question
Message-ID: <e033edfb0607180520g1bc59bcexa892725794f5cbb9@mail.gmail.com>

Hi Everybody,

     I have a general question about programming. My program that I have
been writing is fully modularized. My question is: Is there a programming
technique that would alleviate the passing of a huge number of variables.
Let me further elucidate. I could see a day when I would be writing a
several thousand line program that the variables that I would be passing
into a object's method would be several lines long. In writing this email, I
see two solutions. One is packing them into a list or a dictionary and then
passing it up to the method. The second I could see is passing variables
into an ancestor and having that variable(s) propogate into the children,
grandchildren, etc, etc so that you would be passing the set of variables
once instead into the ancestor rather than to all the children. And I would
like to throw this out to the tutor list for some advice. Thanks

-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060718/ca1b9441/attachment.html 

From Dean.Gardner at barco.com  Tue Jul 18 14:18:22 2006
From: Dean.Gardner at barco.com (Gardner, Dean)
Date: Tue, 18 Jul 2006 14:18:22 +0200
Subject: [Tutor] Win32Com.client help
Message-ID: <EA32F9F395E3BF4092CC796CD7279B751C5B70@EDIMEX01.barco.com>

Hi 

I have been looking at simple examples of controlling applications like
excel and word using python. All seems well until I read in a word document
with multiple lines. It then seems to pick out seemingly random sections of
the document to display. 

This is the class that is handling the opening etc of the document 

class word: 
    def __init__(self, filename=None): 
        """ 
           @ Opens a word document specified by the user 
        """ 
        print "Initiating and opening..."+str(filename) 
        
        self.wdApp = win32com.client.Dispatch('Word.Application')      
        self.wdDoc = self.wdApp.Documents.Open(filename) 
        
    def save(self, newfilename=None): 
        """ Saves the open document with 
            a user defined new filename 
        """ 
        if newfilename: 
            self.filename = newfilename 
            self.wdDoc.SaveAs(newfilename) 
        else: 
            self.wdDoc.Save() 
    
       
    def close(self): 
        
        print "Preparing to close" 
        #self.wdDoc.Close() 
        self.wdDoc.Close() 
        self.wdApp.Quit() 
        
        #del self.wdApp 

    def show(self): 
        self.wdApp.Visible = 1 

    def hide(self): 
        self.wdApp.Visible = 0 
        
    
    def getFileContents(self): 
        print "Get file contents" 
        docString = self.wdApp.Documents[0].Content 
        
        return str(docString).decode('latin-1') 

Dean Gardner
Test Engineer 
Barco
Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK
Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799
www.barco.com 
dean.gardner at barco.com 
Unless indicated otherwise, the information contained in this message is
privileged and confidential, and is intended only for the use of the
addressee(s) named above and others who have been specifically authorized to
receive it. If you are not the intended recipient, you are hereby notified
that any dissemination, distribution or copying of this message and/or
attachments is strictly prohibited. The company accepts no liability for any
damage caused by any virus transmitted by this email. Furthermore, the
company does not warrant a proper and complete transmission of this
information, nor does it accept liability for any delays. If you have
received this message in error, please contact the sender and delete the
message. Thank you.



- - - - - - - DISCLAIMER- - - - - - - -
Unless indicated otherwise, the information contained in this message is
privileged and confidential, and is intended only for the use of the
addressee(s) named above and others who have been specifically authorized to
receive it. If you are not the intended recipient, you are hereby notified
that any dissemination, distribution or copying of this message and/or
attachments is strictly prohibited. The company accepts no liability for any
damage caused by any virus transmitted by this email. Furthermore, the
company does not warrant a proper and complete transmission of this
information, nor does it accept liability for any delays. If you have
received this message in error, please contact the sender and delete the
message. Thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060718/193f20c9/attachment.htm 

From kent37 at tds.net  Tue Jul 18 14:42:03 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Jul 2006 08:42:03 -0400
Subject: [Tutor] General programming question
In-Reply-To: <e033edfb0607180520g1bc59bcexa892725794f5cbb9@mail.gmail.com>
References: <e033edfb0607180520g1bc59bcexa892725794f5cbb9@mail.gmail.com>
Message-ID: <44BCD71B.5060709@tds.net>

Tino Dai wrote:
> Hi Everybody,
>
>      I have a general question about programming. My program that I 
> have been writing is fully modularized. My question is: Is there a 
> programming technique that would alleviate the passing of a huge 
> number of variables. Let me further elucidate. I could see a day when 
> I would be writing a several thousand line program that the variables 
> that I would be passing into a object's method would be several lines 
> long. In writing this email, I see two solutions. One is packing them 
> into a list or a dictionary and then passing it up to the method. 
You can also create a class to hold the variables and pass a class 
instance to the method.
> The second I could see is passing variables into an ancestor and 
> having that variable(s) propogate into the children, grandchildren, 
> etc, etc so that you would be passing the set of variables once 
> instead into the ancestor rather than to all the children.
I'm not sure what you mean by this, can you explain?

I guess you are using some classes but maybe your class design doesn't 
fit the data. Try to find clusters of functions that act on the same 
data and put those functions into a class. Ideally your classes will 
each be responsible for a small, well-defined bit of the overall data 
and functionality. Each class carries the data it needs to do its work. 
Then instead of passing around a bunch of parameters you just pass a few 
objects that encapsulate the data.

Kent


From kent37 at tds.net  Tue Jul 18 15:22:21 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Jul 2006 09:22:21 -0400
Subject: [Tutor] General programming question
In-Reply-To: <e033edfb0607180608n29da4915k4d5fbe762c46ca0a@mail.gmail.com>
References: <e033edfb0607180520g1bc59bcexa892725794f5cbb9@mail.gmail.com>	
	<44BCD71B.5060709@tds.net>
	<e033edfb0607180608n29da4915k4d5fbe762c46ca0a@mail.gmail.com>
Message-ID: <44BCE08D.1050003@tds.net>

Tino Dai wrote:
> On 7/18/06, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> 
> wrote:
>
>     Tino Dai wrote:
>     > Hi Everybody,
>     >
>     >      I have a general question about programming. My program that I
>     > have been writing is fully modularized. My question is: Is there a
>     > programming technique that would alleviate the passing of a huge
>     > number of variables. Let me further elucidate. I could see a day
>     when
>     > I would be writing a several thousand line program that the
>     variables
>     > that I would be passing into a object's method would be several
>     lines
>     > long. In writing this email, I see two solutions. One is packing
>     them
>     > into a list or a dictionary and then passing it up to the method.
>     You can also create a class to hold the variables and pass a class
>     instance to the method.
>
>
> Could you give me a snippet of code or a reference page to how you 
> would send a instance to a method
Something like this:

class Params(object):
  def __init__(self, p1, p2):
    self.p1 = p1
    self.p2 = p2

def do_something(params):
  print params.p1, params.p2

p = Params(1, 2)
do_something(p)

Here is a generic class that does pretty much the same thing:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308
>
>     > The second I could see is passing variables into an ancestor and
>     > having that variable(s) propogate into the children, grandchildren,
>     > etc, etc so that you would be passing the set of variables once
>     > instead into the ancestor rather than to all the children.
>     I'm not sure what you mean by this, can you explain?
>
>
> Actually, on revisiting that. It doesn't work. An instance of a parent 
> doesn't have anything to do with an instance of a child variable wise. 
> AKA, if you pass in a variable into an instance of the parent, the 
> child instance doesn't see it. This just means one thing - Tino needs 
> to get to bed earlier! ;)
I still don't know what you mean my parent and child here.
>
>     I guess you are using some classes but maybe your class design doesn't
>     fit the data. Try to find clusters of functions that act on the same
>     data and put those functions into a class. Ideally your classes will
>     each be responsible for a small, well-defined bit of the overall data
>     and functionality. Each class carries the data it needs to do its
>     work.
>     Then instead of passing around a bunch of parameters you just pass
>     a few
>     objects that encapsulate the data.
>
>
>
> Thanks for that  knowledge nugget. I will be using that in my project.

You're welcome.

Kent

PS Please reply on-list.


From dyoo at hkn.eecs.berkeley.edu  Tue Jul 18 17:39:32 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 18 Jul 2006 08:39:32 -0700 (PDT)
Subject: [Tutor] about copy.copy
In-Reply-To: <1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>
	<44BC922C.8090504@gmail.com>
	<1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0607180822260.9838@hkn.eecs.berkeley.edu>



On Tue, 18 Jul 2006, linda.s wrote:

> But in the following example, a/b/c change and it looks like there is
> no difference.
>>>> a=[[1,2,3], [4,5,6]]
>>>> b=a
>>>> c=copy.copy(a)


Hi Linda,

I find it easiest to explain this by going to box-and-pointer diagrams. 
Let me see if this will help you too.

First, some background: we'll say that a "name" is something that's 
directed at a "value" such as a number or a list.  We'll diagram this by 
drawing an arrow from a name to a value.  For example:

     a = 42

will have a diagram of:

     a -------------> 42



We'll treat a list as a value that itself can point at a lot of values. 
For example:

     a = [1, 2, 3]


is going to look like:

     a ------------> [ . , . , . ]
                       |   |   |
                       V   V   V
                       1   2   3

So there's going to be two levels of arrows here.  I'm using periods here 
just as placeholders so you can see where the arrows are starting from.



Ok, with that background, we'll take a look at the diagram for:

     a = [1, 2, 3]
     b = a
     c = copy.copy(a)

                     b
                     |
                     |
                     V
     a ------------> [ . , . , . ]
                       |   |   |
                       V   V   V
                       1   2   3
                       ^   ^   ^
                       |   |   |
     c ------------> [ . , . , . ]


What's going on is that 'a' and 'b' are directed at the same list value. 
'c' is directed at a different list value, but the elements of that new 
list point to the same elements as 'a'.  We call this a "shallow copy" 
because the copying is only a single level deep.


This diagram tries to model what happens when we start mutating the list 
value that 'a' points to.  But let's say that we do a change to one of 
those lists:

     a[0] = 42

This mutates the first cell of the list to point to a value 42.  What does 
this look like?  Try it out, and then look below to compare:

*** spoiler space ***








*** spoiler space ***

Ok, here's the diagram I have:

                     b
                     |
                     |
                     V
     a ------------> [ . , . , . ]
                       |   |   |
                       V   |   |
                      42   |   |
                           |   |
                           V   V
                       1   2   3
                       ^   ^   ^
                       |   |   |
     c ------------> [ . , . , . ]

It shows that 'c' is not going to "change" in the sense that we're not 
going to observe any differences.  It will have appeared, though, that 
mutating the list that 'a' points to will affect 'b'.


Do you have any questions so far about this?  Some kind of model like this 
is necessary to understand the situation you're seeing now, so please feel 
free to ask if any part of this is confusing.

From gsf at panix.com  Tue Jul 18 18:51:14 2006
From: gsf at panix.com (Gabriel Farrell)
Date: Tue, 18 Jul 2006 12:51:14 -0400
Subject: [Tutor] cartesian product recursive loop
Message-ID: <20060718165114.GD10143@panix.com>

In trying to combine a set of lists together, I landed upon
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 , which
does the job beautifully.  The problem is I really want to understand
how it does it, and I can't quite get my brain wrapped around it.
I'll try to explain, step by step, what I think it's doing, and if
someone would be so kind as to try to show me where I'm missing
something, I'd be grateful.

Okay, so here's the function: 

1   def combine(*seqin):
2       def rloop(seqin, listout, comb):
3           if seqin:
4               for item in seqin[0]:
5                   newcomb = comb + [item]
6                   rloop(seqin[1:], listout, newcomb)
7           else:
8               listout.append(comb)
9       listout = []
10      rloop(seqin, listout, [])
11      return listout

We'll start with the example Mr. Klaffenbach gives in the
documentation on the function: combine((1, 2), (3, 4)) .  Line 10 is
the first thing to act upon the list of seqin, looking like this:

    rloop(((1, 2), (3, 4)), [], [])

So we go into the rloop function.  There is something left in the
seqin, so we pass the if statement and hit the for loop.  seqin[0] ==
(1, 2), and comb == [], so newcomb == [1], the first item, and we're
sent back into the rloop with the following new setup:

    rloop(((3, 4)), [], [1])

This time around we pass the if statement again and the first item in
(3, 4) is 3.  comb == [1], so newcomb == [1, 3].  We get sent back to
the top of the rloop with the following new setup:

    rloop((), [], [1, 3])

Now we fail the if statement, so comb is appended to listout and
listout == [[1, 3]], which is the first combination to be returned.

Great.  But, as far as I can see, the whole function should stop right
here.  How does it produce the rest of the combinations?  I suspect
I'm misunderstanding something about the for loop, or the way seqin is
handed into the rloop function.  Any help is much appreciated.

gsf

From kent37 at tds.net  Tue Jul 18 19:33:27 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Jul 2006 13:33:27 -0400
Subject: [Tutor] cartesian product recursive loop
In-Reply-To: <20060718165114.GD10143@panix.com>
References: <20060718165114.GD10143@panix.com>
Message-ID: <44BD1B67.9040203@tds.net>

Gabriel Farrell wrote:
> In trying to combine a set of lists together, I landed upon
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 , which
> does the job beautifully.  The problem is I really want to understand
> how it does it, and I can't quite get my brain wrapped around it.
> I'll try to explain, step by step, what I think it's doing, and if
> someone would be so kind as to try to show me where I'm missing
> something, I'd be grateful.
>
> Okay, so here's the function: 
>
> 1   def combine(*seqin):
> 2       def rloop(seqin, listout, comb):
> 3           if seqin:
> 4               for item in seqin[0]:
> 5                   newcomb = comb + [item]
> 6                   rloop(seqin[1:], listout, newcomb)
> 7           else:
> 8               listout.append(comb)
> 9       listout = []
> 10      rloop(seqin, listout, [])
> 11      return listout
>
> We'll start with the example Mr. Klaffenbach gives in the
> documentation on the function: combine((1, 2), (3, 4)) .  Line 10 is
> the first thing to act upon the list of seqin, looking like this:
>
>     rloop(((1, 2), (3, 4)), [], [])
>
> So we go into the rloop function.  There is something left in the
> seqin, so we pass the if statement and hit the for loop.  seqin[0] ==
> (1, 2), and comb == [], so newcomb == [1], the first item, and we're
> sent back into the rloop with the following new setup:
>
>     rloop(((3, 4)), [], [1])
>
> This time around we pass the if statement again and the first item in
> (3, 4) is 3.  comb == [1], so newcomb == [1, 3].  We get sent back to
> the top of the rloop with the following new setup:
>
>     rloop((), [], [1, 3])
>
> Now we fail the if statement, so comb is appended to listout and
> listout == [[1, 3]], which is the first combination to be returned.
>   
So far so good.
> Great.  But, as far as I can see, the whole function should stop right
> here.  How does it produce the rest of the combinations?  I suspect
> I'm misunderstanding something about the for loop, or the way seqin is
> handed into the rloop function.  Any help is much appreciated.
>   
You misunderstand the way recursion works. When the lowest-level call to 
rloop() returns with listout = [[1, 3]], the next level up is still in 
the first iteration of the for loop. The loop continues with comb=[1] 
and item=4. This leads to a call of  rloop((), [[1, 3]], [1, 4]) which 
returns with listout = [[1, 3], [1, 4]]. The for loop at this level 
returns and the loop at the next level up continues.

Each call to rloop() has its own local variables and its own state. 
Returning from one call doesn't pop all the way up the stack, it resumes 
execution at the point of call with the local state restored to what it 
was before the call.

It might help to put in some print statements to help you track the 
flow, or run the program in a debugger and step through it.

Kent


From bgailer at alum.rpi.edu  Tue Jul 18 19:40:34 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 18 Jul 2006 10:40:34 -0700
Subject: [Tutor] python challenge 2
In-Reply-To: <301929340607172230i69567cf5m75aaae0ea025c8d8@mail.gmail.com>
References: <301929340607172230i69567cf5m75aaae0ea025c8d8@mail.gmail.com>
Message-ID: <44BD1D12.1010300@alum.rpi.edu>

devayani barve wrote:
> this is what i did for level 2 of python challenge:
Please don't publish challenge solutions. That defeats the purpose of 
the challenge.

That said your program takes a very circuitous route to iterate thru a 
string.

Why not just:
dict = ...
s = ...
for c in s:
    print dict[c],

Also since dict and list are built-in functions it is not a good idea to 
reassign these names.

-- 
Bob Gailer
510-978-4454


From chris.arndt at web.de  Tue Jul 18 19:43:22 2006
From: chris.arndt at web.de (Christopher Arndt)
Date: Tue, 18 Jul 2006 18:43:22 +0100
Subject: [Tutor] General programming question
In-Reply-To: <e033edfb0607180520g1bc59bcexa892725794f5cbb9@mail.gmail.com>
References: <e033edfb0607180520g1bc59bcexa892725794f5cbb9@mail.gmail.com>
Message-ID: <44BD1DBA.40700@web.de>

Tino Dai schrieb:
>      I have a general question about programming. My program that I have
> been writing is fully modularized. My question is: Is there a
> programming technique that would alleviate the passing of a huge number
> of variables.

Yes, it's called "object-oriented programming" ;-)

http://en.wikipedia.org/wiki/Object-oriented_programming

And "refactoring":

http://en.wikipedia.org/wiki/Refactoring


Chris

From bgailer at alum.rpi.edu  Tue Jul 18 19:45:02 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 18 Jul 2006 10:45:02 -0700
Subject: [Tutor] Win32Com.client help
In-Reply-To: <EA32F9F395E3BF4092CC796CD7279B751C5B70@EDIMEX01.barco.com>
References: <EA32F9F395E3BF4092CC796CD7279B751C5B70@EDIMEX01.barco.com>
Message-ID: <44BD1E1E.3040208@alum.rpi.edu>

Gardner, Dean wrote:
>
> Hi
>
> I have been looking at simple examples of controlling applications 
> like excel and word using python. All seems well until I read in a 
> word document with multiple lines. It then seems to pick out seemingly 
> random sections of the document to display.
>
> This is the class that is handling the opening etc of the document
>
Please show us the relevant parts of the program. Most of the methods 
you posted have nothing to do with the problem, and the crucial code for 
instantiating the class and calling its methods is missing, as is an 
example of the desired output vs the actual output.
No can help without this.
>
> class word:
>     def __init__(self, filename=None):
>         """
>            @ Opens a word document specified by the user
>         """
>         print "Initiating and opening..."+str(filename)
>        
>         self.wdApp = win32com.client.Dispatch('Word.Application')     
>         self.wdDoc = self.wdApp.Documents.Open(filename)
>        
>     def save(self, newfilename=None):
>         """ Saves the open document with
>             a user defined new filename
>         """
>         if newfilename:
>             self.filename = newfilename
>             self.wdDoc.SaveAs(newfilename)
>         else:
>             self.wdDoc.Save()
>    
>       
>     def close(self):
>        
>         print "Preparing to close"
>         #self.wdDoc.Close()
>         self.wdDoc.Close()
>         self.wdApp.Quit()
>        
>         #del self.wdApp
>
>     def show(self):
>         self.wdApp.Visible = 1
>
>     def hide(self):
>         self.wdApp.Visible = 0
>        
>    
>     def getFileContents(self):
>         print "Get file contents"
>         docString = self.wdApp.Documents[0].Content
>        
>         return str(docString).decode('latin-1')
>
> *Dean Gardner
> *Test Engineer
> Barco
> Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK
> Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799
> _www.barco.com _
> _dean.gardner at barco.com _
> Unless indicated otherwise, the information contained in this message 
> is privileged and confidential, and is intended only for the use of 
> the addressee(s) named above and others who have been specifically 
> authorized to receive it. If you are not the intended recipient, you 
> are hereby notified that any dissemination, distribution or copying of 
> this message and/or attachments is strictly prohibited. The company 
> accepts no liability for any damage caused by any virus transmitted by 
> this email. Furthermore, the company does not warrant a proper and 
> complete transmission of this information, nor does it accept 
> liability for any delays. If you have received this message in error, 
> please contact the sender and delete the message. Thank you.
>
>
> - - - - - - - DISCLAIMER- - - - - - - -
>
> Unless indicated otherwise, the information contained in this message 
> is privileged and confidential, and is intended only for the use of 
> the addressee(s) named above and others who have been specifically 
> authorized to receive it. If you are not the intended recipient, you 
> are hereby notified that any dissemination, distribution or copying of 
> this message and/or attachments is strictly prohibited. The company 
> accepts no liability for any damage caused by any virus transmitted by 
> this email. Furthermore, the company does not warrant a proper and 
> complete transmission of this information, nor does it accept 
> liability for any delays. If you have received this message in error, 
> please contact the sender and delete the message. Thank you.
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
510-978-4454


From tiagosaboga at terra.com.br  Tue Jul 18 19:46:00 2006
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Tue, 18 Jul 2006 14:46:00 -0300
Subject: [Tutor] python file browser with urwid
In-Reply-To: <44BC40AB.3040802@tds.net>
References: <200607172222.50120.tiagosaboga@terra.com.br>
	<44BC40AB.3040802@tds.net>
Message-ID: <200607181446.01093.tiagosaboga@terra.com.br>

Thank you Kent, I've done the modifications you suggested, and the code 
follows. I splitted the __init__ method in four methods (__init__, header, 
footer, dir_browser) and took the get_file_names out of pyrun class. Now I 
have two more general questions, if you don't mind.

1) (first a philosophical/methodological question) I see now that we can use 
classes in at least two ways. In my code, the class, as you said, is used as 
a container. In this case, the distinction class/instance isn't really 
important, as I will never have several instances of the same class. OTOH, I 
suppose it's not really OO programming. These statements are ok?

2) (a technical question, now) How do I test if a variable has been declared? 
In my first code, I used the try/except clause for that, but now you showed 
me a way of doing it without testing. But now I would like to add a cache in 
get_file_names(). For that, I would create a dir_cache variable of type dict, 
and store in it {'cwd': 'dirlist + filelist'} pairs. But how do I know if 
it's the first time, if I have to create the variable or just read from it?

Thanks,

Tiago.

#!/usr/bin/python

import urwid
import urwid.curses_display
import os

ui = urwid.curses_display.Screen()

ui.register_palette( [
	('splash', 'black', 'dark red'),
	('bg_splash', 'black', 'dark blue'),
	('header', 'white', 'black'),
	('footer', 'dark red', 'light gray'),
	('browser', 'white', 'dark blue'),
	('selected', 'white', 'dark red'),
	('file', 'light gray', 'dark blue'),
	('dir', 'light magenta', 'dark blue')
	  ])

def run():
	size = ui.get_cols_rows()
	inst = pyrun()
	inst.main()

class pyrun:
	def __init__(self):
		self.initial_cwd = os.getcwd()
		self.cwd = self.initial_cwd
		
	def main(self):
		size = ui.get_cols_rows()
				
		while True:
			self.draw_screen( size )
			keys = ui.get_input()
			if "f10" in keys:
				break
			for k in keys:
				if k == "window resize":
					size = ui.get_cols_rows()
					continue
				elif k == "left":
					self.cwd = os.path.split(self.cwd)[0]
	
	def header(self):
		menu_txt = urwid.Text("F1 - Help     F2 - Options     F10 - Quit    
Now: %s" % self.cwd)
		return urwid.AttrWrap( menu_txt, 'header')
	
	def footer(self):
		down_txt = urwid.Text("pybrowser. Left Arrow: Parent.")
		return urwid.AttrWrap( down_txt, 'footer')
	
	def dir_browser(self):
		self.items = self.get_file_names ( self.cwd )
		return urwid.AttrWrap ( urwid.ListBox( self.items ), 'browser')
	
	def top_frame(self):
		return urwid.Frame( self.dir_browser(), self.header(), self.footer() )
		
	def draw_screen( self, size ):
		canvas = self.top_frame().render( size, focus=True )
		ui.draw_screen( size, canvas )
	
	def get_file_names(self, cwd):
		desc_list = os.listdir( cwd )
		dir_list = []
		file_list = []
		
		for f in desc_list:
			if os.path.isdir(os.path.join(cwd, f)):
				dir_list.append(f)
			elif os.path.isfile(os.path.join(cwd,f)):
				file_list.append(f)
		
		file_list.sort()
		dir_list.sort()
		
		file_list = [ urwid.AttrWrap ( urwid.Text(f) , 'file') for f in file_list ]
		dir_list = [ urwid.AttrWrap ( urwid.Text(f) , 'dir')  for f in dir_list ]
		
		return ( dir_list + file_list )
		
ui.run_wrapper( run )

From dyoo at hkn.eecs.berkeley.edu  Tue Jul 18 20:03:55 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 18 Jul 2006 11:03:55 -0700 (PDT)
Subject: [Tutor] General programming question
In-Reply-To: <44BD1DBA.40700@web.de>
References: <e033edfb0607180520g1bc59bcexa892725794f5cbb9@mail.gmail.com>
	<44BD1DBA.40700@web.de>
Message-ID: <Pine.LNX.4.64.0607181054190.22278@hkn.eecs.berkeley.edu>



On Tue, 18 Jul 2006, Christopher Arndt wrote:

>> I have a general question about programming. My program that I have 
>> been writing is fully modularized. My question is: Is there a 
>> programming technique that would alleviate the passing of a huge number 
>> of variables.

One of the things we can do is to try to group related values together 
into structures.  In Python, classes act as a way to glue related data 
together.


For example, let's say we have a program that deals with drawing shapes 
like circles.  One way we could imagine doing this is to represent a 
circle as an x/y coordinate, a radius, and a color.  In this situation, 
things that work on circles will take in at least those three arguments:

########################################################
def draw_circle(x, y, radius, color):
     ...
########################################################


But another way to look at this is to say that there is a single thing 
called a Circle with three properties: center_x, center_y, radius, and 
color:

########################################################
class Circle:
     def __init__(self, x, y, r, k):
         (self.center_x, self.center_y,
          self.radius, self.color) = (x, y, r, k)
########################################################


If we have such a structure to glue those four values into a single thing, 
then our functions that deal with circles now only have to pass that one 
thing around:

########################
def draw_circle(circle):
     ...
########################

This technique is how we avoid passing so many separate parameters around: 
we group them together.  The grouping shouldn't be random, so that's where 
intelligence and asthetics comes in.


Best of wishes!

From dyoo at hkn.eecs.berkeley.edu  Tue Jul 18 20:14:23 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 18 Jul 2006 11:14:23 -0700 (PDT)
Subject: [Tutor] General programming question
In-Reply-To: <Pine.LNX.4.64.0607181054190.22278@hkn.eecs.berkeley.edu>
References: <e033edfb0607180520g1bc59bcexa892725794f5cbb9@mail.gmail.com>
	<44BD1DBA.40700@web.de>
	<Pine.LNX.4.64.0607181054190.22278@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0607181105170.22278@hkn.eecs.berkeley.edu>

> For example, let's say we have a program that deals with drawing shapes 
> like circles.  One way we could imagine doing this is to represent a 
> circle as an x/y coordinate, a radius, and a color.  In this situation, 
> things that work on circles will take in at least those three arguments:
                                                           ^^^^^

Ok, so I have some trouble counting.  *grin* Substitute "three arguments" 
with "four arguments".  My draft message message originally used only x, 
radius and color.  When I added in the y coordinate, I forgot to 
compensate.  My apologies!


One other thing to note: this structuring really doesn't have much to do 
with OOP.  It's more fundamental than that!  Many languages have some 
mechanism for defining a way to build compound data.  C has structs and 
Pascal has records.  It just turns out that most OOP-ish languages provide 
one main construct for bundling data in classes.

From john at fouhy.net  Tue Jul 18 22:59:17 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 19 Jul 2006 08:59:17 +1200
Subject: [Tutor] Comparing times
In-Reply-To: <b6131fdc0607180308n1f3f3d0cw2040feb5687e2616@mail.gmail.com>
References: <b6131fdc0607180308n1f3f3d0cw2040feb5687e2616@mail.gmail.com>
Message-ID: <5e58f2e40607181359p583a38c4j2987f1e8d2016f0f@mail.gmail.com>

On 18/07/06, Steve Nelson <sanelson at gmail.com> wrote:
> What I want to do is establish if the time of the process is *later*
> than the system date.  For example, we might have a process with a
> time of 11:15:00, when the system time is 10:00:00.  In practice this
> means that the process is from 11am yesterday.
>
> Other than splitting the string up more and saying is 11 bigger than
> 10, how can I go about this?

Have a look at time.strptime.  Eg, if s is '11:15:00' then
time.strptime(s, '%H:%M:%S') will be a tuple of 9 integers which you
should be able to compare directly with other time tuples.

# untested
def cmptime(s1, s2):
    """Compare two times as strings in %H:%M:%S format."""
    return cmp(time.strptime(s1, '%H:%M:%S'), time.strptime(s2, '%H:%M:%S'))

-- 
John.

From gsf at panix.com  Tue Jul 18 23:51:16 2006
From: gsf at panix.com (Gabriel Farrell)
Date: Tue, 18 Jul 2006 17:51:16 -0400
Subject: [Tutor] cartesian product recursive loop
In-Reply-To: <44BD1B67.9040203@tds.net>
References: <20060718165114.GD10143@panix.com> <44BD1B67.9040203@tds.net>
Message-ID: <20060718215116.GF10143@panix.com>

On Tue, Jul 18, 2006 at 01:33:27PM -0400, Kent Johnson wrote:
> Each call to rloop() has its own local variables and its own state.
> Returning from one call doesn't pop all the way up the stack, it
> resumes execution at the point of call with the local state restored
> to what it was before the call.

Okay, this was the main abstraction I was missing, and you've spelled
it out clearly.  It seems like such an "intelligent" way to handle the
flow -- I think that's what threw me off.

> It might help to put in some print statements to help you track the 
> flow, or run the program in a debugger and step through it.

I *think* I get it.  I read
http://www.ferg.org/papers/debugging_in_python.html , imported pdb,
and inserted pdb.set_trace() after

    def rloop(seqin, listout, comb):

I'm seeing now, by stepping through the program, how it flows.  Pdb is
pretty awesome!  I had a feeling there was something like different
levels of loops going on, but I didn't get it before.  

Thanks, Kent!

gsf

From kent37 at tds.net  Wed Jul 19 00:02:32 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Jul 2006 18:02:32 -0400
Subject: [Tutor] cartesian product recursive loop
In-Reply-To: <20060718215116.GF10143@panix.com>
References: <20060718165114.GD10143@panix.com> <44BD1B67.9040203@tds.net>
	<20060718215116.GF10143@panix.com>
Message-ID: <44BD5A78.9020704@tds.net>

Gabriel Farrell wrote:
>> > Each call to rloop() has its own local variables and its own state.
>> > Returning from one call doesn't pop all the way up the stack, it
>> > resumes execution at the point of call with the local state restored
>> > to what it was before the call.
>>     
>
> Okay, this was the main abstraction I was missing, and you've spelled
> it out clearly.  It seems like such an "intelligent" way to handle the
> flow -- I think that's what threw me off.
>   
This is typical behavior for many languages, not special to Python. 
Generally each invocation of a function will have its own stack frame.

> I read
> http://www.ferg.org/papers/debugging_in_python.html , imported pdb,
> and inserted pdb.set_trace() after
>
>     def rloop(seqin, listout, comb):
>
> I'm seeing now, by stepping through the program, how it flows.  Pdb is
> pretty awesome!  I had a feeling there was something like different
> levels of loops going on, but I didn't get it before.  
>   
Impressive that you picked up pdb so easily. You might be interested in 
a debugger with a GUI, there are several for Python. A primitive one is 
part of IDLE. I like winpdb. Other dev tools have Python debugger 
support as well.
> Thanks, Kent!
You're welcome, it's very gratifying to see the light go on like this :-)

Kent


From wescpy at gmail.com  Wed Jul 19 09:32:58 2006
From: wescpy at gmail.com (wesley chun)
Date: Wed, 19 Jul 2006 00:32:58 -0700
Subject: [Tutor] Win32Com.client help
In-Reply-To: <EA32F9F395E3BF4092CC796CD7279B751C5B70@EDIMEX01.barco.com>
References: <EA32F9F395E3BF4092CC796CD7279B751C5B70@EDIMEX01.barco.com>
Message-ID: <78b3a9580607190032n1dd43918rf6470365a7aaf902@mail.gmail.com>

>         docString = self.wdApp.Documents[0].Content
>         return str(docString).decode('latin-1')


i've been experimenting with Win32 COM client stuff myself lately,
having added a section for it in the upcoming 2nd ed. of Core Python.

i haven't tried what you're doing yet though, but i have seen code
which uses doc.Content.Text.  have you tried that yet? also, i'm
assuming you know that Latin-1 is the correct Unicode decoding for the
file you're looking at?

and as bob has mentioned, do post the instantiation, sample file, and
output, correct or erroneous.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From Bobby.Howerton at park.edu  Tue Jul 18 21:41:35 2006
From: Bobby.Howerton at park.edu (Bobby J. Howerton Jr.)
Date: Tue, 18 Jul 2006 15:41:35 -0400
Subject: [Tutor] Needing to create a program that will search my hard drive
	for	certain files in certain folders
Message-ID: <20060718154135.es4dw0htlx4ws488@pirate.park.edu>

Hello,
I am new to programming in Python, but I am very excited about
the?possibilities that it (Python) has.

I maybe jumping the gun a little bit here, but this is what I would
like to do:
********************************************************************************************

I would like to create an executable program that when ran it will
search my hard drive for certain folders that contain different
files. Once the program finds these folders, I would like the program
to zip each of the folders up and then e-mail each of the folders to a
certain e-mail address.

********************************************************************************************
Is this possible??? I have been told by someone else that it is
I
just want to make sure.

If this is possible
How would I do this (please remember that I am
new to Programming in Python).

Thanks for all of the help.

Bobby
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060718/75fc3fd9/attachment.htm 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060718/75fc3fd9/attachment.html 

From jgcox39 at highstream.net  Wed Jul 19 04:30:04 2006
From: jgcox39 at highstream.net (Joe Cox)
Date: Tue, 18 Jul 2006 22:30:04 -0400
Subject: [Tutor] List Box binding
Message-ID: <AIECKKGNOCPIFINDPNAKMEBLCDAA.jgcox39@highstream.net>

I am using Tk and have a series of Radio buttons that I want to bind to it's
own listbox for further selection.
I just don't get the point how to click the button and select the proper
listbox I want it tied too.
Joe Cox
513-293-4830 mobile
jgcox39 at highstream.net


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060718/f1a4d40d/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/octet-stream
Size: 5665 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060718/f1a4d40d/attachment.obj 

From rabidpoobear at gmail.com  Wed Jul 19 12:16:35 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 19 Jul 2006 05:16:35 -0500
Subject: [Tutor] Needing to create a program that will search my hard
 drive	for	certain files in certain folders
In-Reply-To: <20060718154135.es4dw0htlx4ws488@pirate.park.edu>
References: <20060718154135.es4dw0htlx4ws488@pirate.park.edu>
Message-ID: <44BE0683.1040009@gmail.com>

Bobby J. Howerton Jr. wrote:
> Hello,
> I am new to programming in Python, but I am very excited about the 
> possibilities that it (Python) has.
>
> I maybe jumping the gun a little bit here, but this is what I would
> like to do:
> ********************************************************************************************
>
> I would like to create an executable program that when ran it will
> search my hard drive for certain folders that contain different
> files. Once the program finds these folders, I would like the program 
> to zip each of the folders up and then e-mail each of the folders to a 
> certain e-mail address.
>
> ********************************************************************************************
> Is this possible??? I have been told by someone else that it is?I
> just want to make sure.
yes.
you can do anything in Python you can do in C.
>
> If this is possible?How would I do this (please remember that I am new 
> to Programming in Python).
use the zlib module for packaging the items
use the os.walk function to walk your directories
use smtplib to e-mail the zips
get the address of your smtp server from your e-mail client
or use sendmail if on linux.
use py2exe to make it an executable.

From kent37 at tds.net  Wed Jul 19 12:45:36 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 19 Jul 2006 06:45:36 -0400
Subject: [Tutor] List Box binding
In-Reply-To: <AIECKKGNOCPIFINDPNAKMEBLCDAA.jgcox39@highstream.net>
References: <AIECKKGNOCPIFINDPNAKMEBLCDAA.jgcox39@highstream.net>
Message-ID: <44BE0D50.5000600@tds.net>

Joe Cox wrote:
> I am using Tk and have a series of Radio buttons that I want to bind 
> to it's own listbox for further selection.
> I just don't get the point how to click the button and select the 
> proper listbox I want it tied too.
Do you mean you want clicking on the radio button to enable a listbox? 
It sounds like you need to bind an event handler to clicks on the radio 
button. Can you show us what you have done so far?

Kent

PS please post in plain text not HTML.


From devayani.barve at gmail.com  Wed Jul 19 14:58:21 2006
From: devayani.barve at gmail.com (devayani barve)
Date: Wed, 19 Jul 2006 18:28:21 +0530
Subject: [Tutor] format string
Message-ID: <301929340607190558s5c98f5a6i45f49a73693902fd@mail.gmail.com>

Hi

This is my program:

import urllib
ans='y'
while ans=='y':
    name=raw_input("Enter search:")
    name=name.replace(' ','+')
    name=name.replace('&','%26')
    go_url="http://www.google.co.in/search?hl=en&q=%s"
%name+"&meta=lr\%3Dlang_en"
    print go_url
    page = urllib.urlopen(go_url).read()
    ans=raw_input("do you want to continue?: ")

It gives following error:
Traceback (most recent call last):
  File "C:\python\urllib.py", line 1, in -toplevel-
    import urllib
  File "C:\python\urllib.py", line 9, in -toplevel-
    page = urllib.urlopen(go_url).read()
AttributeError: 'module' object has no attribute 'urlopen'

What does it mean? also I tried to assign go_url as

    go_url="http://www.google.co.in/search?hl=en&q=%s&meta=lr\%3Dlang_en"
%name

It takes the % in "%3D" as a part of  format is there a way I can overcome
this retaining the same manner of assinging?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060719/3e684981/attachment.htm 

From dyoo at hkn.eecs.berkeley.edu  Wed Jul 19 15:50:45 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 19 Jul 2006 06:50:45 -0700 (PDT)
Subject: [Tutor] format string
In-Reply-To: <301929340607190558s5c98f5a6i45f49a73693902fd@mail.gmail.com>
References: <301929340607190558s5c98f5a6i45f49a73693902fd@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0607190643030.21865@hkn.eecs.berkeley.edu>

> It gives following error:
> Traceback (most recent call last):
> File "C:\python\urllib.py", line 1, in -toplevel-
>   import urllib
> File "C:\python\urllib.py", line 9, in -toplevel-
>   page = urllib.urlopen(go_url).read()
> AttributeError: 'module' object has no attribute 'urlopen'


Hi Devanyani,

Change the name of your program to something other than 'urllib.py'. 
What's happening is that your program --- urllib.py --- has the same name 
as the urllib standard library module that you're trying to import.  So 
the program ends up trying to import itself as a module, which is not what 
you want to do.

Python doesn't yet have a nice way to distinguish between your own program 
modules and the standard library's module.  This causes problems from time 
to time, and although it's going to be fixed as a part of PEP 328, that 
fix is still coming.  Until then, you'll want to take special care not to 
name your program with a conflicting name.



> also I tried to assign go_url as
>
>   go_url="http://www.google.co.in/search?hl=en&q=%s&meta=lr\%3Dlang_en"
> %name
>
> It takes the % in "%3D" as a part of  format is there a way I can overcome
> this retaining the same manner of assinging?

You'll want to look into the urllib.urlencode() function.  See:

     http://www.python.org/doc/lib/module-urllib.html

for more details on it.

From dyoo at hkn.eecs.berkeley.edu  Wed Jul 19 15:57:22 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 19 Jul 2006 06:57:22 -0700 (PDT)
Subject: [Tutor] Needing to create a program that will search my hard
 drive for certain files in certain folders
In-Reply-To: <20060718154135.es4dw0htlx4ws488@pirate.park.edu>
References: <20060718154135.es4dw0htlx4ws488@pirate.park.edu>
Message-ID: <Pine.LNX.4.64.0607190651040.21865@hkn.eecs.berkeley.edu>

> I would like to create an executable program that when ran it will 
> search my hard drive for certain folders that contain different files. 
> Once the program finds these folders, I would like the program to zip 
> each of the folders up and then e-mail each of the folders to a certain 
> e-mail address.

Hi Bobby,

This does sound possible.  We had some discussion on things like this a 
few weeks ago; you can browse through the archives at:

     http://mail.python.org/pipermail/tutor/

In particular, last week's thread "how can I copy files recursively":

     http://mail.python.org/pipermail/tutor/2006-July/047903.html

had some information for doing searches across the filesystem.



> If this is possible?  How would I do this (please remember that I am new 
> to Programming in Python).

But are you new to programming?  If you are new to programming, you may 
need to develop some basic programming skills first before tackling your 
problem.


Best of wishes!

From kent37 at tds.net  Wed Jul 19 15:58:31 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 19 Jul 2006 09:58:31 -0400
Subject: [Tutor] format string
In-Reply-To: <301929340607190558s5c98f5a6i45f49a73693902fd@mail.gmail.com>
References: <301929340607190558s5c98f5a6i45f49a73693902fd@mail.gmail.com>
Message-ID: <44BE3A87.30606@tds.net>

devayani barve wrote:
> Hi
>  
> This is my program:
>
> import urllib
> ans='y'
> while ans=='y':   
>     name=raw_input("Enter search:")
>     name=name.replace(' ','+')
>     name=name.replace('&','%26')
>     go_url=" http://www.google.co.in/search?hl=en&q=%s 
> <http://www.google.co.in/search?hl=en&q=%s>" %name+"&meta=lr\%3Dlang_en"
>     print go_url
>     page = urllib.urlopen(go_url).read()
>     ans=raw_input("do you want to continue?: ")
>
> It gives following error: 
>
> Traceback (most recent call last):
>   File "C:\python\urllib.py", line 1, in -toplevel-
>     import urllib
>   File "C:\python\urllib.py", line 9, in -toplevel-
>     page = urllib.urlopen(go_url).read()
> AttributeError: 'module' object has no attribute 'urlopen'
>  
> What does it mean?
Your program is called urllib.py, when you import urllib you are 
importing your own program. Call the program something else (and delete 
C:\python\urllib.pyc) and it should work better.
> also I tried to assign go_url as
>  
>     
> go_url="http://www.google.co.in/search?hl=en&q=%s&meta=lr\%3Dlang_en 
> <http://www.google.co.in/search?hl=en&q=%s&meta=lr%5C%3Dlang_en>" %name
>  
> It takes the % in "%3D" as a part of  format is there a way I 
> can overcome this retaining the same manner of assinging?
If you want a literal % in a format string you have to escape it with 
another %, in other words use %% to get a single literal escape.

Kent



From klappnase at freenet.de  Wed Jul 19 20:05:56 2006
From: klappnase at freenet.de (Michael Lange)
Date: Wed, 19 Jul 2006 20:05:56 +0200
Subject: [Tutor] List Box binding
In-Reply-To: <44BE0D50.5000600@tds.net>
References: <AIECKKGNOCPIFINDPNAKMEBLCDAA.jgcox39@highstream.net>
	<44BE0D50.5000600@tds.net>
Message-ID: <20060719200556.4d8e3aec.klappnase@freenet.de>

On Wed, 19 Jul 2006 06:45:36 -0400
Kent Johnson <kent37 at tds.net> wrote:

> Joe Cox wrote:
> > I am using Tk and have a series of Radio buttons that I want to bind 
> > to it's own listbox for further selection.
> > I just don't get the point how to click the button and select the 
> > proper listbox I want it tied too.
> Do you mean you want clicking on the radio button to enable a listbox? 
> It sounds like you need to bind an event handler to clicks on the radio 
> button. Can you show us what you have done so far?
> 

Usually a set of Radiobuttons should share one variable, and this sounds like they
should also share one command, which might look like:

var = StringVar()
var.set('a')

def radio_command():
    if var.get() == 'a':
        # button with value 'a' selected
        do_this()
    elif var.get() == 'b':
        # button with value 'b' selected
        do_that()
    (etc.)

radio_a = Radiobutton(parent, variable=var, value='a', command=radio_command)
radio_b = Radiobutton(parent, variable=var, value='b', command=radio_command)
(etc.)

I hope this helps

Michael

From cspears2002 at yahoo.com  Thu Jul 20 00:16:35 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed, 19 Jul 2006 15:16:35 -0700 (PDT)
Subject: [Tutor] removing a card
Message-ID: <20060719221635.50887.qmail@web51606.mail.yahoo.com>

Chapter 15 of How to Think Like a Computer Scientist
teaches you how to deal with sets of objects by
creating a deck of cards.  The tutorial can be found
here: http://www.ibiblio.org/obp/thinkCSpy/chap15.htm.

Here is my code so far in card.py:

class Card:
	suitList = ["Clubs", "Diamonds", "Hearts", "Spades"]
	rankList = ["narf", "Ace", "2", "3", "4", "5", "6",
"7",
		     "8", "9", "10", "Jack", "Queen", "King"]

	def __init__(self, suit=0, rank=0):
		self.suit = suit
		self.rank = rank
		
	def __str__(self):
		return (self.rankList[self.rank] + " of " +
			self.suitList[self.suit])
			
	def __cmp__(self):
		#check the suits
		if self.suit > other.suit: return 1
		if self.suit < other.suit: return -1
		#suits are the same...check ranks
		if self.rank > other.rank: return 1
		if self.rank < other.rank: return -1
		#ranks are the same...it's a tie
		return 0
		
		
class Deck:
	def __init__(self):
		self.cards = []
		for suit in range(4):
			for rank in range(1, 14):
				self.cards.append(Card(suit, rank))
				
	def __str__(self):
		s = ""
		for i in range(len(self.cards)):
			s = s + " "*i + str(self.cards[i]) + "\n"
		return s
		
	def shuffle(self):
		import random
		random.shuffle(self.cards)
		
	def removeCard(self, card):
		if card in self.cards:
			self.cards.remove(card)
			return 1
		else:
			return 0
			
	def popCard(self):
		return self.cards.pop()
		
	def isEmpty(self):
		return (len(self.cards) == 0)
		
I get an error message when I use the removeCard
function:

>>> from card import *
>>> deck = Deck()
>>> print deck
Ace of Clubs
 2 of Clubs
  3 of Clubs
   4 of Clubs
        etc.
>>> deck.removeCard(Card(0,2))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "card.py", line 43, in removeCard
    if card in self.cards:
TypeError: __cmp__() takes exactly 1 argument (2
given)

I am confused by this error because I modified __cmp__
in the Card class to take two arguments.  Am I missing
something here?



From john at fouhy.net  Thu Jul 20 00:28:00 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 20 Jul 2006 10:28:00 +1200
Subject: [Tutor] removing a card
In-Reply-To: <20060719221635.50887.qmail@web51606.mail.yahoo.com>
References: <20060719221635.50887.qmail@web51606.mail.yahoo.com>
Message-ID: <5e58f2e40607191528q7df2197au268813500a9feaf0@mail.gmail.com>

On 20/07/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
>        def __cmp__(self):
[...]
> I am confused by this error because I modified __cmp__
> in the Card class to take two arguments.  Am I missing
> something here?

You haven't defined it that way in the code you posted..

I presume you meant to type:

    def __cmp__(self, other)

?

-- 
John.

From sanelson at gmail.com  Thu Jul 20 08:43:04 2006
From: sanelson at gmail.com (Steve Nelson)
Date: Thu, 20 Jul 2006 07:43:04 +0100
Subject: [Tutor] Comparing times
In-Reply-To: <5e58f2e40607181359p583a38c4j2987f1e8d2016f0f@mail.gmail.com>
References: <b6131fdc0607180308n1f3f3d0cw2040feb5687e2616@mail.gmail.com>
	<5e58f2e40607181359p583a38c4j2987f1e8d2016f0f@mail.gmail.com>
Message-ID: <b6131fdc0607192343t22cdb177h1ddad9196cffa185@mail.gmail.com>

On 7/18/06, John Fouhy <john at fouhy.net> wrote:

> On 18/07/06, Steve Nelson <sanelson at gmail.com> wrote:
> > What I want to do is establish if the time of the process is *later*
> > than the system date.  For example, we might have a process with a
> > time of 11:15:00, when the system time is 10:00:00.  In practice this
> > means that the process is from 11am yesterday.
> >
> > Other than splitting the string up more and saying is 11 bigger than
> > 10, how can I go about this?
>
> Have a look at time.strptime.


Yes - I've worked out how to do this with a combination of
time.strptime() and time.mktime(), although the problem I face now is
that datetime objects need a date, and my way of getting the time
doesn't include a way of specifying the date.  Perhaps I should be
clearer:

I have an application which connects using telnet to a server to
communicate.  The application is largely user-driven - ie such a
connection represents a real user in real time.  If they don't log out
of the system, the pty that is associated with the process will remain
used.  There are only 256 available at present, and it only takes a
few dozen lazy users, and we run out of ptys.  Until we increase the
number of ptys, and for housekeeping, even after, we have a method of
checking the STIME property in ps to see if the format has changed
from eg from 12:44:23 to Jan 7.  If it has changed we kill that
process.  I've been asked to rewrite this script into something more
capabale, because we're still seeing sessions connected from the
previous day that could reasonably be killed off.  Eg at 0900 today if
I see a telnetd process with an STIME of 1000 I know it is 23 hours
old, and has been left connected all night, and I can kill it.  My
task therefore is to find the STIME from ps, and somehow assign a date
to it... perhaps I just assign it a date of today, and if the STIME is
*later* that the system time, I know it is actuallly yesterday's?

Just thinking aloud here... but thoughts / advice most welcome.
Incidentally when I get to killing the process, any recommended ways?

S.

From samrobertsmith at gmail.com  Thu Jul 20 09:51:49 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Thu, 20 Jul 2006 00:51:49 -0700
Subject: [Tutor] about copy.copy
In-Reply-To: <Pine.LNX.4.64.0607180822260.9838@hkn.eecs.berkeley.edu>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>
	<44BC922C.8090504@gmail.com>
	<1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
	<Pine.LNX.4.64.0607180822260.9838@hkn.eecs.berkeley.edu>
Message-ID: <1d987df30607200051v5ffd2e47v7ad708cabdf46b23@mail.gmail.com>

On 7/18/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> On Tue, 18 Jul 2006, linda.s wrote:
>
> > But in the following example, a/b/c change and it looks like there is
> > no difference.
> >>>> a=[[1,2,3], [4,5,6]]
> >>>> b=a
> >>>> c=copy.copy(a)
>
>
> Hi Linda,
>
> I find it easiest to explain this by going to box-and-pointer diagrams.
> Let me see if this will help you too.
>
> First, some background: we'll say that a "name" is something that's
> directed at a "value" such as a number or a list.  We'll diagram this by
> drawing an arrow from a name to a value.  For example:
>
>      a = 42
>
> will have a diagram of:
>
>      a -------------> 42
>
>
>
> We'll treat a list as a value that itself can point at a lot of values.
> For example:
>
>      a = [1, 2, 3]
>
>
> is going to look like:
>
>      a ------------> [ . , . , . ]
>                        |   |   |
>                        V   V   V
>                        1   2   3
>
> So there's going to be two levels of arrows here.  I'm using periods here
> just as placeholders so you can see where the arrows are starting from.
>
>
>
> Ok, with that background, we'll take a look at the diagram for:
>
>      a = [1, 2, 3]
>      b = a
>      c = copy.copy(a)
>
>                      b
>                      |
>                      |
>                      V
>      a ------------> [ . , . , . ]
>                        |   |   |
>                        V   V   V
>                        1   2   3
>                        ^   ^   ^
>                        |   |   |
>      c ------------> [ . , . , . ]
>
>
> What's going on is that 'a' and 'b' are directed at the same list value.
> 'c' is directed at a different list value, but the elements of that new
> list point to the same elements as 'a'.  We call this a "shallow copy"
> because the copying is only a single level deep.
>
>
> This diagram tries to model what happens when we start mutating the list
> value that 'a' points to.  But let's say that we do a change to one of
> those lists:
>
>      a[0] = 42
>
> This mutates the first cell of the list to point to a value 42.  What does
> this look like?  Try it out, and then look below to compare:
>
> *** spoiler space ***
>
>
>
>
>
>
>
>
> *** spoiler space ***
>
> Ok, here's the diagram I have:
>
>                      b
>                      |
>                      |
>                      V
>      a ------------> [ . , . , . ]
>                        |   |   |
>                        V   |   |
>                       42   |   |
>                            |   |
>                            V   V
>                        1   2   3
>                        ^   ^   ^
>                        |   |   |
>      c ------------> [ . , . , . ]
>
> It shows that 'c' is not going to "change" in the sense that we're not
> going to observe any differences.  It will have appeared, though, that
> mutating the list that 'a' points to will affect 'b'.
>
>
> Do you have any questions so far about this?  Some kind of model like this
> is necessary to understand the situation you're seeing now, so please feel
> free to ask if any part of this is confusing.
>
But in the following example, a change in a spread to both b and c:
>>> a=[[1,2,3], [4,5,6]]
>>> b=a
>>> c=copy.copy(a)
>>> a[0][0]='a'
>>> a
[['a', 2, 3], [4, 5, 6]]
>>> b
[['a', 2, 3], [4, 5, 6]]
>>> c
[['a', 2, 3], [4, 5, 6]]

From Dean.Gardner at barco.com  Thu Jul 20 10:13:46 2006
From: Dean.Gardner at barco.com (Gardner, Dean)
Date: Thu, 20 Jul 2006 10:13:46 +0200
Subject: [Tutor] Win32Com.client help
Message-ID: <EA32F9F395E3BF4092CC796CD7279B751C5B76@EDIMEX01.barco.com>

Apologies 

Here is the accessor script 


import win32com.client
import tkFileDialog
import string, sys
 

from Excel import *

import word

#Example of Python controlling external apps

#number of the worksheet to be examined
_workSheetNumber = 1

choice = int(raw_input("Do you want to open:\n1) An Excel File\n2) A Word
File\n3) Exit\nPlease Select....."))
if choice==1:
         
    # Open a specific file
    myExcelDoc = tkFileDialog.askopenfilename()
    #open the excel document
    xlOpen = Excel(myExcelDoc)
    print xlOpen

    #obtain a value from a particular cell
    cellValue = xlOpen.get_cell(_workSheetNumber,3,10)
    print cellValue

    #obtain a 2d tuple from a range of cells
    range_of_cells = xlOpen.get_range(_workSheetNumber,1,1,20,3)

    #print the result form getRange()
    for item in range_of_cells:
        for secondItem in range_of_cells:
            print "Example: " +str(item)+":"+str(secondItem)

    #close the file
    xlOpen.close()

elif choice==2:
    # Open a specific word file
    myWordDoc = tkFileDialog.askopenfilename()
    print myWordDoc
    #create new word object
    wdDoc = word.word(myWordDoc)
    #get the file contents
    try:
        docText =unicode("","utf-8")
        tempDoc = wdDoc.getFileContents()
        docText += tempDoc
        print docText
        wdDoc.close()
    except UnicodeEncodeError:
        print "This file cannot be opened due to a unicode error"
        wdDoc.close()
            
elif choice==3:
    sys.exit(0)


With a sample word file looking something like this

Monday
Tuesday
Wednesday
Thursday
Friday

Only friday is printed out. 

With a longer file (I cannot post the exact contents) like

00000 Description
00001 Description1
00002 Description2
00003 Description3
00004 Description4
00005 Description5

Then 00000,00001,00004 is printed out

Dean Gardner
Test Engineer 
Barco
Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK
Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799
www.barco.com 
dean.gardner at barco.com 
Unless indicated otherwise, the information contained in this message is
privileged and confidential, and is intended only for the use of the
addressee(s) named above and others who have been specifically authorized to
receive it. If you are not the intended recipient, you are hereby notified
that any dissemination, distribution or copying of this message and/or
attachments is strictly prohibited. The company accepts no liability for any
damage caused by any virus transmitted by this email. Furthermore, the
company does not warrant a proper and complete transmission of this
information, nor does it accept liability for any delays. If you have
received this message in error, please contact the sender and delete the
message. Thank you. 




-----Original Message-----
From: Bob Gailer [mailto:bgailer at alum.rpi.edu]
Sent: 18 July 2006 18:45
To: Gardner, Dean
Cc: tutor at python.org
Subject: Re: [Tutor] Win32Com.client help


Gardner, Dean wrote:
>
> Hi
>
> I have been looking at simple examples of controlling applications 
> like excel and word using python. All seems well until I read in a 
> word document with multiple lines. It then seems to pick out seemingly 
> random sections of the document to display.
>
> This is the class that is handling the opening etc of the document
>
Please show us the relevant parts of the program. Most of the methods 
you posted have nothing to do with the problem, and the crucial code for 
instantiating the class and calling its methods is missing, as is an 
example of the desired output vs the actual output.
No can help without this.
>
> class word:
>     def __init__(self, filename=None):
>         """
>            @ Opens a word document specified by the user
>         """
>         print "Initiating and opening..."+str(filename)
>        
>         self.wdApp = win32com.client.Dispatch('Word.Application')     
>         self.wdDoc = self.wdApp.Documents.Open(filename)
>        
>     def save(self, newfilename=None):
>         """ Saves the open document with
>             a user defined new filename
>         """
>         if newfilename:
>             self.filename = newfilename
>             self.wdDoc.SaveAs(newfilename)
>         else:
>             self.wdDoc.Save()
>    
>       
>     def close(self):
>        
>         print "Preparing to close"
>         #self.wdDoc.Close()
>         self.wdDoc.Close()
>         self.wdApp.Quit()
>        
>         #del self.wdApp
>
>     def show(self):
>         self.wdApp.Visible = 1
>
>     def hide(self):
>         self.wdApp.Visible = 0
>        
>    
>     def getFileContents(self):
>         print "Get file contents"
>         docString = self.wdApp.Documents[0].Content
>        
>         return str(docString).decode('latin-1')
>
> *Dean Gardner
> *Test Engineer
> Barco
> Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK
> Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799
> _www.barco.com _
> _dean.gardner at barco.com _
> Unless indicated otherwise, the information contained in this message 
> is privileged and confidential, and is intended only for the use of 
> the addressee(s) named above and others who have been specifically 
> authorized to receive it. If you are not the intended recipient, you 
> are hereby notified that any dissemination, distribution or copying of 
> this message and/or attachments is strictly prohibited. The company 
> accepts no liability for any damage caused by any virus transmitted by 
> this email. Furthermore, the company does not warrant a proper and 
> complete transmission of this information, nor does it accept 
> liability for any delays. If you have received this message in error, 
> please contact the sender and delete the message. Thank you.
>
>
> - - - - - - - DISCLAIMER- - - - - - - -
>
> Unless indicated otherwise, the information contained in this message 
> is privileged and confidential, and is intended only for the use of 
> the addressee(s) named above and others who have been specifically 
> authorized to receive it. If you are not the intended recipient, you 
> are hereby notified that any dissemination, distribution or copying of 
> this message and/or attachments is strictly prohibited. The company 
> accepts no liability for any damage caused by any virus transmitted by 
> this email. Furthermore, the company does not warrant a proper and 
> complete transmission of this information, nor does it accept 
> liability for any delays. If you have received this message in error, 
> please contact the sender and delete the message. Thank you.
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
510-978-4454

- - - - - - - DISCLAIMER- - - - - - - -
Unless indicated otherwise, the information contained in this message is
privileged and confidential, and is intended only for the use of the
addressee(s) named above and others who have been specifically authorized to
receive it. If you are not the intended recipient, you are hereby notified
that any dissemination, distribution or copying of this message and/or
attachments is strictly prohibited. The company accepts no liability for any
damage caused by any virus transmitted by this email. Furthermore, the
company does not warrant a proper and complete transmission of this
information, nor does it accept liability for any delays. If you have
received this message in error, please contact the sender and delete the
message. Thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060720/e95048a7/attachment.htm 

From emilia12 at mail.bg  Thu Jul 20 10:19:46 2006
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Thu, 20 Jul 2006 11:19:46 +0300
Subject: [Tutor] [tutor] how to get the fileextention?
Message-ID: <1153383586.2f10b2371e8d7@mail.bg>

Hi,

is this the right (shortest) way to get the file extention
(under MS WIN)?


def getext(fname):
    ext = fname.split('.').pop()
    return ext

Regards,
Emily

-----------------------------

B2B ?????? ?? ?????????? ?? HP
????, ????????????, on-line ???????, ????????.
????????????? ?? ?? http://hp.most.bg


From klappnase at freenet.de  Thu Jul 20 11:11:53 2006
From: klappnase at freenet.de (Michael Lange)
Date: Thu, 20 Jul 2006 11:11:53 +0200
Subject: [Tutor] [tutor] how to get the fileextention?
In-Reply-To: <1153383586.2f10b2371e8d7@mail.bg>
References: <1153383586.2f10b2371e8d7@mail.bg>
Message-ID: <20060720111153.0d331ece.klappnase@freenet.de>

On Thu, 20 Jul 2006 11:19:46 +0300
emilia12 at mail.bg wrote:

> Hi,
> 
> is this the right (shortest) way to get the file extention
> (under MS WIN)?
> 
> 
> def getext(fname):
>     ext = fname.split('.').pop()
>     return ext
> 

Hi Emily,

for filename operations, you should have a look at the os.path module.
In your case

    os.path.splitext(fname)[1]

should do the trick, or if you need to remove the leading period from the extension
(as in your example)

    os.path.splitext(fname)[1][1:]
.

I hope this helps

Michael

From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=  Thu Jul 20 11:17:32 2006
From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=)
Date: Thu, 20 Jul 2006 12:17:32 +0300
Subject: [Tutor] [tutor] how to get the fileextention?
In-Reply-To: <1153383586.2f10b2371e8d7@mail.bg>
References: <1153383586.2f10b2371e8d7@mail.bg>
Message-ID: <1153387052.28350.10.camel@localhost.localdomain>

On Thu, 2006-07-20 at 11:19 +0300, emilia12 at mail.bg wrote:
> Hi,
> 
> is this the right (shortest) way to get the file extention
> (under MS WIN)?
> 
> 
> def getext(fname):
>     ext = fname.split('.').pop()
>     return ext
> 
> Regards,
> Emily
> 
The following maybe a little better:
        def getExt(fname):
        	return fname.rsplit('.', 1)[1]
                
It uses one method instead of two compared to yours.  And in your code
there's no need for the ?ext? variable, you could use:
        def getext(fname):
        	return fname.split('.').pop()

For more information about ?str? objects type the following inside the
Python shell:
	>>> help(str)


Ziyad.


From emilia12 at mail.bg  Thu Jul 20 13:49:43 2006
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Thu, 20 Jul 2006 14:49:43 +0300
Subject: [Tutor] [tutor] how to get the fileextention?
In-Reply-To: <1153387052.28350.10.camel@localhost.localdomain>
References: <1153383586.2f10b2371e8d7@mail.bg>
	<1153387052.28350.10.camel@localhost.localdomain>
Message-ID: <1153396183.b27ca4b1f0cbe@mail.bg>

Hi Ziyad
thank you very much!

E.

????? ?? ????? ?? ???? ?? ????????? ???????
<zamb at saudi.net.sa>:

> On Thu, 2006-07-20 at 11:19 +0300, emilia12 at mail.bg
> wrote:
> > Hi,
> >
> > is this the right (shortest) way to get the file
> extention
> > (under MS WIN)?
> >
> >
> > def getext(fname):
> >     ext = fname.split('.').pop()
> >     return ext
> >
> > Regards,
> > Emily
> >
> The following maybe a little better:
>         def getExt(fname):
>         	return fname.rsplit('.', 1)[1]
>
> It uses one method instead of two compared to yours.  And
> in your code
> there's no need for the ?ext? variable, you could use:
>         def getext(fname):
>         	return fname.split('.').pop()
>
> For more information about ?str? objects type the
> following inside the
> Python shell:
> 	>>> help(str)
>
>
> Ziyad.
>
>
>




-----------------------------

??????? ?????????!
bg.sportingbet.com


From rfquerin at gmail.com  Thu Jul 20 15:10:17 2006
From: rfquerin at gmail.com (Richard Querin)
Date: Thu, 20 Jul 2006 09:10:17 -0400
Subject: [Tutor] Writing python scripts to control GIMP
Message-ID: <7d81675b0607200610s797e8676j379ecef5649c1ab6@mail.gmail.com>

Hi,

I'm interested in learning about how to write python scripts that can
control the GIMP. I've read about several scripts but I'd like to know where
to start learning about how it's done. Anybody got any good places to look
for tutorials, references etc?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060720/01f644e3/attachment.html 

From tiagosaboga at terra.com.br  Thu Jul 20 15:31:45 2006
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Thu, 20 Jul 2006 10:31:45 -0300
Subject: [Tutor] about copy.copy
In-Reply-To: <1d987df30607200051v5ffd2e47v7ad708cabdf46b23@mail.gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>
	<Pine.LNX.4.64.0607180822260.9838@hkn.eecs.berkeley.edu>
	<1d987df30607200051v5ffd2e47v7ad708cabdf46b23@mail.gmail.com>
Message-ID: <200607201031.46038.tiagosaboga@terra.com.br>

Em Quinta 20 Julho 2006 04:51, linda.s escreveu:
> But in the following example, a change in a spread to both b and c:
> >>> a=[[1,2,3], [4,5,6]]
> >>> b=a
> >>> c=copy.copy(a)
> >>> a[0][0]='a'
> >>> a
>
> [['a', 2, 3], [4, 5, 6]]
>
> >>> b
>
> [['a', 2, 3], [4, 5, 6]]
>
> >>> c
>
> [['a', 2, 3], [4, 5, 6]]

Linda,

re-read Danny's mail, it's all there! But I'll try again. Your first line,

>>> a = [ [1,2,3], [4,5,6] ]

could as well be written as:

>>> a0 = [1,2,3]
>>> a1 = [4,5,6]
>>> a = [a0, a1]

so:

>>> b=a
>>> import copy

And now what is a[0][0]? It's obviously a0[0]. And even if c is a different 
object, c[0][0] is also a0[0]. If you say now that c[0] is no more a0, but 
any other thing, a will not be changed. But if you change a0, directly or 
through the c or a lists, c *and* a first item will be changed. See it in 
action:

In [1]: a0 = [1,2,3]

In [2]: a1 = [4,5,6]

In [3]: import copy

In [4]: a = [a0,a1]

In [5]: b=a

In [6]: c = copy.copy(a)

In [7]: a0[0] = 25

In [8]: a
Out[8]: [[25, 2, 3], [4, 5, 6]]

In [9]: b
Out[9]: [[25, 2, 3], [4, 5, 6]]

In [10]: c
Out[10]: [[25, 2, 3], [4, 5, 6]]

In [11]: c[0] = [7,8,9]

In [12]: a
Out[12]: [[25, 2, 3], [4, 5, 6]]

In [13]: b
Out[13]: [[25, 2, 3], [4, 5, 6]]

In [14]: c
Out[14]: [[7, 8, 9], [4, 5, 6]]

In [15]: a[0][0] = 92

In [16]: a
Out[16]: [[92, 2, 3], [4, 5, 6]]

In [17]: b
Out[17]: [[92, 2, 3], [4, 5, 6]]

In [18]: c
Out[18]: [[7, 8, 9], [4, 5, 6]]

Tiago.

From a.m.i.x at web.de  Thu Jul 20 18:48:16 2006
From: a.m.i.x at web.de (Andreas Mixich)
Date: Thu, 20 Jul 2006 18:48:16 +0200
Subject: [Tutor] AmigaOS like ReadArgs() for Python ?
Message-ID: <44BFB3D0.6040408@web.de>

Hi,

does anyone know about a ReadArgs() implementation for Python as seen on
AmigaDOS ?

Thanks.

-- 
Andreas

From kent37 at tds.net  Thu Jul 20 19:21:19 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 20 Jul 2006 13:21:19 -0400
Subject: [Tutor] AmigaOS like ReadArgs() for Python ?
In-Reply-To: <44BFB3D0.6040408@web.de>
References: <44BFB3D0.6040408@web.de>
Message-ID: <44BFBB8F.1010705@tds.net>

Andreas Mixich wrote:
> Hi,
>
> does anyone know about a ReadArgs() implementation for Python as seen on
> AmigaDOS ?

I don't know about ReadArgs() but for parsing of command line arguments 
in Python see the optparse module or this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844
http://docs.python.org/lib/module-optparse.html

Kent


From jason.massey at gmail.com  Thu Jul 20 19:23:07 2006
From: jason.massey at gmail.com (Jason Massey)
Date: Thu, 20 Jul 2006 12:23:07 -0500
Subject: [Tutor] AmigaOS like ReadArgs() for Python ?
In-Reply-To: <44BFB3D0.6040408@web.de>
References: <44BFB3D0.6040408@web.de>
Message-ID: <7e3eab2c0607201023g4adfa54fq946d8cee12b0d4e1@mail.gmail.com>

I came across this at: http://www.monkeyhouse.eclipse.co.uk/amiga/python/

For more powerful operation under AmigaDOS, and because it is needed for the
ARexx implementation, there are two additional modules. The first is the
low-level builtin module Doslib, and the other, the Dos module, is written
on top of it (in Python). They work together much the same as the strop and
string modules do: you don't use the builtin one directy but rather the
higher-level module. So, you will only need to use the Dos module which
provides the following:

   - set of AmigaDOS specific functions, like Relabel, Examine,
   SetComment, SetFileDate, etc.
   - functions for waiting on and checking of AmigaDOS signal flags
   definition of a set of AmigaDOS flags (break signals, file protection
   bits etc.)
   - higher level wrapper and utility functions like touch, AssignAdd,
   etc.
   - ArgParser class. This is an argument string parser to parse strings
   according to a template as understood by the standard AmigaDOS ReadArgs
   function. The ARexx module uses it for parsing the ARexx command arguments.
   This is actually a very powerful class!



On 7/20/06, Andreas Mixich <a.m.i.x at web.de> wrote:
>
> Hi,
>
> does anyone know about a ReadArgs() implementation for Python as seen on
> AmigaDOS ?
>
> Thanks.
>
> --
> Andreas
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060720/ce4502d1/attachment.htm 

From andrew.arobert at gmail.com  Thu Jul 20 19:25:26 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Thu, 20 Jul 2006 13:25:26 -0400
Subject: [Tutor] Using python to create and save a Ms Word file
Message-ID: <44BFBC86.2090908@gmail.com>

-----BEGIN PGP SIGNED MESSAGE-----

Hash: SHA1



Hi Everyone,

I have a text file being broadcast on a web site and I would like to download it 
and save it as an MS Word file.

The download from web is relatively painless.

#!C:\Python24\Python
import sys
from urllib import urlopen


if  len(sys.argv) == 1 :
	print "\nUsage:   getkwik.py  {output file name} \n"
else:
   open(sys.argv[1],"wb").write( urlopen("http://mydomain/file.txt").read() )

Trying to get the file to word is a little more troubling.


I found the following code on the web that comes close to what i need.

It:

- - reads a file passed to it
- - opens word file 
- - dumps the read contents to the file
- - places a time stamp at the end signaling when the conversion occured

What is is missing is how to automate saving/closing the file when the conversion is complete.

Would someone be able to help fill in the blanks on this?




import sys
import time
import string
import win32com.client

# --------------------------------------------------------------------
class CWordAutomate:
    """Encapsulates a winword com connection"""
    def __init__( self ):
        """construct: create OLE connection to winword"""
        self.m_obWord         = win32com.client.Dispatch( "Word.Application" )
        self.m_obDoc          = self.m_obWord.Documents.Add( ) # create new doc
        self.m_obWord.Visible = 1
        self.m_Sel            = self.m_obWord.Selection # get a selection

    def WriteLine( self, sTxt, sFont, lSize, bBold=0 ):
        """Write a line to winword"""
        self.m_Sel.Font.Name = sFont
        self.m_Sel.Font.Bold = bBold
        self.m_Sel.Font.Size = lSize
        self.m_Sel.TypeText( Text=sTxt + "\n"  )

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

# - open a file
sFileName  = sys.argv[1]
obFile     = file( sFileName, 'r+' )
sContent   = obFile.read()
obFile.close()
lstContent = sContent.splitlines()

# - display contents in word
obWord = CWordAutomate()
obWord.WriteLine( "Content of the file " + sFileName, "Times New Roman", 18, 1 )
for sLine in lstContent:
    obWord.WriteLine( sLine, "Courier New", 10  )
sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )

-----BEGIN PGP SIGNATURE-----

Version: GnuPG v1.2.1 (MingW32)

Comment: GnuPT 2.7.2



iD8DBQFEv7yGDvn/4H0LjDwRAiPPAKCi4LCSuB0qobKavoKqZZ13E7grbwCgriQ8

Bz4uP7IcwipZdfSUUFDi9Hg=

=C1Gx

-----END PGP SIGNATURE-----


From dyoo at hkn.eecs.berkeley.edu  Thu Jul 20 19:33:36 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 20 Jul 2006 10:33:36 -0700 (PDT)
Subject: [Tutor] about copy.copy
In-Reply-To: <1d987df30607200051v5ffd2e47v7ad708cabdf46b23@mail.gmail.com>
References: <1d987df30607180040w211b6b3ancbeab628a99cd392@mail.gmail.com>
	<44BC922C.8090504@gmail.com>
	<1d987df30607180058m57aaf856r3c8c20bcd94e280@mail.gmail.com>
	<Pine.LNX.4.64.0607180822260.9838@hkn.eecs.berkeley.edu>
	<1d987df30607200051v5ffd2e47v7ad708cabdf46b23@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0607200853180.28547@hkn.eecs.berkeley.edu>

>> Do you have any questions so far about this?  Some kind of model like 
>> this is necessary to understand the situation you're seeing now, so 
>> please feel free to ask if any part of this is confusing.
>>
> But in the following example, a change in a spread to both b and c:
>>>> a=[[1,2,3], [4,5,6]]

Hi Linda,

Try drawing out a diagram for what things look like for:

     a = [[1, 2, 3], [4, 5, 6]]
     c = copy.copy(a)

It may help to explain the behavior that you're seeing.

Mutation is a very tricky thing!  It'll take some practice to get an 
intuition of what's happening.


(In fact, it is troublesome enough that some language communities try to 
avoid mutating things at all.  The ML and Haskell communities are examples 
of folks who try to live without mutation.  For the most part, they're 
perfectly happy without mutating their data structures.)


Best of wishes!

From mail at ozzmosis.com  Thu Jul 20 20:12:28 2006
From: mail at ozzmosis.com (andrew clarke)
Date: Fri, 21 Jul 2006 04:12:28 +1000
Subject: [Tutor] Using python to create and save a Ms Word file
In-Reply-To: <44BFBC86.2090908@gmail.com>
References: <44BFBC86.2090908@gmail.com>
Message-ID: <20060720181228.GA82454@ozzmosis.com>

On Thu, Jul 20, 2006 at 01:25:26PM -0400, Andrew Robert wrote:

> I have a text file being broadcast on a web site and I would like to download it 
> and save it as an MS Word file.

...

> I found the following code on the web that comes close to what i need.
> 
> It:
> 
> - - reads a file passed to it
> - - opens word file 
> - - dumps the read contents to the file
> - - places a time stamp at the end signaling when the conversion occured
> 
> What is is missing is how to automate saving/closing the file when the conversion is complete.
> 
> Would someone be able to help fill in the blanks on this?

I've never played with Win32 COM before, but your message inspired me to
learn.  :-)

A quick Google later, and it seems you need to add the following methods
to the CWordAutomate class:

    def Save(self, sFilename):
        self.m_obDoc.SaveAs(sFilename)

    def Quit(self):
        self.m_obWord.Quit()

Then in your code:

> sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
> obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )

Add these:

obWord.Save("blah.doc")
obWord.Quit()

On my system, "blah.doc" was saved as

C:\Documents and Settings\ozzmosis\My Documents\blah.doc

So you'll need to specify an absolute pathname if you want it to be
saved somewhere else.

I picked this up from:

http://mail.python.org/pipermail/python-win32/2002-June/000396.html

I guess we both need to subscribe to the python-win32 mailing list...  ;-)

Regards
Andrew

From john.corry at ntlworld.com  Thu Jul 20 21:16:58 2006
From: john.corry at ntlworld.com (John CORRY)
Date: Thu, 20 Jul 2006 20:16:58 +0100
Subject: [Tutor] Help me make it look pretty!
Message-ID: <000001c6ac31$16617ae0$4c3ea8c0@JOHNC>

Good evening all.
 
I am writing a program using python 2.4, glade 2 and pygtk.  It takes
input from the user using textentry boxes.  The input should be a
number.  When the user keys the data in, it automatically left
justifies.  The function below, takes the input for four boxes and right
justifies it by using an ugly, string format.  The boxes are 45
characters big, so I use the len function to fit them into the box.  The
code is below.
 
I am looking for a way to set the text entry up, so that there is a
decimal point in the box regardless of what the user does and I am also
looking for a way to keep the numbers right justified.
 
Any suggestions or comments as always are greatly appreciated.
 
Regards,
 
John.
 
 
def
callback36(self,data,text37,text38,text39,text40,text41,text42,label):
        a = text37.get_text()
        
        b = text38.get_text()
        c = text39.get_text()
        d = text40.get_text()
        a= float(a)
        b= float(b)
        c= float(c)
        d= float(d)
        
        try:
            
            e = float(a + b + c + d)
            g = e/a
            e = "%0.2f" % e
            
            g = "%0.2f" % g
            g = str(g)
            label.hide()
            e = "                                         %s" % e
            a = "                                         %s" % a
            b = "                                         %s" % b
            c = "                                         %s" % c
            d = "                                         %s" % d
            g = "%s%%" % g
            text42.set_text(str(g)) 
            if len(e)>45:
                x = len(e) - 45
                x = x + 4
                y = e[x:]
                text41.set_text(str(y))               
                return 
            else:
                text41.set_text(str(e)) 
                return
       
        except:
            label.show()
            return
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060720/0484b42d/attachment.html 

From john at fouhy.net  Thu Jul 20 22:55:01 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 21 Jul 2006 08:55:01 +1200
Subject: [Tutor] Using python to create and save a Ms Word file
In-Reply-To: <20060720181228.GA82454@ozzmosis.com>
References: <44BFBC86.2090908@gmail.com> <20060720181228.GA82454@ozzmosis.com>
Message-ID: <5e58f2e40607201355q77f66c2i266d4e4d72497e5f@mail.gmail.com>

On 21/07/06, andrew clarke <mail at ozzmosis.com> wrote:
> A quick Google later, and it seems you need to add the following methods
> to the CWordAutomate class:
>
>    def Save(self, sFilename):
>        self.m_obDoc.SaveAs(sFilename)
>
>    def Quit(self):
>        self.m_obWord.Quit()

Check out the Visual Basic documentation that comes with Word (I think
it's an optional component when you install).  That will descibe (in a
VBA context) the functions you can call after Dispatching something.

Also, pythonwin comes with a utility called makepy.py.  If you run
this, it will crank through your available COM objects and generate a
whole bunch of python code to tell python about what functions are
available.  Once you've done this, you can (I think) use help() and
dir() to find out what functions are available, and what arguments
they expect.  You can also read through the generated code itself;
it's more helpful than you might expect :-)

-- 
John.

From gvwilson at cs.utoronto.ca  Thu Jul 20 23:27:29 2006
From: gvwilson at cs.utoronto.ca (Greg Wilson)
Date: Thu, 20 Jul 2006 17:27:29 -0400 (EDT)
Subject: [Tutor] Software Carpentry 2.0 released
Message-ID: <Pine.GSO.4.58.0607201725530.14577@dvp.cs>

We're pleased to announce the release of Version 2.0 of Software
Carpentry, an open source, Python-based course on basic software
development skills.  The course materials are available at:

    http://www.swc.scipy.org

Feedback and contributions are very welcome.

Thanks,
Greg Wilson

From f.w.kooistra at ocelot.nl  Fri Jul 21 02:37:47 2006
From: f.w.kooistra at ocelot.nl (Frank W. Kooistra)
Date: Fri, 21 Jul 2006 02:37:47 +0200
Subject: [Tutor] Comparing times
In-Reply-To: <b6131fdc0607192343t22cdb177h1ddad9196cffa185@mail.gmail.com>
References: <b6131fdc0607180308n1f3f3d0cw2040feb5687e2616@mail.gmail.com>
	<5e58f2e40607181359p583a38c4j2987f1e8d2016f0f@mail.gmail.com>
	<b6131fdc0607192343t22cdb177h1ddad9196cffa185@mail.gmail.com>
Message-ID: <200607210237.49537.f.w.kooistra@ocelot.nl>

On Thursday 20 July 2006 08:43, Steve Nelson wrote:
> On 7/18/06, John Fouhy <john at fouhy.net> wrote:
> > On 18/07/06, Steve Nelson <sanelson at gmail.com> wrote:
> > > What I want to do is establish if the time of the process is *later*
> > > than the system date.  For example, we might have a process with a
> > > time of 11:15:00, when the system time is 10:00:00.  In practice this
> > > means that the process is from 11am yesterday.
> > >
> > > Other than splitting the string up more and saying is 11 bigger than
> > > 10, how can I go about this?
> >
> > Have a look at time.strptime.
>
> Yes - I've worked out how to do this with a combination of
> time.strptime() and time.mktime(), although the problem I face now is
> that datetime objects need a date, and my way of getting the time
> doesn't include a way of specifying the date.  Perhaps I should be
> clearer:
>
I am really new to Python ..
except for hello never even written a program yet 

But i know unix has a counter which starts after a given moment. 
That is just a number  

I found that the library function time.time()  gets that number 

I found this example ;


import time

now = time.time()

print now, "seconds since", time.gmtime(0)[:6]

937758359.77 seconds since (1970, 1, 1, 0, 0, 0)

the difference between two moments in tim.time() 
can be calculated simple 

am i right ? 

I got the sample from : http://effbot.org/librarybook/time.htm 




> I have an application which connects using telnet to a server to
> communicate.  The application is largely user-driven - ie such a
> connection represents a real user in real time.  If they don't log out
> of the system, the pty that is associated with the process will remain
> used.  There are only 256 available at present, and it only takes a
> few dozen lazy users, and we run out of ptys.  Until we increase the
> number of ptys, and for housekeeping, even after, we have a method of
> checking the STIME property in ps to see if the format has changed
> from eg from 12:44:23 to Jan 7.  If it has changed we kill that
> process.  I've been asked to rewrite this script into something more
> capabale, because we're still seeing sessions connected from the
> previous day that could reasonably be killed off.  Eg at 0900 today if
> I see a telnetd process with an STIME of 1000 I know it is 23 hours
> old, and has been left connected all night, and I can kill it.  My
> task therefore is to find the STIME from ps, and somehow assign a date
> to it... perhaps I just assign it a date of today, and if the STIME is
> *later* that the system time, I know it is actuallly yesterday's?
>
> Just thinking aloud here... but thoughts / advice most welcome.
> Incidentally when I get to killing the process, any recommended ways?

check the OS module 
with that you can send a command. to a process 

under unix we send a signal 
number nine is kill  

i did did not see if the signal module can send a signal to a process or it 
just handles the signals received 


-- 
Kind Regards,  

Frank

_________________
Frank W. Kooistra
Spoorsingel 89 
2613 BB Delft 
t:06 45 77 00 17 

From singingxduck at gmail.com  Fri Jul 21 09:02:30 2006
From: singingxduck at gmail.com (Orri Ganel)
Date: Fri, 21 Jul 2006 03:02:30 -0400
Subject: [Tutor] : finding out if the horizontal scrollbar on a
 Tix.CheckList is being used or not
Message-ID: <44C07C06.9030904@gmail.com>

Hello all,

I'm working on the GUI for my extended iTunes search, which allows 
searches far beyond the native iTunes capability.  Once the search has 
been completed, a window contining a Tix.CheckList with the resulting 
tracks is displayed.  If anyone has any idea how to figure out whether 
or not the horizontal scrollbar is visible (ie if the length of the 
track name extends beyond the width of the CheckList) programmatically, 
I'd be extremely grateful :-).

Thanks in advance,
Orri

P.S. - If you want more information regarding my program, feel free to 
ask away.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: ganel.o.vcf
Type: text/x-vcard
Size: 144 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060721/ff472ca2/attachment.vcf 

From singingxduck at gmail.com  Fri Jul 21 09:03:50 2006
From: singingxduck at gmail.com (Orri Ganel)
Date: Fri, 21 Jul 2006 03:03:50 -0400
Subject: [Tutor] : finding out if the horizontal scrollbar on a
 Tix.CheckList is being used or not
In-Reply-To: <44C07C06.9030904@gmail.com>
References: <44C07C06.9030904@gmail.com>
Message-ID: <44C07C56.7050904@gmail.com>

Oops, please send any questions to this email, not the one I sent the 
last message with.

Thanks,
Orri

From john at fouhy.net  Fri Jul 21 11:09:33 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 21 Jul 2006 21:09:33 +1200
Subject: [Tutor] : finding out if the horizontal scrollbar on a
	Tix.CheckList is being used or not
In-Reply-To: <44C07C06.9030904@gmail.com>
References: <44C07C06.9030904@gmail.com>
Message-ID: <5e58f2e40607210209o20e26f02o6e12f440b49a7ac0@mail.gmail.com>

On 21/07/06, Orri Ganel <singingxduck at gmail.com> wrote:
> I'm working on the GUI for my extended iTunes search, which allows
> searches far beyond the native iTunes capability.  Once the search has
> been completed, a window contining a Tix.CheckList with the resulting
> tracks is displayed.  If anyone has any idea how to figure out whether
> or not the horizontal scrollbar is visible (ie if the length of the
> track name extends beyond the width of the CheckList) programmatically,
> I'd be extremely grateful :-).

I don't know how to check the scrollbar, but one thing you could try
playing with: tkFont.Font instances support a .measure method.  So, if
f is a tkFont.Font, then f.measure('hello world!') will return how
many pixels wide that string would be on the screen.  You could maybe
compare this with the width of the widget itself?

-- 
John.

From klappnase at freenet.de  Fri Jul 21 11:35:32 2006
From: klappnase at freenet.de (Michael Lange)
Date: Fri, 21 Jul 2006 11:35:32 +0200
Subject: [Tutor] Help me make it look pretty!
In-Reply-To: <000001c6ac31$16617ae0$4c3ea8c0@JOHNC>
References: <000001c6ac31$16617ae0$4c3ea8c0@JOHNC>
Message-ID: <20060721113532.33ff256f.klappnase@freenet.de>

On Thu, 20 Jul 2006 20:16:58 +0100
"John CORRY" <john.corry at ntlworld.com> wrote:

> Good evening all.
>  
> I am writing a program using python 2.4, glade 2 and pygtk.  It takes
> input from the user using textentry boxes.  The input should be a
> number.  When the user keys the data in, it automatically left
> justifies.  The function below, takes the input for four boxes and right
> justifies it by using an ugly, string format.  The boxes are 45
> characters big, so I use the len function to fit them into the box.  The
> code is below.
>  
> I am looking for a way to set the text entry up, so that there is a
> decimal point in the box regardless of what the user does and I am also
> looking for a way to keep the numbers right justified.
>  
> Any suggestions or comments as always are greatly appreciated.
>  

Hi John,

I don't know about gtk, but have made some experience validating the user input
in Tkinter Entries, so I can only try to give you some general advice.
First, the Tkinter.Entry has a configuration option "justify", so
entry.config(justify=RIGHT) would very simply solve the first problem; are
you sure the gtk entry box does not have something similar?
Second, I found validating (and especially "on-the-fly"-converting) user input
is always a very tricky thing. Usually when testing some "solution" that seemed
to work, I found that in some special cases the widget showed an completely unexpected
behavior. Generally it is safer not to restrict user input too much and do the validation
when the entry boxes' contents are actually needed; if it is not valid you can pop up
a message box that tells the user what to do. If you really need to perform "real time" validation,
make sure to test your widgets very carefully.
Again, I don't know about gtk, in Tkinter you can pass a "validatecommand" to the entry widget to which
you can pass the old and the new entry's contents,
that is called each time the user types something into the entry box. If gtk offers something similar,
you could start with something like:

# pseudo code
def validate(old, new):
    x = text38.get_text()
    if x in ('', '.'):
        ok = 1
    elif '.' in x:
        try:
            float(x)
            ok = 1
        except ValueError:
            print '\a'#acoustic feedback, in Tkinter I would use bell() of course
            ok = 0
    else:
        try:
            int(x)
            text38.set_text('.'+x)#don't know how this would actually look in gtk, I hope you know what I mean
            ok = 1
        except ValueError:
            print '\a'
            ok = 0
    if not ok:
        # the new text is not allowed, restore the old
        text38.set_text(old)

I bet this kind of solution has its traps, too.
Maybe the best solution is a web search if someone else has already written such a widget.
A quick google search for "pygtk entry validation" for example lead me here:

http://www.astro.umass.edu/~dpopowich/python/ :

ValidatedEntry, a pygtk extension providing a validated Entry widget

ValidatedEntry is a subclass of gtk.Entry, providing validation of input based on programmable functions. Sample functions included in the package provide validation for integers, floats, non-empty strings, ISBN numbers, phone numbers, money and bounded values (e.g., integers in a range). A demo app is included in the package. The latest version, 1.0.4, can be downloaded here.

Good luck!

Michael

From klappnase at freenet.de  Fri Jul 21 11:40:38 2006
From: klappnase at freenet.de (Michael Lange)
Date: Fri, 21 Jul 2006 11:40:38 +0200
Subject: [Tutor] : finding out if the horizontal scrollbar on a
 Tix.CheckList is being used or not
In-Reply-To: <44C07C06.9030904@gmail.com>
References: <44C07C06.9030904@gmail.com>
Message-ID: <20060721114038.4a4f9047.klappnase@freenet.de>

On Fri, 21 Jul 2006 03:02:30 -0400
Orri Ganel <singingxduck at gmail.com> wrote:

> Hello all,
> 
> I'm working on the GUI for my extended iTunes search, which allows 
> searches far beyond the native iTunes capability.  Once the search has 
> been completed, a window contining a Tix.CheckList with the resulting 
> tracks is displayed.  If anyone has any idea how to figure out whether 
> or not the horizontal scrollbar is visible (ie if the length of the 
> track name extends beyond the width of the CheckList) programmatically, 
> I'd be extremely grateful :-).
> 

Hi Orri,

how about check_list.hsb.get() ?
I think in case it is != (0.0, 1.0) the scrollbar should be visible.

I hope this helps

Michael

From kent37 at tds.net  Fri Jul 21 12:35:14 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 21 Jul 2006 06:35:14 -0400
Subject: [Tutor] Help me make it look pretty!
In-Reply-To: <000001c6ac31$16617ae0$4c3ea8c0@JOHNC>
References: <000001c6ac31$16617ae0$4c3ea8c0@JOHNC>
Message-ID: <44C0ADE2.7060304@tds.net>

John CORRY wrote:
>
> Good evening all.
>
>  
>
> I am writing a program using python 2.4, glade 2 and pygtk.  It takes 
> input from the user using textentry boxes.  The input should be a 
> number.  When the user keys the data in, it automatically left 
> justifies.  The function below, takes the input for four boxes and 
> right justifies it by using an ugly, string format.  The boxes are 45 
> characters big, so I use the len function to fit them into the box.  
> The code is below.
>
I'm not familiar with GTK but I would look for a way to set the 
alignment of the text field so it always right aligns. 
gtk-entry-set-alignment() looks promising:
http://www.gtk.org/api/2.6/gtk/GtkEntry.html#gtk-entry-set-alignment

More notes below
>
>  
>
> I am looking for a way to set the text entry up, so that there is a 
> decimal point in the box regardless of what the user does and I am 
> also looking for a way to keep the numbers right justified.
>
>  
>
> Any suggestions or comments as always are greatly appreciated.
>
>  
>
> Regards,
>
>  
>
> John.
>
>  
>
>  
>
> def callback36(self,data,text37,text38,text39,text40,text41,text42,label):
>
>         a = text37.get_text()
>
>        
>
>         b = text38.get_text()
>
>         c = text39.get_text()
>
>         d = text40.get_text()
>
>         a= float(a)
>
>         b= float(b)
>
>         c= float(c)
>
>         d= float(d)
>
>        
>
>         try:
>
>            
>
>             e = float(a + b + c + d)
>
>             g = e/a
>
>             e = "%0.2f" % e
>
>            
>
>             g = "%0.2f" % g
>
>             g = str(g)
>
>             label.hide()
>
>             e = "                                         %s" % e
>
>             a = "                                         %s" % a
>
>             b = "                                         %s" % b
>
>             c = "                                         %s" % c
>
>             d = "                                         %s" % d
>
>             g = "%s%%" % g
>
String formatting can create the strings you want directly. str.rjust() 
is also useful here. For example
In [1]: e=1./3

In [3]: '% 20.2f' % e
Out[3]: '                0.33'

In [4]: '0.33'.rjust(20)
Out[4]: '                0.33'

>             text42.set_text(str(g))
>
>             if len(e)>45:
>
>                 x = len(e) - 45
>
>                 x = x + 4
>
>                 y = e[x:]
>
>                 text41.set_text(str(y))              
>
>                 return
>
I think this is taking the last 41 chars of e if len(e) > 45. You can 
get the last 41 chars of e directly with
e[-41:]

Kent
>
>             else:
>
>                 text41.set_text(str(e))
>
>                 return
>
>       
>
>         except:
>
>             label.show()
>
>             return
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From kent37 at tds.net  Fri Jul 21 12:46:02 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 21 Jul 2006 06:46:02 -0400
Subject: [Tutor] [OT] Python proficiency test
Message-ID: <44C0B06A.8070100@tds.net>

I recently helped create an on-line Python proficiency test. The 
publishers of the test are looking for beta testers to try the test and 
give feedback. If you are interested, here is an announcement from the 
publisher:
> Brainbench is currently beta testing a new series of test questions for
> our Python 2.4 test.
>
> We are looking for knowledgeable Python 2.4 users. 
>
> To take the test, simply go to
> http://www.brainbench.com/xml/bb/common/testcenter/betatests.xml
> and the rest should be self-explanatory.
>
> Any feedback you can provide us on the quality of the questions and the
> test itself would be greatly appreciated.
> You will be given the opportunity to provide anonymous feedback on each
> question as it is administered as well as at the end of the test.
>
> We hope that you enjoy the test and look forward to your feedback!
>
> Feel free to pass this along to your friends.
>
> Thanks in advance for your help and good luck!
>   
Kent


From jgcox39 at highstream.net  Fri Jul 21 13:20:34 2006
From: jgcox39 at highstream.net (Joe Cox)
Date: Fri, 21 Jul 2006 07:20:34 -0400
Subject: [Tutor] Binding ListBox
Message-ID: <AIECKKGNOCPIFINDPNAKMECCCDAA.jgcox39@highstream.net>

  I am learning Python 2.4 with Tkinter. I have a series of radio buttons
that I want to bind to their own individual
listbox in order to narrow down a selection process. I just don't seem to
grasp how to call up the approiate
box to it's proper radiobutton. Please help.


Joe Cox
513-293-4830 mobile
jgcox39 at highstream.net



From andrew.arobert at gmail.com  Fri Jul 21 14:55:48 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Fri, 21 Jul 2006 08:55:48 -0400
Subject: [Tutor] Using python to create and save a Ms Word file
In-Reply-To: <20060720181228.GA82454@ozzmosis.com>
References: <44BFBC86.2090908@gmail.com> <20060720181228.GA82454@ozzmosis.com>
Message-ID: <44C0CED4.1000206@gmail.com>

-----BEGIN PGP SIGNED MESSAGE-----

Hash: SHA1



Thanks for your help on this.

Here is the completed code in case anyone is interested.

#! C:\Python24\python 
#
# program: mswword.py
# Author:  Andrew Robert
# 
# Ver       Date       Programmer    Modification
# 1.0       07/20/06   AAR           Initial Creation
# 1.1       07/21/06   AAR           added doc save/quit items to class
# 1.2                                added argument and source/target file testing 

import sys, time, string, win32com.client, stat, os

class CWordAutomate:
    """Encapsulates a winword com connection"""
    def __init__( self ):
        """construct: create OLE connection to winword"""
        self.m_obWord         = win32com.client.Dispatch( "Word.Application" )
        self.m_obDoc          = self.m_obWord.Documents.Add( ) # create new doc
        self.m_obWord.Visible = 1
        self.m_Sel            = self.m_obWord.Selection # get a selection

    def WriteLine( self, sTxt, sFont, lSize, bBold=0 ):
        """Write a line to winword"""
        self.m_Sel.Font.Name = sFont
        self.m_Sel.Font.Bold = bBold
        self.m_Sel.Font.Size = lSize
        self.m_Sel.TypeText( Text=sTxt + "\n"  )

    def Save(self, sFilename):
        self.m_obDoc.SaveAs(sFilename)

    def Quit(self):
        self.m_obWord.Quit()


def file_test(file):
    """
    Tests user supplied file to see if it exists and contains data.
    If the input file does not exist or is empty, return a warning code
    """

    if (0 == os.path.isfile(file) or (0 == os.stat(file)[stat.ST_SIZE])):
        return 1
    else:
        return 0


if __name__ == "__main__":

	usage = "\n\n\tUsage:  msword.py  {inputfile}  {outputfile}\n"

	#
	# Test number of arguments passed.
	#
	if len(sys.argv) != 3:
		print "\n\n\tmsword.py error: \n\n\tInsufficient arguments passed."
		print usage
		sys.exit(1)

	
	# Test source file to ensure it exists and contains data
	if file_test(sys.argv[1]) == 1 : 
		print "\n\n\tmsword.py error: \n\n\tSource file not found or is empty."
		print usage
		sys.exit(1)

	# Test target file to prevent accidental clobbering
	if file_test(sys.argv[2]) == 0 :
		print "\n\n\tmsword.py error: \n\n\tTarget file already exists."
		print usage
		sys.exit(1)


	sFileName  = sys.argv[1]
	obFile     = file( sFileName, 'r+' )
	sContent   = obFile.read()
	obFile.close()
	lstContent = sContent.splitlines()
	
	# 
	# Write contents of source file to user supplied file name
	#
	obWord = CWordAutomate()
	
	for sLine in lstContent:
		obWord.WriteLine( sLine, "Courier New", 10  )
	
	sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
	obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )
	
	obWord.Save(sys.argv[2])
	obWord.Quit()



andrew clarke wrote:
> On Thu, Jul 20, 2006 at 01:25:26PM -0400, Andrew Robert wrote:
> 
>> I have a text file being broadcast on a web site and I would like to download it 
>> and save it as an MS Word file.
> 
> ...
> 
>> I found the following code on the web that comes close to what i need.
>>
>> It:
>>
>> - - reads a file passed to it
>> - - opens word file 
>> - - dumps the read contents to the file
>> - - places a time stamp at the end signaling when the conversion occured
>>
>> What is is missing is how to automate saving/closing the file when the conversion is complete.
>>
>> Would someone be able to help fill in the blanks on this?
> 
> I've never played with Win32 COM before, but your message inspired me to
> learn.  :-)
> 
> A quick Google later, and it seems you need to add the following methods
> to the CWordAutomate class:
> 
>     def Save(self, sFilename):
>         self.m_obDoc.SaveAs(sFilename)
> 
>     def Quit(self):
>         self.m_obWord.Quit()
> 
> Then in your code:
> 
>> sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
>> obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )
> 
> Add these:
> 
> obWord.Save("blah.doc")
> obWord.Quit()
> 
> On my system, "blah.doc" was saved as
> 
> C:\Documents and Settings\ozzmosis\My Documents\blah.doc
> 
> So you'll need to specify an absolute pathname if you want it to be
> saved somewhere else.
> 
> I picked this up from:
> 
> http://mail.python.org/pipermail/python-win32/2002-June/000396.html
> 
> I guess we both need to subscribe to the python-win32 mailing list...  ;-)
> 
> Regards
> Andrew
> 
-----BEGIN PGP SIGNATURE-----

Version: GnuPG v1.2.1 (MingW32)

Comment: GnuPT 2.7.2



iD8DBQFEwM7UDvn/4H0LjDwRAteBAKCQuk2mwsroT9Nw49j6iqS0a2b13ACfdQNP

L6GWNQORnZjWOvMBrjhHpr8=

=fS7m

-----END PGP SIGNATURE-----


From dyoo at hkn.eecs.berkeley.edu  Fri Jul 21 17:13:41 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Jul 2006 08:13:41 -0700 (PDT)
Subject: [Tutor] Binding ListBox
In-Reply-To: <AIECKKGNOCPIFINDPNAKMECCCDAA.jgcox39@highstream.net>
References: <AIECKKGNOCPIFINDPNAKMECCCDAA.jgcox39@highstream.net>
Message-ID: <Pine.LNX.4.64.0607210757080.14198@hkn.eecs.berkeley.edu>



> I am learning Python 2.4 with Tkinter. I have a series of radio buttons 
> that I want to bind to their own individual listbox in order to narrow 
> down a selection process.

Hi Joe,

Ok, are you familiar with callbacks?  According to:

http://www.pythonware.com/library/tkinter/introduction/x6969-patterns.htm

you can introduce a callback that will fire off when the user does a 
Radiobutton selection.  Do you have much experience using functions as 
values?



> I just don't seem to grasp how to call up the approiate box to it's 
> proper radiobutton.

If the "callback" we bind to to the radio button could only remember the 
listbox, we'd be in business.  It turns out that this is possible if we 
build a function within a function:

####################
def make_adder(n):
     def f(x):
         return x + n
     return f
####################


For example:

#########################
>>> add1 = make_adder(1)
>>> sub1 = make_adder(-1)
>>> add1(3)
4
>>> sub1(3)
2
#########################


This mechanism (lexical scope) is very useful, especially in GUI 
programming.  In your problem, one could imagine making a a function that 
takes in a listbox and returns a new Radiobutton that "remembers" its 
listbox.

########################################################
def makeRadioButtonWithListbox(root, listbox):
     def callback():
         # ... This callback has access to the listbox
     b = Radiobutton(root, text="text", command=callback)
     return b
########################################################

It's the same technique.  In this way, we can create radio buttons that 
have a way of getting at the listbox.

From andrew.arobert at gmail.com  Fri Jul 21 17:14:55 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Fri, 21 Jul 2006 11:14:55 -0400
Subject: [Tutor] Using python to create and save a Ms Word file
Message-ID: <44C0EF6F.7070907@gmail.com>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi Everyone,


I wasn't entirely satisfied with the Ms Word solution because it
requires the program run on Windows and have Office installed.

As an alternate solution, I created the program listed below to read a
file and create a RTF file format document from it.

The program is not platform dependent but it does require installation
of the PyRTF module.

I hope someone finds this useful/interesting.


#!C:\Python24\python
#
# program: rtfmaker.py
# Author:  Andrew Robert
#
# Function: Take a supplied file and dump its contents to an RTF file
#           This code is platform independant.
#
# Ver       Date       Programmer    Modification
# 1.0       07/21/06   AAR           Initial Creation
# 1.1                                added argument and source/target
file testing

import sys, time, string, stat, os
from PyRTF import *
from optparse import OptionParser

def MakeFile(lines):
	"""
	Create the RTF file
	"""

	doc     = Document()
	ss      = doc.StyleSheet
	section = Section()
	doc.Sections.append( section )

        # Append lines from source file
	for line in lines:
		section.append( line )

        return doc

def OpenFile( name ):
	return file( '%s' % name, 'w' )

def file_test(file):
        """
	Tests user supplied file to see if it exists and contains data.
	If the input file does not exist or is empty, return a warning code
	"""
	if (0 == os.path.isfile(file) or (0 == os.stat(file)[stat.ST_SIZE])):
		return 1
	else:
		return 0

def run_tests(input, output):
        """
	Test source file to ensure it exists and contains data
	"""
	if file_test(input) == 1 :
		print "\nError: Source file not found or is empty."
		parser.print_help()
		sys.exit(1)

	# Test target file to prevent accidental clobbering
	if file_test(output) == 0 :
		print "\nError: Target file already exists."
		parser.print_help()
		sys.exit(1)



def test_options(infile, outfile):
	"""
	Verify that required values are specified on commmand line
        and that specified port is within range
	"""

        if not infile :
		print "\nError: No input file specified"
		parser.print_help()
		sys.exit(1)
	
	if not outfile :
		print "\nError: No input file specified"
		parser.print_help()
		sys.exit(1)


if __name__ == '__main__' :

	parser=OptionParser()
	parser.add_option("-i", "--input" , dest="infile",
                  help="Input FILE" , metavar="FILE")
	parser.add_option("-o", "--output", dest="outfile",
                  help="Output file", metavar="FILE")
	
	(options, args) = parser.parse_args()

	test_options( options.infile , options.outfile )
	run_tests(options.infile , options.outfile)

	DR = Renderer()
	lines = open(options.infile,"r").readlines()
	rtffile = MakeFile(lines)

	# Write the new RTF file to disk
	DR.Write( rtffile, OpenFile( options.outfile ) )
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEwO9uDvn/4H0LjDwRAlHSAJ9KIzPYT2YHdK8MptBS8JSIdt8dZACgsfKi
nZQ3Bs71jsbFplmwbnVEIgI=
=ZPSo
-----END PGP SIGNATURE-----

From jsmith at medplus.com  Fri Jul 21 18:52:16 2006
From: jsmith at medplus.com (Smith, Jeff)
Date: Fri, 21 Jul 2006 12:52:16 -0400
Subject: [Tutor] Calling a function by string name
Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A028E07@EXCHMAIL01.corp.medplus.com>

I have an object and I want to call a method that I have constructed the
name for in a string.
 
For example:
str_method = 'myfun'
obj.str_method
 
Of course, this fails.  I know I could probably do this with exec but is
there a better way?
 
For context, the specific application is a wrapper to calling p4python.
Note that the second return (under the else under the try) is where I
want to call 'method' which is the string name of a method valid for
self._client.
 
    def _p4runner(self, method, *args):
        'runs a Perforce command'
        try:
            if callable(method):
                return method(*args)
            else:
                return self._client.method(*args)
        except p4.P4Client.error:
            raise
        except:
            if self._client.errors:
                raise p4.P4Client.error('\n'.join(self._client.errors))
            else:
                raise

 
Clear as mud?
Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060721/7181bc38/attachment-0001.html 

From kent37 at tds.net  Fri Jul 21 19:27:12 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 21 Jul 2006 13:27:12 -0400
Subject: [Tutor] Calling a function by string name
In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A028E07@EXCHMAIL01.corp.medplus.com>
References: <288A3B43F7B2224D9C8441C9FC5D6A028E07@EXCHMAIL01.corp.medplus.com>
Message-ID: <44C10E70.8020709@tds.net>

Smith, Jeff wrote:
> I have an object and I want to call a method that I have constructed 
> the name for in a string.
>  
> For example:
> str_method = 'myfun'
> obj.str_method
>  
> Of course, this fails.  I know I could probably do this with exec but 
> is there a better way?
Use getattr():

getattr(obj, 'myfun')()

Kent


From arcege at gmail.com  Fri Jul 21 19:36:01 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Fri, 21 Jul 2006 13:36:01 -0400
Subject: [Tutor] Calling a function by string name
In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A028E07@EXCHMAIL01.corp.medplus.com>
References: <288A3B43F7B2224D9C8441C9FC5D6A028E07@EXCHMAIL01.corp.medplus.com>
Message-ID: <7e5ba9220607211036i3bd83512x71c08de02ba2391e@mail.gmail.com>

On 7/21/06, Smith, Jeff <jsmith at medplus.com> wrote:
>
>  I have an object and I want to call a method that I have constructed the
> name for in a string.
>
> For example:
> str_method = 'myfun'
> obj.str_method
>
> Of course, this fails.  I know I could probably do this with exec but is
> there a better way?
>
> For context, the specific application is a wrapper to calling p4python.
> Note that the second return (under the else under the try) is where I want
> to call 'method' which is the string name of a method valid for
> self._client.
>
>     def _p4runner(self, method, *args):
>         'runs a Perforce command'
>         try:
>             if callable(method):
>                 return method(*args)
>

elif hasattr(self._client, method) and callable(getattr(self._client,
method)):
    return getattr(self._client, method)(*args)
elif hasattr(self._client, method):
    raise TypeError(method) # not callable
else:
    raise AttributeError(method) # no method/member with that name

            else:
>                 return self._client.method(*args)
>         except p4.P4Client.error:
>             raise
>         except:
>             if self._client.errors:
>                 raise p4.P4Client.error('\n'.join(self._client.errors))
>             else:
>                 raise
>
> Clear as mud?
>

Crystally murky.

  -Arcege
-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060721/419ebee5/attachment.htm 

From singingxduck at gmail.com  Fri Jul 21 21:01:30 2006
From: singingxduck at gmail.com (Orri Ganel)
Date: Fri, 21 Jul 2006 15:01:30 -0400
Subject: [Tutor] : finding out if the horizontal scrollbar on a
 Tix.CheckList is being used or not
In-Reply-To: <44C07C06.9030904@gmail.com>
References: <44C07C06.9030904@gmail.com>
Message-ID: <44C1248A.60507@gmail.com>

As a follow up to my last email, I think the issue is more that the 
display doesn't update before the command associated with the "search" 
button has finished processing, so any attempts to get data about the 
display from within the method are fruitless since the display hasn't 
changed yet.  I am well and truly stumped.  I have no idea how to get 
around this.  The only way I can think of to do this without using the 
display is figuring out the longest track name length and setting the 
CheckList width to the pixel version of that.  Unfortunately, I don't 
know the conversion for character units to pixels, either, so I'm still 
stuck.

Any help is hugely appreciated,
Orri

From jsmith at medplus.com  Fri Jul 21 21:32:08 2006
From: jsmith at medplus.com (Smith, Jeff)
Date: Fri, 21 Jul 2006 15:32:08 -0400
Subject: [Tutor] Calling a function by string name
Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A028E0E@EXCHMAIL01.corp.medplus.com>

Fantastic...that really did the trick!  I actually made one modification
since p4python allows you to run Perforce commands by calling them with
obj.run_COMMAND(args) so the final solution was:
 
    def _p4run(self, method, *args):
        'runs a Perforce command'
        try:
            if callable(method):
                return method(*args)
            elif hasattr(self._client, method) and
callable(getattr(self._client, method)):
                return getattr(self._client, method)(*args)
            elif hasattr(self._client, 'run_'+method) and
callable(getattr(self._client, 'run_'+method)):
                return getattr(self._client, 'run_'+method)(*args)
            elif hasattr(self._client, method): 
                raise TypeError(method) # not callable
            else:
                raise AttributeError(method) # no method/member with
that name
        except p4.P4Client.error:
            raise
        except:
            if self._client.errors:
                raise p4.P4Client.error('\n'.join(self._client.errors))
            else:
                raise

Thanks,
Jeff

-----Original Message-----
From: Michael P. Reilly [mailto:arcege at gmail.com] 
Sent: Friday, July 21, 2006 1:36 PM
To: Smith, Jeff
Cc: tutor at python.org
Subject: Re: [Tutor] Calling a function by string name


On 7/21/06, Smith, Jeff <jsmith at medplus.com> wrote: 


I have an object and I want to call a method that I have constructed the
name for in a string.
 
For example:
str_method = 'myfun'
obj.str_method
 
Of course, this fails.  I know I could probably do this with exec but is
there a better way?
 
For context, the specific application is a wrapper to calling p4python.
Note that the second return (under the else under the try) is where I
want to call 'method' which is the string name of a method valid for
self._client.
 
    def _p4runner(self, method, *args):
        'runs a Perforce command'
        try:
            if callable(method):
                return method(*args)


elif hasattr(self._client, method) and callable(getattr(self._client,
method)):
    return getattr(self._client, method)(*args)
elif hasattr(self._client, method): 
    raise TypeError(method) # not callable
else:
    raise AttributeError(method) # no method/member with that name



            else:
                return self._client.method(*args)
        except p4.P4Client.error:
            raise
        except:
            if self._client.errors:
                raise p4.P4Client.error('\n'.join(self._client.errors))
            else:
                raise

 
Clear as mud?


Crystally murky. 


  -Arcege

-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones. 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060721/87f367b9/attachment.html 

From john.corry at ntlworld.com  Fri Jul 21 22:53:44 2006
From: john.corry at ntlworld.com (John CORRY)
Date: Fri, 21 Jul 2006 21:53:44 +0100
Subject: [Tutor] Good teamwork!
Message-ID: <000001c6ad07$c6072090$4c3ea8c0@JOHNC>

George/Kent,
 
Thanks guys for the pointers.
 
Kent - The gtk-entry-set-alignment() works a treat.
 
George - I like the look of the sample code you posted.  At the moment
it doesn't give me exactly what I need but I am still playing with it.
There may be another question on this later!
 
I have downloaded the ValidatedEntry extension and had a quick look at
it. It looks like it will sort out my validation problems.
 
A good team effort!
 
Thanks,
 
John. 
 
   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060721/f261b166/attachment.html 

From cspears2002 at yahoo.com  Sat Jul 22 05:36:18 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Fri, 21 Jul 2006 20:36:18 -0700 (PDT)
Subject: [Tutor] lists and recursion
Message-ID: <20060722033618.22577.qmail@web51604.mail.yahoo.com>

I am working out of How To Think Like A Computer
Scientist.  Here is the code for a module called
node.py:

def printList(node):
		nodeList = []
		while node:
			nodeList.append(node.cargo)
			node = node.next
		print nodeList
		
def printBackward(node):
	if node == None: return
	head = node
	tail = node.next
	printBackward(tail)
	print head,
		
class Node:
	def __init__(self, cargo=None, next=None):
		self.cargo = cargo
		self.next = next
		
	def __str__(self):
		return str(self.cargo)
		

I'm trying to figure out how the printBackward
function works.  I understand it moves up a linked
list until it reaches the end of the list.  Why does
it print every node?  Shouldn't it just print the last
one?



From kent37 at tds.net  Sat Jul 22 12:20:12 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 22 Jul 2006 06:20:12 -0400
Subject: [Tutor] lists and recursion
In-Reply-To: <20060722033618.22577.qmail@web51604.mail.yahoo.com>
References: <20060722033618.22577.qmail@web51604.mail.yahoo.com>
Message-ID: <44C1FBDC.1060809@tds.net>

Christopher Spears wrote:
> I am working out of How To Think Like A Computer
> Scientist.  Here is the code for a module called
> node.py:
>
> def printList(node):
> 		nodeList = []
> 		while node:
> 			nodeList.append(node.cargo)
> 			node = node.next
> 		print nodeList
> 		
> def printBackward(node):
> 	if node == None: return
> 	head = node
> 	tail = node.next
> 	printBackward(tail)
> 	print head,
> 		
> class Node:
> 	def __init__(self, cargo=None, next=None):
> 		self.cargo = cargo
> 		self.next = next
> 		
> 	def __str__(self):
> 		return str(self.cargo)
> 		
>
> I'm trying to figure out how the printBackward
> function works.  I understand it moves up a linked
> list until it reaches the end of the list.  Why does
> it print every node?  Shouldn't it just print the last
> one?
printBackward() scans to the end of the list by making nested calls to 
itself. Each call is matched by a return which returns to the place 
where it was in the next call up the stack. So the most deeply nested 
call will print head and return to the next-most-deeply-nested call 
which will print head, etc.

Each call has its own set of local variables (called a stack frame) - 
its own value for node, head and tail. So the print statements print all 
the cargo in the list.

We just had a discussion of recursion, you might want to look at it - 
though the code is a bit more complex than this example.
http://mail.python.org/pipermail/tutor/2006-July/048081.html

Kent


From klappnase at freenet.de  Sat Jul 22 14:46:18 2006
From: klappnase at freenet.de (Michael Lange)
Date: Sat, 22 Jul 2006 14:46:18 +0200
Subject: [Tutor] : finding out if the horizontal scrollbar on a
 Tix.CheckList is being used or not
In-Reply-To: <44C1248A.60507@gmail.com>
References: <44C07C06.9030904@gmail.com>
	<44C1248A.60507@gmail.com>
Message-ID: <20060722144618.2bc209b0.klappnase@freenet.de>

On Fri, 21 Jul 2006 15:01:30 -0400
Orri Ganel <singingxduck at gmail.com> wrote:

> As a follow up to my last email, I think the issue is more that the 
> display doesn't update before the command associated with the "search" 
> button has finished processing, so any attempts to get data about the 
> display from within the method are fruitless since the display hasn't 
> changed yet.  I am well and truly stumped.  I have no idea how to get 
> around this.  

Calling update_idletasks() from within this method before quering diplay data
should do the trick.

The only way I can think of to do this without using the 
> display is figuring out the longest track name length and setting the 
> CheckList width to the pixel version of that.  Unfortunately, I don't 
> know the conversion for character units to pixels, either, so I'm still 
> stuck.
> 

I think the tkFont module has what you need:

>>> from Tkinter import *
>>> l=Label(text='hi')
>>> l.pack()
>>> import tkFont
>>> f=tkFont.Font(family='helvetica', size='-14')
>>> l.config(font=f)
>>> print f.measure(l['text'])
11
>>> print f.measure('blahblah')
54

I hope this helps

Michael


From lowseotoh at gmail.com  Sat Jul 22 14:49:52 2006
From: lowseotoh at gmail.com (Ivan Low)
Date: Sat, 22 Jul 2006 20:49:52 +0800
Subject: [Tutor] What is the square bracket about?
Message-ID: <11EBE31E-D25B-40F8-AF5E-F68448B7DD9A@gmail.com>

def adder1(*args):
     print 'adder1',
     if type(args[0]) == type(0):
         sum = 0

     else:
         sum = args[0][:0]
     for arg in args:
         sum = sum + arg

     return sum

Hi, I was trying to understand what this function is all about.
I didn't tried the adder1 function which result in adding number or  
text together which I think there is an easier way to do it right?  
Why go through all the way to write a function like this?

The square is a big mystery to me. I can't explain why it is there.
I tried sum(1,2,3) and sum('a','b','c') it wouldn't work. I even  
search the document and I can't find anything there.

Ivan

From john.corry at ntlworld.com  Sat Jul 22 15:11:23 2006
From: john.corry at ntlworld.com (John CORRY)
Date: Sat, 22 Jul 2006 14:11:23 +0100
Subject: [Tutor] loops to assign variables
Message-ID: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>

Hi,
 
I am refactoring my code.  I am trying to reduce the amount of lines by
using more loops.  I tend to use copy and paste a lot instead of writing
a loop to do the work.
 
For example, I have 30 textentry boxes numbered from entry20 to entry50.
I have used the following code to assign the entryboxes to a local name.
 
text20 = self.wTree.get_widget("entry20")
text21 = self.wTree.get_widget("entry21")
 
I have had a go at writing a loop for the above 30 textentry boxes.  It
is below, but it does not work.  
 
for x in range(20,51):
            ent = "entry%s" % (str(x))
                   
            text_x = self.wTree.get_widget(ent)
 
Is it possible to do what I want it to do?  Am I on the right lines?
Any help or advice would be greatly appreciated.
 
Thanks,
 
John.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060722/43f1de3a/attachment.html 

From python at venix.com  Sat Jul 22 15:49:57 2006
From: python at venix.com (Python)
Date: Sat, 22 Jul 2006 09:49:57 -0400
Subject: [Tutor] loops to assign variables
In-Reply-To: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>
References: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>
Message-ID: <1153576197.25576.23.camel@www.venix.com>

On Sat, 2006-07-22 at 14:11 +0100, John CORRY wrote:
> Hi,
>  
> I am refactoring my code.  I am trying to reduce the amount of lines
> by using more loops.  I tend to use copy and paste a lot instead of
> writing a loop to do the work.
>  
> For example, I have 30 textentry boxes numbered from entry20 to
> entry50.
> I have used the following code to assign the entryboxes to a local
> name.
>  
> text20 = self.wTree.get_widget("entry20")
> text21 = self.wTree.get_widget("entry21")
>  
> I have had a go at writing a loop for the above 30 textentry boxes.
> It is below, but it does not work.  
>  
> for x in range(20,51):
>             ent = "entry%s" % (str(x))
>                    
>             text_x = self.wTree.get_widget(ent)
>  
> Is it possible to do what I want it to do?  

NO.  You are looking to create local variables "on the fly".  But there
is a simple solution that accomplishes what you really want.

> Am I on the right lines?

Rather than use local variables, create a container to hold the entry
values.  Then access the entry values from the container.

One container to consider is a dictionary.  It allows you to retrieve
values using fairly arbitrary keys.  Rewriting your loop from above,

text = {}	# create dictionary
for x in range(20,51):
    ent = "entry%s" % (x)	# removed unnecessary str(x)
    text[x] = self.wTree.get_widget(ent)

Now you can retrieve the values from text using the numbers.  So rather
than text_x, you will code text[x] (or text[20], etc.).

> Any help or advice would be greatly appreciated.

(For program snippets and the kind of content on this list, HTML often
gets in the way.  My email program (Evolution) rendered your email in a
tiny, illegible font.  Turning off HTML would be helpful.)

>  
> Thanks,
>  
> John.
-- 
Lloyd Kvam
Venix Corp


From johnsonv3 at sbcglobal.net  Sat Jul 22 15:57:01 2006
From: johnsonv3 at sbcglobal.net (johnsonv3)
Date: Sat, 22 Jul 2006 09:57:01 -0400
Subject: [Tutor] search path
Message-ID: <000a01c6ad96$b4d9a560$516efb44@home>

Hi,

If one does this...

import sys
sys.path.append("C:\\panda\direct")

Is the change to python search path only temporary?
Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060722/4d910568/attachment.htm 

From johnsonv3 at sbcglobal.net  Sat Jul 22 16:03:14 2006
From: johnsonv3 at sbcglobal.net (johnsonv3)
Date: Sat, 22 Jul 2006 10:03:14 -0400
Subject: [Tutor] search path
Message-ID: <001101c6ad97$9306c840$516efb44@home>

Another search path question

When one installs a program (such as Panda or Livewires) into python sitepackage folder is the python search path automnatically updated to search the newly installed folders and files?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060722/624b87d1/attachment.html 

From khp at pflaesterer.de  Sat Jul 22 17:18:29 2006
From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=)
Date: Sat, 22 Jul 2006 17:18:29 +0200
Subject: [Tutor] loops to assign variables
In-Reply-To: <1153576197.25576.23.camel@www.venix.com> (python@venix.com's
	message of "Sat, 22 Jul 2006 09:49:57 -0400")
References: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>
	<1153576197.25576.23.camel@www.venix.com>
Message-ID: <u4px9k6ve.fsf@hamster.pflaesterer.de>

On 22 Jul 2006, python at venix.com wrote:

>
> On Sat, 2006-07-22 at 14:11 +0100, John CORRY wrote:
>> Hi,
>>  
>> I am refactoring my code.  I am trying to reduce the amount of lines
>> by using more loops.  I tend to use copy and paste a lot instead of
>> writing a loop to do the work.
>>  
>> For example, I have 30 textentry boxes numbered from entry20 to
>> entry50.
>> I have used the following code to assign the entryboxes to a local
>> name.
>>  
>> text20 = self.wTree.get_widget("entry20")
>> text21 = self.wTree.get_widget("entry21")
>>  
>> I have had a go at writing a loop for the above 30 textentry boxes.
>> It is below, but it does not work.  
>>  
>> for x in range(20,51):
>>             ent = "entry%s" % (str(x))
>>                    
>>             text_x = self.wTree.get_widget(ent)
>>  
>> Is it possible to do what I want it to do?  
>
> NO.  You are looking to create local variables "on the fly".  But there
> is a simple solution that accomplishes what you really want.

The "no" is not absolutely right IMO.  He could write directly in the
dictionary he gets when he calls locals() (but I think you're right in
saying that this is only seldom a good idea).


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list

From python at venix.com  Sat Jul 22 17:37:38 2006
From: python at venix.com (Python)
Date: Sat, 22 Jul 2006 11:37:38 -0400
Subject: [Tutor] loops to assign variables
In-Reply-To: <u4px9k6ve.fsf@hamster.pflaesterer.de>
References: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>
	<1153576197.25576.23.camel@www.venix.com>
	<u4px9k6ve.fsf@hamster.pflaesterer.de>
Message-ID: <1153582658.25576.79.camel@www.venix.com>

On Sat, 2006-07-22 at 17:18 +0200, Karl Pfl?sterer wrote:
> On 22 Jul 2006, python at venix.com wrote:
> 
> >
> > On Sat, 2006-07-22 at 14:11 +0100, John CORRY wrote:
> >> Hi,
> >>  
> >> I am refactoring my code.  I am trying to reduce the amount of lines
> >> by using more loops.  I tend to use copy and paste a lot instead of
> >> writing a loop to do the work.
> >>  
> >> For example, I have 30 textentry boxes numbered from entry20 to
> >> entry50.
> >> I have used the following code to assign the entryboxes to a local
> >> name.
> >>  
> >> text20 = self.wTree.get_widget("entry20")
> >> text21 = self.wTree.get_widget("entry21")
> >>  
> >> I have had a go at writing a loop for the above 30 textentry boxes.
> >> It is below, but it does not work.  
> >>  
> >> for x in range(20,51):
> >>             ent = "entry%s" % (str(x))
> >>                    
> >>             text_x = self.wTree.get_widget(ent)
> >>  
> >> Is it possible to do what I want it to do?  
> >
> > NO.  You are looking to create local variables "on the fly".  But there
> > is a simple solution that accomplishes what you really want.
> 
> The "no" is not absolutely right IMO.  He could write directly in the
> dictionary he gets when he calls locals() (but I think you're right in
> saying that this is only seldom a good idea).

Well the reference documentation says:

locals(
)
        Update and return a dictionary representing the current local
        symbol table. Warning: The contents of this dictionary should
        not be modified; changes may not affect the values of local
        variables used by the interpreter.

I believe the compiler thinks it knows of all the local variables, so I
think assignment to locals() is likely to lead to grief even it appears
to work in simple test cases.

-- 
Lloyd Kvam
Venix Corp


From johnsonv3 at sbcglobal.net  Sat Jul 22 18:21:10 2006
From: johnsonv3 at sbcglobal.net (johnsonv3)
Date: Sat, 22 Jul 2006 12:21:10 -0400
Subject: [Tutor] starting a program from python
Message-ID: <002701c6adaa$d823aca0$516efb44@home>

Hi,
Using Windows XP Home & python 234
I am trying to start python programs that run Panda 3D without having to open command prompt and type a path every time I run a program.

This pandastart.bat file works... 

cd C:\Panda3D-1.2.3\mystuff
ppython bvd.py

and from python shell this works....

>>> subprocess.Popen("pandastart.bat")
<subprocess.Popen object at 0x00E07DD0>

But it is not flexible to start other file names..

So I would like to write a python script similar to this....

import subprocess
panda = raw_input("Enter name of Panda python program to start (fileName.py)")
subprocess.Popen("C:\panda3D-1.2.3\mystuff\panda")

But this is the result...

>>> subprocess.Popen("C:\panda3D-1.2.3\mystuff\bvd.py")
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in ?
    subprocess.Popen("C:\panda3D-1.2.3\mystuff\bvd.py")
  File "C:\Python24\lib\subprocess.py", line 542, in __init__
    errread, errwrite)
  File "C:\Python24\lib\subprocess.py", line 706, in _execute_child
    startupinfo)
WindowsError: [Errno 123] The filename, directory name, or volume label syntax is incorrect

Also tried the below (change to the path) with result as indicate below....

>>> subprocess.Popen("C:\panda3D-1.2.3\mystuff bvd.py")
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in ?
    subprocess.Popen("C:\panda3D-1.2.3\mystuff bvd.py")
  File "C:\Python24\lib\subprocess.py", line 542, in __init__
    errread, errwrite)
  File "C:\Python24\lib\subprocess.py", line 706, in _execute_child
    startupinfo)
WindowsError: [Errno 5] Access is denied

Have tried using os.system and os.startfile with similar results

Suggested solution?
Thanks. 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060722/7a0567b8/attachment.html 

From dkuhlman at rexx.com  Sat Jul 22 19:04:25 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sat, 22 Jul 2006 10:04:25 -0700
Subject: [Tutor] What is the square bracket about?
In-Reply-To: <11EBE31E-D25B-40F8-AF5E-F68448B7DD9A@gmail.com>
References: <11EBE31E-D25B-40F8-AF5E-F68448B7DD9A@gmail.com>
Message-ID: <20060722170425.GA19312@cutter.rexx.com>

On Sat, Jul 22, 2006 at 08:49:52PM +0800, Ivan Low wrote:
> def adder1(*args):
>      print 'adder1',
>      if type(args[0]) == type(0):
>          sum = 0
> 
>      else:
>          sum = args[0][:0]
>      for arg in args:
>          sum = sum + arg
> 
>      return sum
> 
> Hi, I was trying to understand what this function is all about.
> I didn't tried the adder1 function which result in adding number or  
> text together which I think there is an easier way to do it right?  
> Why go through all the way to write a function like this?
> 
> The square is a big mystery to me. I can't explain why it is there.
> I tried sum(1,2,3) and sum('a','b','c') it wouldn't work. I even  
> search the document and I can't find anything there.
> 

Square brackets are the indexing operator.  When it contains a
colon, it returns a slice, which is a sub-sequence of the sequence
to which it is applied.  See:

    http://docs.python.org/tut/node5.html#SECTION005140000000000000000

In ``args[0][:0]``,

1. args[0] returns the first item in the array args.

2. next, [:0] returns an empty list.  Why?  It returns a slice of
   the list that starts with the first element (because the index
   *before* the colon is omitted) and ends with the element before
   the first element (because of the zero after the colon).

You might try running this code with the pdb debugger.  And, for
example, add code to set a few temporary variables:

    tmp1 = args[0]
    tmp2 = tmp1[:0]

Then, in the debugger, inspect tmp1 and tmp2.

Or, just add a few print statements.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From dkuhlman at rexx.com  Sat Jul 22 19:22:30 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sat, 22 Jul 2006 10:22:30 -0700
Subject: [Tutor] loops to assign variables
In-Reply-To: <1153582658.25576.79.camel@www.venix.com>
References: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>
	<1153576197.25576.23.camel@www.venix.com>
	<u4px9k6ve.fsf@hamster.pflaesterer.de>
	<1153582658.25576.79.camel@www.venix.com>
Message-ID: <20060722172230.GB19312@cutter.rexx.com>

On Sat, Jul 22, 2006 at 11:37:38AM -0400, Python wrote:
> On Sat, 2006-07-22 at 17:18 +0200, Karl Pfl?sterer wrote:
> > On 22 Jul 2006, python at venix.com wrote:
> > 
> > >
> > > On Sat, 2006-07-22 at 14:11 +0100, John CORRY wrote:
> > >> Hi,
> > >>  
> > >> I am refactoring my code.  I am trying to reduce the amount of lines
> > >> by using more loops.  I tend to use copy and paste a lot instead of
> > >> writing a loop to do the work.
> > >>  
> > >> For example, I have 30 textentry boxes numbered from entry20 to
> > >> entry50.
> > >> I have used the following code to assign the entryboxes to a local
> > >> name.
> > >>  
> > >> text20 = self.wTree.get_widget("entry20")
> > >> text21 = self.wTree.get_widget("entry21")
> > >>  
> > >> I have had a go at writing a loop for the above 30 textentry boxes.
> > >> It is below, but it does not work.  
> > >>  
> > >> for x in range(20,51):
> > >>             ent = "entry%s" % (str(x))
> > >>                    
> > >>             text_x = self.wTree.get_widget(ent)
> > >>  
> > >> Is it possible to do what I want it to do?  
> > >
> > > NO.  You are looking to create local variables "on the fly".  But there
> > > is a simple solution that accomplishes what you really want.
> > 
> > The "no" is not absolutely right IMO.  He could write directly in the
> > dictionary he gets when he calls locals() (but I think you're right in
> > saying that this is only seldom a good idea).
> 
> Well the reference documentation says:
> 
> locals(
> )
>         Update and return a dictionary representing the current local
>         symbol table. Warning: The contents of this dictionary should
>         not be modified; changes may not affect the values of local
>         variables used by the interpreter.
> 
> I believe the compiler thinks it knows of all the local variables, so I
> think assignment to locals() is likely to lead to grief even it appears
> to work in simple test cases.
> 

Lloyd is spot-on in telling you to avoid creating variables from
strings.  There almost always is a better way, which members of
this list seem to have to repeat once each week.

But, (and I'm going off-topic here and possibly into the ditch
along the side of the road) ..., locals() returns a dictionary.
It's a dictionary like any other dictionary.  And, it is that
dictionary which Python uses to check for the existence of a
variable *at runtime*.  Yes. That's right.  Python actually does a
dictionary look-up for each variable at runtime.  This is *not* a
flaw; it is part of the object model and execution model of
Python.  And, that's why compile-time (static) type checking in
Python is either impossible or would require type inference.

And, also, that's why the following statements all have exactly
the same effect:

    total = 5
    locals()['total'] = 5
    exec('total = 5')

But, again, as Lloyd said, don't do that.  (1) Use a dictionary of
your own and do a look up.  Or, (2) implement a class that does a
lookup.  Or, (3) use one of the other suggestion made on this
list.

Dave



-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From dkuhlman at rexx.com  Sat Jul 22 19:29:23 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sat, 22 Jul 2006 10:29:23 -0700
Subject: [Tutor] search path
In-Reply-To: <000a01c6ad96$b4d9a560$516efb44@home>
References: <000a01c6ad96$b4d9a560$516efb44@home>
Message-ID: <20060722172923.GC19312@cutter.rexx.com>

On Sat, Jul 22, 2006 at 09:57:01AM -0400, johnsonv3 wrote:
> Hi,
> 
> If one does this...
> 
> import sys
> sys.path.append("C:\\panda\direct")
> 
> Is the change to python search path only temporary?
> Thanks.

As we quibblers like to say, That depends on the meaning of the
word "temporary".

Modifications to sys.path (insert or append) last until the end of
the execution of your program.

Although there are times when modifying sys.path at run-time is
necessary, there is usually a better way.  Usually you will want
to add a path to the environment variable PYTHONPATH.  How you do
that depends on your platform (Linux, MS Windows, ...).

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From chris.arndt at web.de  Sat Jul 22 19:31:18 2006
From: chris.arndt at web.de (Christopher Arndt)
Date: Sat, 22 Jul 2006 18:31:18 +0100
Subject: [Tutor] search path
In-Reply-To: <000a01c6ad96$b4d9a560$516efb44@home>
References: <000a01c6ad96$b4d9a560$516efb44@home>
Message-ID: <44C260E6.40507@web.de>

johnsonv3 schrieb:
> If one does this...
>  
> import sys
> sys.path.append("C:\\panda\direct")
>  
> Is the change to python search path only temporary?

Yes, it only changes the search path within that program. The system-wide
default search path is not changed.

Chris

From chris.arndt at web.de  Sat Jul 22 19:39:06 2006
From: chris.arndt at web.de (Christopher Arndt)
Date: Sat, 22 Jul 2006 18:39:06 +0100
Subject: [Tutor] search path
In-Reply-To: <001101c6ad97$9306c840$516efb44@home>
References: <001101c6ad97$9306c840$516efb44@home>
Message-ID: <e9tnrs$5je$1@sea.gmane.org>

johnsonv3 schrieb:
> When one installs a program (such as Panda or Livewires) into python
> sitepackage folder is the python search path automnatically updated to
> search the newly installed folders and files?

Generally speaking, yes. The Python package (to use the proper name) either
needs to have a files '__init__.py' in its package directory

(see http://pytut.infogami.com/node8.html, section "Packages")

or the name of its package directory needs to be added to a .pth file

(see http://docs.python.org/lib/module-site.html)


Chris


From kent37 at tds.net  Sat Jul 22 19:41:17 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 22 Jul 2006 13:41:17 -0400
Subject: [Tutor] loops to assign variables
In-Reply-To: <20060722172230.GB19312@cutter.rexx.com>
References: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>	<1153576197.25576.23.camel@www.venix.com>	<u4px9k6ve.fsf@hamster.pflaesterer.de>	<1153582658.25576.79.camel@www.venix.com>
	<20060722172230.GB19312@cutter.rexx.com>
Message-ID: <44C2633D.7020404@tds.net>

Dave Kuhlman wrote:
> On Sat, Jul 22, 2006 at 11:37:38AM -0400, Python wrote:
>   
>>
>> Well the reference documentation says:
>>
>> locals(
>> )
>>         Update and return a dictionary representing the current local
>>         symbol table. Warning: The contents of this dictionary should
>>         not be modified; changes may not affect the values of local
>>         variables used by the interpreter.
>>
>> I believe the compiler thinks it knows of all the local variables, so I
>> think assignment to locals() is likely to lead to grief even it appears
>> to work in simple test cases.
>>
>>     
> But, (and I'm going off-topic here and possibly into the ditch
> along the side of the road) ..., locals() returns a dictionary.
> It's a dictionary like any other dictionary.  And, it is that
> dictionary which Python uses to check for the existence of a
> variable *at runtime*.  Yes. That's right.  Python actually does a
> dictionary look-up for each variable at runtime.  This is *not* a
> flaw; it is part of the object model and execution model of
> Python.  And, that's why compile-time (static) type checking in
> Python is either impossible or would require type inference.
>
> And, also, that's why the following statements all have exactly
> the same effect:
>
>     total = 5
>     locals()['total'] = 5
>     exec('total = 5')

You're not in the mood to believe the docs today, eh? Yes, locals() 
returns a dict and yes, you can modify it. And yes, "changes may not 
affect the values of local variables used by the interpreter." In 
particular modifying locals() inside a function doesn't do what you 
think it will:

In [14]: def badlocals():
   ....:     locals()['total'] = 5
   ....:     print total
   ....:

In [15]: badlocals
Out[15]: <function badlocals at 0x00E4AEB0>

In [16]: badlocals()
---------------------------------------------------------------------------
exceptions.NameError                                 Traceback (most 
recent call last)

F:\Bio\BIOE480\Final project\SequenceAlignment\<ipython console>

F:\Bio\BIOE480\Final project\SequenceAlignment\<ipython console> in 
badlocals()

NameError: global name 'total' is not defined

At global scope, locals() == globals() and modifying it affects the 
global namespace. In function scope, I believe locals() is actually a 
copy of the real namespace.

Kent


From gsf at panix.com  Sat Jul 22 20:59:44 2006
From: gsf at panix.com (Gabriel Farrell)
Date: Sat, 22 Jul 2006 14:59:44 -0400
Subject: [Tutor] lists and recursion
In-Reply-To: <44C1FBDC.1060809@tds.net>
References: <20060722033618.22577.qmail@web51604.mail.yahoo.com>
	<44C1FBDC.1060809@tds.net>
Message-ID: <20060722185944.GC17656@panix.com>

On Sat, Jul 22, 2006 at 06:20:12AM -0400, Kent Johnson wrote:
> We just had a discussion of recursion, you might want to look at it - 
> though the code is a bit more complex than this example.
> http://mail.python.org/pipermail/tutor/2006-July/048081.html

Glad to see I'm not the only one to get tripped up by stack frames.  I
guess that's what happens to us non-CS majors who get into Python.
After I got Kent's explanation in the discussion he refers to above, I
did a little research.  The best shortish description of the call
stack is, not surprisingly, at Wikipedia:
http://en.wikipedia.org/wiki/Call_stack

I understood things a bit better once I took the time to digest that
article.

gabe

From dyoo at hkn.eecs.berkeley.edu  Sat Jul 22 22:03:53 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 22 Jul 2006 13:03:53 -0700 (PDT)
Subject: [Tutor] What is the square bracket about?
In-Reply-To: <20060722170425.GA19312@cutter.rexx.com>
References: <11EBE31E-D25B-40F8-AF5E-F68448B7DD9A@gmail.com>
	<20060722170425.GA19312@cutter.rexx.com>
Message-ID: <Pine.LNX.4.64.0607221258540.32563@hkn.eecs.berkeley.edu>

>> def adder1(*args):
>>      print 'adder1',
>>      if type(args[0]) == type(0):
>>          sum = 0
>>      else:
>>          sum = args[0][:0]
>>      for arg in args:
>>          sum = sum + arg
>>      return sum


This function looks overly enamored with Python slicing.  *grin* Unless 
I'm missing something, this function can be simplified to:

####################################################################
def adder(*args):
     """Sum up a list of args, assuming that the list is nonempty."""
     running_sum = args[0]
     for element in args[1:]:
         running_sum = running_sum + element
     return running_sum
####################################################################

That is, in stilted English: take the first element, and treat that as our 
initial sum.  Run through the rest of the elements, and add each such 
element to our running sum.  At the end of the iteration, we should be 
done, and our running subtotal sum should be the sum of all the elements.

From dkuhlman at rexx.com  Sat Jul 22 22:04:18 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sat, 22 Jul 2006 13:04:18 -0700
Subject: [Tutor] loops to assign variables
In-Reply-To: <44C2633D.7020404@tds.net>
References: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>
	<1153576197.25576.23.camel@www.venix.com>
	<u4px9k6ve.fsf@hamster.pflaesterer.de>
	<1153582658.25576.79.camel@www.venix.com>
	<20060722172230.GB19312@cutter.rexx.com> <44C2633D.7020404@tds.net>
Message-ID: <20060722200418.GA21145@cutter.rexx.com>

On Sat, Jul 22, 2006 at 01:41:17PM -0400, Kent Johnson wrote:
> Dave Kuhlman wrote:

[snip]

> > And, also, that's why the following statements all have exactly
> > the same effect:
> >
> >     total = 5
> >     locals()['total'] = 5
> >     exec('total = 5')
> 
> You're not in the mood to believe the docs today, eh? Yes, locals() 
> returns a dict and yes, you can modify it. And yes, "changes may not 
> affect the values of local variables used by the interpreter." In 
> particular modifying locals() inside a function doesn't do what you 
> think it will:
> 
> In [14]: def badlocals():
>    ....:     locals()['total'] = 5
>    ....:     print total
>    ....:
> 
> In [15]: badlocals
> Out[15]: <function badlocals at 0x00E4AEB0>
> 
> In [16]: badlocals()
> ---------------------------------------------------------------------------
> exceptions.NameError                                 Traceback (most 
> recent call last)
> 
> F:\Bio\BIOE480\Final project\SequenceAlignment\<ipython console>
> 
> F:\Bio\BIOE480\Final project\SequenceAlignment\<ipython console> in 
> badlocals()
> 
> NameError: global name 'total' is not defined

Good lord.  I feel queasy.  I think I just felt the ground move
under me.  (We in California near the fault line are sensitive
that way.)  What is the explanation of this?

> 
> At global scope, locals() == globals() and modifying it affects the 
> global namespace. In function scope, I believe locals() is actually a 
> copy of the real namespace.

Ah. I see.  A copy, eh?  Or, at least a new dictionary separate
from the "real" namespace.  OK.  I don't know why locals() returns
a copy as opposed to the original, but at least that explains the
results of the example you give.  And, the sickening feeling of
dread has gone away, the feeling or dread one has when the
fundamental structure of the (Python) world has been turned upside
down.

Thanks for correcting me and for clarification.  And, looks like
Lloyd was right.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From alan.gauld at freenet.co.uk  Sun Jul 23 12:16:28 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 23 Jul 2006 11:16:28 +0100
Subject: [Tutor] loops to assign variables
References: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC><1153576197.25576.23.camel@www.venix.com><u4px9k6ve.fsf@hamster.pflaesterer.de><1153582658.25576.79.camel@www.venix.com><20060722172230.GB19312@cutter.rexx.com>
	<44C2633D.7020404@tds.net> <20060722200418.GA21145@cutter.rexx.com>
Message-ID: <000e01c6ae41$0fb70e00$0201a8c0@XPpro>

I've been on vacation so missed the start of this, apologies 
if i'm missing a point somewhere but...

> Ah. I see.  A copy, eh?  Or, at least a new dictionary separate
> from the "real" namespace.  OK.  I don't know why locals() returns
> a copy as opposed to the original, 

What else can it do?
When you enter a function you enter a new namespace.
It starts out containing the global names and any parameters 
to the function then adds new names as they are created 
plus overrides any global names that get replaced with 
local versions.

It can only do that if it is working on a copy of the global 
namespace to start with otherwise it would be polluting the 
global namespace with local functon versions and in a 
multithreaded environment creating havoc across threads!...

I hope I haven't missed the point and have added some 
clarification, if not forgive me for butting in late! :-)

Alan G.


From english_summer_rain01 at yahoo.com  Sun Jul 23 19:51:48 2006
From: english_summer_rain01 at yahoo.com (Joe F)
Date: Sun, 23 Jul 2006 10:51:48 -0700 (PDT)
Subject: [Tutor] images in pygame
Message-ID: <20060723175148.43779.qmail@web39207.mail.mud.yahoo.com>

Hello, I have a code here. and I want to make the "rockwholescreen.gif" blocked, but still displayed.  I want it so "001.png" can't walk through that gif.  any ideas?

import pygame, os, sys
from pygame.locals import *
 
 
pygame.init( )
 
def _loadImages_ ( path, name ):
        image_obj   = os.path.join( path, name )
        image_load = pygame.image.load( image_obj )
 
        return image_load
 
images_path  = './img/'
images_dict    = {}
image_names = { 1:"001.png", 2:"rockwholescreen.gif" }
 
for dir, name in image_names.items( ):
    images_dict[dir] = _loadImages_( images_path, name )   
 
setwinsize = ( 640, 480 )
windows    = pygame.display.set_mode( setwinsize )
 
#load First Image
imageload  = images_dict[1]
imagerect   = imageload.get_rect( 0, 0, * windows.get_size( ))
 
#load Second Image
imageloads = images_dict[2]
imagerects  = pygame.Rect( 0, 448, * windows.get_size( ))


 
while True:
    events = pygame.event.wait( )
 
    if events.type == pygame.QUIT:
        break
 
    if events.type == pygame.KEYDOWN:
        if events.key == K_DOWN:
            imagerect.move_ip( 0, 10 ); imageload = images_dict[1]
        if events.key == K_UP:
            imagerect.move_ip( 0, -10 ); imageload = images_dict[1]
        if events.key == K_RIGHT:
            imagerect.move_ip( 10, 0 ); imageload = images_dict[1]
        if events.key == K_LEFT:
            imagerect.move_ip( -10, 0 ); imageload = images_dict[1]
 
 
    windows.fill(( 25, 110, 189 ))
    windows.blit( imageload, imagerect )
    windows.blit( imageloads, imagerects )
    pygame.display.flip( )
 
    print "Image One Rect: %s \n" % imagerect
    print "Image Two Rect: %s \n" % imagerects

fonts = pygame.font.Font(None, 26)

_colors_ = { "black" : (0, 0, 0),
        "red" : (255, 0, 0)
            }
_text_         = fonts.render('Testing', 0, _colors_['red'] )
_rtext_     = screensize[0] - _text_.get_width( ), 0

while True:
    events = pygame.event.wait( )
    if events.type == pygame.QUIT:
        break

    windows.blit( _text_, _rtext_ )
    pygame.display.flip( )

pygame.quit( )


thanks..

 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060723/5e3ab927/attachment.html 

From kent37 at tds.net  Sun Jul 23 22:52:43 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 23 Jul 2006 16:52:43 -0400
Subject: [Tutor] starting a program from python
In-Reply-To: <002701c6adaa$d823aca0$516efb44@home>
References: <002701c6adaa$d823aca0$516efb44@home>
Message-ID: <44C3E19B.7010201@tds.net>

johnsonv3 wrote:
> Hi,
> Using Windows XP Home & python 234
> I am trying to start python programs that run Panda 3D without having 
> to open command prompt and type a path every time I run a program.
>  
> This pandastart.bat file works...
>  
> cd C:\Panda3D-1.2.3\mystuff
> ppython bvd.py
>  
> and from python shell this works....
>  
> >>> subprocess.Popen("pandastart.bat")
> <subprocess.Popen object at 0x00E07DD0>
>  
> But it is not flexible to start other file names..
>  
> So I would like to write a python script similar to this....
>  
> import subprocess
> panda = raw_input("Enter name of Panda python program to start 
> (fileName.py)")
> subprocess.Popen("C:\panda3D-1.2.3\mystuff\panda")
Here panda is the name of a variable whose value is the name of the file 
you want to run. Python won't automatically insert the value of a 
variable into a string, it thinks you want to Popen a file called 
"C:\panda3D-1.2.3\mystuff\panda". Since there is no file with that name, 
you get an error.

You can use string formatting to get the name of the file into the 
string for Popen(). Try this:
subprocess.Popen("C:\panda3D-1.2.3\mystuff\%s" % panda)

For more info on string formatting:
http://docs.python.org/lib/typesseq-strings.html

Kent
>  
> But this is the result...
>  
> >>> subprocess.Popen("C:\panda3D-1.2.3\mystuff\bvd.py")
> Traceback (most recent call last):
>   File "<pyshell#19>", line 1, in ?
>     subprocess.Popen("C:\panda3D-1.2.3\mystuff\bvd.py")
>   File "C:\Python24\lib\subprocess.py", line 542, in __init__
>     errread, errwrite)
>   File "C:\Python24\lib\subprocess.py", line 706, in _execute_child
>     startupinfo)
> WindowsError: [Errno 123] The filename, directory name, or volume 
> label syntax is incorrect
>  
> Also tried the below (change to the path) with result as indicate 
> below....
>  
> >>> subprocess.Popen("C:\panda3D-1.2.3\mystuff bvd.py")
> Traceback (most recent call last):
>   File "<pyshell#20>", line 1, in ?
>     subprocess.Popen("C:\panda3D-1.2.3\mystuff bvd.py")
>   File "C:\Python24\lib\subprocess.py", line 542, in __init__
>     errread, errwrite)
>   File "C:\Python24\lib\subprocess.py", line 706, in _execute_child
>     startupinfo)
> WindowsError: [Errno 5] Access is denied
>  
> Have tried using os.system and os.startfile with similar results
>  
> Suggested solution?
> Thanks. 
>  
>  
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From kent37 at tds.net  Sun Jul 23 22:55:32 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 23 Jul 2006 16:55:32 -0400
Subject: [Tutor] Writing python scripts to control GIMP
In-Reply-To: <7d81675b0607200610s797e8676j379ecef5649c1ab6@mail.gmail.com>
References: <7d81675b0607200610s797e8676j379ecef5649c1ab6@mail.gmail.com>
Message-ID: <44C3E244.2000806@tds.net>

Richard Querin wrote:
> Hi,
>
> I'm interested in learning about how to write python scripts that can 
> control the GIMP. I've read about several scripts but I'd like to know 
> where to start learning about how it's done. Anybody got any good 
> places to look for tutorials, references etc? 

Have you looked at the Gimp-Python docs?
http://www.jamesh.id.au/software/pygimp/

Kent


From amonroe at columbus.rr.com  Mon Jul 24 00:28:33 2006
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sun, 23 Jul 2006 18:28:33 -0400
Subject: [Tutor] images in pygame
In-Reply-To: <20060723175148.43779.qmail@web39207.mail.mud.yahoo.com>
References: <20060723175148.43779.qmail@web39207.mail.mud.yahoo.com>
Message-ID: <66723627010.20060723182833@columbus.rr.com>

Dunno if this is the best way, but it works...
Replace this:

>         if events.key == K_DOWN:

with this:

>         if events.key == K_DOWN and not imagerect.colliderect(imagerects):


Alan


From rabidpoobear at gmail.com  Mon Jul 24 01:00:09 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 23 Jul 2006 18:00:09 -0500
Subject: [Tutor] images in pygame
Message-ID: <44C3FF79.6000208@gmail.com>

the tutor mailing list didn't like the zip I attached, so here's the 
text of the e-mail I wrote to
Joe without the zip included.

----start-----
Pygame-specific questions should be posted to the pygame mailing list, 
not tutor, probably.
Joe F wrote:
> Hello, I have a code here. and I want to make the 
> "rockwholescreen.gif" blocked, but still displayed.  I want it so 
> "001.png" can't walk through that gif.  any ideas?
>
> import pygame, os, sys
> from pygame.locals import *
>  
>  
> pygame.init( )
>  
> def _loadImages_ ( path, name ):
>         image_obj   = os.path.join( path, name )
>         image_load = pygame.image.load( image_obj )
>  
>         return image_load
why do you have underscores in the name of this function?
Usually underscores denote functions that are supposed to be private to 
a class,
I believe, and this function's not in a class at all!
also,there's no reason to create an 'image_load' variable.
return pygame.image.load( image_obj )
would do just as well.

>  
> images_path  = './img/'
> images_dict    = {}
> image_names = { 1:"001.png", 2:"rockwholescreen.gif" }
>  
> for dir, name in image_names.items( ):
>     images_dict[dir] = _loadImages_( images_path, name )
this strikes me as a very odd way to handle image-loading.
if you're using integers as a reference for a dict why not just use
list indices?
#-------
images_path = './img/'
image_names = ['001.png','rockwholescreen.gif']
images = [_loadImages_(images_path,name) for name in image_names]
#-------
It took me a minute to figure out what you
were doing, and this way I think your intent is more clear.
>  
> setwinsize = ( 640, 480 )
> windows    = pygame.display.set_mode( setwinsize )
I'm guessing you're using a global 'setwinsize' so you don't hard-code 
in your resolution.
If you're going to do this, why not just put your globals at the top, so 
they're easier to change?
If you have to go hunting through your code for a global you want, it's 
just barely
better than hunting through your code to find the place where you need 
to change
the hardcoded value.
>  
> #load First Image
> imageload  = images_dict[1]
> imagerect   = imageload.get_rect( 0, 0, * windows.get_size( ))
why not just use setwinsize here also instead of getting the size of the 
display surface?
it'll probably be faster.
also, I don't understand why you're doing get_rect on (0,0,640,480)
does get_rect select a subsurface of the image?
>  
> #load Second Image
> imageloads = images_dict[2]
> imagerects  = pygame.Rect( 0, 448, * windows.get_size( ))
if you find yourself appending letters to variable names to distinguish 
them you're
probably at the point where you should be using lists.
If someone weren't reading your code very carefully they may get 
confused here
and think these variables are the same as the ones above.
Also, later in your code, you might get confused and use the wrong one
of these variables without even realizing and give yourself debugging 
headaches.
I don't understand what the * here is doing.  it doesn't seem to work 
for me.
>
>
>  
> while True:
>     events = pygame.event.wait( )
I'm pretty sure pygame.event.wait() blocks until if gets an event.
Think about this, is this really what you want?
If the user sits there not sending any events, the screen won't update,
but if they move their mouse, you'll get a lot of mousemovement events
and such, and then your program will be rapidly filling the whole screen
with the color (25,110,189) and re-blitting everything even though 
nothing moved.

>  
>     if events.type == pygame.QUIT:
>         break
>  
>     if events.type == pygame.KEYDOWN:
>         if events.key == K_DOWN:
>             imagerect.move_ip( 0, 10 ); imageload = images_dict[1]
>         if events.key == K_UP:
>             imagerect.move_ip( 0, -10 ); imageload = images_dict[1]
>         if events.key == K_RIGHT:
>             imagerect.move_ip( 10, 0 ); imageload = images_dict[1]
>         if events.key == K_LEFT:
>             imagerect.move_ip( -10, 0 ); imageload = images_dict[1]

I don't think the escape key raises a pygame.QUIT so if you want the 
user to be
able to exit with the escape key, you should put
also, since you imported everything from pygame.locals you don't need a 
'pygame.' here
#------
if events.key == K_ESCAPE: break
#---------
to get this effect.
>  
>  
>     windows.fill(( 25, 110, 189 ))
>     windows.blit( imageload, imagerect )
>     windows.blit( imageloads, imagerects )
>     pygame.display.flip( )
here you're not doing dirty-rect animation. you're just updating the 
whole screen every time
you get an event.
This is okay for an example but for a real game you'll need to use some 
form of
dirty-rect updating method if it needs good performance.
>  
>     print "Image One Rect: %s \n" % imagerect
>     print "Image Two Rect: %s \n" % imagerects
>
> fonts = pygame.font.Font(None, 26)
>
> _colors_ = { "black" : (0, 0, 0),
>         "red" : (255, 0, 0)
>             }
again, why the underlines?  Are you trying to avoid a namespace collision?
> _text_         = fonts.render('Testing', 0, _colors_['red'] )
> _rtext_     = screensize[0] - _text_.get_width( ), 0
>
> while True:
>     events = pygame.event.wait( )
>     if events.type == pygame.QUIT:
>         break
>
>     windows.blit( _text_, _rtext_ )
>     pygame.display.flip( )
>
so when the '001.png' runs into the 'rockwholescreen.gif' you want it to 
display 'testing' in red?
You don't have any detection in your first 'while' loop that breaks out 
of the loop
if it finds a collision between these two images.
Right now all your code does is move an image around.
I'm attaching an example zip of what I would do to solve this problem.
> pygame.quit( )
>
>
> thanks..
sure.
Just remember, the pygame mailing list specializes in these kinds of 
questions
and can give you lots of good pointers.
-Luke

From bugracakir at gmail.com  Mon Jul 24 08:46:13 2006
From: bugracakir at gmail.com (Bugra Cakir)
Date: Mon, 24 Jul 2006 09:46:13 +0300
Subject: [Tutor] IDLE Caching
Message-ID: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>

Hi,

I have a problem with IDLE on Windows.
While I'm executing a python script in IDLE subsequence
editing and executions on the file sometimes doesn't reflect the changes.
For example, i changed the file then save it, execute it, although i changed
the file, IDLE shows the previous version of the file. If I close and run
the IDLE
then it correctly shows the execution of the current source file. What will
be
the problem ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/7882c3b3/attachment.htm 

From rabidpoobear at gmail.com  Mon Jul 24 08:51:54 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 24 Jul 2006 01:51:54 -0500
Subject: [Tutor] IDLE Caching
In-Reply-To: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
Message-ID: <44C46E0A.4050601@gmail.com>

Bugra Cakir wrote:
> Hi,
>
> I have a problem with IDLE on Windows.
> While I'm executing a python script in IDLE subsequence
you mean subsequent :)
> editing and executions on the file sometimes doesn't reflect the changes.
> For example, i changed the file then save it, execute it, although i 
> changed
> the file, IDLE shows the previous version of the file. If I close and 
> run the IDLE
> then it correctly shows the execution of the current source file. What 
> will be
> the problem ?
this is what (I believe) usually causes this for me:
I make a file called 'temp.py' for example in the directory
'c:/python scripts/'
I open it in IDLE to edit it.
I say 'oops, I meant for the file to be in a different directory
so I save the file as 'temp.py' in the directory
'c:/python scripts/7-24-2006/'
now whenever I save changes it saves to the
'temp.py' that's in 'c:/python scripts/7-24-2006/'
but whenever I execute the code it executes
'temp.py' that's in 'c:/python scripts/'

Have you been moving your files or saving them in different directories?
Otherwise, I don't know what your problem could be.

From alan.gauld at freenet.co.uk  Mon Jul 24 09:47:46 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 24 Jul 2006 08:47:46 +0100
Subject: [Tutor] IDLE Caching
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
Message-ID: <002c01c6aef5$744de3c0$0201a8c0@XPpro>

> I have a problem with IDLE on Windows.
> While I'm executing a python script in IDLE subsequence
> editing and executions on the file sometimes doesn't reflect the 
> changes.

This is a common issue, you are presumably importing your
program rather than using IDLE's save/run feature? If so you
will need to reload the module after changes using the reload()
function.

HTH,

Alan G. 



From bugracakir at gmail.com  Mon Jul 24 10:17:32 2006
From: bugracakir at gmail.com (Bugra Cakir)
Date: Mon, 24 Jul 2006 11:17:32 +0300
Subject: [Tutor] IDLE Caching
In-Reply-To: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
Message-ID: <5a00f6240607240117y55149c11of749a8e93bbd4049@mail.gmail.com>

class Tree:

    def Tree(self):
        self.rootNode = None
    def Tree(self, rootNode):
        self.rootNode = rootNode
    def getRootNode(self):
        return self.rootNode
    def setRootNode(self, rootNode):
        self.rootNode = rootNode

class Node:

    def Node(self):
        self.content = ''
        self.isleaf = False
        self.childnode = None
        self.label = ''

    def setContent(self, content=''):
        self.content = content
    def getContent(self):
        return self.content
    def setLeaf(self, leaf):
        self.isleaf = leaf
    def isLeaf(self):
        return self.isleaf
    def setChild(self, childnode):
        self.childnode = childnode
    def getChild(self):
        return self.childnode
    def setLabel(self, label=''):
        self.label = label
    def getLabel(self):
        return self.label

t = Tree()
n = Node()


look at this code. Edit this code with IDLE. For example change one of the
'self' statement
in the code. For instance change self => slf then save the file and press
F5(Run Module)
It doesn't complain about the code !!! this is my problem.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/8881f44a/attachment.htm 

From rabidpoobear at gmail.com  Mon Jul 24 11:38:39 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 24 Jul 2006 04:38:39 -0500
Subject: [Tutor] IDLE Caching
In-Reply-To: <5a00f6240607240117y55149c11of749a8e93bbd4049@mail.gmail.com>
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
	<5a00f6240607240117y55149c11of749a8e93bbd4049@mail.gmail.com>
Message-ID: <44C4951F.8060007@gmail.com>

[snip code]
> look at this code. Edit this code with IDLE. For example change one of 
> the 'self' statement
> in the code. For instance change self => slf then save the file and 
> press F5(Run Module)
> It doesn't complain about the code !!! this is my problem.
>
I think maybe you're just confused about what 'self' is.
'self' is not a reserved keyword that's used for the name of class 
instances.
for example:
#-----start code-------

class Foo(object):
    def __init__(abracadabra):
       print 'BAR!'
       print abracadabra
       abracadabra.random_variable = 42

#make an instance of Foo and call its __init__
x = Foo()
#print the value of random_variable
print x.random_variable

#----end code-----
#---start output----

BAR!
<__main__.Foo object at 0x00F0C930>
42

#---end output----

does this clear anything up for you?
There's no reason to name your first arguments of
methods of class instances 'self' other than
readability and tradition.  To the compiler
it makes no difference.

Do you still think it's a problem with IDLE?

From bugracakir at gmail.com  Mon Jul 24 14:12:23 2006
From: bugracakir at gmail.com (Bugra Cakir)
Date: Mon, 24 Jul 2006 15:12:23 +0300
Subject: [Tutor] IDLE Caching
In-Reply-To: <44C4951F.8060007@gmail.com>
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
	<5a00f6240607240117y55149c11of749a8e93bbd4049@mail.gmail.com>
	<44C4951F.8060007@gmail.com>
Message-ID: <5a00f6240607240512x2d8dfc77qd4b222d3efb0029b@mail.gmail.com>

Really, I have realized the difference Luke said. However sometimes IDLE
runs the
old version, this is the thing I cant realized.

On 7/24/06, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
> [snip code]
> > look at this code. Edit this code with IDLE. For example change one of
> > the 'self' statement
> > in the code. For instance change self => slf then save the file and
> > press F5(Run Module)
> > It doesn't complain about the code !!! this is my problem.
> >
> I think maybe you're just confused about what 'self' is.
> 'self' is not a reserved keyword that's used for the name of class
> instances.
> for example:
> #-----start code-------
>
> class Foo(object):
>     def __init__(abracadabra):
>        print 'BAR!'
>        print abracadabra
>        abracadabra.random_variable = 42
>
> #make an instance of Foo and call its __init__
> x = Foo()
> #print the value of random_variable
> print x.random_variable
>
> #----end code-----
> #---start output----
>
> BAR!
> <__main__.Foo object at 0x00F0C930>
> 42
>
> #---end output----
>
> does this clear anything up for you?
> There's no reason to name your first arguments of
> methods of class instances 'self' other than
> readability and tradition.  To the compiler
> it makes no difference.
>
> Do you still think it's a problem with IDLE?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/30742cf9/attachment.html 

From govilakanksha at yahoo.com  Mon Jul 24 15:04:29 2006
From: govilakanksha at yahoo.com (Akanksha Govil)
Date: Mon, 24 Jul 2006 06:04:29 -0700 (PDT)
Subject: [Tutor] AssertionError issue
Message-ID: <20060724130429.60215.qmail@web36501.mail.mud.yahoo.com>

Hi,

I have a class in python which creates an ssh connection to a remote machine.

In a function of the class, I have put the code in try/except block.

try:
     ----------
     ----------
except AssertionError:
     print "Error Condition"

In this code, when error occurs, it raises the AssertionError but the destuctor isnt called itself.
As a result the ssh conenctions are not closed.

Whenever such errors occurs should I call a function closing the ssh connection?

What is the general way a python script exits on encountering an error?

Thanks
Akanksha

 		
---------------------------------
Do you Yahoo!?
 Get on board. You're invited to try the new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/78e7c8fe/attachment.htm 

From dyoo at hkn.eecs.berkeley.edu  Mon Jul 24 16:42:35 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 24 Jul 2006 07:42:35 -0700 (PDT)
Subject: [Tutor] Joe's learning Tk
In-Reply-To: <AIECKKGNOCPIFINDPNAKCECJCDAA.jgcox39@highstream.net>
References: <AIECKKGNOCPIFINDPNAKCECJCDAA.jgcox39@highstream.net>
Message-ID: <Pine.LNX.4.64.0607240724490.29737@hkn.eecs.berkeley.edu>



> Thanks for the great email.I am beginning to see the light on event 
> binding, callbacks and functions. I have attached my program to show my 
> efforts so far. I think I need a some help in application.

Hi Joe,

I haven't seen your message about this on Tutor yet; have you reposted 
your question there?  I'm still a bit busy and haven't had a chance to 
look at this thoroughly; the others on Python-tutor should take a look at 
this.

If I understand your program, it appears to be a mineral or material 
hardness reference program?  It may be nice to organize the data to make 
it easier to extend.  Concretely, it looks like the program is dealing 
with hierarchical data:

     Materials
          Aluminum
               Wrought
               Die Cast
               Sand Cast

          Steel
               Low Carbon
               Medium/High Carbon
               Alloy
          ...

and so keeping this data in a hierarchical data structure seems like a 
useful thing.  Even something simple like:

     { 'Aluminum' : ['Wrought', ...],
       'Steel',   : ['Low Carbon', ...] }

could be a first step in distilling out the interesting data from your 
program into a single place.  At the moment, that knowledge seems spread 
out in the individual GUI elements, and it seems difficult to add more 
information without modifying several parts of the code.



> I seem to be having problems applying things I read. May be I am 
> spending too much time just looking for similar finished programs on the 
> web were I can alter a few things to get results.

It'll take both practice and feedback from others to get more comfortable 
with program design.  Feel free to post your code on the mailing list to 
get feedback.

Good luck!

From alan.gauld at freenet.co.uk  Mon Jul 24 20:04:17 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 24 Jul 2006 19:04:17 +0100
Subject: [Tutor] IDLE Caching
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
	<5a00f6240607240117y55149c11of749a8e93bbd4049@mail.gmail.com>
Message-ID: <002f01c6af4b$94d123e0$0201a8c0@XPpro>


> class Tree:
>
>    def Tree(self):
>        self.rootNode = None
>    def Tree(self, rootNode):
>        self.rootNode = rootNode

This second definition overrides the first - you cannot do
function overloading based on parameters in Python.

>
> t = Tree()
> n = Node()

These just create instances they don;t excercise any of the
methods - especially since you havenot defined any
constructors. (ie __init__() methods)

> look at this code. Edit this code with IDLE. For example change one 
> of the
> 'self' statement
> in the code. For instance change self => slf then save the file and 
> press
> F5(Run Module)
> It doesn't complain about the code !!! this is my problem.

You aren't executing the faulty code so it won't see the mistake.
You should write a tst program to execute all of the methods in
your classes, then call that function to check the code after each
change.

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From bugracakir at gmail.com  Mon Jul 24 20:42:19 2006
From: bugracakir at gmail.com (Bugra Cakir)
Date: Mon, 24 Jul 2006 21:42:19 +0300
Subject: [Tutor] IDLE Caching
In-Reply-To: <002f01c6af4b$94d123e0$0201a8c0@XPpro>
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
	<5a00f6240607240117y55149c11of749a8e93bbd4049@mail.gmail.com>
	<002f01c6af4b$94d123e0$0201a8c0@XPpro>
Message-ID: <5a00f6240607241142l6ac94000v60aed41b9231749c@mail.gmail.com>

So from the answers, i want to imagine how python exercise the code
when you push the button execute. My guess before looking at the docs
or other material,

1. check python syntax
2. transform to byte code.
3. execute the byte code.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/e7a08a4c/attachment.htm 

From cappy2112 at gmail.com  Mon Jul 24 23:05:38 2006
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Mon, 24 Jul 2006 14:05:38 -0700
Subject: [Tutor] simple Model-View-Controller example for QT/PyQT
Message-ID: <8249c4ac0607241405y3fd1a64en12ece9633095d91c@mail.gmail.com>

Does anyone here have a  example/demo using the MVC pattern, in a simple
QT/pyQT program?

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/01478e10/attachment.htm 

From falcon3166 at hotmail.com  Tue Jul 25 00:56:51 2006
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Mon, 24 Jul 2006 16:56:51 -0600
Subject: [Tutor] Is there a method like this already?
Message-ID: <BAY106-DAV221203E1A2FA2EDC2A9D05C4650@phx.gbl>

Is there a method in Python like this already:

[code]
#This program calculates how many days it has been from one day to the other.

def first_date():
    1y = int(raw_input("Enter the year of the first date: "))
    1m = int(raw_input("Enter the month of the first date: "))
    1d = int(raw_input("Enter the day of the first date: "))

def second_date():
    2y = int(raw_input("Enter the year of the second date: "))
    2m = int(raw_input("Enter the month of the second date: "))
    2d = int(raw_input("Enter the day of the second date: "))

def calculate_days(year, month, day):
    
[/code]

Just being curious,
Nathan Pinno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/e3a18bde/attachment.html 

From john at fouhy.net  Tue Jul 25 01:20:32 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 25 Jul 2006 11:20:32 +1200
Subject: [Tutor] Is there a method like this already?
In-Reply-To: <BAY106-DAV221203E1A2FA2EDC2A9D05C4650@phx.gbl>
References: <BAY106-DAV221203E1A2FA2EDC2A9D05C4650@phx.gbl>
Message-ID: <5e58f2e40607241620t70d24499s2ca5bd861b13ffd4@mail.gmail.com>

On 25/07/06, Nathan Pinno <falcon3166 at hotmail.com> wrote:
>
> Is there a method in Python like this already:
>
> [code]
> #This program calculates how many days it has been from one day to the
> other.

Have a look at the datetime module: if date1 and date2 are both
datetime.date instances, then (date1-date2) is a datetime.timedelta,
and (date1-date2).days is the number of days in the timedelta.

Reading the documentation helps!

-- 
John.

From hugonz-lists at h-lab.net  Tue Jul 25 01:39:33 2006
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Mon, 24 Jul 2006 18:39:33 -0500
Subject: [Tutor] Is there a method like this already?
In-Reply-To: <BAY106-DAV221203E1A2FA2EDC2A9D05C4650@phx.gbl>
References: <BAY106-DAV221203E1A2FA2EDC2A9D05C4650@phx.gbl>
Message-ID: <44C55A35.8060105@h-lab.net>

Nathan Pinno wrote:
> Is there a method in Python like this already:
>  
> [code]
> #This program calculates how many days it has been from one day to the 
> other.

Hi,

Check the datetime module, it will give you distance between dates in 
the units you specify. It is included in the standard distribution.

Hugo

From falcon3166 at hotmail.com  Tue Jul 25 03:24:49 2006
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Mon, 24 Jul 2006 19:24:49 -0600
Subject: [Tutor] What's the invalid syntax?
Message-ID: <BAY106-DAV23A23691F50C98EF75CB3AC45A0@phx.gbl>

What's the invalid syntax?

[code]
from datetime import *

def menu():
    print "(A)dd days to current date."
    print "(F)ind how many days have passed since a date."
    print "(E)xit."

def menu_choice():
    choice = raw_input("Enter the letter of your choice: ")
    return choice

def date1():
    y1 = int(raw_input("Enter the year: "))
    m1 = int(raw_input("Enter the month: "))
    d1 = int(raw_input("Enter the day: "))
    date1 = date(y1, m1, d1)
    return date1

def date2():
    y2 = int(raw_input("Enter the 2nd year: "))
    m2 = int(raw_input("Enter the 2nd month: "))
    d2 = int(raw_input("Enter the 2nd day: "))
    date2 = date(y2, m2, d2)
    return date2

print "Date Calculator"
print "By Nathan Pinno"
print
while 1:
    menu()
    menu_choice()
    if choice == A:
        date1()
        days = int(raw_input("Enter the number of days to add: "))
        date3 = date1 + days
        print date(date3).isoformat(), " is the date ", days, " from today."
    elif choice == F:
        date1()
        date2()
        days = date2 - date1
        print days, " days seperate " date2.isoformat(), " from ", date1.isoformat(), "."
    elif choice = E:
        break()
    else:
        print "That's not an option. Try again, please."
[/code]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/35ad8258/attachment.html 

From falcon3166 at hotmail.com  Tue Jul 25 03:43:11 2006
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Mon, 24 Jul 2006 19:43:11 -0600
Subject: [Tutor] What's the invalid syntax?
Message-ID: <BAY106-DAV2375D28A10B75769533361C45A0@phx.gbl>

Ignore this. I've created too many errors to even begin to solve.
  ----- Original Message ----- 
  From: Nathan Pinno 
  To: Tutor mailing list 
  Sent: Monday, July 24, 2006 7:24 PM
  Subject: What's the invalid syntax?


  What's the invalid syntax?

  [code]
  from datetime import *

  def menu():
      print "(A)dd days to current date."
      print "(F)ind how many days have passed since a date."
      print "(E)xit."

  def menu_choice():
      choice = raw_input("Enter the letter of your choice: ")
      return choice

  def date1():
      y1 = int(raw_input("Enter the year: "))
      m1 = int(raw_input("Enter the month: "))
      d1 = int(raw_input("Enter the day: "))
      date1 = date(y1, m1, d1)
      return date1

  def date2():
      y2 = int(raw_input("Enter the 2nd year: "))
      m2 = int(raw_input("Enter the 2nd month: "))
      d2 = int(raw_input("Enter the 2nd day: "))
      date2 = date(y2, m2, d2)
      return date2

  print "Date Calculator"
  print "By Nathan Pinno"
  print
  while 1:
      menu()
      menu_choice()
      if choice == A:
          date1()
          days = int(raw_input("Enter the number of days to add: "))
          date3 = date1 + days
          print date(date3).isoformat(), " is the date ", days, " from today."
      elif choice == F:
          date1()
          date2()
          days = date2 - date1
          print days, " days seperate " date2.isoformat(), " from ", date1.isoformat(), "."
      elif choice = E:
          break()
      else:
          print "That's not an option. Try again, please."
  [/code]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060724/5c4025d0/attachment.htm 

From john at fouhy.net  Tue Jul 25 03:53:35 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 25 Jul 2006 13:53:35 +1200
Subject: [Tutor] What's the invalid syntax?
In-Reply-To: <BAY106-DAV23A23691F50C98EF75CB3AC45A0@phx.gbl>
References: <BAY106-DAV23A23691F50C98EF75CB3AC45A0@phx.gbl>
Message-ID: <5e58f2e40607241853p50e48e17s79792bf8cd25afd3@mail.gmail.com>

On 25/07/06, Nathan Pinno <falcon3166 at hotmail.com> wrote:
>
> What's the invalid syntax?

I don't know, what did python tell you when you tried to run the code?

-- 
John.

From alan.gauld at freenet.co.uk  Tue Jul 25 05:46:37 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 25 Jul 2006 04:46:37 +0100
Subject: [Tutor] Is there a method like this already?
References: <BAY106-DAV221203E1A2FA2EDC2A9D05C4650@phx.gbl>
Message-ID: <003401c6af9c$ee392800$0201a8c0@XPpro>

> Is there a method in Python like this already:
> #This program calculates how many days it has been from one day to 
> the other.

Look at the datetime module it has methods for getting differences in
daes/times etc.

> def first_date():
>    1y = int(raw_input("Enter the year of the first date: "))
>    1m = int(raw_input("Enter the month of the first date: "))
>    1d = int(raw_input("Enter the day of the first date: "))

Doesn't return anything so the data is lost as soon as
you exit the function. You need to return the data(as a tuple?)
so you can store it in a variable:

      return (1y,1m,1d)

date1 = first_date()

> def second_date():
>     2y = int(raw_input("Enter the year of the second date: "))
etc

And this does exactly the same as first_date so you don't need it.
Rename first_date to get_date(), remove the ones, and just call it 
twice:

def get_date():
    y = int(raw_input("Enter the year: "))
    m = int(raw_input("Enter the month: "))
    d = int(raw_input("Enter the day: "))
    return (y,m,d)

print "For the first date"
date1 = get_date()
print "For the second date"
date2 = get_date()

> def calculate_days(year, month, day):

And this would dake the two dates as arguments and return
a number of dats:

def calculate_days(firstDate, secondDate):
      # use datetime module here....

HTH

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at freenet.co.uk  Tue Jul 25 05:51:52 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 25 Jul 2006 04:51:52 +0100
Subject: [Tutor] IDLE Caching
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com><5a00f6240607240117y55149c11of749a8e93bbd4049@mail.gmail.com><002f01c6af4b$94d123e0$0201a8c0@XPpro>
	<5a00f6240607241142l6ac94000v60aed41b9231749c@mail.gmail.com>
Message-ID: <004c01c6af9d$aa7fdb30$0201a8c0@XPpro>

> So from the answers, i want to imagine how python exercise the code
> when you push the button execute. My guess before looking at the 
> docs
> or other material,
>
> 1. check python syntax
> 2. transform to byte code.
> 3. execute the byte code.

What you have is correct for a main program.
If its a module being imported there is a slight difference:

0) check if module already loaded, if yes stop
1) check if a pre-compiled version already exists
2) check if the source file is newer
3) if newer compile code to byte code and save pyc file
4) import byte code

This is described in more detail in the documentation.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at freenet.co.uk  Tue Jul 25 05:56:14 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 25 Jul 2006 04:56:14 +0100
Subject: [Tutor] AssertionError issue
References: <20060724130429.60215.qmail@web36501.mail.mud.yahoo.com>
Message-ID: <005801c6af9e$46291970$0201a8c0@XPpro>

> In a function of the class, I have put the code in try/except block.
>
> try:
>     ----------
>     ----------
> except AssertionError:
>     print "Error Condition"
>
> In this code, when error occurs, it raises the AssertionError
> but the destuctor isnt called itself.

The destructor will only get called if the object is destroyed.
The object will be destroyed once all references to it are broken
either by it moving out of scope (eg exiting a function/method)
or by you del()'ing it sufficient times to reduce its reference count
to zero..

> As a result the ssh conenctions are not closed.
> What is the general way a python script exits on encountering an 
> error?

raise SystemError or call sys,.exit() will exit completely.
But a try/finally (as opposed to a try/except) will also be useful to
guarantee execution of a block of code that can tidy up things
like open sockets/files etc.

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From cspears2002 at yahoo.com  Tue Jul 25 06:54:09 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Mon, 24 Jul 2006 21:54:09 -0700 (PDT)
Subject: [Tutor] confused by linked queue
Message-ID: <20060725045409.98334.qmail@web51613.mail.yahoo.com>

I am working out of How To Think Like A Computer
Scientist.  I am on the chapter that covers linked
queues.  Here is some code that creates a linked queue
class:

class Queue:
	def __init__(self):
		self.length = 0
		self.head = None

	def isEmpty(self):
		return (self.length == 0)

	def insert(self, cargo):
		node = Node(cargo)
		node.next = None
    		if self.head == None:
			# if list is empty the new node goes first
			self.head = node
		else:
			# find the last node in the list
			last = self.head
			while last.next: 
				last = last.next
				# append the new node
				last.next = node
		self.length = self.length + 1

	def remove(self):
		cargo = self.head.cargo
		self.head = self.head.next
		self.length = self.length - 1
		return cargo

The node is defined by:

class Node:
	def __init__(self, cargo=None, next=None):
		self.cargo = cargo
		self.next = next
		
	def __str__(self):
		return str(self.cargo)

I am confused by the insert class.  I am not quite
sure how it works.  More to the point, I am not sure
if it works:


		>>> from linked_queue import *
>>> queue = Queue()
>>> queue.isEmpty()
True
>>> queue.insert("cargo")
>>> print queue.head
cargo
>>> print queue.length
1
>>> queue.insert("more_cargo")
>>> print queue.length
2
>>> print queue.head
cargo

Where is my second node?  How can I access it?
		 
	
		
	


From john at fouhy.net  Tue Jul 25 07:12:54 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 25 Jul 2006 17:12:54 +1200
Subject: [Tutor] confused by linked queue
In-Reply-To: <20060725045409.98334.qmail@web51613.mail.yahoo.com>
References: <20060725045409.98334.qmail@web51613.mail.yahoo.com>
Message-ID: <5e58f2e40607242212o1f62f158m9f05a39756c6737c@mail.gmail.com>

On 25/07/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
>                >>> from linked_queue import *
> >>> queue = Queue()
> >>> queue.isEmpty()
> True
> >>> queue.insert("cargo")
> >>> print queue.head
> cargo
> >>> print queue.length
> 1
> >>> queue.insert("more_cargo")
> >>> print queue.length
> 2
> >>> print queue.head
> cargo
>
> Where is my second node?  How can I access it?

Try 'print queue.head.next' :-)

A queue is, well, a queue.  Visualise a queue of people.  Initially,
the queue is empty: there's no one standing there.  Then someone comes
and stands at the head of the queue; now the queue has one person in
it (queue.length is 1).

Then, another person comes along.  That person starts at the head of
the queue, and walks down the queue until they find the end.  Then
they join the end.

This is what is happening in this bit of code --- here, you walk down
the queue until you get to the end (ie: a node with no "next" node):

                       # find the last node in the list
                       last = self.head
                       while last.next:
                               last = last.next

And here, you add the new node on to the end:

                       # append the new node
                       last.next = node

It appears there is a bug in the code; these two lines should NOT be
part of the while loop (ie: the indendation is incorrect).

The result looks something like this:

(best viewed with a fixed-width font)

head --> /--------\    /--------\
         | next --+--> | next --+--> None
         |        |    |        |
         | cargo-\|    | cargo-\|
         \-------+/    \-------+/
                 |             |
                \|/           \|/
              "cargo"    "more cargo"

Hope this helps; if not, ask more questions :-)

-- 
John.

From cspears2002 at yahoo.com  Tue Jul 25 07:55:17 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Mon, 24 Jul 2006 22:55:17 -0700 (PDT)
Subject: [Tutor] confused by linked queue
Message-ID: <20060725055517.87566.qmail@web51610.mail.yahoo.com>

After reading John's reply, I think I get it now:

>>> from linked_queue import *
>>> queue = Queue()
>>> queue.isEmpty()
True
>>> queue.insert("cargo")
>>> queue.length
1
>>> queue.insert("more cargo")
>>> queue.length
2
>>> print queue.head
cargo
>>> print queue.head.next
more cargo
>>> queue.insert("more and better cargo")
>>> print queue.head.next
more cargo
>>> print queue.head.next.next
more and better cargo
>>> queue.insert("snakes")
>>> print queue.head
cargo
>>> last = queue.head
>>> last.next
<linked_queue.Node instance at 0xb7d5fdcc>
>>> print last.next
more cargo
>>> print last.next.next
more and better cargo
>>> print last.next.next.next
snakes

One of my problems in conecptualizing this is that I
thought a linked queue was just a linked list.  Is a
linked queue a linked list?  There seems to be a
subtle difference...

From bugracakir at gmail.com  Tue Jul 25 08:44:54 2006
From: bugracakir at gmail.com (Bugra Cakir)
Date: Tue, 25 Jul 2006 09:44:54 +0300
Subject: [Tutor] IDLE Caching
In-Reply-To: <004c01c6af9d$aa7fdb30$0201a8c0@XPpro>
References: <5a00f6240607232346s45a35495x9ac8a516b3c33c8@mail.gmail.com>
	<5a00f6240607240117y55149c11of749a8e93bbd4049@mail.gmail.com>
	<002f01c6af4b$94d123e0$0201a8c0@XPpro>
	<5a00f6240607241142l6ac94000v60aed41b9231749c@mail.gmail.com>
	<004c01c6af9d$aa7fdb30$0201a8c0@XPpro>
Message-ID: <5a00f6240607242344q5c512983kb4b2c19ef6a31ea0@mail.gmail.com>

let me dig into documentation before thinking in the blind :) thanks a lot
Alan !


On 7/25/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
> > So from the answers, i want to imagine how python exercise the code
> > when you push the button execute. My guess before looking at the
> > docs
> > or other material,
> >
> > 1. check python syntax
> > 2. transform to byte code.
> > 3. execute the byte code.
>
> What you have is correct for a main program.
> If its a module being imported there is a slight difference:
>
> 0) check if module already loaded, if yes stop
> 1) check if a pre-compiled version already exists
> 2) check if the source file is newer
> 3) if newer compile code to byte code and save pyc file
> 4) import byte code
>
> This is described in more detail in the documentation.
>
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060725/72b338a3/attachment.htm 

From iit_narasimha at yahoo.co.in  Tue Jul 25 16:42:13 2006
From: iit_narasimha at yahoo.co.in (K.R.L. NARASIMHA)
Date: Tue, 25 Jul 2006 15:42:13 +0100 (BST)
Subject: [Tutor] I am not really convinced using Python...
Message-ID: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>

Hey friends,good day.
  I am not a newbie to programming.I already learnt C language.I enjoyed it a lot.
  But I am not a computer student.So I don't require a hifi language like C.
  I am an electronics student.I would really like to know if the language like Python will be of any help(use) to me.Also I heard that it is an intrepeter language.
  Is it true?If yes I would like to know whether it is fast or not.Also I would like to know the capabilities of Python.
  (If I am really convinced I would use it for my life).. 

 				
---------------------------------
 Find out what India is talking about on Yahoo! Answers India.
SMS memory full? Store all your important SMS in your Yahoo! Mail. Register for SMS BAK UP now! 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060725/0fd87d51/attachment.html 

From lunixinclar at orange.fr  Tue Jul 25 17:14:35 2006
From: lunixinclar at orange.fr (Rob Sinclar)
Date: Tue, 25 Jul 2006 17:14:35 +0200
Subject: [Tutor] I am not really convinced using Python...
In-Reply-To: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>
References: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>
Message-ID: <200607251714.35452.lunixinclar@orange.fr>

On Tuesday 25 July 2006 16:42, K.R.L. NARASIMHA wrote:
> Hey friends,good day.
>   I am not a newbie to programming.I already learnt C language.I enjoyed it
> a lot. But I am not a computer student.So I don't require a hifi language
> like C. I am an electronics student.I would really like to know if the
> language like Python will be of any help(use) to me.Also I heard that it is
> an intrepeter language. Is it true?If yes I would like to know whether it
> is fast or not.Also I would like to know the capabilities of Python. (If I
> am really convinced I would use it for my life)..

Hi,
Yep Python is an interpreted language. In other words every python app needs 
the python interpreter to be able to run.

As for performances, it is slightly above Perl end PHP. Slightly, question of 
microseconds. I've been doing benchmark tests.
In terms of GUI apps, when it comes to widgets there's no difference between 
Python and the C language (our only one real and verifiable religion) . But 
they can't be compared as C produces native code.

As a high-level language -with all this involves- Python simply rules it all.
Particulary for scientists. I guess you're one of them.

Best Regards,
Rob Sinclar

From katsanqat at orange.fr  Tue Jul 25 17:13:00 2006
From: katsanqat at orange.fr (Bertrand-Xavier M.)
Date: Tue, 25 Jul 2006 17:13:00 +0200
Subject: [Tutor] I am not really convinced using Python...
In-Reply-To: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>
References: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>
Message-ID: <200607251713.00399.katsanqat@orange.fr>

On Tuesday 25 July 2006 16:42, K.R.L. NARASIMHA wrote:
> Hey friends,good day.
>   I am not a newbie to programming.I already learnt C language.I enjoyed it
> a lot. But I am not a computer student.So I don't require a hifi language
> like C. I am an electronics student.I would really like to know if the
> language like Python will be of any help(use) to me.Also I heard that it is
> an intrepeter language. Is it true?If yes I would like to know whether it
> is fast or not.Also I would like to know the capabilities of Python. (If I
> am really convinced I would use it for my life)..

Hi,
Yep Python is an interpreted language. In other words every python app needs 
the python interpreter to be able to run.

As for performances, it is slightly above Perl end PHP. Slightly, question of 
microseconds. I've been doing benchmark tests.
In terms of GUI apps, when it comes to widgets there's no difference between 
Python and the C language (our only one real and verifiable religion) . But 
they can't be compared as C produces native code.

As a high-level language -with all this involves- Python simply rules it all.
Particulary for scientists. I guess you're one of them.

Best Regards,
Rob Sinclar

From basavarajsp at servion.com  Tue Jul 25 17:04:39 2006
From: basavarajsp at servion.com (Basavaraj SP.)
Date: Tue, 25 Jul 2006 20:34:39 +0530
Subject: [Tutor] IDE for Python
Message-ID: <81EC6DEE84D24B449EAA785352C5E1AF01D7872E@SGSLEX2K3.sgsl.int>

Dear All,

 

I am new to Python.

 

I want to know which IDE I should use for programming.

 

If so from where can I get it?

 

Thanks in advance.

 

- Raj

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060725/49c6b330/attachment.htm 

From mail at ozzmosis.com  Tue Jul 25 17:18:53 2006
From: mail at ozzmosis.com (andrew clarke)
Date: Wed, 26 Jul 2006 01:18:53 +1000
Subject: [Tutor] IDE for Python
In-Reply-To: <81EC6DEE84D24B449EAA785352C5E1AF01D7872E@SGSLEX2K3.sgsl.int>
References: <81EC6DEE84D24B449EAA785352C5E1AF01D7872E@SGSLEX2K3.sgsl.int>
Message-ID: <20060725151853.GA67965@ozzmosis.com>

On Tue, Jul 25, 2006 at 08:34:39PM +0530, Basavaraj SP. wrote:

> I am new to Python.
> 
> I want to know which IDE I should use for programming.
> 
> If so from where can I get it?

ActivePython is a good start:

http://www.activestate.com/Products/ActivePython/

From mail at ozzmosis.com  Tue Jul 25 17:32:10 2006
From: mail at ozzmosis.com (andrew clarke)
Date: Wed, 26 Jul 2006 01:32:10 +1000
Subject: [Tutor] I am not really convinced using Python...
In-Reply-To: <200607251714.35452.lunixinclar@orange.fr>
References: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>
	<200607251714.35452.lunixinclar@orange.fr>
Message-ID: <20060725153210.GB67965@ozzmosis.com>

On Tue, Jul 25, 2006 at 05:14:35PM +0200, Rob Sinclar wrote:

> Yep Python is an interpreted language. In other words every python app needs 
> the python interpreter to be able to run.

I'm not sure, but I don't think there's anything particular about the
language that says it should be interpreted.

As far as I know, programs built with IronPython don't require Python to
be installed - only the .NET (2.0?) Framework.

http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython

You can also build .exe files for Windows using py2exe.

http://www.py2exe.org/

From kent37 at tds.net  Tue Jul 25 17:52:27 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 25 Jul 2006 11:52:27 -0400
Subject: [Tutor] I am not really convinced using Python...
In-Reply-To: <20060725153210.GB67965@ozzmosis.com>
References: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>	<200607251714.35452.lunixinclar@orange.fr>
	<20060725153210.GB67965@ozzmosis.com>
Message-ID: <44C63E3B.9050704@tds.net>

andrew clarke wrote:
> On Tue, Jul 25, 2006 at 05:14:35PM +0200, Rob Sinclar wrote:
>
>   
>> Yep Python is an interpreted language. In other words every python app needs 
>> the python interpreter to be able to run.
>>     
>
> I'm not sure, but I don't think there's anything particular about the
> language that says it should be interpreted.
>   
Jython compiles Python classes to Java byte code, so I guess it is only 
interpreted because Java is. But there is still overhead to using Jython 
because the generated code implements its own types system, etc, using 
the Jython run-time. I wouldn't be surprised if IronPython does 
something similar.
> As far as I know, programs built with IronPython don't require Python to
> be installed - only the .NET (2.0?) Framework.
>   
No IronPython runtime libraries?
> http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython
>
> You can also build .exe files for Windows using py2exe.
>
> http://www.py2exe.org/
>   
py2exe just bundles all the needed files in a nice double-clickable 
package. It still runs the Python interpreter under the hood.

There are major technical difficulties to compiling Python code to 
something that doesn't need a run-time to make it work. ShedSkin and 
PyPy are two projects that compile a restricted subset of Python to 
native code.

Kent


From kent37 at tds.net  Tue Jul 25 18:00:13 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 25 Jul 2006 12:00:13 -0400
Subject: [Tutor] I am not really convinced using Python...
In-Reply-To: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>
References: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>
Message-ID: <44C6400D.3060102@tds.net>

K.R.L. NARASIMHA wrote:
> Hey friends,good day.
> I am *_not a newbie_* to programming.I already learnt C language.I 
> enjoyed it a lot.
> But I am not a computer student.So I don't require a hifi language like C.
> I am an electronics student.I would really like to know if the 
> language like Python will be of any help(use) to me.Also I heard that 
> it is an intrepeter language.
> Is it true?If yes I would like to know whether it is fast or not.Also 
> I would like to know the capabilities of Python.
> *(If I am really convinced I would use it for my life)..*

Take a look at the material on the python web site www.python.org, 
especially the ABOUT page. Take  a few hours to work through a tutorial; 
if you know C, the tutorial that comes with Python will probably get you 
started.

Python is not as fast as C to execute, but it is pretty fast and for 
many uses it is fast enough. It is much, much faster to write working 
Python code than C. There are quite a few techniques to make Python 
faster, also, including just-in-time compilation (psyco), compiling of 
an annotated subset (pyrex), or rewriting to a C extension.

For many uses, you can just write your program in Python and it will be 
fast enough. If it isn't, you can profile to find the hotspots and 
optimize them

If you value *your* time, give Python a try.

Kent


From Mike.Hansen at atmel.com  Tue Jul 25 18:51:54 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Tue, 25 Jul 2006 10:51:54 -0600
Subject: [Tutor] IDE for Python
Message-ID: <57B026980605A64F9B23484C5659E32E2549FE@poccso.US.ad.atmel.com>

 


________________________________

	From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]
On Behalf Of Basavaraj SP.
	Sent: Tuesday, July 25, 2006 9:05 AM
	To: tutor at python.org
	Subject: [Tutor] IDE for Python
	
	

	Dear All,

	I am new to Python.

	I want to know which IDE I should use for programming.

	If so from where can I get it?

	Thanks in advance.	 

	- Raj

I personally use VIM. The closest thing to an IDE I've used is Komodo.
You might check out these links.

http://pyfaq.infogami.com/tutor-whats-the-best-editor-ide-for-python
	
Mike
http://users.adelphia.net/~mahansen/programming/editorides.html
 


From lunixinclar at orange.fr  Tue Jul 25 23:17:40 2006
From: lunixinclar at orange.fr (Rob Sinclar)
Date: Tue, 25 Jul 2006 23:17:40 +0200
Subject: [Tutor] IDE for Python
In-Reply-To: <57B026980605A64F9B23484C5659E32E2549FE@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E2549FE@poccso.US.ad.atmel.com>
Message-ID: <200607252317.40709.lunixinclar@orange.fr>

On Tuesday 25 July 2006 18:51, Mike Hansen wrote:
>	Dear All,
>
> 	I am new to Python.
>
> 	I want to know which IDE I should use for programming.
>
> 	If so from where can I get it?
>
> 	Thanks in advance.
>
> 	- Raj
>
> I personally use VIM. The closest thing to an IDE I've used is Komodo.
> You might check out these links.
>
> http://pyfaq.infogami.com/tutor-whats-the-best-editor-ide-for-python
>
> Mike
> http://users.adelphia.net/~mahansen/programming/editorides.html
>

Scite is interesting for programming.

From treed at ultraviolet.org  Tue Jul 25 23:44:05 2006
From: treed at ultraviolet.org (Tracy R Reed)
Date: Tue, 25 Jul 2006 14:44:05 -0700
Subject: [Tutor] email anonymizing
In-Reply-To: <44B6BFF3.1040608@alum.rpi.edu>
References: <20060713025218.80549.qmail@web55915.mail.re3.yahoo.com>	<44B5C0C2.3010206@gmail.com>
	<44B6BFF3.1040608@alum.rpi.edu>
Message-ID: <44C690A5.80706@ultraviolet.org>

Bob Gailer wrote:
> To amplify Luke's and others' questions - we need a lot more 
> information, and at this point in the process it seems painfully slow to 
> extract it from you. If you want our help please tell us:

In situations like this I like to refer people to:

"How To Ask Questions The Smart Way" by esr:
http://www.catb.org/esr/faqs/smart-questions.html

If they follow this advice they can get better answers to their 
questions more quickly.

-- 
Tracy R Reed                  http://ultraviolet.org
A: Because we read from top to bottom, left to right
Q: Why should I start my reply below the quoted text

From treed at ultraviolet.org  Wed Jul 26 00:11:10 2006
From: treed at ultraviolet.org (Tracy R Reed)
Date: Tue, 25 Jul 2006 15:11:10 -0700
Subject: [Tutor] IDE for Python
In-Reply-To: <81EC6DEE84D24B449EAA785352C5E1AF01D7872E@SGSLEX2K3.sgsl.int>
References: <81EC6DEE84D24B449EAA785352C5E1AF01D7872E@SGSLEX2K3.sgsl.int>
Message-ID: <44C696FE.9040009@ultraviolet.org>

Basavaraj SP. wrote:

> I want to know which IDE I should use for programming.

Emacs has been the gold standard of IDE's for years.

-- 
Tracy R Reed                  http://ultraviolet.org
A: Because we read from top to bottom, left to right
Q: Why should I start my reply below the quoted text

From dyoo at hkn.eecs.berkeley.edu  Wed Jul 26 00:43:34 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 25 Jul 2006 15:43:34 -0700 (PDT)
Subject: [Tutor] confused by linked queue
In-Reply-To: <20060725055517.87566.qmail@web51610.mail.yahoo.com>
References: <20060725055517.87566.qmail@web51610.mail.yahoo.com>
Message-ID: <Pine.LNX.4.64.0607251510020.22412@hkn.eecs.berkeley.edu>

> One of my problems in conecptualizing this is that I thought a linked 
> queue was just a linked list.  Is a linked queue a linked list?  There 
> seems to be a subtle difference...

Hi Chris,

I think you mean to ask:

     Is a "queue" a linked list?


Here's another particular possible queue class that does something 
similar, but with Python's regular lists rather than a linked list:

######################################
class ArrayQueue:
     def __init__(self):
         self.elements = []

     def isEmpty(self):
         return len(self.elements) == 0

     def insert(self, elt):
         self.elements.append(elt)

     def remove(self):
         return self.elements.pop(0)
######################################

This works on a different principle than the linked list queue, but it 
does the same stuff.  The main idea is that a "queue" can be anything, as 
long as it supports three operations:

     * isEmpty
     * insert
     * remove

That is, a queue is an abstract concept, and the LinkedQueue and 
ArrayQueue classes are particular, concrete implementations of that 
abstract concept.

A mechanic is someone who's good with their hands.  MacGyver is a 
particular, concrete mechanic who knows how to blow things up with 
toothpaste.  MacGyver is an implementation of a mechanic.

A "car vehicle" is an abstract concept; a Camry is a particular, concrete 
car that anyone can look at and agree is a car.  We can also look at a 
Prius and also agree that this is a car, even though the engine underneath 
the hood might look weird.


I hope this is making some sort of sense.  *grin*

From Barry.Carroll at psc.com  Wed Jul 26 01:02:08 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Tue, 25 Jul 2006 16:02:08 -0700
Subject: [Tutor] IDE for Python
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36E7@eugsrv400.psc.pscnet.com>

Raj:

I prefer ViM as well.  I have tried several IDEs: Idle, SlickEdit,
Eclipse/PyDev, Stani's Python Editor (SPE).  None of them manages
multiple editing windows as well as ViM, and that is the feature I use
most.  

In a typical editing session I will have six or more editing windows
open, accessing perhaps three different files.  ViM handles all this
effortlessly.  It allows me to have many windows open at once, each one
in the position and of the size that best matches my need at the moment.
Resizing, opening and closing windows, displaying a new file in an
existing window, chancing focus from one window to another.  ViM handles
these tasks far better than any of the IDEs I have tried.   

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

> -----Original Message-----
> Date: Tue, 25 Jul 2006 10:51:54 -0600
> From: "Mike Hansen" <Mike.Hansen at atmel.com>
> Subject: Re: [Tutor] IDE for Python
> To: <tutor at python.org>
> Message-ID:
> 	<57B026980605A64F9B23484C5659E32E2549FE at poccso.US.ad.atmel.com>
> Content-Type: text/plain;	charset="us-ascii"
> 
> 
> 
> 
> ________________________________
> 
> 	From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]
> On Behalf Of Basavaraj SP.
> 	Sent: Tuesday, July 25, 2006 9:05 AM
> 	To: tutor at python.org
> 	Subject: [Tutor] IDE for Python
> 
> 
> 
> 	Dear All,
> 
> 	I am new to Python.
> 
> 	I want to know which IDE I should use for programming.
> 
> 	If so from where can I get it?
> 
> 	Thanks in advance.
> 
> 	- Raj
> 
> I personally use VIM. The closest thing to an IDE I've used is Komodo.
> You might check out these links.
> 
> http://pyfaq.infogami.com/tutor-whats-the-best-editor-ide-for-python
> 
> Mike
> http://users.adelphia.net/~mahansen/programming/editorides.html


From alan.gauld at freenet.co.uk  Wed Jul 26 01:25:27 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 26 Jul 2006 00:25:27 +0100
Subject: [Tutor] I am not really convinced using Python...
References: <20060725144213.11878.qmail@web8415.mail.in.yahoo.com>
Message-ID: <003701c6b041$9ccd7070$0201a8c0@XPpro>

>  I am not a newbie to programming.I already learnt C language.I 
> enjoyed it a lot.
>  But I am not a computer student.So I don't require a hifi language 
> like C.

C is a tterrible language for computer students, its usually used by
engineering types who need to interact with the computer  at a low
level. C is full of what computer scientists view as very bad 
practice!

>  I am an electronics student.I would really like to know if the
> language like Python will be of any help(use) to me

As an electronics grad who workds in telecoms designing large scale
software systems I'll try to answer! :-)

It is extremely useful for modelling problems - if you already use
tools like mathematica to build math models of waveshapes,
filter characteristics, stochastic noise models, data traffic
analyses,  etc etc Python can do all that too.

For general purpose programming Python can build all your
test harnesses, integrate your code libraries, manage your project 
files etc.

For network access there are very good socket and serial port 
libraries
and a bunch of internet protocols supported, it can also use a pile
of more obscure libraries contributed by others - I've seen HPIB, 
Centronics
and S-COM interface libraries and several others have been discussed 
on this list.

Where its not so great is in building bespoke interfaces to new
hardware - there are no direct input/output peek/poke type functions,
no direct memoruy access etc. The usual silution is build a thi access
library in C then wrap that as a Python module with the higher level
interface functions written in python and calling the hardware 
routines in C.

> .Also I heard that it is an intrepeter language.
>  Is it true?

Yes in the same sense that Java, C#, Perl and Smaltalk are 
interpreted.
The code is compiled into byte code and then run in a virtual machine
interpreter. There are even translators from python to Java byte code
so you can run it on any JVM and integrate with all the Java libraries
out there.

> If yes I would like to know whether it is fast or not.

Try it and see. The answer will depend on what you are doing,
what your computing architecture is and how well you write the code.
If its not fast enough you can usually idfentify the bottleneck and
rewrite that part in C. Python was explicitly designed with that style
of build it, tune it, rewqrite the bottlenecks type of development 
cycle
in mind. Only Tcl is better suited to that kind of tweaking IMHO.

> Also I would like to know the capabilities of Python.

It can do most things, and usually more easily than in other
languages but have a look at the python web page, there are
lots of advocacy stories and case studies there.

>  (If I am really convinced I would use it for my life)..

No language is perfect and you will likely find it easier to have
several languages to use as appropriate. But Python can do the lions 
share.

Personally I now use Python 70%, Delphi 15%, C/C++/ObjectiveC 10%
and a variety of others(Tcl, Awk, Java, Smalltalk, Lisp etc) for the 
final 5%

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From tim at johnsons-web.com  Wed Jul 26 01:08:02 2006
From: tim at johnsons-web.com (Tim Johnson)
Date: Tue, 25 Jul 2006 15:08:02 -0800
Subject: [Tutor] IDE for Python
In-Reply-To: <57B026980605A64F9B23484C5659E32E2549FE@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E2549FE@poccso.US.ad.atmel.com>
Message-ID: <20060725230802.GC16709@johnsons-web.com>

* Mike Hansen <Mike.Hansen at atmel.com> [060725 10:26]:
> 
> I personally use VIM. The closest thing to an IDE I've used is Komodo.
> You might check out these links.
 
  I used to use vim extensively with python, now have moved to emacs.

> http://pyfaq.infogami.com/tutor-whats-the-best-editor-ide-for-python
 	
  You can actually compile the python binary *into* the vim binary, that
  contributes to some of the nice python plugins for vim. And I imagine
  that would potentially be unlimited potential functionality.

  Emacs on the other hand is customizable via elisp, but one of these
  days I'm going to investigate pymacs, which is a system for
  customizing emacs with python. 

  I prefer any of these schemes to to the traditional "IDE" 'cuz I
  like the idea of making one's programming environment do exactly
  what I want it to do in my own way.

  The trade-off is time....
  tj

  
> Mike
> http://users.adelphia.net/~mahansen/programming/editorides.html
>  
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com

From alan.gauld at freenet.co.uk  Wed Jul 26 01:27:26 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 26 Jul 2006 00:27:26 +0100
Subject: [Tutor] IDE for Python
References: <81EC6DEE84D24B449EAA785352C5E1AF01D7872E@SGSLEX2K3.sgsl.int>
Message-ID: <004301c6b041$e3c773e0$0201a8c0@XPpro>

> I want to know which IDE I should use for programming.

 IDLE comes with standard Python and is OK for starters.

Pythonwin comes with ActiveState python (as well as IDLE) 
and is better for Windoze users.

Personally I use cygwin, bash, and vim.
Others use emacs...

And there are lots more including commercial ones. But I'd 
start simple with Pythonwin or IDLE...

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From hokkakada at khmeros.info  Wed Jul 26 06:57:53 2006
From: hokkakada at khmeros.info (kakada)
Date: Wed, 26 Jul 2006 11:57:53 +0700
Subject: [Tutor] treeWidget in QT Designer
Message-ID: <44C6F651.4060909@khmeros.info>

Hi there,

I am trying to build GUI python using Qt4.
I am working with treeWidget to view my data.

With the first load, I want the selected item go to the first row by doing:

curItem = self.ui.treeWidget.itemAt(1,1)
self.ui.treeWidget.setCurrentItem(curItem)
It's ok.

Then I want it jump to 4th row by doing

curItem = self.ui.treeWidget.itemAt(4,1)
self.ui.treeWidget.setCurrentItem(curItem)
This time is not ok for me, It goes somewhere else.

 I have read the document about Qtreewidget, but I found it is difficult
to understand.
Could you please help to explain in an easy way?

Thanks a lot,

da




From shaleh at speakeasy.net  Wed Jul 26 08:03:58 2006
From: shaleh at speakeasy.net (Sean Perry)
Date: Tue, 25 Jul 2006 23:03:58 -0700
Subject: [Tutor] understanding __import__()
Message-ID: <44C705CE.3050106@speakeasy.net>

Ok, this may be slightly above tutor's level, but hey, never hurts to 
ask (-:

I am playing with __import__().  Here is my code:
[code]
import os.path

app_path = '/tmp/my/settings'
app_path2 = 'my/settings'

if os.path.exists(app_path + '.py'):
     print "Found", app_path

try:
     f = __import__(app_path, globals(), locals(), [])
     print f.__name__, f.__file__
except Exception, e:
     print e

if os.path.exists(app_path2 + '.py'):
     print "Found", app_path2

try:
     f = __import__(app_path2, globals(), locals(), [])
     print f.__name__, f.__file__
except Exception, e:
     print e
[/code]

The result is the first import fails and the second one works. Even 
though they are the same file.

$ pwd
/tmp
$ ls
importer.py my/
$ ls my
settings.py
$ ./importer.py
Found /tmp/my/settings
No module named /tmp/my/settings
Found my/settings
my/settings /tmp/my/settings.py

What gives??

From python-tutor at v.igoro.us  Wed Jul 26 08:06:25 2006
From: python-tutor at v.igoro.us (python-tutor at v.igoro.us)
Date: Wed, 26 Jul 2006 01:06:25 -0500
Subject: [Tutor] understanding __import__()
In-Reply-To: <44C705CE.3050106@speakeasy.net>
References: <44C705CE.3050106@speakeasy.net>
Message-ID: <44C70661.6060602@v.igoro.us>

Sean Perry wrote:
> Ok, this may be slightly above tutor's level, but hey, never hurts to 
> ask (-:

__import__ is dark magic; generally those who venture into that realm
would do well to read the C source for Python..

I'm guessing that '.' is not in your sys.path, so Python isn't finding
the relative path, while the absolute path works fine.

Dustin

From alan.gauld at btinternet.com  Wed Jul 26 11:11:28 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 26 Jul 2006 10:11:28 +0100
Subject: [Tutor] loops to assign variables
References: <000001c6ad90$59fc4a40$4c3ea8c0@JOHNC>
Message-ID: <ea7bk8$8hi$1@sea.gmane.org>

I'm reading the gmane news archive to see what I missed
while on vacation and noticed this. Sorry the response is
so late...

"John CORRY" <john.corry at ntlworld.com> wrote

> For example, I have 30 textentry boxes numbered from entry20 to 
> entry50.
> I have used the following code to assign the entryboxes to a local 
> name.
>
> text20 = self.wTree.get_widget("entry20")
> text21 = self.wTree.get_widget("entry21")

This is not a resonse to Johns original request but a general
comment on variable naming. It seems quite common in GUI
work for folks to use this style of entryN, buttonM etc.

But its not very programmer friendly! We wouldn't normally
call our variables var1, var2 etc it makes the intent of the code
much harder to comprehend. So we choose meaningful variable
names like width, height, name, location etc.

So why not do the same with GUI widgets? I usually prepend
a short code to indicate the type of widget, and either use the
label text or action name for the vatriable. Thus

eName ---- an entry widget for holding the name and it has
an associated label text of Name

bSave -- a button that has an assaociated action
function called save()

A one or two letter prefix should cover all widget types and
it makes the code much easier to read! Even if using GUI
builder tools it is nearly always possible to rename the
widget from the default widgetXX type name to something
meaningful using the property editor.

> I have had a go at writing a loop for the above 30 textentry boxes. 
> It
> is below, but it does not work.

If you need to loop over widgets in a collection the best way
is to simply add the widgets to a collection.

for widget in widgets:
    widget.doSomething()

Or use a dictionary:

widgets = {'Name': eName, 'Save': bSave, ...}
for widget in widgets:

in fact usually you can just navigate the widget containment
tree to access all the widgets at a given level.

Even if you are creating the widgets in bulk and don't have specific
names for each field you can still do the same thing and group
them together with a name for the group. Then load the entry
widgets into a list named by the group, for example of you have
a set of 5 arbitrary search strings that a user can specify,
you define a list called searchStrings and add the widgets to that:

for n in range(5):
    searchStrings.append(Entry(args here....))

Now we can access the seach strings with

for entry in searchStrings:
     searchString += entry.getval()

mydata.search(searchString)

Or similar techniques. There is hardly ever a good case for
using generic widgetXXX type names IMHO.

Just some stylistic considerations.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




From alan.gauld at btinternet.com  Wed Jul 26 11:24:27 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 26 Jul 2006 10:24:27 +0100
Subject: [Tutor] What's the invalid syntax?
References: <BAY106-DAV23A23691F50C98EF75CB3AC45A0@phx.gbl>
Message-ID: <ea7ccj$asf$1@sea.gmane.org>

"Nathan Pinno" <falcon3166 at hotmail.com> wrote:
> What's the invalid syntax?

Nathan, we have repeatedly asked you to post your
error messages, it really does help. We don't all have the time
nor inclination to have to read through every line of your code
trying to spot an error... Give us a clue, please...the interpreter
does the job for you, just pass on its advice!

Having said that, I see one glaring set of errors:

def menu_choice():
    choice = raw_input("Enter the letter of your choice: ")
    return choice

def date1():

date1 is the name of a function.

def date2():

as is date2

while 1:
    menu()
    menu_choice()

You never assign the return value of the function so choice is not 
set.
You need to reread the tutorial section on functions and return values
and namespaces.

    if choice == A:
        date1()
        days = int(raw_input("Enter the number of days to add: "))
        date3 = date1 + days

But here you try to create a variable which consists of a function
with one added to it. You cannot add numbers to functions.

You should havbe called date1 here

      date3 = date1() + 1

        days = date2 - date1

And here you are subtracting 2 functions. You should have called them 
here:

       days = date2() - date1()

So in essence I think your syntax errors are to do with your using
function names rather than the return values of those functions.
Remember a function returns a value, not a variable.

try this:

>>> def f():
...       x = 42
...      return x
...
>>> print x  #     an error because the name x ionly exists inside f,
                         the function returns the value of x, thus:

>>> print f()
42

and finally, functions are objects:

>>> print f     # <function object>
>>> print f+1  # error message
>>> print f() + 1
43

Or we could assign the result of f to a variable

>>> f_result = f()
>>> print f_result+1
43

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




From kent37 at tds.net  Wed Jul 26 12:44:36 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 26 Jul 2006 06:44:36 -0400
Subject: [Tutor] understanding __import__()
In-Reply-To: <44C705CE.3050106@speakeasy.net>
References: <44C705CE.3050106@speakeasy.net>
Message-ID: <44C74794.1040705@tds.net>

Sean Perry wrote:
> Ok, this may be slightly above tutor's level, but hey, never hurts to 
> ask (-:
>
> I am playing with __import__().  Here is my code:
> [code]
> import os.path
>
> app_path = '/tmp/my/settings'
> app_path2 = 'my/settings'
>
> if os.path.exists(app_path + '.py'):
>      print "Found", app_path
>
> try:
>      f = __import__(app_path, globals(), locals(), [])
>      print f.__name__, f.__file__
> except Exception, e:
>      print e
>
> if os.path.exists(app_path2 + '.py'):
>      print "Found", app_path2
>
> try:
>      f = __import__(app_path2, globals(), locals(), [])
>      print f.__name__, f.__file__
> except Exception, e:
>      print e
> [/code]
>
> The result is the first import fails and the second one works. Even 
> though they are the same file.
>   
The first argument to __import__ should be a module or package name, not 
a file path, e.g. "my.settings". Python will look for the module in the 
current sys.path the same as if you used a normal import. Apparently the 
/ is being interpreted as a . and I guess you have a file my/__init__.py so
  import my.settings
will work but
  import .tmp.my.settings
doesn't.

Kent
> $ pwd
> /tmp
> $ ls
> importer.py my/
> $ ls my
> settings.py
> $ ./importer.py
> Found /tmp/my/settings
> No module named /tmp/my/settings
> Found my/settings
> my/settings /tmp/my/settings.py
>
> What gives??
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From janos.juhasz at VELUX.com  Wed Jul 26 13:40:02 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Wed, 26 Jul 2006 13:40:02 +0200
Subject: [Tutor] getattr()
Message-ID: <OF797F742F.BA5AB8B5-ONC12571B7.003E7FE4-C12571B7.0040171E@velux.com>

Dear All,

I want to use getattr() to collect a list with all the functions on my 
simple script those has got some functionname like 'On....'.

#This should be the complete file
def OnMenuFindMe():
    print 'You found me'

f = getattr(What_Should_It_Be???, 'OnMenuFindMe')

f()
#Till here

It can use getattr() to get an object of a class or module, but not in 
this much simpler situation.



Yours sincerely, 
______________________________
J?nos Juh?sz 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060726/b29c9a53/attachment.html 

From kent37 at tds.net  Wed Jul 26 14:40:07 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 26 Jul 2006 08:40:07 -0400
Subject: [Tutor] getattr()
In-Reply-To: <OF797F742F.BA5AB8B5-ONC12571B7.003E7FE4-C12571B7.0040171E@velux.com>
References: <OF797F742F.BA5AB8B5-ONC12571B7.003E7FE4-C12571B7.0040171E@velux.com>
Message-ID: <44C762A7.7010609@tds.net>

J?nos Juh?sz wrote:
>
> Dear All,
>
> I want to use getattr() to collect a list with all the functions on my 
> simple script those has got some functionname like 'On....'.
>
> #This should be the complete file
> def OnMenuFindMe():
>     print 'You found me'
>
> f = getattr(What_Should_It_Be???, 'OnMenuFindMe')
>
> f()
> #Till here
>
> It can use getattr() to get an object of a class or module, but not in 
> this much simpler situation. 
You can look up the function in the globals() dict, or you can import 
__main__, which is the top-level module, and use getattr() on it. Or you 
could wrap your functions in a class...

def OnMenuFindMe():
    print 'You found me'

f = globals()['OnMenuFindMe']

f()

import __main__

g = getattr(__main__, 'OnMenuFindMe')
g()

Kent


From janos.juhasz at VELUX.com  Wed Jul 26 15:37:23 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Wed, 26 Jul 2006 15:37:23 +0200
Subject: [Tutor]  getattr()
Message-ID: <OFBE946228.2475A845-ONC12571B7.004A8E5F-C12571B7.004AD593@velux.com>

Dear Kent,

>>You can look up the function in the globals() dict, or you can import 
>>__main__, which is the top-level module, and use getattr() on it. Or you 

>>could wrap your functions in a class...
>>
>>def OnMenuFindMe():
>>    print 'You found me'
>>
>>f = globals()['OnMenuFindMe']
>>
>>f()
>>
>>import __main__
>>
>>g = getattr(__main__, 'OnMenuFindMe')
>>g()
>>
>>Kent

Many thanks.


Yours sincerely, 
______________________________
J?nos Juh?sz 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060726/0c632b17/attachment.htm 

From challman at gmail.com  Wed Jul 26 17:45:23 2006
From: challman at gmail.com (Chris Hallman)
Date: Wed, 26 Jul 2006 11:45:23 -0400
Subject: [Tutor] dictionary manipulation
Message-ID: <9f68812f0607260845h3aafa7caoc25dd635e25f9189@mail.gmail.com>

I need some suggestions on how to work with a dictionary. I've got a program
that builds a dictionary. I need to be able to manipulate the different keys
and data so that I can write the output to a file AND utilize the smtplib to
send the data in an email. I had problems using the data in the dictionary,
so I wrote a crude for loop to strip characters:

>>> print result
{'s0100swa': ['running correct IOS'], 's0300swa': ['INCORRECT running IOS'],
's0200swa': ['running correct IOS'], 's0400swa': ['running correct IOS']}

results= sorted(result.items())

>>> print results
[('s0100swa', ['running correct IOS']), ('s0200swa', ['running correct
IOS']), ('s0300swa', ['INCORRECT running IOS']), ('s0400swa', ['running
correct IOS'])]

for x in range(len(results)):
    text = repr(results[x])
    text = text.replace("'", "")
    text = text.replace("(", "")
    text = text.replace(")", "")
    text = text.replace("[", "")
    text = text.replace("]", "")
    text = text.replace(",", ":")
    output.write(text + "\n")
    output.flush()
output.write("\n")

I need to remove the extra characters so the file and email output isn't
difficult to read. I also need to be able to use the dictionary data so that
I can compose the message used by the smtplib.


Any suggestions?



Thanks!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060726/15891fc1/attachment.html 

From Barry.Carroll at psc.com  Wed Jul 26 18:50:39 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Wed, 26 Jul 2006 09:50:39 -0700
Subject: [Tutor] Tutor Digest, Vol 29, Issue 66
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36E9@eugsrv400.psc.pscnet.com>

Greetings:

> -----Original Message-----
> Date: Wed, 26 Jul 2006 10:11:28 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] loops to assign variables
> To: tutor at python.org
> Message-ID: <ea7bk8$8hi$1 at sea.gmane.org>
> 
<<snip>>
> 
> "John CORRY" <john.corry at ntlworld.com> wrote
> 
> > For example, I have 30 textentry boxes numbered from entry20 to
> > entry50.
> > I have used the following code to assign the entryboxes to a local
> > name.
> >
> > text20 = self.wTree.get_widget("entry20")
> > text21 = self.wTree.get_widget("entry21")
> 
> This is not a resonse to Johns original request but a general
> comment on variable naming. It seems quite common in GUI
> work for folks to use this style of entryN, buttonM etc.
> 
> But its not very programmer friendly! We wouldn't normally
> call our variables var1, var2 etc it makes the intent of the code
> much harder to comprehend. So we choose meaningful variable
> names like width, height, name, location etc.
> 
<<snip>>

I agree with Alan here.  Unless the numbers reflect some property of the
object being modeled (room numbers in a hotel, airline flight numbers,
TV channels, etc), they should not be used in the widget name.  

My $0.02.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



From bgailer at alum.rpi.edu  Wed Jul 26 19:24:10 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 26 Jul 2006 10:24:10 -0700
Subject: [Tutor] dictionary manipulation
In-Reply-To: <9f68812f0607260845h3aafa7caoc25dd635e25f9189@mail.gmail.com>
References: <9f68812f0607260845h3aafa7caoc25dd635e25f9189@mail.gmail.com>
Message-ID: <44C7A53A.5060807@alum.rpi.edu>

Chris Hallman wrote:
>
> I need some suggestions on how to work with a dictionary. I've got a 
> program that builds a dictionary. I need to be able to manipulate the 
> different keys and data so that I can write the output to a file AND 
> utilize the smtplib to send the data in an email. I had problems using 
> the data in the dictionary, so I wrote a crude for loop to strip 
> characters:
>
> >>> print result
> {'s0100swa': ['running correct IOS'], 's0300swa': ['INCORRECT running 
> IOS'], 's0200swa': ['running correct IOS'], 's0400swa': ['running 
> correct IOS']}
>
> results= sorted(result.items ())
>
> >>> print results
> [('s0100swa', ['running correct IOS']), ('s0200swa', ['running correct 
> IOS']), ('s0300swa', ['INCORRECT running IOS']), ('s0400swa', 
> ['running correct IOS'])]
>
> for x in range(len(results)):
>     text = repr(results[x])
>     text = text.replace("'", "")
>     text = text.replace("(", "")
>     text = text.replace(")", "")
>     text = text.replace ("[", "")
>     text = text.replace("]", "")
>     text = text.replace(",", ":")
>     output.write(text + "\n")
>     output.flush()
> output.write ("\n")
>
> I need to remove the extra characters so the file and email output 
> isn't difficult to read. I also need to be able to use the dictionary 
> data so that I can compose the message used by the smtplib.
>
>
> Any suggestions?
I for one have no suggestions to offer because I don't know what you 
want. "suggestions on how to work with a dictionary" is not adequate. 
Where are you stuck? Do you want critique of the code you posted, or how 
use smtplib or what?

-- 
Bob Gailer
510-978-4454


From Barry.Carroll at psc.com  Wed Jul 26 19:23:28 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Wed, 26 Jul 2006 10:23:28 -0700
Subject: [Tutor] confused by linked queue
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36EA@eugsrv400.psc.pscnet.com>

Danny, et al:


> -----Original Message-----
> Date: Tue, 25 Jul 2006 15:43:34 -0700 (PDT)
> From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] confused by linked queue
> To: Christopher Spears <cspears2002 at yahoo.com>
> Cc: Tutor <tutor at python.org>
> Message-ID: <Pine.LNX.4.64.0607251510020.22412 at hkn.eecs.berkeley.edu>
> Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed
> 
> > One of my problems in conecptualizing this is that I thought a
linked
> > queue was just a linked list.  Is a linked queue a linked list?
There
> > seems to be a subtle difference...
> 
> Hi Chris,
> 
> I think you mean to ask:
> 
>      Is a "queue" a linked list?
> 
> 
> Here's another particular possible queue class that does something
> similar, but with Python's regular lists rather than a linked list:
> 
> ######################################
> class ArrayQueue:
>      def __init__(self):
>          self.elements = []
> 
>      def isEmpty(self):
>          return len(self.elements) == 0
> 
>      def insert(self, elt):
>          self.elements.append(elt)
> 
>      def remove(self):
>          return self.elements.pop(0)
> ######################################
> 
> This works on a different principle than the linked list queue, but it
> does the same stuff.  The main idea is that a "queue" can be anything,
as
> long as it supports three operations:
> 
>      * isEmpty
>      * insert
>      * remove
> 
<<snip>>

Isn't there a fourth operation needed?

	* isFull  

Even in Python (where the underlying data structure can grow on the fly,
there is a physical upper limit: the size of the heap or stack.  This
condition needs to be handled gracefully. 

Regards,

Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



From David.Heiser at intelliden.com  Wed Jul 26 19:30:28 2006
From: David.Heiser at intelliden.com (David Heiser)
Date: Wed, 26 Jul 2006 11:30:28 -0600
Subject: [Tutor] dictionary manipulation
Message-ID: <3CABD13EA1D5D347A1B75014BD54CFD502B0BD90@COSIUM03.intelliden.net>

  
Chris,
 
This looks similar to what I do for my job. I would be happy to help
you, if I can.
 
My first question is, how would you like the output to look? Can you
manually create a model of the email text you want to send?
 
My second question is, can you create the email content on the fly
instead of creating a dictionary, or are you constrained to using a
dictionary for some reason?
 
Dave
 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of Chris Hallman
Sent: Wednesday, July 26, 2006 9:45 AM
To: tutor at python.org
Subject: [Tutor] dictionary manipulation



I need some suggestions on how to work with a dictionary. I've got a
program that builds a dictionary. I need to be able to manipulate the
different keys and data so that I can write the output to a file AND
utilize the smtplib to send the data in an email. I had problems using
the data in the dictionary, so I wrote a crude for loop to strip
characters: 

>>> print result
{'s0100swa': ['running correct IOS'], 's0300swa': ['INCORRECT running
IOS'], 's0200swa': ['running correct IOS'], 's0400swa': ['running
correct IOS']}

results= sorted(result.items ())

>>> print results
[('s0100swa', ['running correct IOS']), ('s0200swa', ['running correct
IOS']), ('s0300swa', ['INCORRECT running IOS']), ('s0400swa', ['running
correct IOS'])]

for x in range(len(results)): 
    text = repr(results[x])
    text = text.replace("'", "")
    text = text.replace("(", "")
    text = text.replace(")", "")
    text = text.replace ("[", "")
    text = text.replace("]", "")
    text = text.replace(",", ":")
    output.write(text + "\n")
    output.flush()
output.write ("\n")

I need to remove the extra characters so the file and email output isn't
difficult to read. I also need to be able to use the dictionary data so
that I can compose the message used by the smtplib.


Any suggestions?



Thanks!!


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060726/8036ac3a/attachment.html 

From kent37 at tds.net  Wed Jul 26 19:46:01 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 26 Jul 2006 13:46:01 -0400
Subject: [Tutor] dictionary manipulation
In-Reply-To: <9f68812f0607260845h3aafa7caoc25dd635e25f9189@mail.gmail.com>
References: <9f68812f0607260845h3aafa7caoc25dd635e25f9189@mail.gmail.com>
Message-ID: <44C7AA59.7000503@tds.net>

Chris Hallman wrote:
>
> I need some suggestions on how to work with a dictionary. I've got a 
> program that builds a dictionary. I need to be able to manipulate the 
> different keys and data so that I can write the output to a file AND 
> utilize the smtplib to send the data in an email. I had problems using 
> the data in the dictionary, so I wrote a crude for loop to strip 
> characters:
>
> >>> print result
> {'s0100swa': ['running correct IOS'], 's0300swa': ['INCORRECT running 
> IOS'], 's0200swa': ['running correct IOS'], 's0400swa': ['running 
> correct IOS']}
>
> results= sorted(result.items ())
>
> >>> print results
> [('s0100swa', ['running correct IOS']), ('s0200swa', ['running correct 
> IOS']), ('s0300swa', ['INCORRECT running IOS']), ('s0400swa', 
> ['running correct IOS'])]
>
> for x in range(len(results)):
>     text = repr(results[x])
>     text = text.replace("'", "")
>     text = text.replace("(", "")
>     text = text.replace(")", "")
>     text = text.replace ("[", "")
>     text = text.replace("]", "")
>     text = text.replace(",", ":")
>     output.write(text + "\n")
>     output.flush()
> output.write ("\n")
It seems like most of the work you are doing here is getting rid of 
characters you don't want that you introduced by using the string 
representation of the results list. You will do much better by just 
creating the string you want directly. I think you want something like this:

for key, value in sorted(result.items()):
  value = value[0] # get the firset item from the value list
  line = '%s: %s\n' % (key, value)
  output.write(line)

Also you are using a list as the value in the dict, but all the lists 
contain a single string. Maybe you should just store the string directly?

Kent


From kent37 at tds.net  Wed Jul 26 19:52:24 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 26 Jul 2006 13:52:24 -0400
Subject: [Tutor] getattr()
In-Reply-To: <8249c4ac0607261035i7a3bb0abncdd6ed2b514f15d1@mail.gmail.com>
References: <8249c4ac0607261035i7a3bb0abncdd6ed2b514f15d1@mail.gmail.com>
Message-ID: <44C7ABD8.6000407@tds.net>

Tony Cappellini wrote:
> From: Kent Johnson <kent37 at tds.net>
>
>   
>>> or you can import __main__, which is the top-level module
> Do you mean __main__ is the top level module for every python
> program/script?
>   
Yes, at least in the standard Python runtime, I'm not sure what happens 
when running in IDLE, for example.
> Where did you read about this?
Not sure, but this is what makes the test for __name__ == '__main__' 
work, and importing __main__ comes up occasionally on comp.lang.python. 
Also see
http://docs.python.org/ref/naming.html#l2h-320

Kent

PS Please reply on list.


From dyoo at hkn.eecs.berkeley.edu  Wed Jul 26 20:15:49 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Jul 2006 11:15:49 -0700 (PDT)
Subject: [Tutor] confused by linked queue
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C36EA@eugsrv400.psc.pscnet.com>
References: <2BBAEE949D384D40A2B851287ADB6A432C36EA@eugsrv400.psc.pscnet.com>
Message-ID: <Pine.LNX.4.64.0607261043410.3011@hkn.eecs.berkeley.edu>

>> This works on a different principle than the linked list queue, but it 
>> does the same stuff.  The main idea is that a "queue" can be anything, 
>> as long as it supports three operations:
>>
>>      * isEmpty
>>      * insert
>>      * remove
>>
> <<snip>>
>
> Isn't there a fourth operation needed?
>
> 	* isFull

Hi Barry,

If we add this requirement, then we're talking about a queue with bounds. 
That is a perfectly reasonable thing to ask for, and it may or may not be 
an essential property in applications that use queues, depending on our 
application.  Small interfaces are easier to implement than large ones, so 
we should be try to put as few operations as necessary.


In any case, I think we're straying from the main point, which is the idea 
that we can implement a concept in many different ways.

The really simple ArrayQueue class presented earlier should "work" just 
like the LinkedQueue class.  So in practical terms, if we needed a queue 
for some application, we can use the simple thing first.  And if it turns 
out that the Queue implementation we've used is too slow, we can switch. 
No one should know the difference.

(I wouldn't immediately use LinkedQueue only because I don't trust it.  I 
mean that from an engineering point of view: the code has a heck of a lot 
of moving parts, and because I don't see a test suite for it, I can't be 
sure that it's correct without spending time on it.  Queues are boring; I 
don't want to spend time on them unless I really need to.  *grin*)


Good programmming practice allows us to be non-committal in the places 
where we want to support change.

From shaleh at speakeasy.net  Wed Jul 26 01:36:29 2006
From: shaleh at speakeasy.net (shaleh at speakeasy.net)
Date: Tue, 25 Jul 2006 23:36:29 +0000
Subject: [Tutor] problem with __import__()
Message-ID: <W703332615399171153870589@webmail2>

I am attempting to use __import__() to read a Python file. It is not working. 

What is particularly odd is that it works from the interactive prompt. Looking at sys.path I can see that in the interactive session path starts with an empty entry. Adding a similar entry to my script causes the import to work. Not sure why. Any clues?

Here the code:
import sys

try:
    f = __import__("/tmp/my/settings")
    print f.__name__
except:
    print "1. Failed"

sys.path.insert(0, '')

try:
    f = __import__("/tmp/my/settings")
    print f.__name__
except:
    print "2. Failed"




From alan.gauld at freenet.co.uk  Wed Jul 26 21:08:13 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 26 Jul 2006 20:08:13 +0100
Subject: [Tutor] getattr()
References: <OF797F742F.BA5AB8B5-ONC12571B7.003E7FE4-C12571B7.0040171E@velux.com>
Message-ID: <001901c6b0e6$d800b710$0201a8c0@XPpro>

Janos,

I'm confused...

#################
#This should be the complete file
def OnMenuFindMe():
    print 'You found me'

f = getattr(What_Should_It_Be???, 'OnMenuFindMe')

f()
#################

You are trying to get a reference to a function in the same 
file and whose name you know? So why not just

f = OnMenuFindMe
f()

Or just call the function!
getattr makes sense when its another module or a class 
where you may not have access to the function somehow 
but it doesn't make much sense in this case - at least 
not to me!

Alan G.


From alan.gauld at freenet.co.uk  Wed Jul 26 21:22:17 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 26 Jul 2006 20:22:17 +0100
Subject: [Tutor] dictionary manipulation
References: <9f68812f0607260845h3aafa7caoc25dd635e25f9189@mail.gmail.com>
Message-ID: <003d01c6b0e8$ceded890$0201a8c0@XPpro>

Chris, You seem to be going through several hoops that
you don't need here. Let the data structures do the work
of storage and extract the data you want in its various
pieces. You are getting the entire data set in a string
then trying to pick out the bits you want, that defeats
the purpose of having the data structures in the first
place!

>>>> print result
> {'s0100swa': ['running correct IOS'], 's0300swa': ['INCORRECT 
> running IOS'],
> 's0200swa': ['running correct IOS'], 's0400swa': ['running correct 
> IOS']}

So this tells us that result is a dictionary with the keys being 
strings
and the data being a list containing a single string. I'm not sure why
you need the list, if possible lose it and just use the string!

> results= sorted(result.items())

This now replacews the dictionary with a list of tuples.
Each tuple contains the dictiinary key string plus the list
with the string inside - 3 levels of data structure!

> for x in range(len(results)):
>    text = repr(results[x])

It is better to use for loops as Guido intended:

 for res in results:
     text = repr(res)

But in fact this isn't necessary if you iterate over
the original dictionary instead

for key in sorted(result.keys):     a sorted list of keys
      text = key + result[key]   # assuming we can lose the list!

You might want to use string formatting here to tidy it up:

      text = "%s\t%s\n" % (key,result[key]) # add formatting values if 
needed

>    text = text.replace("'", "")
>    text = text.replace("(", "")
>    text = text.replace(")", "")
>    text = text.replace("[", "")
>    text = text.replace("]", "")
>    text = text.replace(",", ":")

and you don;t need any of this gloop

>    output.write(text + "\n")
      output.write(text)  # newline added in the format string

>    output.flush()
> output.write("\n")

Why an extra newline? Just write two newlines above if you really
need the blank lines!

> I need to remove the extra characters so the file and email output 
> isn't
> difficult to read. I also need to be able to use the dictionary data 
> so that
> I can compose the message used by the smtplib.

Hopefully my comments make things clearer

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From shaleh at speakeasy.net  Wed Jul 26 00:07:39 2006
From: shaleh at speakeasy.net (shaleh at speakeasy.net)
Date: Tue, 25 Jul 2006 22:07:39 +0000
Subject: [Tutor] help understanding __import__() oddness
Message-ID: <W6355230708205251153865259@webmail2>

I have a script trying to use __import__ to read Python modules as config files (among other things). Sounds simple enough.
To put it simply, full paths seem to fail but relative path work IF the script is in that path too.

When I run it I get:

$ cd /tmp
$ ls
importer.py my
$ ls my
settings.py  settings.pyc
$ ./importer.py
Starting in /tmp
Found /tmp/my/settings
No module named /tmp/my/settings
Found my/settings
my/settings /tmp/my/settings.pyc

[code]
import os
import os.path

print "Starting in " + os.getcwd()

app_path = '/tmp/my/settings'
app_path2 = 'my/settings'

if os.path.exists(app_path + '.py'):
    print "Found", app_path

try:
    f = __import__(app_path, globals(), locals(), [])
    print f.__name__, f.__file__
except Exception, e:
    print e

# uncomment me if started somewhere else
# print "Moving to /tmp"
# os.chdir("/tmp")

if os.path.exists(app_path2 + '.py'):
    print "Found", app_path2

try:
    f = __import__(app_path2, globals(), locals(), [])
    print f.__name__, f.__file__
except Exception, e:
    print e
[/code]

If I move the script to /foo and add a os.chdir() call before the second module attempt BOTH fail:

$ ./importer.py
Starting in /home/sperry
Found /tmp/my/settings
No module named /tmp/my/settings
Moving to /tmp
Found my/settings
No module named my/settings

Obviously I am confused. None of the docs I have read indicate this should be the case. What gives?

I was just about to hit send when a thought occured to me. What about sys.path? The script's starting directory is added to the path. Which makes the relative lookups work. Fair enough. But if I start the interpreter in ~/ and do:

>>> __import__("/tmp/my/settings")
<module '/tmp/my/settings' from '/tmp/my/settings.pyc'>

It works. <shrug>

Simple script:
$ ./test.py
1. Failed
/tmp/my/settings

[code]
import sys

try:
    f = __import__("/tmp/my/settings")
    print f.__name__
except:
    print "1. Failed"

sys.path.insert(0, '')

try:
    f = __import__("/tmp/my/settings")
    print f.__name__
except:
    print "2. Failed"
[/code]

That works. What gives?



From mjekl at iol.pt  Wed Jul 26 22:27:46 2006
From: mjekl at iol.pt (mjekl at iol.pt)
Date: Wed, 26 Jul 2006 21:27:46 +0100
Subject: [Tutor] Problems with encoding
Message-ID: <f3d3ca5338dd.44c7de52@iol.pt>

Hi,


My interpreter in set via sitecustomize.py to use utf-8 as default encoding.

I'm reading fields from a dbf table to a firebird db with encoding set to win1252.
I guess it's original encoding is cp850, but am not sure, and have been addressing exceptions one by one with lines of:

r = r.replace(u'offending_code', u'ok_code')

But now it seems I've run into a brick wall!
I've this exception I can't seem to avoid with my strategy:
"""
Traceback (most recent call last):
  File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript
    debugger.run(codeObject, __main__.__dict__, start_stepping=0)
  File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run
    _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
  File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run
    exec cmd in globals, locals
  File "C:\Documents and Settings\mel.TECNICON\Desktop\Statistics\fromDBF\import_pcfcli.py", line 216, in ?
    fbCr.execute(sqlTemplate, rec)
  File "C:\Python24\Lib\site-packages\kinterbasdb\typeconv_text_unicode.py", line 108, in unicode_conv_in
    return unicodeString.encode(pyEncodingName)
  File "C:\Python24\Lib\encodings\cp1252.py", line 18, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x99 in position 33: unexpected code byte
"""

I also print the offending record so I can inspect it and apply my strategy:
('', 'A', '', '', 'EDIFICIOS 3B,SOCIEDADE DE CONTRUC\x99ES LDA', 'LISBOA', 'Plafond: 2494, Prazo de Pagamento: 30 Metodo de pagamento: ', '', '', 'RUA JO\x8eO SILVA,N..4,10A', '', '1900-271', '502216972', '218482733', '1663')

The problem is with '\x99' :-(
I added this line to the code:

r = r.replace(u'\x99', u'O')

But it I get exactly the same Traceback!

I'm at a loss.
Txs for all the help,
Miguel

_______________________________________________________________________________________
Sabe em quanto tempo damos resposta para ter 4000Euros?
Saber mais em http://www.iol.pt/correio/rodape.php?dst=0607071


From alan.gauld at freenet.co.uk  Wed Jul 26 22:59:51 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 26 Jul 2006 21:59:51 +0100
Subject: [Tutor] dictionary manipulation
References: <9f68812f0607260845h3aafa7caoc25dd635e25f9189@mail.gmail.com>
	<003d01c6b0e8$ceded890$0201a8c0@XPpro>
Message-ID: <002101c6b0f6$70526810$0201a8c0@XPpro>

> for key in sorted(result.keys):     a sorted list of keys

Oops, that should of course be:

for key in sorted(result.keys() ):

Alan G.


From kent37 at tds.net  Wed Jul 26 23:03:36 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 26 Jul 2006 17:03:36 -0400
Subject: [Tutor] Problems with encoding
In-Reply-To: <f3d3ca5338dd.44c7de52@iol.pt>
References: <f3d3ca5338dd.44c7de52@iol.pt>
Message-ID: <44C7D8A8.8070307@tds.net>

mjekl at iol.pt wrote:
> Hi,
>
>
> My interpreter in set via sitecustomize.py to use utf-8 as default encoding.
>
> I'm reading fields from a dbf table to a firebird db with encoding set to win1252.
> I guess it's original encoding is cp850, but am not sure, and have been addressing exceptions one by one with lines of:
>
> r = r.replace(u'offending_code', u'ok_code')
>   
Why don't you just convert from cp850 to cp1252 directly? Python 
supports both encodings, it's as simple as
some_string.decode('cp850').encode('cp1252')
> But now it seems I've run into a brick wall!
> I've this exception I can't seem to avoid with my strategy:
> """
> Traceback (most recent call last):
>   File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript
>     debugger.run(codeObject, __main__.__dict__, start_stepping=0)
>   File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run
>     _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
>   File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run
>     exec cmd in globals, locals
>   File "C:\Documents and Settings\mel.TECNICON\Desktop\Statistics\fromDBF\import_pcfcli.py", line 216, in ?
>     fbCr.execute(sqlTemplate, rec)
>   File "C:\Python24\Lib\site-packages\kinterbasdb\typeconv_text_unicode.py", line 108, in unicode_conv_in
>     return unicodeString.encode(pyEncodingName)
>   File "C:\Python24\Lib\encodings\cp1252.py", line 18, in encode
>     return codecs.charmap_encode(input,errors,encoding_map)
> UnicodeDecodeError: 'utf8' codec can't decode byte 0x99 in position 33: unexpected code byte
> """
>
> I also print the offending record so I can inspect it and apply my strategy:
> ('', 'A', '', '', 'EDIFICIOS 3B,SOCIEDADE DE CONTRUC\x99ES LDA', 'LISBOA', 'Plafond: 2494, Prazo de Pagamento: 30 Metodo de pagamento: ', '', '', 'RUA JO\x8eO SILVA,N..4,10A', '', '1900-271', '502216972', '218482733', '1663')
>
> The problem is with '\x99' :-(
> I added this line to the code:
>
> r = r.replace(u'\x99', u'O')
>
> But it I get exactly the same Traceback!

My guess is a coding error on your part, otherwise something would have 
changed...can you show some context in import_pcfcli.py?

Kent


From tim at johnsons-web.com  Thu Jul 27 01:34:43 2006
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed, 26 Jul 2006 15:34:43 -0800
Subject: [Tutor] Cookies with CGI
In-Reply-To: <44C7D8A8.8070307@tds.net>
References: <f3d3ca5338dd.44c7de52@iol.pt> <44C7D8A8.8070307@tds.net>
Message-ID: <20060726233443.GJ16709@johnsons-web.com>

Hello:

I'd like to set (write) and get (read) cookies on a client
computer via CGI.

Does python have the libraries to do this. If so, pointers
to the libraries and documentation is welcomed.

thanks
tim

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com

From kent37 at tds.net  Thu Jul 27 03:31:31 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 26 Jul 2006 21:31:31 -0400
Subject: [Tutor] Cookies with CGI
In-Reply-To: <20060726233443.GJ16709@johnsons-web.com>
References: <f3d3ca5338dd.44c7de52@iol.pt> <44C7D8A8.8070307@tds.net>
	<20060726233443.GJ16709@johnsons-web.com>
Message-ID: <44C81773.4060802@tds.net>

Tim Johnson wrote:
> Hello:
>
> I'd like to set (write) and get (read) cookies on a client
> computer via CGI.
>
> Does python have the libraries to do this. If so, pointers
> to the libraries and documentation is welcomed.

The Cookie module is to help with server-side cookies. Docs and examples 
seem a bit thin but try these:
http://pleac.sourceforge.net/pleac_python/cgiprogramming.html
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325484
http://www.cs.virginia.edu/~lab2q/lesson_7/

Or google "python cgi cookie" ...

Kent


From tim at johnsons-web.com  Thu Jul 27 04:23:19 2006
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed, 26 Jul 2006 18:23:19 -0800
Subject: [Tutor] Cookies with CGI
In-Reply-To: <44C81773.4060802@tds.net>
References: <f3d3ca5338dd.44c7de52@iol.pt> <44C7D8A8.8070307@tds.net>
	<20060726233443.GJ16709@johnsons-web.com>
	<44C81773.4060802@tds.net>
Message-ID: <20060727022319.GL16709@johnsons-web.com>

* Kent Johnson <kent37 at tds.net> [060726 17:49]:
> Tim Johnson wrote:
> > Hello:
> >
> > I'd like to set (write) and get (read) cookies on a client
> > computer via CGI.
> >
> > Does python have the libraries to do this. If so, pointers
> > to the libraries and documentation is welcomed.
> 
> The Cookie module is to help with server-side cookies. Docs and examples 
> seem a bit thin but try these:
> http://pleac.sourceforge.net/pleac_python/cgiprogramming.html
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325484
> http://www.cs.virginia.edu/~lab2q/lesson_7/
 
  Thanks! That's enough to get me started.
  cheers
  tim

> Or google "python cgi cookie" ...
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com

From cspears2002 at yahoo.com  Thu Jul 27 04:59:46 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed, 26 Jul 2006 19:59:46 -0700 (PDT)
Subject: [Tutor] remove function
Message-ID: <20060727025946.80509.qmail@web51605.mail.yahoo.com>

Here is a class called PriorityQueue:

class PriorityQueue:
	def __init__(self):
		self.items = []
		
	def isEmpty(self):
		return self.items == []
		
	def insert(self, item):
		self.items.append(item)
		
	def remove(self):
		maxi = 0
		for i in range(1, len(self.items)):
			if self.items[i] > self.items[maxi]:
				maxi = i
		item = self.items[maxi]
 
		return item
		
My question concerns the remove function.  The
function returns the maximum value.  However, I'm
curious about
self.items[maxi:maxi+1] = [].  I understand that the
programmer wants to remove self.items[maxi].  Why
would he or she want to remove that value and the one
next to it (maxi+1)?  Or am I misunderstanding 	
self.items[maxi:maxi+1] = [] ?

As an aside, I can't figure out how to respond to
topics on this list.
 

From sfhaley at gmail.com  Thu Jul 27 05:19:46 2006
From: sfhaley at gmail.com (Steve Haley)
Date: Wed, 26 Jul 2006 23:19:46 -0400
Subject: [Tutor] The In Operator
Message-ID: <f445d9050607262019v2ee66096wed45e6658354e6db@mail.gmail.com>

I am trying to make my way through a book on Python ("Python Ptogramming for
the Absolute Beginner") and have run into some code in the book (and on the
author's accompanying CD) that won't work.  I suspect that it might be
because my version of Python is too old (2.1).

The code includes the in operator as follows:

if "Dancing Baloney" in geek:
...  print "I know what Dancing Baloney is."
... else:
...  print "I have no idea what Dancing Baloney is."

where geek is the nam of a dictionary.  "Dancing Baloney is not in the
dictionary so I should get the second print statement as a result but
instead get:

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: 'in' or 'not in' needs sequence right argument

The error message is the same when I run the author's code but the error
statement itself seems to indicate that there IS an in operator.  I guess I
really have a three questions.  Is the in operator in version 2.1 of
Python?  If it is, what is the syntax?  (I tried to find it in the help etc.
and couldn't.)  Finally, my version of 2.1 came bundled with other software
(ESRI ArcView).  Is anyone out there an ESRI user who can tell me if I can I
go ahead and download a newer version without messing up my ArcView
installation?

Thanks,
Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060726/6b0f4076/attachment.htm 

From john at fouhy.net  Thu Jul 27 05:38:55 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 27 Jul 2006 15:38:55 +1200
Subject: [Tutor] The In Operator
In-Reply-To: <f445d9050607262019v2ee66096wed45e6658354e6db@mail.gmail.com>
References: <f445d9050607262019v2ee66096wed45e6658354e6db@mail.gmail.com>
Message-ID: <5e58f2e40607262038y5e725f71y714a0069ff3016bd@mail.gmail.com>

On 27/07/06, Steve Haley <sfhaley at gmail.com> wrote:
> The error message is the same when I run the author's code but the error
> statement itself seems to indicate that there IS an in operator.  I guess I
> really have a three questions.  Is the in operator in version 2.1 of Python?
>  If it is, what is the syntax?  (I tried to find it in the help etc. and
> couldn't.)

There is an 'in' operator in py2.1; as the error message explains, it
expects a sequence on the right hand side.

Sequences are:
 - lists
 - strings
 - tuples

You could change the code to:

     if "Dancing Baloney" in geek.keys():

and it would work; the .keys() method of a dictionary returns a list
containing the dictionary's keys (in arbitrary order).

You could also change the code to:

    if geek.has_key("Dancing Baloney"):

This will be more efficient, and this is equivalent to using "in" in
recent versionf of python.
(ie: "key in dict" is equivalent to "dict.has_key(key)")

(are you new to programming in general, or just python in particular?)

-- 
John.

From rabidpoobear at gmail.com  Thu Jul 27 05:43:21 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 26 Jul 2006 22:43:21 -0500
Subject: [Tutor] remove function
In-Reply-To: <20060727025946.80509.qmail@web51605.mail.yahoo.com>
References: <20060727025946.80509.qmail@web51605.mail.yahoo.com>
Message-ID: <44C83659.2090400@gmail.com>

Christopher Spears wrote:
> Here is a class called PriorityQueue:
>
> class PriorityQueue:
> 	def __init__(self):
> 		self.items = []
> 		
> 	def isEmpty(self):
> 		return self.items == []
> 		
> 	def insert(self, item):
> 		self.items.append(item)
> 		
> 	def remove(self):
> 		maxi = 0
> 		for i in range(1, len(self.items)):
> 			if self.items[i] > self.items[maxi]:
> 				maxi = i
> 		item = self.items[maxi]
>  
> 		return item
> 		
> My question concerns the remove function.  The
> function returns the maximum value.  However, I'm
> curious about
> self.items[maxi:maxi+1] = [].  I understand that the
> programmer wants to remove self.items[maxi].  Why
> would he or she want to remove that value and the one
> next to it (maxi+1)?  Or am I misunderstanding 	
> self.items[maxi:maxi+1] = [] ?
>   
I don't see the line 'self.items[maxi:maxi+1] = []' anywhere in the 
above code.
In fact, I don't see any list slicing taking place at all.

> As an aside, I can't figure out how to respond to
> topics on this list.
>  
>   
either hit 'reply-all' in your message or change the 'to:'
line from whatever the recipient's address is to 'tutor at python.org'
(you can also cc. to 'tutor at python.org' but this is what will
happen when you 'reply-all' anyway.)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From cspears2002 at yahoo.com  Thu Jul 27 06:12:39 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed, 26 Jul 2006 21:12:39 -0700 (PDT)
Subject: [Tutor] remove function
In-Reply-To: <44C83659.2090400@gmail.com>
Message-ID: <20060727041239.6665.qmail@web51601.mail.yahoo.com>

My apologies to everyone.  Here is the complete code:


class PriorityQueue:
	def __init__(self):
		self.items = []
		
	def isEmpty(self):
		return self.items == []
		
	def insert(self, item):
		self.items.append(item)
		
	def remove(self):
		maxi = 0
		for i in range(1, len(self.items)):
			if self.items[i] > self.items[maxi]:
				maxi = i
		item = self.items[maxi]
		self.items[maxi:maxi+1] = []
		return item
		
	

--- Luke Paireepinart <rabidpoobear at gmail.com> wrote:

> Christopher Spears wrote:
> > Here is a class called PriorityQueue:
> >
> > class PriorityQueue:
> > 	def __init__(self):
> > 		self.items = []
> > 		
> > 	def isEmpty(self):
> > 		return self.items == []
> > 		
> > 	def insert(self, item):
> > 		self.items.append(item)
> > 		
> > 	def remove(self):
> > 		maxi = 0
> > 		for i in range(1, len(self.items)):
> > 			if self.items[i] > self.items[maxi]:
> > 				maxi = i
> > 		item = self.items[maxi]
> >  
> > 		return item
> > 		
> > My question concerns the remove function.  The
> > function returns the maximum value.  However, I'm
> > curious about
> > self.items[maxi:maxi+1] = [].  I understand that
> the
> > programmer wants to remove self.items[maxi].  Why
> > would he or she want to remove that value and the
> one
> > next to it (maxi+1)?  Or am I misunderstanding 	
> > self.items[maxi:maxi+1] = [] ?
> >   
> I don't see the line 'self.items[maxi:maxi+1] = []'
> anywhere in the 
> above code.
> In fact, I don't see any list slicing taking place
> at all.
> 
> > As an aside, I can't figure out how to respond to
> > topics on this list.
> >  
> >   
> either hit 'reply-all' in your message or change the
> 'to:'
> line from whatever the recipient's address is to
> 'tutor at python.org'
> (you can also cc. to 'tutor at python.org' but this is
> what will
> happen when you 'reply-all' anyway.)
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >   
> 
> 


"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"I generally know what I'm doing."
-Buster Keaton

From sfhaley at gmail.com  Thu Jul 27 06:33:58 2006
From: sfhaley at gmail.com (Steve Haley)
Date: Thu, 27 Jul 2006 00:33:58 -0400
Subject: [Tutor] In Operator
Message-ID: <f445d9050607262133i271804f2hc6248daa378657c6@mail.gmail.com>

Thanks for the help on the in operator, John.  In answer to your question I
did a little programming a long time ago in sequential languages such as
dBase, FoxBase, Clipper, and a little C.  Then Windows came along, my job
changed, and I didn't really keep up in the event driven environment.  I
have done a little in Visual Basic for Applications but not even that
recently.  I am in graduate school now for GIS basically and took a course a
couple of semesters ago that involved a little Python and it got me
interested.  I am still basically new to Python.

Thanks again,
Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060727/fc07e480/attachment.html 

From the_evil_laugh at hotmail.com  Thu Jul 27 06:29:19 2006
From: the_evil_laugh at hotmail.com (The Fulch)
Date: Thu, 27 Jul 2006 14:29:19 +1000
Subject: [Tutor] Reg Ex in python
Message-ID: <BAY102-F26A2F39AEA9BEB7C3390A9D7580@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060727/71286612/attachment.htm 

From shaleh at speakeasy.net  Thu Jul 27 07:13:30 2006
From: shaleh at speakeasy.net (Sean Perry)
Date: Wed, 26 Jul 2006 22:13:30 -0700
Subject: [Tutor] understanding __import__()
In-Reply-To: <44C74794.1040705@tds.net>
References: <44C705CE.3050106@speakeasy.net> <44C74794.1040705@tds.net>
Message-ID: <44C84B7A.6090104@speakeasy.net>

Kent Johnson wrote:
> The first argument to __import__ should be a module or package name, not 
> a file path, e.g. "my.settings". Python will look for the module in the 
> current sys.path the same as if you used a normal import. Apparently the 
> / is being interpreted as a . and I guess you have a file my/__init__.py so
>   import my.settings
> will work but
>   import .tmp.my.settings
> doesn't.
> 

as I mention in another email, if I do:

import sys
sys.path.insert(0, '')

It all just works. Very confused.

From janos.juhasz at VELUX.com  Thu Jul 27 08:00:36 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 27 Jul 2006 08:00:36 +0200
Subject: [Tutor] Tutor Digest, Vol 29, Issue 68
In-Reply-To: <mailman.32036.1153943665.27774.tutor@python.org>
Message-ID: <OF3CCD9DCF.6AB90130-ONC12571B8.001F88AE-C12571B8.002103F6@velux.com>

Dear Alan,

> I'm confused...

> #################
> #This should be the complete file
> def OnMenuFindMe():
> print 'You found me'

> f = getattr(What_Should_It_Be???, 'OnMenuFindMe')

> f()
> #################

> You are trying to get a reference to a function in the same
> file and whose name you know? So why not just

> f = OnMenuFindMe
> f()

> Or just call the function!
> getattr makes sense when its another module or a class
> where you may not have access to the function somehow
> but it doesn't make much sense in this case - at least
> not to me!

> Alan G.

I just making a small script to manipulate visio object attributes in my 
network documentation via com,
colouring the PCs based on the HDD free space or memory size, owner 
department ..., labelling with computername or assetnumber.
It works now from Python prompt. I just wanted to put this functionality 
into a small wxpython application and building up the menus like 
pythoncard. So, when there was a functionname like OnMenuShowAssetNumber, 
I would append a new menuitem with ShowAssetNumber.



Yours sincerely, 
______________________________
Janos Juhasz 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060727/15aad7bf/attachment.html 

From pythontut at pusspaws.net  Thu Jul 27 08:50:05 2006
From: pythontut at pusspaws.net (Dave S)
Date: Thu, 27 Jul 2006 07:50:05 +0100
Subject: [Tutor] open(file, 'rw') problem
Message-ID: <200607270750.06164.pythontut@pusspaws.net>

Good morning,

I am having a problem with file open, read & write. The example shows my 
problem. I would have expected it to print a sequence 1,2,3,4 incrementing 
every time it is run. 

#!/usr/bin/env python
import os, shutil, time

basher_dir = '/home/dave/PodCasts'

bit_bucket = basher_dir + '/xbit_bucket'
cd_count = bit_bucket + '/xcd_count'

if not os.path.isfile(cd_count):
	f = open(cd_count, 'w')
	f.write('0')
	f.close()
	
f = open(cd_count,'rw')
n = int(f.read())
n += 1

print n
f.seek(0)
f.write(str(n))
f.close()

Instead I get ...

dave at dave-comp:~/my_files/python_develop/unison/podsplit$ ./test.py
1
Traceback (most recent call last):
  File "./test.py", line 20, in ?
    f.write(str(n))
IOError: [Errno 9] Bad file descriptor
dave at dave-comp:~/my_files/python_develop/unison/podsplit$

It appears to be a problem with me opening the file as 'rw' although I have 
googled and opening as 'rw' appears legal. Can you only open a file as 'r' 
or 'w' -  ie open & close the file twice ?

Any ideas

Cheers

Dave

From alan.gauld at freenet.co.uk  Thu Jul 27 09:31:20 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 27 Jul 2006 08:31:20 +0100
Subject: [Tutor] The In Operator
References: <f445d9050607262019v2ee66096wed45e6658354e6db@mail.gmail.com>
Message-ID: <001d01c6b14e$a7baf210$0201a8c0@XPpro>

>I am trying to make my way through a book on Python ("Python 
>Ptogramming for
> the Absolute Beginner") and have run into some code in the book (and 
> on the
> author's accompanying CD) that won't work.  I suspect that it might 
> be
> because my version of Python is too old (2.1).

Your diagnosis is correct.
The in operator didn't work on dictionaries until 2.3 (I think)
It did work on lists/tuples and it worked for single characters in 
strings
(but not for substrings). By 2.43 both of the abiove failings had been 
fixed.

But you can fix it in this case easily enough:

> if "Dancing Baloney" in geek:

   if "Dancing Baloney" in geek.keys():

Should work.

Alan G. 



From alan.gauld at freenet.co.uk  Thu Jul 27 09:37:00 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 27 Jul 2006 08:37:00 +0100
Subject: [Tutor] remove function
References: <20060727025946.80509.qmail@web51605.mail.yahoo.com>
Message-ID: <002701c6b14f$78ae7630$0201a8c0@XPpro>

> def remove(self):
>   maxi = 0
>   for i in range(1, len(self.items)):
>      if self.items[i] > self.items[maxi]:
>         maxi = i
>      item = self.items[maxi]
> 
>   return item
> 
> My question concerns the remove function.  The
> function returns the maximum value.  However, I'm
> curious about self.items[maxi:maxi+1] = [].  

Me too. Where did you find that line?

> would he or she want to remove that value and the one
> next to it (maxi+1)?  Or am I misunderstanding 
> self.items[maxi:maxi+1] = [] ?

Slicing does not include the top number, it works 
like range() Thus a slice [3:4] only includes [3]

> As an aside, I can't figure out how to respond to
> topics on this list.

Use Reply-All... or if you don;t have that simply add 
the tutor address to the cc list.

Alan G.


From pythontut at pusspaws.net  Thu Jul 27 10:12:11 2006
From: pythontut at pusspaws.net (Dave S)
Date: Thu, 27 Jul 2006 09:12:11 +0100
Subject: [Tutor] open(file, 'rw') problem
In-Reply-To: <200607270750.06164.pythontut@pusspaws.net>
References: <200607270750.06164.pythontut@pusspaws.net>
Message-ID: <200607270912.12246.pythontut@pusspaws.net>


On Thursday 27 July 2006 09:08, Andre Engels wrote:
> 2006/7/27, Dave S <pythontut at pusspaws.net>:
> > It appears to be a problem with me opening the file as 'rw' although I
> > have googled and opening as 'rw' appears legal. Can you only open a file
> > as 'r' or 'w' -  ie open & close the file twice ?
>
> If you use "open(filename, 'rw')", the 'w' does not have effect, and
> you have opened the file read-only. To do what you want to do (both
> read and write with a file), you can use "open(filename, 'r+')"
> instead.

Ahh .. thanks for the heads up - I thought there had to be a better way

Cheers

dave

From alan.gauld at btinternet.com  Thu Jul 27 11:25:39 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 27 Jul 2006 10:25:39 +0100
Subject: [Tutor] Tutor Digest, Vol 29, Issue 68
References: <mailman.32036.1153943665.27774.tutor@python.org>
	<OF3CCD9DCF.6AB90130-ONC12571B8.001F88AE-C12571B8.002103F6@velux.com>
Message-ID: <eaa0qr$arf$1@sea.gmane.org>

> I just making a small script to manipulate visio object attributes 
> in my
> network documentation via com,

OK so far :-)

> It works now from Python prompt. I just wanted to put this 
> functionality
> into a small wxpython application and building up the menus like
> pythoncard.

And Ok with this I think, but....
Are you actually using PythonCard or are you using wxPython directly?

> So, when there was a functionname like OnMenuShowAssetNumber,
> I would append a new menuitem with ShowAssetNumber.

OK, But I still don't see why you need getattr.
Its your code, you know what the functions are, you can build
the menu directly. Why use getattr?

Alan G. 




From janos.juhasz at VELUX.com  Thu Jul 27 12:18:33 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 27 Jul 2006 12:18:33 +0200
Subject: [Tutor] Tutor Digest, Vol 29, Issue 68
In-Reply-To: <mailman.32134.1153992360.27774.tutor@python.org>
Message-ID: <OF58C7D1F9.BDE1CE08-ONC12571B8.00368937-C12571B8.0038A18A@velux.com>

Dear Alan,

> > It works now from Python prompt. I just wanted to put this
> > functionality
> > into a small wxpython application and building up the menus like
> > pythoncard.

> And Ok with this I think, but....
> Are you actually using PythonCard or are you using wxPython directly?

wxPython directly.

> > So, when there was a functionname like OnMenuShowAssetNumber,
> > I would append a new menuitem with ShowAssetNumber.

> OK, But I still don't see why you need getattr.
> Its your code, you know what the functions are, you can build
> the menu directly. Why use getattr?

> Alan G.

It just tried to do it another way.
There is a file for wx, and another for visio, they aren't joined 
together.
wx is filled up based on the functionnames of the other.


class ShellFrame(wx.Frame): 
    def __init__(self, parent=None, id=-1, title='PyCrustVisio'):
        ...
        self.FillUpMenu()

    def FillUpMenu(self):
        MenuItems = [item for item in dir(visio) if 
item.startswith('OnMenu')]
        for FunctionName in MenuItems:
            menuID = wx.NewId()
            menuText = FunctionName[6:]
            self.menu.Append(menuID, menuText, menuText)
            self.Bind(wx.EVT_MENU, getattr(visio, FunctionName), 
id=menuID)



So I can write it with this way:
self.Bind(wx.EVT_MENU, getattr(visio, FunctionName), id=menuID)

Every function in the visio module starting with 'OnMenu' will be appeared 
in the application menu.

Probably its a bad habit, but it is just for trial.



Yours sincerely, 
______________________________
J?nos Juh?sz 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060727/6dbb64d8/attachment.html 

From kent37 at tds.net  Thu Jul 27 12:39:25 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 27 Jul 2006 06:39:25 -0400
Subject: [Tutor] The In Operator
In-Reply-To: <f445d9050607262019v2ee66096wed45e6658354e6db@mail.gmail.com>
References: <f445d9050607262019v2ee66096wed45e6658354e6db@mail.gmail.com>
Message-ID: <44C897DD.7040606@tds.net>

Steve Haley wrote:
> Finally, my version of 2.1 came bundled with other software (ESRI 
> ArcView).  Is anyone out there an ESRI user who can tell me if I can I 
> go ahead and download a newer version without messing up my ArcView 
> installation?
Google is your friend:
http://forums.esri.com/Thread.asp?c=93&f=1729&t=157014&mc=43
http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=26872

Kent


From kent37 at tds.net  Thu Jul 27 12:48:05 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 27 Jul 2006 06:48:05 -0400
Subject: [Tutor] Reg Ex in python
In-Reply-To: <BAY102-F26A2F39AEA9BEB7C3390A9D7580@phx.gbl>
References: <BAY102-F26A2F39AEA9BEB7C3390A9D7580@phx.gbl>
Message-ID: <44C899E5.9070109@tds.net>

The Fulch wrote:
> Hi,
>  
> Given two strings I need to determine weather or not one of the 
> strings is a subset of the other string. In at least one of the 
> strings there is a star "*" which can be any character or a null there 
> is a maximum of one star per string.
>  
> So basically I want the function to return true if you try to match
> st*r and star
> st*r and str
> sta*rshine and star
> st* and star
> st*r and stststar
> t*r and s*ar
I'm not sure how this is a match, can you clarify?
>  
>  
> I tried making a function which splits the input by "*" but don't 
> really know how to continue after that. I have been trying to use reg 
> ex, but with little success.

If just one string has a match, you can change the * to .* and get a 
regular expression to search for in the other string.
In [1]: import re

In [2]: s1='st*r'

In [3]: s2='star'

In [4]: regex = s1.replace('*', '.*')

If the search succeeds, it returns a match object:
In [5]: re.search(regex, s2)
Out[5]: <_sre.SRE_Match object at 0x00E3F6B0>

If the search fails, it returns None:
In [6]: re.search(regex, 'foo')

In [7]:

Kent


From kent37 at tds.net  Thu Jul 27 13:08:12 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 27 Jul 2006 07:08:12 -0400
Subject: [Tutor] remove function
In-Reply-To: <20060727041239.6665.qmail@web51601.mail.yahoo.com>
References: <20060727041239.6665.qmail@web51601.mail.yahoo.com>
Message-ID: <44C89E9C.3040008@tds.net>

Christopher Spears wrote:
> My apologies to everyone.  Here is the complete code:
>
>
> class PriorityQueue:
> 	def __init__(self):
> 		self.items = []
> 		
> 	def isEmpty(self):
> 		return self.items == []
> 		
> 	def insert(self, item):
> 		self.items.append(item)
> 		
> 	def remove(self):
> 		maxi = 0
> 		for i in range(1, len(self.items)):
> 			if self.items[i] > self.items[maxi]:
> 				maxi = i
> 		item = self.items[maxi]
> 		self.items[maxi:maxi+1] = []
> 		return item
>   
Slice indexing in Python is up-to-but-not-including. So

  self.items[maxi:maxi+1] = []

means, replace the slice of self.items, that starts at maxi and goes up 
to but not including maxi+1, with the empty list. So it is effectively 
deleting self.items[maxi], which could also be written as
  del self.items[maxi]

or combine it with the line above as
  item = self.items.pop(maxi)

By the way if this class is for production use, rather than learning, 
you should look into the heapq module, it implements a much more 
efficient algorithm than the one above. heapq implements a min heap, not 
a max heap, so you need some kind of wrapper for your items to get them 
in the order you want.

Kent


From dkuhlman at rexx.com  Thu Jul 27 17:52:00 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Thu, 27 Jul 2006 08:52:00 -0700
Subject: [Tutor] Notes on namespaces, scopes, etc
Message-ID: <20060727155200.GA94348@cutter.rexx.com>

I've written up a few notes on Python namespaces and scopes.  If
anyone has corrections, comments, or suggestions, I'd appreciate
them. You can find my comments here:

    http://www.rexx.com/~dkuhlman/python_comments.html#namespaces

I wrote these notes because I found that I did not understand
Python namespaces as well as I thought I did.  Writing the
comments seemed like a good way to work through and learn about
namespaces, scopes, variables, bindings, etc.

By the way, I was motivated to write these notes because of the
"loops to assign variables" thread on this list a few days ago.
I'm hoping that my notes show that I learned from that thread.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From alan.gauld at btinternet.com  Thu Jul 27 18:14:50 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 27 Jul 2006 17:14:50 +0100
Subject: [Tutor] Tutor Digest, Vol 29, Issue 68
References: <mailman.32134.1153992360.27774.tutor@python.org>
	<OF58C7D1F9.BDE1CE08-ONC12571B8.00368937-C12571B8.0038A18A@velux.com>
Message-ID: <eaaoq2$v86$1@sea.gmane.org>

> There is a file for wx, and another for visio,
> they aren't joined together.
> wx is filled up based on the functionnames of the other.

Aha! This is the missing bit of info.

In that case using getattr makes sense.
The example you gave earlier showed you using getattr on
the local file and seemed to suggest to me that was what
was causing your problem - I just couldn't think why
you'd want to do that!

    def FillUpMenu(self):
        MenuItems = [item for item in dir(visio) if
item.startswith('OnMenu')]
        for FunctionName in MenuItems:

You should probably make sure that the names are all
callable too. Otherwise, if there is a variable called
OnXXX then you will assign it to a menu item and
it will break!

> Every function in the visio module starting with 'OnMenu'
> will be appeared in the application menu.

The way you have written it everything in the dir() result
starting OnXXX will be in the menu - they may not all be
functions!

HTH,

Alan G. 




From alan.gauld at btinternet.com  Thu Jul 27 18:34:13 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 27 Jul 2006 17:34:13 +0100
Subject: [Tutor] Notes on namespaces, scopes, etc
References: <20060727155200.GA94348@cutter.rexx.com>
Message-ID: <eaapue$3qh$1@sea.gmane.org>

Hi Dave,

You are causing yourself some confusion by still treating variables
as something other than a name. Your first paragraph says:

(Actually, functions and classes are just variables that hold
references to function and class objects.)

Which is wrong. variables are simply names that refer to objects,
which includes functions and classes(and instances of classes)
Thus a function is never a variable. variables refer to functions.

In Computer Science terms a function is a lamda expression
and a def in Python should be a shorthand way of doing

var = lambda params... : expression

Unfortunately, in practice, in Python it's the other way around.
The lambda is really an alternative for

def var(params...):
    return expression

But it is important to realize that names in Python - all names - are
simply references to objects of some kind. and that classes, 
instances,
functions, numbers, lists, characters etc  are all objects in this 
sense.

-------------
On the term Global you should probably specifically note that
in Python global really means module scope. In some languages
global implies visible across all modules(like Python built-ins),
in Python it just means visible within the current file(aka module)
--------------
Typo (I assume):
"For example, in the following function, the variable count is not 
bound
to a value until the end of the second iteration of the loop"

I assume you meant to say x not count?
count is bound at the end of *every* iteration.
--------------
On the binding section when addressing formal parameters its worth
pointing out that the binding occurs at function *invocation* not at
definition. Also the parameters get rebound on each invocation.
Finally, default arguments are only bound once.
---------------
On dir() and vars() - its worth pointing out that both functions take
an optional argument and are not restricted to showing the current
local symbol table values.
----------------

A good first attempt, hopefully the above comments can tighten it
up a wee bit more.

Thanks for sharing, these kind of web notes are always handy for
folks searching for additional help - in addition to yourself of 
course!

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



"Dave Kuhlman" <dkuhlman at rexx.com> wrote in message 
news:20060727155200.GA94348 at cutter.rexx.com...
> I've written up a few notes on Python namespaces and scopes.  If
> anyone has corrections, comments, or suggestions, I'd appreciate
> them. You can find my comments here:
>
>    http://www.rexx.com/~dkuhlman/python_comments.html#namespaces
>
> I wrote these notes because I found that I did not understand
> Python namespaces as well as I thought I did.  Writing the
> comments seemed like a good way to work through and learn about
> namespaces, scopes, variables, bindings, etc.
>
> By the way, I was motivated to write these notes because of the
> "loops to assign variables" thread on this list a few days ago.
> I'm hoping that my notes show that I learned from that thread.
>
> Dave
>
> -- 
> Dave Kuhlman
> http://www.rexx.com/~dkuhlman
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




From kent37 at tds.net  Thu Jul 27 18:46:44 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 27 Jul 2006 12:46:44 -0400
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <20060727155200.GA94348@cutter.rexx.com>
References: <20060727155200.GA94348@cutter.rexx.com>
Message-ID: <44C8EDF4.5020809@tds.net>

Dave Kuhlman wrote:
> I've written up a few notes on Python namespaces and scopes.  If
> anyone has corrections, comments, or suggestions, I'd appreciate
> them. You can find my comments here:
>
>     http://www.rexx.com/~dkuhlman/python_comments.html#namespaces

You wrote, "If a variable is assigned a value /anywhere/ in a scope 
(...), then that variable is local to that scope. Otherwise, the 
variable is global."

You omit the enclosing scope and the builtin namespace. A variable can 
be defined in
- local scope
- any of zero or more enclosing scopes
- global scope
- builtin namespace

Names are also bound by for statements and except clauses.

You might note that augmented assignment (e.g. a += 1) counts as 
assignment in the local scope. This is a common cause of UnboundLocalError:

In [5]: a=1

In [6]: def foo():
   ...:     a+=1
   ...:
   ...:

In [7]: foo()
---------------------------------------------------------------------------
exceptions.UnboundLocalError                         Traceback (most 
recent call last)

D:\Projects\e3po\<ipython console>

D:\Projects\e3po\<ipython console> in foo()

UnboundLocalError: local variable 'a' referenced before assignment


I think modifying globals() is guaranteed to work. Modifying locals() 
only works at global scope, i.e. when locals() is globals().

You wrote, "Note that for lexically/statically nested scopes (for 
example, a function defined inside a function), it seems that globals() 
and locals() still give access to all items in the accessible 
namespaces." I'm not sure what you mean by this. locals() doesn't give 
access to items in nested scopes:

In [1]: x=1

In [2]: def maker():
   ...:     y=2
   ...:     def showLocals():
   ...:         z=3
   ...:         print locals()
   ...:     return showLocals
   ...:

In [3]: sl=maker()

In [4]: sl()
{'z': 3}

See also
http://docs.python.org/ref/naming.html

Kent



From carroll at tjc.com  Thu Jul 27 22:41:16 2006
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 27 Jul 2006 13:41:16 -0700 (PDT)
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <20060727155200.GA94348@cutter.rexx.com>
Message-ID: <Pine.LNX.4.44.0607271340210.29738-100000@violet.rahul.net>

On Thu, 27 Jul 2006, Dave Kuhlman wrote:

> I've written up a few notes on Python namespaces and scopes. 

I can't add any suggestions, but I understand namespaces and scopes 
imperfectly, and really look forward to reading your final product.


From the_evil_laugh at hotmail.com  Fri Jul 28 02:46:49 2006
From: the_evil_laugh at hotmail.com (The Fulch)
Date: Fri, 28 Jul 2006 10:46:49 +1000
Subject: [Tutor] Regex in Python
In-Reply-To: <mailman.32180.1154018822.27774.tutor@python.org>
Message-ID: <BAY102-F1226089ACA5F03170CC35ED7590@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060728/7fc1ffaa/attachment.html 

From kent37 at tds.net  Fri Jul 28 04:48:41 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 27 Jul 2006 22:48:41 -0400
Subject: [Tutor] Regex in Python
In-Reply-To: <BAY102-F1226089ACA5F03170CC35ED7590@phx.gbl>
References: <BAY102-F1226089ACA5F03170CC35ED7590@phx.gbl>
Message-ID: <44C97B09.2030306@tds.net>

The Fulch wrote:
>
> Thanks for you help,
>
> Another question, is there a way of comparing two regexs?
>
> EG
>
> s1='st*r'
> s2='s*ar'
>
> r1=s1.replace('*','.*')
> r2=s2.replace('*','.*')
>
> re.match(r1,r2)?
>
That will do something, though I don't know if it is what you want. r1 
and r2 are both strings, so you can use one to search in the other. But 
what do you want it to do?

BTW re.match() and re.search() do different things, which one do you want?
>
> =============
>
> Also how do I use  <_sre.SRE_Match object at 0x00E3F6B0> in my program?
> If its a match, I want to be able to return 'true' or 1
>
You can probably just return the match object, if you test for it in an 
if statement it will test as true. If you really want a boolean value 
then say
  return re.search(...) is not None

Kent
>
> Mike
> >The Fulch wrote:
> > > Hi,
> > >
> > > Given two strings I need to determine weather or not one of the
> > > strings is a subset of the other string. In at least one of the
> > > strings there is a star "*" which can be any character or a null there
> > > is a maximum of one star per string.
> > >
> > > So basically I want the function to return true if you try to match
> > > st*r and star
> > > st*r and str
> > > sta*rshine and star
> > > st* and star
> > > st*r and stststar
> > > t*r and s*ar
> >I'm not sure how this is a match, can you clarify?
> > >
> > >
> > > I tried making a function which splits the input by "*" but don't
> > > really know how to continue after that. I have been trying to use reg
> > > ex, but with little success.
> >
> >If just one string has a match, you can change the * to .* and get a
> >regular expression to search for in the other string.
> >In [1]: import re
> >
> >In [2]: s1='st*r'
> >
> >In [3]: s2='star'
> >
> >In [4]: regex = s1.replace('*', '.*')
> >
> >If the search succeeds, it returns a match object:
> >In [5]: re.search(regex, s2)
> >Out[5]: <_sre.SRE_Match object at 0x00E3F6B0>
> >
> >If the search fails, it returns None:
> >In [6]: re.search(regex, 'foo')
> >
> >In [7]:
> >
> >Kent
> >
>



From hokkakada at khmeros.info  Fri Jul 28 06:51:03 2006
From: hokkakada at khmeros.info (kakada)
Date: Fri, 28 Jul 2006 11:51:03 +0700
Subject: [Tutor] playing around with function
Message-ID: <44C997B7.10307@khmeros.info>

Hello,

I have problem with function jumping:

in my class, I have three function here:

def gotoNextFuzzy(self):
        state = "isfuzzy"
        self.navigationNext(state)

def gotoNextFuzzy(self):
        state = "isapproved"
        self.navigationNext(state)

def navigationNext(self,state):
        if (self.getCurrentItem() == 0):
            return 0
        id = int(self.item.text(0))
        for i in range(id,775):
            i += 1
            state =
            if (i == 775):
                self.warningMessage()
            else:
                    if self.store.units[i].state():
                        curItem = self.ui.treeWidget.topLevelItem(i)
                        self.ui.treeWidget.setCurrentItem(curItem)
                       
self.ui.txtSource.setHtml(self.store.units[i].source)
                       
self.ui.txtTarget.setHtml(self.store.units[i].target)
                        break
and one calling built-in function:
   
QtCore.QObject.connect(self.ui.btnNF,QtCore.SIGNAL("pressed()"),self.gotoNextFuzzy)
and error said:
Attribute Error: no attribute state

------------
Please understand my idea that I just want to replace the state in line

if self.store.units[i].state():

with isfuzzy or isapproved or istranslated...

and if I do as follow:

if self.store.units[i].isfuzzy():
then it works.
----------------
please also note that:
isfuzzy()
isapproved()
istranslated()

are the boolean function in other class.
--------------------

Does anybody have any solution on this coding style?

Thanks,
da






From rabidpoobear at gmail.com  Fri Jul 28 09:19:33 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 28 Jul 2006 02:19:33 -0500
Subject: [Tutor] playing around with function
In-Reply-To: <44C997B7.10307@khmeros.info>
References: <44C997B7.10307@khmeros.info>
Message-ID: <44C9BA85.8070402@gmail.com>

Where is self.ui initialized?
are these functions part of a class?
Why didn't you send the __init__ method?
why didn't you send the whole class structure?


>def gotoNextFuzzy(self):
>        state = "isfuzzy"
>        self.navigationNext(state)

>def gotoNextFuzzy(self):
>        state = "isapproved"
>        self.navigationNext(state)


These functions both have the same name.
They'll just overwrite each other.


 >def navigationNext(self,state):
 >     if (self.getCurrentItem() == 0):
 >         return 0
 >     id = int(self.item.text(0))
 >     for i in range(id,775):
 >         i += 1
 >         state =
state = what?

> and error said:
> Attribute Error: no attribute state
>
>   
If you give us the whole source (ideally) and the full stack trace of 
the error message it's more helpful.
I know you explain further down where the error occurs.
> ------------
> Please understand my idea that I just want to replace the state in line
>
> if self.store.units[i].state():
>
> with isfuzzy or isapproved or istranslated...
>
> and if I do as follow:
>
> if self.store.units[i].isfuzzy():
> then it works.
>   
it works but it doesn't work how you want it to work or what?
> ----------------
> please also note that:
> isfuzzy()
> isapproved()
> istranslated()
>
> are the boolean function in other class.
>   
...
> --------------------
>
> Does anybody have any solution on this coding style?
>
>   
I don't understand your coding style.
I suspect it's because you didn't include all of your code,
but if you did, I have no idea what you're trying to accomplish.
> Thanks,
>   
Just tryin' to help.
> da
>   
Luke

From alan.gauld at btinternet.com  Fri Jul 28 10:05:10 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 28 Jul 2006 09:05:10 +0100
Subject: [Tutor] playing around with function
References: <44C997B7.10307@khmeros.info>
Message-ID: <eacgg0$atp$1@sea.gmane.org>


"kakada" <hokkakada at khmeros.info> wrote
> I have problem with function jumping:

I'm not sure what you mean by "function jumping" but I'll
make a few comments...

> in my class, I have three function here:
>
> def gotoNextFuzzy(self):
>        state = "isfuzzy"
>        self.navigationNext(state)
>
> def gotoNextFuzzy(self):
>        state = "isapproved"
>        self.navigationNext(state)

As Luke pointed out these are the same so only
the second one will actually be present.

Note that you set state but it is only a local variable
within the method, it will not persist outside the method
so you cannot access it, I suspect you meant to write

self.state = "isapproved"

> def navigationNext(self,state):
>        if (self.getCurrentItem() == 0):
>            return 0
>        id = int(self.item.text(0))
>        for i in range(id,775):
>            i += 1

I'm not sure why you immediately add one.
you could change the values in range() to get the
same result:

for i in range(1,776):


>            state =

Its not clear what you are assigning here? An unprintable
character or a typo?

>            if (i == 775):
>                self.warningMessage()
>            else:
>                    if self.store.units[i].state():
>                        curItem = self.ui.treeWidget.topLevelItem(i)
>                        self.ui.treeWidget.setCurrentItem(curItem)
>
> self.ui.txtSource.setHtml(self.store.units[i].source)
>
> self.ui.txtTarget.setHtml(self.store.units[i].target)
>                        break

The indentation changes here but you refer to self which
suggests they should be inside the class. I'm not sure if
thats intentional(and thus an error?) or just a freak of email...

> and one calling built-in function:
>
> QtCore.QObject.connect(self.ui.btnNF,QtCore.SIGNAL("pressed()"),self.gotoNextFuzzy)
> and error said:
> Attribute Error: no attribute state

OK, but at what point did it say that? What does the stack trace in 
the error say?

> and if I do as follow:
>
> if self.store.units[i].isfuzzy():
> then it works.

So what is the problem? Like Luke I'm not sure I understand what
you are trying to do here.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




From hokkakada at khmeros.info  Fri Jul 28 10:57:51 2006
From: hokkakada at khmeros.info (kakada)
Date: Fri, 28 Jul 2006 15:57:51 +0700
Subject: [Tutor] playing around with function
In-Reply-To: <eacgg0$atp$1@sea.gmane.org>
References: <44C997B7.10307@khmeros.info> <eacgg0$atp$1@sea.gmane.org>
Message-ID: <44C9D18F.7020701@khmeros.info>

Thank Alan and Luke,

My coding is divided up into many modules and import from one to another.
Here is my editor.py interface.


#!/usr/bin/python
# -*- coding: utf8 -*-

import sys
import application_rc
from PyQt4 import QtCore, QtGui
from ui_editor import Ui_MainWindow
from translate.storage import factory
import Display


class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.numApproved = 0
        self.numFuzzy = 0
        self.numTranslated = 0

        #events go here
        QtCore.QObject.connect(self.ui.treeWidget,
QtCore.SIGNAL("itemSelectionChanged()"), self.updateField)
        QtCore.QObject.connect(self.ui.cmbMsgFilter,
QtCore.SIGNAL("activated(int)"), self.setFilter)
       
QtCore.QObject.connect(self.ui.chkfuzzy,QtCore.SIGNAL("stateChanged(int)"),self.toggleFuzzy)
       
QtCore.QObject.connect(self.ui.chkapproved,QtCore.SIGNAL("toggled(bool)"),self.toggleApproved)
       
QtCore.QObject.connect(self.ui.btnsource2target,QtCore.SIGNAL("pressed()"),self.source2target)
       
QtCore.QObject.connect(self.ui.btnRemoveAllTU,QtCore.SIGNAL("pressed()"),self.removeAllTrans)
       
QtCore.QObject.connect(self.ui.btnNA,QtCore.SIGNAL("pressed()"),self.gotoNA)
       
QtCore.QObject.connect(self.ui.btnPA,QtCore.SIGNAL("pressed()"),self.gotoPA)
       
QtCore.QObject.connect(self.ui.btnNF,QtCore.SIGNAL("pressed()"),self.gotoNF)
       
QtCore.QObject.connect(self.ui.btnNT,QtCore.SIGNAL("pressed()"),self.gotoNT)
       
QtCore.QObject.connect(self.ui.btnNU,QtCore.SIGNAL("pressed()"),self.gotoNU)
       
QtCore.QObject.connect(self.ui.btnPF,QtCore.SIGNAL("pressed()"),self.gotoPF)
       
QtCore.QObject.connect(self.ui.btnPU,QtCore.SIGNAL("pressed()"),self.gotoPU)
       
QtCore.QObject.connect(self.ui.btnPT,QtCore.SIGNAL("pressed()"),self.gotoPT)
        QtCore.QMetaObject.connectSlotsByName(self)




    def newWindows(self):
        print "new windows"
        self.other = Ui_MainWindow()
        self.other.windowList.append(other)
        self.other.show()

    def openFile(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self, self.tr("Open
Xliff File"),
                                                    
QtCore.QDir.currentPath(),
                                                     self.tr("XLIFF
Files (*.xliff *.xml *.xlf);;All File(*.*)"))

        if fileName.isEmpty():
            self.setWindowTitle( self.tr("WordForge Translation Editor
v.05 - ") + "untitle")
        else:
            self.setWindowTitle( self.tr("WordForge Translation Editor
v.05 - ") + str(fileName))
        self.title = fileName
        self.store = factory.getobject(str(fileName))
        self.uf = Display.Display(self.ui, self.store)

        import FirstShow
        fs = FirstShow.FirstShow(self.ui, self.store)
        fs.firstShow()
        
    def save(self):
        if self.title.isEmpty():
            return self.saveAs()
        else:
            return self.store.savefile(str(self.title))

    def saveAs(self):
        fileName = QtGui.QFileDialog.getSaveFileName(self, self.tr("Save
Xliff File"),
                                                    
QtCore.QDir.currentPath(),
                                                     self.tr("XLIFF
Files (*.xliff *.xml *.xlf)"))
        if fileName.isEmpty():
            return

        self.store.savefile(str(fileName))

        self.ui.cmbMsgFilter.addItem ('Not filtered')
        self.ui.cmbMsgFilter.addItem ('fuzzy')
        self.ui.cmbMsgFilter.addItem ('translated')
        self.ui.cmbMsgFilter.addItem ('untranslated')


    def getCurrentItem(self):
            try:
                self.item = self.ui.treeWidget.selectedItems()[0]
            except IndexError:
                return False
           
# I have change my code style like this:

    def gotoNF(self):
        self.state = "NF"
        self.navigationNext(self.state)
    def gotoNT(self):
        self.state = "NT"
        self.navigationNext(self.state)
    def gotoNU(self):
        self.state = "NU"
        self.navigationNext(self.state)
    def gotoNA(self):
        self.state = "NA"
        self.navigationNext(self.state)
    
    def gotoPA(self):
        self.state = "PA"
        self.navigationPrevious(self.state)
    def gotoPT(self):
        self.state = "PT"
        self.navigationPrevious(self.state)        
    def gotoPU(self):
        self.state = "PU"
        self.navigationPrevious(self.state)            
    def gotoPF(self):
        self.state = "PF"
        self.navigationPrevious(self.state)        
    def navigated(self):
        if (self.state == 'NF') and
(self.store.units[int(self.id)].isfuzzy()):
            return True
        if (self.state == 'PF') and
(self.store.units[int(self.id)].isfuzzy()):
            return True
        if (self.state == 'NT') and
(self.store.units[int(self.id)].istranslated()):
            return True
        if (self.state == 'PT') and
(self.store.units[int(self.id)].istranslated()):
            return True
        if (self.state == 'NU') and
(self.store.units[int(self.id)].isuntranslated()):
            return True
        if (self.state == 'PU') and
(self.store.units[int(self.id)].isuntranslated()):
            return True
        if (self.state == 'NA') and
(self.store.units[int(self.id)].isapproved()):
            return True
        if (self.state == 'PA') and
(self.store.units[int(self.id)].isapproved()):
            return True
    def navigationNext(self,state):
        if (self.getCurrentItem() == 0):
            return 0
        self.id = int(self.item.text(0))
        self.id += 1
        for i in range(self.id,775):
            self.id = i
            if (i == 775):
                pass
                #self.warningMessage()
            else:
                if self.navigated():
                    curItem = self.ui.treeWidget.topLevelItem(self.id)
                    self.ui.treeWidget.setCurrentItem(curItem)
                   
self.ui.txtSource.setHtml(self.store.units[self.id].source)
                   
self.ui.txtTarget.setHtml(self.store.units[self.id].target)
                    break
                else: continue
    
    def navigationPrevious(self,state):
        if (self.getCurrentItem() == 0):
            return 0
        self.id = int(self.item.text(0))
        self.id -= 1
        for i in range(self.id,0,-1):
            self.id = i
            if (self.id == 0):
                pass
                #self.warningMessage()
            else:
                if self.navigated():
                    curItem = self.ui.treeWidget.topLevelItem(self.id)
                    self.ui.treeWidget.setCurrentItem(curItem)
                   
self.ui.txtSource.setHtml(self.store.units[self.id].source)
                   
self.ui.txtTarget.setHtml(self.store.units[self.id].target)
                    break      
                else: continue
                
#class MessageDialog(QtGui.QDialog):
    #def warningMessage(self):    
        #reply = QtGui.QMessageBox.warning(self,
self.tr("QMessageBox.showWarning()"),
                                        #Dialong.MESSAGE,
self.tr("Continue to the begining"),
                                        #self.tr("&Yes"))
        #if reply == 0:
            #self.warningLabel.setText(self.tr("Yes"))
        #else:
            #self.warningLabel.setText(self.tr("Cancel"))




if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    editor = MainWindow()
    editor.show()
    sys.exit(app.exec_())


From hokkakada at khmeros.info  Fri Jul 28 11:01:19 2006
From: hokkakada at khmeros.info (kakada)
Date: Fri, 28 Jul 2006 16:01:19 +0700
Subject: [Tutor] playing around with function
In-Reply-To: <44C9D18F.7020701@khmeros.info>
References: <44C997B7.10307@khmeros.info> <eacgg0$atp$1@sea.gmane.org>
	<44C9D18F.7020701@khmeros.info>
Message-ID: <44C9D25F.1000600@khmeros.info>

???????? kakada:
> Thank Alan and Luke,
>
> My coding is divided up into many modules and import from one to another.
> Here is my editor.py interface.
>
>
> #!/usr/bin/python
> # -*- coding: utf8 -*-
>
> import sys
> import application_rc
> from PyQt4 import QtCore, QtGui
> from ui_editor import Ui_MainWindow
> from translate.storage import factory
> import Display
>
>
> class MainWindow(QtGui.QMainWindow):
>     def __init__(self):
>         QtGui.QMainWindow.__init__(self)
>
>         self.ui = Ui_MainWindow()
>         self.ui.setupUi(self)
>
>         self.numApproved = 0
>         self.numFuzzy = 0
>         self.numTranslated = 0
>
>         #events go here
>         QtCore.QObject.connect(self.ui.treeWidget,
> QtCore.SIGNAL("itemSelectionChanged()"), self.updateField)
>         QtCore.QObject.connect(self.ui.cmbMsgFilter,
> QtCore.SIGNAL("activated(int)"), self.setFilter)
>        
> QtCore.QObject.connect(self.ui.chkfuzzy,QtCore.SIGNAL("stateChanged(int)"),self.toggleFuzzy)
>        
> QtCore.QObject.connect(self.ui.chkapproved,QtCore.SIGNAL("toggled(bool)"),self.toggleApproved)
>        
> QtCore.QObject.connect(self.ui.btnsource2target,QtCore.SIGNAL("pressed()"),self.source2target)
>        
> QtCore.QObject.connect(self.ui.btnRemoveAllTU,QtCore.SIGNAL("pressed()"),self.removeAllTrans)
>        
> QtCore.QObject.connect(self.ui.btnNA,QtCore.SIGNAL("pressed()"),self.gotoNA)
>        
> QtCore.QObject.connect(self.ui.btnPA,QtCore.SIGNAL("pressed()"),self.gotoPA)
>        
> QtCore.QObject.connect(self.ui.btnNF,QtCore.SIGNAL("pressed()"),self.gotoNF)
>        
> QtCore.QObject.connect(self.ui.btnNT,QtCore.SIGNAL("pressed()"),self.gotoNT)
>        
> QtCore.QObject.connect(self.ui.btnNU,QtCore.SIGNAL("pressed()"),self.gotoNU)
>        
> QtCore.QObject.connect(self.ui.btnPF,QtCore.SIGNAL("pressed()"),self.gotoPF)
>        
> QtCore.QObject.connect(self.ui.btnPU,QtCore.SIGNAL("pressed()"),self.gotoPU)
>        
> QtCore.QObject.connect(self.ui.btnPT,QtCore.SIGNAL("pressed()"),self.gotoPT)
>         QtCore.QMetaObject.connectSlotsByName(self)
>
>
>
>
>     def newWindows(self):
>         print "new windows"
>         self.other = Ui_MainWindow()
>         self.other.windowList.append(other)
>         self.other.show()
>
>     def openFile(self):
>         fileName = QtGui.QFileDialog.getOpenFileName(self, self.tr("Open
> Xliff File"),
>                                                     
> QtCore.QDir.currentPath(),
>                                                      self.tr("XLIFF
> Files (*.xliff *.xml *.xlf);;All File(*.*)"))
>
>         if fileName.isEmpty():
>             self.setWindowTitle( self.tr("WordForge Translation Editor
> v.05 - ") + "untitle")
>         else:
>             self.setWindowTitle( self.tr("WordForge Translation Editor
> v.05 - ") + str(fileName))
>         self.title = fileName
>         self.store = factory.getobject(str(fileName))
>         self.uf = Display.Display(self.ui, self.store)
>
>         import FirstShow
>         fs = FirstShow.FirstShow(self.ui, self.store)
>         fs.firstShow()
>         
>     def save(self):
>         if self.title.isEmpty():
>             return self.saveAs()
>         else:
>             return self.store.savefile(str(self.title))
>
>     def saveAs(self):
>         fileName = QtGui.QFileDialog.getSaveFileName(self, self.tr("Save
> Xliff File"),
>                                                     
> QtCore.QDir.currentPath(),
>                                                      self.tr("XLIFF
> Files (*.xliff *.xml *.xlf)"))
>         if fileName.isEmpty():
>             return
>
>         self.store.savefile(str(fileName))
>
>         self.ui.cmbMsgFilter.addItem ('Not filtered')
>         self.ui.cmbMsgFilter.addItem ('fuzzy')
>         self.ui.cmbMsgFilter.addItem ('translated')
>         self.ui.cmbMsgFilter.addItem ('untranslated')
>
>
>     def getCurrentItem(self):
>             try:
>                 self.item = self.ui.treeWidget.selectedItems()[0]
>             except IndexError:
>                 return False
>            
> # I have change my code style like this:
>
>     def gotoNF(self):
>         self.state = "NF"
>         self.navigationNext(self.state)
>     def gotoNT(self):
>         self.state = "NT"
>         self.navigationNext(self.state)
>     def gotoNU(self):
>         self.state = "NU"
>         self.navigationNext(self.state)
>     def gotoNA(self):
>         self.state = "NA"
>         self.navigationNext(self.state)
>     
>     def gotoPA(self):
>         self.state = "PA"
>         self.navigationPrevious(self.state)
>     def gotoPT(self):
>         self.state = "PT"
>         self.navigationPrevious(self.state)        
>     def gotoPU(self):
>         self.state = "PU"
>         self.navigationPrevious(self.state)            
>     def gotoPF(self):
>         self.state = "PF"
>         self.navigationPrevious(self.state)        
>     def navigated(self):
>         if (self.state == 'NF') and
> (self.store.units[int(self.id)].isfuzzy()):
>             return True
>         if (self.state == 'PF') and
> (self.store.units[int(self.id)].isfuzzy()):
>             return True
>         if (self.state == 'NT') and
> (self.store.units[int(self.id)].istranslated()):
>             return True
>         if (self.state == 'PT') and
> (self.store.units[int(self.id)].istranslated()):
>             return True
>         if (self.state == 'NU') and
> (self.store.units[int(self.id)].isuntranslated()):
>             return True
>         if (self.state == 'PU') and
> (self.store.units[int(self.id)].isuntranslated()):
>             return True
>         if (self.state == 'NA') and
> (self.store.units[int(self.id)].isapproved()):
>             return True
>         if (self.state == 'PA') and
> (self.store.units[int(self.id)].isapproved()):
>             return True
>     def navigationNext(self,state):
>         if (self.getCurrentItem() == 0):
>             return 0
>         self.id = int(self.item.text(0))
>         self.id += 1
>         for i in range(self.id,775):
>             self.id = i
>             if (i == 775):
>                 pass
>                 #self.warningMessage()
>             else:
>                 if self.navigated():
>                     curItem = self.ui.treeWidget.topLevelItem(self.id)
>                     self.ui.treeWidget.setCurrentItem(curItem)
>                    
> self.ui.txtSource.setHtml(self.store.units[self.id].source)
>                    
> self.ui.txtTarget.setHtml(self.store.units[self.id].target)
>                     break
>                 else: continue
>     
>     def navigationPrevious(self,state):
>         if (self.getCurrentItem() == 0):
>             return 0
>         self.id = int(self.item.text(0))
>         self.id -= 1
>         for i in range(self.id,0,-1):
>             self.id = i
>             if (self.id == 0):
>                 pass
>                 #self.warningMessage()
>             else:
>                 if self.navigated():
>                     curItem = self.ui.treeWidget.topLevelItem(self.id)
>                     self.ui.treeWidget.setCurrentItem(curItem)
>                    
> self.ui.txtSource.setHtml(self.store.units[self.id].source)
>                    
> self.ui.txtTarget.setHtml(self.store.units[self.id].target)
>                     break      
>                 else: continue
>                 
> #class MessageDialog(QtGui.QDialog):
>     #def warningMessage(self):    
>         #reply = QtGui.QMessageBox.warning(self,
> self.tr("QMessageBox.showWarning()"),
>                                         #Dialong.MESSAGE,
> self.tr("Continue to the begining"),
>                                         #self.tr("&Yes"))
>         #if reply == 0:
>             #self.warningLabel.setText(self.tr("Yes"))
>         #else:
>             #self.warningLabel.setText(self.tr("Cancel"))
>
>
>
>
> if __name__ == "__main__":
>     app = QtGui.QApplication(sys.argv)
>     editor = MainWindow()
>     editor.show()
>     sys.exit(app.exec_())
>
>
>   
It is working like I want now, but I still not like this code style
(regarding navigation). It is too long.

Thx,
da

From kyxaxa at gmail.com  Fri Jul 28 11:43:12 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Fri, 28 Jul 2006 12:43:12 +0300
Subject: [Tutor] how to run python's Graphical User Interface for
	Environments in agents.py
Message-ID: <bf6cdbf10607280243k2a906822tb8c2141510cd5cb8@mail.gmail.com>

<http://groups.yahoo.com/group/aima-talk/message/703;_ylc=X3oDMTJwdmFudGkyBF9TAzk3MzU5NzE1BGdycElkAzMwOTU0MjUEZ3Jwc3BJZAMxNjAwOTQ4OTIzBG1zZ0lkAzcwMwRzZWMDZG1zZwRzbGsDdm1zZwRzdGltZQMxMTU0MDEzNzc4>
  I am reading "Artificial Intelligence: A Modern
Approach<javascript:if(confirm('http://aima.cs.berkeley.edu/ \n\nThis
file was not
retrieved by Teleport Pro, because it is addressed on a domain or path
outside the boundaries set for its Starting Address. \n\nDo you want to open
it from the server?'))window.location='http://aima.cs.berkeley.edu/'>" now (
http://aima.cs.berkeley.edu/), and there are some ready python code from
this book (http://aima.cs.berkeley.edu/python/readme.html).
And I have some problems with the code
http://aima.cs.berkeley.edu/python/agents.py


It is said in the http://aima.cs.berkeley.edu/python/agents.html:

# GUI - Graphical User Interface for Environments
# If you do not have Tkinter installed, either get a new installation of
Python
# (Tkinter is standard in all new releases), or delete the rest of this file
# and muddle through without a GUI.

I have python24.
But just "*v = VacuumEnvironment(); w = EnvFrame(v);*" do nothing - I don't
see any Graphical User Interface for Environments.
What am I doing wrong and how to compel this piece of code to return a
Graphical User Interface for Environments?

Thanks in advance for help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060728/a33b17c8/attachment.htm 

From kent37 at tds.net  Fri Jul 28 12:34:57 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 28 Jul 2006 06:34:57 -0400
Subject: [Tutor] playing around with function
In-Reply-To: <44C9D18F.7020701@khmeros.info>
References: <44C997B7.10307@khmeros.info> <eacgg0$atp$1@sea.gmane.org>
	<44C9D18F.7020701@khmeros.info>
Message-ID: <44C9E851.7020206@tds.net>

kakada wrote:
> # I have change my code style like this:
>
>     def gotoNF(self):
>         self.state = "NF"
>         self.navigationNext(self.state)
>     def gotoNT(self):
>         self.state = "NT"
>         self.navigationNext(self.state)
>     def gotoNU(self):
>         self.state = "NU"
>         self.navigationNext(self.state)
>     def gotoNA(self):
>         self.state = "NA"
>         self.navigationNext(self.state)
>     
>     def gotoPA(self):
>         self.state = "PA"
>         self.navigationPrevious(self.state)
>     def gotoPT(self):
>         self.state = "PT"
>         self.navigationPrevious(self.state)        
>     def gotoPU(self):
>         self.state = "PU"
>         self.navigationPrevious(self.state)            
>     def gotoPF(self):
>         self.state = "PF"
>         self.navigationPrevious(self.state)        
>   
All of the above could store a method as well as or instead of a state. 
Then you can get rid of the big conditional below.

You don't show the code to create self.store.units so I don't know what 
kind of object is there. I'll assume they are instances of class Unit. 
Then you could write for example

    def gotoPF(self):
        self.state = "PF" # You may not need this
        self.test = Unit.isfuzzy # This stores a reference to the correct method of Unit
        self.navigationPrevious(self.state)        

If you change all the gotoXX() methods this way, then navigated becomes just
    def navigated(self):
        if self.test(self.store.units[int(self.id)]:
            return True

Kent
>     def navigated(self):
>         if (self.state == 'NF') and
> (self.store.units[int(self.id)].isfuzzy()):
>             return True
>         if (self.state == 'PF') and
> (self.store.units[int(self.id)].isfuzzy()):
>             return True
>         if (self.state == 'NT') and
> (self.store.units[int(self.id)].istranslated()):
>             return True
>         if (self.state == 'PT') and
> (self.store.units[int(self.id)].istranslated()):
>             return True
>         if (self.state == 'NU') and
> (self.store.units[int(self.id)].isuntranslated()):
>             return True
>         if (self.state == 'PU') and
> (self.store.units[int(self.id)].isuntranslated()):
>             return True
>         if (self.state == 'NA') and
> (self.store.units[int(self.id)].isapproved()):
>             return True
>         if (self.state == 'PA') and
> (self.store.units[int(self.id)].isapproved()):
>             return True
>   



From kent37 at tds.net  Fri Jul 28 13:21:01 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 28 Jul 2006 07:21:01 -0400
Subject: [Tutor] how to run python's Graphical User Interface
 for	Environments in agents.py
In-Reply-To: <bf6cdbf10607280243k2a906822tb8c2141510cd5cb8@mail.gmail.com>
References: <bf6cdbf10607280243k2a906822tb8c2141510cd5cb8@mail.gmail.com>
Message-ID: <44C9F31D.2020201@tds.net>

?????? wrote:
>
>
>     <http://groups.yahoo.com/group/aima-talk/message/703;_ylc=X3oDMTJwdmFudGkyBF9TAzk3MzU5NzE1BGdycElkAzMwOTU0MjUEZ3Jwc3BJZAMxNjAwOTQ4OTIzBG1zZ0lkAzcwMwRzZWMDZG1zZwRzbGsDdm1zZwRzdGltZQMxMTU0MDEzNzc4>
>
>
> I am reading " Artificial Intelligence: A Modern Approach 
> <javascript:if(confirm('http://aima.cs.berkeley.edu/ \n\nThis file was 
> not retrieved by Teleport Pro, because it is addressed on a domain or 
> path outside the boundaries set for its Starting Address. \n\nDo you 
> want to open it from the 
> server?'))window.location='http://aima.cs.berkeley.edu/'>" now 
> (http://aima.cs.berkeley.edu/), and there are some ready python code 
> from this book ( http://aima.cs.berkeley.edu/python/readme.html).
> And I have some problems with the code 
> http://aima.cs.berkeley.edu/python/agents.py
> It is said in the http://aima.cs.berkeley.edu/python/agents.html:
>
> # GUI - Graphical User Interface for Environments
> # If you do not have Tkinter installed, either get a new installation of
> Python
> # (Tkinter is standard in all new releases), or delete the rest of 
> this file
> # and muddle through without a GUI.
>
> I have python24.
> But just "*v = VacuumEnvironment(); w = EnvFrame(v);*" do nothing - I 
> don't see any Graphical User Interface for Environments.
> What am I doing wrong and how to compel this piece of code to return a 
> Graphical User Interface for Environments?

The entire last section of the code - from "import Tkinter as tk" to the 
end - is enclosed in triple-quotes ('''). This makes it into a string 
constant rather than code, effectively commenting it out. Try removing 
the two lines that just contain '''.

Kent


From dyoo at hkn.eecs.berkeley.edu  Fri Jul 28 16:47:47 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 28 Jul 2006 07:47:47 -0700 (PDT)
Subject: [Tutor] playing around with function
In-Reply-To: <44C9D18F.7020701@khmeros.info>
References: <44C997B7.10307@khmeros.info> <eacgg0$atp$1@sea.gmane.org>
	<44C9D18F.7020701@khmeros.info>
Message-ID: <Pine.LNX.4.64.0607280723550.22291@hkn.eecs.berkeley.edu>



>    def navigated(self):
>        if (self.state == 'NF') and
> (self.store.units[int(self.id)].isfuzzy()):
>            return True
>        if (self.state == 'PF') and
> (self.store.units[int(self.id)].isfuzzy()):
>            return True
>        if (self.state == 'NT') and
> (self.store.units[int(self.id)].istranslated()):
>            return True
>        if (self.state == 'PT') and
> (self.store.units[int(self.id)].istranslated()):
>            return True
[code cut]


This code here looks highly repetitive, and there's really nothing bigger 
than a case analysis going on here.  I'd strongly recommend using a data 
structure to record the core essense of this code.

One possible refactoring is:

########################################
navigationTable = {'NF': 'isfuzzy',
                    'PF': 'isfuzzy',
                    'NT': 'istranslated',
                    ...}
test = navigationTable(self.state)
unit = self.store.units[int(self.id)])
if test == 'isfuzzy':
     return unit.isfuzzy()
elif test == 'istranslated':
     return unit.istranslated()
...
########################################

The heart of that code is the mapping between states and the function to 
call at that state, so we can keep that knowledge centralized in a data 
structure.


I get the feeling that the remainder of the code is really too closely 
tied with GUI stuff; there's the finite-state automata thing that I see 
here, but it's entangled with Qt widget logic.  You may want to consider 
how to break the GUI stuff out of the navigational code.

>    def navigationNext(self,state):
>        if (self.getCurrentItem() == 0):
>            return 0
>        self.id = int(self.item.text(0))
>        self.id += 1
>        for i in range(self.id,775):
>            self.id = i
>            if (i == 775):
>                pass
>                #self.warningMessage()


Other comments: the condition testing for i == 775 seems impossible to me. 
775 is outside of the for loop's domain.  That code won't ever fire.

navigationNext() and navigationPrevious() look like the exact same 
function.  The only significant difference I see is the increment or 
decrement used to move 'id' around.  Have you considered turning that into 
a parameter?

From kyxaxa at gmail.com  Fri Jul 28 18:02:28 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Fri, 28 Jul 2006 19:02:28 +0300
Subject: [Tutor] how to run python's Graphical User Interface for
	Environments in agents.py
Message-ID: <bf6cdbf10607280902r44967de4y81bb13ce4f5109b1@mail.gmail.com>

>
> The entire last section of the code - from "import Tkinter as tk" to the
> end - is enclosed in triple-quotes ('''). This makes it into a string
> constant rather than code, effectively commenting it out. Try removing
> the two lines that just contain '''.
>
> Kent


I removed triple-quotes.
And after learning more about Tkinter I saw that a little changed code


v = VacuumEnvironment()
w = EnvFrame(v)
w.mainloop()


shows the grid (it is graphical "environment" for agents).

But I am still working on how to put agents in this environment and to see
their life in this environment...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060728/1a201961/attachment.htm 

From alan.gauld at freenet.co.uk  Fri Jul 28 19:02:43 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 28 Jul 2006 18:02:43 +0100
Subject: [Tutor] how to run python's Graphical User Interface
	forEnvironments in agents.py
References: <bf6cdbf10607280243k2a906822tb8c2141510cd5cb8@mail.gmail.com>
Message-ID: <001701c6b267$a4675990$0201a8c0@XPpro>

> I have python24.
> But just "*v = VacuumEnvironment(); w = EnvFrame(v);*" do nothing - 
> I don't
> see any Graphical User Interface for Environments.
> What am I doing wrong and how to compel this piece of code to return 
> a
> Graphical User Interface for Environments?

Did you delete the triple quotes around the Tkinter section?
Just after the quotation you posted and just before the end of the 
file?

Alan G. 


From kyxaxa at gmail.com  Fri Jul 28 19:10:36 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Fri, 28 Jul 2006 20:10:36 +0300
Subject: [Tutor] how to run python's Graphical User Interface
	forEnvironments in agents.py
In-Reply-To: <001701c6b267$a4675990$0201a8c0@XPpro>
References: <bf6cdbf10607280243k2a906822tb8c2141510cd5cb8@mail.gmail.com>
	<001701c6b267$a4675990$0201a8c0@XPpro>
Message-ID: <bf6cdbf10607281010x6fd6f1eye1489dfdeec0498c@mail.gmail.com>

2006/7/28, Alan Gauld <alan.gauld at freenet.co.uk>:
>
> > I have python24.
> > But just "*v = VacuumEnvironment(); w = EnvFrame(v);*" do nothing -
> > I don't
> > see any Graphical User Interface for Environments.
> > What am I doing wrong and how to compel this piece of code to return
> > a
> > Graphical User Interface for Environments?
>
> Did you delete the triple quotes around the Tkinter section?
> Just after the quotation you posted and just before the end of the
> file?
>
> Alan G.
>
>
yes, I did. (http://mail.python.org/pipermail/tutor/2006-July/048268.html)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060728/0d2d27cc/attachment.html 

From RPhillips at engineer.co.summit.oh.us  Fri Jul 28 19:37:43 2006
From: RPhillips at engineer.co.summit.oh.us (Ron Phillips)
Date: Fri, 28 Jul 2006 13:37:43 -0400
Subject: [Tutor] MySQLdb question.
Message-ID: <44CA1328.0345.0006.0@engineer.co.summit.oh.us>

I am trying to write a script that adds data to a table using MySQLdb.py.  For some reason, "INSERT" seems to work temporarily. I run a command to insert a row, and then do a select query, and it's there. After the program shuts down, though, it's gone. No rows are permanently created. SELECT works fine from MySQLdb, CREATE TABLE too, but when I add data, it's only there while the script is executing, then it's gone.
 
I can add data from the MySQL Query Browser, and it's fine. 
 
I googled, but couldn't find anything. I'm running MySQL5, and the latest MySQLdb.py, too. Python 2.4.
 
I am using animal.py from http://www.kitebird.com/articles/pydbapi.html, but it's been the same thing with other scripts. Is it a setting, or a thinko, or what?
 
Ron
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060728/3dbc43da/attachment.html 

From kent37 at tds.net  Fri Jul 28 20:05:22 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 28 Jul 2006 14:05:22 -0400
Subject: [Tutor] MySQLdb question.
In-Reply-To: <44CA1328.0345.0006.0@engineer.co.summit.oh.us>
References: <44CA1328.0345.0006.0@engineer.co.summit.oh.us>
Message-ID: <44CA51E2.5000408@tds.net>

Ron Phillips wrote:
> I am trying to write a script that adds data to a table using 
> MySQLdb.py.  For some reason, "INSERT" seems to work temporarily. I 
> run a command to insert a row, and then do a select query, and it's 
> there. After the program shuts down, though, it's gone. No rows are 
> permanently created. SELECT works fine from MySQLdb, CREATE TABLE too, 
> but when I add data, it's only there while the script is executing, 
> then it's gone.
Try calling conn.commit() before conn.close(). IIRC older versions of 
MySQL were set to auto-commit by default but newer versions require the 
explicit commit.

Kent


From RPhillips at engineer.co.summit.oh.us  Fri Jul 28 20:18:28 2006
From: RPhillips at engineer.co.summit.oh.us (Ron Phillips)
Date: Fri, 28 Jul 2006 14:18:28 -0400
Subject: [Tutor] MySQLdb question.
References: <44CA1328.0345.0006.0@engineer.co.summit.oh.us>
Message-ID: <44CA1CB4.0345.0006.0@engineer.co.summit.oh.us>

That was it all right! Thanks, Kent! Ron___________________Ron Phillips wrote:>I am trying to write a script that adds data to a table using >MySQLdb.py. For some reason, "INSERT" seems to work temporarily. I >run a command to insert a row, and then do a select query, and it's >there. After the program shuts down, though, it's gone. No rows are >permanently created. SELECT works fine from MySQLdb, CREATE TABLE too, >but when I add data, it's only there while the script is executing, >then it's gone.Try calling conn.commit() before conn.close(). IIRC older versions of MySQL were set to auto-commit by default but newer versions require the explicit commit. Kent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060728/850d190e/attachment-0001.html 

From nephish at gmail.com  Fri Jul 28 20:20:48 2006
From: nephish at gmail.com (shawn bright)
Date: Fri, 28 Jul 2006 13:20:48 -0500
Subject: [Tutor] MySQLdb question.
In-Reply-To: <44CA51E2.5000408@tds.net>
References: <44CA1328.0345.0006.0@engineer.co.summit.oh.us>
	<44CA51E2.5000408@tds.net>
Message-ID: <384c93600607281120s3a54375dqcb7df955d84ac0a0@mail.gmail.com>

you may be missing db.commit().
When you do insert, update, etc.. you call commit() to make the changes
stick.

-sk

On 7/28/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Ron Phillips wrote:
> > I am trying to write a script that adds data to a table using
> > MySQLdb.py.  For some reason, "INSERT" seems to work temporarily. I
> > run a command to insert a row, and then do a select query, and it's
> > there. After the program shuts down, though, it's gone. No rows are
> > permanently created. SELECT works fine from MySQLdb, CREATE TABLE too,
> > but when I add data, it's only there while the script is executing,
> > then it's gone.
> Try calling conn.commit() before conn.close(). IIRC older versions of
> MySQL were set to auto-commit by default but newer versions require the
> explicit commit.
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060728/7a9e0e0e/attachment.htm 

From dkuhlman at rexx.com  Fri Jul 28 22:44:18 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Fri, 28 Jul 2006 13:44:18 -0700
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <eaapue$3qh$1@sea.gmane.org>
References: <20060727155200.GA94348@cutter.rexx.com>
	<eaapue$3qh$1@sea.gmane.org>
Message-ID: <20060728204418.GA11905@cutter.rexx.com>

On Thu, Jul 27, 2006 at 05:34:13PM +0100, Alan Gauld wrote:
> Hi Dave,
> 
> You are causing yourself some confusion by still treating variables
> as something other than a name. Your first paragraph says:
> 
> (Actually, functions and classes are just variables that hold
> references to function and class objects.)
> 
> Which is wrong. variables are simply names that refer to objects,
> which includes functions and classes(and instances of classes)
> Thus a function is never a variable. variables refer to functions.
> 
> In Computer Science terms a function is a lamda expression
> and a def in Python should be a shorthand way of doing
> 
> var = lambda params... : expression
> 
> Unfortunately, in practice, in Python it's the other way around.
> The lambda is really an alternative for
> 
> def var(params...):
>     return expression
> 
> But it is important to realize that names in Python - all names - are
> simply references to objects of some kind. and that classes, 
> instances,
> functions, numbers, lists, characters etc  are all objects in this 
> sense.
> 

Rats.  I wish I'd said it that way.  Can I steal that quote?

Thanks, Alan and Kent, for trying to straighten me out on this.
And, by the way, since I'll be trying to explain this in the next
class I teach, you are doing more than just clear the darkness of
confusion from *my* mind; you may also be helping to prevent me
from confusing students in my next class.

Let me try to summarize a few points that Alan has tried to
explain about variables, names, namespaces, values, and objects.
Let's see if I can get it right this time:

A variable is a name bound to a value in a namespace.

A namespace is a dictionary in which Python can look up a name
(possibly) to obtain its value.

Names refer to objects.  Objects can be integers, tuples, lists,
dictionaries, strings, instances of classes, functions, classes
(themselves), other Python built-in types, and instances of
classes.

In Python, (and here I'm trying to go a bit beyond Alan) since the
use of objects and references to them are so pervasive and
consistent, we sometimes conflate a variable and the object it
refers to.  So, for example, if we have the following code::

    total = 25
    items = [11, 22, 33]
    def func1():
        pass
    class Class1:
        pass

we sometimes say:

- ``total`` is an integer.

- ``items`` is an list.

- ``func1`` is a function.

- ``Class1`` is a class.

But, if we were more careful, we might say:

- ``total`` is a variable that refers to an integer object.

- ``items`` is a variable that refers to a list object.

- ``func1`` is a variable that refers to a function object.

- ``Class1`` is a variable that refers to a class object.

Or, even:

- ``total`` is a name bound to an integer object in the current
  namespace.

- ``items`` is a name bound to a list object in the current namespace.

- ``func1`` is a name bound to an function object in the current
  namespace.

- ``Class1`` is a name bound to an class object in the current
  namespace.

And, it is important to remember:

1. Names are references to objects and

2. Objects are first class, which means that we can:

   - Store them in variables.

   - Store them in data structures.

   - Pass them to functions and methods.

   - Return them from functions and methods.

There, am I any closer?

The point that ``def func1: ...`` creates a variable "func1" is
one that I believe is not clear to someone new to programming or
even to someone familiar only with languages like C, C++, or Java.

Give me a little more time to address and respond to the rest of
Alan's comments.

Dave

[more good comments snipped]

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From dkuhlman at rexx.com  Fri Jul 28 22:45:26 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Fri, 28 Jul 2006 13:45:26 -0700
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <44C8EDF4.5020809@tds.net>
References: <20060727155200.GA94348@cutter.rexx.com> <44C8EDF4.5020809@tds.net>
Message-ID: <20060728204526.GB11905@cutter.rexx.com>

On Thu, Jul 27, 2006 at 12:46:44PM -0400, Kent Johnson wrote:
> Dave Kuhlman wrote:
> > I've written up a few notes on Python namespaces and scopes.  If
> > anyone has corrections, comments, or suggestions, I'd appreciate
> > them. You can find my comments here:
> >
> >     http://www.rexx.com/~dkuhlman/python_comments.html#namespaces
> 
> You wrote, "If a variable is assigned a value /anywhere/ in a scope 
> (...), then that variable is local to that scope. Otherwise, the 
> variable is global."
> 
> You omit the enclosing scope and the builtin namespace. A variable can 
> be defined in
> - local scope
> - any of zero or more enclosing scopes
> - global scope
> - builtin namespace

Thanks.  I've added the built-in namespace to my notes.

But, I don't believe in the existence of nested namespaces.  I
think they are a hoax.  Some people believe that nested namespaces
were added sometime around Python 2.1 or 2.2.  But, that's just a
fraud.  If there were really such a thing as nested
scopes/namespaces, we would have a function that would give us
access to them, similar to the way that locals() and globals()
give us access to the local and global namespace.

> 
> Names are also bound by for statements and except clauses.

Right.  I've added that, now.

> 
> You might note that augmented assignment (e.g. a += 1) counts as 
> assignment in the local scope. This is a common cause of UnboundLocalError:
> 
> In [5]: a=1
> 
> In [6]: def foo():
>    ...:     a+=1
>    ...:
>    ...:
> 
> In [7]: foo()
> ---------------------------------------------------------------------------
> exceptions.UnboundLocalError                         Traceback (most 
> recent call last)
> 
> D:\Projects\e3po\<ipython console>
> 
> D:\Projects\e3po\<ipython console> in foo()
> 
> UnboundLocalError: local variable 'a' referenced before assignment
> 
> 
> I think modifying globals() is guaranteed to work. Modifying locals() 
> only works at global scope, i.e. when locals() is globals().
> 
> You wrote, "Note that for lexically/statically nested scopes (for 
> example, a function defined inside a function), it seems that globals() 
> and locals() still give access to all items in the accessible 
> namespaces." I'm not sure what you mean by this. locals() doesn't give 
> access to items in nested scopes:
> 

You are right.  I'm confused about this.  But, it is Python's
fault.  See more below.

> In [1]: x=1
> 
> In [2]: def maker():
>    ...:     y=2
>    ...:     def showLocals():
>    ...:         z=3
>    ...:         print locals()
>    ...:     return showLocals
>    ...:
> 
> In [3]: sl=maker()
> 
> In [4]: sl()
> {'z': 3}
> 

Oh yeah?  Well, what about this?

    In [1]: def maker():
       ...:         y=2
       ...:     def showLocals():
       ...:             z=3
       ...:         keys = locals().keys()
       ...:         keys.sort()
       ...:         print 'locals:', keys
       ...:         keys = globals().keys()
       ...:         keys.sort()
       ...:         print 'globals:', keys
       ...:     return showLocals
       ...:
    In [2]: sl = maker()
    In [3]: sl()
    locals: ['z']
    globals: ['In', 'Out', '_', '__', '__IP', '___', '__builtins__', 
    '__name__', '__nonzero__', '_dh', '_i', '_i0', '_i1', '_i2', 
    '_i3', '_ih', '_ii', '_iii', '_oh', 'help', 'maker', 'sl']

So, were is y?  See, nested scopes do not exist.

> See also
> http://docs.python.org/ref/naming.html
> 

OK.  Trying to be a little more serious ... Maybe Python now
*does* have nested scopes, but Python does not give us a function
to access them.  Or does it?

Thanks again for the help.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From dyoo at hkn.eecs.berkeley.edu  Fri Jul 28 23:36:08 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 28 Jul 2006 14:36:08 -0700 (PDT)
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <20060728204526.GB11905@cutter.rexx.com>
References: <20060727155200.GA94348@cutter.rexx.com> <44C8EDF4.5020809@tds.net>
	<20060728204526.GB11905@cutter.rexx.com>
Message-ID: <Pine.LNX.4.64.0607281425420.13099@hkn.eecs.berkeley.edu>

> If there were really such a thing as nested scopes/namespaces, we would 
> have a function that would give us access to them, similar to the way 
> that locals() and globals() give us access to the local and global 
> namespace.

It would be _convenient_ to have such a function for inspection, but it's 
not a requirement.

Here's a function that shows lexical scope in action:

##########################
>>> def pair(x, y):
...     def f(b):
...         if b: return x
...         return y
...     return f
...
>>> p = pair(3, 4)
>>> p(True)
3
>>> p(False)
4
##########################

From kyxaxa at gmail.com  Sat Jul 29 01:16:58 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sat, 29 Jul 2006 02:16:58 +0300
Subject: [Tutor] visualization
Message-ID: <bf6cdbf10607281616l28a3dd03p9c83e3f1e8bed2ea@mail.gmail.com>

I have a world (environment), where live different objects.
And all objects like to move.

This is the code:
"""

import random, time, Tkinter

class Object:
    def __init__ (self, x=10, y=10):
        self.name = random.randint(0, 100000)
        self.x = x
        self.y = y

    def __repr__ (self):
        return str(self.name)

    def display(self, canvas, x, y, width, height):
        """Display an image of this Object on the canvas."""
        pass

    def rand_vec(self):
        return random.randint(-1, 1), random.randint(-1, 1)


class Environment:
    def __init__ (self):
        self.objects = []

    def step(self):
        for obj in self.objects:
            old_x, old_y = obj.x, obj.y
            change_x, change_y = obj.rand_vec()
            obj.x, obj.y = old_x + change_x, old_y + change_y
            print obj.name, '\t:\t ', old_x, old_y,' -> ', obj.x,
obj.y


    def run(self, steps=10):
        """Run the Environment for given number of time steps."""
        for step in range(steps):
            self.step()
            time.sleep(2)

    def add_object(self, object):
        print object.name, ' was added to environment'
        self.objects.append(object)


print '\tBORN'
env = Environment()
for obj in range(10):
    child = Object()
    print child, ' was born'
    env.add_object(child)

print '\tLIFE'
env.run(100)

"""



And now I want to visualizate this world.

What modules can you advise me for "easy" visualization?

"Easy" means that it would be really nice if I could do vizualization with
minimum change of existing classes.



Thanks in advance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060729/6dd519f9/attachment.html 

From mjekl at iol.pt  Fri Jul 28 21:45:42 2006
From: mjekl at iol.pt (mjekl at iol.pt)
Date: Fri, 28 Jul 2006 20:45:42 +0100
Subject: [Tutor] Problems with encoding
Message-ID: <f5edb0d236a.44ca7776@iol.pt>

>kent37 at tds.net wrote:

>>mjekl at iol.pt wrote:
>> Hi,
>>
>>
>> My interpreter in set via sitecustomize.py to use utf-8 as default encoding.
>>
>> I'm reading fields from a dbf table to a firebird db with encoding set to win1252.
>> I guess it's original encoding is cp850, but am not sure, and have been addressing exceptions one by one with lines of:
>>
>> r = r.replace(u'offending_code', u'ok_code')
>>   
>Why don't you just convert from cp850 to cp1252 directly? Python 
>supports both encodings, it's as simple as
>some_string.decode('cp850').encode('cp1252')

In the mean while somewhat accidently (read some stuff) I followed a similar approach.

[...] ORIGINAL POST DELETED HERE [...]

>My guess is a coding error on your part, otherwise something would have changed...can you show some context in import_pcfcli.py?

I also expect it's my error ;-(   ;-)

The following snippet of my present code isn't giving me any problems. Although I'm not really sure why it works. Also I had some problems encoding to 'cp1252' and not to 'utf-8'.

Anyone as a pointer to a nice resource that can help me understand this decode / encode biz better?

 try:
                    # TODO: Check the str.translate() method
                    r = recordSet.Fields(fieldsDict[f]).Value.strip()
                    r.decode('cp850')
                    r = r.replace(u'\x8f', u'')
                    r = r.replace(u'\u20ac', u'\xc7')
                    r = r.replace(u'\xa6', u'\xaa')
                    r = r.replace(u'\u2122', u'\xd5')
                    r = r.replace(u'\u017d', u'\xc3')
                    r = r.replace(u'\xa7', u'\xba')
                    # The following line does not work if with 'cp1252' !?
                    rec.append(r.encode('utf-8')) # kinterbasdb makes conversions by itself ;-)
                except UnicodeDecodeError, UnicodeEncodeError:
                    print f
                    return None

Txs,
Miguel

_______________________________________________________________________________________
Uma mensalidade a medida da sua carteira.
Saber mais em http://www.iol.pt/correio/rodape.php?dst=0607191


From kent37 at tds.net  Sat Jul 29 05:38:01 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 28 Jul 2006 23:38:01 -0400
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <20060728204418.GA11905@cutter.rexx.com>
References: <20060727155200.GA94348@cutter.rexx.com>	<eaapue$3qh$1@sea.gmane.org>
	<20060728204418.GA11905@cutter.rexx.com>
Message-ID: <44CAD819.1070608@tds.net>

Dave Kuhlman wrote:
> On Thu, Jul 27, 2006 at 05:34:13PM +0100, Alan Gauld wrote:
>   
>> Hi Dave,
>>
>> You are causing yourself some confusion by still treating variables
>> as something other than a name. Your first paragraph says:
>>
>> (Actually, functions and classes are just variables that hold
>> references to function and class objects.)
>>
>> Which is wrong. variables are simply names that refer to objects,
>> which includes functions and classes(and instances of classes)
>> Thus a function is never a variable. variables refer to functions.
>>
>> In Computer Science terms a function is a lamda expression
>> and a def in Python should be a shorthand way of doing
>>
>> var = lambda params... : expression
>>
>> Unfortunately, in practice, in Python it's the other way around.
>> The lambda is really an alternative for
>>
>> def var(params...):
>>     return expression
>>
>> But it is important to realize that names in Python - all names - are
>> simply references to objects of some kind. and that classes, 
>> instances,
>> functions, numbers, lists, characters etc  are all objects in this 
>> sense.
>>
>>     
>
> Rats.  I wish I'd said it that way.  Can I steal that quote?
>
> Thanks, Alan and Kent, for trying to straighten me out on this.
> And, by the way, since I'll be trying to explain this in the next
> class I teach, you are doing more than just clear the darkness of
> confusion from *my* mind; you may also be helping to prevent me
> from confusing students in my next class.
>
> Let me try to summarize a few points that Alan has tried to
> explain about variables, names, namespaces, values, and objects.
> Let's see if I can get it right this time:
>
> A variable is a name bound to a value in a namespace.
>
> A namespace is a dictionary in which Python can look up a name
> (possibly) to obtain its value.
>
> Names refer to objects.  Objects can be integers, tuples, lists,
> dictionaries, strings, instances of classes, functions, classes
> (themselves), other Python built-in types, and instances of
> classes.
>
> In Python, (and here I'm trying to go a bit beyond Alan) since the
> use of objects and references to them are so pervasive and
> consistent, we sometimes conflate a variable and the object it
> refers to.  So, for example, if we have the following code::
>
>     total = 25
>     items = [11, 22, 33]
>     def func1():
>         pass
>     class Class1:
>         pass
>
> we sometimes say:
>
> - ``total`` is an integer.
>
> - ``items`` is an list.
>
> - ``func1`` is a function.
>
> - ``Class1`` is a class.
>
> But, if we were more careful, we might say:
>
> - ``total`` is a variable that refers to an integer object.
>
> - ``items`` is a variable that refers to a list object.
>
> - ``func1`` is a variable that refers to a function object.
>
> - ``Class1`` is a variable that refers to a class object.
>
> Or, even:
>
> - ``total`` is a name bound to an integer object in the current
>   namespace.
>
> - ``items`` is a name bound to a list object in the current namespace.
>
> - ``func1`` is a name bound to an function object in the current
>   namespace.
>
> - ``Class1`` is a name bound to an class object in the current
>   namespace.
>
> And, it is important to remember:
>
> 1. Names are references to objects and
>
> 2. Objects are first class, which means that we can:
>   
Right up to here, I'm standing on my chair and cheering.
>    - Store them in variables.
>   
Ouch! No! Variables don't store values, they refer to values. Thinking 
of variables as containers doesn't work in Python.
>    - Store them in data structures.
>   
That's a little better, but really you store a reference to a value in a 
data structure. It's references all the way down ;)
>    - Pass them to functions and methods.
>
>    - Return them from functions and methods.
>
> There, am I any closer?
>   
Lots closer.
> The point that ``def func1: ...`` creates a variable "func1" is
> one that I believe is not clear to someone new to programming or
> even to someone familiar only with languages like C, C++, or Java.
>   
Better to say "def func1:" creates a function object and binds it to the 
name "func1". And your point is a good one, that this takes a little 
getting used to. By the way "class k2:" creates a class object and binds 
it to a name also. Namespaces and name binding are pervasive in Python.

Kent


From kent37 at tds.net  Sat Jul 29 06:06:36 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 29 Jul 2006 00:06:36 -0400
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <20060728204526.GB11905@cutter.rexx.com>
References: <20060727155200.GA94348@cutter.rexx.com> <44C8EDF4.5020809@tds.net>
	<20060728204526.GB11905@cutter.rexx.com>
Message-ID: <44CADECC.9070607@tds.net>

Dave Kuhlman wrote:
> If there were really such a thing as nested
> scopes/namespaces, we would have a function that would give us
> access to them, similar to the way that locals() and globals()
> give us access to the local and global namespace.
>   
Nested namespaces are actually stored with the nested function. They are 
also called closures. For example:

In [1]: def m(x):
   ...:     y=3
   ...:     def f(z):
   ...:         print x, y, z
   ...:     return f
   ...:

In [2]: ff=m(2)

Just to prove that the closure exists:
In [3]: ff(5)
2 3 5

The closure is stored in the func_closure attribute of the function:
In [5]: ff.func_closure
Out[5]:
(<cell at 0x00E39170: int object at 0x00A658D8>,
 <cell at 0x00E39150: int object at 0x00A658E4>)

In [6]: ff.func_closure[0]
Out[6]: <cell at 0x00E39170: int object at 0x00A658D8>

This is pretty opaque. There is a way to get the values out; see this 
recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439096

For more discussion, search comp.lang.python for func_closure.

Kent


From alan.gauld at freenet.co.uk  Sat Jul 29 10:05:38 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 29 Jul 2006 09:05:38 +0100
Subject: [Tutor] Notes on namespaces, scopes, etc
References: <20060727155200.GA94348@cutter.rexx.com><eaapue$3qh$1@sea.gmane.org>
	<20060728204418.GA11905@cutter.rexx.com>
Message-ID: <002701c6b2e5$c797b120$0201a8c0@XPpro>

> Let me try to summarize a few points that Alan has tried to

> A variable is a name bound to a value in a namespace.
>
> A namespace is a dictionary in which Python can look up a name
> (possibly) to obtain its value.

A namespace is *implemented* in Python as a dictionary.

A namespace is a concept that applies in most computing
languages and they all implement it differently. Many simply
rely on the lexical context and the parser to control access.
If you are using this for a class it's important that the students
realise that the concept of namespace is distinct from the
implementation details in Python.

Its because the implementation details vary so much that
I start the namespace topic in my tutor by saying:
------------------
"What's a namespace? I hear you ask. Well, it's kinda hard to explain.
Not because they are especially complicated, but because every
language does them differently. ..."
-----------------
The concept is the same in every language but how they
implement the concept is completely different in each one.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


From alan.gauld at freenet.co.uk  Sat Jul 29 10:17:45 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 29 Jul 2006 09:17:45 +0100
Subject: [Tutor] visualization
References: <bf6cdbf10607281616l28a3dd03p9c83e3f1e8bed2ea@mail.gmail.com>
Message-ID: <003f01c6b2e7$790ecb40$0201a8c0@XPpro>

> class Object:

Probably good to change the name, there is a built in class
"object" and this could cause confusion...

>    def __init__ (self, x=10, y=10):
>    def __repr__ (self):
>    def display(self, canvas, x, y, width, height):
>    def rand_vec(self):
>
>
> class Environment:
>    def __init__ (self):
>    def step(self):
>            print obj.name, '\t:\t ', old_x, old_y,' -> ', obj.x,

The print statements will go to a console if you convert to
a GUI. |Since they are basically debug statements
that shouldn't be a problem, but you may prefer to
display them in a message widget instead...

>    def run(self, steps=10):
>    def add_object(self, object):

> print '\tBORN'
> env = Environment()
> for obj in range(10):
>    child = Object()
>    print child, ' was born'
>    env.add_object(child)
>
> print '\tLIFE'
> env.run(100)

> And now I want to visualizate this world.
> What modules can you advise me for "easy" visualization?

You already import Tkinter so presumabnly you want to use
that as your GUI? What other kinds of modules do you want?
You already have a display method in your object so you
just need to write the code to display something - a small
image maybe? - on a canvas.

You will need to create a module that draws the GUI and
handles the user events. That module will probably
import this one (rather than this one importing Tkinter)
You can then just pass the canvas object to each object
in your environment and ask it to draw itself...

You might like to separate your objects into model and
view representations but thats getting into more advanced
GUI design and probably not needed here.

> "Easy" means that it would be really nice if I could do 
> vizualization with
> minimum change of existing classes.

The golden rule is always to avoid writing code that mixes
display and computation. That is to avoid using print statements
inside the core objects etc.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


From kyxaxa at gmail.com  Sat Jul 29 11:09:25 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sat, 29 Jul 2006 12:09:25 +0300
Subject: [Tutor] visualization
In-Reply-To: <003f01c6b2e7$790ecb40$0201a8c0@XPpro>
References: <bf6cdbf10607281616l28a3dd03p9c83e3f1e8bed2ea@mail.gmail.com>
	<003f01c6b2e7$790ecb40$0201a8c0@XPpro>
Message-ID: <bf6cdbf10607290209o2a7e9f11sa87e90899d9ca8be@mail.gmail.com>

>
> Probably good to change the name, there is a built in class
> "object" and this could cause confusion...


Ok, I'll do this.

You already import Tkinter so presumabnly you want to use
> that as your GUI? What other kinds of modules do you want?
> You already have a display method in your object so you
> just need to write the code to display something - a small
> image maybe? - on a canvas.


I've used Tkinter because of historical reasons :)
I was trying to do visualization with Tkinter earlier, but I couldn't compel
objects to display themselfs..

You will need to create a module that draws the GUI and
> handles the user events. That module will probably
> import this one (rather than this one importing Tkinter)
> You can then just pass the canvas object to each object
> in your environment and ask it to draw itself...



You might like to separate your objects into model and
> view representations but thats getting into more advanced
> GUI design and probably not needed here.


 Can you advise me some links on examples of realization of this two
different approaches? Some tutorials would really help me :)

And thanks, now I understand what will be my next steps.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060729/d519a9a0/attachment.html 

From python at venix.com  Sat Jul 29 14:24:45 2006
From: python at venix.com (Python)
Date: Sat, 29 Jul 2006 08:24:45 -0400
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <44CAD819.1070608@tds.net>
References: <20060727155200.GA94348@cutter.rexx.com>
	<eaapue$3qh$1@sea.gmane.org> <20060728204418.GA11905@cutter.rexx.com>
	<44CAD819.1070608@tds.net>
Message-ID: <1154175885.28304.145.camel@www.venix.com>

On Fri, 2006-07-28 at 23:38 -0400, Kent Johnson wrote:
> Dave Kuhlman wrote:
> > On Thu, Jul 27, 2006 at 05:34:13PM +0100, Alan Gauld wrote:
<snipped>
> Right up to here, I'm standing on my chair and cheering.
> >    - Store them in variables.
> >   
> Ouch! No! Variables don't store values, they refer to values. Thinking 
> of variables as containers doesn't work in Python.

What I told my kids (Dad, Do we really have to learn Python?) was that
variables are sticky notes.  The variable name is written on the note
and stuck onto the object.

a = 3

creates an int object with a value of 3 and slaps a sticky note
containing "a" onto the object.

a = 3 + 1

results in a new int object with a value of 4 and the sticky note is
transferred from the "3 object" to the "4 object".  (int objects are
immutable, so the "3 object" can not be changed into a "4 object").  If
there are no sticky notes on the "3 object", it can be discarded and the
memory it used to occupy is now available for other objects.
- - - - - - - - - - - - - - - - -

Dave, this may be too simplistic for the document you're writing, but I
think the analogy provides a useful mental image.

-- 
Lloyd Kvam
Venix Corp


From nephish at gmail.com  Sat Jul 29 16:26:28 2006
From: nephish at gmail.com (shawn bright)
Date: Sat, 29 Jul 2006 09:26:28 -0500
Subject: [Tutor] question about type str
Message-ID: <384c93600607290726v397a838cq14e2d99c7c86dacb@mail.gmail.com>

Hey there,
i have an app with this line.....
sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit, digit_count))

it is failing with the following error.

Traceback (most recent call last):
  File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 88, in ?
    entered_digits = getNumber(welcome, time_limit, password_digits)
  File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 72, in getNumber
    sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit, digit_count))
TypeError: 'str' object is not callable


anyone know what i may be doing wrong here?

thanks
shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060729/fc7cd23f/attachment.html 

From python at venix.com  Sat Jul 29 16:44:17 2006
From: python at venix.com (Python)
Date: Sat, 29 Jul 2006 10:44:17 -0400
Subject: [Tutor] question about type str
In-Reply-To: <384c93600607290726v397a838cq14e2d99c7c86dacb@mail.gmail.com>
References: <384c93600607290726v397a838cq14e2d99c7c86dacb@mail.gmail.com>
Message-ID: <1154184257.28304.182.camel@www.venix.com>

On Sat, 2006-07-29 at 09:26 -0500, shawn bright wrote:
> Hey there,
> i have an app with this line.....
> sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit, digit_count))

sys.stderr.write("GET DATA %s %d %d\n" % (sound, time_limit, digit_count))
                                   ----^----
You meant to do string interpolation, but left out the interpolation
(formating) operator.  So the parenthesized expression looked like a
function call.

> 
> it is failing with the following error.
> 
> Traceback (most recent call last): 
>   File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 88, in ?
>     entered_digits = getNumber(welcome, time_limit, password_digits)
>   File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 72, in
> getNumber 
>     sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit,
> digit_count))
> TypeError: 'str' object is not callable
> 
> 
> anyone know what i may be doing wrong here?
> 
> thanks
> shawn
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From nephish at gmail.com  Sat Jul 29 17:13:58 2006
From: nephish at gmail.com (shawn bright)
Date: Sat, 29 Jul 2006 10:13:58 -0500
Subject: [Tutor] question about type str
In-Reply-To: <1154184257.28304.182.camel@www.venix.com>
References: <384c93600607290726v397a838cq14e2d99c7c86dacb@mail.gmail.com>
	<1154184257.28304.182.camel@www.venix.com>
Message-ID: <384c93600607290813q68e682c4hcfa57cf421c074db@mail.gmail.com>

gee whiz, i thought i had poured over that line sufficiently.
It works now. imagine that.
thanks,
shawn

On 7/29/06, Python <python at venix.com> wrote:
>
> On Sat, 2006-07-29 at 09:26 -0500, shawn bright wrote:
> > Hey there,
> > i have an app with this line.....
> > sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit, digit_count))
>
> sys.stderr.write("GET DATA %s %d %d\n" % (sound, time_limit, digit_count))
>                                    ----^----
> You meant to do string interpolation, but left out the interpolation
> (formating) operator.  So the parenthesized expression looked like a
> function call.
>
> >
> > it is failing with the following error.
> >
> > Traceback (most recent call last):
> >   File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 88, in ?
> >     entered_digits = getNumber(welcome, time_limit, password_digits)
> >   File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 72, in
> > getNumber
> >     sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit,
> > digit_count))
> > TypeError: 'str' object is not callable
> >
> >
> > anyone know what i may be doing wrong here?
> >
> > thanks
> > shawn
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> --
> Lloyd Kvam
> Venix Corp
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060729/eac2c74d/attachment.htm 

From alan.gauld at freenet.co.uk  Sat Jul 29 20:19:50 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 29 Jul 2006 19:19:50 +0100
Subject: [Tutor] visualization
References: <bf6cdbf10607281616l28a3dd03p9c83e3f1e8bed2ea@mail.gmail.com><003f01c6b2e7$790ecb40$0201a8c0@XPpro>
	<bf6cdbf10607290209o2a7e9f11sa87e90899d9ca8be@mail.gmail.com>
Message-ID: <001901c6b33b$94c468a0$0201a8c0@XPpro>

> You will need to create a module that draws the GUI and
>> handles the user events. That module will probably
>> import this one (rather than this one importing Tkinter)
>> You can then just pass the canvas object to each object
>> in your environment and ask it to draw itself...
>
> You might like to separate your objects into model and
>> view representations but thats getting into more advanced
>> GUI design and probably not needed here.
>
> Can you advise me some links on examples of realization of this two
> different approaches? Some tutorials would really help me :)

For a quick overview of Model/View (and sometimes Controller)
take a look at the Apple web site. their default GUI design uses
the paradigm and there is a good visual description  in the
overview:

http://developer.apple.com/documentation/Cocoa/Conceptual/ObjCTutorial/chapter02/chapter_2_section_3.html

For a slightly different approach try:

http://www.mimuw.edu.pl/~sl/teaching/00_01/Delfin_EC/Overviews/ModelViewPresenter.htm

For an example of the first approach I'll create a list of Characters
(an environment of objects if you like?) And I'll arbitrarily modify 
them
between button presses and get them to present themselves on each
button press....

from Tkinter import *

class Char:
    def __init__(self,c=''):
        self.c = c

    def display(self, aLabel):
        aLabel['text'] += self.c

env = [Char(i) for i in 'abcdefgh']

# create an event handler
def show():
    lMessage['text'] = ''  # reset text
    for c in env:
        c.display(lMessage)
    env.reverse()     # change for next time


# now create GUI
top = Tk()
F = Frame(top)
F.pack()

# add the widgets
lMessage = Label(F, text="")
lMessage.pack()
bQuit = Button(F, text="Display", command=show)
bQuit.pack()

# set the loop running
top.mainloop() 


From nephish at gmail.com  Sun Jul 30 00:44:07 2006
From: nephish at gmail.com (shawn bright)
Date: Sat, 29 Jul 2006 17:44:07 -0500
Subject: [Tutor] problem with rejected mail smtplib
Message-ID: <384c93600607291544v5cc0bf47ve2672605f3804b6a@mail.gmail.com>

Hello there,
i have a customer list, each with a number of email address that we send
notifications to via text message.
the problem is, there are a number of providers ( just two ) that reject our
messages.
the script goes a little something like this :

Address = 'going at somewhere.net'
>From = 'me at myhost.net'
message = 'From: me at myhost.net\r\nTo: %s\r\nSubject: %s\r\n\r\n%s' %
(Address,'alert',message)
server.sendmail(From, Address, message)

most of the time it goes thru ok. but only some providers have a problem.
However, those same providers get messages if i send them thru Evolution.

any ideas of what to check out?

thanks
-sk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060729/ca300176/attachment.html 

From kyxaxa at gmail.com  Sun Jul 30 01:52:38 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sun, 30 Jul 2006 02:52:38 +0300
Subject: [Tutor] visualization
In-Reply-To: <001901c6b33b$94c468a0$0201a8c0@XPpro>
References: <bf6cdbf10607281616l28a3dd03p9c83e3f1e8bed2ea@mail.gmail.com>
	<003f01c6b2e7$790ecb40$0201a8c0@XPpro>
	<bf6cdbf10607290209o2a7e9f11sa87e90899d9ca8be@mail.gmail.com>
	<001901c6b33b$94c468a0$0201a8c0@XPpro>
Message-ID: <bf6cdbf10607291652v2fa0d471td035906a37af6481@mail.gmail.com>

>
> For a quick overview of Model/View (and sometimes Controller)
> take a look at the Apple web site. their default GUI design uses
> the paradigm and there is a good visual description  in the
> overview:
>
> http://developer.apple.com/documentation/Cocoa/Conceptual/ObjCTutorial/chapter02/chapter_2_section_3.html
>
>
> For a slightly different approach try:
>
> http://www.mimuw.edu.pl/~sl/teaching/00_01/Delfin_EC/Overviews/ModelViewPresenter.htm
>


Thanks a lot, Alan.
Your links and example (and a wonderful tutorial on Tkinter
http://doctormickey.com/python/pythontutorial_100.htm) really helped me!

This is the working version of my visualization:




# -*- coding: windows-1251 -*-

import random, time, Tkinter

class Agent:
    def __init__ (self, x=100, y=100):
        self.name = random.randint(0, 100000)
        self.x = x
        self.y = y

    def __repr__ (self):
        return str(self.name)

    def display(self, canvas, x, y):
        """Display an image of this Agent on the canvas."""
        canvas.coords(self.ID, x, y)

    def rand_vec(self):
        return random.randint(-5, 5), random.randint(-5, 5)


class Environment:
    def __init__ (self):
        self.alive_agents = []

    def step(self):
        for obj in self.alive_agents:
            old_x, old_y = obj.x, obj.y
            change_x, change_y = obj.rand_vec()
            obj.x, obj.y = old_x + change_x, old_y + change_y
#            print obj.name, '\t:\t ', old_x, old_y,' -> ', obj.x, obj.y

    def add_agent(self, agent):
#        print agent.name, ' was added to environment'
        self.alive_agents.append(agent)



class GraphEnvironment(Tkinter.Frame):
    def __init__ (self, root):

        self.root = root
        self.background = Tkinter.Canvas(self.root, width=200, height=200,
background="white")

        for agent in env.alive_agents:
            agent.ID=self.background.create_image (100, 100, anchor=
Tkinter.NW, image=picture)

        self.background.pack(fill=Tkinter.BOTH,expand=Tkinter.YES)

        self.root.after(100,self.NextDay)

    def NextDay(self):
        env.step()
        for agent in env.alive_agents:
            agent.display(self.background, agent.x, agent.y)
        self.root.after(200,self.NextDay)

print '\tBORN'
env = Environment()
for obj in range(100):
    child = Agent()
#    print child, ' was born'
    env.add_agent(child)

print '\tGRAPH LIFE'

root=Tkinter.Tk()
picture =Tkinter.PhotoImage(file="HolyGrail.gif")
GraphEnvironment(root)
root.mainloop()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060730/d7be83b5/attachment-0001.html 

From alan.gauld at freenet.co.uk  Sun Jul 30 09:55:35 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 30 Jul 2006 08:55:35 +0100
Subject: [Tutor] visualization
References: <bf6cdbf10607281616l28a3dd03p9c83e3f1e8bed2ea@mail.gmail.com><003f01c6b2e7$790ecb40$0201a8c0@XPpro><bf6cdbf10607290209o2a7e9f11sa87e90899d9ca8be@mail.gmail.com><001901c6b33b$94c468a0$0201a8c0@XPpro>
	<bf6cdbf10607291652v2fa0d471td035906a37af6481@mail.gmail.com>
Message-ID: <002201c6b3ad$8b500870$0201a8c0@XPpro>

Glad you got it working.
A couple of observations:

> This is the working version of my visualization:

> class Agent:
>    def __init__ (self, x=100, y=100):
>        self.name = random.randint(0, 100000)
>        self.x = x
>        self.y = y
>
>    def __repr__ (self):
>        return str(self.name)
>
>    def display(self, canvas, x, y):
>        """Display an image of this Agent on the canvas."""
>        canvas.coords(self.ID, x, y)

You don't need the x,y since its your own x,y, so you could just use:

canvas.coords(self.ID,self.x,self.y)

This is better OO practice that the Environment extracting
the x,y from the agent and passing them back as parameters.
Objects should "do it to themselves" to summarize a principle
known as the Law of Demeter...

>    def rand_vec(self):
>        return random.randint(-5, 5), random.randint(-5, 5)
>
>
> class Environment:
>    def __init__ (self):
>        self.alive_agents = []
>
>    def step(self):
>        for obj in self.alive_agents:
>            old_x, old_y = obj.x, obj.y
>            change_x, change_y = obj.rand_vec()
>            obj.x, obj.y = old_x + change_x, old_y + change_y
> #            print obj.name, '\t:\t ', old_x, old_y,' -> ', obj.x, 
> obj.y

Similarl;y you have the Environment changing the objects
coordinates, but really the coords belong to the object
therefore the object should change them itself.
After all there is nothing in the algorithm that relies on Environment
data - and even if there were the Environment should pass that to
obj as arguments...

Thus Environment should just call

obj.set_coords()

And the algorithm above moves into the Agent method set_coords()

The golden rule is that whichever object owns the data being changed
should be the one that does the changing. If you ever find yourself
accessing another objects data so as to change it then there is
something wrong with your design.

>    def add_agent(self, agent):
> #        print agent.name, ' was added to environment'
>        self.alive_agents.append(agent)
>
> class GraphEnvironment(Tkinter.Frame):
>    def __init__ (self, root):
>        self.root = root
>        self.background = Tkinter.Canvas(self.root, width=200, 
> height=200,
> background="white")
>
>        for agent in env.alive_agents:
>            agent.ID=self.background.create_image (100, 100, anchor=
> Tkinter.NW, image=picture)

And this is a good example of an exception to the rule.
Purists would argue that you should create an Agent.setID
method but it would only be a simple assignment so this is ok.
The assignment uses Environment data so I'd be happy to
leave as-is.

>        self.background.pack(fill=Tkinter.BOTH,expand=Tkinter.YES)
>        self.root.after(100,self.NextDay)
>
>    def NextDay(self):
>        env.step()
>        for agent in env.alive_agents:
>            agent.display(self.background, agent.x, agent.y)
>        self.root.after(200,self.NextDay)
>
> print '\tBORN'
> env = Environment()
> for obj in range(100):
>    child = Agent()
> #    print child, ' was born'
>    env.add_agent(child)

You could just:

      env.add_agent(Agent())

However these are minor points of OOP style.
I'm glad you got it working.

Alan G. 


From kyxaxa at gmail.com  Sun Jul 30 11:52:01 2006
From: kyxaxa at gmail.com (=?ISO-8859-5?B?wdXg0/bZ?=)
Date: Sun, 30 Jul 2006 12:52:01 +0300
Subject: [Tutor] visualization
In-Reply-To: <002201c6b3ad$8b500870$0201a8c0@XPpro>
References: <bf6cdbf10607281616l28a3dd03p9c83e3f1e8bed2ea@mail.gmail.com>
	<003f01c6b2e7$790ecb40$0201a8c0@XPpro>
	<bf6cdbf10607290209o2a7e9f11sa87e90899d9ca8be@mail.gmail.com>
	<001901c6b33b$94c468a0$0201a8c0@XPpro>
	<bf6cdbf10607291652v2fa0d471td035906a37af6481@mail.gmail.com>
	<002201c6b3ad$8b500870$0201a8c0@XPpro>
Message-ID: <bf6cdbf10607300252w7e29cbcew60812a94f31e61fe@mail.gmail.com>

Thanks for your remarks, Alan.
And " Law of Demeter" was something new and useful for me.
This is corrected code (I hope I've understand all your remarks right):



# -*- coding: windows-1251 -*-

import random, time, Tkinter

class Agent:
    def __init__ (self, x=100, y=100):
        self.name = random.randint(0, 100000)
        self.x = x
        self.y = y

    def __repr__ (self):
        return str(self.name)

    def step (self):
        old_x, old_y = self.x, self.y
        change_x, change_y = self.rand_vec()
        self.x, self.y = old_x + change_x, old_y + change_y

    def rand_vec(self):
        return random.randint(-5, 5), random.randint(-5, 5)

    def display(self, canvas):
        canvas.coords(self.ID, self.x, self.y)


class Environment:
    def __init__ (self):
        self.alive_agents = []

    def step(self):
        for obj in self.alive_agents:
            obj.step()

    def add_agent(self, agent):
#        print agent.name, ' was added to environment'
        self.alive_agents.append(agent)

    def show_env (self, canvas):
        for agent in env.alive_agents:
            agent.display(canvas)


class GraphEnvironment(Tkinter.Frame):

    def __init__ (self, root):

        self.root = root
        self.background = Tkinter.Canvas(self.root, width=200, height=200,
background="white")

        for agent in env.alive_agents:
            agent.ID=self.background.create_image(100, 100, anchor=
Tkinter.NW, image=picture)

        self.background.pack(fill=Tkinter.BOTH,expand=Tkinter.YES)

        self.root.after(100,self.NextDay)

    def NextDay(self):
        env.step()
        env.show_env(self.background)
        self.root.after(50,self.NextDay)



print '\tBORN'

env = Environment()
for obj in range(100):
    child = Agent()
#    print child, ' was born'
    env.add_agent(child)

print '\tGRAPH LIFE'

root=Tkinter.Tk()
picture =Tkinter.PhotoImage(file="HolyGrail.gif")
GraphEnvironment(root)
root.mainloop()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060730/dac8e3b3/attachment.html 

From arcege at gmail.com  Sun Jul 30 11:58:40 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Sun, 30 Jul 2006 05:58:40 -0400
Subject: [Tutor] problem with rejected mail smtplib
In-Reply-To: <384c93600607291544v5cc0bf47ve2672605f3804b6a@mail.gmail.com>
References: <384c93600607291544v5cc0bf47ve2672605f3804b6a@mail.gmail.com>
Message-ID: <7e5ba9220607300258l3fe0e36fpa40d991c969ca026@mail.gmail.com>

On 7/29/06, shawn bright <nephish at gmail.com> wrote:
>
> Hello there,
> i have a customer list, each with a number of email address that we send
> notifications to via text message.
> the problem is, there are a number of providers ( just two ) that reject
> our messages.
> the script goes a little something like this :
>
> Address = 'going at somewhere.net'
> From = 'me at myhost.net'
> message = 'From: me at myhost.net\r\nTo: %s\r\nSubject: %s\r\n\r\n%s' %
> (Address,'alert',message)
> server.sendmail(From, Address, message)
>
> most of the time it goes thru ok. but only some providers have a problem.
> However, those same providers get messages if i send them thru Evolution.
>
> any ideas of what to check out?
>

The second argument to SMTP.sendmail is supposed to be a sequence.  You are
sending a sequence (a string), so you do not get a complaint, but it is not
the sequence you want.  Try this:

server.sendmail(From, [Address], message)

  -Arcege

-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060730/ef7e65d6/attachment.htm 

From kent37 at tds.net  Sun Jul 30 13:43:02 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 30 Jul 2006 07:43:02 -0400
Subject: [Tutor] problem with rejected mail smtplib
In-Reply-To: <7e5ba9220607300258l3fe0e36fpa40d991c969ca026@mail.gmail.com>
References: <384c93600607291544v5cc0bf47ve2672605f3804b6a@mail.gmail.com>
	<7e5ba9220607300258l3fe0e36fpa40d991c969ca026@mail.gmail.com>
Message-ID: <44CC9B46.5000003@tds.net>

Michael P. Reilly wrote:
> The second argument to SMTP.sendmail is supposed to be a sequence.  
> You are sending a sequence (a string), so you do not get a complaint, 
> but it is not the sequence you want.  Try this:
>
> server.sendmail(From, [Address], message)
Actually server.sendmail allows a string to represent a single address. 
This was undocumented until recently but it does work.

Kent


From kent37 at tds.net  Sun Jul 30 13:43:41 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 30 Jul 2006 07:43:41 -0400
Subject: [Tutor] problem with rejected mail smtplib
In-Reply-To: <384c93600607291544v5cc0bf47ve2672605f3804b6a@mail.gmail.com>
References: <384c93600607291544v5cc0bf47ve2672605f3804b6a@mail.gmail.com>
Message-ID: <44CC9B6D.4080102@tds.net>

shawn bright wrote:
> Hello there,
> i have a customer list, each with a number of email address that we 
> send notifications to via text message.
> the problem is, there are a number of providers ( just two ) that 
> reject our messages.
What error do you get with the rejection?

Kent
> the script goes a little something like this :
>
> Address = 'going at somewhere.net <mailto:going at somewhere.net>'
> From = 'me at myhost.net <mailto:me at myhost.net>'
> message = 'From: me at myhost.net\r\nTo: %s\r\nSubject: %s\r\n\r\n%s' % 
> (Address,'alert',message)
> server.sendmail(From, Address, message)
>
> most of the time it goes thru ok. but only some providers have a 
> problem. However, those same providers get messages if i send them 
> thru Evolution.
>
> any ideas of what to check out?
>
> thanks
> -sk
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From lunixinclar at orange.fr  Sun Jul 30 15:16:31 2006
From: lunixinclar at orange.fr (Rob Sinclar)
Date: Sun, 30 Jul 2006 15:16:31 +0200
Subject: [Tutor] problem with rejected mail smtplib
In-Reply-To: <44CC9B6D.4080102@tds.net>
References: <384c93600607291544v5cc0bf47ve2672605f3804b6a@mail.gmail.com>
	<44CC9B6D.4080102@tds.net>
Message-ID: <200607301516.31906.lunixinclar@orange.fr>

> Hello there,
> i have a customer list, each with a number of email address that we
> send notifications to via text message.
> the problem is, there are a number of providers ( just two ) that
> reject our messages.
>
> What error do you get with the rejection?
>
>
> the script goes a little something like this :
>
> Address = 'going at somewhere.net <mailto:going at somewhere.net>'
> From = 'me at myhost.net <mailto:me at myhost.net>'
> message = 'From: me at myhost.net\r\nTo: %s\r\nSubject: %s\r\n\r\n%s' %
> (Address,'alert',message)
> server.sendmail(From, Address, message)
>
> most of the time it goes thru ok. but only some providers have a
> problem. However, those same providers get messages if i send them
> thru Evolution.
>
> any ideas of what to check out?

I'd look at sendmail() exceptions, described in the smtplib docs.

try:
  m.sendmail(...)
except SMTPRecipientsRefused:
    print "All recipients were refused...."
except SMTPHeloError:
    print "The server didn't reply properly to the ...."
except SMTPSenderRefused:
    print "The server didn't accept the..."
except SMTPDataError:
   print "The server replied with an ..."

From nephish at gmail.com  Sun Jul 30 15:18:12 2006
From: nephish at gmail.com (shawn bright)
Date: Sun, 30 Jul 2006 08:18:12 -0500
Subject: [Tutor] problem with rejected mail smtplib
In-Reply-To: <7e5ba9220607300258l3fe0e36fpa40d991c969ca026@mail.gmail.com>
References: <384c93600607291544v5cc0bf47ve2672605f3804b6a@mail.gmail.com>
	<7e5ba9220607300258l3fe0e36fpa40d991c969ca026@mail.gmail.com>
Message-ID: <384c93600607300618v180f40e6pc9c9cb861266f520@mail.gmail.com>

Oh, right... sorry... i didn't know i could do it like that. I was looping
thru them
for address in addresses:
    server.sendmail(from,address,message)

i did not mention that in the OP.

-shawn


On 7/30/06, Michael P. Reilly <arcege at gmail.com> wrote:
>
> On 7/29/06, shawn bright <nephish at gmail.com> wrote:
> >
> > Hello there,
> > i have a customer list, each with a number of email address that we send
> > notifications to via text message.
> > the problem is, there are a number of providers ( just two ) that reject
> > our messages.
> > the script goes a little something like this :
> >
> > Address = 'going at somewhere.net'
> > From = ' me at myhost.net'
> > message = 'From: me at myhost.net\r\nTo: %s\r\nSubject: %s\r\n\r\n%s' %
> > (Address,'alert',message)
> > server.sendmail(From, Address, message)
> >
> > most of the time it goes thru ok. but only some providers have a
> > problem. However, those same providers get messages if i send them thru
> > Evolution.
> >
> > any ideas of what to check out?
> >
>
> The second argument to SMTP.sendmail is supposed to be a sequence.  You
> are sending a sequence (a string), so you do not get a complaint, but it is
> not the sequence you want.  Try this:
>
>
> server.sendmail(From, [Address], message)
>
>   -Arcege
>
> --
> There's so many different worlds,
> So many different suns.
> And we have just one world,
> But we live in different ones.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060730/dd58cee6/attachment.html 

From accelerateddevelopment at gmail.com  Mon Jul 31 12:32:57 2006
From: accelerateddevelopment at gmail.com (Sebastian Smith)
Date: Mon, 31 Jul 2006 18:32:57 +0800
Subject: [Tutor] The Self
Message-ID: <f3406aa50607310332k10fe28belc4562ab147ee60ff@mail.gmail.com>

I am new to Python, real new. I am loving the language and learning
fast but I have hit a wall with the 'self'. I have Googled and
searched and read a few definitions but it still doesn't make sense to
me.

I would love to hear some of your 'layman's definitions' on the self.

Thank you all,

Ben.

From rabidpoobear at gmail.com  Mon Jul 31 14:54:55 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 31 Jul 2006 07:54:55 -0500
Subject: [Tutor] The Self
In-Reply-To: <f3406aa50607310332k10fe28belc4562ab147ee60ff@mail.gmail.com>
References: <f3406aa50607310332k10fe28belc4562ab147ee60ff@mail.gmail.com>
Message-ID: <44CDFD9F.1010402@gmail.com>

Sebastian Smith wrote:
> I am new to Python, real new. I am loving the language and learning
> fast but I have hit a wall with the 'self'. I have Googled and
> searched and read a few definitions but it still doesn't make sense to
> me.
>
> I would love to hear some of your 'layman's definitions' on the self.
>
> Thank you all,
>
> Ben.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   
Consider this:
#--start code
def f():
    print 'hello'
 >>> a = f
 >>> a
<function f at 0x00AE67F0>
 >>> a()
hello
 >>> f
<function f at 0x00AE67F0>
 >>> f()
hello
#-- end code

See how whenever you define a function, it creates a 'function' object? 
This means you can do anything with the function, assign a variable to it,
put it in a list or a dictionary, etc.
we assigned the variable 'a' to the function 'f', so we could call
function 'f' using either 'a()' or 'f()'.
The reason we're allowed to have as many variables pointing to the same
function as we want is because the function always does the same thing
when passed the same parameters (more or less.)
However, when you have a 'Class' object, it has its own collection
of variables that it can modify, and its own set of functions that work
on its variables.  Because of this, you might want one class to do
a certain thing and another class to do something else.
Consider the following class:
#-- start code
Class Address(object):
    def __init__(street,city,zip):
       print "Street: %s, City: %s, Zip: %s" % (street,city,zip)
#-- end code
We can do whatever we want with these variables inside of our __init__ 
function.
If we call the function, using Address.__init__('1232 west highway 
boulevard','indianapolis','10000')
it will print the string 'Street: 1232 west highway boulevard, City: 
indianapolis, Zip: 10000'
That's cool, but what if we want to store the values of these attributes?
Well, if we're going to store the values, we'll want to make a separate 
copy of the class
that we can modify, so that we don't have to change the original.
This is where self comes in.
#-- start code
Class Address(object):
    def __init__(self,street,city,zip):
       self.street = street
       self.city = city
       self.zip = zip
    def output(self):
       print "Street: %s, City: %s, Zip: %s" % 
(self.street,self.city,self.zip)
#-- end code
Now we can make a separate copy of the Address class, called
an 'instance' of the class, like this:
 >>> address1 = Address('1232 lexington drive','Annapolis','32423')
when we call the output method of address1 we see:
 >>> address1.output()
Street: 1232 lexington drive, City: Annapolis, Zip: 32423
Now say we want to change the city name, cause we meant to put
'Indianapolis.'  All we have to do is this:
address1.city = 'Indianapolis'
Basically, when you call any function inside of a class, using a class 
instance,
(calling address1.anything is calling a function in an instance of a class,
calling Address.anything is calling the function from the original copy 
of the class.)
the first argument passed will be 'self', which is just the entire 
contents of the class.
Hope that helps, I'd go more in-depth but I gotta run.
Luke

From nephish at gmail.com  Mon Jul 31 15:39:41 2006
From: nephish at gmail.com (shawn bright)
Date: Mon, 31 Jul 2006 09:39:41 -0400
Subject: [Tutor] The Self
In-Reply-To: <44CDFD9F.1010402@gmail.com>
References: <f3406aa50607310332k10fe28belc4562ab147ee60ff@mail.gmail.com>
	<44CDFD9F.1010402@gmail.com>
Message-ID: <384c93600607310639w4db3d61aud8d32aa9f4a3a7d3@mail.gmail.com>

Im not the OP, but this clears up some stuff for ma about "self".
I thank you for your time to post this.
-shawn

On 7/31/06, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
> Sebastian Smith wrote:
> > I am new to Python, real new. I am loving the language and learning
> > fast but I have hit a wall with the 'self'. I have Googled and
> > searched and read a few definitions but it still doesn't make sense to
> > me.
> >
> > I would love to hear some of your 'layman's definitions' on the self.
> >
> > Thank you all,
> >
> > Ben.
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> Consider this:
> #--start code
> def f():
>     print 'hello'
> >>> a = f
> >>> a
> <function f at 0x00AE67F0>
> >>> a()
> hello
> >>> f
> <function f at 0x00AE67F0>
> >>> f()
> hello
> #-- end code
>
> See how whenever you define a function, it creates a 'function' object?
> This means you can do anything with the function, assign a variable to it,
> put it in a list or a dictionary, etc.
> we assigned the variable 'a' to the function 'f', so we could call
> function 'f' using either 'a()' or 'f()'.
> The reason we're allowed to have as many variables pointing to the same
> function as we want is because the function always does the same thing
> when passed the same parameters (more or less.)
> However, when you have a 'Class' object, it has its own collection
> of variables that it can modify, and its own set of functions that work
> on its variables.  Because of this, you might want one class to do
> a certain thing and another class to do something else.
> Consider the following class:
> #-- start code
> Class Address(object):
>     def __init__(street,city,zip):
>        print "Street: %s, City: %s, Zip: %s" % (street,city,zip)
> #-- end code
> We can do whatever we want with these variables inside of our __init__
> function.
> If we call the function, using Address.__init__('1232 west highway
> boulevard','indianapolis','10000')
> it will print the string 'Street: 1232 west highway boulevard, City:
> indianapolis, Zip: 10000'
> That's cool, but what if we want to store the values of these attributes?
> Well, if we're going to store the values, we'll want to make a separate
> copy of the class
> that we can modify, so that we don't have to change the original.
> This is where self comes in.
> #-- start code
> Class Address(object):
>     def __init__(self,street,city,zip):
>        self.street = street
>        self.city = city
>        self.zip = zip
>     def output(self):
>        print "Street: %s, City: %s, Zip: %s" %
> (self.street,self.city,self.zip)
> #-- end code
> Now we can make a separate copy of the Address class, called
> an 'instance' of the class, like this:
> >>> address1 = Address('1232 lexington drive','Annapolis','32423')
> when we call the output method of address1 we see:
> >>> address1.output()
> Street: 1232 lexington drive, City: Annapolis, Zip: 32423
> Now say we want to change the city name, cause we meant to put
> 'Indianapolis.'  All we have to do is this:
> address1.city = 'Indianapolis'
> Basically, when you call any function inside of a class, using a class
> instance,
> (calling address1.anything is calling a function in an instance of a
> class,
> calling Address.anything is calling the function from the original copy
> of the class.)
> the first argument passed will be 'self', which is just the entire
> contents of the class.
> Hope that helps, I'd go more in-depth but I gotta run.
> Luke
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060731/6f2153b0/attachment.htm 

From nephish at gmail.com  Mon Jul 31 19:49:34 2006
From: nephish at gmail.com (shawn bright)
Date: Mon, 31 Jul 2006 13:49:34 -0400
Subject: [Tutor] question about headers and smtplib
Message-ID: <384c93600607311049g62919e0bj9f6539329263167@mail.gmail.com>

Hey there,
me again with another question about headers..

if i use my python script to send an email, it gets rejected by some
providers.
but another app that i use can send the same email and it gets thru.
i have sent myself test messages from both apps and looked at the headers.

the only difference in one from the other is that in the headers of the
other app (not my python script)
there exist the following lines:

MIME-Version: 1.0
X-Mailer: OstroSoft SMTP Control (4.0.20)
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7-bit

i do not understand how to make mine work and include (or configure to) the
above example.

anyone point me in a right direction ?

thanks,
shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060731/7ca91a0c/attachment.htm 

From python-tutor at v.igoro.us  Mon Jul 31 20:07:18 2006
From: python-tutor at v.igoro.us (Dustin J. Mitchell)
Date: Mon, 31 Jul 2006 13:07:18 -0500
Subject: [Tutor] question about headers and smtplib
In-Reply-To: <384c93600607311049g62919e0bj9f6539329263167@mail.gmail.com>
References: <384c93600607311049g62919e0bj9f6539329263167@mail.gmail.com>
Message-ID: <44CE46D6.7000204@v.igoro.us>

shawn bright wrote:
> the only difference in one from the other is that in the headers of the
> other app (not my python script)
> there exist the following lines:
> 
> MIME-Version: 1.0
> X-Mailer: OstroSoft SMTP Control (4.0.20)
> Content-Type: text/plain; charset="us-ascii"
> Content-Transfer-Encoding: 7-bit
> 
> i do not understand how to make mine work and include (or configure to)
> the above example.
> 
> anyone point me in a right direction ?


It's hard to tell what the problem is without seeing the error messages
-- do you get a "bounce"?  Is there anything in your logfile?  Have you
tried set_debuglevel and looking at the output?  If you have information
there, but don't know how to interpret it, post it here and we'll take a
look.

You could try adding the Content-Type header to your own messages.
People configure mailservers in a lot of weird ways, and it's possible
that some mailservers reject emails without a Content-Type header..

Dustin

From alan.gauld at btinternet.com  Mon Jul 31 23:35:11 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 31 Jul 2006 22:35:11 +0100
Subject: [Tutor] The Self
References: <f3406aa50607310332k10fe28belc4562ab147ee60ff@mail.gmail.com>
	<44CDFD9F.1010402@gmail.com>
Message-ID: <ealt2g$nj$1@sea.gmane.org>


"Luke Paireepinart" <rabidpoobear at gmail.com> wrote
>> I would love to hear some of your 'layman's definitions' on the 
>> self.

> However, when you have a 'Class' object, it has its own collection
> of variables that it can modify, and its own set of functions that 
> work
> on its variables.  Because of this, you might want one class to do
> a certain thing and another class to do something else.

Thus is all true and good.

> Class Address(object):
>    def __init__(street,city,zip):
>       print "Street: %s, City: %s, Zip: %s" % (street,city,zip)

> That's cool, but what if we want to store the values of these 
> attributes?
> Well, if we're going to store the values, we'll want to make a 
> separate
> copy of the class  that we can modify,

But this isn't.
Its very wrong to think of creating instamnces as being copies of the 
class.
classes are objects in the python sense in their own right and its 
possible
to instantiate them and also possible to copy them, and the two are
different!

One way to copy a class is to create a blank class that inherits from
the one we want to copy:

>>> class Thing:
...  def __init__(self,a=42):
...   self.a = a
...  def speak(self):
...   print "I am a thing with value", self.a
...
>>> class Different(Thing): pass
...
>>> t = Thing()
>>> t2 = Thing(27)
>>> d = Different(666)
>>> for it in [t,t2,d]: it.speak()
...
I am a thing with value 42
I am a thing with value 27
I am a thing with value 666
>>>

Notice that d thinks it is a Thing too...

But we have two instances ofThing and one instance of Different.
Which brings us back to the OPs point about the use of self.
Now if we read Luke's response but use instance instead of
copy then the reply is correct. :-)


> This is where self comes in.
> #-- start code
> Class Address(object):
>    def __init__(self,street,city,zip):
>       self.street = street
>       self.city = city
>       self.zip = zip
>    def output(self):
>       print "Street: %s, City: %s, Zip: %s" %
> (self.street,self.city,self.zip)
> #-- end code
> Now we can make a separate copy of the Address class, called
> an 'instance' of the class, like this:

As Luke says we create instances, but instances are not copies.
I am of class Man, but I am jot a copy of a man I am an instance,
just as my father is and many others. Classes are common nouns
instances are proper nouns in grammatical terms.

> >>> address1 = Address('1232 lexington drive','Annapolis','32423')
> when we call the output method of address1 we see:
> >>> address1.output()
> Street: 1232 lexington drive, City: Annapolis, Zip: 32423
> Now say we want to change the city name, cause we meant to put
> 'Indianapolis.'  All we have to do is this:
> address1.city = 'Indianapolis'
> Basically, when you call any function inside of a class, using a 
> class
> instance,
> (calling address1.anything is calling a function in an instance of a 
> class,
> calling Address.anything is calling the function from the original 
> copy
> of the class.)
> the first argument passed will be 'self', which is just the entire
> contents of the class.
> Hope that helps, I'd go more in-depth but I gotta run.

Likewise :-)
But you can read more on my web site OOP topic under the
heading "What is self".

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld